@staix/agent-hub 0.38.0 → 0.40.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 (195) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/README.md +28 -12
  3. package/docs/adding-an-ai-tool.md +7 -5
  4. package/docs/agent-notes/README.md +23 -0
  5. package/docs/agent-notes/adapters.md +9 -5
  6. package/docs/agent-notes/benchmarks.md +2 -0
  7. package/docs/agent-notes/budget.md +9 -0
  8. package/docs/agent-notes/bus.md +1 -0
  9. package/docs/agent-notes/daemon.md +21 -9
  10. package/docs/agent-notes/local-worker.md +4 -2
  11. package/docs/agent-notes/security-review.md +56 -0
  12. package/docs/agent-notes/tasks.md +22 -6
  13. package/docs/agent-notes/tests.md +10 -9
  14. package/docs/contracts/companion-cli-v1.json +4 -0
  15. package/docs/design/adapters.md +142 -0
  16. package/docs/design/agent-hub-architecture.md +46 -1
  17. package/docs/design/agent-hub.md +10 -0
  18. package/docs/design/bus.md +7 -0
  19. package/docs/design/cli-output.md +183 -0
  20. package/docs/design/execution-reference.md +6 -1
  21. package/docs/design/roadmap.md +191 -0
  22. package/docs/design/task-board.md +185 -5
  23. package/docs/dogfood.md +30 -9
  24. package/docs/events.md +7 -7
  25. package/docs/memory.md +5 -5
  26. package/docs/operations.md +315 -54
  27. package/docs/profiles.md +101 -8
  28. package/docs/quickstart.md +47 -6
  29. package/docs/research.md +6 -3
  30. package/docs/roles.md +52 -0
  31. package/docs/sdlc.md +190 -2
  32. package/docs/security.md +90 -15
  33. package/docs/text-projection.md +1 -0
  34. package/docs/verification/2026-11-13-claude-implementer-2.1.323.md +59 -0
  35. package/docs/verification/2026-11-13-codex-01672-reviewer-isolation.md +69 -0
  36. package/docs/verification/2026-11-14-0.39.0.md +51 -0
  37. package/docs/verification/2026-11-14-codex-0169-reviewer-isolation.md +70 -0
  38. package/docs/verification/2026-11-14-codex-0169-reviewer-tool-call.md +48 -0
  39. package/docs/verification/2026-11-14-pi-152-compat.md +45 -0
  40. package/docs/verification/2026-11-15-0.40.0.md +39 -0
  41. package/docs/verification/2026-11-16-pi-loopback-1447.md +39 -0
  42. package/docs/verification/pi-152-model-free.ts +57 -0
  43. package/docs/verification/pi-152-native.mjs +21 -0
  44. package/docs/verified.json +48 -25
  45. package/package.json +4 -4
  46. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  47. package/plugins/agent-hub/kimi-hook.js +2266 -530
  48. package/plugins/agent-hub/kimi-review-policy-worker.js +16 -11
  49. package/plugins/agent-hub/server.js +2423 -645
  50. package/src/adapters/acp-model-policy.ts +1 -1
  51. package/src/adapters/acp-session-model.ts +35 -0
  52. package/src/adapters/acp.ts +14 -0
  53. package/src/adapters/agy/definition.ts +2 -2
  54. package/src/adapters/agy/hooks.ts +7 -0
  55. package/src/adapters/claude-channel.ts +1 -1
  56. package/src/adapters/claude-implementer.ts +8 -0
  57. package/src/adapters/claude-print-child.ts +26 -2
  58. package/src/adapters/claude-print.ts +4 -0
  59. package/src/adapters/codex-appserver.ts +90 -16
  60. package/src/adapters/codex-review-isolation.ts +63 -17
  61. package/src/adapters/compat.ts +10 -10
  62. package/src/adapters/conformance/fakes/acp-server.ts +11 -2
  63. package/src/adapters/conformance/fakes/app-server.ts +5 -1
  64. package/src/adapters/conformance/fakes/pi-rpc.ts +1 -1
  65. package/src/adapters/definitions/builtin-metadata.ts +12 -12
  66. package/src/adapters/definitions/native-cli-jcode-mcp.ts +18 -3
  67. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  68. package/src/adapters/definitions/native-config-policy.ts +1 -1
  69. package/src/adapters/definitions/native-quota.ts +122 -0
  70. package/src/adapters/definitions/native-recovery.ts +3 -0
  71. package/src/adapters/definitions/qwen.ts +2 -2
  72. package/src/adapters/kimi-review.ts +23 -0
  73. package/src/adapters/kimi-wire-usage.ts +39 -16
  74. package/src/adapters/local-worker.ts +9 -4
  75. package/src/adapters/pi-state-model.ts +12 -0
  76. package/src/adapters/pi.ts +76 -11
  77. package/src/adapters/print-result-model.ts +24 -0
  78. package/src/adapters/registry-types.ts +12 -2
  79. package/src/adapters/registry.ts +19 -2
  80. package/src/adapters/reviewer-print.ts +132 -16
  81. package/src/adapters/role-eligibility.ts +99 -0
  82. package/src/adapters/same-directory.ts +16 -0
  83. package/src/cli/agy-mcp.ts +18 -7
  84. package/src/cli/answer-args.ts +11 -3
  85. package/src/cli/console-question.ts +1 -1
  86. package/src/cli/console-state.ts +98 -11
  87. package/src/cli/console.ts +6 -2
  88. package/src/cli/error-format.ts +19 -0
  89. package/src/cli/free-text.ts +20 -0
  90. package/src/cli/handoff-args.ts +1 -1
  91. package/src/cli/help.ts +350 -30
  92. package/src/cli/identity-audit.ts +8 -7
  93. package/src/cli/identity.ts +27 -4
  94. package/src/cli/init-prompt.ts +31 -2
  95. package/src/cli/init-roles.ts +156 -0
  96. package/src/cli/init-settings.ts +24 -2
  97. package/src/cli/init.ts +232 -17
  98. package/src/cli/main.js +2 -2
  99. package/src/cli/main.ts +250 -69
  100. package/src/cli/model.ts +1 -1
  101. package/src/cli/output-standard.ts +56 -0
  102. package/src/cli/output.ts +199 -9
  103. package/src/cli/preview.ts +1 -1
  104. package/src/cli/recovery-launch.ts +114 -0
  105. package/src/cli/recovery-package.ts +14 -7
  106. package/src/cli/recovery-version-preflight.ts +104 -0
  107. package/src/cli/roadmap.ts +215 -0
  108. package/src/cli/role-doctor.ts +39 -0
  109. package/src/cli/sdlc-output.ts +66 -1
  110. package/src/cli/smoke-pty-bridge.ts +7 -24
  111. package/src/cli/study-output.ts +54 -0
  112. package/src/cli/study.ts +14 -1
  113. package/src/cli/task-output.ts +3 -1
  114. package/src/cli/terminal-recovery.ts +14 -0
  115. package/src/cli/upgrade-presentation-flags.ts +2 -2
  116. package/src/cli/upgrade-presentation.ts +4 -0
  117. package/src/cli/upgrade-restore-state.ts +12 -3
  118. package/src/cli/upgrade-runtime.ts +40 -2
  119. package/src/cli/upgrade.ts +8 -4
  120. package/src/hub/advisor-survey.ts +139 -0
  121. package/src/hub/audit-source.ts +66 -0
  122. package/src/hub/board.ts +677 -15
  123. package/src/hub/budget.ts +54 -4
  124. package/src/hub/bus.ts +9 -0
  125. package/src/hub/check-runner.ts +3 -4
  126. package/src/hub/ci-watch.ts +19 -4
  127. package/src/hub/conductor.ts +14 -8
  128. package/src/hub/config-apply.ts +2 -1
  129. package/src/hub/config-edit-host.ts +77 -5
  130. package/src/hub/considered-findings.ts +47 -0
  131. package/src/hub/control-client.ts +1 -1
  132. package/src/hub/daemon.ts +585 -98
  133. package/src/hub/deliverable-files.ts +17 -1
  134. package/src/hub/dogfood-profile.ts +3 -2
  135. package/src/hub/events.ts +25 -4
  136. package/src/hub/execution-reference.ts +1 -1
  137. package/src/hub/folder-trigger.ts +11 -4
  138. package/src/hub/github-import.ts +81 -0
  139. package/src/hub/hub-tools.ts +117 -20
  140. package/src/hub/install-policy.ts +23 -0
  141. package/src/hub/kimi-usage.ts +34 -2
  142. package/src/hub/lifecycle-schema.ts +3 -3
  143. package/src/hub/memory-profile.ts +9 -1
  144. package/src/hub/memory-sync-state.ts +1 -0
  145. package/src/hub/model-overrides.ts +2 -1
  146. package/src/hub/no-writes.ts +5 -0
  147. package/src/hub/operational-authority.ts +8 -1
  148. package/src/hub/operational-view.ts +6 -2
  149. package/src/hub/peers.ts +2 -0
  150. package/src/hub/pi-failure.ts +7 -0
  151. package/src/hub/plan-conformance.ts +20 -2
  152. package/src/hub/question-desk.ts +26 -7
  153. package/src/hub/questions.ts +33 -5
  154. package/src/hub/quota-account.ts +34 -0
  155. package/src/hub/recovery-policy.ts +18 -4
  156. package/src/hub/research-evidence.ts +51 -3
  157. package/src/hub/research.ts +77 -13
  158. package/src/hub/restart.ts +21 -0
  159. package/src/hub/review-budget.ts +88 -0
  160. package/src/hub/review-findings.ts +93 -12
  161. package/src/hub/reviewer-pool-config.ts +6 -2
  162. package/src/hub/reviewer-pool.ts +39 -6
  163. package/src/hub/roadmap-triage.ts +86 -0
  164. package/src/hub/roadmap-unplaced.ts +169 -0
  165. package/src/hub/roadmap-view.ts +83 -0
  166. package/src/hub/roadmap.ts +127 -0
  167. package/src/hub/routing.ts +7 -3
  168. package/src/hub/sdlc-merge.ts +6 -5
  169. package/src/hub/sdlc-queue.ts +17 -7
  170. package/src/hub/sdlc-release.ts +1 -1
  171. package/src/hub/sdlc.ts +47 -8
  172. package/src/hub/security-audit.ts +178 -0
  173. package/src/hub/security-pass.ts +115 -0
  174. package/src/hub/settings.ts +11 -5
  175. package/src/hub/source-read.ts +80 -2
  176. package/src/hub/sources.ts +57 -9
  177. package/src/hub/specs-task.ts +7 -0
  178. package/src/hub/startup-event-seeds.ts +5 -3
  179. package/src/hub/startup-timing.ts +1 -0
  180. package/src/hub/synthesis-readiness.ts +279 -0
  181. package/src/hub/task-sweep.ts +29 -2
  182. package/src/hub/task-worktree.ts +37 -0
  183. package/src/hub/tasks.ts +1464 -76
  184. package/src/hub/text-projection.ts +11 -1
  185. package/src/memory/capture.ts +2 -1
  186. package/src/pi/dependency-publish.ts +50 -0
  187. package/src/pi/extension.ts +1 -1
  188. package/src/pi/launch.ts +1 -1
  189. package/src/pi/task-dependencies.ts +249 -0
  190. package/src/ui/index.html +56 -13
  191. package/src/ui/office-model.ts +11 -3
  192. package/src/ui/office-space.ts +50 -30
  193. package/src/ui/plugin-questions.ts +5 -0
  194. package/src/ui/plugin.ts +27 -12
  195. package/templates/config.json +1 -1
