@staix/agent-hub 0.36.0 → 0.37.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 (102) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +6 -2
  3. package/THIRD_PARTY_NOTICES.md +0 -18
  4. package/docs/agent-notes/README.md +13 -3
  5. package/docs/agent-notes/daemon.md +4 -4
  6. package/docs/agent-notes/local-worker.md +1 -0
  7. package/docs/agent-notes/models.md +2 -1
  8. package/docs/agent-notes/tasks.md +1 -1
  9. package/docs/agent-notes/tests.md +1 -2
  10. package/docs/contracts/companion-cli-v1.json +70 -0
  11. package/docs/design/adapters.md +43 -2
  12. package/docs/design/agent-hub-architecture.md +9 -1
  13. package/docs/design/guidance-probes.md +802 -0
  14. package/docs/design/model-routes.md +437 -12
  15. package/docs/dogfood.md +11 -13
  16. package/docs/events.md +20 -1
  17. package/docs/memory.md +3 -3
  18. package/docs/operations.md +112 -148
  19. package/docs/quickstart.md +9 -3
  20. package/docs/research.md +1 -1
  21. package/docs/sdlc.md +5 -3
  22. package/docs/security.md +21 -1
  23. package/docs/specs/2026-09-19-agent-hub-design.md +9 -7
  24. package/docs/specs/2026-10-04-switchyard-source-port-design.md +3 -1
  25. package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +25 -11
  26. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +21 -6
  27. package/docs/verification/2026-11-11-0.37.0.md +40 -0
  28. package/docs/verification/2026-11-11-guidance-probe-t2-1226.md +153 -0
  29. package/docs/verification/2026-11-11-qwen-setter-suggestions-off.md +167 -0
  30. package/docs/verified.json +24 -24
  31. package/package.json +3 -4
  32. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  33. package/plugins/agent-hub/kimi-hook.js +2373 -1436
  34. package/plugins/agent-hub/server.js +2445 -1497
  35. package/src/adapters/channel-peer.ts +7 -1
  36. package/src/adapters/compat.ts +1 -1
  37. package/src/adapters/local-probe.ts +174 -0
  38. package/src/adapters/local-worker.ts +232 -21
  39. package/src/cli/console-state.ts +25 -6
  40. package/src/cli/console-versions.ts +99 -0
  41. package/src/cli/console.ts +13 -1
  42. package/src/cli/help.ts +2 -1
  43. package/src/cli/install-paths.ts +7 -2
  44. package/src/cli/main.ts +60 -4
  45. package/src/cli/runtime-version-warning.ts +2 -2
  46. package/src/cli/sdlc-output.ts +9 -5
  47. package/src/hub/config-apply.ts +4 -2
  48. package/src/hub/config-trust.ts +6 -1
  49. package/src/hub/control-client.ts +5 -2
  50. package/src/hub/daemon.ts +169 -9
  51. package/src/hub/events.ts +3 -2
  52. package/src/hub/guidance-probe-store.ts +713 -0
  53. package/src/hub/guidance-probes.ts +358 -0
  54. package/src/hub/inference.ts +18 -5
  55. package/src/hub/operational-authority.ts +13 -1
  56. package/src/hub/peers.ts +5 -0
  57. package/src/hub/ports.ts +1 -1
  58. package/src/hub/progress.ts +23 -16
  59. package/src/hub/report.ts +2 -0
  60. package/src/hub/research.ts +1 -0
  61. package/src/hub/restart.ts +7 -0
  62. package/src/hub/sdlc-release-authorization.ts +139 -17
  63. package/src/hub/sdlc-release-policy.ts +100 -0
  64. package/src/hub/sdlc-release.ts +59 -7
  65. package/src/hub/tasks.ts +317 -6
  66. package/src/local/probe-errors.ts +28 -0
  67. package/src/local/probe-sandbox.ts +224 -0
  68. package/src/local/probe-types.ts +108 -0
  69. package/src/local/probe-workspace.ts +237 -0
  70. package/src/local/sandbox.ts +71 -2
  71. package/src/local/tools.ts +135 -9
  72. package/src/models/route/advisor-trigger.ts +88 -0
  73. package/src/models/route/config.ts +21 -17
  74. package/src/models/route/conversation-view.ts +179 -0
  75. package/src/models/route/decision-evidence.ts +1 -1
  76. package/src/models/route/decision.ts +114 -19
  77. package/src/models/route/escalation-control.ts +30 -0
  78. package/src/models/route/hub-prompts.ts +97 -0
  79. package/src/models/route/judge-choice.ts +155 -0
  80. package/src/models/route/judge-replies.ts +102 -0
  81. package/src/models/route/labels.ts +14 -70
  82. package/src/models/route/observation-signals.ts +250 -0
  83. package/src/models/route/plan-execute-choice.ts +27 -0
  84. package/src/models/route/relay-selector.ts +2 -2
  85. package/src/models/route/runtime.ts +115 -52
  86. package/src/models/route/turn-state.ts +77 -0
  87. package/src/omniroute/client.ts +3 -0
  88. package/src/ui/plugin.ts +70 -20
  89. package/src/version.ts +4 -0
  90. package/templates/adec/README.md +32 -0
  91. package/templates/adec/ahub.plan-execute.json +23 -0
  92. package/templates/adec/ahub.stage.json +23 -0
  93. package/LICENSES/Apache-2.0.txt +0 -204
  94. package/src/models/route/advisor.ts +0 -102
  95. package/src/models/route/escalation.ts +0 -82
  96. package/src/models/route/judge.ts +0 -23
  97. package/src/models/route/normalize.ts +0 -103
  98. package/src/models/route/plan-execute.ts +0 -52
  99. package/src/models/route/prompts.ts +0 -8
  100. package/src/models/route/signals.ts +0 -247
  101. package/src/models/route/state.ts +0 -54
  102. package/src/models/route/text.ts +0 -61
