@aidenhq/sdk 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +5 -4
  2. package/dist/src/agent-paused.d.ts +7 -0
  3. package/dist/src/agent-paused.js +4 -0
  4. package/dist/src/attribution.d.ts +16 -0
  5. package/dist/src/attribution.js +21 -0
  6. package/dist/src/box-bundle.d.ts +9 -0
  7. package/dist/src/box-bundle.js +59 -0
  8. package/dist/src/caller.js +2 -1
  9. package/dist/src/checks.d.ts +101 -0
  10. package/dist/src/checks.js +151 -0
  11. package/dist/src/churn.d.ts +46 -0
  12. package/dist/src/churn.js +177 -0
  13. package/dist/src/closed-event.d.ts +36 -0
  14. package/dist/src/closed-event.js +17 -0
  15. package/dist/src/engine-io.d.ts +2 -0
  16. package/dist/src/engine-io.js +13 -8
  17. package/dist/src/executor.d.ts +46 -3
  18. package/dist/src/executor.js +23 -13
  19. package/dist/src/fence.d.ts +12 -0
  20. package/dist/src/fence.js +24 -1
  21. package/dist/src/for-others.d.ts +3 -0
  22. package/dist/src/for-others.js +7 -0
  23. package/dist/src/instance-details.d.ts +10 -0
  24. package/dist/src/instance-details.js +63 -0
  25. package/dist/src/instance-paths.d.ts +3 -0
  26. package/dist/src/instance-paths.js +7 -0
  27. package/dist/src/judge.d.ts +65 -0
  28. package/dist/src/judge.js +71 -0
  29. package/dist/src/kernel-client.d.ts +45 -0
  30. package/dist/src/kernel-client.js +103 -0
  31. package/dist/src/kit.js +19 -4
  32. package/dist/src/maintained-repos.d.ts +58 -0
  33. package/dist/src/maintained-repos.js +136 -0
  34. package/dist/src/model-text.d.ts +29 -0
  35. package/dist/src/model-text.js +361 -0
  36. package/dist/src/owner-day.d.ts +12 -0
  37. package/dist/src/owner-day.js +39 -0
  38. package/dist/src/paperclip.d.ts +34 -0
  39. package/dist/src/paperclip.js +64 -0
  40. package/dist/src/pass-rule.d.ts +10 -0
  41. package/dist/src/pass-rule.js +24 -0
  42. package/dist/src/pin-owner.d.ts +2 -0
  43. package/dist/src/pin-owner.js +1 -0
  44. package/dist/src/progress.js +7 -2
  45. package/dist/src/provider.d.ts +83 -0
  46. package/dist/src/provider.js +31 -0
  47. package/dist/src/quality.d.ts +74 -0
  48. package/dist/src/quality.js +131 -0
  49. package/dist/src/repeat.d.ts +19 -0
  50. package/dist/src/repeat.js +38 -0
  51. package/dist/src/responses.d.ts +64 -0
  52. package/dist/src/responses.js +198 -0
  53. package/dist/src/reviewer.d.ts +79 -34
  54. package/dist/src/reviewer.js +198 -22
  55. package/dist/src/source-store.d.ts +13 -3
  56. package/dist/src/source-store.js +12 -7
  57. package/dist/src/task-state-types.d.ts +77 -0
  58. package/dist/src/task-state-types.js +4 -0
  59. package/dist/src/tiers.d.ts +88 -0
  60. package/dist/src/tiers.js +156 -0
  61. package/dist/src/tools-client.d.ts +60 -0
  62. package/dist/src/tools-client.js +192 -0
  63. package/dist/src/types.d.ts +28 -2
  64. package/dist/src/vendor/needs.d.ts +35 -0
  65. package/dist/src/vendor/needs.js +43 -0
  66. package/dist/src/vendor/oauth.d.ts +82 -2
  67. package/dist/src/vendor/oauth.js +282 -32
  68. package/dist/src/vendor/proxy.d.ts +33 -4
  69. package/dist/src/vendor/proxy.js +377 -49
  70. package/package.json +13 -11
