@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,88 @@
1
+ export declare const TIERS: readonly ["skip", "trivial", "standard", "sensitive"];
2
+ export type Tier = (typeof TIERS)[number];
3
+ /** A tier's rank: a higher one is riskier (what "loosening" compares). */
4
+ export declare const RANK: Record<Tier, number>;
5
+ export declare const REPO_CLASSES: readonly ["critical", "standard", "sandbox"];
6
+ export type RepoClass = (typeof REPO_CLASSES)[number];
7
+ export declare const AUTHORS: readonly ["member", "bot", "outsider"];
8
+ export type AuthorKind = (typeof AUTHORS)[number];
9
+ /** Lockfiles: made, not written. They never count toward `lines`, and any change to one is a sensitive path (SENSITIVE). */
10
+ export declare const LOCKS: string[];
11
+ /** Generated code and build output: never counted toward `lines`. */
12
+ export declare const GENERATED: string[];
13
+ /** Package manifests: a bot's PR that changes only these and lockfiles (Dependabot) is skipped: no review unless someone asks. */
14
+ export declare const MANIFESTS: string[];
15
+ /** Prose: the docs folder's documents (plans, specs, designs). A change that is only these is judged by what it says, not by a keyword in a path. */
16
+ export declare const PROSE: string[];
17
+ /** Rule files a folder's AGENTS.md links to (`modules/AGENTS.md`): a change to one steers an agent as much as the guide does. */
18
+ export declare const FOLDER_RULES: string[];
19
+ /** The files that steer an agent (a reviewer reads them as guidance): prose, but never demoted. */
20
+ export declare const INSTRUCTIONS: string[];
21
+ /** The default sensitive paths: what CI's critical-path regex and ship's safe.deny meant, in one list. */
22
+ export declare const SENSITIVE: string[];
23
+ /** What the rules see: the PR's own change (merge base to head) and who made it, plus the repo's class. */
24
+ export type Facts = {
25
+ /** Substantive lines: additions plus deletions over every file but generated files and lockfiles. */
26
+ lines: number;
27
+ /** How many files count toward `lines`. */
28
+ files: number;
29
+ /** Every changed path, a rename's old path and generated files included. */
30
+ paths: string[];
31
+ author: AuthorKind;
32
+ base: string;
33
+ repo_class: RepoClass;
34
+ };
35
+ /** One entry of GitHub's PR files list. */
36
+ export type FileChange = {
37
+ path: string;
38
+ previous?: string;
39
+ additions: number;
40
+ deletions: number;
41
+ };
42
+ /** A GitHub files list stops at this many files: a PR with more is sensitive, unread. */
43
+ export declare const TOO_MANY_FILES = 3000;
44
+ export declare const matches: (path: string, globs: readonly string[]) => boolean;
45
+ export declare function factsOf(files: FileChange[], o: {
46
+ author: AuthorKind;
47
+ base: string;
48
+ repo_class: RepoClass;
49
+ }): Facts;
50
+ /** Who opened the PR: the instance's own App is a member (`own`), Dependabot and Renovate (exact logins, never from a fork) bots,
51
+ * an owner, member or collaborator a member. Any other `*[bot]` is judged by its association, as a person is. */
52
+ export declare function authorKind(login: string, association: string | undefined, own?: boolean, fork?: boolean): AuthorKind;
53
+ export type When = {
54
+ lines_min?: number;
55
+ lines_max?: number;
56
+ files_min?: number;
57
+ files_max?: number;
58
+ paths?: string[];
59
+ only_paths?: string[];
60
+ author?: AuthorKind;
61
+ base?: string[];
62
+ repo_class?: RepoClass;
63
+ };
64
+ export type Rule = {
65
+ when?: When;
66
+ tier: Tier;
67
+ };
68
+ export declare const CONDITIONS: readonly ["lines_min", "lines_max", "files_min", "files_max", "paths", "only_paths", "base", "author", "repo_class"];
69
+ /** The default rules: the first that holds names the tier. */
70
+ export declare const DEFAULT_RULES: Rule[];
71
+ /** A rules list checked whole: the rules, or the first reason it isn't one. */
72
+ export declare function parseRules(raw: unknown): Rule[] | {
73
+ error: string;
74
+ };
75
+ /** The tier the first matching rule names, its index, and why in plain words. */
76
+ export declare function classify(f: Facts, rules: Rule[]): {
77
+ tier: Tier;
78
+ rule: number;
79
+ why: string;
80
+ };
81
+ /** A PR whose files list GitHub can't give whole: sensitive, unread. */
82
+ export declare const tooMany: (n: number) => {
83
+ tier: Tier;
84
+ rule: number;
85
+ why: string;
86
+ };
87
+ /** The tiers a rules list can select: those some rule names. */
88
+ export declare const selectable: (rules: Rule[]) => ("sensitive" | "skip" | "standard" | "trivial")[];
@@ -0,0 +1,156 @@
1
+ // Risk tiers (docs/design/code-review.md, "Risk tiers"): one tier per PR head from cheap facts about its own change,
2
+ // by a repo's ordered rules (the first whose conditions all hold names it). No model call, no labels. Code review owns the rules and
3
+ // serves the tier through its verdict; the CI template classifies a PR itself with this same file. Dependency-free (node:path only):
4
+ // scripts/sync-shared.ts copies it into code review's service and recipe, the engineer image and the CI template.
5
+ import { posix } from "node:path";
6
+ export const TIERS = ["skip", "trivial", "standard", "sensitive"];
7
+ /** A tier's rank: a higher one is riskier (what "loosening" compares). */
8
+ export const RANK = { skip: 0, trivial: 1, standard: 2, sensitive: 3 };
9
+ export const REPO_CLASSES = ["critical", "standard", "sandbox"];
10
+ export const AUTHORS = ["member", "bot", "outsider"];
11
+ /** Lockfiles: made, not written. They never count toward `lines`, and any change to one is a sensitive path (SENSITIVE). */
12
+ export const LOCKS = ["**/package-lock.json", "**/npm-shrinkwrap.json", "**/*.lock", "**/*-lock.json", "**/*-lock.yaml", "**/go.sum", "**/bun.lockb"];
13
+ /** Generated code and build output: never counted toward `lines`. */
14
+ export const GENERATED = ["**/generated/**", "**/__generated__/**", "**/node_modules/**", "**/dist/**", "**/*.min.js", "**/*.min.css", "**/*.map", "**/*.snap"];
15
+ /** Package manifests: a bot's PR that changes only these and lockfiles (Dependabot) is skipped: no review unless someone asks. */
16
+ export const MANIFESTS = ["**/package.json", "**/go.mod", "**/Cargo.toml", "**/pyproject.toml"];
17
+ // Globs are case-sensitive, so the default list spells the common capitalised forms too (Auth, Session…).
18
+ const RISKY = ["auth", "secur", "token", "session", "permission"].flatMap((w) => [w, w[0].toUpperCase() + w.slice(1)]).flatMap((w) => [`**/*${w}*`, `**/*${w}*/**`]);
19
+ /** Prose: the docs folder's documents (plans, specs, designs). A change that is only these is judged by what it says, not by a keyword in a path. */
20
+ export const PROSE = ["docs/**/*.md", "docs/**/*.rst"]; // not mdx: it can run code
21
+ /** Rule files a folder's AGENTS.md links to (`modules/AGENTS.md`): a change to one steers an agent as much as the guide does. */
22
+ export const FOLDER_RULES = ["modules/agent-anatomy.md", "modules/teammates.md"];
23
+ /** The files that steer an agent (a reviewer reads them as guidance): prose, but never demoted. */
24
+ export const INSTRUCTIONS = ["**/AGENTS.md", "**/AGENTS.override.md", "**/CLAUDE.md", "**/REVIEW.md", "docs/conventions-*.md", ...FOLDER_RULES];
25
+ /** The default sensitive paths: what CI's critical-path regex and ship's safe.deny meant, in one list. */
26
+ export const SENSITIVE = [
27
+ ".github/**", "**/Dockerfile*", "**/package.json", ...INSTRUCTIONS, "**/.codex/**", "**/codex.toml", ...RISKY,
28
+ ...LOCKS, "**/.eslintrc*", "**/eslint.config.*", "**/.oxlintrc*", "**/oxlint.config.*", "**/oxlint-plugin.*", "**/oxlint-suppressions.json", "**/vitest.config.*", "**/jest.config.*", "**/tsconfig*.json", "**/CODEOWNERS",
29
+ "**/migrations/**", "**/*.tf", "infra/**", "**/.env*", "**/config/**", "**/docker-compose*",
30
+ ];
31
+ /** A GitHub files list stops at this many files: a PR with more is sensitive, unread. */
32
+ export const TOO_MANY_FILES = 3000;
33
+ /** A path's segments without their leading dot: a glob's wildcards skip dot-files and dot-folders, so `.github/**` would miss
34
+ * `.github/.release.yml`. Each glob is also tried with both sides undotted, so a dot-name matches like any other name. */
35
+ const undot = (s) => s.replace(/(^|\/)\.(?=[^/])/g, "$1");
36
+ export const matches = (path, globs) => globs.some((g) => posix.matchesGlob(path, g) || posix.matchesGlob(undot(path), undot(g)));
37
+ export function factsOf(files, o) {
38
+ const counted = files.filter((f) => !matches(f.path, GENERATED) && !matches(f.path, LOCKS));
39
+ const paths = [...new Set(files.flatMap((f) => (f.previous && f.previous !== f.path ? [f.path, f.previous] : [f.path])))];
40
+ return { lines: counted.reduce((n, f) => n + f.additions + f.deletions, 0), files: counted.length, paths, ...o };
41
+ }
42
+ /** Who opened the PR: the instance's own App is a member (`own`), Dependabot and Renovate (exact logins, never from a fork) bots,
43
+ * an owner, member or collaborator a member. Any other `*[bot]` is judged by its association, as a person is. */
44
+ export function authorKind(login, association, own = false, fork = false) {
45
+ if (own)
46
+ return "member";
47
+ if (!fork && /^(dependabot|renovate)\[bot\]$/i.test(login))
48
+ return "bot";
49
+ return ["OWNER", "MEMBER", "COLLABORATOR"].includes(String(association ?? "").toUpperCase()) ? "member" : "outsider";
50
+ }
51
+ const COUNTS = ["lines_min", "lines_max", "files_min", "files_max"];
52
+ const GLOBS = ["paths", "only_paths", "base"];
53
+ export const CONDITIONS = [...COUNTS, ...GLOBS, "author", "repo_class"];
54
+ /** The default rules: the first that holds names the tier. */
55
+ export const DEFAULT_RULES = [
56
+ { when: { repo_class: "critical" }, tier: "sensitive" },
57
+ { when: { author: "bot", only_paths: [...MANIFESTS, ...LOCKS] }, tier: "skip" },
58
+ { when: { paths: INSTRUCTIONS }, tier: "sensitive" },
59
+ { when: { author: "member", only_paths: PROSE }, tier: "standard" },
60
+ { when: { paths: SENSITIVE }, tier: "sensitive" },
61
+ { when: { author: "outsider" }, tier: "sensitive" },
62
+ { when: { repo_class: "sandbox" }, tier: "trivial" },
63
+ { when: { lines_max: 0 }, tier: "sensitive" },
64
+ { when: { lines_min: 600 }, tier: "sensitive" },
65
+ { when: { author: "member", lines_max: 10, files_max: 20 }, tier: "trivial" },
66
+ { tier: "standard" },
67
+ ];
68
+ /** A rules list checked whole: the rules, or the first reason it isn't one. */
69
+ export function parseRules(raw) {
70
+ if (!Array.isArray(raw) || !raw.length || raw.length > 100)
71
+ return { error: "rules is a list of 1 to 100 { when?, tier }, the last with no when" };
72
+ const out = [];
73
+ for (const [i, r] of raw.entries()) {
74
+ const at = `rules[${i}]`;
75
+ if (!r || typeof r !== "object" || Array.isArray(r))
76
+ return { error: `${at} is { when?, tier }` };
77
+ const extra = Object.keys(r).filter((k) => k !== "when" && k !== "tier");
78
+ if (extra.length)
79
+ return { error: `${at}: unknown field ${extra.join(", ")}` };
80
+ const { when, tier } = r;
81
+ if (!TIERS.includes(tier))
82
+ return { error: `${at}.tier is one of ${TIERS.join(", ")}` };
83
+ const last = i === raw.length - 1;
84
+ if (last && when !== undefined)
85
+ return { error: `${at}: the last rule has no when (it is everything else)` };
86
+ if (!last && when === undefined)
87
+ return { error: `${at}: only the last rule has no when` };
88
+ if (last) {
89
+ out.push({ tier: tier });
90
+ continue;
91
+ }
92
+ if (!when || typeof when !== "object" || Array.isArray(when) || !Object.keys(when).length)
93
+ return { error: `${at}.when names at least one condition` };
94
+ const w = {};
95
+ for (const [k, v] of Object.entries(when)) {
96
+ if (COUNTS.includes(k)) {
97
+ if (!Number.isInteger(v) || v < 0 || v > 10_000_000)
98
+ return { error: `${at}.when.${k} is a whole number` };
99
+ }
100
+ else if (GLOBS.includes(k)) {
101
+ if (!Array.isArray(v) || !v.length || v.length > 300 || !v.every((g) => typeof g === "string" && g.length > 0 && g.length <= 200))
102
+ return { error: `${at}.when.${k} is a list of globs` };
103
+ }
104
+ else if (k === "author") {
105
+ if (!AUTHORS.includes(v))
106
+ return { error: `${at}.when.author is one of ${AUTHORS.join(", ")}` };
107
+ }
108
+ else if (k === "repo_class") {
109
+ if (!REPO_CLASSES.includes(v))
110
+ return { error: `${at}.when.repo_class is one of ${REPO_CLASSES.join(", ")}` };
111
+ }
112
+ else
113
+ return { error: `${at}.when: unknown condition ${k} (one of ${CONDITIONS.join(", ")})` };
114
+ w[k] = Array.isArray(v) ? [...v] : v;
115
+ }
116
+ out.push({ when: w, tier: tier });
117
+ }
118
+ return out;
119
+ }
120
+ const holds = (f, w) => (w.lines_min === undefined || f.lines >= w.lines_min) && (w.lines_max === undefined || f.lines <= w.lines_max)
121
+ && (w.files_min === undefined || f.files >= w.files_min) && (w.files_max === undefined || f.files <= w.files_max)
122
+ && (w.paths === undefined || f.paths.some((p) => matches(p, w.paths)))
123
+ && (w.only_paths === undefined || (f.paths.length > 0 && f.paths.every((p) => matches(p, w.only_paths))))
124
+ && (w.author === undefined || f.author === w.author)
125
+ && (w.base === undefined || matches(f.base, w.base))
126
+ && (w.repo_class === undefined || f.repo_class === w.repo_class);
127
+ /** The tier the first matching rule names, its index, and why in plain words. */
128
+ export function classify(f, rules) {
129
+ const i = rules.findIndex((r) => !r.when || holds(f, r.when));
130
+ const r = rules[i];
131
+ return { tier: r.tier, rule: i, why: why(f, r.when) };
132
+ }
133
+ /** A PR whose files list GitHub can't give whole: sensitive, unread. */
134
+ export const tooMany = (n) => ({ tier: "sensitive", rule: -1, why: `too many files to read (${n} changed; GitHub lists at most ${TOO_MANY_FILES})` });
135
+ function why(f, w) {
136
+ if (!w)
137
+ return `${f.lines} line${f.lines === 1 ? "" : "s"} in ${f.files} file${f.files === 1 ? "" : "s"}, by a ${f.author}`;
138
+ const parts = [];
139
+ if (w.repo_class)
140
+ parts.push(`the repo is ${w.repo_class}`);
141
+ if (w.author)
142
+ parts.push(`by a ${w.author}`);
143
+ if (w.paths)
144
+ parts.push(`touches ${f.paths.find((p) => matches(p, w.paths))}`);
145
+ if (w.only_paths)
146
+ parts.push(`only ${f.paths.length === 1 ? f.paths[0] : `${f.paths.length} matching files`}`);
147
+ if (w.lines_min !== undefined || w.lines_max !== undefined)
148
+ parts.push(`${f.lines} line${f.lines === 1 ? "" : "s"}${f.lines === 0 && w.lines_max === 0 ? " of code (only generated files, lockfiles, binaries or renames)" : ""}`);
149
+ if (w.files_min !== undefined || w.files_max !== undefined)
150
+ parts.push(`${f.files} file${f.files === 1 ? "" : "s"}`);
151
+ if (w.base)
152
+ parts.push(`into ${f.base}`);
153
+ return parts.join(", ");
154
+ }
155
+ /** The tiers a rules list can select: those some rule names. */
156
+ export const selectable = (rules) => TIERS.filter((t) => rules.some((r) => r.tier === t));
@@ -0,0 +1,60 @@
1
+ /** What a tool call resolves to: its text blocks as the proxy sent them (fenced for an untrusted connection), its images saved as files. */
2
+ export interface ToolResult {
3
+ text: string;
4
+ images: string[];
5
+ structured?: unknown;
6
+ }
7
+ /** A call that didn't succeed: refused by the proxy, an error from the tool, or a transport failure. `record`: the write's record, when one was filed. */
8
+ export declare class ToolError extends Error {
9
+ connection: string;
10
+ tool: string;
11
+ code: string;
12
+ /** What went wrong, in the proxy's or the tool's own words (the message prefixed with the tool and code). */
13
+ detail: string;
14
+ record?: string;
15
+ constructor(connection: string, tool: string, code: string, detail: string, record?: string);
16
+ }
17
+ /** A write that has not happened yet: its record waits on the AI reviewer (tier 1) or the owner (tier 2); the outcome lands on the task. */
18
+ export declare class ToolPending extends Error {
19
+ connection: string;
20
+ tool: string;
21
+ record: string;
22
+ tier: number;
23
+ state: string;
24
+ constructor(connection: string, tool: string, record: string, tier: number, state: string);
25
+ }
26
+ type Message = {
27
+ id?: unknown;
28
+ result?: any;
29
+ error?: {
30
+ code?: number;
31
+ message?: string;
32
+ };
33
+ };
34
+ /** One JSON-RPC answer: the message with this request's id, and the record id the proxy marks a pending write with. */
35
+ export interface Answer {
36
+ message: Message;
37
+ pending?: string;
38
+ }
39
+ /**
40
+ * An MCP client over HTTP: `url(connection)` is each connection's endpoint, `headers` the caller's credential. Each connection
41
+ * gets one session per process (initialize once, its mcp-session-id kept), then requests on it. A transport failure throws
42
+ * ToolError (401: the job ended; a status; a timeout), named by `tool` (the tool called, or the method).
43
+ */
44
+ export declare function mcp({ url, headers }: {
45
+ url: (connection: string) => string;
46
+ headers: Record<string, string>;
47
+ }): {
48
+ request: (connection: string, method: string, params: Record<string, unknown>, { signal, tool }: {
49
+ signal: AbortSignal;
50
+ tool?: string;
51
+ }) => Promise<Answer>;
52
+ };
53
+ /**
54
+ * One tool of a connection, called once as this job. Resolves to its text and images; throws ToolError (a refusal, the tool's
55
+ * own error, a transport failure) or ToolPending (a write waiting on a decision). `timeoutS`: the connection's tool timeout + 30.
56
+ */
57
+ export declare function call(connection: string, tool: string, args?: unknown, { timeoutS }?: {
58
+ timeoutS?: number;
59
+ }): Promise<ToolResult>;
60
+ export {};
@@ -0,0 +1,192 @@
1
+ // The one MCP client a job's computer has (code mode: docs/design/sessions.md, "Code mode"). A
2
+ // session's generated tool files (<state>/aidenhq-tools/) and the in-box `aidenhq` CLI call connections through it, as the job:
3
+ // POST $AIDENHQ_GATEWAY_URL/c/<connection>/mcp with X-Agent-Key: $AIDENHQ_RUN_TOKEN, which the launcher checks and passes on to
4
+ // the kernel's tool proxy. The proxy decides every call (grants, fencing, tiers, write records); nothing is decided here.
5
+ // The kernel lists a job's tools at launch with the same client (`mcp`), straight to its own proxy with the job token as bearer.
6
+ //
7
+ // A call is sent once and never replayed: a timeout, an oversized result or a needs-owner answer can all mean a write happened.
8
+ // Copied into the engineer image as /opt/aidenhq/lib/tools.ts (scripts/sync-shared.ts); Node runs it with type stripping, so it
9
+ // uses erasable TypeScript only.
10
+ import { mkdtempSync, writeFileSync } from "node:fs";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
13
+ /** The proxy's refusals: the tool isn't this job's to call. */
14
+ const REFUSALS = ["tool-unlisted", "no-grant", "method-refused"];
15
+ /** A call that didn't succeed: refused by the proxy, an error from the tool, or a transport failure. `record`: the write's record, when one was filed. */
16
+ export class ToolError extends Error {
17
+ connection;
18
+ tool;
19
+ code;
20
+ /** What went wrong, in the proxy's or the tool's own words (the message prefixed with the tool and code). */
21
+ detail;
22
+ record;
23
+ constructor(connection, tool, code, detail, record) {
24
+ super(`${connection}.${tool}: ${code}: ${detail}`);
25
+ this.name = "ToolError";
26
+ this.connection = connection;
27
+ this.tool = tool;
28
+ this.code = code;
29
+ this.detail = detail;
30
+ if (record)
31
+ this.record = record;
32
+ }
33
+ }
34
+ /** A write that has not happened yet: its record waits on the AI reviewer (tier 1) or the owner (tier 2); the outcome lands on the task. */
35
+ export class ToolPending extends Error {
36
+ connection;
37
+ tool;
38
+ record;
39
+ tier;
40
+ state;
41
+ constructor(connection, tool, record, tier, state) {
42
+ super(`${connection}.${tool}: write ${record} is waiting on ${tier === 1 ? "the AI reviewer" : "the owner"} (${state}); it has not happened, and its outcome lands on your task`);
43
+ this.name = "ToolPending";
44
+ this.connection = connection;
45
+ this.tool = tool;
46
+ this.record = record;
47
+ this.tier = tier;
48
+ this.state = state;
49
+ }
50
+ }
51
+ const PROTOCOL = "2025-06-18";
52
+ /** The JSON-RPC messages of an answer: one JSON object, or SSE events, each one's data lines joined (a message may span several). */
53
+ function messages(text, sse) {
54
+ const raw = sse ? text.split(/\r\n\r\n|\n\n|\r\r/).map((ev) => ev.split(/\r\n|\r|\n/).filter((l) => l.startsWith("data:")).map((l) => l.slice(l.startsWith("data: ") ? 6 : 5)).join("\n")).filter((d) => d.trim()) : [text];
55
+ return raw.flatMap((m) => { try {
56
+ const v = JSON.parse(m);
57
+ return v && typeof v === "object" && !Array.isArray(v) ? [v] : [];
58
+ }
59
+ catch {
60
+ return [];
61
+ } });
62
+ }
63
+ /**
64
+ * An MCP client over HTTP: `url(connection)` is each connection's endpoint, `headers` the caller's credential. Each connection
65
+ * gets one session per process (initialize once, its mcp-session-id kept), then requests on it. A transport failure throws
66
+ * ToolError (401: the job ended; a status; a timeout), named by `tool` (the tool called, or the method).
67
+ */
68
+ export function mcp({ url, headers }) {
69
+ const sessions = new Map();
70
+ let ids = 0;
71
+ const failed = (connection, tool, e) => {
72
+ const err = e;
73
+ if (err.name === "TimeoutError" || err.name === "AbortError")
74
+ return new ToolError(connection, tool, "timeout", "no answer in time; the call is never sent again (a write may have happened)");
75
+ return new ToolError(connection, tool, "transport", `the gateway didn't answer (${err.message})`);
76
+ };
77
+ async function post(connection, tool, body, session, signal) {
78
+ let res, text;
79
+ try {
80
+ // A redirect is refused, never followed: the credential header stays with the gateway.
81
+ res = await fetch(url(connection), {
82
+ method: "POST", signal, redirect: "error",
83
+ headers: { ...headers, "content-type": "application/json", accept: "application/json, text/event-stream", "mcp-protocol-version": session?.protocol ?? PROTOCOL, ...(session?.id ? { "mcp-session-id": session.id } : {}) },
84
+ body: JSON.stringify({ jsonrpc: "2.0", ...body }),
85
+ });
86
+ // The deadline holds while the body is read too: a stalled answer is a timeout, never an empty one.
87
+ text = await res.text();
88
+ }
89
+ catch (e) {
90
+ throw failed(connection, tool, e);
91
+ }
92
+ if (res.status === 401)
93
+ throw new ToolError(connection, tool, "job-ended", "the job's token was refused: the job has ended");
94
+ // A session the connection no longer knows (404 on its id) goes: the next call starts a new one. This call is not sent again.
95
+ if (res.status === 404 && session?.id)
96
+ sessions.delete(connection);
97
+ if (!res.ok && res.status !== 202)
98
+ throw new ToolError(connection, tool, "transport", `the gateway answered ${res.status}: ${text.slice(0, 500)}`);
99
+ return { res, text };
100
+ }
101
+ function session(connection, signal) {
102
+ let s = sessions.get(connection);
103
+ if (!s) {
104
+ s = (async () => {
105
+ const init = ++ids;
106
+ const { res, text } = await post(connection, "initialize", { id: init, method: "initialize", params: { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: "aidenhq-tools", version: "1" } } }, undefined, signal);
107
+ // The version the connection chose is the session's: every later request carries it.
108
+ const chosen = messages(text, String(res.headers.get("content-type") ?? "").includes("text/event-stream")).find((m) => m.id === init)?.result?.protocolVersion;
109
+ const s = { protocol: typeof chosen === "string" && chosen ? chosen : PROTOCOL, ...(res.headers.get("mcp-session-id") ? { id: res.headers.get("mcp-session-id") } : {}) };
110
+ await post(connection, "initialize", { method: "notifications/initialized" }, s, signal);
111
+ return s;
112
+ })();
113
+ sessions.set(connection, s);
114
+ s.catch(() => sessions.delete(connection));
115
+ }
116
+ return s;
117
+ }
118
+ /** One request on the connection's session: its answer, or ToolError when none came. */
119
+ async function request(connection, method, params, { signal, tool = method }) {
120
+ const sid = await session(connection, signal);
121
+ const id = ++ids;
122
+ const { res, text } = await post(connection, tool, { id, method, params }, sid, signal);
123
+ const message = messages(text, String(res.headers.get("content-type") ?? "").includes("text/event-stream")).find((m) => m.id === id);
124
+ if (!message)
125
+ throw new ToolError(connection, tool, "transport", "the connection sent no answer");
126
+ const pending = res.headers.get("x-aidenhq-pending") ?? undefined;
127
+ return { message, ...(pending ? { pending } : {}) };
128
+ }
129
+ return { request };
130
+ }
131
+ const env = (name) => process.env[name] || (() => { throw new Error(`${name} is not set: tools are called from inside a job's computer`); })();
132
+ let box;
133
+ /** The job's own client: the gateway and run token from the box's environment. */
134
+ const client = () => (box ??= mcp({ url: (c) => new URL(`/c/${encodeURIComponent(c)}/mcp`, env("AIDENHQ_GATEWAY_URL")).href, headers: { "x-agent-key": env("AIDENHQ_RUN_TOKEN") } }));
135
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
136
+ /** How long a Tier 0 write still running is waited for before its record id is handed back. */
137
+ const WRITE_WAIT_MS = 10 * 60_000;
138
+ /** A write record as its job reads it (GET /v1/writes/<id>): its outcome fenced by the kernel as the live answer would be. */
139
+ async function record(connection, tool, id) {
140
+ const res = await fetch(new URL(`/v1/writes/${encodeURIComponent(id)}`, env("AIDENHQ_GATEWAY_URL")), { redirect: "error", headers: { authorization: `Bearer ${env("AIDENHQ_RUN_TOKEN")}` }, signal: AbortSignal.timeout(60_000) })
141
+ .catch((e) => { throw new ToolError(connection, tool, "transport", `the gateway didn't answer reading write ${id} (${e.message})`, id); });
142
+ if (!res.ok)
143
+ throw new ToolError(connection, tool, "transport", `reading write ${id} answered ${res.status}`, id);
144
+ return (await res.json());
145
+ }
146
+ /** A write the proxy marked pending: waiting on a decision throws ToolPending; a Tier 0 write still running is waited for. */
147
+ async function settle(connection, tool, id) {
148
+ for (const until = Date.now() + WRITE_WAIT_MS;;) {
149
+ const r = await record(connection, tool, id);
150
+ if (r.tier > 0 && (r.state === "review" || r.state === "owner" || r.state === "approved"))
151
+ throw new ToolPending(connection, tool, id, r.tier, r.state);
152
+ if (r.state === "done")
153
+ return { text: r.outcome?.text ?? "", images: [] };
154
+ if (r.state !== "approved" && r.state !== "claimed")
155
+ throw new ToolError(connection, tool, r.state, r.outcome?.text ?? r.reason ?? `the write ended ${r.state}`, id);
156
+ if (Date.now() > until)
157
+ throw new ToolError(connection, tool, "timeout", `write ${id} is still running after ${WRITE_WAIT_MS / 60_000} minutes. It is never sent again: don't repeat the call; its record id is ${id}`, id);
158
+ await sleep(1000);
159
+ }
160
+ }
161
+ /** Image blocks saved as files under the temp folder: their paths. */
162
+ function saveImages(content) {
163
+ const images = content.filter((c) => c?.type === "image" && typeof c.data === "string");
164
+ if (!images.length)
165
+ return [];
166
+ const dir = mkdtempSync(join(tmpdir(), "aidenhq-tool-"));
167
+ return images.map((c, i) => {
168
+ const file = join(dir, `image-${i + 1}.${String(c.mimeType ?? "image/png").split("/")[1]?.replace(/[^a-z0-9]/g, "") || "png"}`);
169
+ writeFileSync(file, Buffer.from(c.data, "base64"));
170
+ return file;
171
+ });
172
+ }
173
+ /**
174
+ * One tool of a connection, called once as this job. Resolves to its text and images; throws ToolError (a refusal, the tool's
175
+ * own error, a transport failure) or ToolPending (a write waiting on a decision). `timeoutS`: the connection's tool timeout + 30.
176
+ */
177
+ export async function call(connection, tool, args = {}, { timeoutS = 330 } = {}) {
178
+ const { message: m, pending } = await client().request(connection, "tools/call", { name: tool, arguments: args ?? {} }, { signal: AbortSignal.timeout(timeoutS * 1000), tool });
179
+ if (pending)
180
+ return settle(connection, tool, pending);
181
+ if (m.error) {
182
+ const msg = String(m.error.message ?? "");
183
+ if (REFUSALS.includes(msg))
184
+ throw new ToolError(connection, tool, msg, "the kernel's proxy refused this call: it decides each call by this job's grants, so this tool isn't yours to call now");
185
+ throw new ToolError(connection, tool, "tool-error", msg);
186
+ }
187
+ const content = Array.isArray(m.result?.content) ? m.result.content : [];
188
+ const text = content.filter((c) => c?.type === "text").map((c) => String(c.text ?? "")).join("\n");
189
+ if (m.result?.isError)
190
+ throw new ToolError(connection, tool, "tool-error", text || "the tool reported an error");
191
+ return { text, images: saveImages(content), ...(m.result?.structuredContent !== undefined ? { structured: m.result.structuredContent } : {}) };
192
+ }
@@ -29,6 +29,13 @@ export interface CardText {
29
29
  digest: string;
30
30
  requester: string;
31
31
  task: string;
32
+ /** A card waiting on the owner: its task's title, what was asked (`from`: the owner's own request a delegated task belongs to) and why it is his (kernel/src/card-context.ts). */
33
+ task_title?: string;
34
+ asked?: {
35
+ text: string;
36
+ from?: string;
37
+ } | null;
38
+ why?: string;
32
39
  }