@@ -1,10 +1,11 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
- import { existsSync, mkdtempSync, readdirSync, rmSync, type Dirent } from "node:fs";
2
+ import { existsSync, lstatSync, mkdtempSync, readdirSync, rmdirSync, rmSync, type Dirent } from "node:fs";
3
3
  import { homedir, tmpdir } from "node:os";
4
4
  import { dirname, join, resolve } from "node:path";
5
5
  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
+ import { stopOwnedProcess, trackGroup } from "../hub/child-process.ts";
8
9
 
9
10
  const SANDBOX_EXEC = "/usr/bin/sandbox-exec";
10
11
  export const OUTPUT_CAP = 20_000;
@@ -197,10 +198,15 @@ export function profile(cwd: string, network: SandboxNetwork, readAllow: string[
197
198
  export interface ExecResult {
198
199
  code: number | null;
199
200
  output: string;
201
+ /** Probe-only owned-process proof; ordinary command results retain their existing shape. */
202
+ quiescent?: boolean;
203
+ stop?: () => Promise<void>;
200
204
  }
205
+ export interface ProbeCommandOptions { workspaceRoot: string; temporaryRoot: string; home: string; current(): void; physical(): void }
201
206
 
202
207
  /** Run argv under seatbelt with a scrubbed environment. Never runs unsandboxed: no sandbox, no exec. */
203
- export function sandboxedExec(argv: string[], opts: { cwd: string; profile: string; timeoutMs?: number; env?: Record<string, string>; signal?: AbortSignal; readOnlyData?: boolean }): Promise<ExecResult> {
208
+ export function sandboxedExec(argv: string[], opts: { cwd: string; profile: string; timeoutMs?: number; env?: Record<string, string>; signal?: AbortSignal; readOnlyData?: boolean; probe?: ProbeCommandOptions }): Promise<ExecResult> {
209
+ if (opts.probe) return probeCommand(argv, opts as Parameters<typeof probeCommand>[1]);
204
210
  if (opts.readOnlyData && /\(allow file-write\* \(subpath /.test(opts.profile)) return Promise.resolve({ code: null, output: "error: data.readonly command profile contains a broad write grant" });
205
211
  if (!sandboxAvailable()) return Promise.resolve({ code: null, output: "error: command execution needs macOS sandbox-exec and is disabled on this host" });
206
212
  if (opts.signal?.aborted) return Promise.resolve({ code: null, output: "error: command cancelled before execution" });
@@ -255,6 +261,69 @@ export function sandboxedExec(argv: string[], opts: { cwd: string; profile: stri
255
261
  });
256
262
  }
257
263
 
264
+ /** Same sandbox entry point, with a readonly owned temp and verified cleanup for fixed host proof commands. */
265
+ async function probeCommand(argv: string[], opts: { cwd: string; profile: string; timeoutMs?: number; env?: Record<string, string>; signal?: AbortSignal; probe: ProbeCommandOptions }): Promise<ExecResult> {
266
+ const proof = opts.probe;
267
+ if (!sandboxAvailable()) return { code: null, output: "error: probe confinement needs macOS sandbox-exec", quiescent: true };
268
+ try {
269
+ proof.physical(); proof.current();
270
+ const root = realPath(proof.workspaceRoot), temporary = realPath(proof.temporaryRoot), home = realPath(proof.home);
271
+ if (realPath(opts.cwd) !== root || !temporary.startsWith(root + "/") || !opts.env || opts.env.HOME !== home
272
+ || opts.env.PATH !== "/usr/bin:/bin:/usr/sbin:/sbin" || opts.env.LANG !== "C" || opts.env.TERM !== "dumb"
273
+ || Object.keys(opts.env).some(key => !["PATH", "HOME", "LANG", "TERM"].includes(key))) throw new Error("probe command binding unavailable");
274
+ if (opts.signal?.aborted) throw new Error("probe command cancelled");
275
+ } catch { return { code: null, output: "error: probe command authority or environment unavailable", quiescent: true }; }
276
+ const own = realPath(mkdtempSync(join(proof.temporaryRoot, "command-")));
277
+ const created = lstatSync(own);
278
+ let removed = false;
279
+ const dropOwn = () => {
280
+ if (removed) return;
281
+ proof.physical();
282
+ const current = lstatSync(own);
283
+ if (!current.isDirectory() || current.isSymbolicLink() || current.dev !== created.dev || current.ino !== created.ino || realPath(own) !== own) throw new Error("probe command temp ownership changed");
284
+ // The lane grants no temp writes. Unexpected contents are retained rather than recursively removed.
285
+ rmdirSync(own); removed = true;
286
+ };
287
+ // Never append the ordinary broad temp read/write/exec suffix: the verified profile already bounds this directory.
288
+ const env = { ...opts.env, TMPDIR: `${own}/` };
289
+ return new Promise<ExecResult>(resolve => {
290
+ let child: ReturnType<typeof spawn>;
291
+ try { proof.current(); child = spawn(SANDBOX_EXEC, ["-p", opts.profile, ...argv], { cwd: opts.cwd, env, stdio: ["ignore", "pipe", "pipe"], detached: true }); }
292
+ catch {
293
+ try { dropOwn(); resolve({ code: null, output: "error: probe command did not launch", quiescent: true }); }
294
+ catch { resolve({ code: null, output: "error: probe command setup cleanup is unconfirmed", quiescent: false, stop: async () => dropOwn() }); }
295
+ return;
296
+ }
297
+ trackGroup(child);
298
+ let output = "", settled = false, cancelled = false;
299
+ let pipeTimer: ReturnType<typeof setTimeout> | undefined;
300
+ const take = (data: Buffer) => { if (output.length < OUTPUT_CAP) output += data.toString(); };
301
+ child.stdout?.on("data", take); child.stderr?.on("data", take);
302
+ const stop = async () => { await stopOwnedProcess(child, { group: true }); dropOwn(); };
303
+ const finish = async (code: number | null) => {
304
+ if (settled) return; settled = true;
305
+ clearTimeout(timer); if (pipeTimer) clearTimeout(pipeTimer); opts.signal?.removeEventListener("abort", abort);
306
+ let quiescent = false;
307
+ try { await stop(); quiescent = true; } catch { /* keep the child and directory in the returned owned stop handle */ }
308
+ const clipped = output.length >= OUTPUT_CAP ? `${output.slice(0, OUTPUT_CAP)}\n(output truncated)` : output;
309
+ const observed = child.signalCode ? `${clipped}\n(probe command signal: ${child.signalCode}; owned pid: ${child.pid})` : clipped;
310
+ resolve({ code, output: cancelled ? `${observed}\n(probe command cancelled)` : observed, quiescent, ...(quiescent ? {} : { stop }) });
311
+ };
312
+ const abort = () => { cancelled = true; void finish(null); };
313
+ const timer = setTimeout(abort, opts.timeoutMs ?? 5000);
314
+ opts.signal?.addEventListener("abort", abort, { once: true });
315
+ child.once("error", error => {
316
+ output = `error: probe command spawn failed (${(error as NodeJS.ErrnoException).code ?? "unknown"})`;
317
+ void finish(null);
318
+ });
319
+ child.once("close", code => { void finish(code); });
320
+ // A leader exit is not proof that descendants released pipes. The owned stop proves or retains uncertainty.
321
+ child.once("exit", code => { pipeTimer = setTimeout(() => { void finish(code); }, 500); });
322
+ if (child.exitCode !== null || child.signalCode !== null) pipeTimer = setTimeout(() => { void finish(child.exitCode); }, 500);
323
+ if (opts.signal?.aborted) abort();
324
+ });
325
+ }
326
+
258
327
  /** The environment that sends a command's HTTPS through the egress proxy (#65); empty without one. */
259
328
  export function proxyEnv(network: SandboxNetwork): Record<string, string> {
260
329
  if (typeof network !== "object") return {};
@@ -7,6 +7,8 @@ import { isDenied } from "./deny.ts";
7
7
  import { docRead, type DocReadContext, type DocReadPort } from "./doc-read.ts";
8
8
  import { webFetch, type WebFetchContext, type WebFetchPort } from "./web-fetch.ts";
9
9
  import { OUTPUT_CAP, sandboxedExec } from "./sandbox.ts";
10
+ import { PROBE_WORKSPACE_LIMITS, probeRelativePath } from "./probe-workspace.ts";
11
+ import { formatProbeToolRefusal, ProbeToolRefusal } from "./probe-errors.ts";
10
12
 
11
13
  export { isDenied };
12
14
 
@@ -21,7 +23,69 @@ const approvalError = (picked: ToolApproval, denied: string): string | undefined
21
23
 
22
24
  export type ShellPermitPolicy = { forceAsk?: true };
23
25
  export type ShellExecutionCheck = "valid" | "ask" | "aborted";
26
+ /** Constructor-only probe authority. Model arguments never create or widen this capability. */
27
+ export interface ProbeToolRestriction {
28
+ readonly root: string;
29
+ readonly writableRoots: readonly string[];
30
+ current(): void;
31
+ reserveWrite(bytes: number, canonicalPath: string): Promise<void>;
32
+ }
33
+ function probeCurrent(probe: ProbeToolRestriction): void {
34
+ try { probe.current(); } catch { throw new ProbeToolRefusal("authority_stopped"); }
35
+ }
36
+ export interface ProbeToolResourcePlan {
37
+ readonly scratchBytes: number;
38
+ readonly outputBytes: number;
39
+ readonly target?: string;
40
+ readonly maximumBytes: number;
41
+ }
42
+ interface ProbeToolPlanState { root: string; target?: string; maximum: number; identity?: string; used: boolean }
43
+ const probeToolPlans = new WeakMap<ProbeToolResourcePlan, ProbeToolPlanState>();
44
+ function probeTargetIdentity(target: string): string | undefined {
45
+ const stat = lstatSync(target, { throwIfNoEntry: false });
46
+ if (!stat) return undefined;
47
+ if (!stat.isFile()) throw new ProbeToolRefusal("nonregular_target");
48
+ if (stat.nlink !== 1) throw new ProbeToolRefusal("hardlinked_target");
49
+ return [stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs].join(":");
50
+ }
51
+ /** Content-free pre-admission plan. A paid conservative reservation is not measured filesystem usage. */
52
+ export function planProbeTool(name: string, rawArgs: string, ctx: ToolContext): ProbeToolResourcePlan {
53
+ if (!ctx.probe) throw new ProbeToolRefusal("authority_stopped");
54
+ probeCurrent(ctx.probe);
55
+ const root = realPath(ctx.cwd);
56
+ let target: string | undefined, maximum = 0, identity: string | undefined;
57
+ try {
58
+ if (name === "write" || name === "edit") {
59
+ const value = JSON.parse(rawArgs || "{}");
60
+ target = guardPath(ctx, String(value.path), "write"); identity = probeTargetIdentity(target);
61
+ if (name === "write") maximum = Buffer.byteLength(String(value.content ?? ""), "utf8");
62
+ else {
63
+ const stat = lstatSync(target, { throwIfNoEntry: false });
64
+ if (!stat || !stat.isFile()) throw new ProbeToolRefusal("nonregular_target");
65
+ maximum = Math.min(PROBE_WORKSPACE_LIMITS.fileBytes, stat.size + Buffer.byteLength(String(value.new ?? ""), "utf8"));
66
+ }
67
+ if (maximum > PROBE_WORKSPACE_LIMITS.fileBytes) throw new ProbeToolRefusal("file_ceiling");
68
+ }
69
+ } catch { target = undefined; maximum = 0; identity = undefined; }
70
+ const kind = target === undefined ? undefined : relative(root, target).split("/")[0];
71
+ const plan: ProbeToolResourcePlan = Object.freeze({ scratchBytes: kind === "scratch" ? maximum : 0,
72
+ outputBytes: kind === "output" ? maximum : 0, ...(target === undefined ? {} : { target }), maximumBytes: maximum });
73
+ probeToolPlans.set(plan, { root, target, maximum, identity, used: false });
74
+ return plan;
75
+ }
76
+ /** Verify the already-charged compound tool reservation immediately before its sole filesystem write. */
77
+ export function requireProbeToolWrite(plan: ProbeToolResourcePlan, bytes: number, canonicalPath: string, ctx: ToolContext): void {
78
+ if (ctx.probe) probeCurrent(ctx.probe);
79
+ const state = probeToolPlans.get(plan);
80
+ if (!ctx.probe || !state || state.used || state.target === undefined || !Number.isSafeInteger(bytes) || bytes < 0
81
+ || bytes > state.maximum || realPath(ctx.cwd) !== state.root || canonicalPath !== state.target
82
+ || guardPath(ctx, relative(state.root, canonicalPath), "write") !== state.target || probeTargetIdentity(canonicalPath) !== state.identity) {
83
+ throw new ProbeToolRefusal("target_changed");
84
+ }
85
+ state.used = true;
86
+ }
24
87
  export interface ToolContext {
88
+ probe?: ProbeToolRestriction;
25
89
  readOnly?: string[];
26
90
  cwd: string;
27
91
  /** Extra denylist entries from config: substrings of the project-relative path. */
@@ -56,7 +120,18 @@ const lexists = (p: string) => {
56
120
  };
57
121
 
58
122
  /** Absolute path inside cwd after resolving symlinks, or an Error. `write` also refuses .git and .agenthub. */
59
- export function guardPath(ctx: Pick<ToolContext, "cwd" | "deny" | "readOnly">, path: string, mode: "read" | "write"): string {
123
+ export function guardPath(ctx: Pick<ToolContext, "cwd" | "deny" | "readOnly" | "probe">, path: string, mode: "read" | "write"): string {
124
+ if (ctx.probe) {
125
+ probeCurrent(ctx.probe);
126
+ if (realPath(ctx.probe.root) !== realPath(ctx.cwd)) throw new ProbeToolRefusal("target_changed");
127
+ if (path === "/workspace") path = ".";
128
+ else if (path.startsWith("/workspace/")) path = path.slice("/workspace/".length);
129
+ else if (path.startsWith("/") || /^[a-z]:/i.test(path)) throw new ProbeToolRefusal("outside_workspace");
130
+ if (!(mode === "read" && path === ".") && !probeRelativePath(path)) throw new ProbeToolRefusal("invalid_path");
131
+ const normalized = relative(realPath(ctx.cwd), resolve(realPath(ctx.cwd), path));
132
+ if (!(mode === "read" && !normalized) && !probeRelativePath(normalized)) throw new ProbeToolRefusal("invalid_path");
133
+ path = normalized || ".";
134
+ }
60
135
  const root = realPath(ctx.cwd);
61
136
  const abs = resolve(root, path);
62
137
  // Resolve symlinks on the deepest part that exists: a link pointing outside must not pass as an inside path.
@@ -67,22 +142,49 @@ export function guardPath(ctx: Pick<ToolContext, "cwd" | "deny" | "readOnly">, p
67
142
  try {
68
143
  realExisting = realPath(existing);
69
144
  } catch {
145
+ if (ctx.probe) throw new ProbeToolRefusal("nonregular_target");
70
146
  throw new Error(`${path} goes through a dangling symlink`);
71
147
  }
72
148
  const real = join(realExisting, relative(existing, abs));
73
149
  const rel = relative(root, real);
74
- if (rel.startsWith("..") || resolve(root, rel) !== real) throw new Error(`${path} is outside the project directory`);
150
+ if (rel.startsWith("..") || resolve(root, rel) !== real) {
151
+ if (ctx.probe) throw new ProbeToolRefusal("outside_workspace");
152
+ throw new Error(`${path} is outside the project directory`);
153
+ }
75
154
  // Never trust the resolved name alone (#541): on a hardlinked file Bun's realpath sometimes names another link of the same inode, so the
76
155
  // name the caller typed is judged too. A refusal on either name stands; the typed name only ever adds refusals. Only a typed name INSIDE the project is judged
77
156
  // (`insideRoot`, #555): a name outside it (`../o/.env`, a link into the project) is no project path for any policy to name, and it was never refused before #541.
78
157
  const typed = relative(root, abs), inside = insideRoot(typed);
79
- if (isDenied(rel, ctx.deny) || inside && isDenied(typed, ctx.deny)) throw new Error(`${path} is on the secrets denylist`);
158
+ if (isDenied(rel, ctx.deny) || inside && isDenied(typed, ctx.deny)) {
159
+ if (ctx.probe) throw new ProbeToolRefusal("invalid_path");
160
+ throw new Error(`${path} is on the secrets denylist`);
161
+ }
162
+ if (ctx.probe) {
163
+ const stat = lstatSync(real, { throwIfNoEntry: false });
164
+ if (stat && !stat.isFile() && !(mode === "read" && stat.isDirectory())) throw new ProbeToolRefusal("nonregular_target");
165
+ if (stat?.isFile() && stat.nlink !== 1) throw new ProbeToolRefusal("hardlinked_target");
166
+ if (stat?.isFile() && stat.size > PROBE_WORKSPACE_LIMITS.fileBytes) throw new ProbeToolRefusal("file_ceiling");
167
+ if (mode === "write" && (isHubWritePath(rel) || inside && isHubWritePath(typed) || matchesPolicy(root, path, ctx.readOnly ?? []))) throw new ProbeToolRefusal("unadmitted_write");
168
+ }
80
169
  // Not secret, but writing .git or .agenthub changes what runs outside the worker's control. Names are compared
81
170
  // folded: a new `.GIT/config` is `.git/config` to a case-insensitive disk, and git then runs what it names.
82
171
  if (mode === "write" && (isHubWritePath(rel) || inside && isHubWritePath(typed))) throw new Error(`${path} is not writable by the local worker`);
83
172
  // Identity refusal is stable even when realPath names a protected hardlink alias.
84
173
  if (mode === "write" && ctx.readOnly?.length && (lstatSync(real, { throwIfNoEntry: false })?.nlink ?? 1) > 1) throw new Error("hardlinked write target cannot be verified with data.readonly");
85
174
  if (mode === "write" && matchesPolicy(root, path, ctx.readOnly ?? [])) throw new Error("target is protected by data.readonly");
175
+ if (ctx.probe && mode === "write") {
176
+ const allowed = ctx.probe.writableRoots.some(approved => {
177
+ const spelling = resolve(ctx.probe!.root), requested = resolve(spelling, approved);
178
+ const fromSpelling = relative(spelling, requested);
179
+ const suffix = insideRoot(fromSpelling) ? fromSpelling : relative(root, requested);
180
+ if (!insideRoot(suffix)) return false;
181
+ const entry = resolve(root, suffix), part = relative(root, entry).split("/");
182
+ return part.length > 1 && ["scratch", "output"].includes(part[0]!) && insideRoot(relative(root, entry))
183
+ && insideRoot(relative(entry, real)) && insideRoot(relative(entry, abs));
184
+ });
185
+ if (!allowed) throw new ProbeToolRefusal("unadmitted_write");
186
+ probeCurrent(ctx.probe);
187
+ }
86
188
  return real;
87
189
  }
88
190
 
@@ -154,6 +256,11 @@ export function toolResultFailed(name: string, output: string): boolean {
154
256
 
155
257
  /** Executes one tool call. Never throws: every failure comes back as text for the model to read. */
156
258
  export async function runTool(name: string, rawArgs: string, ctx: ToolContext): Promise<string> {
259
+ if (ctx.probe) {
260
+ if (ctx.signal?.aborted) return formatProbeToolRefusal(new ProbeToolRefusal("authority_stopped"));
261
+ try { probeCurrent(ctx.probe); } catch (error) { return formatProbeToolRefusal(error); }
262
+ if (!["read", "write", "edit"].includes(name)) return formatProbeToolRefusal(new ProbeToolRefusal("tool_unavailable"));
263
+ }
157
264
  let a: Record<string, any>;
158
265
  try {
159
266
  a = JSON.parse(rawArgs || "{}");
@@ -161,7 +268,7 @@ export async function runTool(name: string, rawArgs: string, ctx: ToolContext):
161
268
  return "error: tool arguments were not valid JSON";
162
269
  }
163
270
  try {
164
- if (ctx.signal?.aborted) return "error: turn cancelled before tool execution";
271
+ if (ctx.signal?.aborted) return ctx.probe ? formatProbeToolRefusal(new ProbeToolRefusal("authority_stopped")) : "error: turn cancelled before tool execution";
165
272
  switch (name) {
166
273
  case "read": {
167
274
  const file = guardPath(ctx, String(a.path), "read");
@@ -175,11 +282,20 @@ export async function runTool(name: string, rawArgs: string, ctx: ToolContext):
175
282
  let file = guardPath(ctx, String(a.path), "write");
176
283
  const approvedTarget = file;
177
284
  const content = String(a.content ?? "");
285
+ if (ctx.probe && Buffer.byteLength(content, "utf8") > PROBE_WORKSPACE_LIMITS.fileBytes) return formatProbeToolRefusal(new ProbeToolRefusal("file_ceiling"));
178
286
  const refused = approvalError(await ctx.permit(`write ${a.path} (${content.length} chars):\n${preview(content)}`, "write", ctx.signal, file, undefined, String(a.path), a), "error: the user did not approve this write");
179
287
  if (refused) return refused;
180
- if (ctx.signal?.aborted) return "error: turn cancelled before write";
288
+ if (ctx.signal?.aborted) return ctx.probe ? formatProbeToolRefusal(new ProbeToolRefusal("authority_stopped")) : "error: turn cancelled before write";
181
289
  file = guardPath(ctx, String(a.path), "write");
182
- if (file !== approvedTarget) return "error: path target changed during approval; inspect before retrying";
290
+ if (file !== approvedTarget) return ctx.probe ? formatProbeToolRefusal(new ProbeToolRefusal("target_changed")) : "error: path target changed during approval; inspect before retrying";
291
+ if (ctx.probe) {
292
+ const bytes = Buffer.byteLength(content, "utf8");
293
+ if (bytes > PROBE_WORKSPACE_LIMITS.fileBytes) return formatProbeToolRefusal(new ProbeToolRefusal("file_ceiling"));
294
+ await ctx.probe.reserveWrite(bytes, file);
295
+ probeCurrent(ctx.probe);
296
+ if (ctx.signal?.aborted) return formatProbeToolRefusal(new ProbeToolRefusal("authority_stopped"));
297
+ if (guardPath(ctx, String(a.path), "write") !== approvedTarget) return formatProbeToolRefusal(new ProbeToolRefusal("target_changed"));
298
+ }
183
299
  mkdirSync(dirname(file), { recursive: true });
184
300
  writeFileSync(file, content);
185
301
  return `wrote ${a.path}`;
@@ -192,14 +308,23 @@ export async function runTool(name: string, rawArgs: string, ctx: ToolContext):
192
308
  if (!a.old || count !== 1) return `error: \`old\` must match exactly once, it matched ${count} times`;
193
309
  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, undefined, String(a.path), a), "error: the user did not approve this edit");
194
310
  if (refused) return refused;
195
- if (ctx.signal?.aborted) return "error: turn cancelled before edit";
311
+ if (ctx.signal?.aborted) return ctx.probe ? formatProbeToolRefusal(new ProbeToolRefusal("authority_stopped")) : "error: turn cancelled before edit";
196
312
  // Approval can outlive another peer's edit or a path change. Apply only the approved fragment to current bytes.
197
313
  file = guardPath(ctx, String(a.path), "write");
198
- if (file !== approvedTarget) return "error: path target changed during approval; inspect before retrying";
314
+ if (file !== approvedTarget) return ctx.probe ? formatProbeToolRefusal(new ProbeToolRefusal("target_changed")) : "error: path target changed during approval; inspect before retrying";
199
315
  text = readFileSync(file, "utf8");
200
316
  count = text.split(String(a.old)).length - 1;
201
317
  if (count !== 1) return `error: file changed during approval; \`old\` must match exactly once, it matched ${count} times`;
202
- writeFileSync(file, text.replace(String(a.old), () => String(a.new ?? "")));
318
+ const replacement = text.replace(String(a.old), () => String(a.new ?? ""));
319
+ if (ctx.probe) {
320
+ const bytes = Buffer.byteLength(replacement, "utf8");
321
+ if (bytes > PROBE_WORKSPACE_LIMITS.fileBytes) return formatProbeToolRefusal(new ProbeToolRefusal("file_ceiling"));
322
+ await ctx.probe.reserveWrite(bytes, file);
323
+ probeCurrent(ctx.probe);
324
+ if (ctx.signal?.aborted) return formatProbeToolRefusal(new ProbeToolRefusal("authority_stopped"));
325
+ if (guardPath(ctx, String(a.path), "write") !== approvedTarget || readFileSync(file, "utf8") !== text) return formatProbeToolRefusal(new ProbeToolRefusal("target_changed"));
326
+ }
327
+ writeFileSync(file, replacement);
203
328
  return `edited ${a.path}`;
204
329
  }
205
330
  case "bash": {
@@ -255,6 +380,7 @@ export async function runTool(name: string, rawArgs: string, ctx: ToolContext):
255
380
  return `error: unknown tool ${name}`;
256
381
  }
257
382
  } catch (e) {
383
+ if (ctx.probe) return formatProbeToolRefusal(e);
258
384
  return `error: ${(e as Error).message}`;
259
385
  }
260
386
  }
@@ -0,0 +1,88 @@
1
+ import type { JudgeConversation } from "./conversation-view.ts";
2
+
3
+ const LEDGER_ENTRIES = 1024, STALLED_SCOPES = 1024, FAILED_REVIEWS = 3;
4
+ const CONFIG_LIMIT = 200_000, SCOPE_KEY_BYTES = 4096;
5
+ interface Budget { charged: number; failures: number }
6
+ export interface AdvisorTriggerOptions {
7
+ trigger?: "no_tool_call" | "pattern";
8
+ pattern?: string;
9
+ maxReviews?: number;
10
+ gateMinToolResults?: number;
11
+ gateStallTurns?: number;
12
+ }
13
+
14
+ /** Host review eligibility and reservation ledger, deliberately separate from ScopeStore. */
15
+ export class AdvisorTrigger {
16
+ private readonly budgets = new Map<string, Budget>();
17
+ private readonly checkpoints = new Set<string>();
18
+ private readonly reviewLimit: number;
19
+ private readonly minimumResults: number;
20
+ private readonly stallAt: number;
21
+ private readonly pattern: RegExp | undefined;
22
+
23
+ constructor(options: AdvisorTriggerOptions = {}) {
24
+ this.reviewLimit = options.maxReviews ?? 1;
25
+ this.minimumResults = options.gateMinToolResults ?? 0;
26
+ this.stallAt = options.gateStallTurns ?? 0;
27
+ for (const [value, minimum] of [[this.reviewLimit, 1], [this.minimumResults, 0], [this.stallAt, 0]] as const) {
28
+ if (!Number.isSafeInteger(value) || value < minimum || value > CONFIG_LIMIT) throw new RangeError("invalid advisor gate bound");
29
+ }
30
+ if (options.trigger !== undefined && options.trigger !== "no_tool_call" && options.trigger !== "pattern") throw new TypeError("invalid advisor trigger");
31
+ if (options.trigger === "pattern") {
32
+ if (!options.pattern) throw new TypeError("advisor pattern is required");
33
+ this.pattern = new RegExp(options.pattern, "u");
34
+ }
35
+ }
36
+
37
+ eligible(view: JudgeConversation | undefined, terminal: { hasToolUse: boolean; visibleText: string }, scope = "instance"): boolean {
38
+ this.key(scope);
39
+ if (this.exhausted(this.budgets.get(scope)) || !view) return false;
40
+ const primary = this.pattern ? this.pattern.test(terminal.visibleText)
41
+ : !terminal.hasToolUse && view.resultCount >= this.minimumResults;
42
+ const checkpoint = this.stallAt > 0 && view.assistantTurns >= this.stallAt && !this.checkpoints.has(scope);
43
+ if (!primary && checkpoint) { this.checkpointRoom(scope); this.checkpoints.add(scope); }
44
+ return primary || checkpoint;
45
+ }
46
+
47
+ reserve(scope = "instance"): boolean {
48
+ this.key(scope);
49
+ const budget = this.budgets.get(scope) ?? { charged: 0, failures: 0 };
50
+ if (this.exhausted(budget)) { this.checkpoints.delete(scope); return false; }
51
+ this.budgetRoom(scope);
52
+ this.budgets.set(scope, { charged: budget.charged + 1, failures: budget.failures });
53
+ return true;
54
+ }
55
+
56
+ settle(scope: string, result: "success" | "failure"): void {
57
+ this.key(scope);
58
+ if (result === "success") return;
59
+ const budget = this.budgets.get(scope) ?? { charged: 0, failures: 0 };
60
+ this.budgetRoom(scope);
61
+ this.budgets.set(scope, { charged: Math.max(0, budget.charged - 1), failures: Math.min(FAILED_REVIEWS, budget.failures + 1) });
62
+ this.checkpoints.delete(scope);
63
+ }
64
+
65
+ evict(scope: string): void {
66
+ this.key(scope);
67
+ if (scope !== "instance") this.budgets.delete(scope);
68
+ this.checkpoints.delete(scope);
69
+ }
70
+
71
+ private exhausted(budget: Budget | undefined): boolean {
72
+ return !!budget && (budget.charged >= this.reviewLimit || budget.failures >= FAILED_REVIEWS);
73
+ }
74
+ private budgetRoom(scope: string): void {
75
+ if (!this.budgets.has(scope) && this.budgets.size >= LEDGER_ENTRIES) {
76
+ for (const key of this.budgets.keys()) if (key !== "instance") { this.budgets.delete(key); break; }
77
+ }
78
+ }
79
+ private checkpointRoom(scope: string): void {
80
+ if (!this.checkpoints.has(scope) && this.checkpoints.size >= STALLED_SCOPES) {
81
+ const key = this.checkpoints.values().next().value;
82
+ if (key !== undefined) this.checkpoints.delete(key);
83
+ }
84
+ }
85
+ private key(scope: string): void {
86
+ if (typeof scope !== "string" || !scope || scope.length > SCOPE_KEY_BYTES || Buffer.byteLength(scope) > SCOPE_KEY_BYTES) throw new RangeError("invalid advisor scope");
87
+ }
88
+ }
@@ -50,6 +50,8 @@ export function parseHubRoutes(input: unknown): Record<string, HubRoute> {
50
50
  out[id] = parseDecisionConfig(id, r);
51
51
  } else if (r.type === "stage") {
52
52
  out[id] = parseStageConfig(id, r);
53
+ } else if (SERVICE_FIELDS.some(field => r[field] !== undefined)) {
54
+ out[id] = parseDecisionConfig(id, r);
53
55
  } else out[id] = r as unknown as HubRoute;
54
56
  }
55
57
  return out;
@@ -59,33 +61,21 @@ export function parseHubRoutes(input: unknown): Record<string, HubRoute> {
59
61
  function parseStageConfig(id: string, r: Record<string, unknown>): HubRoute {
60
62
  if (r.classifier === undefined) {
61
63
  if (r.ambiguous_band !== undefined) throw new Error(`routing.toml: invalid ${id}.ambiguous_band; set classifier = "decision" first`);
64
+ if (SERVICE_FIELDS.some(field => r[field] !== undefined)) throw new Error(`routing.toml: invalid ${id} service binding; set classifier = "decision" first`);
62
65
  return r as unknown as HubRoute;
63
66
  }
64
67
  const problem = (field: string, step: string): never => { throw new Error(`routing.toml: invalid ${id}.${field}; ${step}`); };
65
68
  if (r.classifier !== "decision") problem("classifier", 'use "decision"');
66
- // ponytail: these four service validators repeat parseDecisionConfig because a stage route names two tiers instead of alias/effort pairs; fold both into one adec-service parser if a third route type needs it.
67
- if (r.decision_backend !== "adec") problem("decision_backend", 'set decision_backend = "adec" for a loopback policy service');
68
- if (r.decision_mode === "enforce") throw new Error("decision_mode enforce is not available yet; use shadow; tracked in #554");
69
- if (r.decision_mode !== undefined && !["off", "shadow"].includes(String(r.decision_mode))) problem("decision_mode", 'use "off" or "shadow"');
70
- if (typeof r.policy_id !== "string" || !/^[a-z0-9][a-z0-9._-]{0,49}$/.test(r.policy_id)) problem("policy_id", "name a configured adec policy with 1 to 50 lowercase identifier characters");
71
- const endpoint = r.adec_endpoint ?? "http://127.0.0.1:8740/v1/route";
72
- if (!isAdecRouteEndpoint(endpoint)) problem("adec_endpoint", "use an HTTP numeric loopback /v1/route URL without credentials, query or fragment");
73
- if (r.decision_timeout_ms !== undefined && (!Number.isSafeInteger(r.decision_timeout_ms) || Number(r.decision_timeout_ms) < 1 || Number(r.decision_timeout_ms) > 30_000)) problem("decision_timeout_ms", "use 1 to 30000 milliseconds");
69
+ const service = parseServiceConfig(id, r);
74
70
  for (const tier of ["efficient", "capable"] as const) if (typeof r[tier] !== "string" || !(r[tier] as string).trim()) problem(tier, 'name the model alias this tier executes when classifier = "decision"');
75
71
  const band = r.ambiguous_band ?? AMBIGUOUS_BAND_DEFAULT;
76
72
  if (typeof band !== "number" || !Number.isFinite(band) || band < 0 || band > AMBIGUOUS_BAND_MAX) problem("ambiguous_band", `use a number from 0 to ${AMBIGUOUS_BAND_MAX}`);
77
- return { ...r, decision_backend: "adec", decision_mode: r.decision_mode ?? "off", adec_endpoint: endpoint, ambiguous_band: band } as unknown as HubRoute;
73
+ return { ...r, ...service, ambiguous_band: band } as unknown as HubRoute;
78
74
  }
79
75
 
80
76
  function parseDecisionConfig(id: string, r: Record<string, unknown>): HubRoute {
77
+ const service = parseServiceConfig(id, r);
81
78
  const problem = (field: string, step: string): never => { throw new Error(`routing.toml: invalid ${id}.${field}; ${step}`); };
82
- if (r.decision_backend !== "adec") problem("decision_backend", 'set decision_backend = "adec" for a loopback policy service');
83
- if (r.decision_mode === "enforce") throw new Error("decision_mode enforce is not available yet; use shadow; tracked in #554");
84
- if (r.decision_mode !== undefined && !["off", "shadow"].includes(String(r.decision_mode))) problem("decision_mode", 'use "off" or "shadow"');
85
- if (typeof r.policy_id !== "string" || !/^[a-z0-9][a-z0-9._-]{0,49}$/.test(r.policy_id)) problem("policy_id", "name a configured adec policy with 1 to 50 lowercase identifier characters");
86
- const endpoint = r.adec_endpoint ?? "http://127.0.0.1:8740/v1/route";
87
- if (!isAdecRouteEndpoint(endpoint)) problem("adec_endpoint", "use an HTTP numeric loopback /v1/route URL without credentials, query or fragment");
88
- if (r.decision_timeout_ms !== undefined && (!Number.isSafeInteger(r.decision_timeout_ms) || Number(r.decision_timeout_ms) < 1 || Number(r.decision_timeout_ms) > 30_000)) problem("decision_timeout_ms", "use 1 to 30000 milliseconds");
89
79
  if (!Array.isArray(r.candidates) || !r.candidates.length || r.candidates.length > 26) problem("candidates", "list 1 to 26 policy alias/effort pairs");
90
80
  const candidates: { alias: string; efforts: string[] }[] = [], seen = new Set<string>();
91
81
  let pairCount = 0;
@@ -98,5 +88,19 @@ function parseDecisionConfig(id: string, r: Record<string, unknown>): HubRoute {
98
88
  if (seen.has(alias) || new Set(efforts).size !== efforts.length || pairCount > 26) problem("candidates", "remove duplicate aliases/efforts and keep at most 26 pairs");
99
89
  seen.add(alias); candidates.push({ alias, efforts: [...efforts] });
100
90
  }
101
- return { ...r, decision_backend: "adec", decision_mode: r.decision_mode ?? "off", adec_endpoint: endpoint, candidates } as unknown as HubRoute;
91
+ return { ...r, ...service, candidates } as unknown as HubRoute;
92
+ }
93
+
94
+ const SERVICE_FIELDS = ["decision_backend", "decision_mode", "policy_id", "adec_endpoint", "candidates", "decision_timeout_ms"] as const;
95
+ /** One validator for service binding, independent of a route's stage/host semantics. */
96
+ function parseServiceConfig(id: string, r: Record<string, unknown>): Pick<HubRoute, "decision_backend" | "decision_mode" | "adec_endpoint"> {
97
+ const problem = (field: string, step: string): never => { throw new Error(`routing.toml: invalid ${id}.${field}; ${step}`); };
98
+ if (r.decision_backend !== "adec") problem("decision_backend", 'set decision_backend = "adec" for a loopback policy service');
99
+ if (r.decision_mode === "enforce") throw new Error("decision_mode enforce is not available yet; use shadow; tracked in #554");
100
+ if (r.decision_mode !== undefined && !["off", "shadow"].includes(String(r.decision_mode))) problem("decision_mode", 'use "off" or "shadow"');
101
+ if (typeof r.policy_id !== "string" || !/^[a-z0-9][a-z0-9._-]{0,49}$/.test(r.policy_id)) problem("policy_id", "name a configured adec policy with 1 to 50 lowercase identifier characters");
102
+ const endpoint = r.adec_endpoint ?? "http://127.0.0.1:8740/v1/route";
103
+ if (!isAdecRouteEndpoint(endpoint)) return problem("adec_endpoint", "use an HTTP numeric loopback /v1/route URL without credentials, query or fragment");
104
+ if (r.decision_timeout_ms !== undefined && (!Number.isSafeInteger(r.decision_timeout_ms) || Number(r.decision_timeout_ms) < 1 || Number(r.decision_timeout_ms) > 30_000)) problem("decision_timeout_ms", "use 1 to 30000 milliseconds");
105
+ return { decision_backend: "adec", decision_mode: (r.decision_mode ?? "off") as "off" | "shadow", adec_endpoint: endpoint };
102
106
  }