@aidenhq/sdk 0.3.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 +54 -20
  28. package/dist/src/judge.js +57 -75
  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 +31 -6
  69. package/dist/src/vendor/proxy.js +376 -49
  70. package/package.json +11 -10
package/dist/src/judge.js CHANGED
@@ -1,89 +1,71 @@
1
1
  // The judges' shared pieces (design §4.4 "Judge"): the AI reviewer and the grader keep their own contracts, prompts and
2
- // credentials, and share the models they may use, the cross-family choice and the one schema-bound, tool-less model call.
2
+ // credentials, and share the models they may use (the provider's roles, read once per review), the cross-family choice and
3
+ // the one schema-bound model call (with the caller's read-only tools, when it gives any), spoken over the Responses reader.
3
4
  //
4
5
  // Canonical copy: kernel/sdk/src/judge.ts. The reviewer and grading services hold byte-identical copies at
5
- // src/aidenhq-sdk/judge.ts: edit this one, then run `node scripts/sync-shared.mjs`.
6
- // GPT Luna at medium, then DeepSeek Flash at high (the owner's pick, 2026-11-13; the reviewer eval scores it). GLM Flash at high
7
- // is the owner's checker model (the reviewer's second opinion).
8
- export const LUNA = "~openai/gpt-luna-latest";
9
- export const DEEPSEEK = "~deepseek/deepseek-flash-latest";
10
- export const GLM = "~z-ai/glm-flash-latest";
11
- /** Each judge model's reasoning effort. */
12
- export const EFFORT = { [LUNA]: "medium", [DEEPSEEK]: "high", [GLM]: "high" };
6
+ // src/aidenhq-sdk/judge.ts: edit this one, then run `node scripts/sync-shared.ts`.
7
+ import { ModelError, respondLoop } from "./responses.js";
13
8
  /** Output cap, reasoning included: room for high-effort reasoning; Luna allows 128,000. */
14
9
  export const MAX_TOKENS = 100_000;
15
- /** The largest diff a judge reads; the reviewer sends a larger one to the owner as too large. */
10
+ /** The most diff a judge is shown inline; the reviewer's tools read the rest. */
16
11
  export const MAX_DIFF = 150_000;
12
+ /** The most rounds of tool calls one judge call takes; past it the call fails (`max_turns`) and the caller escalates. */
13
+ export const MAX_TURNS = 30;
14
+ /** The provider's roles, from the gateway (once per review). Throws when the gateway doesn't answer: a review that can't name its models can't run. */
15
+ export async function judgeRoles(url, cred, fetchFn = fetch) {
16
+ const res = await fetchFn(`${url.replace(/\/$/, "")}/provider`, { headers: { authorization: `Bearer ${cred}` }, signal: AbortSignal.timeout(30_000) });
17
+ if (!res.ok)
18
+ throw new Error(`the provider's roles: the gateway answered ${res.status}`);
19
+ const j = (await res.json());
20
+ if (!j?.roles || (j.billing !== "metered" && j.billing !== "plan"))
21
+ throw new Error("the provider's roles: the gateway's answer isn't {billing, roles}");
22
+ return { billing: j.billing, roles: j.roles };
23
+ }
24
+ /** A model id's family (the vendor that trained it), as far as the judges tell families apart. */
25
+ const FAMILIES = [["openai", /openai|gpt/i], ["deepseek", /deepseek/i], ["anthropic", /anthropic|claude|opus|sonnet|haiku/i], ["zai", /z-ai|glm/i]];
26
+ // An id outside those is its vendor prefix (`google/gemini-…`), so two models of one vendor are one family.
27
+ const familyOf = (id) => {
28
+ const vendor = id.replace(/^(?:openrouter\/)?~?/, "").split("/");
29
+ return FAMILIES.find(([, re]) => re.test(id))?.[0] ?? (vendor.length > 1 ? vendor[0] : id);
30
+ };
31
+ const ids = (r, ...roles) => [...new Set(roles.flatMap((x) => (r.roles[x]?.model ? [r.roles[x].model] : [])))];
17
32
  /**
18
- * The models to ask, in order: GPT Luna, then DeepSeek Flash, minus the author's own model family (a DeepSeek author, most of
19
- * the fleet, gets Luna only; an OpenAI author gets DeepSeek only; never its own family, not even as the fallback).
20
- */
21
- const FAMILIES = [
22
- [LUNA, /openai|gpt/i],
23
- [DEEPSEEK, /deepseek/i],
24
- ];
25
- export const judgeModels = (authorModel = "") => FAMILIES.filter(([, re]) => !re.test(String(authorModel))).map(([m]) => m);
26
- /**
27
- * A second opinion's models, in order: never the author's family nor the first judge's (GPT Sol, the advisor, is OpenAI like
28
- * Luna, so it can't be the second opinion on Luna's verdict).
33
+ * The models to ask, in order. Metered (OpenRouter): the checker, then the default, minus the author's own model family (a
34
+ * DeepSeek author, most of the fleet, gets the checker only; never its own family, not even as the fallback). The advisor and
35
+ * chat picks follow: the owner may set the checker and the default to one family (the role picks are the owner's), and a review
36
+ * that would otherwise have no model of its own — the kernel then fails open — still gets an independent one. On a plan there
37
+ * is one family: the checker alone, and the verdict says so (`samePlan`).
29
38
  */
