Eklenti yazmak
Safran'ın konuştuğu her sistem bir eklentidir; yerleşikler de öyle. Eklenti düz bir nesnedir: bir kind, profilde onu seçen type dizesi, profil girişi için bir şema ve bağlayıcı döndüren bir create işlevi. Bu sayfa eksiksiz bir özel iş takip sistemi kurar, ardından bir kod barındırıcı, bir gömme modeli ve bir doküman kaynağı yazar; eklentileri yüklemenin iki yolunu gösterir ve bir eklentinin uyması gereken kuralları belirtir.
Dört tür, her birini tanımlayan yardımcı ve bağlayıcısının uyguladığı sözleşme:
| Tür | Yardımcı | Sözleşme | Profil bölümü |
|---|---|---|---|
| İş takip sistemi | defineTracker | Tracker | trackers[] |
| Kod barındırıcı | defineCodeHost | CodeHost | code.hosts[] |
| Doküman kaynağı | defineDocSource | DocSource | docs[] |
| Gömme modeli | defineEmbedder | Embedder | embeddings |
Yardımcılar yalnızca kind alanını ekler ve tip çıkarımı sağlar: create içinde config, şemanızın çıktı tipini taşır. Örnekler, eklenti yazarları için hazırlanmış paket olan @safran/kit paketinden içe aktarır; @safran/core da define* yardımcılarını, createHttpClient, envVarName, httpUrl ve hata yardımcılarını yeniden dışa açar, dolayısıyla küçük bir eklenti yalnızca @safran/core ile de yazılabilir.
Eksiksiz bir iş takip sistemi
Acme, https://desk.acme.test adresinde kendi geliştirdiği bir iş takip sistemi, Acme Desk'i çalıştırır. Anahtarları DESK-412 biçimindedir ve küçük bir JSON API'si vardır. Bu eklenti onu, yorumları ve araması olan bir Safran iş takip sistemi yapar:
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 };
},
};
},
});Gerçek servis olmadan deneyin. mockFetch bir rota tablosundan yanıt verir; bağlayıcı da üretimde çalıştırdığı kodun tam olarak aynısını çalıştırır:
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"
]Aşağıdaki bölümler eklentinin her parçasını açıklar.
Yapılandırma şeması
configSchema, id ve type dahil profil girişinin tamamını doğrular. Profil önce bir türün her girişinin paylaştığı alanları doğrular, sonra girişi sizin şemanıza verir:
| Tür | Profilin her girişe eklediği alanlar |
|---|---|
| İş takip sistemi | id, type, projects (varsayılanı boş liste) |
| Kod barındırıcı | id, type, include, exclude (ikisinin de varsayılanı boş liste) |
| Doküman kaynağı | id, type |
| Gömme modeli | type (id yoktur: profilde tek bir embeddings girişi bulunur) |
Şemanız bu alanları kabul etmelidir; yoksa onları belirten bir profil reddedilir. Bunun ötesinde:
z.strictObjectkullanın. Yanlış yazılmış bir anahtar (tokne_env) o zaman sessizce yok sayılan bir ayar değil, yoluyla birlikte bildirilen bir hata olur.- Gizli değerler için
envVarNamekullanın. Yalnızca bir ortam değişkeninin adını (DESK_TOKEN) kabul eder. Profile yapıştırılan bir jeton, nedenini söyleyen bir iletiyle doğrulamadan geçemez; amaç da budur: gizli değerlerin profilde yeri yoktur. - Temel URL'ler için
httpUrlkullanın. Yalın birhttp(s)URL'sini kabul eder; kimlik bilgisi, sorgu dizesi veya parça (fragment) taşıyanı reddeder. - Varsayılanları şemada verin (
.default(...)); böylececreateeksiksiz bir yapılandırma alır.
Şema sorunları girişin konumuyla (trackers.1.url: …), PLUGIN_CONFIG_INVALID olarak ve profilin diğer bütün sorunlarıyla birlikte bildirilir.
Bağlam
create(config, ctx), bir PluginContext alır:
| Üye | Ne için kullanılır |
|---|---|
company | Profildeki şirket kısa adı. |
logger | Tanılama. createHttpClient çağrısına verin. Asla jeton yazmayın. |
fetch | Her HTTP isteği. Örneğin fetch seçeneğidir; testler ve vekil sunucular araya girebilir. |
dataDir | Önbellekler için size ait bir dizin: <dataDir>/cache/<entryId>. İlk yazışınızda oluşturun. |
profileDir | Profil dosyasının mutlak dizini; girişte yazılı göreli yolları çözmek için. Satır içi profilde bulunmaz. |
secret(envName) | Zorunlu bir gizli değer. Değişken tanımsız veya boşsa ipuçlu AUTH_MISSING fırlatır. |
optionalSecret(envName) | İsteğe bağlı bir jeton için aynısı: tanımsızsa undefined. |
/** 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;
}tanımlandığı yer: packages/kit/src/plugin.ts
HTTP istemcisi
createHttpClient, yerleşik her bağlayıcının kullandığı fetch sarmalayıcısıdır. Çağıranların beklediği davranışı, yeniden yazmadan eklentiye kazandırır:
- Deneme başına zaman aşımı (varsayılan 30 saniye) ve 429, 5xx ile ağ hataları için
Retry-Afterbaşlığına uyan beklemeyle en çok üç yeniden deneme. - Satıcı durum kodlarının Safran kodlarına eşlenmesi: 401 ve 403
AUTH_FAILED, 404NOT_FOUND, 429RATE_LIMITED, gerisiUPSTREAM. Bkz. hatalar. - İptal: çağrının
signaldeğerini her istekte iletin. - Kökene sabitleme. Başka bir kökeni gösteren istek yolu reddedilir ve yönlendirmeler yalnızca sorulan kökenin içinde izlenir; böylece
headersiçindeki jeton, sunucunun verdiği bir "sonraki sayfa" bağlantısıyla başka bir sunucuya gönderilemez. - Başlık değerlerini ve sorgu dizelerini asla içermeyen hatalar ve günlük satırları.
Üç metot çoğu API'yi karşılar: ayrıştırılmış gövde için json(), indirmeler için bytes(), yanıt başlıklarına ihtiyaç duyduğunuzda raw().
| Seçenek | Anlamı |
|---|---|
service | Hata iletilerinde kullanılan ad; örneğin "Acme Desk". |
baseUrl | Yollar buna eklenir. |
headers | Temel URL'nin kökenine giden her istekle gönderilir. Kimlik bilgisi buraya konur. |
fetch | ctx.fetch verin. |
logger | ctx.logger verin. |
timeoutMs | Deneme başına zaman aşımı. |
maxRetries | İlk denemeden sonraki yeniden deneme sayısı. |
mapError | Hataları kendine özgü biçimde bildiren servisler için, başarısız bir yanıtı varsayılan eşlemeden önce kendiniz sınıflandırın. |
notFoundHint | 404 hatalarına konan ipucu; örneğin eksik şeyi hangi profil alanının adlandırdığı. |
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>;
}tanımlandığı yer: packages/kit/src/http.ts
Satıcıdan gelen JSON, bakılana kadar unknown tipindedir. asRecord, asString, asNumber, asArray ve isoDate yardımcıları eksik veya beklenmedik tipte bir alanı, üç satır sonra bir çökme yerine undefined yapar.
Yetenekler metotlarla eşleşir
getTicket, listProjects ve matchTicketRef zorunludur. Geri kalan her şey isteğe bağlıdır ve capabilities üzerinden duyurulur:
| İş takip yeteneği | Gerektirdiği metot(lar) |
|---|---|
comments | getComments |
attachments | listAttachments, getAttachment |
links | getLinks |
history | getHistory |
search | searchTickets |
native-query | searchTickets (o zaman query.native değerini kabul eder) |
| Kod barındırıcı yeteneği | Gerektirdiği metot |
|---|---|
pull-requests | listMergedPullRequests |
remote-head | getRemoteHead |
Çağıranlar bu kümeye güvenir: history yeteneği olmayan bir sistemde tickets.history temiz bir UNSUPPORTED verir. Bu yüzden ikisi tutarlı olmalıdır ve Safran bunu örnek kurulurken denetler. Metodu olmayan bir yetenek listeleyen bağlayıcı, eklentinin hatası olarak reddedilir:
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)Tersi, yani yeteneği olmayan bir metot hata değildir: metot yalnızca hiç çağrılmaz.
matchTicketRef
matchTicketRef(input) tek bir soruyu yanıtlar: bu dize benim kayıtlarımdan biri mi ve kanonik anahtarı nedir? Safran onu bir referansı yönlendirmek için her sistemde çağırır (nasıl); dolayısıyla:
- Ucuz ve çevrimdışı. Bir dize testi. Asla bir istek değil: her referans için her sistemde çalışır.
- Kanonik anahtarı döndürün, yani
getTicketçağrısının beklediği biçimi, ya daundefined. - Başka sistemlerin biçimlerini sahiplenmeyin. Kendi URL'lerinizi, ayrıştırılmış kökeni ve yolu karşılaştırarak kabul edin. Yalın bir anahtarı yalnızca açıkça sizinse kabul edin: giriş
projectsbildiriyorsa başka bir projenin anahtarı sizin değildir. Her şeye evet diyen bir sistem her referansı belirsiz kılar. - Asla fırlatmayın. Tuhaf girdi
undefineddemektir.
/**
* 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>>;
}tanımlandığı yer: packages/kit/src/types.ts
Bir kod barındırıcı
Kod barındırıcı repoları listeler, git'in nasıl kimlik doğrulayacağını söyler ve isteğe bağlı olarak bağlantı deposu için birleştirilmiş pull request'leri listeler. Acme Forge, şirket içi git sunucusudur:
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 };
},
};
},
});Burada önemli olanlar:
include/excludekodunuzda değil, şemada durur.listReposçağrısından bütün repoları döndürün; glob desenlerini adlara Safran uygular.nameanahtardır; başka her yerde kullanılır:code.groupsiçinde, ekiplerinreposlistesinde, arama kapsamlarında. Barındırıcı girişinin içinde benzersiz olmalıdır.cloneUrlkimlik bilgisi taşımaz. Kimlik bilgilerinigitAuth()çağrısından{ kind: "bearer", token }veya{ kind: "basic", username, password }olarak, herkese açık repolar içinundefinedolarak döndürün. Safran bunları git'e ortamı üzerinden verir; URL'de,.git/configdosyasında veya süreç listesinde asla görünmezler.listMergedPullRequests, birleştirilmiş pull request'leri en yeniden eskiye döndürmeli vemergedSincedeğerine uymalıdır.linkedTicketKeysyalnızca barındırıcının kendisinin bağladıklarını tutar; başlıktaki, daldaki ve açıklamadaki anahtarları Safran kendisi tanır. İkinci bir istek gerektiriyorsachangedFilesalanını yazmayın, onun yerinegetPullRequestFilesmetodunu uygulayın.
/** 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;
}tanımlandığı yer: packages/kit/src/types.ts
Bir gömme modeli
Gömme modeli metinleri vektörlere çevirir. İki yükümlülüğü vardır:
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)));
},
};
},
});idvektörleri tanımlar. İndeks onu repo başına kaydeder ve farklı kimliklerin vektörlerini karıştırmayı reddeder (INDEX_NOT_READY). Çıktıyı değiştiren her şeyi içine koyun: servisi ve modeli, aynı model adı değişebiliyorsa bir sürümü de.- Her girdi için, sırasıyla, L2 normalleştirilmiş bir
Float32Arraydöndürün. İndeksin nokta çarpımını kosinüs benzerliği yapan şey birim uzunluktur.options.kind, sorguları ve dokümanları farklı gömen modeller için"query"veya"document"değerini taşır.
options.signal değerine uyun: büyük bir repoyu indekslemek binlerce çağrı demektir ve iptal edilen senkronizasyon hemen durmalıdır.
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";
}tanımlandığı yer: packages/kit/src/types.ts
Bir doküman kaynağı
Doküman kaynağı, kayıtların bağlandığı sayfaları getirir. matchUrl metodu bir güvenlik sınırıdır: Safran bir URL'yi yalnızca bir kaynak onu sahiplendiğinde getirir (neden).
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 }),
};
},
};
},
});matchUrlayrıştırılmış kökenleri karşılaştırmalıdır.url.startsWith("https://handbook.acme.test"),https://handbook.acme.test.attacker.test/…adresiyle de eşleşir.new URL()ile ayrıştırın veorigindeğerini karşılaştırın, sonra yolu denetleyin.matchTicketRefgibi ucuz ve çevrimdışıdır, asla fırlatmaz.getPage,contentiçinde Markdown döndürür. HTML'yi veya satıcıya özgü bir biçimi bağlayıcıda dönüştürün.- Yalnızca kendi kökeninizden getirin. İsteği çağıranın dizesinden değil, doğruladığınız parçalardan kurun.
/**
* 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;
}tanımlandığı yer: packages/kit/src/types.ts
Eklentileri yüklemek
Bir projenin eklentilerini tek bir modülde toplayın:
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];plugins seçeneğiyle
Kendi örneğini kuran bir program onları doğrudan verir:
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" ]Profil üzerinden
CLI ve MCP sunucusu için modülün adını profilde verin. plugins: altındaki her giriş, profil dosyasına göre bir yol ya da bir paket adıdır:
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]Bir modül şöyle yüklenir:
- Eklenti biçimindeki her dışa aktarım kaydedilir; dışa aktarılan bir dizinin her üyesi de öyle. İki kez dışa aktarılan eklenti (adıyla ve bir listede) bir kez sayılır. Hiç eklenti dışa aktarmayan modül
PLUGIN_NOT_FOUNDhatasıdır. - Modül kendi bağımlılıklarını içe aktarabilmelidir. Eklenti dosyası
@safran/kitvezodiçe aktarır; dolayısıyla, Safran kullanan diğer her kod gibi, bunları bildiren bir paketin içinde durmalıdır (kurulum). - Satır içi profilin dosyası yoktur;
plugins:yolları geçerli dizine göre çözümlenir. - Bir modülü yüklemek onu çalıştırır.
createSafran({ allowProfilePlugins: false }), eklenti listeleyen profiliFORBIDDENile reddeder. CLI bunu geçerli dizinde yalnızca bulduğu profil için yapar;--profileile adını verdiğiniz profilin eklentilerini ise yükler. Bkz.allowProfilePlugins.
safran plugins, profilin getirdiği eklentiler dahil, kayıtlı olanları listeler.
Çakışmalar
Bir eklenti türü ve type değeriyle tanımlanır. Aynı çifti iki kez kaydetmek, ikisi hangi yoldan gelmiş olursa olsun (yerleşik, profil modülü, seçenek) INVALID_INPUT hatasıdır. Akılda tutulacak bir ezme sırası yoktur. Yerleşik bir bağlayıcının yerine başkasını koymak için builtinPlugins: false verip istediğiniz kümeyi kaydedin ya da eklentinize kendi type değerini verin.
Eklenti kuralları
Bir bağlayıcı birinin ajanının içinde, onun kimlik bilgileriyle çalışır. Kurallar kısadır ve yerleşik her eklenti bunlara uyar:
createiçinde ağ yok.createSafrançevrimdışı çalışabilmeli,safran profile checkde ağa ihtiyaç duymamalıdır. İstemcileri tembel kurun.- Gizli değerleri yalnızca
ctx.secret/ctx.optionalSecretile okuyun. Aslaprocess.envile değil: çağıran kendienveşlemesini vermiş olabilir ve değişkenin adını taşıyanAUTH_MISSINGyalnızca bağlamdan gelir. - Global
fetchyerinectx.fetchkullanın. Aksi hâlde testler araya giremez ve çağıranın vekil sunucusu atlanır. - Bir jetonu asla günlüğe yazmayın, asla fırlatmayın. İletide, ipucunda,
detailsiçinde veya bir günlük alanında yer almasın. Kimlik bilgilerini URL'lere koymayın. - Salt okunur. Bir Safran bağlayıcısı okuduğu sistemde asla bir şey oluşturmaz, düzenlemez veya silmez.
- Satıcı hatalarını HTTP istemcisi üzerinden eşleyin; istemcinin göremediği durumlar için (200 yanıtının içindeki hata, beklenmedik biçimde bir gövde) doğru kodla
SafranErrorfırlatın. - Seçenek alan her metotta
signaldeğerine uyun. - Sayfalama kurallarını uygulayın: sınırlar için
resolveLimit, opak imleçler, verinin sonu olaraknextCursoralanının yokluğu. Bkz. sayfalama. - Tarafsız yapılar döndürün. Metin için Markdown, tarihler için ISO 8601,
todo/in_progress/donedeğerlerine eşlenmişstatusCategory, satıcıya özgü fazlalıklar için okunabilir anahtarlarlaTicket.fields.
Bir bağlayıcıyı gerçek servise yöneltmeden önce mockFetch ile kayıtlı yanıtlara karşı test edin.
Sık yapılan hatalar
| Belirti | Neden |
|---|---|
PLUGIN_CONFIG_INVALID: … Unrecognized key: "projects" | projects alanını bildirmeyen katı bir iş takip şeması (ya da include / exclude içermeyen bir kod barındırıcı şeması). Profil bu alanları her girişe ekler. |
INTERNAL: … lists the capability … but does not implement | capabilities ile metotlar tutarsız. |
INVALID_INPUT: "…" could belong to several trackers | matchTicketRef kendisine ait olmayan anahtarları sahipleniyor. Onu bildirilen projects ile sınırlayın. |
INVALID_INPUT: … is registered more than once | Eklenti hem profilin plugins: listesinden hem plugins seçeneğiyle yükleniyor ya da type değeri bir yerleşiğinkiyle aynı. |
İlk kullanım yerine kurulumda AUTH_MISSING | Eklenti ctx.secret çağrısını create içinde yapıyor. İlk istek yapılırken okuyun. |
PLUGIN_NOT_FOUND: Could not load plugin module | Yol profil dosyasına göre değil ya da modül bulunduğu yerden @safran/kit paketini çözemiyor. |