@aidenhq/sdk 0.5.8 → 0.5.9

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 (71) hide show
  1. package/dist/assets/page-kit.js +13 -33
  2. package/dist/src/attribution.d.ts +0 -4
  3. package/dist/src/attribution.js +1 -9
  4. package/dist/src/box-bundle.d.ts +1 -5
  5. package/dist/src/box-bundle.js +2 -9
  6. package/dist/src/caller.d.ts +0 -2
  7. package/dist/src/caller.js +2 -6
  8. package/dist/src/checks.d.ts +9 -52
  9. package/dist/src/checks.js +10 -53
  10. package/dist/src/churn.d.ts +2 -12
  11. package/dist/src/churn.js +3 -17
  12. package/dist/src/closed-event.d.ts +0 -1
  13. package/dist/src/closed-event.js +1 -5
  14. package/dist/src/executor.d.ts +4 -7
  15. package/dist/src/executor.js +2 -8
  16. package/dist/src/face-kit.js +1 -4
  17. package/dist/src/fence.d.ts +2 -10
  18. package/dist/src/fence.js +4 -15
  19. package/dist/src/for-others.d.ts +0 -1
  20. package/dist/src/for-others.js +1 -5
  21. package/dist/src/instance-details.d.ts +1 -7
  22. package/dist/src/instance-details.js +4 -16
  23. package/dist/src/instance-paths.d.ts +1 -6
  24. package/dist/src/instance-paths.js +2 -11
  25. package/dist/src/judge.d.ts +3 -21
  26. package/dist/src/judge.js +5 -25
  27. package/dist/src/kernel-client.d.ts +0 -1
  28. package/dist/src/kernel-client.js +3 -12
  29. package/dist/src/kit.d.ts +0 -3
  30. package/dist/src/kit.js +0 -3
  31. package/dist/src/maintained-repos.d.ts +5 -22
  32. package/dist/src/maintained-repos.js +7 -23
  33. package/dist/src/number-setting.d.ts +0 -2
  34. package/dist/src/number-setting.js +1 -6
  35. package/dist/src/owner-day.d.ts +0 -4
  36. package/dist/src/owner-day.js +1 -8
  37. package/dist/src/paperclip.d.ts +0 -3
  38. package/dist/src/paperclip.js +1 -7
  39. package/dist/src/pass-rule.d.ts +0 -2
  40. package/dist/src/pass-rule.js +2 -10
  41. package/dist/src/provider.d.ts +1 -7
  42. package/dist/src/provider.js +2 -8
  43. package/dist/src/quality.d.ts +0 -10
  44. package/dist/src/quality.js +2 -12
  45. package/dist/src/repeat.d.ts +1 -6
  46. package/dist/src/repeat.js +2 -10
  47. package/dist/src/responses.d.ts +1 -8
  48. package/dist/src/responses.js +3 -13
  49. package/dist/src/selector.d.ts +1 -11
  50. package/dist/src/selector.js +1 -6
  51. package/dist/src/source-store.d.ts +4 -26
  52. package/dist/src/source-store.js +5 -30
  53. package/dist/src/task-state-types.d.ts +3 -18
  54. package/dist/src/task-state-types.js +1 -3
  55. package/dist/src/teammate-name.d.ts +0 -1
  56. package/dist/src/teammate-name.js +2 -6
  57. package/dist/src/tiers.d.ts +1 -11
  58. package/dist/src/tiers.js +4 -14
  59. package/dist/src/tools-client.d.ts +3 -13
  60. package/dist/src/tools-client.js +7 -28
  61. package/dist/src/types.d.ts +0 -2
  62. package/dist/src/types.js +1 -2
  63. package/dist/src/url-setting.d.ts +0 -1
  64. package/dist/src/url-setting.js +1 -4
  65. package/dist/src/vendor/needs.d.ts +1 -7
  66. package/dist/src/vendor/needs.js +3 -12
  67. package/dist/src/vendor/oauth.d.ts +6 -35
  68. package/dist/src/vendor/oauth.js +12 -37
  69. package/dist/src/vendor/proxy.d.ts +5 -27
  70. package/dist/src/vendor/proxy.js +42 -114
  71. package/package.json +1 -1
