@staix/agent-hub 0.12.20 → 0.12.22

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 (67) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +17 -9
  3. package/docs/agent-notes/adapters.md +13 -3
  4. package/docs/agent-notes/benchmarks.md +1 -1
  5. package/docs/agent-notes/bus.md +7 -3
  6. package/docs/agent-notes/daemon.md +12 -2
  7. package/docs/agent-notes/local-worker.md +5 -1
  8. package/docs/agent-notes/tasks.md +4 -2
  9. package/docs/agent-notes/tests.md +5 -2
  10. package/docs/bench.md +143 -0
  11. package/docs/events.md +15 -5
  12. package/docs/operations.md +510 -54
  13. package/docs/quickstart.md +16 -11
  14. package/docs/research.md +92 -0
  15. package/docs/security.md +49 -11
  16. package/docs/smoke.md +138 -0
  17. package/docs/specs/2026-09-19-agent-hub-design.md +227 -20
  18. package/docs/specs/2026-09-20-upgrade-recovery-design.md +152 -18
  19. package/docs/verified.json +34 -17
  20. package/package.json +1 -1
  21. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  22. package/plugins/agent-hub/server.js +3 -2
  23. package/src/adapters/acp.ts +77 -10
  24. package/src/adapters/codex-appserver.ts +72 -2
  25. package/src/adapters/local-worker.ts +46 -11
  26. package/src/adapters/pi.ts +215 -22
  27. package/src/cli/bench.ts +287 -0
  28. package/src/cli/console-state.ts +226 -28
  29. package/src/cli/console.ts +16 -4
  30. package/src/cli/facts-hook.ts +50 -8
  31. package/src/cli/help.ts +16 -5
  32. package/src/cli/identity.ts +10 -4
  33. package/src/cli/launch.ts +272 -18
  34. package/src/cli/main.ts +290 -30
  35. package/src/cli/preview.ts +13 -3
  36. package/src/cli/recovery-package.ts +17 -0
  37. package/src/cli/status-lines.ts +2 -1
  38. package/src/cli/terminal-recovery.ts +83 -31
  39. package/src/cli/upgrade-interactive.ts +297 -0
  40. package/src/cli/upgrade-runtime.ts +123 -20
  41. package/src/cli/upgrade.ts +108 -19
  42. package/src/hub/bench.ts +211 -0
  43. package/src/hub/bus.ts +24 -7
  44. package/src/hub/conductor.ts +22 -21
  45. package/src/hub/config-trust.ts +1 -0
  46. package/src/hub/control-client.ts +4 -1
  47. package/src/hub/daemon.ts +477 -86
  48. package/src/hub/delivery-journal.ts +6 -6
  49. package/src/hub/events.ts +4 -2
  50. package/src/hub/lifecycle.ts +8 -13
  51. package/src/hub/manager.ts +16 -14
  52. package/src/hub/peers.ts +2 -2
  53. package/src/hub/permission-mode.ts +44 -0
  54. package/src/hub/recovery-store.ts +59 -9
  55. package/src/hub/registry.ts +36 -22
  56. package/src/hub/research.ts +255 -0
  57. package/src/hub/tasks.ts +99 -55
  58. package/src/hub/tool-refusal.ts +7 -0
  59. package/src/hub/ui.ts +4 -1
  60. package/src/local/deny.ts +48 -1
  61. package/src/local/sandbox.ts +6 -3
  62. package/src/local/tools.ts +34 -11
  63. package/src/pi/extension.ts +43 -20
  64. package/src/pi/process-signature.ts +23 -0
  65. package/src/pi/tool-receipts.ts +24 -2
  66. package/src/ui/index.html +98 -17
  67. package/src/ui/task-progress.ts +33 -0
