@staix/agent-hub 0.43.0 → 0.45.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 (118) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +3 -8
  3. package/docs/agent-notes/adapters.md +2 -2
  4. package/docs/agent-notes/daemon.md +4 -4
  5. package/docs/agent-notes/local-worker.md +2 -1
  6. package/docs/agent-notes/security-review.md +1 -1
  7. package/docs/agent-notes/tasks.md +5 -2
  8. package/docs/agent-notes/tests.md +4 -3
  9. package/docs/design/adapters.md +4 -2
  10. package/docs/design/agent-hub-architecture.md +2 -0
  11. package/docs/design/agent-hub.md +1 -1
  12. package/docs/design/roadmap.md +75 -2
  13. package/docs/design/supervision.md +34 -2
  14. package/docs/design/task-board.md +36 -2
  15. package/docs/dogfood.md +20 -5
  16. package/docs/events.md +9 -3
  17. package/docs/influences.md +7 -0
  18. package/docs/memory.md +4 -4
  19. package/docs/operations.md +84 -31
  20. package/docs/quickstart.md +14 -2
  21. package/docs/research.md +18 -0
  22. package/docs/roadmap.json +4 -0
  23. package/docs/roadmap.md +9 -0
  24. package/docs/sdlc.md +19 -4
  25. package/docs/security.md +4 -4
  26. package/docs/verification/2026-11-11-supervision-pilot-1221.md +864 -0
  27. package/docs/verification/2026-11-19-0.44.0.md +60 -0
  28. package/docs/verification/2026-11-19-claude-implementer-2.1.328.md +49 -0
  29. package/docs/verification/2026-11-20-claude-implementer-2.1.329.md +49 -0
  30. package/docs/verification/2026-11-20-sdlc-metrics-diagnosis.md +7 -0
  31. package/docs/verification/2026-11-21-0.45.0.md +69 -0
  32. package/docs/verification/2026-11-22-codex-0171-reviewer-isolation.md +47 -0
  33. package/docs/verified.json +32 -26
  34. package/package.json +2 -2
  35. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  36. package/plugins/agent-hub/kimi-hook.js +585 -264
  37. package/plugins/agent-hub/kimi-review-policy-worker.js +5 -5
  38. package/plugins/agent-hub/server.js +629 -293
  39. package/scripts/check-docs.mjs +9 -1
  40. package/src/adapters/acp.ts +11 -1
  41. package/src/adapters/compat.ts +3 -3
  42. package/src/adapters/definitions/builtin-metadata.ts +2 -2
  43. package/src/adapters/definitions/native-context.ts +10 -0
  44. package/src/adapters/jcode.ts +10 -0
  45. package/src/adapters/local-worker.ts +3 -2
  46. package/src/adapters/pi.ts +15 -4
  47. package/src/cli/console-state.ts +3 -1
  48. package/src/cli/help.ts +3 -1
  49. package/src/cli/identity.ts +2 -1
  50. package/src/cli/main.ts +12 -6
  51. package/src/cli/output.ts +2 -2
  52. package/src/cli/recovery-package.ts +16 -3
  53. package/src/cli/roadmap-write.ts +59 -0
  54. package/src/cli/roadmap.ts +81 -4
  55. package/src/cli/sdlc-output.ts +11 -1
  56. package/src/cli/upgrade-runtime.ts +10 -6
  57. package/src/cli/upgrade.ts +9 -3
  58. package/src/hub/agent-mem-range.ts +43 -0
  59. package/src/hub/board.ts +116 -2
  60. package/src/hub/bus.ts +4 -0
  61. package/src/hub/check-runner.ts +25 -1
  62. package/src/hub/claude-shell-wrapper.ts +2 -1
  63. package/src/hub/config-apply.ts +4 -2
  64. package/src/hub/config-trust.ts +1 -1
  65. package/src/hub/context-window.ts +1 -1
  66. package/src/hub/control-write-trace.ts +39 -2
  67. package/src/hub/cost-governance.ts +11 -7
  68. package/src/hub/daemon.ts +318 -53
  69. package/src/hub/dogfood-read.ts +4 -2
  70. package/src/hub/edit-guard.ts +100 -0
  71. package/src/hub/events.ts +79 -8
  72. package/src/hub/facts.ts +85 -2
  73. package/src/hub/hub-tools.ts +3 -1
  74. package/src/hub/lifecycle.ts +6 -1
  75. package/src/hub/log-rotation.ts +130 -0
  76. package/src/hub/memory-profile.ts +137 -21
  77. package/src/hub/no-writes.ts +1 -0
  78. package/src/hub/operational-authority.ts +3 -2
  79. package/src/hub/operational-settings.ts +2 -2
  80. package/src/hub/quota-events.ts +40 -0
  81. package/src/hub/recovery-store.ts +70 -24
  82. package/src/hub/report.ts +1 -1
  83. package/src/hub/research-experiments.ts +132 -0
  84. package/src/hub/research-quality.ts +13 -3
  85. package/src/hub/research-record.ts +38 -2
  86. package/src/hub/research.ts +128 -28
  87. package/src/hub/restart.ts +49 -2
  88. package/src/hub/roadmap-check.ts +65 -0
  89. package/src/hub/roadmap-decompose.ts +80 -0
  90. package/src/hub/roadmap-export.ts +27 -0
  91. package/src/hub/roadmap-sync.ts +97 -0
  92. package/src/hub/roadmap.ts +40 -0
  93. package/src/hub/runtime-capture-prune.ts +9 -1
  94. package/src/hub/runtime-prune-health.ts +5 -1
  95. package/src/hub/sdlc-branch-ci.ts +128 -0
  96. package/src/hub/sdlc-merge.ts +12 -5
  97. package/src/hub/sdlc-metrics.ts +33 -10
  98. package/src/hub/sdlc.ts +90 -10
  99. package/src/hub/settings.ts +1 -0
  100. package/src/hub/snapshots.ts +56 -1
  101. package/src/hub/startup-event-seeds.ts +21 -15
  102. package/src/hub/startup-timing.ts +3 -1
  103. package/src/hub/supervision-proposals.ts +10 -2
  104. package/src/hub/supervision-rules.ts +27 -4
  105. package/src/hub/supervision.ts +7 -0
  106. package/src/hub/task-pr.ts +47 -0
  107. package/src/hub/task-shell-command.ts +124 -0
  108. package/src/hub/task-worktree.ts +18 -11
  109. package/src/hub/tasks.ts +617 -45
  110. package/src/hub/usage-rollup.ts +35 -20
  111. package/src/hub/worktree-shelf.ts +2 -1
  112. package/src/local/sandbox.ts +2 -1
  113. package/src/local/shell-environment.ts +6 -0
  114. package/src/local/tools.ts +13 -1
  115. package/src/memory/brief.ts +10 -1
  116. package/src/memory/client.ts +3 -2
  117. package/src/pi/extension.ts +15 -3
  118. package/src/pi/tool-receipts.ts +26 -0