@@ -1,16 +1,9 @@
1
- // Shared sources (docs/design/sources.md): the writer side. Each source writer (slack-live,
2
- // github, jira, ops-mcp for meetings, google-workspace for docs) logs in to the warehouse as src_<source>, owns schema src_<source> (its module's
3
- // warehouse.sources entry; apps-mcp creates both) and writes through this: typed upserts that keep first_seen_at, bump src_meta.seq on any difference and
4
- // log tracked-field changes, a baseline flag for first syncs, per-scope sync state, and one src_meta.ingest_run per pass.
5
- // No LLM anywhere: ingest is code.
6
- //
7
- // Every module imports it from npm (@aidenhq/sdk/source-store) at an exact pin (pg is theirs: a peer dependency): a change here needs a version bump in package.json,
8
- // which is what publishes it.
1
+ // Shared sources (docs/design/sources.md): the writer side. Each source writer logs in to the warehouse as src_<source>, owns schema src_<source> (its module's warehouse.sources entry; apps-mcp creates both) and writes through this: typed upserts that keep first_seen_at, bump src_meta.seq on any difference and log tracked-field changes, a baseline flag for first syncs, per-scope sync state, one src_meta.ingest_run per pass. No LLM: ingest is code.
2
+ // Modules import it from npm (@aidenhq/sdk/source-store) at an exact pin (pg is a peer dependency): a change here needs a package.json version bump, which publishes it.
9
3
  import { readFileSync } from "node:fs";
10
4
  import pg from "pg";
11
5
  /** Long text is cut to about 4 KB by default; the row keeps a <field>_truncated flag and its url for the rest. */
12
6
  const TEXT_CAP = 4096;
