Skip to content
safran

Type to search. Enter opens the first result.

    Writing plugins

    Every system Safran talks to is a plugin, including the built-in ones. A plugin is a plain object: a kind, the type string that selects it in a profile, a schema for its profile entry, and a create function that returns a connector. This page builds a complete custom tracker, then a code host, an embedder and a doc source, shows the two ways of loading them, and states the rules a plugin must follow.

    The four kinds, with the helper that defines each and the contract its connector implements:

    KindHelperContractProfile section
    TrackerdefineTrackerTrackertrackers[]
    Code hostdefineCodeHostCodeHostcode.hosts[]
    Doc sourcedefineDocSourceDocSourcedocs[]
    EmbedderdefineEmbedderEmbedderembeddings

    The helpers only add the kind and give you type inference: inside create, config has the output type of your schema. The examples import from @safran/kit, the package made for plugin authors; @safran/core re-exports the define* helpers, createHttpClient, envVarName, httpUrl and the error helpers, so a small plugin can also be written against @safran/core alone.

    A complete tracker

    Acme runs an in-house issue tracker, Acme Desk, at https://desk.acme.test. Its keys look like DESK-412 and it has a small JSON API. This plugin makes it a Safran tracker with comments and search:

    plugins/acme-desk.ts
    import {
      asArray,
      asRecord,
      asString,
      createHttpClient,
      decodeCursor,
      defineTracker,
      encodeCursor,
      envVarName,
      httpUrl,
      isoDate,
      resolveLimit,
      SafranError,
      type Comment,
      type HttpClient,
      type StatusCategory,
      type Ticket,
      type TicketSummary,
      type TrackerCapability,
    } from "@safran/kit";
    import { z } from "zod";
    
    const DEFAULT_PAGE_SIZE = 50;
    const MAX_PAGE_SIZE = 200;
    
    /** The whole profile entry, `id` and `type` included. Strict: a misspelled key is an error, not ignored. */
    const configSchema = z.strictObject({
      id: z.string().min(1),
      type: z.literal("acme-desk"),
      /** Site root, e.g. https://desk.acme.test */
      url: httpUrl,
      /** NAME of the variable that holds the API token. */
      token_env: envVarName,
      /** Project keys this tracker owns. The profile gives every tracker entry this field. */
      projects: z.array(z.string().min(1)).default([]),
    });
    
    const CATEGORY: Record<string, StatusCategory> = { open: "todo", triaged: "todo", working: "in_progress", review: "in_progress", closed: "done" };
    
    function summary(raw: unknown, siteUrl: string): TicketSummary | undefined {
      const issue = asRecord(raw);
      const key = asString(issue?.key);
      if (!issue || !key) return undefined;
      const status = asString(issue.status);
      const category = status === undefined ? undefined : CATEGORY[status.toLowerCase()];
      const type = asString(issue.type);
      return {
        key,
        title: asString(issue.title) ?? "",
        url: `${siteUrl}/issues/${key}`,
        ...(type === undefined ? {} : { type }),
        ...(status === undefined ? {} : { status }),
        ...(category === undefined ? {} : { statusCategory: category }),
      };
    }
    
    export const acmeDesk = defineTracker({
      type: "acme-desk",
      description: "Acme Desk, the in-house issue tracker",
      configSchema,
    
      // No network and no secret here: `create` runs when the instance is built, possibly offline.
      create(config, ctx) {
        const siteUrl = config.url.replace(/\/+$/, "");
        const projects = config.projects.map((project) => project.toUpperCase());
    
        // Built on first use, so a missing token fails the call that needs it (AUTH_MISSING), not creation.
        let client: HttpClient | undefined;
        const http = (): HttpClient =>
          (client ??= createHttpClient({
            service: "Acme Desk",
            baseUrl: `${siteUrl}/api/v1`,
            headers: { authorization: `Bearer ${ctx.secret(config.token_env)}` },
            fetch: ctx.fetch,
            logger: ctx.logger,
            notFoundHint: "Check the ticket key, and that the token may read its project.",
          }));
    
        const capabilities = new Set<TrackerCapability>(["comments", "search"]);
    
        return {
          id: config.id,
          type: "acme-desk",
          capabilities,
    
          // Cheap and offline: a string test, never a lookup. Claims only what is clearly ours.
          matchTicketRef(input) {
            const text = input.trim();
            const fromUrl = text.startsWith(`${siteUrl}/issues/`) ? text.slice(`${siteUrl}/issues/`.length) : text;
            const match = /^([A-Za-z][A-Za-z0-9]*)-(\d+)$/.exec(fromUrl);
            if (!match) return undefined;
            const project = (match[1] ?? "").toUpperCase();
            // A key of a project this entry does not declare belongs to another tracker.
            if (projects.length > 0 && !projects.includes(project)) return undefined;
            return `${project}-${Number(match[2])}`;
          },
    
          async listProjects(options) {
            const body = await http().json({ path: "projects", ...(options?.signal ? { signal: options.signal } : {}) });
            return asArray(asRecord(body)?.projects).flatMap((raw) => {
              const key = asString(asRecord(raw)?.key);
              return key ? [{ key, name: asString(asRecord(raw)?.name) ?? key }] : [];
            });
          },
    
          async getTicket(key, options): Promise<Ticket> {
            const body = await http().json({ path: `issues/${encodeURIComponent(key)}`, ...(options?.signal ? { signal: options.signal } : {}) });
            const issue = asRecord(body);
            const base = summary(issue, siteUrl);
            if (!issue || !base) {
              throw new SafranError("UPSTREAM", "Acme Desk returned an issue in an unexpected shape", { hint: "Check that the URL in the profile points at Acme Desk." });
            }
            const assignee = asString(asRecord(issue.assignee)?.name);
            const updatedAt = isoDate(issue.updated_at);
            return {
              ...base,
              url: `${siteUrl}/issues/${base.key}`,
              tracker: config.id,
              project: base.key.slice(0, base.key.lastIndexOf("-")),
              description: asString(issue.body) ?? "",
              labels: asArray(issue.labels).flatMap((label) => asString(label) ?? []),
              ...(assignee === undefined ? {} : { assignee: { name: assignee } }),
              ...(updatedAt === undefined ? {} : { updatedAt }),
              fields: {},
            };
          },
    
          // Listed in `capabilities` above, so it must exist: a capability without its method is refused at creation.
          async getComments(key, options) {
            const limit = resolveLimit(options?.limit, { default: DEFAULT_PAGE_SIZE, max: MAX_PAGE_SIZE });
            const offset = options?.cursor ? decodeCursor(options.cursor, (value): value is number => Number.isInteger(value) && Number(value) >= 0) : 0;
            const body = await http().json({ path: `issues/${encodeURIComponent(key)}/comments`, query: { offset, limit }, ...(options?.signal ? { signal: options.signal } : {}) });
            const record = asRecord(body);
            const items: Comment[] = asArray(record?.comments).flatMap((raw) => {
              const comment = asRecord(raw);
              const id = asString(comment?.id);
              if (!comment || !id) return [];
              const author = asString(comment.author);
              const createdAt = isoDate(comment.created_at);
              return [{ id, body: asString(comment.text) ?? "", ...(author === undefined ? {} : { author: { name: author } }), ...(createdAt === undefined ? {} : { createdAt }) }];
            });
            return record?.has_more === true ? { items, nextCursor: encodeCursor(offset + limit) } : { items };
          },
    
          async searchTickets(query, options) {
            const limit = resolveLimit(options?.limit, { default: DEFAULT_PAGE_SIZE, max: MAX_PAGE_SIZE });
            const offset = options?.cursor ? decodeCursor(options.cursor, (value): value is number => Number.isInteger(value) && Number(value) >= 0) : 0;
            const body = await http().json({
              path: "issues",
              query: {
                q: query.text,
                project: query.projects && query.projects.length > 0 ? query.projects : projects,
                updated_since: query.updatedSince,
                offset,
                limit,
              },
              ...(options?.signal ? { signal: options.signal } : {}),
            });
            const record = asRecord(body);
            const wanted = query.statusCategories;
            const items = asArray(record?.issues)
              .flatMap((raw) => summary(raw, siteUrl) ?? [])
              .filter((item) => !wanted || wanted.length === 0 || (item.statusCategory !== undefined && wanted.includes(item.statusCategory)));
            return record?.has_more === true ? { items, nextCursor: encodeCursor(offset + limit) } : { items };
          },
        };
      },
    });

    Try it without the real service. mockFetch answers from a route table, and the connector runs exactly the code it runs in production:

    try-desk.ts
    import { createSafran, defineProfile } from "@safran/core";
    import { mockFetch } from "@safran/kit/testing";
    import { acmeDesk } from "./plugins/acme-desk";
    
    // Canned answers instead of the real service: the connector runs its real code path.
    const desk = mockFetch([
      {
        url: "https://desk.acme.test/api/v1/issues/DESK-412",
        reply: { json: { key: "DESK-412", title: "Refund e-mail is sent twice", type: "Incident", status: "Working", body: "Customers receive two refund e-mails.", labels: ["refund"], assignee: { name: "Deniz Kaya" }, updated_at: "2026-11-02T08:30:00+0300" } },
      },
      {
        url: "https://desk.acme.test/api/v1/issues/DESK-412/comments",
        reply: (request) =>
          request.url.searchParams.get("offset") === "0"
            ? { json: { comments: [{ id: "1", author: "Deniz Kaya", text: "Reproduced on staging." }], has_more: true } }
            : { json: { comments: [{ id: "2", author: "Ece Arslan", text: "Duplicate webhook delivery, see PAY-1500." }], has_more: false } },
      },
    ]);
    
    await using safran = await createSafran({
      profile: defineProfile({
        version: 1,
        company: "acme",
        trackers: [{ id: "desk", type: "acme-desk", url: "https://desk.acme.test", token_env: "DESK_TOKEN", projects: ["DESK"] }],
      }),
      plugins: [acmeDesk],
      index: false,
      fetch: desk.fetch,
      env: { DESK_TOKEN: "test-token" },
    });
    
    const ticket = await safran.tickets.get("desk-412");
    console.log(ticket.key, ticket.status, ticket.statusCategory, ticket.assignee?.name, ticket.updatedAt);
    
    const first = await safran.tickets.comments("DESK-412", { limit: 1 });
    const second = await safran.tickets.comments("DESK-412", { limit: 1, ...(first.nextCursor === undefined ? {} : { cursor: first.nextCursor }) });
    console.log([...first.items, ...second.items].map((comment) => `${comment.author?.name}: ${comment.body}`));
    
    console.log(desk.requests.map((request) => `${request.method} ${request.url.pathname}${request.url.search}`));
    $ bun try-desk.ts
    DESK-412 Working in_progress Deniz Kaya 2026-11-02T05:30:00.000Z
    [ "Deniz Kaya: Reproduced on staging.", "Ece Arslan: Duplicate webhook delivery, see PAY-1500." ]
    [ "GET /api/v1/issues/DESK-412", "GET /api/v1/issues/DESK-412/comments?offset=0&limit=1",
      "GET /api/v1/issues/DESK-412/comments?offset=1&limit=1"
    ]

    The sections below explain each part of the plugin.

    The config schema

    configSchema validates the whole profile entry, id and type included. The profile validates the fields every entry of a kind shares first, then hands the entry to your schema:

    KindFields the profile adds to every entry
    Trackerid, type, projects (defaults to an empty list)
    Code hostid, type, include, exclude (both default to empty lists)
    Doc sourceid, type
    Embeddertype (no id: a profile has one embeddings entry)

    Your schema must accept those fields, or a profile that sets them is rejected. Beyond that:

    • Use z.strictObject. A misspelled key (tokne_env) is then an error with its path, instead of a setting that is silently ignored.
    • Use envVarName for secrets. It accepts only the name of an environment variable (DESK_TOKEN). A token pasted into the profile fails validation with a message that says why, which is the point: secrets do not belong in a profile.
    • Use httpUrl for base URLs. It accepts a plain http(s) URL and refuses one that carries credentials, a query string or a fragment.
    • Give defaults in the schema (.default(...)), so create receives a complete config.

    Schema problems are reported with the entry's position, trackers.1.url: …, as PLUGIN_CONFIG_INVALID, together with every other problem of the profile.

    The context

    create(config, ctx) receives a PluginContext:

    MemberUse it for
    companyThe company slug from the profile.
    loggerDiagnostics. Pass it to createHttpClient. Never log a token.
    fetchEvery HTTP request. It is the instance's fetch option, so tests and proxies can intercept.
    dataDirA directory of your own for caches: <dataDir>/cache/<entryId>. Create it when you first write to it.
    profileDirAbsolute directory of the profile file, for resolving relative paths written in the entry. Absent for an inline profile.
    secret(envName)The value of a required secret. Throws AUTH_MISSING with a hint when the variable is unset or empty.
    optionalSecret(envName)The same for an optional token: undefined when unset.
    /** What Safran hands a plugin when it builds a connector. */
    export interface PluginContext {
      /** Company slug from the profile. */
      readonly company: string;
      readonly logger: Logger;
      /** Use this instead of the global so tests and proxies can intercept. */
      readonly fetch: typeof fetch;
      /** Directory the plugin may use for caches. Created on demand by the plugin. */
      readonly dataDir: string;
      /**
       * Absolute directory of the profile file, for resolving relative paths written in the profile.
       * Absent when the profile was passed inline instead of loaded from disk.
       */
      readonly profileDir?: string;
      /**
       * Reads a secret from the environment variable named in the profile.
       * Throws AUTH_MISSING with a hint when it is unset or empty.
       */
      secret(envName: string): string;
      /** Same as `secret`, but returns undefined when unset. For optional tokens. */
      optionalSecret(envName: string | undefined): string | undefined;
    }

    defined in packages/kit/src/plugin.ts

    The HTTP client

    createHttpClient is the fetch wrapper every built-in connector uses. It gives a plugin the behaviour callers expect without writing it again:

    • A per-attempt timeout (30 seconds by default) and up to three retries for 429, 5xx and network failures, with backoff that honours Retry-After.
    • Vendor statuses mapped to Safran's codes: 401 and 403 to AUTH_FAILED, 404 to NOT_FOUND, 429 to RATE_LIMITED, the rest to UPSTREAM. See errors.
    • Cancellation: pass the call's signal on every request.
    • Origin pinning. A request path that names another origin is refused, and redirects are only followed inside the origin that was asked, so the token in headers cannot be sent to another host by a server-supplied "next page" link.
    • Errors and log lines that never contain header values or query strings.

    Three methods cover most APIs: json() for a parsed body, bytes() for downloads, raw() when you need response headers.

    OptionMeaning
    serviceName used in error messages, such as "Acme Desk".
    baseUrlPaths are joined to it.
    headersSent with every request on the base URL's origin. This is where the credential goes.
    fetchPass ctx.fetch.
    loggerPass ctx.logger.
    timeoutMsPer-attempt timeout.
    maxRetriesRetries after the first attempt.
    mapErrorClassify a failed response yourself before the default mapping, for services that report errors in their own way.
    notFoundHintHint put on 404 errors, such as which profile field names the missing thing.
    export interface HttpClientConfig {
      /** Name used in error messages, e.g. "Jira". */
      service: string;
      baseUrl: string;
      /** Sent with every request. Values are never logged or put into errors. */
      headers?: Record<string, string>;
      fetch?: typeof fetch;
      logger?: Logger;
      /** Per-attempt timeout. */
      timeoutMs?: number;
      /** Retries after the first attempt, for 429 / 5xx / network failures. */
      maxRetries?: number;
      /** Upper bound for a single backoff wait. */
      maxRetryDelayMs?: number;
      /** Test seam; defaults to a real timer. */
      sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
      /**
       * Redirect policy; unset means `DEFAULT_HTTP_REDIRECT` (`same-origin`). Under `same-origin` and
       * `error` the request is sent to `fetch` as `manual` and the 3xx is handled here, before `isOk`
       * sees it. With `manual` a 3xx comes back as a failure unless `isOk` accepts it.
       */
      redirect?: HttpRedirect;
      /** Decides whether a response counts as success. Defaults to `response.ok`. Must not read the body. */
      isOk?: (response: Response) => boolean;
      /**
       * Classifies a failed response before the default status mapping. Called once, when the client
       * is about to throw (after retries). Return undefined to keep the default mapping.
       */
      mapError?: (info: HttpErrorInfo) => SafranError | undefined;
      /** Hint put on 404 errors, e.g. which profile field names the missing thing. */
      notFoundHint?: string;
    }
    
    export interface HttpRequest {
      method?: "GET" | "POST";
      /**
       * Path relative to baseUrl, or an absolute URL on the same origin as baseUrl. An absolute URL on
       * any other origin is refused with `INVALID_INPUT` unless `allowOtherOrigin` is set.
       */
      path: string;
      /**
       * Lets `path` name another origin (a pre-signed download link, a CDN). Such a request is sent
       * WITHOUT the client-level `headers`, so the token configured for the service never leaves its
       * origin; only this request's own `headers` go along. A `path` on the client's origin is
       * unaffected by the flag.
       */
      allowOtherOrigin?: true;
      query?: Record<string, string | number | boolean | undefined | readonly (string | number)[]>;
      /** JSON-serialised when not a string. */
      body?: unknown;
      headers?: Record<string, string>;
      signal?: AbortSignal;
      /** Overrides the client's redirect policy for this request. */
      redirect?: HttpRedirect;
      /** Overrides the client's `notFoundHint` for this request. */
      notFoundHint?: string;
    }
    
    export interface HttpClient {
      /** Parsed JSON body. An empty 2xx body is an `UPSTREAM` error: no caller of a JSON API expects one. */
      json<T = unknown>(request: HttpRequest): Promise<T>;
      bytes(request: HttpRequest): Promise<{ data: Uint8Array; contentType?: string }>;
      /** Full response for callers that need headers (pagination via Link, continuation tokens). */
      raw(request: HttpRequest): Promise<Response>;
    }

    defined in packages/kit/src/http.ts

    Vendor JSON is unknown until it has been looked at. The helpers asRecord, asString, asNumber, asArray and isoDate turn a missing or oddly typed field into undefined instead of a crash three lines later.

    Capabilities are paired with methods

    getTicket, listProjects and matchTicketRef are required. Everything else is optional and announced through capabilities:

    Tracker capabilityMethod(s) it requires
    commentsgetComments
    attachmentslistAttachments, getAttachment
    linksgetLinks
    historygetHistory
    searchsearchTickets
    native-querysearchTickets (it then accepts query.native)
    Code host capabilityMethod it requires
    pull-requestslistMergedPullRequests
    remote-headgetRemoteHead

    Callers trust the set: tickets.history on a tracker without history is a clean UNSUPPORTED. So the two must agree, and Safran checks it when the instance is built. A connector that lists a capability without its method is refused, as a bug of the plugin:

    broken-capability.ts
    import { createSafran, defineProfile, defineTracker, isSafranError, SafranError } from "@safran/core";
    import { z } from "zod";
    
    const broken = defineTracker({
      type: "broken",
      configSchema: z.looseObject({ id: z.string(), type: z.literal("broken") }),
      create: (config) => ({
        id: config.id,
        type: "broken",
        // Claims history, implements no getHistory.
        capabilities: new Set(["history"] as const),
        matchTicketRef: () => undefined,
        listProjects: async () => [],
        getTicket: async (key) => {
          throw new SafranError("NOT_FOUND", `No ticket ${key}`);
        },
      }),
    });
    
    try {
      await createSafran({ profile: defineProfile({ version: 1, company: "acme", trackers: [{ id: "old", type: "broken" }] }), plugins: [broken], index: false });
    } catch (error) {
      if (!isSafranError(error)) throw error;
      console.log(error.code);
      console.log(error.message);
    }
    $ bun broken-capability.ts
    INTERNAL
    The profile has 1 configuration problem:
      - trackers.0 (old): The tracker plugin "broken" is broken: the connector it built lists the capability "history" but does not implement `getHistory` (This is a bug in the plugin, not in the profile. Report it to the plugin's author)

    The opposite, a method without its capability, is not an error: the method is simply never called.

    matchTicketRef

    matchTicketRef(input) answers one question: is this string one of my tickets, and what is its canonical key? Safran calls it on every tracker to route a reference (how), so:

    • Cheap and offline. A string test. Never a request: it runs for every reference on every tracker.
    • Return the canonical key, the form getTicket expects, or undefined.
    • Do not claim other trackers' forms. Accept your own URLs by comparing the parsed origin and path. Accept a bare key only when it is clearly yours: when the entry declares projects, a key of another project is not yours. A tracker that says yes to everything makes every reference ambiguous.
    • Never throw. Odd input is undefined.
    /**
     * Read-only access to an issue tracker. Optional methods are paired with a capability:
     * a tracker that lists `comments` must implement `getComments`, and so on.
     */
    export interface Tracker {
      /** Profile entry id. */
      readonly id: string;
      /** Plugin type, e.g. "jira". */
      readonly type: string;
      readonly capabilities: ReadonlySet<TrackerCapability>;
    
      /**
       * Recognises a ticket key or URL belonging to this tracker and returns the canonical key.
       * Must be cheap and offline: it is used to route a reference to the right tracker.
       */
      matchTicketRef(input: string): string | undefined;
    
      listProjects(options?: CallOptions): Promise<Project[]>;
      getTicket(key: string, options?: CallOptions): Promise<Ticket>;
    
      getComments?(key: string, options?: PageOptions): Promise<Page<Comment>>;
      listAttachments?(key: string, options?: CallOptions): Promise<Attachment[]>;
      getAttachment?(key: string, attachmentId: string, options?: CallOptions): Promise<AttachmentContent>;
      getLinks?(key: string, options?: CallOptions): Promise<TicketLink[]>;
      getHistory?(key: string, options?: PageOptions): Promise<Page<HistoryEntry>>;
      searchTickets?(query: TicketSearchQuery, options?: PageOptions): Promise<Page<TicketSummary>>;
    }

    defined in packages/kit/src/types.ts

    A code host

    A code host lists repositories, says how git authenticates, and optionally lists merged pull requests for the links store. Acme Forge is the in-house git server:

    plugins/acme-forge.ts
    import {
      asArray,
      asRecord,
      asString,
      createHttpClient,
      defineCodeHost,
      envVarName,
      httpUrl,
      isoDate,
      resolveLimit,
      type CodeHostCapability,
      type HttpClient,
      type PullRequest,
      type RepoInfo,
    } from "@safran/kit";
    import { z } from "zod";
    
    const configSchema = z.strictObject({
      id: z.string().min(1),
      type: z.literal("acme-forge"),
      url: httpUrl,
      token_env: envVarName,
      // The profile gives every code host entry these two. Safran applies them to what `listRepos`
      // returns, so the plugin only has to accept them.
      include: z.array(z.string().min(1)).default([]),
      exclude: z.array(z.string().min(1)).default([]),
    });
    
    export const acmeForge = defineCodeHost({
      type: "acme-forge",
      description: "Acme Forge, the in-house git server",
      configSchema,
    
      create(config, ctx) {
        const siteUrl = config.url.replace(/\/+$/, "");
        let client: HttpClient | undefined;
        const http = (): HttpClient =>
          (client ??= createHttpClient({
            service: "Acme Forge",
            baseUrl: `${siteUrl}/api`,
            headers: { authorization: `Bearer ${ctx.secret(config.token_env)}` },
            fetch: ctx.fetch,
            logger: ctx.logger,
          }));
    
        return {
          id: config.id,
          type: "acme-forge",
          capabilities: new Set<CodeHostCapability>(["pull-requests"]),
    
          async listRepos(options): Promise<RepoInfo[]> {
            const body = await http().json({ path: "repos", ...(options?.signal ? { signal: options.signal } : {}) });
            return asArray(asRecord(body)?.repos).flatMap((raw) => {
              const repo = asRecord(raw);
              const name = asString(repo?.name);
              if (!repo || !name) return [];
              return [
                {
                  name,
                  fullName: `acme/${name}`,
                  defaultBranch: asString(repo.default_branch) ?? "main",
                  // Without credentials: Safran hands `gitAuth()` to git through the environment.
                  cloneUrl: `${siteUrl}/git/${encodeURIComponent(name)}.git`,
                  webUrl: `${siteUrl}/repos/${encodeURIComponent(name)}`,
                  ...(repo.archived === true ? { archived: true } : {}),
                },
              ];
            });
          },
    
          async gitAuth() {
            return { kind: "bearer", token: ctx.secret(config.token_env) };
          },
    
          // Paired with the `pull-requests` capability. Newest first; `changedFiles` included, so no second call is needed.
          async listMergedPullRequests(repo, query) {
            const limit = resolveLimit(query?.limit, { default: 50, max: 100 });
            const body = await http().json({
              path: `repos/${encodeURIComponent(repo)}/merges`,
              query: { merged_since: query?.mergedSince, after: query?.cursor, limit },
              ...(query?.signal ? { signal: query.signal } : {}),
            });
            const record = asRecord(body);
            const items: PullRequest[] = asArray(record?.merges).flatMap((raw) => {
              const merge = asRecord(raw);
              const id = asString(merge?.id);
              if (!merge || !id) return [];
              const sourceBranch = asString(merge.branch);
              const mergedAt = isoDate(merge.merged_at);
              return [
                {
                  id,
                  repo,
                  title: asString(merge.title) ?? "",
                  description: asString(merge.description) ?? "",
                  ...(sourceBranch === undefined ? {} : { sourceBranch }),
                  ...(mergedAt === undefined ? {} : { mergedAt }),
                  // Only what the host itself links. Keys in the title and branch are recognised by Safran.
                  linkedTicketKeys: asArray(merge.issues).flatMap((key) => asString(key) ?? []),
                  changedFiles: asArray(merge.files).flatMap((path) => asString(path) ?? []),
                },
              ];
            });
            const next = asString(record?.next);
            return next === undefined ? { items } : { items, nextCursor: next };
          },
        };
      },
    });

    What matters here:

    • include / exclude belong in the schema, not in your code. Return every repository from listRepos; Safran applies the globs to the names.
    • name is the key used everywhere else: in code.groups, in team repos, in search scopes. It must be unique inside the host entry.
    • cloneUrl carries no credentials. Return them from gitAuth() as { kind: "bearer", token } or { kind: "basic", username, password }, or undefined for public repositories. Safran passes them to git through its environment, so they never appear in the URL, in .git/config or in a process listing.
    • listMergedPullRequests should return merged pull requests newest first and honour mergedSince. linkedTicketKeys holds only what the host itself links; Safran recognises keys in the title, branch and description on its own. Leave changedFiles out when it needs a second request and implement getPullRequestFiles instead.
    /** Read-only access to a place where repositories live. */
    export interface CodeHost {
      readonly id: string;
      readonly type: string;
      readonly capabilities: ReadonlySet<CodeHostCapability>;
    
      listRepos(options?: CallOptions): Promise<RepoInfo[]>;
      /** Credentials for cloning, or undefined for public / local repositories. */
      gitAuth(options?: CallOptions): Promise<GitAuth | undefined>;
    
      listMergedPullRequests?(repo: string, query?: PullRequestQuery): Promise<Page<PullRequest>>;
      getPullRequestFiles?(repo: string, pullRequestId: string, options?: CallOptions): Promise<string[]>;
      /** Head commit of a branch on the remote, to tell whether a local clone is behind. */
      getRemoteHead?(repo: string, branch: string, options?: CallOptions): Promise<string | undefined>;
      /** Web link to a file (and line range) for humans. */
      fileUrl?(repo: string, path: string, branch: string, lines?: { start: number; end?: number }): string | undefined;
    }
    
    /**
     * Credentials for git over HTTPS. Safran passes them to git through the environment
     * (an http.extraHeader config), never inside the URL, so they cannot end up in
     * `.git/config`, process listings or logs.
     */
    export type GitAuth =
      | { kind: "basic"; username: string; password: string }
      | { kind: "bearer"; token: string };
    
    export interface PullRequestQuery extends PageOptions {
      /** ISO date; only PRs merged at or after it. */
      mergedSince?: string;
    }

    defined in packages/kit/src/types.ts

    An embedder

    An embedder turns texts into vectors. It has two obligations:

    plugins/acme-embedder.ts
    import { asArray, asRecord, createHttpClient, defineEmbedder, envVarName, httpUrl, SafranError, type HttpClient } from "@safran/kit";
    import { z } from "zod";
    
    // An embeddings entry has no `id`: a profile has exactly one.
    const configSchema = z.strictObject({
      type: z.literal("acme-ml"),
      url: httpUrl,
      model: z.string().min(1),
      token_env: envVarName.optional(),
    });
    
    /** Scales a vector to length 1. Safran compares vectors with a dot product, which is only a cosine for unit vectors. */
    function normalise(values: readonly number[]): Float32Array {
      const vector = Float32Array.from(values);
      let sum = 0;
      for (const value of vector) sum += value * value;
      const norm = Math.sqrt(sum) || 1;
      for (let i = 0; i < vector.length; i++) vector[i] = (vector[i] ?? 0) / norm;
      return vector;
    }
    
    export const acmeEmbedder = defineEmbedder({
      type: "acme-ml",
      description: "Embeddings from the Acme ML gateway",
      configSchema,
    
      create(config, ctx) {
        let client: HttpClient | undefined;
        const http = (): HttpClient => {
          const token = ctx.optionalSecret(config.token_env);
          return (client ??= createHttpClient({
            service: "Acme ML",
            baseUrl: config.url,
            ...(token === undefined ? {} : { headers: { authorization: `Bearer ${token}` } }),
            fetch: ctx.fetch,
            logger: ctx.logger,
          }));
        };
    
        return {
          // Identity of the vectors. Include everything that changes them: vectors of different ids never mix.
          id: `acme-ml:${config.model}`,
    
          async embed(texts, options) {
            if (texts.length === 0) return [];
            const body = await http().json({
              path: "embed",
              body: { model: config.model, input: texts, purpose: options?.kind ?? "document" },
              ...(options?.signal ? { signal: options.signal } : {}),
            });
            const vectors = asArray(asRecord(body)?.vectors);
            if (vectors.length !== texts.length) {
              throw new SafranError("UPSTREAM", `Acme ML returned ${vectors.length} vectors for ${texts.length} texts`, { hint: "Check the model name under `embeddings` in the profile." });
            }
            // One vector per input, in the order of the inputs.
            return vectors.map((vector) => normalise(asArray(vector).map(Number)));
          },
        };
      },
    });
    • id identifies the vectors. The index records it per repository and refuses to mix vectors of different ids (INDEX_NOT_READY). Put everything that changes the output into it: the service and the model, and a version if the same model name can change.
    • Return one L2-normalised Float32Array per input, in order. Unit length is what makes the index's dot product a cosine similarity. options.kind is "query" or "document" for models that embed the two differently.

    Honour options.signal: indexing a large repository is thousands of calls, and a cancelled sync should stop promptly.

    export interface Embedder {
      /** Identity of the model, e.g. "ollama:bge-m3". Vectors from different ids never mix. */
      readonly id: string;
      /** Returns one L2-normalised vector per input, in order. */
      embed(texts: string[], options?: EmbedOptions): Promise<Float32Array[]>;
    }
    
    export interface EmbedOptions extends CallOptions {
      /** Some models embed queries and documents differently. */
      kind?: "query" | "document";
    }

    defined in packages/kit/src/types.ts

    A doc source

    A doc source fetches pages that tickets link to. Its matchUrl is a security boundary: Safran fetches a URL only when a source claims it (why).

    plugins/acme-handbook.ts
    import { asRecord, asString, createHttpClient, defineDocSource, envVarName, httpUrl, isoDate, SafranError, type DocPage, type HttpClient } from "@safran/kit";
    import { z } from "zod";
    
    const configSchema = z.strictObject({
      id: z.string().min(1),
      type: z.literal("acme-handbook"),
      url: httpUrl,
      token_env: envVarName,
    });
    
    export const acmeHandbook = defineDocSource({
      type: "acme-handbook",
      description: "Pages of the Acme Handbook",
      configSchema,
    
      create(config, ctx) {
        const origin = new URL(config.url).origin;
        let client: HttpClient | undefined;
        const http = (): HttpClient =>
          (client ??= createHttpClient({
            service: "Acme Handbook",
            baseUrl: `${origin}/api`,
            headers: { authorization: `Bearer ${ctx.secret(config.token_env)}` },
            fetch: ctx.fetch,
            logger: ctx.logger,
            notFoundHint: "Check the link in the ticket; the page may have been moved or deleted.",
          }));
    
        /** `/p/<slug>` on our own origin, or undefined. Parsed, never prefix-matched. */
        const slugOf = (url: string): string | undefined => {
          try {
            const parsed = new URL(url);
            if (parsed.origin !== origin) return undefined;
            return /^\/p\/([a-z0-9-]+)\/?$/.exec(parsed.pathname)?.[1];
          } catch {
            return undefined;
          }
        };
    
        return {
          id: config.id,
          type: "acme-handbook",
    
          matchUrl: (url) => slugOf(url) !== undefined,
    
          async getPage(url, options): Promise<DocPage> {
            const slug = slugOf(url);
            // Safran only calls getPage after matchUrl; a connector still never fetches what it does not own.
            if (slug === undefined) throw new SafranError("INVALID_INPUT", "Not an Acme Handbook page URL");
            const body = await http().json({ path: `pages/${slug}`, ...(options?.signal ? { signal: options.signal } : {}) });
            const page = asRecord(body);
            const updatedAt = isoDate(page?.updated_at);
            return {
              source: config.id,
              url,
              title: asString(page?.title) ?? slug,
              content: asString(page?.markdown) ?? "",
              ...(updatedAt === undefined ? {} : { updatedAt }),
            };
          },
        };
      },
    });
    • matchUrl must compare parsed origins. url.startsWith("https://handbook.acme.test") also matches https://handbook.acme.test.attacker.test/…. Parse with new URL() and compare origin, then check the path.
    • Cheap, offline, never throws, like matchTicketRef.
    • getPage returns Markdown in content. Convert HTML or a vendor format in the connector.
    • Fetch only your own origin. Build the request from the parts you validated, not from the caller's string.
    /**
     * Read-only access to pages that tickets link to: wikis, design docs, specs.
     * A source only ever fetches URLs it recognises as its own.
     */
    export interface DocSource {
      readonly id: string;
      readonly type: string;
      /** Cheap, offline check: does this URL belong to this source? */
      matchUrl(url: string): boolean;
      getPage(url: string, options?: CallOptions): Promise<DocPage>;
    }
    
    export interface DocPage {
      /** Id of the doc source entry in the profile. */
      source: string;
      url: string;
      title: string;
      /** Markdown. */
      content: string;
      updatedAt?: string;
      author?: Person;
    }

    defined in packages/kit/src/types.ts

    Loading plugins

    Collect the plugins of a project in one module:

    plugins/index.ts
    import { acmeDesk } from "./acme-desk";
    import { acmeEmbedder } from "./acme-embedder";
    import { acmeForge } from "./acme-forge";
    import { acmeHandbook } from "./acme-handbook";
    
    // Every export shaped like a plugin is registered, and so is every member of an exported array.
    export const plugins = [acmeDesk, acmeForge, acmeHandbook, acmeEmbedder];

    Through the plugins option

    A program that builds its own instance passes them in:

    use-plugins.ts
    import { createSafran, defineProfile } from "@safran/core";
    import { plugins } from "./plugins/index";
    
    const profile = defineProfile({
      version: 1,
      company: "acme",
      trackers: [
        { id: "jira", type: "jira", url: "https://acme.atlassian.net", email_env: "JIRA_EMAIL", token_env: "JIRA_TOKEN", projects: ["PAY", "MOB", "WEB"] },
        { id: "desk", type: "acme-desk", url: "https://desk.acme.test", token_env: "DESK_TOKEN", projects: ["DESK"] },
      ],
      code: { hosts: [{ id: "forge", type: "acme-forge", url: "https://forge.acme.test", token_env: "FORGE_TOKEN", exclude: ["*-archive"] }] },
      docs: [{ id: "handbook", type: "acme-handbook", url: "https://handbook.acme.test", token_env: "HANDBOOK_TOKEN" }],
      embeddings: { type: "acme-ml", url: "https://ml.acme.test/v1", model: "code-embed-2" },
    });
    
    // The built-in plugins stay registered; these are added next to them.
    await using safran = await createSafran({ profile, plugins });
    
    console.log(safran.tickets.resolve("DESK-412").tracker.id, safran.tickets.resolve("PAY-1423").tracker.id);
    console.log(safran.tickets.resolve("https://desk.acme.test/issues/desk-0412").key);
    console.log(safran.docs.canFetch("https://handbook.acme.test/p/refund-policy"), safran.docs.canFetch("https://handbook.acme.test.attacker.test/p/refund-policy"));
    console.log([...(safran.trackers.get("desk")?.capabilities ?? [])]);
    $ bun use-plugins.ts
    desk jira
    DESK-412
    true false
    [ "comments", "search" ]

    Through the profile

    For the CLI and the MCP server, name the module in the profile. Each entry under plugins: is a path relative to the profile file, or a package name:

    version: 1
    company: acme
    
    plugins:
      - ./plugins/index.ts        # relative to this file
      - acme-safran-plugins       # or a package, resolved from this file's directory
    
    trackers:
      - id: desk
        type: acme-desk
        url: https://desk.acme.test
        token_env: DESK_TOKEN
        projects: [DESK]

    How a module is loaded:

    • Every export shaped like a plugin is registered, and so is every member of an exported array. A plugin exported twice (by name and in a list) counts once. A module that exports no plugin is PLUGIN_NOT_FOUND.
    • The module must be able to import its own dependencies. A plugin file imports @safran/kit and zod, so it has to live in a package that declares them, exactly like any other code that uses Safran (installation).
    • An inline profile has no file; its plugins: paths resolve against the current directory.
    • Loading a module runs it. createSafran({ allowProfilePlugins: false }) refuses a profile that lists plugins with FORBIDDEN. The CLI does that for a profile it merely found in the current directory, and loads plugins for a profile you named with --profile. See allowProfilePlugins.

    safran plugins lists what is registered, including the plugins a profile brought in.

    Collisions

    A plugin is identified by kind and type. Registering the same pair twice is an INVALID_INPUT error, whichever way the two arrived (built-in, profile module, option). There is no override order to remember. To replace a built-in connector, pass builtinPlugins: false and register the set you want, or give your plugin its own type.

    Rules for plugins

    A connector runs inside someone's agent, with their credentials. The rules are short and every built-in plugin follows them:

    1. No network in create. createSafran must work offline, and safran profile check must not need the network. Build clients lazily.
    2. Read secrets only through ctx.secret / ctx.optionalSecret. Never process.env: the caller may have passed its own env, and AUTH_MISSING with the variable's name only comes from the context.
    3. Use ctx.fetch, never the global fetch. Otherwise tests cannot intercept you and a caller's proxy is bypassed.
    4. Never log or throw a token. Not in a message, a hint, details or a log field. Do not put credentials in URLs.
    5. Read-only. A Safran connector never creates, edits or deletes anything in the system it reads.
    6. Map vendor errors through the HTTP client, and throw SafranError with the right code for what it cannot see (an error inside a 200 response, a body in an unexpected shape).
    7. Honour signal in every method that takes options.
    8. Apply the paging rules: resolveLimit for limits, opaque cursors, the end of data as an absent nextCursor. See pagination.
    9. Return neutral shapes. Markdown for text, ISO 8601 for dates, statusCategory mapped to todo / in_progress / done, vendor extras under Ticket.fields with human-readable keys.

    Test a connector against recorded responses with mockFetch before pointing it at the real service.

    Common mistakes

    SymptomCause
    PLUGIN_CONFIG_INVALID: … Unrecognized key: "projects"A strict tracker schema that does not declare projects (or a code host schema without include / exclude). The profile adds those fields to every entry.
    INTERNAL: … lists the capability … but does not implementcapabilities and the methods disagree.
    INVALID_INPUT: "…" could belong to several trackersmatchTicketRef claims keys that are not its own. Restrict it to the declared projects.
    INVALID_INPUT: … is registered more than onceThe plugin is loaded both from the profile's plugins: and through the plugins option, or its type equals a built-in's.
    AUTH_MISSING at creation instead of first useThe plugin calls ctx.secret inside create. Read it when the first request is made.
    PLUGIN_NOT_FOUND: Could not load plugin moduleThe path is not relative to the profile file, or the module cannot resolve @safran/kit from where it lives.