@@ -1,6 +1,7 @@
1
1
  import type { Database } from "./db-schema.ts";
2
2
  import { openHubDatabase } from "./db-schema.ts";
3
- import { closeSync, existsSync, fstatSync, openSync, readSync } from "node:fs";
3
+ import { closeSync, fstatSync, openSync, readSync } from "node:fs";
4
+ import { segmentsOf, streamEnd } from "./log-rotation.ts";
4
5
 
5
6
  /**
6
7
  * The usage roll-up (#683 U2): `events.jsonl` folded into `hub.db`, so a view never rescans the whole log.
@@ -103,30 +104,44 @@ export class UsageRollup {
103
104
  poll(maxMs = 20): { bytes: number; done: boolean } {
104
105
  const deadline = performance.now() + Math.max(0, Math.min(20, maxMs));
105
106
  if (this.closed) return { bytes: 0, done: true };
106
- if (!existsSync(this.eventsFile)) return { bytes: 0, done: true };
107
- const fd = openSync(this.eventsFile, "r");
107
+ // #1546: the log is the rotated segments plus the live file, one byte stream; the stored offset is a position in that stream, so it survives a rotation unchanged.
108
+ const segments = segmentsOf(this.eventsFile);
109
+ if (!segments.length) return { bytes: 0, done: true };
110
+ const end = streamEnd(segments);
111
+ let { offset } = this.state();
112
+ if (end < offset) { this.reset(); offset = 0; }
113
+ if (end === offset) return { bytes: 0, done: true };
114
+ // Kept history starts at the oldest segment: bytes below it were dropped by retention after the roll-up folded them (or, on a first fold, never will be).
115
+ if (offset < segments[0]!.start) {
116
+ const first = segments[0]!.start;
117
+ const moved = this.db.transaction(() => { if (this.state().offset !== offset) return false; this.db.query("UPDATE rollup_state SET byte_offset = ? WHERE id = 1").run(first); return true; }).immediate();
118
+ return { bytes: 0, done: !moved ? false : first >= end };
119
+ }
120
+ const segment = segments.find(candidate => offset < candidate.start + candidate.size)!;
121
+ const base = segment.start, local = offset - base;
122
+ const fd = openSync(segment.path, "r");
108
123
  try {
109
124
  const size = fstatSync(fd).size;
110
- let { offset } = this.state();
111
- if (size < offset) { this.reset(); offset = 0; }
112
- if (size === offset) return { bytes: 0, done: true };
125
+ if (size === local) return { bytes: 0, done: true };
113
126
  // The cap bounds a pass, but one line is never split: a line longer than the cap makes this pass read on, up to MAX_LINE_BYTES, until it
114
127
  // holds a whole line, so a single large event can never stall the roll-up. A line past that bound is skipped as corrupt.
115
- let want = Math.min(size - offset, this.opts.maxBytesPerPass ?? DEFAULT_MAX_BYTES), buffer: Buffer, got = 0, end = -1;
128
+ let want = Math.min(size - local, this.opts.maxBytesPerPass ?? DEFAULT_MAX_BYTES), buffer: Buffer, got = 0, last = -1;
116
129
  for (;;) {
117
130
  buffer = Buffer.alloc(want); got = 0;
118
- while (got < want) { const n = readSync(fd, buffer, got, want - got, offset + got); if (!n) break; got += n; }
119
- end = buffer.subarray(0, got).lastIndexOf(0x0a);
120
- if (end >= 0 || offset + want >= size) break; // a whole line, or the end of the file (a line still being written)
131
+ while (got < want) { const n = readSync(fd, buffer, got, want - got, local + got); if (!n) break; got += n; }
132
+ last = buffer.subarray(0, got).lastIndexOf(0x0a);
133
+ if (last >= 0 || local + want >= size) break; // a whole line, or the end of the file (a line still being written)
121
134
  if (want >= MAX_LINE_BYTES) { // an unbounded line: skip what was read up to the next newline
122
- const next = this.skipLongLine(fd, offset, size);
135
+ const next = this.skipLongLine(fd, local, size);
123
136
  if (next === undefined) return { bytes: 0, done: true };
124
- const moved = this.db.transaction(() => { if (this.state().offset !== offset) return false; this.db.query("UPDATE rollup_state SET byte_offset = ? WHERE id = 1").run(next); return true; }).immediate();
125
- return moved ? { bytes: next - offset, done: next >= size } : { bytes: 0, done: false };
137
+ const moved = this.db.transaction(() => { if (this.state().offset !== offset) return false; this.db.query("UPDATE rollup_state SET byte_offset = ? WHERE id = 1").run(base + next); return true; }).immediate();
138
+ return moved ? { bytes: next - local, done: base + next >= end } : { bytes: 0, done: false };
126
139
  }
127
- want = Math.min(size - offset, want * 2);
140
+ want = Math.min(size - local, want * 2);
128
141
  }
129
- if (end < 0) return { bytes: 0, done: true }; // the last line is still being written: it waits for the next pass
142
+ // A rotated segment always ends in a newline; one that does not (a hand-made file) is folded to its end rather than stalling the stream.
143
+ if (last < 0 && !segment.live && local + got >= size) last = got - 1;
144
+ if (last < 0) return { bytes: 0, done: true }; // the last line is still being written: it waits for the next pass
130
145
  let consumed = 0;
131
146
  // The offset was read before the slice was; another roll-up on this hub.db (a restart that overlaps the old process) may have folded the same
132
147
  // bytes since. The transaction takes the write lock first and checks the stored offset again: a pass whose start is stale is abandoned whole,
@@ -136,18 +151,18 @@ export class UsageRollup {
136
151
  // Commit only complete processed records with their offset. Yield between records;
137
152
  // ponytail: one whole record and the existing corrupt-line skip are indivisible;
138
153
  // a streaming parser would be needed to preempt within either operation.
139
- for (let start = 0; start <= end;) {
140
- const newline = buffer.indexOf(0x0a, start);
141
- if (newline < 0 || newline > end) break;
154
+ for (let start = 0; start <= last;) {
155
+ let newline = buffer.indexOf(0x0a, start);
156
+ if (newline < 0 || newline > last) { if (newline < 0 && start <= last) newline = last + 1; else break; }
142
157
  this.fold(buffer.subarray(start, newline).toString("utf8"));
143
- consumed = newline + 1; start = consumed;
158
+ consumed = Math.min(newline + 1, got); start = consumed;
144
159
  if (performance.now() >= deadline) break;
145
160
  }
146
161
  this.db.query("UPDATE rollup_state SET byte_offset = ? WHERE id = 1").run(offset + consumed);
147
162
  return true;
148
163
  }).immediate();
149
164
  if (!applied) return { bytes: 0, done: false }; // stale: the next pass starts from the stored offset
150
- return { bytes: consumed, done: offset + consumed >= size };
165
+ return { bytes: consumed, done: offset + consumed >= end };
151
166
  } finally { closeSync(fd); }
152
167
  }
153
168
 
@@ -113,7 +113,8 @@ export function boundTask(tasks: readonly Pick<Task, "id" | "state" | "refs" | "
113
113
  * action, which reads GitHub, may learn `closed` or `open` (a later change).
114
114
  */