13
- /** Text cut to `cap` bytes (whole characters), NULs dropped (Postgres text can't hold them). */
14
7
  export function capText(s, cap = TEXT_CAP) {
15
8
  if (s == null)
16
9
  return { text: null, truncated: false };
@@ -27,7 +20,6 @@ const ident = (s) => {
27
20
  throw new Error(`bad identifier ${s}`);
28
21
  return s;
29
22
  };
30
- /** CREATE TABLE for a source table: its columns plus the common ones every source row carries. */
31
23
  export function tableDdl(schema, t) {
32
24
  const cols = Object.entries(t.cols).map(([c, type]) => ` ${ident(c)} ${type}${t.key.includes(c) ? " NOT NULL" : ""}`);
33
25
  // 'simple': no stemming or stop words, so product names, codes and handles match as written.
@@ -42,7 +34,6 @@ ${tsv} baseline boolean NOT NULL DEFAULT false,
42
34
  );
43
35
  CREATE INDEX IF NOT EXISTS ${t.name}_seq ON ${schema}.${t.name} (seq);${tsv ? `\nCREATE INDEX IF NOT EXISTS ${t.name}_tsv ON ${schema}.${t.name} USING gin (tsv);` : ""}`;
44
36
  }
45
- /** Per-scope sync state and the change log: in every source schema. */
46
37
  function commonDdl(schema) {
47
38
  const s = ident(schema);
48
39
  return `CREATE TABLE IF NOT EXISTS ${s}.scope (
@@ -75,10 +66,7 @@ export class SourceStore {
75
66
  this.schema = ident(schema);
76
67
  this.pool = pool;
77
68
  }
78
- /**
79
- * The writer's store, or undefined while it can't be (no password file: the warehouse module or its secret is missing).
80
- * WAREHOUSE_HOST defaults to the warehouse app's container, reached on the `sources` network (compose.yaml), which no app joins.
81
- */
69
+ /** The writer's store, or undefined while it can't be (no password file). WAREHOUSE_HOST defaults to the warehouse app's container on the `sources` network (compose.yaml), which no app joins. */
82
70
  static fromEnv(source, env = process.env) {
83
71
  const file = env.WAREHOUSE_PASSWORD_FILE;
84
72
  let password = "";
@@ -95,7 +83,6 @@ export class SourceStore {
95
83
  pool.on("error", () => undefined); // idle-client errors surface on the next query
96
84
  return new SourceStore(role, pool);
97
85
  }
98
- /** Runs the writer's DDL once per process, serialised across processes by an advisory lock. */
99
86
  async migrate(ddl) {
100
87
  if (this.migrated)
101
88
  return;
@@ -118,21 +105,16 @@ export class SourceStore {
118
105
  const r = await this.pool.query(`SELECT baselined_at, cursor FROM ${this.schema}.scope WHERE scope = $1`, [scope]);
119
106
  return { baselined: !!r.rows[0]?.baselined_at, cursor: r.rows[0]?.cursor ?? null };
120
107
  }
121
- /** Every scope whose name starts with `prefix`, with when it was last saved (epoch ms): lets a pass pick the oldest-synced first. */
122
108
  async scopesByPrefix(prefix) {
123
109
  const r = await this.pool.query(`SELECT scope, baselined_at, cursor, updated_at FROM ${this.schema}.scope WHERE starts_with(scope, $1)`, [prefix]);
124
110
  return new Map(r.rows.map((x) => [x.scope, { baselined: !!x.baselined_at, cursor: x.cursor ?? null, syncedAt: new Date(x.updated_at).getTime() }]));
125
111
  }
126
- /** Saves a scope's cursor; `baselined` marks its first full pass done (only after it completed). */
127
112
  async saveScope(scope, cursor, baselined = false) {
128
113
  await this.pool.query(`INSERT INTO ${this.schema}.scope (scope, cursor, baselined_at) VALUES ($1, $2, CASE WHEN $3 THEN now() END)
129
114
  ON CONFLICT (scope) DO UPDATE SET cursor = COALESCE(EXCLUDED.cursor, ${this.schema}.scope.cursor),
130
115
  baselined_at = COALESCE(${this.schema}.scope.baselined_at, EXCLUDED.baselined_at), updated_at = now()`, [scope, cursor, baselined]);
131
116
  }
132
- /**
133
- * Insert or update one row by its key. New rows carry `baseline`; an existing row is rewritten only when a written
134
- * column differs (seq and ingested_at bumped), and its tracked differences go to the change log unless `baseline`.
135
- */
117
+ /** Insert or update one row by key: new rows carry `baseline`; an existing row is rewritten only when a written column differs (seq, ingested_at bumped), tracked differences logged unless `baseline`. */
136
118
  async upsert(t, row, o) {
137
119
  for (let attempt = 0;; attempt++) {
138
120
  const c = await this.pool.connect();
@@ -193,13 +175,7 @@ export class SourceStore {
193
175
  }
194
176
  return "changed";
195
177
  }
196
- /**
197
- * One ingest pass: records src_meta.ingest_run (rows = rows written with a difference) and rethrows a failure.
198
- * `commit` is the git HEAD a repo target was read at, when the pass covers a checkout. A pass that read a scope to its end and
199
- * got a reliable count of what the source holds for it (the API's total) says so on `pass.complete`: `total` (the source's count)
200
- * and `fetched` (distinct records the pass read). The Fleet Steward flags a scope whose completed passes keep fetching fewer.
201
- * A pass that stopped early, resumed mid-scope or whose API gives no total leaves it unset.
202
- */
178
+ /** One ingest pass: records src_meta.ingest_run (rows = rows written with a difference), rethrows failures. `commit`: the git HEAD a repo target was read at. A pass that read a scope to its end with a reliable total says so on `pass.complete` (`total`, `fetched`); the Fleet Steward flags scopes whose completed passes keep fetching fewer. Early-stopped, resumed or total-less passes leave it unset. */
203
179
  async run(source, scope, fn, meta = {}) {
204
180
  const started = new Date();
205
181
  let rows = 0;
@@ -220,7 +196,6 @@ export class SourceStore {
220
196
  }
221
197
  }
222
198
  }
223
- /** Top-level keys of two JSON objects whose values differ: [key, old, new]. */
224
199
  function jsonDiff(a, b) {
225
200
  const o = (a && typeof a === "object" ? a : {});
226
201
  const n = (b && typeof b === "object" ? b : {});
@@ -6,7 +6,6 @@ export type Attention = {
6
6
  ref: string; /** When what it names began (the board orders asks by it). */
7
7
  since: string;
8
8
  };
9
- /** The board's column for a task (its Agent work layout): one per task, from all its obligations (laneOf). */
10
9
  export type Lane = "needs_you" | "working" | "waiting" | "blocked" | "idle" | "done";
11
10
  export type TaskState = {
12
11
  kind: Kind;
@@ -18,33 +17,22 @@ export type TaskState = {
18
17
  lane: Lane;
19
18
  /** An open blocker (`task:<id>`), whatever the representative reason: a queued job or a wait can outrank it. */
20
19
  blocker?: string;
21
- /** A module stage's label, only while working or waiting. */
22
20
  stage?: string;
23
- /** The open owner or delegator wait's question (the ask gate reads it). */
24
21
  question?: string;
25
22
  /** What the open wait's question is about (notify's `detail`, e.g. the draft to send), beside the question. */
26
23
  detail?: string;
27
- /** When the open owner or delegator wait began, whatever the representative reason (only the owner's has a `question`). */
28
24
  wait_since?: string;
29
25
  /** The open owner or delegator wait's own deadline (`until`), so a retry of its question reuses the wait instead of re-arming it. */
30
26
  wait_until?: string;
31
- /** The open wait's own words (task_wait's reason). */
32
27
  note?: string;
33
- /** When the earliest open scheduled wake is due, whatever the representative reason. */
34
28
  scheduled_for?: string;
35
- /** The agent (id) an open delegator wait's question went to, when the wait recorded it. */
36
29
  waits_on?: string;
37
- /** An open delegator wait re-asking a question this task already had answered (it settled that episode): the Steward's incident
38
- * detector does not raise it again while this wait stands, and a genuinely new question carries none. */
30
+ /** An open delegator wait re-asking a question already answered: the Steward's incident detector does not raise it while this wait stands. */
39
31
  ask_settled?: true;
40
32
  /** When the task was last reopened (a status leaving done or cancelled), while it is open: a close needs evidence newer than this. */
41
33
  reopened_at?: string;
42
34
  };
43
- /**
44
- * `origin`: what created the task (`task.created` `data.origin`): a routine's `routine_execution`, a module's `module:<key>`,
45
- * or null for one a person or an agent made. `holder_name` and `holder_gone` name a holder Paperclip reports terminated (a
46
- * holder no grant maps stays its raw id).
47
- */
35
+ /** `origin`: what created the task (`task.created` `data.origin`): a routine's `routine_execution`, `module:<key>`, or null for a person or agent. `holder_name`/`holder_gone` name a holder Paperclip reports terminated (an unmapped holder stays its raw id). */
48
36
  export type StateRow = TaskState & {
49
37
  task: string;
50
38
  identifier: string | null;
@@ -62,10 +50,7 @@ export type StateRead = {
62
50
  unexplained_idle: number;
63
51
  };
64
52
  };
65
- /**
66
- * What the kernel's issue mirror last recorded of a task from Paperclip (GET /v1/tasks/issues): its identifier, title, status,
67
- * agent assignee (id), parent (id) and Paperclip's updatedAt. A task the kernel has never seen has no row.
68
- */
53
+ /** What the kernel's issue mirror last recorded of a task from Paperclip (GET /v1/tasks/issues); a task the kernel has never seen has no row. */
69
54
  export type IssueRow = {
70
55
  id: string;
71
56
  identifier: string | null;
@@ -1,4 +1,2 @@
1
- // A task's state as the kernel serves it (GET /v1/tasks/state): the one definition of its shape. The kernel computes it
2
- // (kernel/src/task-state.ts, task-state-read.ts); the board reads it through its copy (services/board/src/aidenhq-sdk/,
3
- // kept identical by scripts/sync-shared.ts). Types only: no imports, no code.
1
+ // A task's state as the kernel serves it (GET /v1/tasks/state): the one definition of its shape, computed in kernel/src/task-state.ts; the board reads it through its copy (scripts/sync-shared.ts). Types only: no imports, no code.
4
2
  export {};
@@ -1,4 +1,3 @@
1
- /** Why `name` can't be agent `key`'s name among `agents` (every compiled agent), or undefined when it can. */
2
1
  export declare function teammateNameProblem(name: unknown, key: string, agents: Record<string, {
3
2
  name: string;
4
3
  }>): string | undefined;
@@ -1,13 +1,9 @@
1
- // A teammate's name (its default in the module, or the owner's rename: overrides.agents.<key>.name): one rule for the
2
- // compiler (scripts/modules.ts), the board's settings change and the kernel's (a synced copy, scripts/sync-shared.ts).
3
- // The name must be addressable: chat's @name (services/board/src/chats.ts norm) and the task tools match every agent by
4
- // name or key, so it may not collide with any other agent's, hidden ones included. A task comment's @handle is the name
5
- // without its spaces (services/board/src/crew.ts mentionedAgents): letters, digits and - only, and unique too.
1
+ // A teammate's name (module default or the owner's rename, overrides.agents.<key>.name): one rule for the compiler (scripts/modules.ts), the board's settings change and the kernel's (synced copy, scripts/sync-shared.ts).
2
+ // It must be addressable: chat's @name (board chats.ts norm) and the task tools match agents by name or key, so it may not collide with any other agent's, hidden ones included; a task comment's @handle is the name without spaces (board crew.ts mentionedAgents): letters, digits and - only, and unique.
6
3
  const norm = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
7
4
  // One space between words: chat's @name parser takes a single separator.
8
5
  const SHAPE = /^[A-Za-z][A-Za-z0-9 -]{0,23}$/;
9
6
  const handle = (s) => s.replace(/\s+/g, "").toLowerCase();
10
- /** Why `name` can't be agent `key`'s name among `agents` (every compiled agent), or undefined when it can. */
11
7
  export function teammateNameProblem(name, key, agents) {
12
8
  if (typeof name !== "string" || !SHAPE.test(name) || name.trim() !== name || name.includes(" ") || name.split(" ").length > 4)
13
9
  return "a name is 1 to 24 letters, digits, spaces or -, at most 4 words";
@@ -1,6 +1,5 @@
1
1
  export declare const TIERS: readonly ["skip", "trivial", "standard", "sensitive"];
2
2
  export type Tier = (typeof TIERS)[number];
3
- /** A tier's rank: a higher one is riskier (what "loosening" compares). */
4
3
  export declare const RANK: Record<Tier, number>;
5
4
  export declare const REPO_CLASSES: readonly ["critical", "standard", "sandbox"];
6
5
  export type RepoClass = (typeof REPO_CLASSES)[number];
@@ -18,13 +17,10 @@ export declare const PROSE: string[];
18
17
  export declare const FOLDER_RULES: string[];
19
18
  /** The files that steer an agent (a reviewer reads them as guidance): prose, but never demoted. */
20
19
  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
20
  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
21
  export type Facts = {
25
22
  /** Substantive lines: additions plus deletions over every file but generated files and lockfiles. */
26
23
  lines: number;
27
- /** How many files count toward `lines`. */
28
24
  files: number;
29
25
  /** Every changed path, a rename's old path and generated files included. */
30
26
  paths: string[];
@@ -32,7 +28,6 @@ export type Facts = {
32
28
  base: string;
33
29
  repo_class: RepoClass;
34
30
  };
35
- /** One entry of GitHub's PR files list. */
36
31
  export type FileChange = {
37
32
  path: string;
38
33
  previous?: string;
@@ -47,8 +42,7 @@ export declare function factsOf(files: FileChange[], o: {
47
42
  base: string;
48
43
  repo_class: RepoClass;
49
44
  }): 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. */
45
+ /** Who opened the PR: the instance's own App is `own`, Dependabot and Renovate (exact logins, never from a fork) bots, an owner/member/collaborator a member; any other `*[bot]` is judged by association like a person. */
52
46
  export declare function authorKind(login: string, association: string | undefined, own?: boolean, fork?: boolean): AuthorKind;
53
47
  export type When = {
54
48
  lines_min?: number;
@@ -66,13 +60,10 @@ export type Rule = {
66
60
  tier: Tier;
67
61
  };
68
62
  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
63
  export declare const DEFAULT_RULES: Rule[];
71
- /** A rules list checked whole: the rules, or the first reason it isn't one. */
72
64
  export declare function parseRules(raw: unknown): Rule[] | {
73
65
  error: string;
74
66
  };
75
- /** The tier the first matching rule names, its index, and why in plain words. */
76
67
  export declare function classify(f: Facts, rules: Rule[]): {
77
68
  tier: Tier;
78
69
  rule: number;
@@ -84,5 +75,4 @@ export declare const tooMany: (n: number) => {
84
75
  rule: number;
85
76
  why: string;
86
77
  };
87
- /** The tiers a rules list can select: those some rule names. */
88
78
  export declare const selectable: (rules: Rule[]) => ("sensitive" | "skip" | "standard" | "trivial")[];
package/dist/src/tiers.js CHANGED
@@ -1,10 +1,7 @@
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.
1
+ // Risk tiers (docs/design/code-review.md): one tier per PR head from cheap facts about its own change, by a repo's ordered rules (first whose conditions all hold names it). No model call, no labels. Code review owns the rules; the CI template classifies with this same file.
2
+ // Dependency-free (node:path only): scripts/sync-shared.ts copies it into code review's service and recipe, the engineer image and the CI template.
5
3
  import { posix } from "node:path";
6
4
  export const TIERS = ["skip", "trivial", "standard", "sensitive"];
7
- /** A tier's rank: a higher one is riskier (what "loosening" compares). */
8
5
  export const RANK = { skip: 0, trivial: 1, standard: 2, sensitive: 3 };
9
6
  export const REPO_CLASSES = ["critical", "standard", "sandbox"];
10
7
  export const AUTHORS = ["member", "bot", "outsider"];
@@ -22,7 +19,6 @@ export const PROSE = ["docs/**/*.md", "docs/**/*.rst"]; // not mdx: it can run c
22
19
  export const FOLDER_RULES = ["modules/agent-anatomy.md", "modules/teammates.md"];
23
20
  /** The files that steer an agent (a reviewer reads them as guidance): prose, but never demoted. */
24
21
  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
22
  export const SENSITIVE = [
27
23
  ".github/**", "**/Dockerfile*", "**/package.json", ...INSTRUCTIONS, "**/.codex/**", "**/codex.toml", ...RISKY,
28
24
  ...LOCKS, "**/.eslintrc*", "**/eslint.config.*", "**/.oxlintrc*", "**/oxlint.config.*", "**/oxlint-plugin.*", "**/oxlint-suppressions.json", "**/vitest.config.*", "**/jest.config.*", "**/tsconfig*.json", "**/CODEOWNERS",
@@ -30,8 +26,7 @@ export const SENSITIVE = [
30
26
  ];
31
27
  /** A GitHub files list stops at this many files: a PR with more is sensitive, unread. */
32
28
  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. */
29
+ /** A path's segments without leading dot: glob wildcards skip dot-files, so `.github/**` would miss `.github/.release.yml`; each glob is also tried undotted. */
35
30
  const undot = (s) => s.replace(/(^|\/)\.(?=[^/])/g, "$1");
36
31
  export const matches = (path, globs) => globs.some((g) => posix.matchesGlob(path, g) || posix.matchesGlob(undot(path), undot(g)));
37
32
  export function factsOf(files, o) {
@@ -39,8 +34,7 @@ export function factsOf(files, o) {
39
34
  const paths = [...new Set(files.flatMap((f) => (f.previous && f.previous !== f.path ? [f.path, f.previous] : [f.path])))];
40
35
  return { lines: counted.reduce((n, f) => n + f.additions + f.deletions, 0), files: counted.length, paths, ...o };
41
36
  }
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. */
37
+ /** Who opened the PR: the instance's own App is `own`, Dependabot and Renovate (exact logins, never from a fork) bots, an owner/member/collaborator a member; any other `*[bot]` is judged by association like a person. */
44
38
  export function authorKind(login, association, own = false, fork = false) {
45
39
  if (own)
46
40
  return "member";
@@ -51,7 +45,6 @@ export function authorKind(login, association, own = false, fork = false) {
51
45
  const COUNTS = ["lines_min", "lines_max", "files_min", "files_max"];
52
46
  const GLOBS = ["paths", "only_paths", "base"];
53
47
  export const CONDITIONS = [...COUNTS, ...GLOBS, "author", "repo_class"];
54
- /** The default rules: the first that holds names the tier. */
55
48
  export const DEFAULT_RULES = [
56
49
  { when: { repo_class: "critical" }, tier: "sensitive" },
57
50
  { when: { author: "bot", only_paths: [...MANIFESTS, ...LOCKS] }, tier: "skip" },
@@ -65,7 +58,6 @@ export const DEFAULT_RULES = [
65
58
  { when: { author: "member", lines_max: 10, files_max: 20 }, tier: "trivial" },
66
59
  { tier: "standard" },
67
60
  ];
68
- /** A rules list checked whole: the rules, or the first reason it isn't one. */
69
61
  export function parseRules(raw) {
70
62
  if (!Array.isArray(raw) || !raw.length || raw.length > 100)
71
63
  return { error: "rules is a list of 1 to 100 { when?, tier }, the last with no when" };
@@ -124,7 +116,6 @@ const holds = (f, w) => (w.lines_min === undefined || f.lines >= w.lines_min) &&
124
116
  && (w.author === undefined || f.author === w.author)
125
117
  && (w.base === undefined || matches(f.base, w.base))
126
118
  && (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
119
  export function classify(f, rules) {
129
120
  const i = rules.findIndex((r) => !r.when || holds(f, r.when));
130
121
  const r = rules[i];
@@ -152,5 +143,4 @@ function why(f, w) {
152
143
  parts.push(`into ${f.base}`);
153
144
  return parts.join(", ");
154
145
  }
155
- /** The tiers a rules list can select: those some rule names. */
156
146
  export const selectable = (rules) => TIERS.filter((t) => rules.some((r) => r.tier === t));
@@ -1,15 +1,13 @@
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
1
  export interface ToolResult {
3
2
  text: string;
4
3
  images: string[];
5
4
  structured?: unknown;
6
5
  }
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. */
6
+ /** A call that didn't succeed (refused, tool error, transport failure). `record`: the write's record, if one was filed. */
8
7
  export declare class ToolError extends Error {
9
8
  connection: string;
10
9
  tool: string;
11
10
  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
11
  detail: string;
14
12
  record?: string;
15
13
  constructor(connection: string, tool: string, code: string, detail: string, record?: string);
@@ -31,16 +29,11 @@ type Message = {
31
29
  message?: string;
32
30
  };
33
31
  };
34
- /** One JSON-RPC answer: the message with this request's id, and the record id the proxy marks a pending write with. */
35
32
  export interface Answer {
36
33
  message: Message;
37
34
  pending?: string;
38
35
  }
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
- */
36
+ /** An MCP client over HTTP: `url(connection)` is each connection's endpoint, `headers` the caller's credential. One session per connection per process (initialize once, mcp-session-id kept). A transport failure throws ToolError (401: the job ended). */
44
37
  export declare function mcp({ url, headers }: {
45
38
  url: (connection: string) => string;
46
39
  headers: Record<string, string>;
@@ -50,10 +43,7 @@ export declare function mcp({ url, headers }: {
50
43
  tool?: string;
51
44
  }) => Promise<Answer>;
52
45
  };
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
- */
46
+ /** One tool of a connection, called once as this job: resolves to text and images; throws ToolError or ToolPending (a write waiting on a decision). `timeoutS`: the connection's tool timeout + 30. */
57
47
  export declare function call(connection: string, tool: string, args?: unknown, { timeoutS }?: {
58
48
  timeoutS?: number;
59
49
  }): Promise<ToolResult>;
@@ -1,23 +1,16 @@
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.
1
+ // The one MCP client a job's computer has (docs/design/sessions.md "Code mode"): generated tool files and the in-box `aidenhq` CLI call connections through it as the job: POST $AIDENHQ_GATEWAY_URL/c/<connection>/mcp with X-Agent-Key: $AIDENHQ_RUN_TOKEN, passed to the kernel's tool proxy, which decides every call (grants, fencing, tiers, write records); nothing is decided here.
2
+ // The kernel lists a job's tools at launch with the same client (`mcp`), straight to its proxy with the job token as bearer.
3
+ // A call is sent once and never replayed: a timeout, oversized result or needs-owner answer can all mean a write happened.
4
+ // Copied into the engineer image as /opt/aidenhq/lib/tools.ts (scripts/sync-shared.ts); Node runs it with type stripping, so erasable TypeScript only.
10
5
  import { mkdtempSync, writeFileSync } from "node:fs";
11
6
  import { tmpdir } from "node:os";
12
7
  import { join } from "node:path";
13
- /** The proxy's refusals: the tool isn't this job's to call. */
14
8
  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. */
9
+ /** A call that didn't succeed (refused, tool error, transport failure). `record`: the write's record, if one was filed. */
16
10
  export class ToolError extends Error {
17
11
  connection;
18
12
  tool;
19
13
  code;
20
- /** What went wrong, in the proxy's or the tool's own words (the message prefixed with the tool and code). */
21
14
  detail;
22
15
  record;
23
16
  constructor(connection, tool, code, detail, record) {
@@ -49,7 +42,6 @@ export class ToolPending extends Error {
49
42
  }
50
43
  }
51
44
  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
45
  function messages(text, sse) {
54
46
  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
47
  return raw.flatMap((m) => { try {
@@ -60,11 +52,7 @@ function messages(text, sse) {
60
52
  return [];
61
53
  } });
62
54
  }
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
- */
55
+ /** An MCP client over HTTP: `url(connection)` is each connection's endpoint, `headers` the caller's credential. One session per connection per process (initialize once, mcp-session-id kept). A transport failure throws ToolError (401: the job ended). */
68
56
  export function mcp({ url, headers }) {
69
57
  const sessions = new Map();
70
58
  let ids = 0;
@@ -104,7 +92,6 @@ export function mcp({ url, headers }) {
104
92
  s = (async () => {
105
93
  const init = ++ids;
106
94
  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
95
  const chosen = messages(text, String(res.headers.get("content-type") ?? "").includes("text/event-stream")).find((m) => m.id === init)?.result?.protocolVersion;
109
96
  const s = { protocol: typeof chosen === "string" && chosen ? chosen : PROTOCOL, ...(res.headers.get("mcp-session-id") ? { id: res.headers.get("mcp-session-id") } : {}) };
110
97
  await post(connection, "initialize", { method: "notifications/initialized" }, s, signal);
@@ -115,7 +102,6 @@ export function mcp({ url, headers }) {
115
102
  }
116
103
  return s;
117
104
  }
118
- /** One request on the connection's session: its answer, or ToolError when none came. */
119
105
  async function request(connection, method, params, { signal, tool = method }) {
120
106
  const sid = await session(connection, signal);
121
107
  const id = ++ids;
@@ -130,12 +116,10 @@ export function mcp({ url, headers }) {
130
116
  }
131
117
  const env = (name) => process.env[name] || (() => { throw new Error(`${name} is not set: tools are called from inside a job's computer`); })();
132
118
  let box;
133
- /** The job's own client: the gateway and run token from the box's environment. */
134
119
  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
120
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
136
121
  /** How long a Tier 0 write still running is waited for before its record id is handed back. */
137
122
  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
123
  async function record(connection, tool, id) {
140
124
  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
125
  .catch((e) => { throw new ToolError(connection, tool, "transport", `the gateway didn't answer reading write ${id} (${e.message})`, id); });
@@ -143,7 +127,6 @@ async function record(connection, tool, id) {
143
127
  throw new ToolError(connection, tool, "transport", `reading write ${id} answered ${res.status}`, id);
144
128
  return (await res.json());
145
129
  }
146
- /** A write the proxy marked pending: waiting on a decision throws ToolPending; a Tier 0 write still running is waited for. */
147
130
  async function settle(connection, tool, id) {
148
131
  for (const until = Date.now() + WRITE_WAIT_MS;;) {
149
132
  const r = await record(connection, tool, id);
@@ -158,7 +141,6 @@ async function settle(connection, tool, id) {
158
141
  await sleep(1000);
159
142
  }
160
143
  }
161
- /** Image blocks saved as files under the temp folder: their paths. */
162
144
  function saveImages(content) {
163
145
  const images = content.filter((c) => c?.type === "image" && typeof c.data === "string");
164
146
  if (!images.length)
@@ -170,10 +152,7 @@ function saveImages(content) {
170
152
  return file;
171
153
  });
172
154
  }
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
- */
155
+ /** One tool of a connection, called once as this job: resolves to text and images; throws ToolError or ToolPending (a write waiting on a decision). `timeoutS`: the connection's tool timeout + 30. */
177
156
  export async function call(connection, tool, args = {}, { timeoutS = 330 } = {}) {
178
157
  const { message: m, pending } = await client().request(connection, "tools/call", { name: tool, arguments: args ?? {} }, { signal: AbortSignal.timeout(timeoutS * 1000), tool });
179
158
  if (pending)
@@ -1,10 +1,8 @@
1
- /** A module's `providers.executor` (spec §3.3.2): its write kinds' executor endpoint and the secret the kernel calls it with. */
2
1
  export interface ExecutorDecl {
3
2
  contract: "executor@1";
4
3
  url: string;
5
4
  auth: string;
6
5
  }
7
- /** A module's `providers.reviewer` (spec §3.3.3; reviewer.ts): its review endpoint and the secret the kernel calls it with. */
8
6
  export interface ReviewerDecl {
9
7
  contract: "reviewer@1";
10
8
  url: string;
package/dist/src/types.js CHANGED
@@ -1,4 +1,3 @@
1
- // The public contract types (spec §3.3.1). engine@1 minor additions are marked "minor": optional for engines, always
2
- // written by the runner.
1
+ // The public contract types (spec §3.3.1). engine@1 additions marked "minor": optional for engines, always written by the runner.
3
2
  export {};
4
3
  // exit code: 0 = turn done; non-zero = failed (the runner reports, the requesting module decides retries)
@@ -1,5 +1,4 @@
1
1
  export declare const URL_MAX = 500;
2
- /** Whether `host` matches `pattern`: exact, or `*.example.com` for any subdomain of example.com (not example.com itself). */
3
2
  export declare function hostMatches(host: string, pattern: string): boolean;
4
3
  /** Why `value` can't be this setting's URL, or null when it can. An empty value means not set, and is fine. */
5
4
  export declare function urlSettingProblem(value: unknown, host?: string): string | null;
@@ -1,10 +1,7 @@
1
- // A URL setting (module.yaml `type: url`, optional `host:` pattern): one check for the board (the owner's feedback as he
2
- // types) and the compiler (the gate: an agent writes the commit). Plain TypeScript Node runs as is (scripts/modules.ts
3
- // imports this file directly); the board holds a synced copy (scripts/sync-shared.ts). docs/design/settings-changes.md.
1
+ // A URL setting (module.yaml `type: url`, optional `host:` pattern): one check for the board (live feedback) and the compiler (the gate). Plain TypeScript Node runs as is (scripts/modules.ts imports it); the board holds a synced copy (scripts/sync-shared.ts). docs/design/settings-changes.md.
4
2
  /** Query parameters whose name says they carry a credential: those belong in the vault, never in a setting. */
5
3
  const SECRET_PARAM = /token|key|secret|sig|password|passwd|auth|code|session|credential/i;
6
4
  export const URL_MAX = 500;
7
- /** Whether `host` matches `pattern`: exact, or `*.example.com` for any subdomain of example.com (not example.com itself). */
8
5
  export function hostMatches(host, pattern) {
9
6
  const h = host.toLowerCase();
10
7
  const p = pattern.toLowerCase();
@@ -10,7 +10,6 @@ export type Need = {
10
10
  url?: string;
11
11
  account?: string;
12
12
  };
13
- /** The tool result a connection answers when only the owner can fix it. */
14
13
  export declare function needsOwner(need: Need): {
15
14
  isError: true;
16
15
  content: [{
@@ -22,14 +21,9 @@ export declare function needsOwner(need: Need): {
22
21
  need: Need;
23
22
  };
24
23
  };
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
- */
24
+ /** The `_meta` key set on a successful answer its sign-in served: only such an answer clears the connection's down state (a tool that works signed out proves nothing). */
29
25
  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
26
  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
27
  export declare function servedSignedIn(result: unknown): boolean;
34
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. */
35
29
  export declare function readNeed(result: unknown): Need | undefined;
@@ -1,25 +1,16 @@
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; every module imports it from
5
- // npm (@aidenhq/sdk/vendor/needs) at an exact pin.
1
+ // The one answer a connection gives when only the owner can fix why a call can't be served: an MCP isError result with structuredContent { error: "needs_owner", need }. The kernel's tool proxy reads it before fencing, records the connection down and decides who hears (the owner in the conversation, or the digest); the agent gets the kernel's fixed words, never this text.
2
+ // Import-free; modules import it from npm (@aidenhq/sdk/vendor/needs) at an exact pin.
6
3
  /** The causes only the owner can fix. A vendor that is down or a rate limit is a plain error, never a need. */
7
4
  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
5
  export function needsOwner(need) {
10
6
  return { isError: true, content: [{ type: "text", text: need.detail }], structuredContent: { error: "needs_owner", need } };
11
7
  }
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
- */
8
+ /** The `_meta` key set on a successful answer its sign-in served: only such an answer clears the connection's down state (a tool that works signed out proves nothing). */
16
9
  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
10
  export function signedIn(result, account) {
19
11
  const meta = result._meta;
20
12
  return { ...result, _meta: { ...(meta && typeof meta === "object" ? meta : {}), [SIGNED_IN]: account || true } };
21
13
  }
22
- /** Whether a tools/call result is a success the connection's sign-in served. */
23
14
  export function servedSignedIn(result) {
24
15
  const r = result;
25
16
  const v = r && typeof r === "object" && r.isError !== true && r._meta && typeof r._meta === "object" ? r._meta[SIGNED_IN] : undefined;