createSafran and its options
createSafran() turns a profile into a running instance: it loads and validates the profile, registers the plugins and builds one connector per profile entry. This page lists every option, says exactly what happens at creation and what waits until first use, and describes the instance you get back.
A complete example
With no options, Safran reads ./safran.yaml, keeps its data in ./data next to it and uses the built-in plugins:
import { createSafran } from "@safran/core";
await using safran = await createSafran();
console.log(safran.profile.company, safran.profileFile, safran.dataDir);
console.log([...safran.trackers.keys()], [...safran.hosts.keys()], [...safran.docSources.keys()]);The same instance from an inline profile, with the data directory named explicitly:
import { createSafran, defineProfile } from "@safran/core";
const profile = defineProfile({
version: 1,
company: "acme",
languages: { tickets: "tr", code: "en" },
trackers: [{ id: "jira", type: "jira", url: "https://acme.atlassian.net", email_env: "JIRA_EMAIL", token_env: "JIRA_TOKEN", projects: ["PAY", "MOB", "WEB"] }],
code: {
hosts: [{ id: "azure", type: "azure-repos", organization: "acme", project: "Platform", token_env: "AZURE_DEVOPS_PAT" }],
groups: { backend: ["payments-api", "ledger"] },
},
glossary: [{ term: "İade", code: ["refund", "chargeback"] }],
});
await using safran = await createSafran({ profile, dataDir: "/work/acme/data" });
console.log(safran.profileFile, safran.dataDir);
console.log([...safran.trackers.keys()], [...safran.hosts.keys()], [...safran.docSources.keys()]);
console.log([...(safran.trackers.get("jira")?.capabilities ?? [])].join(", "));$ bun inline.ts
undefined /work/acme/data
[ "jira" ] [ "azure" ] []
comments, attachments, links, history, search, native-queryThis runs without a network connection and without JIRA_TOKEN being set: building connectors does no I/O, and the built-in connectors read their token on the first call that needs it.
Options
Every field is optional. One convention holds throughout: undefined means "use the default", false means "off".
| Option | Type | Default | What it does |
|---|---|---|---|
profile | string | ProfileInput | "safran.yaml" in the current directory | The company profile: a path to a YAML file, or the profile object itself. |
dataDir | string | data next to the profile file | Where clones, the code index, the links store and connector caches live. |
plugins | SafranPlugin[] | [] | Extra plugins, registered next to the built-in ones. |
builtinPlugins | boolean | true | false starts with an empty registry, so only plugins (and the profile's plugins:) exist. |
embedder | Embedder | built from profile.embeddings on first use | Replaces the embedder of the profile. |
index | CodeIndex | false | opened in <dataDir>/index on first use | A live index to use instead, or false for no code search at all. |
env | Record<string, string | undefined> | process.env | Where secrets are looked up. |
logger | Logger | silent | Receives diagnostics. See logging. |
fetch | typeof fetch | the global fetch | The HTTP function handed to every connector. |
allowProfilePlugins | boolean | true | Whether modules listed under plugins: in the profile may be imported. |
/**
* Options for `createSafran`. Every field is optional: with none, Safran reads
* `./safran.yaml`, keeps its data in `./data` and uses the built-in plugins.
*
* Convention used throughout: `undefined` means "use the default", `false` means "off".
*/
export interface SafranOptions {
/**
* The company profile: a path to a YAML file, or the profile itself.
* Default: `safran.yaml` in the current directory.
*/
profile?: string | ProfileInput;
/** Where clones, the index and caches live. Default: `data` next to the profile file. */
dataDir?: string;
/** Extra plugins, registered next to the built-in ones. A type collision is an error. */
plugins?: SafranPlugin[];
/** `false` starts with an empty registry, so only `plugins` are available. Default: true. */
builtinPlugins?: boolean;
/** Overrides the embedder built from `profile.embeddings`. */
embedder?: Embedder;
/**
* Overrides the code index. `false` disables code search entirely (tickets-only use).
* An index passed in here is owned by the caller: `close()` does not close it, so one index
* can serve several instances. Only the index Safran opens itself is closed with it.
*/
index?: CodeIndex | false;
/** Environment used to resolve secrets. Default: `process.env`. */
env?: Record<string, string | undefined>;
/** Default: silent. */
logger?: Logger;
/** Default: the global `fetch`. */
fetch?: typeof fetch;
/**
* Whether modules listed under `plugins:` in the profile may be imported (which runs their
* code). Default: true. A caller that did not choose the profile itself (a CLI picking up
* `./safran.yaml` from the working directory) passes `false`; a profile that lists plugins then
* fails with FORBIDDEN instead of executing them.
*/
allowProfilePlugins?: boolean;
}defined in packages/core/src/api.ts
profile
A string is a path. A relative path resolves against the current directory; the file is parsed as YAML and validated. A missing file and an invalid one both fail with PROFILE_INVALID, and the error's details.problems lists every problem with its path in the file.
An object is the profile itself, validated the same way. defineProfile only adds types; it returns its argument unchanged. An inline profile has no file, which changes three things:
safran.profileFileisundefined.- The default data directory is
./datain the current directory. - Paths in the profile (a
localhost's directories,plugins:entries) resolve against the current directory, and plugins receive noprofileDir.
The profile format is described in the profile reference.
dataDir
The first rule that applies wins:
dataDirgiven: that path, made absolute against the current directory.- The profile was loaded from a file:
datanext to that file. - Inline profile:
./datain the current directory.
safran.dataDir is always absolute. Nothing is created until something is written. Inside it:
| Path | Holds |
|---|---|
repos/<hostId>/<repo> | The working trees Safran clones. See repositories. |
index/index.db | The code index. |
safran.db | The links store. |
cache/<entryId> | The directory each connector may use for its own cache (ctx.dataDir of a plugin). |
plugins and builtinPlugins
Plugins are registered in this order: the built-in ones (unless builtinPlugins: false), the modules named under plugins: in the profile, then the plugins option. A plugin is identified by its kind and type; registering the same pair twice is an INVALID_INPUT error, never a silent override. To replace a built-in, pass builtinPlugins: false and register what you need:
import { builtinPlugins, createSafran } from "@safran/core";
// Only the tracker plugins: no code hosts, no doc sources, no embedders.
const trackersOnly = builtinPlugins.filter((plugin) => plugin.kind === "tracker");
await using safran = await createSafran({ builtinPlugins: false, plugins: trackersOnly });
console.log((await safran.tickets.get("PAY-1423")).title);A profile entry whose type has no registered plugin fails creation with PLUGIN_NOT_FOUND, so the profile for this instance must not contain code.hosts or docs entries. Writing your own plugins is covered in plugins.
embedder
By default the embedder is built from the profile's embeddings entry (ollama with bge-m3 when the profile says nothing). An Embedder passed here is used instead, and the embeddings entry is then not looked at. The embedder is only called by code search and indexing.
index
- Left out: Safran opens its own index in
<dataDir>/indexon the first code call and closes it inclose(). - A
CodeIndexinstance: used as given. It stays yours:close()does not close it, so one index can serve several instances. A fullrepos.sync()never removes repos from an index you passed in. false: no code search. Everysafran.code.*call and an indexingrepos.sync()throwUNSUPPORTED; tickets, docs, repos listing, links and company calls work as usual. See ticket-only use.
env
Secrets never appear in a profile. A profile names environment variables (token_env: JIRA_TOKEN) and connectors resolve them through this map. Pass your own to keep secrets out of process.env, or to give two instances different credentials:
import { createSafran } from "@safran/core";
declare function readFromVault(name: string): Promise<string>;
await using safran = await createSafran({
env: {
JIRA_EMAIL: "bot@acme.test",
JIRA_TOKEN: await readFromVault("jira"),
AZURE_DEVOPS_PAT: await readFromVault("azure"),
},
});A variable that is unset or empty makes the call that needs it fail with AUTH_MISSING; the error's details.variable is its name.
logger and fetch
logger is silent by default; pass a Logger to see what Safran does (retries, skipped repos, failing trackers). fetch replaces the HTTP function of every connector at once, which is how tests avoid the network (mockFetch) and how a proxy or a recording layer is inserted.
allowProfilePlugins
A profile can list plugin modules under plugins:. Loading a module runs its code, so this option decides whether the profile is trusted to do that. The default is true: a program that names its profile has chosen it. A program that picks up whatever safran.yaml sits in the working directory should pass false; a profile that lists plugins then fails with FORBIDDEN before any module is imported:
import { createSafran, isSafranError } from "@safran/core";
try {
await using safran = await createSafran({ allowProfilePlugins: false });
console.log(safran.profile.company);
} catch (error) {
if (!isSafranError(error, "FORBIDDEN")) throw error;
// error.details.plugins lists the modules the profile wanted to load
console.error(error.format());
}The CLI does exactly this for a profile found in the current directory.
What creation does
In order:
- Loads and validates the profile.
- Refuses a profile with
plugins:whenallowProfilePluginsisfalse. - Registers the plugins and imports the profile's plugin modules.
- For every entry under
trackers,code.hostsanddocs: looks up the plugin bytype, validates the entry with the plugin's schema and calls the plugin'screate. - Checks that every connector implements the methods behind the capabilities it lists.
- Looks up the embedder plugin and validates the
embeddingsentry, without building the embedder.
Every entry is tried even after one failed, and all problems are reported in a single error, one per line:
import { createSafran, defineProfile, isSafranError } from "@safran/core";
const profile = defineProfile({
version: 1,
company: "acme",
trackers: [{ id: "jira", type: "jira", url: "https://acme.atlassian.net", token_env: "JIRA_TOKEN" }],
code: { hosts: [{ id: "azure", type: "azure-repo", organization: "acme", token_env: "AZURE_DEVOPS_PAT" }] },
embeddings: { type: "ollama", model: "bge-m3", batch: 16 },
});
try {
await createSafran({ profile });
} catch (error) {
if (!isSafranError(error)) throw error;
console.log(error.code);
console.log(error.format());
}$ bun problems.ts
PLUGIN_CONFIG_INVALID
The profile has 3 configuration problems:
- trackers.0.email_env: is required for Jira Cloud (the API token is used together with the account e-mail)
- code.hosts.0 (azure): No code-host plugin handles type "azure-repo" (Available code-host types: azure-repos, github, gitlab, local.)
- embeddings: Unrecognized key: "batch"
→ Fix these entries in the profile. `safran plugins` lists the available types and their fields.The same lines are in error.details.problems as an array. The error's code is the code the problems share, or PLUGIN_CONFIG_INVALID when they differ, as here.
What creation does not do
- No network. No connector is contacted. A wrong URL or an expired token shows up on the first call that uses it.
- No secrets, for the built-in connectors. They resolve their token on first use, so an instance can be created (and its profile checked) on a machine without credentials.
- No index, no embedder. The code index is opened and the embedder is built on the first code call or the first indexing sync. Ticket, docs, repo listing, links and company calls never trigger either.
- No files. The data directory is created when something is first written to it.
Step 6 is skipped when this instance will not build an embedder itself: embedder or index was passed (including index: false), or no embedder plugin is registered at all.
Errors at creation
| Code | When |
|---|---|
PROFILE_INVALID | The profile file is missing, is not valid YAML or does not match the schema. |
FORBIDDEN | The profile lists plugins: and allowProfilePlugins is false. |
PLUGIN_NOT_FOUND | A module under plugins: cannot be imported or exports no plugin; or no plugin handles an entry's type. |
PLUGIN_CONFIG_INVALID | An entry does not match its plugin's schema; also the code of a report that mixes several kinds of problems. |
INVALID_INPUT | Two plugins share a kind and type. |
INTERNAL | A plugin's create threw something that is not a SafranError, or the connector lists a capability without its method. |
The instance
| Member | Type | What it is |
|---|---|---|
profile | Profile | The validated profile with defaults applied. |
profileFile | string | undefined | Absolute path of the profile file; undefined for an inline profile. |
dataDir | string | Absolute path of the data directory. |
trackers | ReadonlyMap<string, Tracker> | The tracker connectors by profile entry id. |
hosts | ReadonlyMap<string, CodeHost> | The code host connectors by entry id. |
docSources | ReadonlyMap<string, DocSource> | The doc source connectors by entry id. |
tickets | TicketsApi | Reading and searching tickets across every tracker. |
code | CodeApi | Search, grep and file reads over the indexed code. |
docs | DocsApi | Fetching linked pages through the doc sources. |
repos | ReposApi | Listing and syncing repositories. |
links | LinksApi | Work history: which tickets changed which files. |
company | CompanyApi | Teams, glossary, conventions, ownership. |
close() | Promise<void> | Stops the instance and releases its handles. See lifecycle. |
The instance is also an AsyncDisposable, so await using calls close() for you.
The three maps give direct access to a connector when the sub-APIs are not enough, for example to check a capability before offering a feature:
import { createSafran } from "@safran/core";
await using safran = await createSafran();
for (const [id, tracker] of safran.trackers) {
console.log(id, tracker.type, [...tracker.capabilities].join(", "));
}
const azure = safran.hosts.get("azure");
console.log(azure?.capabilities.has("pull-requests"));Calls made directly on a connector skip what the sub-APIs add: reference routing, capability errors with hints, and cancellation when the instance closes. Prefer the sub-APIs.
export interface Safran extends AsyncDisposable {
readonly profile: Profile;
/** Absolute path of the profile file, when it was loaded from disk. */
readonly profileFile: string | undefined;
readonly dataDir: string;
/** Connectors by profile entry id. Built eagerly; building them does no network I/O. */
readonly trackers: ReadonlyMap<string, Tracker>;
readonly hosts: ReadonlyMap<string, CodeHost>;
readonly docSources: ReadonlyMap<string, DocSource>;
readonly tickets: TicketsApi;
readonly code: CodeApi;
readonly docs: DocsApi;
readonly repos: ReposApi;
readonly links: LinksApi;
readonly company: CompanyApi;
/**
* Stops the instance: later calls fail, calls still running are cancelled (they end with
* ABORTED; `repos.sync` and `links.refresh` return their report with `aborted: true`) and are
* waited for, then the index and every open handle are released. Nothing can open a handle
* afterwards. Safe to call more than once; never rejects because a running call failed.
*/
close(): Promise<void>;
}defined in packages/core/src/api.ts