115
115
  export function prFromTask(task: Pick<Task, "state" | "sdlc" | "history"> | undefined, observed?: PrObserver): WorktreeFact["pr"] {
116
- const merge = task?.sdlc?.merge;
116
+ const guarded = task?.sdlc?.merge;
117
+ const merge = guarded?.state === "merged" ? guarded : task?.sdlc?.mergeReadback;
117
118
  if (merge && merge.state === "merged" && Number.isFinite(merge.at)) return { state: "merged", changedAt: merge.at };
118
119
  // A PR state the person asked the hub to read (the explicit refresh action) is a stored fact, never fetched here: this module has no GitHub access (AC5).
119
120
  const repo = task?.sdlc?.repo, pr = task?.sdlc?.pr;
@@ -6,6 +6,7 @@ import { realPath } from "../hub/project.ts";
6
6
  import { hubGitSync } from "../hub/git.ts";
7
7
  import { denyRegexes, hubWriteRegexes, objectStoreRules, sbplString } from "./deny.ts";
8
8
  import { stopOwnedProcess, trackGroup } from "../hub/child-process.ts";
9
+ import { sandboxCommandEnvironment } from "./shell-environment.ts";
9
10
 
10
11
  const SANDBOX_EXEC = "/usr/bin/sandbox-exec";
11
12
  export const OUTPUT_CAP = 20_000;
@@ -216,7 +217,7 @@ export function sandboxedExec(argv: string[], opts: { cwd: string; profile: stri
216
217
  const own = realPath(mkdtempSync(join(tmpdir(), "ahub-cmd-")));
217
218
  const sandbox = `${opts.profile}\n(allow file-read* ${opts.readOnlyData ? "" : "file-write* "}process-exec (subpath ${q(own)}))`;
218
219
  // A path-only deny cannot contain hardlink aliases; data mode allows reads/stdout, never filesystem writes.
219
- const env = { PATH: process.env.PATH ?? "/usr/bin:/bin", HOME: homedir(), LANG: process.env.LANG ?? "en_US.UTF-8", TERM: "dumb", ...opts.env, TMPDIR: `${own}/` };
220
+ const env = sandboxCommandEnvironment({ PATH: process.env.PATH ?? "/usr/bin:/bin", HOME: homedir(), LANG: process.env.LANG ?? "en_US.UTF-8", TERM: "dumb", ...opts.env }, own);
220
221
  // Own process group: a timeout has to take the grandchildren too, or they keep the pipes open and the project writable.
221
222
  const child = spawn(SANDBOX_EXEC, ["-p", sandbox, ...argv], { cwd: opts.cwd, env, stdio: ["ignore", "pipe", "pipe"], detached: true });
222
223
  let output = "";
@@ -1,4 +1,5 @@
1
1
  import { homedir } from "node:os";
2
+ import { join } from "node:path";
2
3
 
3
4
  export interface HostShellEnvironment extends Record<string, string> { PATH: string; HOME: string; LANG: string; TERM: string }
4
5
 
@@ -8,3 +9,8 @@ export interface HostShellEnvironment extends Record<string, string> { PATH: str
8
9
  export function hostShellEnvironment(extra: Readonly<Record<string, string>> = {}): HostShellEnvironment {
9
10
  return { PATH: process.env.PATH ?? "/usr/bin:/bin", HOME: homedir(), LANG: process.env.LANG ?? "en_US.UTF-8", TERM: "dumb", ...extra };
10
11
  }
12
+
13
+ /** Per-command cache defaults are confined to the same owned temp directory as TMPDIR. */
14
+ export function sandboxCommandEnvironment(base: Readonly<Record<string, string>>, own: string): Record<string, string> {
15
+ return { BUN_INSTALL_CACHE_DIR: join(own, "bun-cache"), NPM_CONFIG_CACHE: join(own, "npm-cache"), ...base, TMPDIR: `${own}/` };
16
+ }
@@ -100,6 +100,8 @@ export interface ToolContext {
100
100
  permit: (title: string, tool?: string, signal?: AbortSignal, canonicalTarget?: string, observe?: ApprovalObserver, originalPath?: string, input?: unknown, policy?: ShellPermitPolicy) => Promise<ToolApproval>;
101
101
  /** Host-only synchronous recheck, immediately before a shell process can be spawned. */
102
102
  shellExecutionCheck?: (input: unknown) => ShellExecutionCheck;
103
+ /** Host-owned guard: absent unless an admitted edit policy is active. */
104
+ editGuard?: { read(file: string, bytes: Buffer, full: boolean): void; write(file: string): boolean | undefined; written(file: string, unverified: boolean | undefined): void; shell(command: string): (() => void) | undefined };
103
105
  /** #515: present only when the project opted in (`local.doc_read`), so `doc_read` exists for this worker and nothing else gets it. `pii`: this turn is a PII task turn. */
104
106
  docRead?: DocReadPort & { pii: boolean };
105
107
  /** #515b: present only when the project opted in (`local.web_fetch.allow` names a host), so `web_fetch` exists for this worker and nothing else gets it. `pii`: this turn is a PII task turn, for which it is refused. */
@@ -273,9 +275,11 @@ export async function runTool(name: string, rawArgs: string, ctx: ToolContext):
273
275
  case "read": {
274
276
  const file = guardPath(ctx, String(a.path), "read");
275
277
  if (statSync(file).size > 5_000_000) return "error: file is larger than 5 MB; use bash (head, grep, sed -n) to look at parts of it";
276
- const lines = readFileSync(file, "utf8").split("\n");
278
+ const bytes = readFileSync(file);
279
+ const lines = bytes.toString("utf8").split("\n");
277
280
  const from = Math.max(1, Number(a.offset) || 1);
278
281
  const out = lines.slice(from - 1, from - 1 + (Number(a.limit) || 2000)).map((l, i) => `${from + i}\t${l}`).join("\n");
282
+ ctx.editGuard?.read(file, bytes, a.offset === undefined && a.limit === undefined && out.split("\n").length === lines.length && out.length <= OUTPUT_CAP);
279
283
  return out.length > OUTPUT_CAP ? `${out.slice(0, OUTPUT_CAP)}\n(truncated: read again with offset/limit)` : out;
280
284
  }
281
285
  case "write": {
@@ -296,8 +300,11 @@ export async function runTool(name: string, rawArgs: string, ctx: ToolContext):
296
300
  if (ctx.signal?.aborted) return formatProbeToolRefusal(new ProbeToolRefusal("authority_stopped"));
297
301
  if (guardPath(ctx, String(a.path), "write") !== approvedTarget) return formatProbeToolRefusal(new ProbeToolRefusal("target_changed"));
298
302
  }
303
+ // ponytail: another process can write between this check and the write; Design 1.2 0444/ahub-edit isolation is the upgrade.
304
+ const unverified = ctx.editGuard?.write(file);
299
305
  mkdirSync(dirname(file), { recursive: true });
300
306
  writeFileSync(file, content);
307
+ try { ctx.editGuard?.written(file, unverified); } catch { /* evidence cannot undo a completed write */ }
301
308
  return `wrote ${a.path}`;
302
309
  }
303
310
  case "edit": {
@@ -324,7 +331,10 @@ export async function runTool(name: string, rawArgs: string, ctx: ToolContext):
324
331
  if (ctx.signal?.aborted) return formatProbeToolRefusal(new ProbeToolRefusal("authority_stopped"));
325
332
  if (guardPath(ctx, String(a.path), "write") !== approvedTarget || readFileSync(file, "utf8") !== text) return formatProbeToolRefusal(new ProbeToolRefusal("target_changed"));
326
333
  }
334
+ // ponytail: another process can write between this check and the write; Design 1.2 0444/ahub-edit isolation is the upgrade.
335
+ const unverified = ctx.editGuard?.write(file);
327
336
  writeFileSync(file, replacement);
337
+ try { ctx.editGuard?.written(file, unverified); } catch { /* evidence cannot undo a completed write */ }
328
338
  return `edited ${a.path}`;
329
339
  }
330
340
  case "bash": {
@@ -343,7 +353,9 @@ export async function runTool(name: string, rawArgs: string, ctx: ToolContext):
343
353
  if(check==="valid")break;
344
354
  if(attempt)return "error: read-only shell proof remained unstable; no command was executed";
345
355
  }
356
+ const observedShell = ctx.editGuard?.shell(command);
346
357
  const res = await sandboxedExec(["/bin/bash", "-c", command], { cwd: ctx.cwd, profile: ctx.sandboxProfile, readOnlyData: !!ctx.readOnly?.length, timeoutMs: (Number(a.timeout_s) || 120) * 1000, ...(ctx.sandboxEnv ? { env: ctx.sandboxEnv } : {}), ...(ctx.signal ? { signal: ctx.signal } : {}) });
358
+ try { observedShell?.(); } catch { /* optional observation cannot change an executed command result */ }
347
359
  try { ctx.onProcessExit?.(res.code); } catch { /* optional status observer never changes a tool result */ }
348
360
  return `${res.output}\n(exit ${res.code})`;
349
361
  }
@@ -67,6 +67,7 @@ export interface RecordBriefPort {
67
67
  maxBytes?: number | (() => number);
68
68
  }
69
69
  const RECORD_ROWS = 32, RECORD_BYTES = 2048;
70
+ const INTENT_SCREEN_BATCH = 32;
70
71
  const LEGACY_KNOWLEDGE_HEADER = "Knowledge brief (advice, not a block):";
71
72
  const LEGACY_NATIVE_HEADER = "Memory brief (hub memory first, fails first: ahub memory show <mem id>; amem by mem:id):";
72
73
  const LEGACY_CURATED_HEADER = "Memory brief (amem curated notes; fetch details by mem:id):";
@@ -220,7 +221,15 @@ export class Briefs {
220
221
  if (!current()) return undefined;
221
222
  const seen = this.seen.get(peer) ?? new Set<string>();
222
223
  const revision = context.options.policyVersion();
223
- const result = await buildIntentBrief(context.source, context.options);
224
+ const policy = context.options.policy(); let screened = 0;
225
+ const result = await buildIntentBrief(context.source, { ...context.options, policy: () => ({ ...policy, screen: async value => {
226
+ const accepted = await policy.screen(value);
227
+ if (++screened % INTENT_SCREEN_BATCH === 0) {
228
+ await new Promise<void>(resolve => setImmediate(resolve));
229
+ context.options.assertCurrent?.();
230
+ }
231
+ return accepted;
232
+ } }) });
224
233
  if (!current()) return undefined;
225
234
  if (result.state === "unknown" || context.options.allowed?.() === false || context.options.policyVersion() !== revision) return undefined;
226
235
  context.options.assertCurrent?.();
@@ -1,6 +1,6 @@
1
- import packageJson from "../../package.json";
2
1
  import { createHash } from "node:crypto";
3
2
  import { controlWriteSpan } from "../hub/control-write-trace.ts";
3
+ import { AGENT_MEM_VERSION } from "../hub/memory-profile.ts";
4
4
  import { CaptureStore, SearchIndex, looksSecret, memoryBase, readCaptureConfig, type CaptureOptions as StoreCaptureOptions, type MemoryStore, type CandidateStore, type View } from "@staix/agent-mem";
5
5
 
6
6
  export interface CaptureEvent {
@@ -149,6 +149,7 @@ export class MemoryClient {
149
149
  });
150
150
  }
151
151
  async health(): Promise<{ ok: boolean; version?: string }> {
152
- return this.run(() => ({ ok: true, version: packageJson.dependencies["@staix/agent-mem"] })) ?? { ok: false };
152
+ // #1605: the dependency is a range, so report the attested loaded release rather than a range as a version.
153
+ return this.run(() => ({ ok: true, version: AGENT_MEM_VERSION })) ?? { ok: false };
153
154
  }
154
155
  }
@@ -33,6 +33,11 @@ let shutdown: (() => void) | undefined;
33
33
  let runtimeCtx: any;
34
34
  let modelRegistry: any;
35
35
 
36
+ function contextObservation(message: any, ctx: any): Record<string, unknown> {
37
+ const usage = message?.role === "assistant" && typeof message.model === "string" && message.model === ctx?.model?.id ? message.usage : undefined;
38
+ return { input: usage?.input, cacheRead: usage?.cacheRead, cacheWrite: usage?.cacheWrite, contextWindow: ctx?.model?.contextWindow };
39
+ }
40
+
36
41
  async function post(path: string, body: unknown): Promise<any> {
37
42
  if (!bridgeUrl || !bridgeToken) throw new Error("Pi bridge is not configured");
38
43
  const response = await fetch(`${bridgeUrl}${path}`, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${bridgeToken}` }, body: JSON.stringify(body) });
@@ -127,6 +132,8 @@ async function poll(pi: ExtensionAPI): Promise<void> {
127
132
  ...(typeof pi.getSessionName === "function" ? { sessionName: pi.getSessionName() ?? "", titleEpoch, titleRevision } : {}),
128
133
  idle: runtimeCtx.isIdle() === true,
129
134
  empty: entries.every((entry: any) => ["model_change", "thinking_level_change"].includes(entry.type)),
135
+ model: runtimeCtx?.model ? { id: runtimeCtx.model.id } : undefined,
136
+ context: contextObservation(entries.slice().reverse().find((entry: any) => entry.type === "message" && entry.message?.role === "assistant")?.message, runtimeCtx),
130
137
  } });
131
138
  continue;
132
139
  } else if (command.type === "set_model") {
@@ -178,7 +185,7 @@ export default function(pi: ExtensionAPI): void {
178
185
  sessionId = String(state?.id ?? "");
179
186
  titleRevision = 0; titleEpoch = crypto.randomUUID();
180
187
  try {
181
- const claimed = await post("/event", { type: "session_start", ownerToken, pid: process.pid, signature: processSignature(process.pid), ...(typeof pi.getSessionName === "function" ? { sessionName: pi.getSessionName() ?? "", titleEpoch, titleRevision } : {}), sessionId: state?.id, sessionFile: ctx.sessionManager.getSessionFile(), approvalTurnAbort: typeof ctx.abort === "function", fencedPrompt: true });
188
+ const claimed = await post("/event", { type: "session_start", ownerToken, pid: process.pid, signature: processSignature(process.pid), ...(typeof pi.getSessionName === "function" ? { sessionName: pi.getSessionName() ?? "", titleEpoch, titleRevision } : {}), sessionId: state?.id, sessionFile: ctx.sessionManager.getSessionFile(), model: ctx.model ? { id: ctx.model.id } : undefined, approvalTurnAbort: typeof ctx.abort === "function", fencedPrompt: true });
182
189
  if (claimed?.ok === false) { ctx.shutdown?.(); return; }
183
190
  } catch (error) { ctx.shutdown?.(); throw error; }
184
191
  if (!pollStarted) { pollStarted = true; void poll(pi); }
@@ -190,7 +197,12 @@ export default function(pi: ExtensionAPI): void {
190
197
  const cancelled = !forcedFailure && message?.stopReason === "aborted";
191
198
  await post("/event", { type: "agent_end", generation: turnGeneration, ...(activePromptId ? { promptId: activePromptId } : {}), text: text ?? "", failed, cancelled, ...(failed ? { error: forcedFailure || message?.errorMessage || message?.stopReason } : {}) });
192
199
  });
193
- pi.on("message_end", async (event: any) => {
200
+ pi.on("message_end", async (event: any, ctx: any) => {
201
+ if (ctx) runtimeCtx = ctx;
202
+ if (event.message?.role === "assistant") {
203
+ try { await post("/event", { type: "pi_usage", sessionId, generation: turnGeneration, model: (ctx ?? runtimeCtx)?.model ? { id: (ctx ?? runtimeCtx).model.id } : undefined, context: contextObservation(event.message, ctx ?? runtimeCtx) }); }
204
+ catch { /* telemetry must not break a native turn */ }
205
+ }
194
206
  const tokens = assistantTokens(event.message);
195
207
  if (tokens === undefined) return;
196
208
  // Message-end is the sole usage source: agent_end carries those same messages again.
@@ -210,7 +222,7 @@ export default function(pi: ExtensionAPI): void {
210
222
  });
211
223
  // Native retries/continuations emit more starts before the one logical agent_settled.
212
224
  pi.on("agent_start", async () => { toolSteps = 0; forcedFailure = ""; turnGeneration++; activePromptId = pendingPromptId ?? activePromptId; pendingPromptId = undefined; await post("/event", { type: "agent_start", sessionId, ...(typeof pi.getSessionName === "function" ? { sessionName: pi.getSessionName() ?? "", titleEpoch, titleRevision } : {}), generation: turnGeneration, ...(activePromptId ? { promptId: activePromptId } : {}) }); });
213
- pi.on("model_select", async (_event: any, ctx: any) => { if (ctx.model?.provider && ctx.model.provider !== "agent-hub-local") ctx.shutdown?.(); });
225
+ pi.on("model_select", async (_event: any, ctx: any) => { runtimeCtx = ctx; if (ctx.model?.provider && ctx.model.provider !== "agent-hub-local") ctx.shutdown?.(); else try { await post("/event", { type: "pi_model", sessionId, model: ctx.model ? { id: ctx.model.id } : undefined }); } catch { /* optional telemetry */ } });
214
226
  pi.on("before_agent_start", async (event: any, ctx: any) => {
215
227
  if (ctx.model?.provider && ctx.model.provider !== "agent-hub-local") { ctx.abort?.(); return { systemPrompt: event.systemPrompt }; }
216
228
  return undefined;
@@ -5,6 +5,19 @@ import { createHash } from "node:crypto";
5
5
  import { PreEffectToolRefusal } from "../hub/tool-refusal.ts";
6
6
 
7
7
  export const PI_TOOL_RESULT_CAP = 100_000;
8
+ /** #1555 AC6: what a settled receipt of a closed session keeps. A replay inside that session never needs more than the outcome and, for a shell, its exit code. */
9
+ export const PI_CLOSED_RESULT_CAP = 2_000;
10
+ const COMPACTED = "\n[result compacted after the session closed]";
11
+ export function compactPiResult(result: string, cap = PI_CLOSED_RESULT_CAP): string {
12
+ if (result.length <= cap) return result;
13
+ try {
14
+ const parsed = JSON.parse(result) as { kind?: unknown; text?: unknown; exitCode?: unknown };
15
+ if (parsed && parsed.kind === "user-bash-result" && typeof parsed.text === "string") return JSON.stringify({ kind: parsed.kind, text: parsed.text.slice(0, Math.max(0, cap - 200)) + COMPACTED, exitCode: parsed.exitCode });
16
+ } catch { /* plain text result */ }
17
+ // bash and git results end with "(exit N)", which toolResultFailed reads to tell a failure from a success on a replay: keep that line.
18
+ const exit = result.match(/\n\(exit [^\n)]+\)$/u)?.[0] ?? "";
19
+ return result.slice(0, Math.max(0, cap - exit.length)) + COMPACTED + exit;
20
+ }
8
21
  /** Bound encoded text before wrapping it so escaping never cuts off trusted exit metadata. */
9
22
  export function packPiShellResult(text: string, exitCode: number | null): string {
10
23
  const pack = (value: string) => JSON.stringify({ kind: "user-bash-result", text: value, exitCode });
@@ -26,6 +39,7 @@ export class PiToolReceipts {
26
39
  private closing = false;
27
40
  private closed = false;
28
41
  private readonly pending = new Map<string, Promise<string>>();
42
+ private currentSession: string | undefined;
29
43
  constructor(file: string) {
30
44
  this.db = openHubDatabase(file, { create: true });
31
45
  chmodSync(file, 0o600);
@@ -37,6 +51,7 @@ export class PiToolReceipts {
37
51
  async execute(session: string, callId: string, name: string, args: unknown, run: () => Promise<string>): Promise<string> {
38
52
  if (this.closing) return "error: Pi tool ledger is shutting down; no new operation was executed";
39
53
  if (!session || !callId || session.length > 512 || callId.length > 512) return "error: invalid Pi session/tool call identity";
54
+ this.closeOthers(session);
40
55
  const fingerprint = createHash("sha256").update(JSON.stringify({ name, args })).digest("hex");
41
56
  const key = JSON.stringify([session, callId]);
42
57
  const row = this.db.query("SELECT fingerprint,state,result FROM pi_tool_receipts WHERE session=? AND call_id=?").get(session, callId) as { fingerprint: string; state: string; result: string | null } | null;
@@ -63,6 +78,17 @@ export class PiToolReceipts {
63
78
  return work;
64
79
  }
65
80
 
81
+ /** A call from a new session closes the previous one: its settled results shrink, while the active session's receipts are never touched. */
82
+ private closeOthers(session: string): void {
83
+ if (this.currentSession === session) return;
84
+ this.currentSession = session;
85
+ try {
86
+ const rows = this.db.query("SELECT session,call_id,result FROM pi_tool_receipts WHERE state='done' AND session != ? AND length(result) > ?").all(session, PI_CLOSED_RESULT_CAP) as { session: string; call_id: string; result: string }[];
87
+ const update = this.db.query("UPDATE pi_tool_receipts SET result=? WHERE session=? AND call_id=? AND state='done'");
88
+ this.db.transaction(() => { for (const row of rows) update.run(compactPiResult(row.result), row.session, row.call_id); })();
89
+ } catch { /* retention only: a failed pass leaves every receipt as it was */ }
90
+ }
91
+
66
92
  get unsettled(): boolean { return this.pending.size > 0 || !!this.db.query("SELECT 1 FROM pi_tool_receipts WHERE state != 'done' LIMIT 1").get(); }
67
93
  get inFlight(): number { return this.pending.size; }
68
94
  async drain(): Promise<void> { await Promise.allSettled(this.pending.values()); }