30
- const SECOND = [
31
- [GLM, /z-ai|glm/i],
32
- [DEEPSEEK, /deepseek/i],
33
- [LUNA, /openai|gpt/i],
34
- ];
35
- export const secondModels = (authorModel = "", first = "") => SECOND.filter(([, re]) => !re.test(String(authorModel)) && !re.test(String(first))).map(([m]) => m);
36
- const RETRY_STATUS = new Set([429, 500, 502, 503, 504, 524]);
37
- /** Retries for a caller that reaches OpenRouter directly (an eval); through the model gateway, which retries, pass none. */
38
- export const RETRY_DELAYS_MS = [1000, 3000, 9000, 20000];
39
+ export const judgeModels = (r, authorModel = "") => r.billing === "plan" ? ids(r, "checker") : ids(r, "checker", "default", "advisor", "chat").filter((m) => familyOf(m) !== familyOf(String(authorModel)));
40
+ /** True when the judge is the author's own family by construction: a plan has one family. */
41
+ export const samePlan = (r) => r.billing === "plan";
39
42
  /**
40
- * fetch that retries a transient OpenRouter failure (429/5xx "high demand", a reset or timeout) with jittered backoff,
41
- * honouring Retry-After (capped at 20s); a 4xx validation or auth error is returned at once.
43
+ * A second opinion's models, in order: never the author's family nor the first judge's. Metered only (the chat pick, then the
44
+ * default and the checker); a plan has no second family, so none.
42
45
  */