@@ -29,21 +29,21 @@ export interface CompatPolicy {
29
29
 
30
30
  const plain = (text: string) => text.length <= 64 && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(text) ? text : undefined;
31
31
  export const COMPAT = {
32
- // Receipts: docs/verification/2026-10-26-pi-140-compat.md (1.4.0); docs/verification/2026-11-03-pi-150-compat.md (1.5.0)
33
- pi: { label: "Pi", verified: ["1.4.0", "1.5.0"], gate: "contract", probe: ["pi", "--version"], config: "pi.cmd",
32
+ // Receipts: docs/verification/2026-10-26-pi-140-compat.md (1.4.0); docs/verification/2026-11-03-pi-150-compat.md (1.5.0); docs/verification/2026-11-14-pi-152-compat.md (1.5.2)
33
+ pi: { label: "Pi", verified: ["1.4.0", "1.5.0", "1.5.2"], gate: "contract", probe: ["pi", "--version"], config: "pi.cmd",
34
34
  parse: out => plain(out.trim()),
35
- trustNote: "The model-free extension load, RPC session identity and managed tool receipt path were checked on 1.4.0 and 1.5.0. Permissions remain host-owned; account-backed inference and another version's extension contract are unverified.",
36
- receipt: "docs/verification/2026-11-03-pi-150-compat.md" },
37
- // Transport receipts: docs/verification/2026-10-23-headless-claude-permissions.md; 2.1.310: docs/verification/2026-10-26-claude-implementer-2.1.310.md; 2.1.314 (transport and wrapper): docs/verification/2026-10-31-claude-implementer-2.1.314.md; 2.1.316: docs/verification/2026-10-31-claude-implementer-2.1.316.md; 2.1.318: docs/verification/2026-11-05-claude-implementer-2.1.318.md; 2.1.319: docs/verification/2026-11-06-claude-implementer-2.1.319.md; 2.1.322: docs/verification/2026-11-10-claude-implementer-2.1.322.md; host-wrapper receipt below repeats with them.
38
- "claude-implementer": { label: "Claude headless implementer", verified: ["2.1.309", "2.1.310", "2.1.314", "2.1.316", "2.1.318", "2.1.319", "2.1.322"], gate: "contract", probe: ["claude", "--version"],
35
+ trustNote: "The model-free extension load, RPC session identity and managed tool receipt path were checked on 1.4.0, 1.5.0 and 1.5.2. Permissions remain host-owned; account-backed inference and another version's extension contract are unverified.",
36
+ receipt: "docs/verification/2026-11-14-pi-152-compat.md" },
37
+ // Transport receipts: docs/verification/2026-10-23-headless-claude-permissions.md; 2.1.310: docs/verification/2026-10-26-claude-implementer-2.1.310.md; 2.1.314 (transport and wrapper): docs/verification/2026-10-31-claude-implementer-2.1.314.md; 2.1.316: docs/verification/2026-10-31-claude-implementer-2.1.316.md; 2.1.318: docs/verification/2026-11-05-claude-implementer-2.1.318.md; 2.1.319: docs/verification/2026-11-06-claude-implementer-2.1.319.md; 2.1.322: docs/verification/2026-11-10-claude-implementer-2.1.322.md; 2.1.323: docs/verification/2026-11-13-claude-implementer-2.1.323.md; host-wrapper receipt below repeats with them.
38
+ "claude-implementer": { label: "Claude headless implementer", verified: ["2.1.309", "2.1.310", "2.1.314", "2.1.316", "2.1.318", "2.1.319", "2.1.322", "2.1.323"], gate: "contract", probe: ["claude", "--version"],
39
39
  parse: out => plain(out.trim().replace(/ \(Claude Code\)$/, "")),
40
40
  trustNote: "The native prompt-tool transport and host-wrapper rewrite, environment isolation and replay contract have isolated receipts. No dontAsk/bypass fallback exists; another version's permission or rewrite behavior is unverified.",
41
- receipt: "docs/verification/2026-11-10-claude-implementer-2.1.322.md" },
42
- // 0.163.0 receipt: docs/verification/2026-10-22-codex-reviewer-isolation.md; 0.164.0 receipt: docs/verification/2026-10-24-codex-0164-reviewer-isolation.md; 0.166.0: docs/verification/2026-10-31-codex-0166-reviewer-isolation.md; 0.167.0 model-free only, not verified until its model-backed run: docs/verification/2026-11-06-codex-0167-reviewer-isolation.md
43
- "codex-review": { label: "Codex reviewer (codex-cli)", verified: ["0.146.0", "0.163.0", "0.164.0", "0.166.0"], gate: "isolation", probe: ["codex", "--version"], config: "codex_bin",
41
+ receipt: "docs/verification/2026-11-13-claude-implementer-2.1.323.md" },
42
+ // 0.163.0 receipt: docs/verification/2026-10-22-codex-reviewer-isolation.md; 0.164.0 receipt: docs/verification/2026-10-24-codex-0164-reviewer-isolation.md; 0.166.0: docs/verification/2026-10-31-codex-0166-reviewer-isolation.md; 0.167.0 model-free only, not verified until its model-backed run: docs/verification/2026-11-06-codex-0167-reviewer-isolation.md; 0.167.2 model-free only, not verified until its model-backed run: docs/verification/2026-11-13-codex-01672-reviewer-isolation.md; 0.169.0 (model-free and one model-backed review): docs/verification/2026-11-14-codex-0169-reviewer-isolation.md and docs/verification/2026-11-14-codex-0169-reviewer-tool-call.md
43
+ "codex-review": { label: "Codex reviewer (codex-cli)", verified: ["0.146.0", "0.163.0", "0.164.0", "0.166.0", "0.169.0"], gate: "isolation", probe: ["codex", "--version"], config: "codex_bin",
44
44
  parse: out => plain(out.trim().replace(/^codex-cli /, "")),
45
45
  trustNote: "Every launch still proves the MCP inventory, Apps/plugins/hooks disabled, sandbox read/write denial and the binary fence; a failed leg still refuses. Trust covers only the source-level claims those probes cannot see (docs/verification/2026-10-19-reviewer-isolation.md).",
46
- receipt: "docs/verification/2026-11-06-codex-0167-reviewer-isolation.md" },
46
+ receipt: "docs/verification/2026-11-14-codex-0169-reviewer-isolation.md" },
47
47
  // Kimi 2.3.0 / Qwen 0.26.0 receipt: docs/verification/2026-10-22-kimi-qwen-compat.md; Kimi 2.3.1: docs/verification/2026-10-25-kimi-231-reviewer-compat.md; Kimi 2.3.2: docs/verification/2026-10-26-kimi-232-reviewer-compat.md; Kimi 2.4.1: docs/verification/2026-10-31-kimi-241-reviewer-compat.md; Kimi 2.5.1: docs/verification/2026-11-06-kimi-251-reviewer-compat.md
48
48
  "kimi-review": { label: "Kimi reviewer (kimi-code)", verified: ["2.2.0", "2.3.0", "2.3.1", "2.3.2", "2.4.1", "2.5.1"], gate: "isolation", probe: ["kimi", "--version"],
49
49
  parse: out => plain(out.trim()),
@@ -8,6 +8,15 @@ import { createInterface } from "node:readline";
8
8
  import { KIMI_2_1_1_5H_REFUSAL_PREFIX } from "../../acp-quota.ts";
9
9
 
10
10
  const delay = Number(process.env.FAKE_ACP_DELAY_MS ?? 20);
11
+ // #1402: `--model-id <id>` reports a current model in the session result, as `models.currentModelId` (Kimi, Jcode, Qwen) or, with `--model-shape config`, as the `model` select of `configOptions`.
12
+ const argAfter = (flag: string) => { const i = process.argv.indexOf(flag); return i >= 0 ? process.argv[i + 1] : undefined; };
13
+ const sessionModelShape = (): Record<string, unknown> => {
14
+ const id = argAfter("--model-id");
15
+ if (!id) return {};
16
+ return argAfter("--model-shape") === "config"
17
+ ? { configOptions: [{ id: "model", type: "select", currentValue: id, options: [{ value: id, name: id }] }] }
18
+ : { models: { currentModelId: id, availableModels: [{ modelId: id, name: id }] } };
19
+ };
11
20
  let responseBatch: string[] | undefined;
12
21
  const send = (m: unknown) => { const line = `${JSON.stringify(m)}\n`; if (responseBatch) responseBatch.push(line); else process.stdout.write(line); };
13
22
  const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
@@ -223,13 +232,13 @@ createInterface({ input: process.stdin }).on("line", (line) => {
223
232
  if (record > 0) Bun.write(process.argv[record + 1]!, msg.params.sessionId); // argv, not env: the hub scrubs a child's environment
224
233
  // what a real agent does while it loads: replay the history, then answer
225
234
  send({ jsonrpc: "2.0", method: "session/update", params: { sessionId: msg.params.sessionId, update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "replayed history" } } } });
226
- send({ jsonrpc: "2.0", id: msg.id, result: { modes } });
235
+ send({ jsonrpc: "2.0", id: msg.id, result: { modes, ...sessionModelShape() } });
227
236
  }
228
237
  else if (msg.method === "session/new") {
229
238
  modes.currentModeId = arg("--new-mode") ?? "default";
230
239
  if (process.env.FAKE_ACP_RECORD) Bun.write(process.env.FAKE_ACP_RECORD, JSON.stringify(msg.params));
231
240
  if (process.env.FAKE_ACP_ENV_RECORD) Bun.write(process.env.FAKE_ACP_ENV_RECORD, JSON.stringify({ recovery: process.env.AGENTHUB_RECOVERY_OPERATION, codex: process.env.CODEX_HOME, claude: process.env.CLAUDE_CONFIG_DIR, state: process.env.AGENTHUB_STATE_DIR }));
232
- send({ jsonrpc: "2.0", id: msg.id, result: { sessionId: "s1", modes } });
241
+ send({ jsonrpc: "2.0", id: msg.id, result: { sessionId: "s1", modes, ...sessionModelShape() } });
233
242
  }
234
243
  else if (msg.method === "session/set_mode") {
235
244
  modePending = true;
@@ -6,6 +6,7 @@ export function startFakeAppServer(
6
6
  usedPercent = 93,
7
7
  reportApprovalPolicy = true,
8
8
  onRequest?: (msg: any) => void,
9
+ rateLimitsRead?: () => unknown,
9
10
  ) {
10
11
  let turnSeq = 0;
11
12
  let threadTotal = 0; // the thread's running token total, as Codex keeps it
@@ -36,7 +37,7 @@ export function startFakeAppServer(
36
37
  reply({ thread: { id: msg.params.threadId }, model: "fake", ...(reportApprovalPolicy ? { approvalPolicy: msg.params.approvalPolicy ?? "untrusted" } : {}) });
37
38
  return note("thread/tokenUsage/updated", { threadId: msg.params.threadId, turnId: "old", tokenUsage: { total: usage(threadTotal), last: usage(800) } });
38
39
  }
39
- if (msg.method === "account/rateLimits/read") return reply({ rateLimits: { primary: { usedPercent, windowDurationMins: 300, resetsAt: 1_900_000_000 }, secondary: null } });
40
+ if (msg.method === "account/rateLimits/read") return reply(rateLimitsRead ? rateLimitsRead() : { rateLimits: { primary: { usedPercent, windowDurationMins: 300, resetsAt: 1_900_000_000 }, secondary: null } });
40
41
  if (msg.method === "thread/revert") {
41
42
  reverted.push(msg.params);
42
43
  onRevert?.(msg.params);
@@ -73,6 +74,9 @@ export function startFakeAppServer(
73
74
  }
74
75
  reply({ turn });
75
76
  note("turn/started", { threadId, turn });
77
+ // `REROUTE:<model>` is Codex moving the running turn to another model (schema `model/rerouted`).
78
+ const rerouted = /REROUTE:(\S+)/.exec(text)?.[1];
79
+ if (rerouted) note("model/rerouted", { threadId, turnId: turn.id, fromModel: "fake", toModel: rerouted, reason: "highRiskCyberActivity" });
76
80
  await Bun.sleep(delayMs);
77
81
  const slow = /SLOW:(\d+)/.exec(text); // a turn that keeps running for this many ms
78
82
  if (slow) await Bun.sleep(Number(slow[1]));
@@ -14,7 +14,7 @@ let messageCount = 0;
14
14
  const send = (value: unknown) => process.stdout.write(`${JSON.stringify(value)}\n`);
15
15
  createInterface({ input: process.stdin }).on("line", (line) => {
16
16
  const request = JSON.parse(line) as { id?: string; type?: string };
17
- if (request.type === "get_state") send({ type: "response", id: request.id, command: "get_state", success: true, data: { isStreaming: false, isCompacting: false, pendingMessageCount: 0, messageCount, sessionId, sessionFile } });
17
+ if (request.type === "get_state") send({ type: "response", id: request.id, command: "get_state", success: true, data: { ...(option("--model-id") ? { model: { id: option("--model-id"), name: option("--model-id"), api: "openai-completions", provider: "agent-hub-local" } } : {}), isStreaming: false, isCompacting: false, pendingMessageCount: 0, messageCount, sessionId, sessionFile } });
18
18
  else if (request.type === "set_model") send({ type: "response", id: request.id, command: "set_model", success: true });
19
19
  else if (request.type === "prompt" || request.type === "steer") { messageCount++; send({ type: "response", id: request.id, command: request.type, success: true }); }
20
20
  });
@@ -75,7 +75,7 @@ const CLAUDE_IMPLEMENTER_VARIANT: AdapterDefinition = {
75
75
  // daemon.ts runtime mappings/stop policy, budget.ts exemptions, and ui/peer-palette.ts CSS foregrounds.
76
76
  export const NATIVE_BUILTIN_DEFINITIONS_WITHOUT_QWEN: readonly AdapterDefinition[] = Object.freeze([
77
77
  {
78
- projection: { roleRank: 0, helpRank: 0, plannerEligible: true },
78
+ projection: { roleRank: 0, helpRank: 0, plannerEligible: true, conductorEligible: true, reviewerEligible: true },
79
79
  api: 1, kind: "claude", questionWaitMs: 45000, displayName: "Claude Code", family: "claude", transport: "claude-channel",
80
80
  roles: Object.freeze(["planner", "reviewer"]), defaultOnRoster: true, trust: { onPrem: false, hubSandboxed: false },
81
81
  start: { forms: Object.freeze(["tui"] as const), defaultForm: "tui", launch: claudeNativeLaunch, version: claudeObservedVersion, ...CLAUDE_LAUNCH_POLICY, conductorStartable: true, upStart: { allowed: true, default: true },
@@ -87,12 +87,12 @@ export const NATIVE_BUILTIN_DEFINITIONS_WITHOUT_QWEN: readonly AdapterDefinition
87
87
  "never-ask": "every tool runs without asking" } },
88
88
  session: { idField: "sessionId", currentId: sessionId("sessionId"), configDirEnv: "CLAUDE_CONFIG_DIR", zeroTurnFresh: true, launchKind: "claude-channel", launchRecord: true, ...CLAUDE_RECOVERY_SESSION, crashPlan: claudeCrashPlan, unrecordedTerminal: "always" },
89
89
  turnEnd: "native-hook", settle: { signal: "native-stop" }, budget: { account: "claude", checkpoint: true, reader: { source: "claude status line", read: claudeWindows }, context: { source: "claude_statusline", read: claudeContext } },
90
- cli: { command: "claude", entry: { lifecycleAdmission: true, execute: runClaudeEntry }, preview: previewClaude, usage: [["ahub claude [--print-command] [--unattended] [args...]", "launch Claude Code with the hub channel"]], retainedTerminalNotice: claudeRetainedTerminalNotice, stopNotice: () => "this peer belongs to a native terminal; end it in its terminal", startWords: () => ["claude"] }, display: CLAUDE_DISPLAY, hooks: { recallPlatform: "claude", recallSource: "claude", recallInjected: true, pluginInventory: claudePluginInventory },
90
+ cli: { command: "claude", entry: { lifecycleAdmission: true, execute: runClaudeEntry }, preview: previewClaude, usage: [["ahub claude [--print-command] [--unattended] [args...]", "launch Claude Code with the hub channel", "launch Claude Code with the hub channel"]], retainedTerminalNotice: claudeRetainedTerminalNotice, stopNotice: () => "this peer belongs to a native terminal; end it in its terminal", startWords: () => ["claude"] }, display: CLAUDE_DISPLAY, hooks: { recallPlatform: "claude", recallSource: "claude", recallInjected: true, pluginInventory: claudePluginInventory },
91
91
  reviewerVariant: CLAUDE_REVIEWER_VARIANT, headlessVariant: CLAUDE_IMPLEMENTER_VARIANT,
92
92
  },
93
93
  {
94
94
  reviewerVariant: CODEX_REVIEWER_VARIANT,
95
- projection: { roleRank: 1, startRank: 1, helpRank: 1, plannerEligible: true },
95
+ projection: { roleRank: 1, startRank: 1, helpRank: 1, plannerEligible: true, conductorEligible: true, reviewerEligible: true },
96
96
  api: 1, kind: "codex", questionWaitMs: 45000, displayName: "Codex", family: "codex", transport: "codex-appserver",
97
97
  modelOverride: { boundary: "turn" },
98
98
  roles: Object.freeze(["implementer"]), defaultOnRoster: true, trust: { onPrem: false, hubSandboxed: false },
@@ -102,11 +102,11 @@ export const NATIVE_BUILTIN_DEFINITIONS_WITHOUT_QWEN: readonly AdapterDefinition
102
102
  permission: { trackUnattended: true, grants: { ask: "the session's own approval policy applies again", "ask-when-needed": "approval policy on-request on every turn", "never-ask": "approval policy never on every turn: nothing asks" } },
103
103
  session: { nativeRevert: true, idField: "threadId", currentId: sessionId("threadId"), configDirEnv: "CODEX_HOME", zeroTurnFresh: true, launchKind: "codex", launchRecord: true, ...CODEX_RECOVERY_SESSION, crashPlan: codexCrashPlan, unrecordedTerminal: "always" },
104
104
  turnEnd: "adapter", settle: { signal: "turn-completed" }, budget: { account: "codex", checkpoint: true, reader: { source: "codex rateLimits", read: codexWindows }, context: { source: "codex_token_usage", read: codexContext } },
105
- cli: { command: "codex", entry: { lifecycleAdmission: true, execute: runCodexEntry }, preview: previewCodex, usage: [["ahub codex [--print-command] [--unattended] [args...]", "start the Codex adapter and attach the TUI"]], launchConfigKeys: ["codex_bin"], retainedTerminalNotice: codexRetainedTerminalNotice, rosterReturnNotice: codexRosterReturnNotice, stopNotice: () => "this peer belongs to a native terminal; end it in its terminal", startWords: () => ["codex"] }, display: CODEX_DISPLAY, hooks: { recallPlatform: "codex", recallSource: "codex", recallInjected: true, pluginInventory: codexPluginInventory, classifyTool: codexToolSemantic },
105
+ cli: { command: "codex", entry: { lifecycleAdmission: true, execute: runCodexEntry }, preview: previewCodex, usage: [["ahub codex [--print-command] [--unattended] [args...]", "start the Codex adapter and attach the TUI", "start the Codex adapter and attach the TUI"]], launchConfigKeys: ["codex_bin"], retainedTerminalNotice: codexRetainedTerminalNotice, rosterReturnNotice: codexRosterReturnNotice, stopNotice: () => "this peer belongs to a native terminal; end it in its terminal", startWords: () => ["codex"] }, display: CODEX_DISPLAY, hooks: { recallPlatform: "codex", recallSource: "codex", recallInjected: true, pluginInventory: codexPluginInventory, classifyTool: codexToolSemantic },
106
106
  },
107
107
  {
108
108
  reviewerVariant: KIMI_REVIEWER_VARIANT,
109
- projection: { roleRank: 2, startRank: 2, helpRank: 2, plannerEligible: true },
109
+ projection: { roleRank: 2, startRank: 2, helpRank: 2, plannerEligible: true, conductorEligible: false, reviewerEligible: true },
110
110
  api: 1, kind: "kimi", questionWaitMs: 45000, displayName: "Kimi Code", family: "kimi", transport: "acp",
111
111
  modelOverride: { boundary: "turn", acp: { admission: { nativeIdentity: true }, agentName: "Kimi Code CLI", version: "2.5.2",
112
112
  setter: "set_config_option", modelUpdate: "config_option_update", receipt: "docs/verification/2026-11-08-kimi-252-model-setter-1317.md" } },
@@ -120,10 +120,10 @@ export const NATIVE_BUILTIN_DEFINITIONS_WITHOUT_QWEN: readonly AdapterDefinition
120
120
  unmanagedForms: Object.freeze(["tui"] as const), unmanagedStatusNote: "Kimi approves tools in its own TUI; no hub permission mode", unmanagedNote: "Kimi approves tools and selects its permission mode in its own TUI; no hub permission mode" },
121
121
  session: { idField: "sessionId", currentId: sessionId("sessionId"), freshOnRestore: true, launchKind: "acp", ...KIMI_RECOVERY_SESSION, crashPlan: kimiCrashPlan },
122
122
  turnEnd: "adapter", settle: { signal: "prompt-response" }, budget: { account: "kimi", resetSoftTokensOnResume: true, context: { source: "acp_usage_update", read: acpContextValue } }, capabilities: { watch: true }, hooks: { factsHook: KIMI_TUI_FACTS_HOOK, recallPlatform: "kimi", recallSource: "kimi" },
123
- cli: { command: "kimi", entry: { lifecycleAdmission: true, execute: runKimiEntry }, preview: previewKimi, usage: [["ahub kimi [--print-command] [--mode tui|headless] [--model <alias>]", "default: Kimi's own TUI, pull-only via hub_inbox; no push, steer, watchdog, console approvals or automatic quota handoff. Select headless for ACP"]], launchConfigKeys: ["kimi_cmd", "peers.kimi.start_mode"], stopNotice: form => form === "tui" ? "Kimi belongs to its own TUI terminal; end it in that terminal" : "", startWords: form => ["kimi", "--mode", form] }, display: KIMI_DISPLAY,
123
+ cli: { command: "kimi", entry: { lifecycleAdmission: true, execute: runKimiEntry }, preview: previewKimi, usage: [["ahub kimi [--print-command] [--mode tui|headless] [--model <alias>]", "default: Kimi's own TUI, pull-only via hub_inbox; no push, steer, watchdog, console approvals or automatic quota handoff. Select headless for ACP", "start Kimi in its own TUI, or headless over ACP"]], launchConfigKeys: ["kimi_cmd", "peers.kimi.start_mode"], stopNotice: form => form === "tui" ? "Kimi belongs to its own TUI terminal; end it in that terminal" : "", startWords: form => ["kimi", "--mode", form] }, display: KIMI_DISPLAY,
124
124
  },
125
125
  {
126
- projection: { roleRank: 4, startRank: 0, helpRank: 6, plannerEligible: false },
126
+ projection: { roleRank: 4, startRank: 0, helpRank: 6, plannerEligible: false, conductorEligible: true, reviewerEligible: true },
127
127
  api: 1, kind: "pi", questionWaitMs: 300000, title: "hub", titlePersistence: "native", enabledSwitchStartOnly: true, displayName: "Pi", family: "pi", transport: "hub-native",
128
128
  modelOverride: { boundary: "turn" },
129
129
  roles: implementerRoles, defaultOnRoster: false, trust: { onPrem: false, hubSandboxed: true },
@@ -134,10 +134,10 @@ export const NATIVE_BUILTIN_DEFINITIONS_WITHOUT_QWEN: readonly AdapterDefinition
134
134
  session: { idField: "sessionId", currentId: sessionId("sessionId"), restoreOnStart: true, launchKind: "pi", launchRecord: true, ...PI_RECOVERY_SESSION, crashPlan: piCrashPlan, unrecordedTerminal: "tui", continuityBookmark: piRecoveryContinuity, continuity: { key: "pi", parse: parsePiContinuity } },
135
135
  turnEnd: "adapter", settle: { signal: "agent-settled" }, budget: { account: "pi", instrumented: true, noQuotaReason: "on-prem backends have no provider quota" }, reporting: { tokensNotReported: true }, configuration: { schema: piConfigSchema, routingSchema: piRoutingSchema, settings: PI_SETTINGS, restartReasons: PI_RESTART_REASONS, validateEffective: piEffectiveConfig },
136
136
  routing: { localAllowedRefusal: "local_allowed = false also excludes pi for this class", longContext: "backend-limit", preferredTier: true, handoffPriority: 0, trace: "backend", backendLabel: "pi" },
137
- cli: { command: "pi", entry: { lifecycleAdmission: false, execute: runPiEntry }, preview: previewPi, usage: [["ahub pi [--print-command] [--mode headless|tui | --headless] [--backend auto|dgx|mlx] [--model <alias>] [--session-id <id>] [--session-file <path>] [--replace-session]", "start Pi: its TUI in this terminal unless --headless or the start mode setting (peers.pi.start_mode) says headless; without a terminal the hub opens one or says how"]], launchConfigKeys: ["pi.cmd", "pi.backend", "pi.dgx_coding", "pi.dgx_fast", "pi.max_steps", "routing.pi", "peers.pi.start_mode"], previewArgs: ["--mode", "tui"], retainedTerminalNotice: piRetainedTerminalNotice, personOnlyFlags: ["--replace-session"], startWords: form => ["pi", "--mode", form] }, display: PI_DISPLAY,
137
+ cli: { command: "pi", entry: { lifecycleAdmission: false, execute: runPiEntry }, preview: previewPi, usage: [["ahub pi [--print-command] [--mode headless|tui | --headless] [--backend auto|dgx|mlx] [--model <alias>] [--session-id <id>] [--session-file <path>] [--replace-session]", "start Pi: its TUI in this terminal unless --headless or the start mode setting (peers.pi.start_mode) says headless; without a terminal the hub opens one or says how", "start Pi in a terminal, or headless"]], launchConfigKeys: ["pi.cmd", "pi.backend", "pi.dgx_coding", "pi.dgx_fast", "pi.max_steps", "routing.pi", "peers.pi.start_mode"], previewArgs: ["--mode", "tui"], retainedTerminalNotice: piRetainedTerminalNotice, personOnlyFlags: ["--replace-session"], startWords: form => ["pi", "--mode", form] }, display: PI_DISPLAY,
138
138
  },
139
139
  {
140
- projection: { roleRank: 3, helpRank: 7, plannerEligible: false },
140
+ projection: { roleRank: 3, helpRank: 7, plannerEligible: false, conductorEligible: false, reviewerEligible: true },
141
141
  api: 1, kind: "local", questionWaitMs: 300000, title: "hub", displayName: "Local worker", family: "local", transport: "hub-native",
142
142
  modelOverride: { boundary: "turn" },
143
143
  roles: implementerRoles, defaultOnRoster: true, trust: { onPrem: true, hubSandboxed: true },
@@ -148,10 +148,10 @@ export const NATIVE_BUILTIN_DEFINITIONS_WITHOUT_QWEN: readonly AdapterDefinition
148
148
  session: { idField: "sessionId", currentId: sessionId("sessionId"), freshOnRestore: true, launchKind: "local", ...LOCAL_RECOVERY_SESSION, crashPlan: localCrashPlan },
149
149
  turnEnd: "adapter", settle: { signal: "route-outcome" }, budget: { account: "local", quotaExempt: true, instrumented: true, noQuotaReason: "on-prem gateway has no provider quota" }, configuration: { schema: localConfigSchema, routingSchema: localRoutingSchema, restartReasons: LOCAL_RESTART_REASONS },
150
150
  routing: { localAllowedRefusal: "local_allowed = false for this class", longContext: "skip-owner", preferredTier: true, handoffPriority: 1, trace: "route" },
151
- cli: { command: "local", entry: { lifecycleAdmission: false, execute: runLocalEntry }, usage: [["ahub local [--route <id> | --model <id>]", "start the hub-native worker on the self-hosted models (routing.toml)"]], launchConfigKeys: ["local.deny", "local.bash_network", "local.network_allow", "local.max_steps", "local.read_allow", "routing.local"], startWords: () => ["local"] }, display: LOCAL_DISPLAY,
151
+ cli: { command: "local", entry: { lifecycleAdmission: false, execute: runLocalEntry }, usage: [["ahub local [--route <id> | --model <id>]", "start the hub-native worker on the self-hosted models (routing.toml)", "start the hub-native worker on self-hosted models"]], launchConfigKeys: ["local.deny", "local.bash_network", "local.network_allow", "local.max_steps", "local.read_allow", "routing.local"], startWords: () => ["local"] }, display: LOCAL_DISPLAY,
152
152
  },
153
153
  {
154
- projection: { roleRank: 6, startRank: 3, helpRank: 3, plannerEligible: true },
154
+ projection: { roleRank: 6, startRank: 3, helpRank: 3, plannerEligible: true, conductorEligible: true, reviewerEligible: true },
155
155
  api: 1, kind: "jcode", questionWaitMs: 45000, displayName: "Jcode", family: "jcode", transport: "acp",
156
156
  roles: implementerRoles, optional: true, defaultOnRoster: false, trust: { onPrem: false, hubSandboxed: false },
157
157
  start: { create: createJcode, preflight: jcodeStartPreflight, daemonPort: "owned-acp", forms: dualForms, defaultForm: "tui", explicitHeadlessMode: true, conductorStartable: true, upStart: { allowed: true }, hubSwitches: [], ownedFlags: [] },
@@ -161,6 +161,6 @@ export const NATIVE_BUILTIN_DEFINITIONS_WITHOUT_QWEN: readonly AdapterDefinition
161
161
  ask: "no verified hub mode mapping; native policy only", "ask-when-needed": "no verified hub mode mapping; native policy only", "never-ask": "no verified hub mode mapping; native policy only" } },
162
162
  session: { idField: "sessionId", currentId: sessionId("sessionId"), launchKind: "jcode", ...JCODE_RECOVERY_SESSION, crashPlan: jcodeCrashPlan }, turnEnd: "adapter", settle: { signal: "prompt-response" }, budget: { account: "jcode", context: { source: "jcode_usage_update", read: jcodeContextValue } },
163
163
  // Jcode has no dedicated CSS swatch today: retain peer-palette.ts's existing 'other' fallback.
164
- cli: { command: "jcode", entry: { lifecycleAdmission: true, execute: runJcodeEntry }, preview: previewJcode, usage: [["ahub jcode [--mode tui|headless] [--model <alias>] [--provider-profile <name>] [--session-id <id>] [--print-command]", "optional Jcode (roster.jcode, default off): its TUI on the hub-owned ACP session, opened once that session is saved; --mode headless for ACP only; native policy unmanaged, no hub sandbox"]], authority: "person", launchConfigKeys: ["jcode_cmd", "jcode_home", "jcode_provider_profile"], startWords: mode => ["jcode", "--mode", mode] }, display: JCODE_DISPLAY, hooks: { recallPlatform: "jcode" },
164
+ cli: { command: "jcode", entry: { lifecycleAdmission: true, execute: runJcodeEntry }, preview: previewJcode, usage: [["ahub jcode [--mode tui|headless] [--model <alias>] [--provider-profile <name>] [--session-id <id>] [--print-command]", "optional Jcode (roster.jcode, default off): its TUI on the hub-owned ACP session, opened once that session is saved; --mode headless for ACP only; native policy unmanaged, no hub sandbox", "start optional Jcode, in its TUI or headless"]], authority: "person", launchConfigKeys: ["jcode_cmd", "jcode_home", "jcode_provider_profile"], startWords: mode => ["jcode", "--mode", mode] }, display: JCODE_DISPLAY, hooks: { recallPlatform: "jcode" },
165
165
  },
166
166
  ] satisfies AdapterDefinition[]);
@@ -2,6 +2,7 @@ import { closeSync, constants, existsSync, fstatSync, lstatSync, mkdirSync, open
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { join } from "node:path";
4
4
  import { hubGitSync } from "../../hub/git.ts";
5
+ import { sameDirectory, shownValue } from "../same-directory.ts";
5
6
 
6
7
  export const JCODE_MCP_FILE = ".jcode/mcp.json", JCODE_MCP_NAME = "agent-hub-jcode";
7
8
  type Document = Record<string, unknown>;
@@ -24,8 +25,21 @@ const map = (doc: Document): Document => (doc.mcpServers ?? doc.servers ?? {}) a
24
25
  * hub tools act as the base peer. Each owned launch path supplies its own id instead (peerChildEnv for serve and ACP, the TUI launch env).
25
26
  * An entry written before this still hardcodes the id: `jcodeMcpReady` is false for it, and the launcher rewrites it.
26
27
  */
27
- const owned = (entry: unknown, cwd: string): entry is Document => object(entry) && object(entry.env) && entry.env.AGENTHUB_MODE === "tools"
28
- && (entry.env.AGENTHUB_PEER_ID === undefined || entry.env.AGENTHUB_PEER_ID === "jcode") && entry.env.AGENTHUB_PROJECT_DIR === cwd;
28
+ /**
29
+ * The first field that makes an existing entry not the hub's, or undefined when it is. The project dir is compared by real path (#1423): a project directory that was renamed, with the old
30
+ * path left as a symlink, still names this directory, so the hub's own entry from before the move is rewritten rather than refused as foreign.
31
+ */
32
+ function foreignField(entry: unknown, cwd: string): string | undefined {
33
+ if (!object(entry)) return "the entry is not an object";
34
+ if (!object(entry.env)) return "env is missing";
35
+ if (entry.env.AGENTHUB_MODE !== "tools") return "AGENTHUB_MODE is not tools";
36
+ if (entry.env.AGENTHUB_PEER_ID !== undefined && entry.env.AGENTHUB_PEER_ID !== "jcode") return "AGENTHUB_PEER_ID names another peer";
37
+ if (!sameDirectory(entry.env.AGENTHUB_PROJECT_DIR, cwd)) {
38
+ const named = shownValue(entry.env.AGENTHUB_PROJECT_DIR);
39
+ return `AGENTHUB_PROJECT_DIR ${named ? `${named} ` : ""}is not this project (${cwd})`;
40
+ }
41
+ return undefined;
42
+ }
29
43
 
30
44
  export function jcodeMcpEntry(cwd: string, stateDir: string, bundle: string) {
31
45
  return { command: "bun", args: ["run", bundle], shared: false, env: { AGENTHUB_MODE: "tools", AGENTHUB_DELIVERY_ONLY: "true", AGENTHUB_STATE_DIR: stateDir, AGENTHUB_PROJECT_DIR: cwd } };
@@ -48,7 +62,8 @@ export function jcodeMcpReady(cwd: string, stateDir: string, bundle: string): bo
48
62
  /** Only the console launcher calls this; daemon starts use jcodeMcpReady read-only. */
49
63
  export function configureJcodeMcp(cwd: string, stateDir: string, bundle: string, remove = false): { changed: boolean; tracked: boolean } {
50
64
  const current = inspect(cwd), servers = { ...map(current) }, existing = servers[JCODE_MCP_NAME];
51
- if (existing !== undefined && !owned(existing, cwd)) throw new Error("agent-hub-jcode is a foreign MCP entry; it was not changed");
65
+ const why = existing === undefined ? undefined : foreignField(existing, cwd);
66
+ if (why !== undefined) throw new Error(`agent-hub-jcode is a foreign MCP entry (${why}); it was not changed. If it is the hub's own entry from before the project moved, remove the ${JCODE_MCP_NAME} key from ${JCODE_MCP_FILE} and run ahub jcode again.`);
52
67
  if (remove) delete servers[JCODE_MCP_NAME]; else servers[JCODE_MCP_NAME] = jcodeMcpEntry(cwd, stateDir, bundle);
53
68
  const key = current.servers !== undefined ? "servers" : "mcpServers";
54
69
  const next = { ...current, ...(current[key] !== undefined || !remove ? { [key]: servers } : {}) };
@@ -8,7 +8,7 @@ export function nativeConfigurationDefaults(ctx: { home: string; env: Readonly<R
8
8
  return {
9
9
  commands: { kimi_cmd: ["kimi", "acp"], qwen_cmd: ["qwen", "--acp"], jcode_cmd: ["jcode"], jcode_home: ctx.env.JCODE_HOME ?? join(ctx.home, ".jcode"), jcode_provider_profile: "" },
10
10
  proxy: { codex_bin: "codex" },
11
- rpc: { pi: { enabled: false, auto_start: false, cmd: ["pi"], backend: "auto" as const, dgx_coding: "coding", dgx_fast: "fast", max_steps: 30 } },
11
+ rpc: { pi: { enabled: false, auto_start: false, cmd: ["pi"], backend: "auto" as const, dgx_coding: "coding", dgx_fast: "fast", max_steps: 100, max_continuations: 2 } },
12
12
  sandbox: { local: { deny: [] as string[], bash_network: false, network_allow: ctx.networkAllow, max_steps: 30, read_allow: [] as string[], doc_read: false, web_fetch: { allow: [] as string[] } } },
13
13
  };
14
14
  }
@@ -4,7 +4,7 @@ import { webFetchAllow } from "../../local/web-fetch-config.ts";
4
4
 
5
5
  /** Native config uses the host's checked schema vocabulary, retaining its shape/path introspection. */
6
6
  export function piConfigSchema(v: NativeConfigValidators): Record<string, NativeConfigCheck> {
7
- return { pi: v.block({ enabled: v.bool, auto_start: v.bool, cmd: v.argv, backend: v.words(["auto", "dgx", "mlx"]), dgx_coding: v.text, dgx_fast: v.text, max_steps: v.number(1, 1_000_000, true) }) };
7
+ return { pi: v.block({ enabled: v.bool, auto_start: v.bool, cmd: v.argv, backend: v.words(["auto", "dgx", "mlx"]), dgx_coding: v.text, dgx_fast: v.text, max_steps: v.number(1, 1_000_000, true), max_continuations: v.number(0, 10, true) }) };
8
8
  }
9
9
  export function localConfigSchema(v: NativeConfigValidators): Record<string, NativeConfigCheck> {
10
10
  return { local: v.block({ deny: v.strings, bash_network: (value, key) => { if (value !== "direct") v.bool(value, key); }, network_allow: v.strings, max_steps: v.number(1, 1_000_000, true), read_allow: v.strings, doc_read: v.bool, web_fetch: v.block({ allow: (value, key) => { webFetchAllow(value); void key; } }) }) };
@@ -1,3 +1,5 @@
1
+ import { quotaAccountUsage, type QuotaAccountUsage } from "../../hub/quota-account.ts";
2
+ import { types } from "node:util";
1
3
  import type { UsageWindow } from "../../hub/budget.ts";
2
4
 
3
5
  /** Codex `rateLimits` snapshot (account/rateLimits/read, account/rateLimits/updated) -> windows. */
@@ -27,3 +29,123 @@ export function claudeWindows(rateLimits: any): UsageWindow[] {
27
29
  }
28
30
  return out;
29
31
  }
32
+
33
+
34
+ /** Bounds inspection of native detail rows; the native availableCount remains authoritative. */
35
+ const MAX_RESET_CREDIT_DETAILS = 128;
36
+ const record = (value: unknown): Record<string, unknown> => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
37
+ const epochMillis = (value: unknown): number | undefined => {
38
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) return undefined;
39
+ const ms = value * 1000;
40
+ return Number.isSafeInteger(ms) && Number.isFinite(new Date(ms).getTime()) ? ms : undefined;
41
+ };
42
+
43
+ /** Codex 0.167.2 GetAccountRateLimitsResponse: no balance, account/credit id, title or description escapes. */
44
+ export function codexAccountUsage(snapshot: unknown): QuotaAccountUsage {
45
+ const value = record(snapshot), limits = record(value.rateLimits), credits = record(limits.credits), reset = record(value.rateLimitResetCredits);
46
+ const out: QuotaAccountUsage = {};
47
+ if (typeof value.ordinaryUsageAllowed === "boolean") out.ordinaryUsageAllowed = value.ordinaryUsageAllowed;
48
+ if (typeof credits.hasCredits === "boolean") out.hasCredits = credits.hasCredits;
49
+ if (typeof credits.unlimited === "boolean") out.unlimited = credits.unlimited;
50
+ const count = reset.availableCount;
51
+ if (typeof count === "number" && Number.isSafeInteger(count) && count >= 0) {
52
+ out.resetCreditsAvailable = count;
53
+ out.resetCreditsExpiryKnown = count === 0;
54
+ const rows = reset.credits;
55
+ // Native lists may be capped: a partial list cannot prove the earliest expiry across the full count.
56
+ if (count > 0 && Array.isArray(rows) && rows.length === count && rows.length <= MAX_RESET_CREDIT_DETAILS) {
57
+ let complete = true, earliest: number | undefined;
58
+ for (const item of rows) {
59
+ const row = record(item);
60
+ if (row.status !== "available" || row.resetType !== "codexRateLimits") { complete = false; break; }
61
+ if (row.expiresAt === null) continue; // explicitly non-expiring; absence instead means unknown
62
+ const expires = epochMillis(row.expiresAt);
63
+ if (expires === undefined) { complete = false; break; }
64
+ earliest = earliest === undefined ? expires : Math.min(earliest, expires);
65
+ }
66
+ out.resetCreditsExpiryKnown = complete;
67
+ if (complete && earliest !== undefined) out.resetCreditsExpireAt = earliest;
68
+ }
69
+ }
70
+ return quotaAccountUsage(out);
71
+ }
72
+
73
+ /** Preserve the existing window callback shape without forwarding raw account/credit data. */
74
+ export function codexQuotaWindowInput(value: unknown): unknown {
75
+ const raw = record(value);
76
+ const window = (value: unknown) => {
77
+ const row = record(value);
78
+ if (typeof row.usedPercent !== "number" || !Number.isFinite(row.usedPercent)) return null;
79
+ return { usedPercent: row.usedPercent,
80
+ ...(typeof row.windowDurationMins === "number" && Number.isFinite(row.windowDurationMins) ? { windowDurationMins: row.windowDurationMins } : {}),
81
+ ...(typeof row.resetsAt === "number" && Number.isFinite(row.resetsAt) ? { resetsAt: row.resetsAt } : {}) };
82
+ };
83
+ const reached = raw.rateLimitReachedType;
84
+ const known = ["usageLimitExceeded", "rate_limit_reached", "workspace_owner_credits_depleted", "workspace_member_credits_depleted", "workspace_owner_usage_limit_reached", "workspace_member_usage_limit_reached"];
85
+ return { primary: window(raw.primary), secondary: window(raw.secondary),
86
+ ...(reached ? { rateLimitReachedType: typeof reached === "string" && known.includes(reached) ? reached : "usageLimitExceeded" } : {}) };
87
+ }
88
+
89
+ /** Closed native failure metadata. No vendor message, account data or credit information leaves the decoder. */
90
+ export interface NativeReviewerQuota {
91
+ id: "5h" | "week";
92
+ used: 1;
93
+ windowMins: number;
94
+ source: "Claude reviewer quota" | "Codex reviewer quota" | "Kimi reviewer quota";
95
+ resetsAt?: number;
96
+ }
97
+ function nativeQuotaObject(value: unknown): Record<string, unknown> {
98
+ if (!value || typeof value !== "object" || Array.isArray(value) || types.isProxy(value)
99
+ || ![Object.prototype, null].includes(Object.getPrototypeOf(value)) || Object.getOwnPropertySymbols(value).length) return {};
100
+ const fields = Object.getOwnPropertyDescriptors(value);
101
+ if (Object.values(fields).some(field => !Object.hasOwn(field, "value") || !field.enumerable)) return {};
102
+ return Object.fromEntries(Object.entries(fields).map(([key, field]) => [key, field.value]));
103
+ }
104
+ /** Revalidate even a backend's typed result before a host callback receives it. */
105
+ export function nativeReviewerQuota(value: unknown): NativeReviewerQuota | undefined {
106
+ const row = nativeQuotaObject(value);
107
+ if (row.used !== 1 || row.id !== "5h" && row.id !== "week" || !["Claude reviewer quota", "Codex reviewer quota", "Kimi reviewer quota"].includes(row.source as string)) return;
108
+ const expected = row.id === "week" ? 10_080 : 300;
109
+ if (row.windowMins !== expected) return;
110
+ const resetsAt = typeof row.resetsAt === "number" && Number.isSafeInteger(row.resetsAt) && row.resetsAt > 0 && Number.isFinite(new Date(row.resetsAt).getTime()) ? row.resetsAt : undefined;
111
+ return { id: row.id, used: 1, windowMins: expected, source: row.source as NativeReviewerQuota["source"], ...(resetsAt === undefined ? {} : { resetsAt }) };
112
+ }
113
+ /** Claude Agent SDK native rate_limit_event uses camelCase inside rate_limit_info, not the SDK's snake_case projection. */
114
+ export function claudeReviewerQuota(value: unknown): NativeReviewerQuota | undefined {
115
+ const row = nativeQuotaObject(value), base = { id: "5h" as const, used: 1 as const, windowMins: 300, source: "Claude reviewer quota" as const };
116
+ if (row.type === "assistant" && row.error === "rate_limit") return base;
117
+ if (row.type !== "rate_limit_event") return;
118
+ const info = nativeQuotaObject(row.rate_limit_info);
119
+ if (info.status !== "rejected") return;
120
+ const kind = info.rateLimitType;
121
+ const known = kind === "five_hour" || kind === "seven_day" || kind === "seven_day_opus" || kind === "seven_day_sonnet";
122
+ const id = kind === "five_hour" ? "5h" as const : "week" as const;
123
+ const resetsAt = known ? epochMillis(info.resetsAt) : undefined;
124
+ return known ? { ...base, id, windowMins: id === "week" ? 10_080 : 300, ...(resetsAt === undefined ? {} : { resetsAt }) } : base;
125
+ }
126
+ /** Codex 0.166.0 exec ThreadErrorEvent is message-only. Never read assistant/item/tool prose or app-server-shaped invented fields. */
127
+ export const CODEX_EXEC_QUOTA_PREFIX = "You’ve hit your usage limit.";
128
+ const CODEX_EXEC_QUOTA_MESSAGES = [
129
+ "Your workspace is out of credits. Add credits to continue.",
130
+ "Your workspace is out of credits. Ask your workspace owner to refill in order to continue.",
131
+ "You hit your spend cap set in your workspace. Increase your spend cap to continue.",
132
+ "You hit your spend cap set by the owner of your workspace. Ask an owner to increase your spend cap to continue.",
133
+ ];
134
+ export function codexReviewerQuota(value: unknown): NativeReviewerQuota | undefined {
135
+ const row = nativeQuotaObject(value);
136
+ const message = row.type === "error" ? row.message : row.type === "turn.failed" ? nativeQuotaObject(row.error).message : undefined;
137
+ if (typeof message !== "string" || !(message.startsWith(CODEX_EXEC_QUOTA_PREFIX) || message.startsWith("You’ve hit your usage limit for ") || CODEX_EXEC_QUOTA_MESSAGES.includes(message))) return;
138
+ return { id: "5h", used: 1, windowMins: 300, source: "Codex reviewer quota" };
139
+ }
140
+
141
+ /**
142
+ * ponytail: only the owned nonzero-exit stderr line observed on Kimi 2.2.0 is classified (2026-10-19 receipt).
143
+ * 2.5.2 remains unverified for this diagnostic. Replace with a version-pinned typed native frame when one exists.
144
+ */
145
+ export function kimiReviewerQuotaOnExit(value: { exitCode: number | null; stderr: { status: "complete"; text: string } | { status: "unknown" } }): NativeReviewerQuota | undefined {
146
+ if (typeof value.exitCode !== "number" || value.exitCode === 0 || value.stderr.status !== "complete" || !value.stderr.text.endsWith("\n")) return;
147
+ const hit = value.stderr.text.split(/\r?\n/).some(line => line.startsWith("error: failed to run prompt: provider.") && line.includes("usage limit"));
148
+ if (!hit) return;
149
+ // The receipt supplied no exact reset. Its displayed weekly wording supplies no guessed timestamp.
150
+ return { id: "5h", used: 1, windowMins: 300, source: "Kimi reviewer quota" };
151
+ }
@@ -48,6 +48,7 @@ export const CLAUDE_RECOVERY_SESSION: SessionPolicy = {
48
48
  personFresh: true, missingEvidence: "transcript",
49
49
  };
50
50
  export const PI_RECOVERY_SESSION: SessionPolicy = {
51
+ restoreVersionGate: "pi",
51
52
  resumeArgv: binding => ["pi", "--mode", "tui", ...(binding.backend ? ["--backend", binding.backend] : []), ...(binding.model ? ["--model", binding.model] : []),
52
53
  ...(binding.sessionFile ? ["--session-file", binding.sessionFile] : ["--session-id", binding.sessionId])],
53
54
  personFresh: false,
@@ -75,11 +76,13 @@ export const KIMI_RECOVERY_SESSION: SessionPolicy = {
75
76
  };
76
77
  export const LOCAL_RECOVERY_SESSION: SessionPolicy = { restoreArgs: startupArgs };
77
78
  export const JCODE_RECOVERY_SESSION: SessionPolicy = {
79
+ restoreVersionGate: "jcode",
78
80
  legacyTargetSupport: { file: "src/hub/peer-catalog.ts", exportName: "OPTIONAL_PEERS", refusal: "target does not support Jcode; end it and make a new plan, or choose a supporting target; runtimes unchanged" },
79
81
  recoveryRefusal: (_peer, phase = "plan") => phase === "restore" ? undefined : "jcode: source-pinned native load cannot prove conversation identity; end the peer and make a new recovery plan before effects",
80
82
  restoreArgs: peer => ({ ...startupArgs(peer), ...(peer.sessionId ? { "session-id": peer.sessionId } : {}), ...(peer.args?.providerProfile ? { "provider-profile": peer.args.providerProfile } : {}) }),
81
83
  };
82
84
  export const QWEN_RECOVERY_SESSION: SessionPolicy = {
85
+ restoreVersionGate: "qwen",
83
86
  legacyTargetSupport: { file: "src/hub/peer-catalog.ts", exportName: "OPTIONAL_PEERS", refusal: "target does not support Qwen; end Qwen and make a new plan, or choose a supporting target; runtimes unchanged" },
84
87
  restoreArgs: peer => ({ ...startupArgs(peer), ...(peer.sessionId ? { "session-id": peer.sessionId } : {}) }),
85
88
  // #286 Part 3: the Qwen TUI belongs to the person's terminal. It is never restored as a headless worker; `ahub qwen --mode tui` resumes it (qwen -r <session>) from its saved offset.
@@ -13,7 +13,7 @@ import { createQwenDual } from "./native-factories.ts";
13
13
  export const QWEN_DEFINITION: AdapterDefinition = {
14
14
  api: 1,
15
15
  kind: "qwen",
16
- projection: { roleRank: 5, helpRank: 5, plannerEligible: true },
16
+ projection: { roleRank: 5, helpRank: 5, plannerEligible: true, conductorEligible: false, reviewerEligible: true },
17
17
  displayName: "Qwen Code",
18
18
  family: "qwen",
19
19
  transport: "acp",
@@ -74,7 +74,7 @@ export const QWEN_DEFINITION: AdapterDefinition = {
74
74
  settle: { signal: "message-stop" },
75
75
  budget: { account: "qwen" },
76
76
  capabilities: { watch: true },
77
- cli: { command: "qwen", entry: { lifecycleAdmission: true, execute: runQwenEntry }, preview: previewQwen, usage: [["ahub qwen [--mode headless|tui] [--model <alias>] [--session-id <id>] [--print-command]", `start optional Qwen Code ACP (${describe("qwen")}; roster.qwen, default off); --mode tui runs Qwen's own TUI in this terminal, driven through its dual-output files (${describe("qwen-dual")}); a hub deny ends the turn without an answer and a stalled turn is stopped with Esc in the Qwen terminal`]], launchConfigKeys: ["qwen_cmd"], startWords: () => ["qwen"] },
77
+ cli: { command: "qwen", entry: { lifecycleAdmission: true, execute: runQwenEntry }, preview: previewQwen, usage: [["ahub qwen [--mode headless|tui] [--model <alias>] [--session-id <id>] [--print-command]", `start optional Qwen Code ACP (${describe("qwen")}; roster.qwen, default off); --mode tui runs Qwen's own TUI in this terminal, driven through its dual-output files (${describe("qwen-dual")}); a hub deny ends the turn without an answer and a stalled turn is stopped with Esc in the Qwen terminal`, "start optional Qwen Code, headless or in its TUI"]], launchConfigKeys: ["qwen_cmd"], startWords: () => ["qwen"] },
78
78
  display: QWEN_DISPLAY,
79
79
  hooks: { recallPlatform: "qwen" },
80
80
  };
@@ -5,6 +5,9 @@ import { homedir, tmpdir } from "node:os";
5
5
  import { basename, join, resolve } from "node:path";
6
6
  import { stopOwnedProcess, trackGroup } from "../hub/child-process.ts";
7
7
  import { realPath } from "../hub/project.ts";
8
+ import { kimiReviewerQuotaOnExit } from "./definitions/native-quota.ts";
9
+ import { ownedKimiSession, type KimiWireRow } from "./kimi-wire-usage.ts";
10
+ import { KimiUsage } from "../hub/kimi-usage.ts";
8
11
  import type { ReviewerBackend, ReviewerLaunch, ReviewerPrepareContext } from "./reviewer-print.ts";
9
12
  import { assertCleanCwdAncestors, checkKimiReviewPolicy, kimiReviewFingerprint as hash, projectKimiReviewPolicyBinding, readKimiReviewFile as read } from "./kimi-review-policy.ts";
10
13
  import { startKimiReviewPolicyWatch, type KimiReviewPolicyFactory } from "./kimi-review-policy-worker.ts";
@@ -86,6 +89,19 @@ export async function stopKimiReview(child: ChildProcess, locks: readonly string
86
89
  await stopOwnedProcess(child, { group: true });
87
90
  }
88
91
 
92
+ /** Usage only: the error diagnostic exception never reads wire or log error content. */
93
+ export function readKimiReviewerUsage(home: string, startedAt: number): readonly KimiWireRow[] | undefined {
94
+ const session = ownedKimiSession(home);
95
+ if (!session) return;
96
+ const rows: KimiWireRow[] = []; let now = startedAt;
97
+ const usage = new KimiUsage({ home, now: () => now, ceiling: () => 0, session: () => session,
98
+ record: (_peer, row) => { rows.push(row); }, report: () => {}, forget: () => {}, notice: () => {} });
99
+ try {
100
+ usage.turnStarted("owned-review"); now = Date.now(); usage.collect("owned-review", false, true);
101
+ return usage.complete("owned-review") && rows.length ? rows : undefined;
102
+ } finally { usage.stop(); }
103
+ }
104
+
89
105
  export async function prepareKimiReviewer(context: ReviewerPrepareContext, policyFactory: KimiReviewPolicyFactory = startKimiReviewPolicyWatch): Promise<ReviewerLaunch | { unavailable: string }> {
90
106
  let own: string | undefined;
91
107
  try {
@@ -131,6 +147,12 @@ export async function prepareKimiReviewer(context: ReviewerPrepareContext, polic
131
147
  };
132
148
  return { command, args: ["-p", "Review the supplied task facts and record the evidence-based verdict with hub_review.", "--output-format", "stream-json", "--agent-file", agentFile, "--skills-dir", skills],
133
149
  cwd, env, envMode: "replace", cleanup, watchCurrent: true,
150
+ readUsage: (startedAt, receive) => {
151
+ const rows = readKimiReviewerUsage(tool, startedAt);
152
+ if (!rows) return false;
153
+ for (const row of rows) receive({ input_tokens: row.inputOther, output_tokens: row.output, cache_creation_input_tokens: row.inputCacheCreation, cache_read_input_tokens: row.inputCacheRead }, { id: row.id, at: row.at, ...(row.model ? { model: row.model } : {}) });
154
+ return true;
155
+ },
134
156
  stop: child => stopKimiReview(child, [join(sources[1]!, "kimi-code.lock"), join(sources[1]!, `${selected.lock}.lock`)]),
135
157
  current: () => !cleaned && !context.signal.aborted && checkKimiReviewPolicy(binding),
136
158
  startPolicyWatch: () => {
@@ -161,4 +183,5 @@ export async function prepareKimiReviewer(context: ReviewerPrepareContext, polic
161
183
 
162
184
  export const kimiReviewerBackend: ReviewerBackend = {
163
185
  id: "kimi", taskMcp: true, nativePolicy: true, prepare: context => prepareKimiReviewer(context),
186
+ failureOnExit: kimiReviewerQuotaOnExit,
164
187
  };
@@ -1,4 +1,4 @@
1
- import { closeSync, fstatSync, lstatSync, openSync, readSync as fsReadSync, readdirSync, statSync } from "node:fs";
1
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync as fsReadSync, readdirSync, statSync } from "node:fs";
2
2
  import { createHash } from "node:crypto";
3
3
  import { join, sep } from "node:path";
4
4
  import { realPath } from "../hub/project.ts";
@@ -85,6 +85,43 @@ class Unknown extends Error { constructor(readonly reason: KimiWireReason) { sup
85
85
  const count = (value: unknown): number | undefined => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
86
86
  const inside = (root: string, path: string): boolean => path.startsWith(root + sep);
87
87
 
88
+ type IndexRead = (fd: number, buffer: Buffer, offset: number, length: number, position: number) => number;
89
+ function readIndex(home: string, read: IndexRead = fsReadSync, owned = false): string {
90
+ let fd: number;
91
+ try { fd = openSync(join(home, "session_index.jsonl"), owned ? constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK : "r"); } catch { throw new Unknown("no-index"); }
92
+ try {
93
+ const stat = fstatSync(fd);
94
+ if (!stat.isFile() || stat.size > INDEX_CAP) throw new Unknown("io-error");
95
+ const buffer = Buffer.allocUnsafe(stat.size); let got = 0;
96
+ while (got < stat.size) { const n = read(fd, buffer, got, stat.size - got, got); if (n <= 0) break; got += n; }
97
+ if (owned && (got !== stat.size || fstatSync(fd).size !== stat.size)) throw new Unknown("partial-line");
98
+ return buffer.toString("utf8", 0, got);
99
+ } catch (error) { throw error instanceof Unknown ? error : new Unknown("io-error"); }
100
+ finally { closeSync(fd); }
101
+ }
102
+
103
+ /** The fresh owned reviewer profile may contain exactly one native session. This is not a hub observer UUID. */
104
+ export function ownedKimiSession(home: string): string | undefined {
105
+ try {
106
+ const root = realPath(home), sessions = realPath(join(home, "sessions"));
107
+ if (!inside(root, sessions)) return;
108
+ const text = readIndex(home, fsReadSync, true);
109
+ if (!text.endsWith("\n")) return;
110
+ const entries = new Map<string, string>();
111
+ for (const line of text.split("\n")) {
112
+ if (!line.trim()) continue;
113
+ if (Buffer.byteLength(line) > LINE_CAP) return;
114
+ const row = JSON.parse(line) as { sessionId?: unknown; sessionDir?: unknown };
115
+ if (typeof row.sessionId !== "string" || !SESSION_ID.test(row.sessionId) || typeof row.sessionDir !== "string") return;
116
+ const directory = realPath(row.sessionDir);
117
+ if (!inside(sessions, directory) || entries.has(row.sessionId) && entries.get(row.sessionId) !== directory) return;
118
+ entries.set(row.sessionId, directory);
119
+ if (entries.size > 1) return;
120
+ }
121
+ return entries.size === 1 ? [...entries.keys()][0] : undefined;
122
+ } catch { return; }
123
+ }
124
+
88
125
  export class KimiWireReader {
89
126
  private readonly home: string;
90
127
  private readonly sessionId: string;
@@ -178,21 +215,7 @@ export class KimiWireReader {
178
215
 
179
216
  /** The index, opened once and sized from that descriptor, so a link swapped in between a check and the read cannot lift the bound. */
180
217
  private index(): string {
181
- let fd: number;
182
- try { fd = openSync(join(this.home, "session_index.jsonl"), "r"); } catch { throw new Unknown("no-index"); }
183
- try {
184
- const stat = fstatSync(fd);
185
- if (!stat.isFile() || stat.size > INDEX_CAP) throw new Unknown("io-error");
186
- const buffer = Buffer.allocUnsafe(stat.size);
187
- let got = 0;
188
- while (got < stat.size) {
189
- const n = this.readBytes(fd, buffer, got, stat.size - got, got);
190
- if (n <= 0) break;
191
- got += n;
192
- }
193
- return buffer.toString("utf8", 0, got);
194
- } catch (error) { throw error instanceof Unknown ? error : new Unknown("io-error"); }
195
- finally { closeSync(fd); }
218
+ return readIndex(this.home, (fd, buffer, offset, length, position) => this.readBytes(fd, buffer, offset, length, position));
196
219
  }
197
220
 
198
221
  /** `agents/<name>/wire.jsonl` of every agent that has one: the main agent and its sub-agents. */