package/src/local/deny.ts CHANGED
@@ -10,7 +10,6 @@ export const DENY_SEGMENTS = [".maru/secrets", ".agenthub/state", ".agenthub/arc
10
10
  export const DENY_NAMES = ["^\\.env", "\\.pem$", "\\.key$", "^id_rsa", "^id_ed25519", "^credentials(\\.|$)", "^auth\\.json$", "^\\.netrc$", "^\\.npmrc$", "^\\.pypirc$"];
11
11
 
12
12
  const hasSegment = (rel: string, seg: string) => `/${rel}/`.includes(`/${seg}/`);
13
- export { hasSegment };
14
13
 
15
14
  /** True when a path names something the worker must never read, write or report. `extra`: substrings from `local.deny`. */
16
15
  export function isDenied(path: string, extra: string[] = []): boolean {
@@ -27,6 +26,54 @@ const sbplEscape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
27
26
  */
28
27
  export const sbplString = (s: string) => `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
29
28
 
29
+ /**
30
+ * The 16 code points HFS+ ignores in file names: U+200C-200F, U+202A-202E, U+206A-206F, U+FEFF (a probe found
31
+ * case-insensitive APFS ignores none). `mkdir .g<U+200D>it` on HFS+ makes what everything afterwards opens as
32
+ * `.git` (#270). One source for the seatbelt profile's folded patterns; the file tools' `foldSegment` removes
33
+ * every default-ignorable, a superset of these.
34
+ */
35
+ export const HFS_IGNORABLE_POINTS = ["\u200C", "\u200D", "\u200E", "\u200F", "\u202A", "\u202B", "\u202C", "\u202D", "\u202E", "\u206A", "\u206B", "\u206C", "\u206D", "\u206E", "\u206F", "\uFEFF"];
36
+
37
+ /**
38
+ * One HFS+-ignorable code point as a seatbelt regex atom. A group alternation, not a character class: the
39
+ * seatbelt regex engine is byte-oriented, so a quantifier after a multi-byte class member binds to its last
40
+ * byte and a class never matches the plain name (verified with the real sandbox-exec, #270).
41
+ */
42
+ const HFS_IGNORABLE = `(${HFS_IGNORABLE_POINTS.join("|")})`;
43
+
44
+ /** A regex source matching `name` with any number of HFS+-ignorable code points interleaved, at the ends included. */
45
+ const hfsFoldedName = (name: string) => `${HFS_IGNORABLE}*${[...name].map((c) => sbplEscape(c)).join(`${HFS_IGNORABLE}*`)}${HFS_IGNORABLE}*`;
46
+
47
+ /**
48
+ * Seatbelt rules for the hub's and git's own names (#270). `.agenthub` is refused anywhere under the project root.
49
+ * `.git` is refused at any depth, the name itself included, so a planted repository cannot arrive by creation,
50
+ * rename, symlink or gitfile, and `config` and `hooks` directly under it are folded too; the cost is that
51
+ * `git init`, `git clone` and `git worktree add` no longer run inside the sandbox. `commondir` is refused at any
52
+ * depth below a `.git` and below each external git dir: that is where git keeps it for linked worktrees and
53
+ * submodules. An external git dir's `config`/`hooks` rules cover only its own children (plus the hooks
54
+ * directory's contents): at any depth they would deny refs named `config` or `hooks` in a worktree or submodule
55
+ * project (`git branch fix/config` fails on `.git/logs/refs/heads/fix/config`). Every pattern keeps its `^`
56
+ * anchor (an unanchored starred alternation does not match in this engine) and no folded literal contains the
57
+ * root: an SBPL string literal dies at 1024 bytes ("Error reading string"), which a long project path would trip.
58
+ */
59
+ export function hubWriteRegexes(root: string, gitDirs: string[] = []): string[] {
60
+ const git = hfsFoldedName(".git");
61
+ const re = (s: string) => `(regex ${sbplString(s)})`;
62
+ const external = gitDirs.flatMap((d) => [
63
+ `(require-all ${re(`^${sbplEscape(d)}/[^/]+$`)} ${re(`^.*/(${hfsFoldedName("config")}|${hfsFoldedName("hooks")})$`)})`,
64
+ `(subpath ${sbplString(`${d}/hooks`)})`,
65
+ `(require-all (subpath ${sbplString(d)}) ${re(`^.*/${hfsFoldedName("commondir")}$`)})`,
66
+ ]);
67
+ return [
68
+ `(require-all (subpath ${sbplString(root)}) ${re(`^.*/${hfsFoldedName(".agenthub")}(/|$)`)})`,
69
+ re(`^.*/${git}$`),
70
+ re(`^.*/${git}/${hfsFoldedName("config")}$`),
71
+ re(`^.*/${git}/${hfsFoldedName("hooks")}(/|$)`),
72
+ `(require-all ${re(`^.*/${git}/.*$`)} ${re(`^.*/${hfsFoldedName("commondir")}$`)})`,
73
+ ...external,
74
+ ];
75
+ }
76
+
30
77
  /**
31
78
  * Seatbelt regex filters equivalent to isDenied. Seatbelt sees absolute paths, so the `local.deny` substrings are
32
79
  * anchored under the project root: a bare "private/" would otherwise match /private/var/... and deny the whole temp tree.
@@ -3,7 +3,7 @@ import { existsSync, mkdtempSync, rmSync } from "node:fs";
3
3
  import { homedir, tmpdir } from "node:os";
4
4
  import { join, resolve } from "node:path";
5
5
  import { realPath } from "../hub/project.ts";
6
- import { denyRegexes, sbplString } from "./deny.ts";
6
+ import { denyRegexes, hubWriteRegexes, sbplString } from "./deny.ts";
7
7
 
8
8
  const SANDBOX_EXEC = "/usr/bin/sandbox-exec";
9
9
  export const OUTPUT_CAP = 20_000;
@@ -102,8 +102,11 @@ export function profile(cwd: string, network: SandboxNetwork, readAllow: string[
102
102
  ...start,
103
103
  "(deny file-write*)",
104
104
  `(allow file-write* (subpath ${q(root)}) (regex #"^/dev/") ${gitDirs.map((d) => `(subpath ${q(d)})`).join(" ")})`,
105
- // Inside cwd: nothing that runs later outside the sandbox, nothing that reconfigures the hub.
106
- `(deny file-write* (subpath ${q(join(root, ".agenthub"))}) ${[join(root, ".git"), ...gitDirs].map((d) => `(subpath ${q(join(d, "hooks"))}) (literal ${q(join(d, "config"))})`).join(" ")})`,
105
+ // Inside cwd: nothing that runs later outside the sandbox, nothing that reconfigures the hub. The .git and
106
+ // .agenthub patterns tolerate the code points HFS+ ignores in every segment, the .git name itself is refused
107
+ // at any depth (creation, rename, symlink, gitfile), and the external git dirs get folded hooks/config rules
108
+ // (#270). The cost: git init, clone and worktree add no longer run inside the sandbox.
109
+ `(deny file-write* ${hubWriteRegexes(root, gitDirs).join(" ")})`,
107
110
  `(deny file-read* file-write* ${creds.map((c) => `(subpath ${q(join(home, c))})`).join(" ")})`,
108
111
  `(deny file-read* file-write* ${denyRegexes(root, deny).join(" ")})`,
109
112
  // Python's own CA bundle (certifi, which pip vendors too): pip, requests and httpx read it instead of the system's (#64).
@@ -1,11 +1,21 @@
1
1
  import { lstatSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
2
  import { dirname, join, relative, resolve } from "node:path";
3
3
  import { realPath } from "../hub/project.ts";
4
- import { hasSegment, isDenied } from "./deny.ts";
4
+ import { isHubWritePath } from "../hub/permission-mode.ts";
5
+ import { isDenied } from "./deny.ts";
5
6
  import { OUTPUT_CAP, sandboxedExec } from "./sandbox.ts";
6
7
 
7
8
  export { isDenied };
8
9
 
10
+ export type ToolApproval = boolean | "expired" | "aborted";
11
+ export interface ApprovalProvenance { source: "person" | "automatic" | "expired" | "aborted"; answerEpoch: number; eligibleExpiry?: boolean; }
12
+ export type ApprovalObserver = (provenance: ApprovalProvenance) => void;
13
+ export const APPROVAL_EXPIRED_TEXT = "error: approval expired: no person answered; do not retry this call; hand the task off or stop";
14
+ export class ApprovalWaitStop extends Error {}
15
+ const approvalError = (picked: ToolApproval, denied: string): string | undefined => picked === true ? undefined
16
+ : picked === "expired" ? APPROVAL_EXPIRED_TEXT
17
+ : picked === "aborted" ? "error: approval withdrawn because the turn ended; no operation was executed" : denied;
18
+
9
19
  export interface ToolContext {
10
20
  cwd: string;
11
21
  /** Extra denylist entries from config: substrings of the project-relative path. */
@@ -16,15 +26,14 @@ export interface ToolContext {
16
26
  sandboxEnv?: Record<string, string>;
17
27
  /** Turn cancellation signal, including the execution-budget wall cap. */
18
28
  signal?: AbortSignal;
19
- /** Ask the console. Resolves false on deny or timeout. */
20
- permit: (title: string) => Promise<boolean>;
29
+ /** Only true permits an effect; expiry and abort remain distinct from a person's denial. */
30
+ permit: (title: string, tool?: string, signal?: AbortSignal, canonicalTarget?: string, observe?: ApprovalObserver) => Promise<ToolApproval>;
31
+ /** Trusted process status, independent of what its stdout says. */
32
+ onProcessExit?: (code: number | null) => void;
21
33
  /** Publish a message to other peers mid-turn. Returns a one-line receipt. */
22
34
  send: (text: string, to?: string[]) => string;
23
35
  }
24
36
 
25
- /** Not secret, but writing them changes what runs outside the worker's control. */
26
- const WRITE_DENY_SEGMENTS = [".git", ".agenthub"];
27
-
28
37
  const lexists = (p: string) => {
29
38
  try {
30
39
  lstatSync(p);
@@ -52,7 +61,9 @@ export function guardPath(ctx: Pick<ToolContext, "cwd" | "deny">, path: string,
52
61
  const rel = relative(root, real);
53
62
  if (rel.startsWith("..") || resolve(root, rel) !== real) throw new Error(`${path} is outside the project directory`);
54
63
  if (isDenied(rel, ctx.deny)) throw new Error(`${path} is on the secrets denylist`);
55
- if (mode === "write" && WRITE_DENY_SEGMENTS.some((s) => hasSegment(rel, s))) throw new Error(`${path} is not writable by the local worker`);
64
+ // Not secret, but writing .git or .agenthub changes what runs outside the worker's control. Names are compared
65
+ // folded: a new `.GIT/config` is `.git/config` to a case-insensitive disk, and git then runs what it names.
66
+ if (mode === "write" && isHubWritePath(rel)) throw new Error(`${path} is not writable by the local worker`);
56
67
  return real;
57
68
  }
58
69
 
@@ -129,23 +140,29 @@ export async function runTool(name: string, rawArgs: string, ctx: ToolContext):
129
140
  }
130
141
  case "write": {
131
142
  let file = guardPath(ctx, String(a.path), "write");
143
+ const approvedTarget = file;
132
144
  const content = String(a.content ?? "");
133
- if (!(await ctx.permit(`write ${a.path} (${content.length} chars):\n${preview(content)}`))) return "error: the user did not approve this write";
145
+ const refused = approvalError(await ctx.permit(`write ${a.path} (${content.length} chars):\n${preview(content)}`, "write", ctx.signal, file), "error: the user did not approve this write");
146
+ if (refused) return refused;
134
147
  if (ctx.signal?.aborted) return "error: turn cancelled before write";
135
148
  file = guardPath(ctx, String(a.path), "write");
149
+ if (file !== approvedTarget) return "error: path target changed during approval; inspect before retrying";
136
150
  mkdirSync(dirname(file), { recursive: true });
137
151
  writeFileSync(file, content);
138
152
  return `wrote ${a.path}`;
139
153
  }
140
154
  case "edit": {
141
155
  let file = guardPath(ctx, String(a.path), "write");
156
+ const approvedTarget = file;
142
157
  let text = readFileSync(file, "utf8");
143
158
  let count = text.split(String(a.old)).length - 1;
144
159
  if (!a.old || count !== 1) return `error: \`old\` must match exactly once, it matched ${count} times`;
145
- if (!(await ctx.permit(`edit ${a.path}:\n- ${preview(String(a.old), 600)}\n+ ${preview(String(a.new ?? ""), 600)}`))) return "error: the user did not approve this edit";
160
+ const refused = approvalError(await ctx.permit(`edit ${a.path}:\n- ${preview(String(a.old), 600)}\n+ ${preview(String(a.new ?? ""), 600)}`, "edit", ctx.signal, file), "error: the user did not approve this edit");
161
+ if (refused) return refused;
146
162
  if (ctx.signal?.aborted) return "error: turn cancelled before edit";
147
163
  // Approval can outlive another peer's edit or a path change. Apply only the approved fragment to current bytes.
148
164
  file = guardPath(ctx, String(a.path), "write");
165
+ if (file !== approvedTarget) return "error: path target changed during approval; inspect before retrying";
149
166
  text = readFileSync(file, "utf8");
150
167
  count = text.split(String(a.old)).length - 1;
151
168
  if (count !== 1) return `error: file changed during approval; \`old\` must match exactly once, it matched ${count} times`;
@@ -157,8 +174,10 @@ export async function runTool(name: string, rawArgs: string, ctx: ToolContext):
157
174
  if (!command.trim()) return "error: empty command";
158
175
  // The approver sees the whole command, not a prefix: what is hidden cannot be approved.
159
176
  if (command.length > 4000) return "error: command longer than 4000 characters; put it in a script file with write, then run that";
160
- if (!(await ctx.permit(`bash: ${command}`))) return "error: the user did not approve this command";
177
+ const refused = approvalError(await ctx.permit(`bash: ${command}`, "bash", ctx.signal), "error: the user did not approve this command");
178
+ if (refused) return refused;
161
179
  const res = await sandboxedExec(["/bin/bash", "-c", command], { cwd: ctx.cwd, profile: ctx.sandboxProfile, timeoutMs: (Number(a.timeout_s) || 120) * 1000, ...(ctx.sandboxEnv ? { env: ctx.sandboxEnv } : {}), ...(ctx.signal ? { signal: ctx.signal } : {}) });
180
+ try { ctx.onProcessExit?.(res.code); } catch { /* optional status observer never changes a tool result */ }
162
181
  return `${res.output}\n(exit ${res.code})`;
163
182
  }
164
183
  case "git": {
@@ -167,9 +186,13 @@ export async function runTool(name: string, rawArgs: string, ctx: ToolContext):
167
186
  if (!GIT_READ.has(sub) && !GIT_WRITE.has(sub)) return `error: git ${sub} is not available to the local worker`;
168
187
  const problem = gitArgsProblem(args, ctx.deny);
169
188
  if (problem) return `error: git ${sub}: ${problem}`;
170
- if (GIT_WRITE.has(sub) && !(await ctx.permit(`git ${args.join(" ")}`))) return "error: the user did not approve this git command";
189
+ if (GIT_WRITE.has(sub)) {
190
+ const refused = approvalError(await ctx.permit(`git ${args.join(" ")}`, "git", ctx.signal), "error: the user did not approve this git command");
191
+ if (refused) return refused;
192
+ }
171
193
  // Sandboxed like bash: flags such as --output or an editor cannot write outside the project or reach the network.
172
194
  const res = await sandboxedExec(["git", "--no-pager", ...args], { cwd: ctx.cwd, profile: ctx.sandboxProfile, ...(ctx.sandboxEnv ? { env: ctx.sandboxEnv } : {}), ...(ctx.signal ? { signal: ctx.signal } : {}) });
195
+ try { ctx.onProcessExit?.(res.code); } catch { /* optional status observer never changes a tool result */ }
173
196
  return `${res.output}\n(exit ${res.code})`;
174
197
  }
175
198
  case "hub_send":
@@ -19,6 +19,7 @@ let pollStopped = false;
19
19
  let toolSteps = 0;
20
20
  let lastActivity = 0;
21
21
  let usageSeq = 0;
22
+ let shellSeq = 0;
22
23
  let forcedFailure = "";
23
24
  let turnGeneration = 0;
24
25
  let sessionId = "";
@@ -33,9 +34,13 @@ async function post(path: string, body: unknown): Promise<any> {
33
34
  if (!response.ok) throw new Error(`Pi bridge HTTP ${response.status}`);
34
35
  return response.json();
35
36
  }
36
- async function admitBudget(unit: BudgetUnit, idleUserBash = false): Promise<{ allowed: boolean; reservation?: string }> {
37
+ async function admitBudget(unit: BudgetUnit, idleUserBash = false, generation = turnGeneration, callSessionId = sessionId): Promise<{ allowed: boolean; reservation?: string; reason?: string }> {
38
+ const current = () => generation === turnGeneration && callSessionId === sessionId;
39
+ const stale = () => ({ allowed: false, reason: "Pi tool lineage ended during admission; do not retry the old call" });
40
+ if (!current()) return stale();
37
41
  try {
38
- const result = await post("/budget", { unit, generation: turnGeneration, ...(idleUserBash ? { idleUserBash: true } : {}) });
42
+ const result = await post("/budget", { unit, generation, ...(idleUserBash ? { idleUserBash: true } : {}) });
43
+ if (!current()) return stale();
39
44
  const decisions = Array.isArray(result?.decisions) ? result.decisions : [];
40
45
  const denied = decisions.find((item: any) => item?.allowed === false);
41
46
  if (!denied) return { allowed: true, ...(idleUserBash && typeof result?.reservation === "string" ? { reservation: result.reservation } : {}) };
@@ -43,12 +48,14 @@ async function admitBudget(unit: BudgetUnit, idleUserBash = false): Promise<{ al
43
48
  if (idleUserBash) return { allowed: false };
44
49
  forcedFailure = reason;
45
50
  } catch (error) {
51
+ if (!current()) return stale();
46
52
  if (idleUserBash) return { allowed: false };
47
53
  forcedFailure = `execution budget admission unavailable: ${(error as Error).message}`;
48
54
  }
49
- try { await post("/event", { type: "agent_end", generation: turnGeneration, failed: true, error: forcedFailure }); } catch { /* abort remains authoritative when the bridge is unavailable */ }
50
- runtimeCtx?.abort?.();
51
- return { allowed: false };
55
+ const reason = forcedFailure;
56
+ try { await post("/event", { type: "agent_end", generation, failed: true, error: reason }); } catch { /* abort remains authoritative when the bridge is unavailable */ }
57
+ if (current()) runtimeCtx?.abort?.();
58
+ return { allowed: false, reason };
52
59
  }
53
60
  async function poll(pi: ExtensionAPI): Promise<void> {
54
61
  while (!pollStopped) {
@@ -77,10 +84,13 @@ async function poll(pi: ExtensionAPI): Promise<void> {
77
84
  shutdown?.();
78
85
  } else if (command.type === "abort_budget") {
79
86
  if (Number.isSafeInteger(command.generation) && command.generation === turnGeneration) {
80
- const reason = "execution budget exhausted: elapsed_ms wall cap reached";
87
+ if (typeof runtimeCtx?.abort !== "function") throw new Error("Pi runtime cannot abort the current turn");
88
+ const generation = turnGeneration, callSessionId = sessionId;
89
+ const reason = command.cause === "approval" && typeof command.reason === "string" && command.reason
90
+ ? command.reason : "execution budget exhausted: elapsed_ms wall cap reached";
81
91
  forcedFailure = reason;
82
- await post("/event", { type: "agent_end", generation: turnGeneration, failed: true, error: reason });
83
- runtimeCtx?.abort?.();
92
+ await post("/event", { type: "agent_end", generation, failed: true, error: reason });
93
+ if (generation === turnGeneration && callSessionId === sessionId) runtimeCtx?.abort?.();
84
94
  }
85
95
  }
86
96
  await post("/ack", { id: command.id, ok: true });
@@ -107,7 +117,7 @@ export default function(pi: ExtensionAPI): void {
107
117
  const state = ctx.sessionManager.getHeader();
108
118
  sessionId = String(state?.id ?? "");
109
119
  try {
110
- const claimed = await post("/event", { type: "session_start", ownerToken, pid: process.pid, signature: processSignature(process.pid), sessionId: state?.id, sessionFile: ctx.sessionManager.getSessionFile() });
120
+ const claimed = await post("/event", { type: "session_start", ownerToken, pid: process.pid, signature: processSignature(process.pid), sessionId: state?.id, sessionFile: ctx.sessionManager.getSessionFile(), approvalTurnAbort: typeof ctx.abort === "function" });
111
121
  if (claimed?.ok === false) { ctx.shutdown?.(); return; }
112
122
  } catch (error) { ctx.shutdown?.(); throw error; }
113
123
  if (!pollStarted) { pollStarted = true; void poll(pi); }
@@ -140,8 +150,10 @@ export default function(pi: ExtensionAPI): void {
140
150
  });
141
151
  pi.on("before_provider_request", async (_event: any, ctx: any) => {
142
152
  if (ctx.model?.provider && ctx.model.provider !== "agent-hub-local") { ctx.abort?.(); return undefined; }
143
- try { if (!(await admitBudget("model_calls")).allowed) ctx.abort?.(); }
144
- catch (error) { forcedFailure = `execution budget admission failed: ${(error as Error).message}`; ctx.abort?.(); }
153
+ const generation = turnGeneration, callSessionId = sessionId;
154
+ const current = () => generation === turnGeneration && callSessionId === sessionId;
155
+ try { if (!(await admitBudget("model_calls", false, generation, callSessionId)).allowed && current()) ctx.abort?.(); }
156
+ catch (error) { if (current()) { forcedFailure = `execution budget admission failed: ${(error as Error).message}`; ctx.abort?.(); } }
145
157
  return undefined;
146
158
  });
147
159
  pi.on("agent_settled", async (_event: any, ctx: any) => {
@@ -151,10 +163,11 @@ export default function(pi: ExtensionAPI): void {
151
163
  await post("/event", { type: "agent_settled", generation: turnGeneration, ...(text ? { text } : {}) });
152
164
  });
153
165
  pi.on("user_bash", async (event: any) => {
154
- const admission = await admitBudget("tool_calls", true);
166
+ const generation = turnGeneration, callSessionId = sessionId;
167
+ const admission = await admitBudget("tool_calls", true, generation, callSessionId);
155
168
  if (!admission.allowed || !admission.reservation) return { cancel: true };
156
- const result = await post("/tool", { name: "bash", args: { command: event.command, cwd: event.cwd }, toolCallId: `pi-shell-${Date.now()}`, purpose: "idle_user_bash", generation: turnGeneration, reservation: admission.reservation });
157
- return { result: { output: String(result.text ?? result), exitCode: 0, cancelled: false, truncated: false } };
169
+ const result = await post("/tool", { name: "bash", args: { command: event.command, cwd: event.cwd }, toolCallId: `pi-shell-${Date.now()}-${++shellSeq}`, purpose: "idle_user_bash", generation, sessionId: callSessionId, reservation: admission.reservation });
170
+ return { result: { output: String(result.text ?? result), exitCode: typeof result.exitCode === "number" ? result.exitCode : undefined, cancelled: result.exitCode === null, truncated: false } };
158
171
  });
159
172
  // Managed sessions may only be handed over by PiPeer after it has fenced the
160
173
  // owner and verified the replacement identity. User /fork and /resume would
@@ -164,8 +177,11 @@ export default function(pi: ExtensionAPI): void {
164
177
  pi.on("session_shutdown", async () => { pollStopped = true; await post("/event", { type: "session_shutdown" }); });
165
178
  for (const raw of (() => { try { return JSON.parse(process.env.AGENTHUB_PI_TOOLS ?? "[]") as any[]; } catch { return []; } })()) {
166
179
  if (!raw || typeof raw.name !== "string" || !raw.parameters) continue;
167
- pi.registerTool({ name: raw.name, label: raw.name, description: raw.description ?? raw.name, parameters: raw.parameters, async execute(toolCallId: string, params: unknown) {
168
- if (!(await admitBudget("tool_calls")).allowed) return { content: [{ type: "text", text: `error: ${forcedFailure}` }], details: {}, isError: true };
180
+ pi.registerTool({ name: raw.name, label: raw.name, description: raw.description ?? raw.name, parameters: raw.parameters, async execute(toolCallId: string, params: unknown, signal?: AbortSignal) {
181
+ const generation = turnGeneration, callSessionId = sessionId;
182
+ if (signal?.aborted) return { content: [{ type: "text", text: "error: tool call cancelled before execution" }], details: {}, isError: true };
183
+ const admission = await admitBudget("tool_calls", false, generation, callSessionId);
184
+ if (!admission.allowed) return { content: [{ type: "text", text: `error: ${admission.reason ?? forcedFailure}` }], details: {}, isError: true };
169
185
  if (toolSteps++ >= maxSteps) {
170
186
  const reason = `Pi tool step limit ${maxSteps} reached`;
171
187
  forcedFailure = reason;
@@ -173,12 +189,19 @@ export default function(pi: ExtensionAPI): void {
173
189
  // event, so the adapter binds it while the turn still owns it. The counter already counts the
174
190
  // rejected pre-effect invocation (toolSteps++ above); its side effect never executes. The
175
191
  // reason text stays the failure record; the signal adds the validated counts.
176
- try { await post("/event", { type: "ceiling", kind: PI_CEILING_KIND, unit: PI_CEILING_UNIT, count: toolSteps, limit: maxSteps, sessionId, generation: turnGeneration }); } catch { /* the agent_end failure below remains authoritative */ }
177
- await post("/event", { type: "agent_end", generation: turnGeneration, failed: true, error: reason });
178
- runtimeCtx?.abort?.();
192
+ try { await post("/event", { type: "ceiling", kind: PI_CEILING_KIND, unit: PI_CEILING_UNIT, count: toolSteps, limit: maxSteps, sessionId: callSessionId, generation }); } catch { /* the agent_end failure below remains authoritative */ }
193
+ await post("/event", { type: "agent_end", generation, failed: true, error: reason });
194
+ if (generation === turnGeneration && callSessionId === sessionId) runtimeCtx?.abort?.();
179
195
  return { content: [{ type: "text", text: `error: ${reason}` }], details: {}, isError: true };
180
196
  }
181
- const result = await post("/tool", { name: raw.name, args: params, toolCallId });
197
+ const aborted = () => { void post("/event", { type: "tool_abort", sessionId: callSessionId, generation, toolCallId }).catch(() => undefined); };
198
+ if (signal?.aborted) return { content: [{ type: "text", text: "error: tool call cancelled before execution" }], details: {}, isError: true };
199
+ signal?.addEventListener("abort", aborted, { once: true });
200
+ let result: any;
201
+ try {
202
+ result = await post("/tool", { name: raw.name, args: params, toolCallId, sessionId: callSessionId, generation });
203
+ if (signal?.aborted) aborted();
204
+ } finally { signal?.removeEventListener("abort", aborted); }
182
205
  const text = String(result.text ?? result);
183
206
  // Pi 1.0.1 reads isError === true alone (#181). The bridge computes `failed` with the
184
207
  // managed-tool failure contract (toolResultFailed); the extension never re-parses the text.
@@ -17,3 +17,26 @@ export function processSignature(pid: number): string | undefined {
17
17
  return text ? createHash("sha256").update(text).digest("hex") : undefined;
18
18
  } catch { return undefined; }
19
19
  }
20
+
21
+ export type Liveness = "live" | "gone" | "unknown";
22
+
23
+ /**
24
+ * #226: the one ownership check behind every recorded pid (hub manifest, registry claim, recovery runner, manager
25
+ * owner, launcher records). With a recorded `signature` the identity decides: equal is live, different is gone (the
26
+ * pid was reused, after a reboot for example, also by a process we may not signal), and a pid that exists but whose
27
+ * identity cannot be read is unknown. Without one (records written by 0.12.20 and older) the pid probe answers as it
28
+ * always did: live, gone on ESRCH, unknown otherwise. Unknown is never gone.
29
+ */
30
+ // ponytail: `ps lstart` is derived from boot time plus the process's age; a wall-clock step on Linux can change it for a
31
+ // live process, which then reads as gone (a second hub could take its claim). Upgrade path: a boot-id or start-tick
32
+ // (Linux /proc/<pid>/stat field 22) component in the signature.
33
+ export function processLiveness(pid: unknown, signature?: string | null, identity: (pid: number) => string | undefined = processSignature): Liveness {
34
+ if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0) return "unknown";
35
+ if (signature) {
36
+ let current: string | undefined;
37
+ try { current = identity(pid); } catch { /* unreadable: the pid probe below decides between gone and unknown */ }
38
+ if (current) return current === signature ? "live" : "gone";
39
+ }
40
+ try { process.kill(pid, 0); return signature ? "unknown" : "live"; }
41
+ catch (error) { return (error as NodeJS.ErrnoException).code === "ESRCH" ? "gone" : "unknown"; }
42
+ }
@@ -1,6 +1,23 @@
1
1
  import { chmodSync } from "node:fs";
2
2
  import { Database } from "bun:sqlite";
3
3
  import { createHash } from "node:crypto";
4
+ import { PreEffectToolRefusal } from "../hub/tool-refusal.ts";
5
+
6
+ export const PI_TOOL_RESULT_CAP = 100_000;
7
+ /** Bound encoded text before wrapping it so escaping never cuts off trusted exit metadata. */
8
+ export function packPiShellResult(text: string, exitCode: number | null): string {
9
+ const pack = (value: string) => JSON.stringify({ kind: "user-bash-result", text: value, exitCode });
10
+ const full = pack(text);
11
+ if (full.length <= PI_TOOL_RESULT_CAP) return full;
12
+ const suffix = "\n[output truncated]";
13
+ let low = 0, high = text.length;
14
+ while (low < high) {
15
+ const middle = Math.ceil((low + high) / 2);
16
+ if (pack(text.slice(0, middle) + suffix).length <= PI_TOOL_RESULT_CAP) low = middle;
17
+ else high = middle - 1;
18
+ }
19
+ return pack(text.slice(0, low) + suffix);
20
+ }
4
21
 
5
22
  /** Private, session-scoped dedupe. An interrupted effect is never automatically repeated. */
6
23
  export class PiToolReceipts {
@@ -31,10 +48,15 @@ export class PiToolReceipts {
31
48
  }
32
49
  const claim = this.db.query("INSERT OR IGNORE INTO pi_tool_receipts(session,call_id,fingerprint,state) VALUES(?,?,?,'pending')").run(session, callId, fingerprint);
33
50
  if (!claim.changes) return this.execute(session, callId, name, args, run);
34
- const work = Promise.resolve().then(run).then((result) => {
35
- const text = result.slice(0, 100_000);
51
+ const settle = (result: string): string => {
52
+ const text = result.slice(0, PI_TOOL_RESULT_CAP);
36
53
  this.db.query("UPDATE pi_tool_receipts SET state='done',result=? WHERE session=? AND call_id=?").run(text, session, callId);
37
54
  return text;
55
+ };
56
+ // Legacy pending rows have no refusal proof: neither the current board nor an error's text can settle them.
57
+ const work = Promise.resolve().then(run).then(settle, (error: unknown) => {
58
+ if (error instanceof PreEffectToolRefusal) return settle(`error: ${error.message}`);
59
+ throw error;
38
60
  }).catch(() => "error: tool outcome is uncertain; stop and reconcile it, do not repeat the effect")
39
61
  .finally(() => this.pending.delete(key));
40
62
  this.pending.set(key, work);