43
- async function fetchRetrying(fetchFn, delays, url, init, timeoutMs) {
44
- for (let n = 0;; n++) {
45
- let res, err;
46
- try {
47
- res = await fetchFn(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
48
- }
49
- catch (e) {
50
- err = e;
51
- }
52
- if (!(err ? true : RETRY_STATUS.has(res.status)) || n >= delays.length) {
53
- if (err)
54
- throw err;
55
- return res;
56
- }
57
- const after = Number(res?.headers?.get("retry-after"));
58
- const wait = Math.min(after > 0 ? after * 1000 : delays[n] * (0.75 + Math.random() / 2), 20_000);
59
- console.error(`openrouter retry ${n + 1}/${delays.length} (${res?.status ?? String(err.message).slice(0, 80)}) in ${Math.round(wait)}ms`);
60
- await res?.body?.cancel().catch(() => { });
61
- await new Promise((r) => setTimeout(r, wait));
62
- }
63
- }
46
+ export const secondModels = (r, authorModel = "", first = "") => r.billing === "plan" ? [] : ids(r, "chat", "default", "checker").filter((m) => ![authorModel, first].some((x) => x && familyOf(m) === familyOf(x)));
47
+ /** For callers that go straight to OpenRouter (the evals): ZDR providers only, as the gateway sends it. */
48
+ export const zdrFetch = (url, init) => fetch(url, { ...init, body: init?.body ? JSON.stringify({ ...JSON.parse(String(init.body)), provider: { zdr: true } }) : init?.body });
64
49
  /**
65
- * OpenRouter chat completions with a strict JSON schema, ZDR providers only, no tools. Resolves { content, refusal, usage }.
66
- * The services pass the model gateway's url and the token the kernel minted for the call; an eval passes OpenRouter's key.
50
+ * One schema-bound model call over the Responses reader. Resolves { content, refusal, usage, turns }. With `tools` (the caller's,
51
+ * read-only), the model may call them first: each round's calls are answered by code (the caller fences what they return) until
52
+ * it answers, at most MAX_TURNS rounds. `url` is the API base (…/api/v1): the services pass the model gateway's and the token the
53
+ * kernel minted for the call; an eval passes OpenRouter's own, its key, and `retry`. A plan limit is never retried.
67
54
  */
68
- export function openRouterAsk(key, { timeoutMs = 600_000, fetchFn = fetch, schema, url = "https://openrouter.ai/api/v1/chat/completions", retryDelaysMs = [] }) {
69
- return async (model, { system, user }) => {
70
- const res = await fetchRetrying(fetchFn, retryDelaysMs, url, {
71
- method: "POST",
72
- headers: { authorization: `Bearer ${key}`, "content-type": "application/json" },
73
- body: JSON.stringify({
74
- model,
75
- messages: [{ role: "system", content: system }, { role: "user", content: user }],
76
- response_format: { type: "json_schema", json_schema: { name: "verdict", strict: true, schema } },
77
- provider: { zdr: true },
78
- reasoning: { effort: EFFORT[model] ?? "high" },
79
- max_tokens: MAX_TOKENS,
80
- temperature: 0,
81
- }),
82
- }, timeoutMs);
83
- if (!res.ok)
84
- throw new Error(`OpenRouter ${res.status}: ${(await res.text().catch(() => "")).slice(0, 200)}`);
85
- const json = await res.json();
86
- const msg = json?.choices?.[0]?.message ?? {};
87
- return { content: msg.content ?? "", refusal: msg.refusal ?? null, usage: json?.usage };
55
+ export function judgeAsk(cred, { url, schema, effort = "high", timeoutMs = 600_000, fetchFn, retry, onProgress = () => { } }) {
56
+ return async (model, { system, user, tools = {} }) => {
57
+ const fns = Object.entries(tools).map(([name, t]) => ({ name, description: t.description, parameters: t.parameters, run: (a) => { const out = t.run(a); onProgress(); return out; } }));
58
+ const send = fetchFn ?? fetch;
59
+ const r = await respondLoop({
60
+ url, headers: { authorization: `Bearer ${cred}` }, model, effort, instructions: system, input: [{ role: "user", content: user }], tools: fns,
61
+ schema: { name: "verdict", schema }, maxOutputTokens: MAX_TOKENS, timeoutMs, retry, maxTurns: MAX_TURNS + 1, // MAX_TURNS rounds of tool calls, then the answer
62
+ fetchFn: (u, init) => { onProgress(); return send(u, init); },
63
+ });
64
+ onProgress();
65
+ // A cut-off verdict is not a verdict: it fails loudly so the caller escalates rather than grading a partial answer.
66
+ if (r.incomplete)
67
+ throw new ModelError("other", 200, `the model's answer was cut off (${r.incomplete})`);
68
+ const refusal = r.output.flatMap((i) => (i.type === "message" && Array.isArray(i.content) ? i.content.filter((c) => c.type === "refusal").map((c) => c.refusal ?? "") : [])).join("") || null;
69
+ return { content: r.text, refusal, usage: r.usage, turns: r.turns - 1 };
88
70
  };
89
71
  }
@@ -0,0 +1,45 @@
1
+ /** The kernel's own error body (`error.type`, `error.message`), when it sent one (admission.ts names each refusal). */
2
+ export type KernelRefusal = {
3
+ type?: string;
4
+ message?: string;
5
+ };
6
+ export declare class KernelError extends Error {
7
+ status: number;
8
+ body?: KernelRefusal;
9
+ constructor(status: number, message: string, body?: KernelRefusal);
10
+ }
11
+ export declare function kernelClient(url: string, token: string, { timeoutMs, fetcher }?: {
12
+ timeoutMs?: number;
13
+ fetcher?: typeof fetch;
14
+ }): {
15
+ call: (method: string, path: string, body?: unknown, headers?: Record<string, string>) => Promise<any>;
16
+ raw: (method: string, path: string, body?: unknown, headers?: Record<string, string>) => Promise<{
17
+ status: number;
18
+ json: any;
19
+ }>;
20
+ /** A read of the control plane (GET only), e.g. read("/api/issues/WOR-1"). */
21
+ read: (path: string) => Promise<any>;
22
+ bytes: (path: string) => Promise<Buffer>;
23
+ upload: (path: string, data: Buffer) => Promise<any>;
24
+ };
25
+ export type KernelClient = ReturnType<typeof kernelClient>;
26
+ /** A fact a module sends the kernel (POST /v1/facts, docs/design/flow.md §2). The kernel sets the actor; never send one. */
27
+ export type FactIn = {
28
+ type: string;
29
+ subject: string;
30
+ version: string;
31
+ at: string;
32
+ task?: string | null;
33
+ source?: "live" | "backfill";
34
+ data?: Record<string, unknown>;
35
+ };
36
+ export declare function factEmitter(client: KernelClient, log: (msg: string, f?: Record<string, unknown>) => void, { everyMs, max }?: {
37
+ everyMs?: number | undefined;
38
+ max?: number | undefined;
39
+ }): {
40
+ /** `at` is queued as UTC (`Z`): offsets from a source never reach the log (an unparsable one is left for the kernel to refuse). */
41
+ emit(f: FactIn): void;
42
+ flush: () => Promise<void>;
43
+ stop: () => void;
44
+ };
45
+ export type FactEmitter = ReturnType<typeof factEmitter>;
@@ -0,0 +1,103 @@
1
+ export class KernelError extends Error {
2
+ status;
3
+ body;
4
+ constructor(status, message, body) { super(message); this.status = status; this.body = body; }
5
+ }
6
+ export function kernelClient(url, token, { timeoutMs = 30_000, fetcher = fetch } = {}) {
7
+ const base = url.replace(/\/$/, "");
8
+ const send = (method, path, body, headers = {}) => fetcher(`${base}${path}`, { method, headers: { authorization: `Bearer ${token}`, "content-type": "application/json", ...headers }, ...(body !== undefined ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(timeoutMs) });
9
+ const raw = async (method, path, body, headers) => {
10
+ const r = await send(method, path, body, headers);
11
+ return { status: r.status, json: await r.json().catch(() => ({})) };
12
+ };
13
+ // The kernel answers a refusal as {error: {code, type, message}} (backplane.ts): keep its type and words for the caller.
14
+ const refusalBody = (j) => (j?.error && typeof j.error === "object" ? { ...(typeof j.error.type === "string" ? { type: j.error.type } : {}), ...(typeof j.error.message === "string" ? { message: j.error.message } : {}) } : undefined);
15
+ const call = async (method, path, body, headers) => {
16
+ const r = await raw(method, path, body, headers);
17
+ if (r.status < 200 || r.status >= 300)
18
+ throw new KernelError(r.status, `kernel ${method} ${path} → ${r.status}: ${JSON.stringify(r.json).slice(0, 200)}`, refusalBody(r.json));
19
+ return r.json;
20
+ };
21
+ return {
22
+ call, raw,
23
+ /** A read of the control plane (GET only), e.g. read("/api/issues/WOR-1"). */
24
+ read: (path) => call("GET", `/v1/cp/read${path}`),
25
+ bytes: async (path) => {
26
+ const r = await send("GET", path);
27
+ if (!r.ok)
28
+ throw new KernelError(r.status, `kernel GET ${path} → ${r.status}`);
29
+ return Buffer.from(await r.arrayBuffer());
30
+ },
31
+ upload: async (path, data) => {
32
+ const r = await fetcher(`${base}${path}`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/octet-stream" }, body: new Uint8Array(data), signal: AbortSignal.timeout(timeoutMs) });
33
+ const j = await r.json().catch(() => ({}));
34
+ if (!r.ok)
35
+ throw new KernelError(r.status, `kernel POST ${path} → ${r.status}: ${JSON.stringify(j).slice(0, 200)}`, refusalBody(j));
36
+ return j;
37
+ },
38
+ };
39
+ }
40
+ /**
41
+ * A module's fact emitter: `emit` queues and returns at once; the queue is sent every `everyMs` (≤ 500 per call); a batch the
42
+ * kernel refuses (4xx) is dropped and logged, and one it couldn't take (5xx, network) is kept on a
43
+ * failure for the next flush, so emitting never fails or slows the module's own work. Deterministic ids make resends harmless.
44
+ * `flush` sends now (tests, shutdown) and, when the send it joined or made failed, makes one bounded retry so a shutdown's flush
45
+ * does not resolve with the batch still queued over a passing 5xx. `stop` clears the timer.
46
+ */
47
+ const FLUSH_ATTEMPTS = 2;
48
+ const RETRY_AFTER_FAIL_MS = 250;
49
+ export function factEmitter(client, log, { everyMs = 5_000, max = 10_000 } = {}) {
50
+ let queue = [];
51
+ let inflight;
52
+ let failed = false;
53
+ // A flush while one runs joins it (its loop sends all that is queued), so a shutdown flush resolves only when the queue is sent.
54
+ // A joined send that failed leaves the batch queued (a 5xx, a reset): the flush waits its end and makes one more attempt, so a
55
+ // shutdown's flush does not resolve with the fact still unsent when the kernel was briefly unavailable.
56
+ const flush = async () => {
57
+ for (let attempt = 0; attempt < FLUSH_ATTEMPTS; attempt++) {
58
+ // The wait sits before a retry, not after the last attempt: a brief outage is waited out, then tried once more.
59
+ if (attempt > 0)
60
+ await new Promise((r) => setTimeout(r, RETRY_AFTER_FAIL_MS));
61
+ const run = (inflight ??= send().finally(() => { inflight = undefined; }));
62
+ await run;
63
+ if (!failed || !queue.length)
64
+ return;
65
+ }
66
+ };
67
+ async function send() {
68
+ if (!queue.length)
69
+ return;
70
+ try {
71
+ while (queue.length) {
72
+ const batch = queue.slice(0, 500);
73
+ try {
74
+ await client.call("POST", "/v1/facts", { facts: batch });
75
+ }
76
+ catch (e) {
77
+ // The kernel refused the batch (a fact it won't take): resending can't help, so it is dropped, once, loudly.
78
+ const status = e.status;
79
+ if (!(status >= 400 && status < 500))
80
+ throw e;
81
+ log("facts: the kernel refused a batch, dropped", { status, dropped: batch.length, error: String(e.message).slice(0, 200) });
82
+ }
83
+ // emit() may have trimmed the queue's head during the await: drop exactly what was sent, not the first N.
84
+ const sent = new Set(batch);
85
+ queue = queue.filter((f) => !sent.has(f));
86
+ }
87
+ failed = false;
88
+ }
89
+ catch (e) {
90
+ failed = true;
91
+ log("facts: send failed, kept for the next flush", { queued: queue.length, error: String(e.message).slice(0, 200) });
92
+ }
93
+ }
94
+ const timer = setInterval(() => void flush(), everyMs);
95
+ timer.unref?.();
96
+ return {
97
+ /** `at` is queued as UTC (`Z`): offsets from a source never reach the log (an unparsable one is left for the kernel to refuse). */
98
+ emit(f) { const ms = Date.parse(f.at); queue.push(Number.isNaN(ms) ? { ...f } : { ...f, at: new Date(ms).toISOString() }); if (queue.length > max)
99
+ queue = queue.slice(-max); },
100
+ flush,
101
+ stop: () => clearInterval(timer),
102
+ };
103
+ }
package/dist/src/kit.js CHANGED
@@ -3,12 +3,27 @@
3
3
  import { spawn } from "node:child_process";
4
4
  import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
5
  import { tmpdir } from "node:os";
6
- import { join } from "node:path";
6
+ import { join, resolve } from "node:path";
7
7
  import { createRequire } from "node:module";
8
8
  import { appendLine, lines, readFrom } from "./engine-io.js";
9
+ /** `yaml` from the module's own dependencies, else from each NODE_PATH entry (named here: not every runtime reads NODE_PATH itself). */
10
+ function requireYaml(moduleDir) {
11
+ try {
12
+ return createRequire(join(moduleDir, "module.yaml"))("yaml");
13
+ }
14
+ catch (e) {
15
+ for (const dir of (process.env.NODE_PATH ?? "").split(":").filter(Boolean)) {
16
+ try {
17
+ return createRequire(join(resolve(dir), "x.js"))("yaml");
18
+ }
19
+ catch { }
20
+ }
21
+ throw e;
22
+ }
23
+ }
9
24
  /** The engines a module declares. module.yaml is read with the `yaml` package, from the module's own dependencies or NODE_PATH. */
10
25
  export function engineDecls(moduleDir) {
11
- const YAML = createRequire(join(moduleDir, "module.yaml"))("yaml");
26
+ const YAML = requireYaml(moduleDir);
12
27
  const def = YAML.parse(readFileSync(join(moduleDir, "module.yaml"), "utf8")) ?? {};
13
28
  const list = [def.providers?.engine ?? []].flat();
14
29
  if (!list.length)
@@ -24,8 +39,8 @@ export async function turn(moduleDir, decl, { session, env = {}, comment, timeou
24
39
  mkdirSync(d);
25
40
  const spec = {
26
41
  contract: "engine@1", job: "kit-1", agent: "agent-kit", task: "task-kit", prompt: "Kit: answer ok.", ...(session ? { session } : {}),
27
- model: { base_url: "http://127.0.0.1:9/api/v1", token_env: "AIDENHQ_MODEL_TOKEN", id: "kit-model", effort: "" },
28
- mcp: [], env: [], limits: { timeout_s: 60 }, web: true, state, sandbox: { kind: "bwrap", writable: [work], network: true },
42
+ model: { base_url: "http://127.0.0.1:9/api/v1", token_env: "AIDENHQ_MODEL_TOKEN", id: "kit-model", effort: "", api: "chat" },
43
+ mcp: [], env: [], limits: { timeout_s: 60 }, web: true, state, sandbox: { kind: "box", writable: [work], network: true },
29
44
  };
30
45
  writeFileSync(join(job, "job.json"), JSON.stringify(spec));
31
46
  try {
@@ -0,0 +1,58 @@
1
+ export declare const AGENT_FIX = "agent-fix";
2
+ export declare const FEATURE_LABEL = "feature-request";
3
+ export declare const BUILD_LABEL = "agent-build";
4
+ export declare const TRUST_ROLES: readonly ["admin", "maintain", "write"];
5
+ export declare const TRIAGE: readonly ["off", "new", "new+backlog"];
6
+ /** What happens to an issue triage (or the resolved-check) finds a duplicate, not a bug or request, or already fixed: always a comment
7
+ * saying why; `label` adds the verdict's label (its name, below) and leaves the issue open; `close` closes it. */
8
+ export declare const ACTIONS: readonly ["comment", "label", "close"];
9
+ export declare const VERDICTS: readonly ["duplicate", "invalid", "fixed"];
10
+ /** The label each verdict adds under `label`: GitHub's own names, the same on every repo. */
11
+ export declare const VERDICT_LABELS: Record<(typeof VERDICTS)[number], string>;
12
+ /** Labels every automatic close skips, unless the entry names its own list. */
13
+ export declare const PROTECTED_LABELS: string[];
14
+ /** Product constants, not settings: triage runs a day per outside author on rejected issues, the ceiling on all its unanswered runs
15
+ * (pending or rejected: without it a stranger's spam, which takes no verdict, runs up the model bill), closes per resolved-check run, and
16
+ * the days between an inactive issue's notice and its close. */
17
+ export declare const TRIAGE_CAP_PER_AUTHOR_DAY = 5;
18
+ export declare const TRIAGE_ADMISSION_PER_AUTHOR_DAY = 20;
19
+ export declare const RESOLVED_CLOSES_PER_RUN = 10;
20
+ export declare const INACTIVE_GRACE_DAYS = 14;
21
+ export interface MaintainedRepo {
22
+ repo: string;
23
+ owner: string;
24
+ name: string;
25
+ /** Validate `fix_label` issues, hand fixes over and see them through (default on). */
26
+ fixes: boolean;
27
+ /** Whether unlabelled issues are triaged: no, each new one, or each new one and the backlog (default new). */
28
+ triage: (typeof TRIAGE)[number];
29
+ /** Triage feature requests, and build the ones carrying BUILD_LABEL (default off). */
30
+ features: boolean;
31
+ /** What each verdict does (default label for all three). */
32
+ actions: Record<(typeof VERDICTS)[number], (typeof ACTIONS)[number]>;
33
+ /** Close an issue this many days after asking its reporter for details with no reply; null leaves it open (default). */
34
+ no_reply_days: number | null;
35
+ /** Give an issue quiet this many days one notice, close it INACTIVE_GRACE_DAYS later; null leaves it open (default). */
36
+ inactive_issue_days: number | null;
37
+ /** The label that asks for a fix. */
38
+ fix_label: string;
39
+ trusted: string[];
40
+ /** Labels every automatic close skips. */
41
+ protected_labels: string[];
42
+ }
43
+ /**
44
+ * `maintainer_repos` as compiled from the setting: JSON when an entry is `{ repo, ... }`, or comma-joined when every entry
45
+ * is a bare "owner/name" (an entry with every default). Anything malformed throws, naming the entry, so the caller refuses
46
+ * every tool rather than act on a list it misread.
47
+ */
48
+ export declare function parseRepos(raw: string): MaintainedRepo[];
49
+ /**
50
+ * The one way a repo joins maintainer_repos (the Maintainer page's add; Ship keeps its own list): the list with `repo`
51
+ * appended as an entry carrying `fields` (none = every default). Throws with the owner-readable reason for a malformed or already
52
+ * listed repo; the caller still runs parseRepos over the result.
53
+ */
54
+ export declare function addListed(list: unknown[], repo: string, fields?: Record<string, unknown>): unknown[];
55
+ /** Whether `slug` (owner/name, any case) is one of the listed repos. */
56
+ export declare const inMaintained: (repos: MaintainedRepo[], slug: string) => boolean;
57
+ /** One line per repo, for tool descriptions: what the Maintainer may act on there. */
58
+ export declare const describeRepos: (repos: MaintainedRepo[]) => string;
@@ -0,0 +1,136 @@
1
+ // `maintainer_repos`, the Maintainer's own list of repos (issues only: pull requests are Ship's): the setting as compiled, parsed
2
+ // once here for github-mcp (the Maintainer's tools and watcher read) and the Maintainer's page. Each entry's duties are opt-in.
3
+ export const AGENT_FIX = "agent-fix";
4
+ // The labels of the feature flow, fixed names (not per-repo settings): a feature request awaiting the owner's word, and the
5
+ // owner's word that it may be built. Trust is a collaborator's role (maintainer.ts); the owner's login is an admin.
6
+ export const FEATURE_LABEL = "feature-request";
7
+ export const BUILD_LABEL = "agent-build";
8
+ // The roles a repo may trust to vouch for a label: a fixed set in code, never wider than write. A repo's `trusted` picks
9
+ // from it (default admin and maintain); triage, read and custom roles never count.
10
+ export const TRUST_ROLES = ["admin", "maintain", "write"];
11
+ const DEFAULT_TRUSTED = ["admin", "maintain"];
12
+ export const TRIAGE = ["off", "new", "new+backlog"];
13
+ /** What happens to an issue triage (or the resolved-check) finds a duplicate, not a bug or request, or already fixed: always a comment
14
+ * saying why; `label` adds the verdict's label (its name, below) and leaves the issue open; `close` closes it. */
15
+ export const ACTIONS = ["comment", "label", "close"];
16
+ export const VERDICTS = ["duplicate", "invalid", "fixed"];
17
+ /** The label each verdict adds under `label`: GitHub's own names, the same on every repo. */
18
+ export const VERDICT_LABELS = { duplicate: "duplicate", invalid: "invalid", fixed: "fixed" };
19
+ /** Labels every automatic close skips, unless the entry names its own list. */
20
+ export const PROTECTED_LABELS = ["roadmap", "wip", "blocked"];
21
+ /** Product constants, not settings: triage runs a day per outside author on rejected issues, the ceiling on all its unanswered runs
22
+ * (pending or rejected: without it a stranger's spam, which takes no verdict, runs up the model bill), closes per resolved-check run, and
23
+ * the days between an inactive issue's notice and its close. */
24
+ export const TRIAGE_CAP_PER_AUTHOR_DAY = 5;
25
+ export const TRIAGE_ADMISSION_PER_AUTHOR_DAY = 20;
26
+ export const RESOLVED_CLOSES_PER_RUN = 10;
27
+ export const INACTIVE_GRACE_DAYS = 14;
28
+ const KEYS = ["repo", "fixes", "triage", "features", "actions", "no_reply_days", "inactive_issue_days", "fix_label", "trusted", "protected_labels"];
29
+ const SHAPE = `{ ${KEYS.join(", ")} }`;
30
+ /** Keys an older entry may still carry, with what replaced each: named in the refusal. */
31
+ const REMOVED = {
32
+ label: "it is now fix_label", issues: "it is now fixes", preset: "removed: set triage and features", triage_labels: "removed",
33
+ close: "removed: see actions", triage_cap_per_author_day: "removed: 5 a day is fixed", resolved_check: "removed: see actions.fixed and protected_labels",
34
+ needs_info_close_days: "it is now no_reply_days", stale_issues: "it is now inactive_issue_days", contributor_prs: "moved to Ship: quiet_pr_days on the repo's ship.repos entry",
35
+ stale_days: "moved to Ship: quiet_pr_days on the repo's ship.repos entry",
36
+ // Pull-request duties are Ship's (owner, 2026-11-27): each is a field of the repo's ship entry now.
37
+ dependabot: "moved to Ship: dependabot on the repo's ship.repos entry", quiet_pr_days: "moved to Ship: quiet_pr_days on the repo's ship.repos entry",
38
+ };
39
+ const whole = (v, min) => typeof v === "number" && Number.isInteger(v) && v >= min;
40
+ const labelList = (where, k, v) => {
41
+ if (!Array.isArray(v) || v.some((l) => typeof l !== "string" || !/^[^\p{Cc}$]{1,50}$/u.test(l)))
42
+ throw new Error(`${where}: ${k} is a list of labels`);
43
+ return [...new Set(v)];
44
+ };
45
+ /**
46
+ * `maintainer_repos` as compiled from the setting: JSON when an entry is `{ repo, ... }`, or comma-joined when every entry
47
+ * is a bare "owner/name" (an entry with every default). Anything malformed throws, naming the entry, so the caller refuses
48
+ * every tool rather than act on a list it misread.
49
+ */
50
+ export function parseRepos(raw) {
51
+ if (!raw.trim())
52
+ return [];
53
+ let list;
54
+ try {
55
+ list = raw.trim().startsWith("[") ? JSON.parse(raw) : raw.split(",").map((x) => x.trim());
56
+ }
57
+ catch {
58
+ throw new Error(`maintainer_repos is not a list of ${SHAPE}`);
59
+ }
60
+ if (!Array.isArray(list))
61
+ throw new Error("maintainer_repos is not a list");
62
+ const seen = new Set();
63
+ return list.map((entry, i) => {
64
+ const where = `maintainer_repos[${i}]`;
65
+ const e = typeof entry === "string" ? { repo: entry } : entry;
66
+ if (!e || typeof e !== "object" || Array.isArray(e))
67
+ throw new Error(`${where}: an entry is ${SHAPE}`);
68
+ const unknown = Object.keys(e).filter((k) => !KEYS.includes(k));
69
+ if (unknown.length)
70
+ throw new Error(`${where}: unknown key ${unknown.map((k) => (REMOVED[k] ? `${k} (${REMOVED[k]})` : k)).join(", ")}`);
71
+ const m = String(e.repo ?? "").trim().match(/^([A-Za-z0-9_.-]{1,100})\/([A-Za-z0-9_.-]{1,100})$/);
72
+ if (!m)
73
+ throw new Error(`${where}: repo must be owner/name`);
74
+ const key = `${m[1]}/${m[2]}`.toLowerCase();
75
+ if (seen.has(key))
76
+ throw new Error(`${where}: ${m[1]}/${m[2]} is listed twice`);
77
+ seen.add(key);
78
+ const fix_label = e.fix_label === undefined ? AGENT_FIX : String(e.fix_label);
79
+ if (!/^[A-Za-z0-9][A-Za-z0-9 ._:-]{0,49}$/.test(fix_label))
80
+ throw new Error(`${where}: fix_label must be 1-50 letters, digits, spaces or ._:-`);
81
+ if ([...Object.values(VERDICT_LABELS), FEATURE_LABEL, BUILD_LABEL].includes(fix_label.toLowerCase()))
82
+ throw new Error(`${where}: fix_label ${fix_label} is a label the Maintainer uses for something else`);
83
+ const trusted = e.trusted === undefined ? DEFAULT_TRUSTED : e.trusted;
84
+ if (!Array.isArray(trusted) || !trusted.length || trusted.some((r) => !TRUST_ROLES.includes(r)))
85
+ throw new Error(`${where}: trusted must be one or more of ${TRUST_ROLES.join(", ")}`);
86
+ const bool = (k, dflt) => {
87
+ if (e[k] === undefined)
88
+ return dflt;
89
+ if (typeof e[k] !== "boolean")
90
+ throw new Error(`${where}: ${k} must be true or false`);
91
+ return e[k];
92
+ };
93
+ const one = (k, v, values, dflt) => {
94
+ if (v === undefined)
95
+ return dflt;
96
+ if (!values.includes(v))
97
+ throw new Error(`${where}: ${k} must be one of ${values.join(", ")}`);
98
+ return v;
99
+ };
100
+ const days = (k) => {
101
+ if (e[k] === undefined || e[k] === null)
102
+ return null;
103
+ if (!whole(e[k], 1))
104
+ throw new Error(`${where}: ${k} must be a whole number of days, 1 or more, or null (off)`);
105
+ return e[k];
106
+ };
107
+ const a = e.actions ?? {};
108
+ if (typeof a !== "object" || Array.isArray(a) || Object.keys(a).some((k) => !VERDICTS.includes(k)))
109
+ throw new Error(`${where}: actions is { ${VERDICTS.join(", ")} }, each ${ACTIONS.join(" | ")}`);
110
+ const actions = Object.fromEntries(VERDICTS.map((v) => [v, one(`actions.${v}`, a[v], ACTIONS, "label")]));
111
+ return {
112
+ repo: `${m[1]}/${m[2]}`, owner: m[1], name: m[2],
113
+ fixes: bool("fixes", true), triage: one("triage", e.triage, TRIAGE, "new"), features: bool("features", false),
114
+ actions,
115
+ no_reply_days: days("no_reply_days"), inactive_issue_days: days("inactive_issue_days"),
116
+ fix_label, trusted: [...new Set(trusted)],
117
+ protected_labels: e.protected_labels === undefined ? PROTECTED_LABELS : labelList(where, "protected_labels", e.protected_labels),
118
+ };
119
+ });
120
+ }
121
+ /**
122
+ * The one way a repo joins maintainer_repos (the Maintainer page's add; Ship keeps its own list): the list with `repo`
123
+ * appended as an entry carrying `fields` (none = every default). Throws with the owner-readable reason for a malformed or already
124
+ * listed repo; the caller still runs parseRepos over the result.
125
+ */
126
+ export function addListed(list, repo, fields = {}) {
127
+ if (!/^[\w.-]{1,100}\/[\w.-]{1,100}$/.test(repo))
128
+ throw new Error(`${repo.slice(0, 100)} isn't owner/name, for example acme/api`);
129
+ if (list.some((e) => String(typeof e === "string" ? e : e?.repo).toLowerCase() === repo.toLowerCase()))
130
+ throw new Error(`${repo} is already listed`);
131
+ return [...list, { repo, ...fields }];
132
+ }
133
+ /** Whether `slug` (owner/name, any case) is one of the listed repos. */
134
+ export const inMaintained = (repos, slug) => repos.some((r) => r.repo.toLowerCase() === slug.toLowerCase());
135
+ /** One line per repo, for tool descriptions: what the Maintainer may act on there. */
136
+ export const describeRepos = (repos) => repos.length ? repos.map((r) => `${r.repo} (label ${r.fix_label}, trusted ${r.trusted.join("/")})`).join("; ") : "none configured (setting maintainer_repos)";
@@ -0,0 +1,29 @@
1
+ /**
2
+ * A final message without the model-format sentinels a tokenizer or chat template leaks as literal text. They leak at the edges
3
+ * of a completion, so a sentinel at either end is removed, with the padding beside it and the role line its header carries: a
4
+ * reply that was only sentinels is left empty, so its dispatcher reads it as one that ended without a reply, while a reply that
5
+ * shows a marker in a blockquote keeps it. Every step reads only the characters it needs, so a long reply or a run of
6
+ * sentinels costs its own length rather than its square.
7
+ */
8
+ export declare function stripSentinels(text: string): string;
9
+ /** Whether `text` carries raw tool-call markup: the task tools refuse such an argument, and a reply's body is stripped of it. */
10
+ export declare const hasToolMarkup: (text: string) => boolean;
11
+ /**
12
+ * A reply's body without model-format markup at its edges: the chat-template headers and sentinels (`stripSentinels`' own
13
+ * policy), a bare opening role tag, and a trailing run of tool-call tags, opening or closing, with a half-written one at the
14
+ * very end. A marker the reply shows on purpose stays: escaped, inside a fenced code block, or the whole of a blockquote line.
15
+ * The fences are read before anything is cut, so a marker that was inside one keeps that fence's protection even once the
16
+ * text after it is gone. A body that was only markup comes back empty, so its dispatcher posts no reply, as at jobs.ts's
17
+ * stored last message. Each edge is walked to its end, so a long reply or a long run of tags costs its own length.
18
+ */
19
+ export declare function sanitizeReply(text: string): string;
20
+ /** The agent's word for "nothing to send to anyone". */
21
+ export declare const NO_REPLY = "NO_REPLY";
22
+ /**
23
+ * A final message read for NO_REPLY: the whole message, or its last line after the run's note. Either way the run is silent
24
+ * (nothing relayed to a person), the sentinel itself is dropped, and the note before it stays as `text` for the task.
25
+ */
26
+ export declare function silentReply(text: string): {
27
+ text: string;
28
+ silent: boolean;
29
+ };