33
40
  export interface JobSpec {
34
41
  contract: "engine@1";
@@ -42,11 +49,14 @@ export interface JobSpec {
42
49
  token_env: string;
43
50
  id: string;
44
51
  effort: string;
52
+ api: "chat" | "responses";
53
+ models?: string[];
45
54
  };
46
55
  mcp: {
47
56
  name: string;
48
57
  url: string;
49
- token_env: "AIDENHQ_JOB_TOKEN";
58
+ token_env: "AIDENHQ_RUN_TOKEN";
59
+ tools: string[];
50
60
  tool_timeout_s?: number;
51
61
  }[];
52
62
  env: string[];
@@ -55,11 +65,16 @@ export interface JobSpec {
55
65
  };
56
66
  web: boolean;
57
67
  state?: string;
68
+ tools?: {
69
+ dir: string;
70
+ index: string;
71
+ };
58
72
  sandbox: {
59
- kind: "bwrap" | "box";
73
+ kind: "box";
60
74
  writable: string[];
61
75
  network: boolean;
62
76
  };
77
+ budget_usd?: number;
63
78
  }
64
79
  export type EngineEvent = {
65
80
  t: "progress";
@@ -79,12 +94,23 @@ export type EngineEvent = {
79
94
  output: number;
80
95
  cached?: number;
81
96
  model: string;
97
+ cost_usd?: number;
82
98
  } | {
83
99
  t: "session";
84
100
  id: string;
85
101
  } | {
86
102
  t: "final";
87
103
  text: string;
104
+ vendor_error?: string;
105
+ } | {
106
+ t: "reply";
107
+ id: string;
108
+ text: string;
109
+ start?: number;
110
+ end?: number;
111
+ } | {
112
+ t: "turn";
113
+ busy: boolean;
88
114
  };
89
115
  export interface InboxLine {
90
116
  t: "comment";
@@ -0,0 +1,35 @@
1
+ /** The causes only the owner can fix. A vendor that is down or a rate limit is a plain error, never a need. */
2
+ export declare const OWNER_CAUSES: readonly ["not_connected", "expired", "scope", "sso", "restricted"];
3
+ export type Cause = (typeof OWNER_CAUSES)[number];
4
+ /** `detail`: one sentence for the owner. `scope`, `org`: what a partial cause is about. `url`: the vendor's own page (sso, restricted). */
5
+ export type Need = {
6
+ cause: Cause;
7
+ detail: string;
8
+ scope?: string;
9
+ org?: string;
10
+ url?: string;
11
+ account?: string;
12
+ };
13
+ /** The tool result a connection answers when only the owner can fix it. */
14
+ export declare function needsOwner(need: Need): {
15
+ isError: true;
16
+ content: [{
17
+ type: "text";
18
+ text: string;
19
+ }];
20
+ structuredContent: {
21
+ error: "needs_owner";
22
+ need: Need;
23
+ };
24
+ };
25
+ /**
26
+ * The `_meta` key a connection sets on a successful answer its sign-in served. Only such an answer clears the connection's down
27
+ * state in the kernel: a tool that works signed out (a prefilled link) proves nothing about the sign-in.
28
+ */
29
+ export declare const SIGNED_IN = "aidenhq/signed_in";
30
+ /** Marks a result as served by the connection's sign-in (SIGNED_IN); `account` names whose it was, for a multi-account one. */
31
+ export declare function signedIn<T extends object>(result: T, account?: string): T;
32
+ /** Whether a tools/call result is a success the connection's sign-in served. */
33
+ export declare function servedSignedIn(result: unknown): boolean;
34
+ /** The need in a tools/call result, if it is one; an unknown cause reads as not_connected. Only known string fields are kept. */
35
+ export declare function readNeed(result: unknown): Need | undefined;
@@ -0,0 +1,43 @@
1
+ // The one answer a connection gives when only the owner can fix why a call can't be served (spec 2026-11-20 connect on first
2
+ // use §1): an MCP isError result whose structuredContent is { error: "needs_owner", need }. The kernel's tool proxy reads it
3
+ // before fencing, records the connection as down, and decides who hears about it (the owner, in the conversation they asked
4
+ // in, or the daily digest); the agent gets the kernel's own fixed words, never this text. Import-free: first-party modules
5
+ // hold byte-identical copies (scripts/sync-shared.ts: edit this one and run it).
6
+ /** The causes only the owner can fix. A vendor that is down or a rate limit is a plain error, never a need. */
7
+ export const OWNER_CAUSES = ["not_connected", "expired", "scope", "sso", "restricted"];
8
+ /** The tool result a connection answers when only the owner can fix it. */
9
+ export function needsOwner(need) {
10
+ return { isError: true, content: [{ type: "text", text: need.detail }], structuredContent: { error: "needs_owner", need } };
11
+ }
12
+ /**
13
+ * The `_meta` key a connection sets on a successful answer its sign-in served. Only such an answer clears the connection's down
14
+ * state in the kernel: a tool that works signed out (a prefilled link) proves nothing about the sign-in.
15
+ */
16
+ export const SIGNED_IN = "aidenhq/signed_in";
17
+ /** Marks a result as served by the connection's sign-in (SIGNED_IN); `account` names whose it was, for a multi-account one. */
18
+ export function signedIn(result, account) {
19
+ const meta = result._meta;
20
+ return { ...result, _meta: { ...(meta && typeof meta === "object" ? meta : {}), [SIGNED_IN]: account || true } };
21
+ }
22
+ /** Whether a tools/call result is a success the connection's sign-in served. */
23
+ export function servedSignedIn(result) {
24
+ const r = result;
25
+ const v = r && typeof r === "object" && r.isError !== true && r._meta && typeof r._meta === "object" ? r._meta[SIGNED_IN] : undefined;
26
+ return v === true || (typeof v === "string" && !!v);
27
+ }
28
+ /** The need in a tools/call result, if it is one; an unknown cause reads as not_connected. Only known string fields are kept. */
29
+ export function readNeed(result) {
30
+ const r = result;
31
+ if (!r || typeof r !== "object" || r.isError !== true)
32
+ return undefined;
33
+ const s = r.structuredContent;
34
+ if (!s || typeof s !== "object" || s.error !== "needs_owner" || !s.need || typeof s.need !== "object")
35
+ return undefined;
36
+ const n = s.need;
37
+ const cause = OWNER_CAUSES.includes(n.cause) ? n.cause : "not_connected";
38
+ const out = { cause, detail: typeof n.detail === "string" ? n.detail : "" };
39
+ for (const k of ["scope", "org", "url", "account"])
40
+ if (typeof n[k] === "string")
41
+ out[k] = n[k];
42
+ return out;
43
+ }