@@ -0,0 +1,83 @@
1
+ /** What a failed model call means, whatever vendor said it. */
2
+ export type ErrorKind = "quota" | "auth" | "ineligible" | "unsupported" | "unavailable";
3
+ export declare class ProviderError extends Error {
4
+ kind: ErrorKind;
5
+ status: number;
6
+ resetAt?: string;
7
+ param?: string;
8
+ /** What the vendor already billed before this refusal (a billed attempt that failed, then a repair the limit cut off): the gateway
9
+ * settles a classified error at it, so the spend reaches the ledger even though the call itself is refused. */
10
+ usage?: Usage;
11
+ constructor(kind: ErrorKind, message: string, o?: {
12
+ status?: number;
13
+ resetAt?: string;
14
+ param?: string;
15
+ usage?: Usage;
16
+ });
17
+ }
18
+ /** The status the gateway answers a kind with. */
19
+ export declare const STATUS: Record<ErrorKind, number>;
20
+ /** What one call used: tokens (input without the cached part), and what it cost when the vendor says. */
21
+ export type Usage = {
22
+ input: number;
23
+ cached: number;
24
+ output: number;
25
+ costUsd?: number;
26
+ model: string;
27
+ };
28
+ export declare const ROLES: readonly ["default", "checker", "advisor", "chat"];
29
+ export type Role = (typeof ROLES)[number];
30
+ /** A model id a caller sends instead of a concrete one: the active provider's pick for that role. */
31
+ export declare const ROLE_ID: RegExp;
32
+ export type Pick = {
33
+ model: string;
34
+ effort: string;
35
+ };
36
+ /** A provider's picks: default (agents, chat), checker (grader, reviewer), advisor; chat (the fast lane) is default's when absent. */
37
+ export type Picks = Record<"default" | "checker" | "advisor", Pick> & {
38
+ chat?: Pick;
39
+ };
40
+ export type ProviderState = {
41
+ provider: string;
42
+ account?: string;
43
+ picks: Record<string, Picks>;
44
+ privacy_ack?: string;
45
+ /** When the model step finished: the provider was signed in and its probe passed. Latched: a quota stop or an expired sign-in never clears it. */
46
+ ready?: string;
47
+ paused?: {
48
+ kind: "quota" | "auth" | "switch";
49
+ until?: string;
50
+ at: string;
51
+ };
52
+ };
53
+ /** Which engine conversation a resumable session belongs to: one from another provider, account or engine never resumes. */
54
+ export declare const sessionKey: (provider: string, account: string | undefined, engine: string) => string;
55
+ /** A model the provider lists: USD per million tokens (an estimate on a plan), `created` in unix seconds, `context` and `output` in tokens. */
56
+ export type CatalogModel = {
57
+ id: string;
58
+ name: string;
59
+ provider: string;
60
+ created: number;
61
+ context: number;
62
+ output: number;
63
+ in: number;
64
+ cached_in: number | null;
65
+ out: number;
66
+ tools: boolean;
67
+ reasoning: boolean;
68
+ };
69
+ /** A model's prices for a reservation: USD per million tokens, and the output ceiling. */
70
+ export type Price = {
71
+ in: number;
72
+ cached_in: number;
73
+ out: number;
74
+ max_output: number;
75
+ };
76
+ export type PriceLookup = {
77
+ prices: Price[];
78
+ } | {
79
+ missing: string[];
80
+ } | {
81
+ unavailable: true;
82
+ };
83
+ export type Route = "responses" | "chat/completions" | "messages" | "embeddings";
@@ -0,0 +1,31 @@
1
+ // The model provider's shared words: the instance's one provider (data/kernel/provider.json), the roles a caller names
2
+ // instead of a model id (`role:default|checker|advisor|chat`), what one call used, and the normalised errors every adapter
3
+ // and the Responses reader (responses.ts) speak; a vendor's error code becomes a kind in responses.ts (errorKind). Copied
4
+ // (scripts/sync-shared.ts) beside responses.ts wherever that goes. It imports nothing, so every package's build takes it.
5
+ export class ProviderError extends Error {
6
+ kind;
7
+ status;
8
+ resetAt;
9
+ param;
10
+ /** What the vendor already billed before this refusal (a billed attempt that failed, then a repair the limit cut off): the gateway
11
+ * settles a classified error at it, so the spend reaches the ledger even though the call itself is refused. */
12
+ usage;
13
+ constructor(kind, message, o = {}) {
14
+ super(message);
15
+ this.kind = kind;
16
+ this.status = o.status ?? STATUS[kind];
17
+ if (o.resetAt)
18
+ this.resetAt = o.resetAt;
19
+ if (o.param)
20
+ this.param = o.param;
21
+ if (o.usage)
22
+ this.usage = o.usage;
23
+ }
24
+ }
25
+ /** The status the gateway answers a kind with. */
26
+ export const STATUS = { quota: 429, auth: 403, ineligible: 403, unsupported: 400, unavailable: 503 };
27
+ export const ROLES = ["default", "checker", "advisor", "chat"];
28
+ /** A model id a caller sends instead of a concrete one: the active provider's pick for that role. */
29
+ export const ROLE_ID = /^role:(default|checker|advisor|chat)$/;
30
+ /** Which engine conversation a resumable session belongs to: one from another provider, account or engine never resumes. */
31
+ export const sessionKey = (provider, account, engine) => `${provider}:${account ?? ""}:${engine}`;
@@ -0,0 +1,74 @@
1
+ export declare const TIERS: readonly ["ran", "reviewer", "panel", "owner"];
2
+ export type Tier = (typeof TIERS)[number];
3
+ /** An approval record, as little as this needs (the kernel's row or the board's approval, mapped). `at`: when it ran. */
4
+ export type Row = {
5
+ id: string;
6
+ kind: string;
7
+ args: unknown;
8
+ tier: number;
9
+ panel: boolean;
10
+ by: string | null;
11
+ state: string;
12
+ at: string;
13
+ outcome?: string | null;
14
+ identifier?: string | null;
15
+ };
16
+ /** A revert PR or an incident as text: `repo` and `number` are its own (a bare #n in it names this repo; its own number is skipped). */
17
+ export type Text = {
18
+ id: string;
19
+ title: string;
20
+ body?: string;
21
+ url?: string;
22
+ repo?: string;
23
+ number?: number;
24
+ };
25
+ export type Change = {
26
+ id: string;
27
+ tier: Tier;
28
+ at: string;
29
+ keys: string[];
30
+ link: string;
31
+ label: string;
32
+ };
33
+ /** Who approved it: the reviewer (alone or with the panel's second), the owner, or nobody (it ran at once); undefined when no one did. */
34
+ export declare function tierOf(r: Pick<Row, "tier" | "panel" | "by">): Tier | undefined;
35
+ /** Agent changes that landed (merge, a PR that merges, an apply), one per PR or apply commit however many records carried it. */
36
+ export declare function changesFrom(rows: Row[]): Change[];
37
+ /** The one change a text names, or why not: `unknown` (ambiguous or no usable reference) or `none` (names no agent change). */
38
+ export declare function link(t: Text, changes: Change[]): {
39
+ change: Change;
40
+ } | "unknown" | "none";
41
+ /** A revert is titled Revert… (a revert of a revert puts the original back and is not one). */
42
+ export declare const isRevert: (t: Text) => boolean;
43
+ /** The PRs the fleet opened itself (their title and body are in the record): a revert among them is found without GitHub. */
44
+ export declare const revertsFrom: (rows: Row[]) => Text[];
45
+ /** Failed or rolled-back app deploys as incident text: the deployed commit and what the executor said. */
46
+ export declare const deployIncidents: (rows: Row[]) => Text[];
47
+ export type Count = {
48
+ changes: number;
49
+ reverted: number;
50
+ incidents: number;
51
+ };
52
+ export type Report = {
53
+ windows: {
54
+ days: number;
55
+ tiers: Record<Tier, Count>;
56
+ }[];
57
+ /** The reverted changes of the longest window, with the revert that names them. */
58
+ reverted: {
59
+ change: string;
60
+ tier: Tier;
61
+ link: string;
62
+ revert: string;
63
+ }[];
64
+ /** Reverts that could not be tied to one change (ambiguous or no reference), by their ids. */
65
+ unknown: string[];
66
+ };
67
+ export declare function report(rows: Row[], { reverts, incidents }: {
68
+ reverts?: Text[];
69
+ incidents?: Text[];
70
+ }, now?: number, days?: number[]): Report;
71
+ /** The table: per tier and window, changes, reverted (count and %), incidents; then the reverted ones and the unknown. */
72
+ export declare function render(r: Report): string;
73
+ /** One line for the owner's weekly digest: the revert rate by approver over the first window. */
74
+ export declare function oneLine(r: Report): string;
@@ -0,0 +1,131 @@
1
+ // Quality per approval tier: how often an agent change that landed was later reverted or tied to an incident, by who approved
2
+ // it (ran at once, the AI reviewer alone, the reviewer panel, the owner). Pure: records and GitHub text in, a report out, so the
3
+ // board's fleet summary, the report CLI (scripts/quality.ts) and the kernel's flow DORA (flow.ts) share it.
4
+ // A revert or incident is linked to its original only by a PR number or a commit sha it names: exactly one agent change named
5
+ // links it; several, a bare number that names no repository, or no reference at all is `unknown`, never a guess.
6
+ export const TIERS = ["ran", "reviewer", "panel", "owner"];
7
+ // A code host's kinds (github.merge, codehost-local.pr) are bare actions too, as kernel review-loop.ts actionOf reads them.
8
+ const action = (kind) => kind.replace(/^(runner|kernel|github|codehost-local)\./, "");
9
+ const repoKey = (s) => s.toLowerCase().replace(/\.git$/, "");
10
+ /** Who approved it: the reviewer (alone or with the panel's second), the owner, or nobody (it ran at once); undefined when no one did. */
11
+ export function tierOf(r) {
12
+ const by = r.by ?? "";
13
+ if (by.startsWith("reviewer:"))
14
+ return r.panel || by.includes("+") ? "panel" : "reviewer";
15
+ if (r.tier === 0 || by.startsWith("kernel"))
16
+ return "ran";
17
+ return by && !by.startsWith("stale:") ? "owner" : undefined;
18
+ }
19
+ // A GitHub PR's URL, or a change request's on this server (codehost:<org>/<name>/change/<n>): both key as <repo>#<n>.
20
+ const PR_URL = /(?:github\.com\/([\w.-]+\/[\w.-]+)\/pull|codehost:([\w.-]+\/[\w.-]+)\/change)\/(\d+)/gi;
21
+ /** Where a PR key links to: GitHub's page, or nowhere for this server's change requests (no web page; the board shows them). */
22
+ const prLink = (pr) => (pr.startsWith("record:") || pr.startsWith("local/") ? "" : `https://github.com/${pr.replace("#", "/pull/")}`);
23
+ const SHA = /\b[0-9a-f]{7,40}\b/g;
24
+ /** Agent changes that landed (merge, a PR that merges, an apply), one per PR or apply commit however many records carried it. */
25
+ export function changesFrom(rows) {
26
+ const out = new Map();
27
+ for (const r of [...rows].sort((a, b) => a.at.localeCompare(b.at))) {
28
+ const a = action(r.kind);
29
+ const args = (r.args ?? {});
30
+ const tier = tierOf(r);
31
+ if (r.state !== "done" || !tier || !(a === "merge" || (a === "pr" && args.merge === true) || a === "apply"))
32
+ continue;
33
+ const prs = [...(args.prs ?? []).map((p) => (p.number ? `${repoKey(p.repo)}#${p.number}` : "")), ...[...String(r.outcome ?? "").matchAll(PR_URL)].map((m) => `${repoKey((m[1] ?? m[2]))}#${m[3]}`)].filter(Boolean);
34
+ const shas = [args.sha, ...(args.only ?? []).map((b) => b.sha), ...(args.prs ?? []).map((p) => p.head)].filter((s) => typeof s === "string").map((s) => s.toLowerCase());
35
+ for (const pr of prs.length ? [...new Set(prs)] : [`record:${r.id}`]) {
36
+ const prev = out.get(pr);
37
+ out.set(pr, { id: pr, tier, at: r.at, keys: [...new Set([...(prev?.keys ?? []), ...(pr.startsWith("record:") ? [] : [pr]), ...shas])], link: prLink(pr), label: r.identifier ?? pr });
38
+ }
39
+ }
40
+ return [...out.values()];
41
+ }
42
+ /** The PRs and commits a text names; `loose`: it names a bare number outside any repository, or nothing at all. */
43
+ function refs(t) {
44
+ const text = `${t.title}\n${t.body ?? ""}\n${t.url ?? ""}`;
45
+ const prs = new Set([...text.matchAll(PR_URL)].map((m) => `${repoKey((m[1] ?? m[2]))}#${m[3]}`));
46
+ for (const m of text.matchAll(/([\w.-]+\/[\w.-]+)#(\d+)/g))
47
+ prs.add(`${repoKey(m[1])}#${m[2]}`);
48
+ let bare = false;
49
+ for (const m of text.replace(PR_URL, " ").replace(/[\w.-]+\/[\w.-]+#\d+/g, " ").matchAll(/(?:^|[^\w&])#(\d+)\b/g)) {
50
+ if (t.repo)
51
+ prs.add(`${repoKey(t.repo)}#${m[1]}`);
52
+ else
53
+ bare = true;
54
+ }
55
+ if (t.repo && t.number)
56
+ prs.delete(`${repoKey(t.repo)}#${t.number}`);
57
+ const shas = [...text.toLowerCase().matchAll(SHA)].map((m) => m[0]).filter((s) => /\d/.test(s));
58
+ return { prs: [...prs], shas, loose: bare || (!prs.size && !shas.length) };
59
+ }
60
+ /** The one change a text names, or why not: `unknown` (ambiguous or no usable reference) or `none` (names no agent change). */
61
+ export function link(t, changes) {
62
+ const r = refs(t);
63
+ const hit = changes.filter((c) => r.prs.some((p) => c.keys.includes(p)) || r.shas.some((s) => c.keys.some((k) => /^[0-9a-f]{7,40}$/.test(k) && k.startsWith(s))));
64
+ if (hit.length === 1 && !r.loose)
65
+ return { change: hit[0] };
66
+ return hit.length > 1 || r.loose ? "unknown" : "none";
67
+ }
68
+ /** A revert is titled Revert… (a revert of a revert puts the original back and is not one). */
69
+ export const isRevert = (t) => /^revert\b/i.test(t.title.trim()) && !/^revert\s+"?revert\b/i.test(t.title.trim());
70
+ /** The PRs the fleet opened itself (their title and body are in the record): a revert among them is found without GitHub. */
71
+ export const revertsFrom = (rows) => rows
72
+ .filter((r) => r.state === "done" && action(r.kind) === "pr")
73
+ .map((r) => { const a = (r.args ?? {}); return { id: r.id, title: a.text?.title ?? "", body: a.text?.body, repo: a.only?.[0]?.repo }; })
74
+ .filter((t) => t.title);
75
+ /** Failed or rolled-back app deploys as incident text: the deployed commit and what the executor said. */
76
+ export const deployIncidents = (rows) => rows
77
+ .filter((r) => /(^|\.)deploy(_app)?$/.test(r.kind) && (r.state === "failed" || /rolled back/i.test(r.outcome ?? "")))
78
+ .map((r) => ({ id: r.id, title: `deploy ${r.args?.name ?? ""} failed`, body: `${r.args?.sha ?? ""} ${r.outcome ?? ""}` }));
79
+ export function report(rows, { reverts = [], incidents = [] }, now = Date.now(), days = [7, 30]) {
80
+ const changes = changesFrom(rows);
81
+ const reverted = new Map();
82
+ const unknown = [];
83
+ for (const t of [...reverts, ...revertsFrom(rows)].filter(isRevert)) {
84
+ const l = link(t, changes);
85
+ if (l === "unknown")
86
+ unknown.push(t.url ?? t.id);
87
+ else if (l !== "none" && !reverted.has(l.change.id))
88
+ reverted.set(l.change.id, t);
89
+ }
90
+ const hit = new Set();
91
+ for (const t of [...incidents, ...deployIncidents(rows)]) {
92
+ const l = link(t, changes);
93
+ if (l !== "unknown" && l !== "none")
94
+ hit.add(l.change.id);
95
+ }
96
+ const windows = days.map((d) => {
97
+ const tiers = Object.fromEntries(TIERS.map((t) => [t, { changes: 0, reverted: 0, incidents: 0 }]));
98
+ for (const c of changes.filter((c) => Date.parse(c.at) >= now - d * 864e5)) {
99
+ tiers[c.tier].changes++;
100
+ if (reverted.has(c.id))
101
+ tiers[c.tier].reverted++;
102
+ if (hit.has(c.id))
103
+ tiers[c.tier].incidents++;
104
+ }
105
+ return { days: d, tiers };
106
+ });
107
+ const horizon = now - Math.max(...days) * 864e5;
108
+ return {
109
+ windows,
110
+ reverted: changes.filter((c) => reverted.has(c.id) && Date.parse(c.at) >= horizon).map((c) => ({ change: c.label, tier: c.tier, link: c.link, revert: reverted.get(c.id).url ?? reverted.get(c.id).id })),
111
+ unknown: [...new Set(unknown)],
112
+ };
113
+ }
114
+ const pct = (c) => (c.changes ? `${Math.round((100 * c.reverted) / c.changes)}%` : "-");
115
+ /** The table: per tier and window, changes, reverted (count and %), incidents; then the reverted ones and the unknown. */
116
+ export function render(r) {
117
+ const lines = ["tier " + r.windows.map((w) => `${`${w.days}d`.padEnd(24)}`).join(""), " " + r.windows.map(() => "changes reverted incid. ").join("")];
118
+ for (const t of TIERS)
119
+ lines.push(t.padEnd(11) + r.windows.map((w) => `${String(w.tiers[t].changes).padEnd(9)}${`${w.tiers[t].reverted} (${pct(w.tiers[t])})`.padEnd(10)}${String(w.tiers[t].incidents).padEnd(8)}`).join(""));
120
+ if (r.reverted.length)
121
+ lines.push("", "Reverted:", ...r.reverted.map((x) => ` ${x.change} [${x.tier}] ${x.link} <- ${x.revert}`));
122
+ if (r.unknown.length)
123
+ lines.push("", `Unknown (a revert that names no single agent change): ${r.unknown.join(", ")}`);
124
+ return lines.join("\n");
125
+ }
126
+ /** One line for the owner's weekly digest: the revert rate by approver over the first window. */
127
+ export function oneLine(r) {
128
+ const w = r.windows[0];
129
+ const parts = TIERS.filter((t) => w.tiers[t].changes).map((t) => `${t} ${w.tiers[t].reverted}/${w.tiers[t].changes} (${pct(w.tiers[t])})`);
130
+ return `Reverted by approver, ${w.days}d: ${parts.join(", ") || "no agent changes landed"}${r.unknown.length ? `; ${r.unknown.length} revert(s) not tied to one change` : ""}`;
131
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The short answer for a read the same run made before whose result has not changed, else undefined. Always call it with the
3
+ * fresh result: nothing is served from a cache. `full` (the caller asks again, e.g. after its context was compacted) and a
4
+ * caller with no run both get the whole result.
5
+ */
6
+ export declare function unchangedSince(run: string | undefined, key: string, result: unknown, full?: boolean): {
7
+ unchanged: true;
8
+ since: string;
9
+ note: string;
10
+ } | undefined;
11
+ /** Rows from `offset` on, as many as fit `max` characters (whole rows, at least one, at most `limit`), and a note on how to read on. */
12
+ export declare function pageRows<T>(rows: T[], { offset, limit, max }: {
13
+ offset?: number;
14
+ limit?: number;
15
+ max?: number;
16
+ }): {
17
+ rows: T[];
18
+ more?: string;
19
+ };
@@ -0,0 +1,38 @@
1
+ // What a tool answers a run that read the same thing again, and a page of rows that fits a size: one place, so every read tool
2
+ // that long runs repeat (a task's comments, the fleet's status, the warehouse) keeps its prompt small the same way.
3
+ // First-party modules hold byte-identical copies (scripts/sync-shared.ts: edit this one and run it).
4
+ import { createHash } from "node:crypto";
5
+ /** The newest reads per run (the caller's `run`: a kernel job's id), by tool and arguments: what was read, and when. */
6
+ const reads = new Map();
7
+ const MAX_READS = 2000;
8
+ /**
9
+ * The short answer for a read the same run made before whose result has not changed, else undefined. Always call it with the
10
+ * fresh result: nothing is served from a cache. `full` (the caller asks again, e.g. after its context was compacted) and a
11
+ * caller with no run both get the whole result.
12
+ */
13
+ export function unchangedSince(run, key, result, full) {
14
+ if (!run)
15
+ return undefined;
16
+ const k = `${run}\0${key}`, hash = createHash("sha256").update(JSON.stringify(result)).digest("hex").slice(0, 16);
17
+ const before = reads.get(k), same = before?.hash === hash;
18
+ reads.delete(k);
19
+ reads.set(k, { hash, at: same ? before.at : new Date().toISOString() });
20
+ while (reads.size > MAX_READS)
21
+ reads.delete(reads.keys().next().value);
22
+ if (!same || full)
23
+ return undefined;
24
+ return { unchanged: true, since: before.at, note: `Unchanged since ${before.at} (your earlier result in this run still holds). Pass \`full: true\` to read it again.` };
25
+ }
26
+ /** Rows from `offset` on, as many as fit `max` characters (whole rows, at least one, at most `limit`), and a note on how to read on. */
27
+ export function pageRows(rows, { offset = 0, limit = Infinity, max = 4000 }) {
28
+ const out = [];
29
+ let size = 0;
30
+ for (let i = offset; i < rows.length && out.length < limit; i++) {
31
+ size += JSON.stringify(rows[i]).length;
32
+ if (out.length && size > max)
33
+ break;
34
+ out.push(rows[i]);
35
+ }
36
+ const next = offset + out.length;
37
+ return { rows: out, ...(next < rows.length ? { more: `${rows.length - next} more: call again with cursor ${next}` } : {}) };
38
+ }
@@ -0,0 +1,64 @@
1
+ import type { ErrorKind, Usage } from "./provider.js";
2
+ /**
3
+ * A vendor's error code (or the gateway's own `type`, which is the kind itself) → its kind; undefined for any other code.
4
+ * The one table: adapters classify with it, the Responses reader types errors with it.
5
+ */
6
+ export declare function errorKind(code: string): ErrorKind | undefined;
7
+ /** An input or output item, as the Responses format has it (reasoning items kept as they came). */
8
+ export type Item = Record<string, unknown>;
9
+ export type FnTool = {
10
+ name: string;
11
+ description: string;
12
+ parameters: object;
13
+ run(a: Record<string, unknown>): string | Promise<string>;
14
+ };
15
+ export type RespondOpts = {
16
+ /** The API base (`…/api/v1`): the call goes to `<url>/responses`. */
17
+ url: string;
18
+ headers: Record<string, string>;
19
+ model: string;
20
+ effort?: string;
21
+ instructions?: string;
22
+ input: Item[];
23
+ tools?: FnTool[];
24
+ schema?: {
25
+ name: string;
26
+ schema: object;
27
+ };
28
+ images?: string[];
29
+ maxOutputTokens?: number;
30
+ signal?: AbortSignal;
31
+ timeoutMs?: number;
32
+ fetchFn?: typeof fetch;
33
+ /** Only for callers that go straight to OpenRouter (the evals): `unavailable`, 5xx and a plain 429 rate limit are tried again, never a typed `quota`. */
34
+ retry?: boolean;
35
+ onText?(text: string): void;
36
+ };
37
+ export type RespondResult = {
38
+ text: string;
39
+ calls: {
40
+ id: string;
41
+ name: string;
42
+ arguments: string;
43
+ }[];
44
+ output: Item[];
45
+ usage: Usage;
46
+ model: string;
47
+ /** Why the provider cut the answer off (its output limit, a content filter): the text is partial, never a finished answer. */
48
+ incomplete?: string;
49
+ };
50
+ export declare class ModelError extends Error {
51
+ kind: ErrorKind | "cap" | "other";
52
+ status: number;
53
+ /** The request field the provider blamed, when it named one (a rejected shared field fails every caller, not only this input). */
54
+ param?: string;
55
+ constructor(kind: ModelError["kind"], status: number, message: string, param?: string);
56
+ }
57
+ /** One model call: streamed, `store: false`, the whole history in `input`. */
58
+ export declare function respond(o: RespondOpts): Promise<RespondResult>;
59
+ /** Calls the model, runs the function tools it asks for, and calls it again with their results, until it answers without one. */
60
+ export declare function respondLoop(o: RespondOpts & {
61
+ maxTurns: number;
62
+ }): Promise<RespondResult & {
63
+ turns: number;
64
+ }>;
@@ -0,0 +1,198 @@
1
+ const ERROR_KINDS = ["quota", "auth", "ineligible", "unsupported", "unavailable"];
2
+ /**
3
+ * A vendor's error code (or the gateway's own `type`, which is the kind itself) → its kind; undefined for any other code.
4
+ * The one table: adapters classify with it, the Responses reader types errors with it.
5
+ */
6
+ export function errorKind(code) {
7
+ if (ERROR_KINDS.includes(code))
8
+ return code;
9
+ return VENDOR_CODES[code];
10
+ }
11
+ const VENDOR_CODES = {
12
+ subscription_sharing_usage_limit_exceeded: "quota",
13
+ subscription_sharing_user_not_eligible: "ineligible",
14
+ subscription_sharing_unsupported_capability: "unsupported",
15
+ subscription_sharing_usage_unavailable: "unavailable",
16
+ subscription_sharing_user_unavailable: "unavailable",
17
+ subscription_sharing_invalid_user: "auth",
18
+ };
19
+ export class ModelError extends Error {
20
+ kind;
21
+ status;
22
+ /** The request field the provider blamed, when it named one (a rejected shared field fails every caller, not only this input). */
23
+ param;
24
+ constructor(kind, status, message, param) {
25
+ super(message);
26
+ this.kind = kind;
27
+ this.status = status;
28
+ if (param)
29
+ this.param = param;
30
+ }
31
+ }
32
+ const RETRY_MS = [1000, 3000, 9000];
33
+ /** A gateway or vendor error body (`{error: {type, code, message}}`), or an SSE error event → its ModelError. */
34
+ function errorOf(status, j, fallback) {
35
+ const e = (j && typeof j === "object" ? (j.error ?? j.response?.error ?? j) : {});
36
+ // A streamed failure arrives on an HTTP 200: its own error code (or type) names an overload, rate limit or vendor fault,
37
+ // which is `unavailable`, so `retry` tries it like a 5xx. A definite answer (a refusal, a bad request) stays `other`.
38
+ const TRANSIENT = new Set(["server_error", "api_error", "overloaded_error", "rate_limit_error", "rate_limit_exceeded", "timeout"]);
39
+ const codes = [e.type, e.code].map((c) => String(c ?? ""));
40
+ if (status < 400 && codes.some((c) => TRANSIENT.has(c)))
41
+ return new ModelError("unavailable", status, String(e.message ?? fallback).slice(0, 500));
42
+ const kind = codes.map(errorKind).find(Boolean) ?? (codes.includes("cap_reached") ? "cap" : status >= 500 ? "unavailable" : "other");
43
+ return new ModelError(kind, status, String(e.message ?? fallback).slice(0, 500), typeof e.param === "string" ? e.param : undefined);
44
+ }
45
+ function body(o) {
46
+ const input = o.images?.length ? [...o.input, { role: "user", content: o.images.map((image_url) => ({ type: "input_image", image_url })) }] : o.input;
47
+ return {
48
+ // Nothing is stored upstream, so a reasoning item comes back encrypted for the next turn to send.
49
+ model: o.model, stream: true, store: false, include: ["reasoning.encrypted_content"], input,
50
+ ...(o.instructions ? { instructions: o.instructions } : {}),
51
+ ...(o.effort ? { reasoning: { effort: o.effort } } : {}),
52
+ ...(o.tools?.length ? { tools: o.tools.map((t) => ({ type: "function", name: t.name, description: t.description, parameters: t.parameters })) } : {}),
53
+ ...(o.schema ? { text: { format: { type: "json_schema", name: o.schema.name, schema: o.schema.schema, strict: true } } } : {}),
54
+ ...(o.maxOutputTokens ? { max_output_tokens: o.maxOutputTokens } : {}),
55
+ };
56
+ }
57
+ async function once(o) {
58
+ const signal = AbortSignal.any([...(o.signal ? [o.signal] : []), AbortSignal.timeout(o.timeoutMs ?? 600_000)]);
59
+ const res = await (o.fetchFn ?? fetch)(`${o.url.replace(/\/$/, "")}/responses`, { method: "POST", headers: { "content-type": "application/json", accept: "text/event-stream", ...o.headers }, body: JSON.stringify(body(o)), signal });
60
+ if (!res.ok) {
61
+ const text = await res.text().catch(() => "");
62
+ let j;
63
+ try {
64
+ j = JSON.parse(text);
65
+ }
66
+ catch { }
67
+ throw errorOf(res.status, j, `the model call answered ${res.status}`);
68
+ }
69
+ if (!res.body)
70
+ throw new ModelError("unavailable", res.status, "the model call answered without a body");
71
+ let text = "", model = o.model, done = false, incomplete, buf = "";
72
+ const output = [];
73
+ const usage = { input: 0, cached: 0, output: 0, model };
74
+ const event = (data) => {
75
+ if (!data || data === "[DONE]")
76
+ return;
77
+ let j;
78
+ try {
79
+ j = JSON.parse(data);
80
+ }
81
+ catch {
82
+ return;
83
+ }
84
+ if (j.type === "response.output_text.delta" && typeof j.delta === "string") {
85
+ text += j.delta;
86
+ o.onText?.(j.delta);
87
+ return;
88
+ }
89
+ if (j.type === "response.output_item.done" && j.item) {
90
+ output.push(j.item);
91
+ return;
92
+ }
93
+ if (j.type === "error" || j.type === "response.failed" || (j.error && !j.type))
94
+ throw errorOf(res.status, j, "the model call failed");
95
+ if (j.type === "response.completed" || j.type === "response.incomplete") {
96
+ const r = (j.response ?? {});
97
+ if (typeof r.model === "string")
98
+ model = r.model;
99
+ // `response.incomplete` (or a `completed` event whose response says `status: "incomplete"`): the provider stopped short of
100
+ // an answer (an output limit, a filter). The text is partial, so callers must label or retry it, never report it as the answer.
101
+ if (j.type === "response.incomplete" || r.status === "incomplete") {
102
+ const why = r.incomplete_details?.reason;
103
+ incomplete = typeof why === "string" && why ? why : "the answer was cut off";
104
+ }
105
+ // A stream that never sent output_item.done events still carries the whole output here.
106
+ if (!output.length && Array.isArray(r.output))
107
+ output.push(...r.output);
108
+ const u = r.usage ?? {};
109
+ const cached = Number(u.input_tokens_details?.cached_tokens ?? 0) || 0;
110
+ Object.assign(usage, { input: Math.max(0, (Number(u.input_tokens) || 0) - cached), cached, output: Number(u.output_tokens) || 0, model, ...(typeof u.cost === "number" ? { costUsd: u.cost } : {}) });
111
+ done = true;
112
+ }
113
+ };
114
+ const dec = new TextDecoder();
115
+ const reader = res.body.getReader();
116
+ // Read to the response's terminal event (a stream left open after it is not waited on), then let go of the body.
117
+ try {
118
+ for (;;) {
119
+ const r = await reader.read();
120
+ buf += r.done ? dec.decode() : dec.decode(r.value, { stream: true });
121
+ const events = buf.split(/\r?\n\r?\n/);
122
+ buf = r.done ? "" : events.pop();
123
+ for (const ev of events)
124
+ event(ev.split(/\r?\n/).filter((l) => l.startsWith("data:")).map((l) => l.slice(l[5] === " " ? 6 : 5)).join("\n"));
125
+ if (r.done || done)
126
+ break;
127
+ }
128
+ }
129
+ finally {
130
+ await reader.cancel().catch(() => { });
131
+ }
132
+ if (!done)
133
+ throw new ModelError("unavailable", res.status, "the model's stream ended before the response completed");
134
+ if (!text)
135
+ text = output.flatMap((i) => (i.type === "message" && Array.isArray(i.content) ? i.content.filter((c) => c.type === "output_text").map((c) => c.text ?? "") : [])).join("");
136
+ const calls = output.filter((i) => i.type === "function_call").map((i) => ({ id: String(i.call_id ?? i.id ?? ""), name: String(i.name ?? ""), arguments: String(i.arguments ?? "{}") }));
137
+ return { text, calls, output, usage, model, ...(incomplete ? { incomplete } : {}) };
138
+ }
139
+ /** One model call: streamed, `store: false`, the whole history in `input`. */
140
+ export async function respond(o) {
141
+ for (let n = 0;; n++) {
142
+ try {
143
+ return await once(o);
144
+ }
145
+ catch (e) {
146
+ // A ModelError is the model's answer; anything else is the transport's (a reset, a timeout).
147
+ const passing = e instanceof ModelError ? e.kind === "unavailable" || e.status >= 500 || (e.kind === "other" && e.status === 429) : true;
148
+ const again = o.retry && passing && n < RETRY_MS.length && !o.signal?.aborted;
149
+ if (!again)
150
+ throw e;
151
+ await new Promise((r) => setTimeout(r, RETRY_MS[n]));
152
+ }
153
+ }
154
+ }
155
+ /** Calls the model, runs the function tools it asks for, and calls it again with their results, until it answers without one. */
156
+ export async function respondLoop(o) {
157
+ let input = [...o.input];
158
+ const total = { input: 0, cached: 0, output: 0, model: o.model };
159
+ for (let turn = 1;; turn++) {
160
+ const r = await respond({ ...o, input });
161
+ Object.assign(total, { input: total.input + r.usage.input, cached: total.cached + r.usage.cached, output: total.output + r.usage.output, model: r.model });
162
+ if (r.usage.costUsd !== undefined)
163
+ total.costUsd = (total.costUsd ?? 0) + r.usage.costUsd;
164
+ // A cut-off answer ends the loop: its tool calls may be truncated too, and more turns can't un-cut it.
165
+ if (r.incomplete)
166
+ return { ...r, usage: total, turns: turn };
167
+ if (!r.calls.length || !o.tools?.length)
168
+ return { ...r, usage: total, turns: turn };
169
+ if (turn >= o.maxTurns)
170
+ throw new ModelError("other", 200, `max_turns: the model asked for more than ${o.maxTurns} rounds of tool calls`);
171
+ const results = [];
172
+ for (const c of r.calls) {
173
+ const tool = o.tools.find((t) => t.name === c.name);
174
+ let out;
175
+ if (!tool)
176
+ out = `no tool ${c.name}`;
177
+ else {
178
+ let args = {};
179
+ try {
180
+ args = JSON.parse(c.arguments || "{}");
181
+ }
182
+ catch {
183
+ out = "the arguments weren't JSON";
184
+ results.push({ type: "function_call_output", call_id: c.id, output: out });
185
+ continue;
186
+ }
187
+ try {
188
+ out = await tool.run(args);
189
+ }
190
+ catch (e) {
191
+ out = `the tool failed: ${e.message}`;
192
+ }
193
+ }
194
+ results.push({ type: "function_call_output", call_id: c.id, output: out });
195
+ }
196
+ input = [...input, ...r.output, ...results];
197
+ }
198
+ }