@staix/agent-hub 0.50.0 → 0.52.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 (350) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +1 -1
  3. package/docs/adding-an-ai-tool.md +26 -4
  4. package/docs/agent-notes/README.md +1 -0
  5. package/docs/agent-notes/adapters.md +4 -3
  6. package/docs/agent-notes/budget.md +8 -2
  7. package/docs/agent-notes/daemon.md +13 -8
  8. package/docs/agent-notes/local-worker.md +3 -3
  9. package/docs/agent-notes/security-review.md +6 -5
  10. package/docs/agent-notes/tasks.md +10 -3
  11. package/docs/agent-notes/tests.md +4 -3
  12. package/docs/cooperbench.md +1 -1
  13. package/docs/design/adapters.md +21 -0
  14. package/docs/design/cli-output-inventory.md +165 -150
  15. package/docs/design/cli-output.md +4 -3
  16. package/docs/design/guidance-probes.md +1 -0
  17. package/docs/design/roadmap.md +3 -1
  18. package/docs/design/task-board.md +35 -0
  19. package/docs/dogfood.md +21 -3
  20. package/docs/events.md +4 -2
  21. package/docs/memory.md +5 -3
  22. package/docs/operations.md +259 -19
  23. package/docs/quickstart.md +29 -2
  24. package/docs/roadmap.json +20 -20
  25. package/docs/roadmap.md +2 -2
  26. package/docs/roles.md +1 -1
  27. package/docs/sdlc.md +29 -5
  28. package/docs/security.md +11 -5
  29. package/docs/specs/2026-09-19-agent-hub-design.md +44 -0
  30. package/docs/specs/2026-09-19-multi-project-design.md +4 -0
  31. package/docs/specs/2026-09-20-upgrade-recovery-design.md +17 -0
  32. package/docs/specs/mcp-endpoint.md +63 -0
  33. package/docs/verification/2026-11-29-agy-1.5.20.md +33 -0
  34. package/docs/verification/2026-11-29-claude-profile-hook.md +12 -0
  35. package/docs/verification/2026-11-29-idle-daemon-footprint.md +75 -0
  36. package/docs/verification/2026-11-29-kimi-281-reviewer-compat.md +38 -0
  37. package/docs/verification/2026-11-29-kimi-tui-281.md +12 -0
  38. package/docs/verification/2026-11-30-0.51.0.md +91 -0
  39. package/docs/verification/2026-11-30-account-switch-1806.md +445 -0
  40. package/docs/verification/2026-11-30-capability-listing-shape-1808.md +45 -0
  41. package/docs/verification/2026-11-30-upgrade-keep-1807.md +174 -0
  42. package/docs/verification/2026-12-01-1811-confirmation-receipt.md +19 -0
  43. package/docs/verification/2026-12-01-1811-orca-agent-list.md +20 -0
  44. package/docs/verification/2026-12-01-1811-orca-pane-key.md +21 -0
  45. package/docs/verification/2026-12-02-1819-claude-process-after-renewal.md +54 -0
  46. package/docs/verification/2026-12-02-agy-1.5.21.md +74 -0
  47. package/docs/verification/2026-12-02-claude-implementer-2.1.334.md +44 -0
  48. package/docs/verification/2026-12-02-cli-import-graph.md +33 -0
  49. package/docs/verification/2026-12-03-0.52.0.md +150 -0
  50. package/docs/verification/2026-12-03-codex-0173-reviewer-isolation.md +53 -0
  51. package/docs/verification/2026-12-03-codex-0173-reviewer-tool-call.md +34 -0
  52. package/docs/verification/2026-12-03-jcode-1.3.0.md +25 -0
  53. package/docs/verification/agy/README.md +17 -0
  54. package/docs/verification/agy/cli-surface.ts +68 -0
  55. package/docs/verification/agy/interactive-bridge.ts +92 -0
  56. package/docs/verification/agy/interactive-session.ts +131 -0
  57. package/docs/verification/agy/launcher-nonce.ts +215 -0
  58. package/docs/verification/agy/native-hooks.ts +210 -0
  59. package/docs/verification/agy/originals/agent-hub-681/cli-surface.ts +87 -0
  60. package/docs/verification/agy/originals/agent-hub-681/native-hooks-adapted.ts +91 -0
  61. package/docs/verification/agy/originals/agent-hub-681/tui-actual.ts +200 -0
  62. package/docs/verification/agy/originals/agent-hub-684/probe.ts +107 -0
  63. package/docs/verification/agy/originals.json +25 -0
  64. package/docs/verification/agy/permission-new-functions.ts +128 -0
  65. package/docs/verification/agy/run-probe.py +108 -0
  66. package/docs/verification/agy/runtime.ts +171 -0
  67. package/docs/verification/agy/tmux-helper-control.ts +6 -0
  68. package/docs/verification/agy/tmux-session.ts +235 -0
  69. package/docs/verified.json +87 -42
  70. package/package.json +3 -3
  71. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  72. package/plugins/agent-hub/compat.json +157 -0
  73. package/plugins/agent-hub/kimi-hook.js +1416 -24985
  74. package/plugins/agent-hub/server.js +17415 -32755
  75. package/scripts/check-docs.mjs +1 -1
  76. package/src/adapters/acp.ts +13 -13
  77. package/src/adapters/agy/definition.ts +9 -26
  78. package/src/adapters/agy/entry.ts +2 -0
  79. package/src/adapters/channel-peer.ts +3 -1
  80. package/src/adapters/claude-channel-evidence.ts +7 -3
  81. package/src/adapters/claude-channel.ts +38 -257
  82. package/src/adapters/claude-implementer.ts +3 -1
  83. package/src/adapters/codex-appserver.ts +77 -15
  84. package/src/adapters/compat.ts +78 -14
  85. package/src/adapters/configured-acp.ts +23 -163
  86. package/src/adapters/configured-adapter-policy.ts +160 -0
  87. package/src/adapters/configured-pull-entry.ts +53 -0
  88. package/src/adapters/configured-pull.ts +38 -0
  89. package/src/adapters/conformance/fakes/app-server.ts +9 -2
  90. package/src/adapters/declaration-catalog.ts +25 -0
  91. package/src/adapters/declaration-data.ts +342 -0
  92. package/src/adapters/declaration-resolution.ts +53 -0
  93. package/src/adapters/definitions/builtin-metadata.ts +62 -84
  94. package/src/adapters/definitions/jcode-launch.ts +13 -0
  95. package/src/adapters/definitions/native-adapter-policy.ts +390 -0
  96. package/src/adapters/definitions/native-cli-claude-launch.ts +6 -3
  97. package/src/adapters/definitions/native-cli-codex-launch.ts +2 -1
  98. package/src/adapters/definitions/native-cli-entry-claude.ts +17 -2
  99. package/src/adapters/definitions/native-cli-entry-codex.ts +2 -0
  100. package/src/adapters/definitions/native-cli-entry-jcode.ts +6 -2
  101. package/src/adapters/definitions/native-cli-entry-kimi.ts +2 -0
  102. package/src/adapters/definitions/native-cli-entry-pi.ts +2 -0
  103. package/src/adapters/definitions/native-cli-entry-qwen.ts +2 -0
  104. package/src/adapters/definitions/native-cli-entry-types.ts +12 -3
  105. package/src/adapters/definitions/native-cli-jcode-home-init.ts +1 -1
  106. package/src/adapters/definitions/native-cli-launch-common.ts +2 -2
  107. package/src/adapters/definitions/native-cli-preview-common.ts +1 -1
  108. package/src/adapters/definitions/native-cli-retained.ts +1 -1
  109. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  110. package/src/adapters/definitions/native-configuration.ts +18 -0
  111. package/src/adapters/definitions/native-help.ts +24 -0
  112. package/src/adapters/definitions/native-launch-declarations.ts +34 -0
  113. package/src/adapters/definitions/native-launch-policy.ts +4 -0
  114. package/src/adapters/definitions/native-launch-settings.ts +72 -0
  115. package/src/adapters/definitions/native-light-cli.ts +18 -0
  116. package/src/adapters/definitions/native-light-preview.ts +10 -0
  117. package/src/adapters/definitions/native-wrapper-launch.ts +10 -0
  118. package/src/adapters/definitions/qwen.ts +6 -29
  119. package/src/adapters/definitions/reviewer-variants.ts +7 -8
  120. package/src/adapters/external-declarations.ts +31 -0
  121. package/src/adapters/external-modules.ts +4 -29
  122. package/src/adapters/jcode.ts +19 -12
  123. package/src/adapters/native-capabilities.ts +18 -8
  124. package/src/adapters/native-facts-hooks.ts +12 -0
  125. package/src/adapters/native-proof-ports.ts +1 -1
  126. package/src/adapters/presets.ts +136 -0
  127. package/src/adapters/qwen-dual.ts +2 -2
  128. package/src/adapters/registry-types.ts +3 -0
  129. package/src/adapters/registry.ts +20 -81
  130. package/src/adapters/reviewer-print.ts +26 -9
  131. package/src/adapters/role-eligibility.ts +2 -1
  132. package/src/cli/accounts-import.ts +72 -0
  133. package/src/cli/agents-latest-table.ts +88 -0
  134. package/src/cli/agents-latest.ts +22 -0
  135. package/src/cli/agents-output.ts +10 -0
  136. package/src/cli/agents-presets.ts +100 -0
  137. package/src/cli/agents.ts +1 -1
  138. package/src/cli/attention.ts +3 -2
  139. package/src/cli/autonomy-homes.ts +7 -2
  140. package/src/cli/autonomy-offline.ts +1 -1
  141. package/src/cli/bench.ts +1 -1
  142. package/src/cli/budget-renew-guidance.ts +129 -0
  143. package/src/cli/claude-homes.ts +9 -5
  144. package/src/cli/claude-profile-hook.ts +31 -11
  145. package/src/cli/command-context.ts +3 -0
  146. package/src/cli/command-table.ts +123 -0
  147. package/src/cli/commands/accounts.ts +8 -0
  148. package/src/cli/commands/agents.ts +18 -0
  149. package/src/cli/commands/answer.ts +28 -0
  150. package/src/cli/commands/ask.ts +17 -0
  151. package/src/cli/commands/autonomy.ts +83 -0
  152. package/src/cli/commands/backlog.ts +46 -0
  153. package/src/cli/commands/bench.ts +60 -0
  154. package/src/cli/commands/board.ts +48 -0
  155. package/src/cli/commands/broker.ts +9 -0
  156. package/src/cli/commands/budget.ts +96 -0
  157. package/src/cli/commands/capabilities.ts +12 -0
  158. package/src/cli/commands/check-path.ts +55 -0
  159. package/src/cli/commands/completion.ts +8 -0
  160. package/src/cli/commands/console.ts +12 -0
  161. package/src/cli/commands/daemon.ts +8 -0
  162. package/src/cli/commands/deliverables.ts +25 -0
  163. package/src/cli/commands/doctor.ts +249 -0
  164. package/src/cli/commands/down.ts +3 -0
  165. package/src/cli/commands/export.ts +15 -0
  166. package/src/cli/commands/facts.ts +15 -0
  167. package/src/cli/commands/goal.ts +22 -0
  168. package/src/cli/commands/guidance.ts +102 -0
  169. package/src/cli/commands/help.ts +17 -0
  170. package/src/cli/commands/host.ts +45 -0
  171. package/src/cli/commands/init.ts +121 -0
  172. package/src/cli/commands/instructed.ts +19 -0
  173. package/src/cli/commands/instruction-hook.ts +15 -0
  174. package/src/cli/commands/intake.ts +24 -0
  175. package/src/cli/commands/kill.ts +15 -0
  176. package/src/cli/commands/learn.ts +23 -0
  177. package/src/cli/commands/lineage.ts +30 -0
  178. package/src/cli/commands/logs.ts +21 -0
  179. package/src/cli/commands/manager.ts +15 -0
  180. package/src/cli/commands/memory.ts +21 -0
  181. package/src/cli/commands/model.ts +25 -0
  182. package/src/cli/commands/models.ts +40 -0
  183. package/src/cli/commands/native.ts +39 -0
  184. package/src/cli/commands/pause.ts +5 -0
  185. package/src/cli/commands/peer.ts +32 -0
  186. package/src/cli/commands/permission.ts +26 -0
  187. package/src/cli/commands/permit.ts +12 -0
  188. package/src/cli/commands/pet.ts +24 -0
  189. package/src/cli/commands/projects.ts +49 -0
  190. package/src/cli/commands/queue.ts +70 -0
  191. package/src/cli/commands/recovery-run.ts +13 -0
  192. package/src/cli/commands/recovery.ts +130 -0
  193. package/src/cli/commands/release.ts +23 -0
  194. package/src/cli/commands/releases.ts +91 -0
  195. package/src/cli/commands/remember.ts +6 -0
  196. package/src/cli/commands/report.ts +27 -0
  197. package/src/cli/commands/research.ts +53 -0
  198. package/src/cli/commands/reset.ts +89 -0
  199. package/src/cli/commands/restart.ts +5 -0
  200. package/src/cli/commands/results.ts +31 -0
  201. package/src/cli/commands/resume.ts +5 -0
  202. package/src/cli/commands/review.ts +24 -0
  203. package/src/cli/commands/roadmap.ts +21 -0
  204. package/src/cli/commands/role.ts +34 -0
  205. package/src/cli/commands/roles.ts +30 -0
  206. package/src/cli/commands/room.ts +14 -0
  207. package/src/cli/commands/roster.ts +48 -0
  208. package/src/cli/commands/route.ts +9 -0
  209. package/src/cli/commands/say.ts +21 -0
  210. package/src/cli/commands/schedule.ts +17 -0
  211. package/src/cli/commands/sdlc.ts +321 -0
  212. package/src/cli/commands/settings.ts +148 -0
  213. package/src/cli/commands/setup.ts +89 -0
  214. package/src/cli/commands/shared-refusals.ts +25 -0
  215. package/src/cli/commands/smoke.ts +44 -0
  216. package/src/cli/commands/source.ts +64 -0
  217. package/src/cli/commands/specs.ts +13 -0
  218. package/src/cli/commands/status.ts +28 -0
  219. package/src/cli/commands/stop.ts +17 -0
  220. package/src/cli/commands/structure.ts +60 -0
  221. package/src/cli/commands/study.ts +39 -0
  222. package/src/cli/commands/tail.ts +19 -0
  223. package/src/cli/commands/task.ts +114 -0
  224. package/src/cli/commands/title.ts +17 -0
  225. package/src/cli/commands/turns.ts +10 -0
  226. package/src/cli/commands/ui.ts +47 -0
  227. package/src/cli/commands/undo.ts +77 -0
  228. package/src/cli/commands/up.ts +39 -0
  229. package/src/cli/commands/upgrade.ts +5 -0
  230. package/src/cli/commands/usage.ts +33 -0
  231. package/src/cli/commands/version.ts +5 -0
  232. package/src/cli/commands/watch.ts +30 -0
  233. package/src/cli/commands/worktrees.ts +31 -0
  234. package/src/cli/conductor-recovery.ts +1 -1
  235. package/src/cli/console-state.ts +5 -138
  236. package/src/cli/console-versions.ts +1 -1
  237. package/src/cli/facts-hook.ts +11 -4
  238. package/src/cli/help.ts +44 -20
  239. package/src/cli/identity.ts +27 -4
  240. package/src/cli/init-prompt.ts +1 -1
  241. package/src/cli/init-settings.ts +4 -35
  242. package/src/cli/init.ts +1 -1
  243. package/src/cli/json-text-spans.ts +57 -0
  244. package/src/cli/launch-check.ts +156 -0
  245. package/src/cli/launch.ts +19 -70
  246. package/src/cli/light-dispatch.ts +29 -0
  247. package/src/cli/main.js +8 -1
  248. package/src/cli/main.ts +257 -2799
  249. package/src/cli/memory.ts +1 -1
  250. package/src/cli/orca-probe.ts +119 -0
  251. package/src/cli/output.ts +45 -3
  252. package/src/cli/preview.ts +11 -6
  253. package/src/cli/recovery-launch.ts +1 -1
  254. package/src/cli/recovery-version-preflight.ts +28 -9
  255. package/src/cli/replace-process.ts +22 -0
  256. package/src/cli/report-layout.ts +142 -0
  257. package/src/cli/roadmap-usage.ts +16 -0
  258. package/src/cli/roadmap.ts +3 -16
  259. package/src/cli/sdlc-doctor.ts +27 -0
  260. package/src/cli/sdlc-output.ts +55 -1
  261. package/src/cli/setup-homes.ts +2 -2
  262. package/src/cli/start-agents-run.ts +85 -7
  263. package/src/cli/start-check.ts +28 -0
  264. package/src/cli/statusline-tee.ts +25 -4
  265. package/src/cli/terminal-recovery.ts +53 -10
  266. package/src/cli/upgrade-interactive.ts +1 -0
  267. package/src/cli/upgrade-runtime.ts +12 -1
  268. package/src/cli/upgrade.ts +4 -15
  269. package/src/cli/warn-line.ts +1 -1
  270. package/src/hub/accounts.ts +148 -0
  271. package/src/hub/addons.ts +20 -0
  272. package/src/hub/agent-drift.ts +2 -1
  273. package/src/hub/budget-projection.ts +39 -7
  274. package/src/hub/budget.ts +231 -16
  275. package/src/hub/channel-project.ts +3 -3
  276. package/src/hub/ci-watch.ts +311 -79
  277. package/src/hub/conductor-peer.ts +24 -0
  278. package/src/hub/conductor.ts +2 -21
  279. package/src/hub/config-apply.ts +25 -14
  280. package/src/hub/config-edit.ts +1 -1
  281. package/src/hub/config-tier.ts +2 -0
  282. package/src/hub/config.ts +535 -0
  283. package/src/hub/control-client.ts +49 -1
  284. package/src/hub/daemon.ts +492 -569
  285. package/src/hub/delivery-public.ts +11 -0
  286. package/src/hub/events.ts +3 -0
  287. package/src/hub/home-tag.ts +12 -0
  288. package/src/hub/host.ts +217 -0
  289. package/src/hub/hub-check.ts +125 -0
  290. package/src/hub/hub-tools.ts +2 -1
  291. package/src/hub/instance-budget.ts +2 -2
  292. package/src/hub/instance-config.ts +15 -126
  293. package/src/hub/instances.ts +22 -6
  294. package/src/hub/instruction-receipt.ts +2 -2
  295. package/src/hub/kimi-usage.ts +38 -11
  296. package/src/hub/lifecycle.ts +86 -4
  297. package/src/hub/mcp-bridge-core.ts +98 -0
  298. package/src/hub/mcp-channel-push.ts +20 -0
  299. package/src/hub/mcp-endpoint-serve.ts +178 -0
  300. package/src/hub/mcp-endpoint.ts +226 -0
  301. package/src/hub/mcp-tool-call.ts +181 -0
  302. package/src/hub/operational-settings.ts +2 -0
  303. package/src/hub/orca-env.ts +6 -0
  304. package/src/hub/orca-state.ts +84 -0
  305. package/src/hub/path-policy.ts +1 -1
  306. package/src/hub/peers.ts +5 -1
  307. package/src/hub/permission-mode.ts +5 -41
  308. package/src/hub/permission-paths.ts +41 -0
  309. package/src/hub/project.ts +20 -0
  310. package/src/hub/protocol-window.ts +58 -0
  311. package/src/hub/quota-origin.ts +20 -0
  312. package/src/hub/recovery-policy.ts +1 -1
  313. package/src/hub/registry.ts +36 -2
  314. package/src/hub/releases-inventory.ts +198 -0
  315. package/src/hub/report.ts +1 -1
  316. package/src/hub/research.ts +1 -1
  317. package/src/hub/review-brief.ts +47 -2
  318. package/src/hub/roster.ts +6 -3
  319. package/src/hub/routing.ts +9 -2
  320. package/src/hub/runtime-capture-prune.ts +25 -3
  321. package/src/hub/runtime-prune-health.ts +8 -1
  322. package/src/hub/sdlc-check.ts +205 -0
  323. package/src/hub/sdlc-release-authorization.ts +42 -21
  324. package/src/hub/sdlc-release-diagnostics.ts +5 -0
  325. package/src/hub/sdlc-release-policy.ts +21 -7
  326. package/src/hub/sdlc-release.ts +80 -20
  327. package/src/hub/sdlc-sync.ts +146 -0
  328. package/src/hub/sdlc.ts +38 -5
  329. package/src/hub/settings.ts +7 -4
  330. package/src/hub/start-agents.ts +1 -1
  331. package/src/hub/start-mode.ts +11 -4
  332. package/src/hub/structure-budget.ts +131 -0
  333. package/src/hub/structure-scan.ts +149 -0
  334. package/src/hub/tasks-experiment.ts +455 -0
  335. package/src/hub/tasks-guidance.ts +606 -0
  336. package/src/hub/tasks-roadmap-plan.ts +419 -0
  337. package/src/hub/tasks-roadmap.ts +491 -0
  338. package/src/hub/tasks-study.ts +661 -0
  339. package/src/hub/tasks-survey.ts +192 -0
  340. package/src/hub/tasks.ts +457 -2584
  341. package/src/hub/terminal-open.ts +5 -3
  342. package/src/hub/tooling.ts +3 -19
  343. package/src/hub/usage-rollup.ts +9 -3
  344. package/src/local/tools.ts +5 -0
  345. package/src/ui/index.html +1 -1
  346. package/src/ui/needs.ts +17 -5
  347. package/src/ui/peer-palette.ts +2 -4
  348. package/src/ui/plugin.ts +1 -1
  349. package/templates/presets/agents.json +60 -0
  350. package/templates/presets/confirmation-matrix.json +8 -8
@@ -0,0 +1,136 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { shellQuote } from "../cli/shell-quote.ts";
5
+ import presetsJson from "../../templates/presets/agents.json";
6
+
7
+ /** #1809 T1: a known agent CLI as data. A preset names no code; `ahub agents add` turns it into the same declaration a person could write by hand. */
8
+ export interface AgentPreset {
9
+ id: string;
10
+ displayName: string;
11
+ executable: string;
12
+ acp?: { args: string[]; identity: { name: string } };
13
+ versionArgs: string[];
14
+ mcp: { add: string[] | null; check: { file: string; key: string } };
15
+ recorded: string;
16
+ status: "verified" | "untested";
17
+ receipt: string | null;
18
+ }
19
+ interface PresetRow { id: string; displayName: string; executable: string; acp: boolean; status: "verified" | "untested"; receipt: string | null; recorded: string }
20
+
21
+ const REPOSITORY_ROOT = new URL("../../", import.meta.url);
22
+ const KIND = /^[a-z][a-z0-9-]{0,31}$/;
23
+
24
+ function text(value: unknown, at: string): string {
25
+ if (typeof value !== "string" || !value || value.length > 512) throw new Error(`presets: ${at} must be a short nonempty string`);
26
+ return value;
27
+ }
28
+ function words(value: unknown, at: string): string[] {
29
+ if (!Array.isArray(value) || value.length > 32) throw new Error(`presets: ${at} must be a short list`);
30
+ return value.map((item, index) => text(item, `${at}[${index}]`));
31
+ }
32
+
33
+ /** The presets file read strictly: an unknown field or a wrong type refuses the whole file, so a typo never becomes a launch line. */
34
+ export function loadPresets(raw: unknown = presetsJson): readonly AgentPreset[] {
35
+ const file = raw as { schemaVersion?: unknown; presets?: unknown };
36
+ if (file?.schemaVersion !== 1 || !Array.isArray(file.presets)) throw new Error("presets: unsupported file");
37
+ const seen = new Set<string>();
38
+ return Object.freeze(file.presets.map((entry: Record<string, unknown>, index): AgentPreset => {
39
+ const at = `presets[${index}]`;
40
+ const unknown = Object.keys(entry).filter(key => !["id", "displayName", "executable", "acp", "versionArgs", "mcp", "recorded", "status", "receipt"].includes(key));
41
+ if (unknown.length) throw new Error(`presets: ${at} has unknown field ${unknown[0]}`);
42
+ const id = text(entry.id, `${at}.id`);
43
+ if (!KIND.test(id) || seen.has(id)) throw new Error(`presets: ${at}.id is invalid or repeated`);
44
+ seen.add(id);
45
+ const acp = entry.acp as { args?: unknown; identity?: { name?: unknown } } | undefined;
46
+ const mcp = entry.mcp as { add?: unknown; check?: { file?: unknown; key?: unknown } };
47
+ if (entry.status !== "verified" && entry.status !== "untested") throw new Error(`presets: ${at}.status must be verified or untested`);
48
+ if (entry.receipt !== null && typeof entry.receipt !== "string") throw new Error(`presets: ${at}.receipt must be a path or null`);
49
+ return {
50
+ id, displayName: text(entry.displayName, `${at}.displayName`), executable: text(entry.executable, `${at}.executable`),
51
+ ...(acp ? { acp: { args: words(acp.args, `${at}.acp.args`), identity: { name: text(acp.identity?.name, `${at}.acp.identity.name`) } } } : {}),
52
+ versionArgs: words(entry.versionArgs, `${at}.versionArgs`),
53
+ mcp: { add: mcp?.add === null ? null : words(mcp?.add, `${at}.mcp.add`), check: { file: text(mcp?.check?.file, `${at}.mcp.check.file`), key: text(mcp?.check?.key, `${at}.mcp.check.key`) } },
54
+ recorded: text(entry.recorded, `${at}.recorded`), status: entry.status, receipt: entry.receipt as string | null,
55
+ };
56
+ }));
57
+ }
58
+
59
+ /** `verified` only when the row says so and its receipt file is there; every other preset is `untested`, whatever the row claims. */
60
+ function presetStatus(preset: AgentPreset, root: URL = REPOSITORY_ROOT): "verified" | "untested" {
61
+ return preset.status === "verified" && preset.receipt !== null && preset.receipt.startsWith("docs/verification/") && !preset.receipt.includes("..") && existsSync(new URL(preset.receipt, root)) ? "verified" : "untested";
62
+ }
63
+
64
+ /** The status word of a preset id; an id the presets file does not know is `untested`, never an error. */
65
+ export function presetStatusById(id: string, presets: readonly AgentPreset[] = loadPresets()): "verified" | "untested" {
66
+ const row = presets.find(preset => preset.id === id);
67
+ return row ? presetStatus(row) : "untested";
68
+ }
69
+
70
+ export function presetRows(presets: readonly AgentPreset[] = loadPresets(), root?: URL): PresetRow[] {
71
+ return presets.map(preset => ({ id: preset.id, displayName: preset.displayName, executable: preset.executable, acp: preset.acp !== undefined, status: presetStatus(preset, root), receipt: preset.receipt, recorded: preset.recorded }));
72
+ }
73
+
74
+ /** The first dotted-number token of a version probe's output, or undefined: the pin a start checks `initialize` against. */
75
+ export function parseProbeVersion(output: string): string | undefined {
76
+ return /\b\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?\b/.exec(output)?.[0];
77
+ }
78
+
79
+ /** The `adapters.<kind>` declaration for a preset: exactly the fields a hand-written ACP declaration has, so it passes the same validation. */
80
+ export function presetDeclaration(preset: AgentPreset, resolvedExecutable: string, version: string): Record<string, unknown> {
81
+ if (!preset.acp) throw new Error(`${preset.id} has no headless launch line`);
82
+ return {
83
+ transport: "acp", command: resolvedExecutable, args: [...preset.acp.args], displayName: preset.displayName,
84
+ roles: ["implementer", "verifier"], identity: { name: preset.acp.identity.name, version }, preset: preset.id,
85
+ };
86
+ }
87
+
88
+ /** The bridge bundle a pull CLI registers, in the installed package; `agents add --pull` and `ahub doctor` print the same path. */
89
+ export const BRIDGE_BUNDLE = fileURLToPath(new URL("../../plugins/agent-hub/server.js", import.meta.url));
90
+
91
+ /** The name the hub's bridge is registered under in a pull CLI's MCP settings. */
92
+ const BRIDGE_NAME = "agent-hub";
93
+
94
+ /** The `adapters.<kind>` declaration of a pull kind for a preset: the person's own TUI, `tasks: false`, the same fields a hand-written one has. */
95
+ export function presetPullDeclaration(preset: AgentPreset, resolvedExecutable: string): Record<string, unknown> {
96
+ return { transport: "pull", command: resolvedExecutable, args: [], displayName: preset.displayName, roles: ["implementer", "verifier"], versionArgs: [...preset.versionArgs], tasks: false, preset: preset.id };
97
+ }
98
+
99
+ /**
100
+ * What the person runs to register the hub's bridge in the CLI, printed and never run. `{name}`, `{command}` and `{args}` of the preset's template take
101
+ * the bridge name, the Bun that runs it and the bundle path; a preset with no scripted form (`add: null`) says where to put the entry instead.
102
+ */
103
+ export function registrationText(preset: AgentPreset, bun: string, bridge: string): string {
104
+ if (preset.mcp.add === null) return `${preset.displayName} has no scripted registration: add an MCP server named ${BRIDGE_NAME} that runs ${shellQuote(bun)} ${shellQuote(bridge)} to ${preset.mcp.check.file} under ${preset.mcp.check.key}`;
105
+ const words = preset.mcp.add.flatMap(word => word === "{args}" ? [bridge] : [word.replace("{name}", BRIDGE_NAME).replace("{command}", bun)]);
106
+ return words.map(shellQuote).join(" ");
107
+ }
108
+
109
+ /** Whether the CLI's settings file names the bridge: `present`, `missing` (a readable file without it, or no file) or `unknown` (a file this check cannot read). Reads one file, writes nothing. */
110
+ function registrationState(preset: AgentPreset, home: string): "present" | "missing" | "unknown" {
111
+ const file = preset.mcp.check.file.startsWith("~/") ? join(home, preset.mcp.check.file.slice(2)) : preset.mcp.check.file;
112
+ if (!existsSync(file)) return "missing";
113
+ try {
114
+ const parsed = JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>;
115
+ const block = parsed?.[preset.mcp.check.key];
116
+ return block && typeof block === "object" && !Array.isArray(block) ? (Object.hasOwn(block, BRIDGE_NAME) ? "present" : "missing") : "missing";
117
+ } catch { return "unknown"; }
118
+ }
119
+
120
+ /** One doctor row for each configured pull kind written from a known preset. */
121
+ export function pullRegistrationChecks(adapters: unknown, home: string, presets: readonly AgentPreset[] = loadPresets()): { kind: string; preset: string; state: "present" | "missing" | "unknown"; command: string }[] {
122
+ if (!adapters || typeof adapters !== "object") return [];
123
+ return Object.entries(adapters as Record<string, unknown>).flatMap(([kind, raw]) => {
124
+ const declared = raw as { transport?: unknown; preset?: unknown } | null;
125
+ const preset = declared?.transport === "pull" && typeof declared.preset === "string" ? presets.find(row => row.id === declared.preset) : undefined;
126
+ return preset ? [{ kind, preset: preset.id, state: registrationState(preset, home), command: registrationText(preset, process.execPath, BRIDGE_BUNDLE) }] : [];
127
+ });
128
+ }
129
+
130
+ /** Reads a JSON file that may not exist: absent is undefined; a file that is not valid JSON throws, so a write never replaces what it cannot read. */
131
+ export function readJsonFile(file: string): Record<string, unknown> | undefined {
132
+ if (!existsSync(file)) return undefined;
133
+ const value = JSON.parse(readFileSync(file, "utf8")) as unknown;
134
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${file} is not a JSON object`);
135
+ return value as Record<string, unknown>;
136
+ }
@@ -106,10 +106,10 @@ const NOTIFICATION_CAP = 64 * 1024;
106
106
  export function isQwenTaskNotification(text: string): boolean { return text.length <= NOTIFICATION_CAP && QWEN_TASK_NOTIFICATIONS.test(text); }
107
107
 
108
108
  /** `qwen --version` against the dual-output compat entry. Never throws: a refusal is a reason. */
109
- export async function qwenDualVersionAsync(cmd: readonly string[], cwd: string): Promise<{ ok: true; version: string; note?: string } | { ok: false; reason: string }> {
109
+ export async function qwenDualVersionAsync(cmd: readonly string[], cwd: string, env: NodeJS.ProcessEnv = process.env): Promise<{ ok: true; version: string; note?: string } | { ok: false; reason: string }> {
110
110
  const [bin, ...prefix] = cmd.filter(word => word !== "--acp");
111
111
  try {
112
- const child = Bun.spawn([bin ?? "qwen", ...prefix, "--version"], { cwd, stdout: "pipe", stderr: "ignore", stdin: "ignore", env: withoutOrcaEnv(childEnv(process.env)) });
112
+ const child = Bun.spawn([bin ?? "qwen", ...prefix, "--version"], { cwd, stdout: "pipe", stderr: "ignore", stdin: "ignore", env: withoutOrcaEnv(childEnv(env)) });
113
113
  const timer = setTimeout(() => child.kill("SIGKILL"), 10_000);
114
114
  const out = await new Response(child.stdout).text(); await child.exited; clearTimeout(timer);
115
115
  const verdict = assessVersion("qwen-dual", out.trim());
@@ -209,6 +209,8 @@ export interface AdapterDefinition {
209
209
  family: string;
210
210
  transport: "acp" | "codex-appserver" | "claude-channel" | "ws-pull" | "hub-native";
211
211
  roles: readonly string[];
212
+ /** #1809: `false` means the kind owns no task. Every ownership view reads this field, never the transport; only a configured pull kind sets it, and nothing sets it to `true` yet. */
213
+ tasks?: false;
212
214
  optional?: boolean;
213
215
  defaultOnRoster?: boolean;
214
216
  /** A legacy enable switch gates new starts, not retained sockets or queues. */
@@ -381,6 +383,7 @@ export type KindMap = Readonly<Record<string, { readonly kind: string; readonly
381
383
  export interface ProjectAdapterCatalog {
382
384
  readonly definitions: readonly AdapterDefinition[];
383
385
  readonly externalDefinitions: readonly AdapterDefinition[];
386
+ declaredHeadlessFactory?(definition: AdapterDefinition): boolean | undefined;
384
387
  definitionOf(id: string, instances?: KindMap): AdapterDefinition | undefined;
385
388
  kindOf(id: string, instances?: KindMap): string | undefined;
386
389
  familyOf(id: string, instances?: KindMap): string | undefined;
@@ -1,14 +1,16 @@
1
+ import { NATIVE_ADAPTER_POLICY, NATIVE_FRESH_REVIEWER_FACTORY } from "./definitions/native-adapter-policy.ts";
1
2
  import { AGY_DEFINITION } from "./agy/definition.ts";
2
3
  import { AGY_REVIEWER_VARIANT } from "./definitions/reviewer-variants.ts";
4
+ import { compareNativeRank } from "./definitions/native-help.ts";
3
5
  import { builtinCliEntries } from "./definitions/native-cli-entry.ts";
4
6
  import { builtinPreview } from "./definitions/native-cli-preview.ts";
5
7
  import { DAEMON_PORTS } from "./definitions/native-factories.ts";
6
8
  export { DAEMON_PORTS };
7
9
  import { NATIVE_BUILTIN_DEFINITIONS_WITHOUT_QWEN } from "./definitions/builtin-metadata.ts";
8
10
  import { QWEN_DEFINITION } from "./definitions/qwen.ts";
9
- import { configuredAcpDefinitions } from "./configured-acp.ts";
11
+ import { configuredAcpDefinitions, declaredConfiguredFactory } from "./configured-acp.ts";
10
12
  import type { AdapterDefinition, KindMap, ProjectAdapterCatalog } from "./registry-types.ts";
11
- import { types } from "node:util";
13
+ import { catalogFromDefinitions, declaredKind, resolvedDefinition } from "./declaration-resolution.ts";
12
14
 
13
15
  export type * from "./registry-types.ts";
14
16
  import { ADAPTER_API } from "./adapter-api.ts";
@@ -50,10 +52,7 @@ export function deriveAdapterLists(definitions: readonly AdapterDefinition[]): A
50
52
  const ordered = (field: "roleRank" | "startRank" | "helpRank", eligible = (_definition: AdapterDefinition) => true) => definitions
51
53
  .map((definition, index) => ({ definition, index })).filter(({ definition }) => eligible(definition))
52
54
  .sort((left, right) => {
53
- const a = left.definition.projection?.[field], b = right.definition.projection?.[field];
54
- if (a === undefined) return b === undefined ? left.index - right.index : 1;
55
- if (b === undefined) return -1;
56
- return a - b || left.index - right.index;
55
+ return compareNativeRank(left.definition.projection?.[field], right.definition.projection?.[field]) || left.index - right.index;
57
56
  }).map(({ definition }) => definition.kind);
58
57
  const KNOWN_PEERS = definitions.filter(definition => !definition.optional).map(definition => definition.kind);
59
58
  const OPTIONAL_PEERS = definitions.filter(definition => definition.optional).map(definition => definition.kind);
@@ -87,53 +86,29 @@ export const QUOTA_HANDOFF_PLATFORMS: Readonly<Record<string, string>> = Object.
87
86
  ADAPTERS.flatMap(adapter => adapter.hooks?.recallPlatform ? [[adapter.kind, adapter.hooks.recallPlatform]] : []),
88
87
  ));
89
88
 
90
- /** Own enumerable data field of a plain object, never a caller accessor or an inherited value. */
91
- function ownField(value: unknown, key: string): unknown {
92
- if (!value || typeof value !== "object" || types.isProxy(value) || Array.isArray(value)
93
- || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return undefined;
94
- const field = Object.getOwnPropertyDescriptor(value, key);
95
- return field && Object.hasOwn(field, "value") && field.enumerable ? field.value : undefined;
96
- }
97
- /** Declaration reads never execute caller accessors or inherit another project's mapping. */
98
- function declaredKind(id: string, instances: KindMap | undefined, catalog: ReadonlyMap<string, AdapterDefinition> = definitions): string | undefined {
99
- if (!instances || typeof instances !== "object" || types.isProxy(instances) || Array.isArray(instances)
100
- || ![Object.prototype, null].includes(Object.getPrototypeOf(instances))) return undefined;
101
- const field = Object.getOwnPropertyDescriptor(instances, id);
102
- if (!field || !Object.hasOwn(field, "value") || !field.enumerable) return undefined;
103
- const entry: unknown = field.value;
104
- if (!entry || typeof entry !== "object" || types.isProxy(entry) || Array.isArray(entry)
105
- || ![Object.prototype, null].includes(Object.getPrototypeOf(entry))) return undefined;
106
- const kind = Object.getOwnPropertyDescriptor(entry, "kind");
107
- if (!kind || !Object.hasOwn(kind, "value") || !kind.enumerable || typeof kind.value !== "string" || !catalog.has(kind.value)) return undefined;
108
- const prefix = `${kind.value}-`;
109
- return /^[a-z][a-z0-9-]{0,31}$/.test(id) && id.startsWith(prefix) && /^[a-z0-9][a-z0-9-]*$/.test(id.slice(prefix.length)) ? kind.value : undefined;
110
- }
111
89
  /** Legacy ids retain their identity. Extra instances resolve only through the explicit project map. */
112
90
  export function kindOf(id: string, instances?: KindMap): string | undefined {
113
- return definitions.has(id) ? id : typeof id === "string" ? declaredKind(id, instances) : undefined;
91
+ return definitions.has(id) ? id : typeof id === "string" ? declaredKind(id, instances, definitions) : undefined;
114
92
  }
115
93
  export function definitionOf(id: string, instances?: KindMap): AdapterDefinition | undefined {
116
94
  const kind = kindOf(id, instances);
117
95
  return resolvedDefinition(id, kind, instances, definitions);
118
96
  }
119
- function resolvedDefinition(id: string, kind: string | undefined, instances: KindMap | undefined, catalog: ReadonlyMap<string, AdapterDefinition>): AdapterDefinition | undefined {
120
- const definition = kind === undefined ? undefined : catalog.get(kind);
121
- // #223: only a declared extra (never the builtin id) with start_mode "headless" runs as the kind's reviewer variant.
122
- const declaration = ownField(instances, id), roles = ownField(declaration, "roles");
123
- const reviewerOnly = Array.isArray(roles) && !types.isProxy(roles) && roles.length === 1 && Object.getOwnPropertyDescriptor(roles, "0")?.value === "reviewer";
124
- const variant = definition?.reviewerVariant;
125
- const fresh = variant?.reviewer?.declaration === "automatic" || ownField(declaration, "review_mode") === "fresh";
126
- const headless = kind !== id && ownField(declaration, "start_mode") === "headless";
127
- if (variant && headless && reviewerOnly && fresh) return variant;
128
- const roleValues = Array.isArray(roles) && !types.isProxy(roles) && roles.length <= 4 ? Array.from({ length: roles.length }, (_, index) => Object.getOwnPropertyDescriptor(roles, String(index))?.value) : [];
129
- const writerRoles = roleValues.includes("implementer") && roleValues.every(role => role === "implementer" || role === "verifier");
130
- return headless && writerRoles && definition?.headlessVariant ? definition.headlessVariant : definition;
131
- }
132
97
  export function familyOf(id: string, instances?: KindMap): string | undefined {
133
98
  return definitionOf(id, instances)?.family;
134
99
  }
135
100
 
136
101
  /** Compile one captured, host-trusted declaration set; never register native policy globally. */
102
+ const builtinFactories = new Map<AdapterDefinition, boolean>();
103
+ for (const definition of ADAPTERS) {
104
+ const kind = definition.kind as keyof typeof NATIVE_ADAPTER_POLICY;
105
+ builtinFactories.set(definition, NATIVE_ADAPTER_POLICY[kind].headlessFactory);
106
+ if (definition.headlessVariant) builtinFactories.set(definition.headlessVariant, NATIVE_ADAPTER_POLICY.claudeImplementer.headlessFactory);
107
+ if (definition.reviewerVariant) builtinFactories.set(definition.reviewerVariant, kind === "claude"
108
+ ? NATIVE_ADAPTER_POLICY.claudeReviewer.headlessFactory
109
+ : NATIVE_FRESH_REVIEWER_FACTORY[kind as keyof typeof NATIVE_FRESH_REVIEWER_FACTORY]);
110
+ }
111
+
137
112
  export function createProjectAdapterCatalog(rawAdapters?: unknown, externalDefinitions: readonly AdapterDefinition[] = []): ProjectAdapterCatalog {
138
113
  const configured = configuredAcpDefinitions(rawAdapters, [...definitions.keys()]);
139
114
  for (const definition of configured) { assertDefinitionCoherence(definition); assertNativeCapabilityScope(definition); }
@@ -145,51 +120,15 @@ export function createProjectAdapterCatalog(rawAdapters?: unknown, externalDefin
145
120
  }
146
121
  const external = immutable([...externalDefinitions]);
147
122
  const entries = Object.freeze([...ADAPTERS, ...configured, ...external]);
148
- const catalog = new Map([...definitions, ...[...configured, ...external].map(definition => [definition.kind, definition] as const)]);
149
- const kindOf = (id: string, instances?: KindMap): string | undefined => catalog.has(id) ? id : typeof id === "string" ? declaredKind(id, instances, catalog) : undefined;
150
- const definitionOf = (id: string, instances?: KindMap): AdapterDefinition | undefined => resolvedDefinition(id, kindOf(id, instances), instances, catalog);
151
- return Object.freeze({ definitions: entries, externalDefinitions: external, kindOf, definitionOf,
152
- familyOf: (id: string, instances?: KindMap) => definitionOf(id, instances)?.family,
153
- isSupportedPeer: (id: unknown, instances?: KindMap): id is string => {
154
- if (typeof id !== "string") return false;
155
- const kind = kindOf(id, instances), runtime = kind === undefined ? undefined : catalog.get(kind), resolved = definitionOf(id, instances);
156
- return runtime !== undefined && resolved !== undefined && (kind === id || resolved === runtime || resolved.reviewer?.unavailable === undefined);
157
- },
158
- });
123
+ return catalogFromDefinitions(entries, external, definition => builtinFactories.get(definition) ?? declaredConfiguredFactory(definition));
159
124
  }
160
125
 
161
126
  /** Compatibility projection order is observable in default role maps and planner selection. */
162
127
 
163
128
 
164
- /** Callers own their role arrays, independent of immutable native policy. */
165
- export function defaultPeerRoles(includeOptional = false): Record<string, string[]> {
166
- return Object.fromEntries(ROLE_ORDER.filter(peer => includeOptional || !definitionOf(peer)!.optional)
167
- .map(peer => [peer, [...definitionOf(peer)!.roles]]));
168
- }
169
-
170
- /** Preserve the tool schema's legacy preferred order without spreading native names into tools. */
171
- const CONDUCTOR_START_PRIORITY = ["local", "kimi", "pi"] as const;
172
- export const CONDUCTOR_START_PEERS = [
173
- ...CONDUCTOR_START_PRIORITY,
174
- ...ADAPTERS.filter(adapter => !(CONDUCTOR_START_PRIORITY as readonly string[]).includes(adapter.kind)).map(adapter => adapter.kind),
175
- ];
129
+ export { defaultPeerRoles } from "./definitions/native-adapter-policy.ts";
176
130
 
177
- /**
178
- * The words a person reads about which kinds a conductor may start, derived from the definitions in registry order so a new kind is named without a text edit (#1408 R5).
179
- * `refusal` keeps the sentence the conductor always got, with the kinds read from `conductorStartable` and `optional`.
180
- */
181
- export function conductorStartText(): { peers: string; refusal: string; tuiPeers: string } {
182
- const startable = SUPPORTED_PEERS.filter(peer => definitionOf(peer)?.start.conductorStartable === true);
183
- const list = (names: readonly string[], joiner: string) => names.length < 2 ? names.join("") : `${names.slice(0, names.length - 1).join(", ")} ${joiner} ${names[names.length - 1]}`;
184
- const optional = (peer: string) => definitionOf(peer)?.optional === true;
185
- // A kind opens in a terminal when its person-set start mode is tui, and a kind whose own default form is a terminal one starts that way.
186
- const tui = startable.filter(peer => definitionOf(peer)!.start.defaultForm === "tui" && definitionOf(peer)!.start.forms.includes("tui"));
187
- return {
188
- peers: list(startable, "or"),
189
- refusal: `only ${list(startable.filter(peer => !optional(peer)), "and")}, plus the opt-in ${list(startable.filter(optional), "and")}, may be started by the conductor`,
190
- tuiPeers: list(tui, "and"),
191
- };
192
- }
131
+ export { CONDUCTOR_START_PEERS, conductorStartText } from "./declaration-catalog.ts";
193
132
 
194
133
  /** A missing definition retains external-id admission; Pi's legacy enabled switch controls its default only. */
195
134
  export function defaultRosterEnabled(peer: string, piEnabled: boolean): boolean {
@@ -294,7 +233,7 @@ export type SupportedPeer = typeof SUPPORTED_PEERS[number];
294
233
  export function isSupportedPeer(peer: unknown, instances?: KindMap): peer is string {
295
234
  if (typeof peer !== "string") return false;
296
235
  if (ADAPTERS.some(definition => definition.kind === peer)) return true;
297
- const kind = declaredKind(peer, instances);
236
+ const kind = declaredKind(peer, instances, definitions);
298
237
  const runtime = ADAPTERS.find(definition => definition.kind === kind), resolved = definitionOf(peer, instances);
299
238
  return runtime !== undefined && resolved !== undefined && (resolved === runtime || resolved.reviewer?.unavailable === undefined);
300
239
  }
@@ -162,13 +162,13 @@ export interface ReviewerPrintOptions {
162
162
  /** Host journal ACK before any usage-producing child is constructed; absent port refuses that launch. */
163
163
  usageIntent?(attempt: string, task: number): boolean;
164
164
  /** Proven native quota is account evidence, independent of whether this task later reroutes. */
165
- onQuota?(reading: NativeReviewerQuota, attempt: string, current: () => boolean): boolean;
165
+ onQuota?(reading: NativeReviewerQuota, attempt: string, current: () => boolean, turnStartedAt: number): boolean;
166
166
  /** Only after this attempt's owned group and watch have settled. Never grants task authority. */
167
167
  quotaSettled?(attempt: string): void;
168
168
  /** ACK after owned settlement and usage read; failed ACK retains the private profile for recovery. */
169
169
  usageSettled?(attempt: string, outcome: "complete" | "unknown", task: number): boolean;
170
170
  /** True confirms that the host re-offered the current review; void/false retains uncertainty. */
171
- onUnavailable?(failure: ReviewerFailure, current: () => boolean): boolean | void | Promise<boolean | void>;
171
+ onUnavailable?(failure: ReviewerFailure, current: () => boolean, turnStartedAt?: number): boolean | void | Promise<boolean | void>;
172
172
  onNoVerdict?(diagnostic: ReviewerNoVerdict, current: () => boolean): void;
173
173
  log?(line: string): void;
174
174
  taskMcp?(task: number, current: () => boolean): ReviewerMcpSession;
@@ -223,6 +223,16 @@ export class ReviewerPrintPeer extends BasePeer {
223
223
  private observerSessionIdValue: string | undefined;
224
224
  get isolationReceipt(): ReviewerIsolationReceipt | undefined { return this.receipt; }
225
225
  reviewObserverInputHeld(): boolean { return this.opts.reviewObserverHeld?.() ?? false; }
226
+
227
+ compareQuotaHome(): "unknown" | undefined {
228
+ return this.quotaLaunchInFlight() ? "unknown" : undefined;
229
+ }
230
+
231
+ /** An active attempt can still use a prior spawn environment, including during child cleanup. */
232
+ quotaLaunchInFlight(): boolean {
233
+ return this.activeDeliveryId !== undefined || this.preparation !== undefined
234
+ || this.child !== undefined || this.childCleanup !== undefined;
235
+ }
226
236
  /** The task whose review the running child was started for (R4: the hub records `fresh` for its verdict). */
227
237
  reviewing: number | undefined;
228
238
  /** Privacy-only identity for a fresh review profile; never part of resume or budget authority. */
@@ -259,6 +269,13 @@ export class ReviewerPrintPeer extends BasePeer {
259
269
  return this.reviewSeq;
260
270
  }
261
271
 
272
+ private readonly quotaFailureStarts = new WeakMap<ReviewerFailure, number>();
273
+
274
+ private rememberQuotaStart(failure: ReviewerFailure, turnStartedAt: number): ReviewerFailure {
275
+ if (failure.cause === "quota") this.quotaFailureStarts.set(failure, turnStartedAt);
276
+ return failure;
277
+ }
278
+
262
279
  constructor(id: string, private readonly opts: ReviewerPrintOptions) { super(id, opts.watchdogMs); }
263
280
 
264
281
  recoveryMetadata(): Record<string, unknown> { return { launch: { kind: "reviewer-print", peer: this.id } }; }
@@ -345,7 +362,7 @@ export class ReviewerPrintPeer extends BasePeer {
345
362
  if (env.private) { failure = { state: "needs_review", reason: "a private review is the person's, never a cloud reviewer's" }; break; }
346
363
  const since = Date.now();
347
364
  let result: { code: number | null; quota: boolean; quotaReadings?: readonly NativeReviewerQuota[]; trace: ReviewerTraceState };
348
- try { result = await this.review(env, task, generation); }
365
+ try { result = await this.review(env, task, generation, since); }
349
366
  catch (error) {
350
367
  if (generation !== this.generation) return;
351
368
  if (error instanceof ReviewerInputAdmissionError) {
@@ -391,9 +408,9 @@ export class ReviewerPrintPeer extends BasePeer {
391
408
  else this.opts.log?.(reviewerNoVerdictLine(this.id, diagnostic));
392
409
  } catch { this.opts.log?.(reviewerNoVerdictLine(this.id, { task, exitCode: result.code, reviewCalled: false }, undefined, true)); }
393
410
  const quotaMetadata = result.quotaReadings?.length ? { quota: result.quotaReadings } : {};
394
- if (target) reroute.push({ ...target, cause: result.quota ? "quota" : "no_verdict", ...quotaMetadata });
411
+ if (target) reroute.push(this.rememberQuotaStart({ ...target, cause: result.quota ? "quota" : "no_verdict", ...quotaMetadata }, since));
395
412
  if (result.quota) {
396
- reroute.push(...remainingFailures(batch, index + 1, "quota").map(failure => ({ ...failure, ...quotaMetadata })));
413
+ reroute.push(...remainingFailures(batch, index + 1, "quota").map(failure => this.rememberQuotaStart({ ...failure, ...quotaMetadata }, since)));
397
414
  batch.next = envs.length;
398
415
  break;
399
416
  }
@@ -419,7 +436,7 @@ export class ReviewerPrintPeer extends BasePeer {
419
436
  const identity = JSON.stringify([failed.task, failed.head, failed.flowRevision]);
420
437
  if (seen.has(identity)) continue;
421
438
  seen.add(identity);
422
- try { if (await this.opts.onUnavailable?.(failed, () => generation === this.generation) !== true) reoffered = false; }
439
+ try { if (await this.opts.onUnavailable?.(failed, () => generation === this.generation, this.quotaFailureStarts.get(failed)) !== true) reoffered = false; }
423
440
  catch { reoffered = false; this.opts.log?.(`[${this.id}] reviewer fallback could not be recorded; inspect the task`); }
424
441
  }
425
442
  return reoffered;
@@ -456,7 +473,7 @@ export class ReviewerPrintPeer extends BasePeer {
456
473
  if (this.opts.admit?.(env) === false) throw new ReviewerAdmissionError(this.opts.bindingCurrent?.(task, binding) === false ? "stale_binding" : "policy_changed");
457
474
  }
458
475
 
459
- private async review(env: Envelope, task: number, generation: number): Promise<{ code: number | null; quota: boolean; quotaReadings?: readonly NativeReviewerQuota[]; trace: ReviewerTraceState }> {
476
+ private async review(env: Envelope, task: number, generation: number, turnStartedAt: number): Promise<{ code: number | null; quota: boolean; quotaReadings?: readonly NativeReviewerQuota[]; trace: ReviewerTraceState }> {
460
477
  const revision=Number(env.refs?.reviewRevision);
461
478
  const binding: ReviewerReviewBinding=Object.freeze({head:env.refs?.commit,flowRevision:Number.isSafeInteger(revision)&&revision>0?revision:undefined});
462
479
  this.assertAdmission(env, task, binding);
@@ -539,13 +556,13 @@ export class ReviewerPrintPeer extends BasePeer {
539
556
  const observeQuota = (reading: NativeReviewerQuota) => {
540
557
  const key = JSON.stringify(reading);
541
558
  if (publishedQuota.has(key)) return;
542
- try { if (this.opts.onQuota?.(reading, quotaAttempt, () => generation === this.generation) === true) publishedQuota.add(key); }
559
+ try { if (this.opts.onQuota?.(reading, quotaAttempt, () => generation === this.generation, turnStartedAt) === true) publishedQuota.add(key); }
543
560
  catch { /* Retain the proven quota in the batch even if its immediate account write could not commit. */ }
544
561
  };
545
562
  const rememberQuota = () => {
546
563
  const batch = this.batch, target = batch?.targets[batch.next];
547
564
  if (!batch || generation !== this.generation || target?.task !== task) return;
548
- const failure: ReviewerFailure = { ...target, cause: "quota", ...(quotaReadings.size ? { quota: [...quotaReadings.values()] } : {}) };
565
+ const failure = this.rememberQuotaStart({ ...target, cause: "quota", ...(quotaReadings.size ? { quota: [...quotaReadings.values()] } : {}) }, turnStartedAt);
549
566
  const prior = batch.failures.findIndex(row => row.task === target.task && row.head === target.head && row.flowRevision === target.flowRevision && row.cause === "quota");
550
567
  if (prior < 0) batch.failures.push(failure); else batch.failures[prior] = failure;
551
568
  };
@@ -1,4 +1,5 @@
1
- import { SUPPORTED_PEERS, definitionOf, type ProjectAdapterCatalog } from "./registry.ts";
1
+ import { DECLARATION_SUPPORTED_PEERS as SUPPORTED_PEERS, builtinDeclarationOf as definitionOf } from "./declaration-catalog.ts";
2
+ import type { ProjectAdapterCatalog } from "./registry-types.ts";
2
3
  import type { StartMode } from "../hub/start-mode.ts";
3
4
 
4
5
  /**
@@ -0,0 +1,72 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { accountKinds, MAX_ACCOUNTS_PER_KIND } from "../hub/accounts.ts";
3
+ import { childEnv } from "../hub/child-process.ts";
4
+ import { warnLine } from "./warn-line.ts";
5
+ import { withoutOrcaEnv } from "../hub/orca-env.ts";
6
+
7
+ /**
8
+ * #1811 T4: `ahub accounts import --from orca` (person only, src/cli/identity.ts). One read of `orca account list --json`, then a printed `accounts` block for the accounts spec
9
+ * (#1810) in `.agenthub/config.local.json`. It writes nothing, and it prints no email, no account id, no organization and no workspace id: a label is `<kind>-<n>` only: Orca's workspace
10
+ * label can be a team or organization name, and the label is shown in status. A home is printed only when Orca's own output carries one; otherwise a placeholder the person must replace, which
11
+ * `readAccounts` refuses until they do.
12
+ */
13
+ const HOME_PLACEHOLDER = "/REPLACE/WITH/THE/ABSOLUTE/HOME";
14
+
15
+ interface ImportedAccounts { readonly accounts: Record<string, { kind: string; home: string }>; readonly notes: string[] }
16
+
17
+ /** Pure: Orca's `result` object (kind to `{ accounts: [...] }`) to a declaration. Only a kind the hub can bind to a home is read; the rest is ignored. */
18
+ function importOrcaAccounts(result: unknown): ImportedAccounts {
19
+ const accounts: Record<string, { kind: string; home: string }> = {};
20
+ const notes: string[] = [];
21
+ if (!result || typeof result !== "object" || Array.isArray(result)) return { accounts, notes: ["Orca returned no account list"] };
22
+ for (const kind of accountKinds()) {
23
+ const list = (result as Record<string, { accounts?: unknown }>)[kind]?.accounts;
24
+ if (!Array.isArray(list)) continue;
25
+ let counter = 0;
26
+ for (const entry of list) {
27
+ if (!entry || typeof entry !== "object") continue;
28
+ if (counter >= MAX_ACCOUNTS_PER_KIND) { notes.push(`${kind}: only the first ${MAX_ACCOUNTS_PER_KIND} accounts are listed (the limit per kind)`); break; }
29
+ counter++;
30
+ const row = entry as Record<string, unknown>;
31
+ const label = `${kind}-${counter}`;
32
+ const home = typeof row.home === "string" && row.home.startsWith("/") ? row.home : HOME_PLACEHOLDER;
33
+ accounts[label] = { kind, home };
34
+ }
35
+ }
36
+ if (Object.values(accounts).some(account => account.home === HOME_PLACEHOLDER)) notes.push(`replace ${HOME_PLACEHOLDER} with each account's absolute home before saving; the hub refuses the block until then`);
37
+ if (Object.keys(accounts).length === 0) notes.push("Orca lists no account for a kind the hub can bind");
38
+ return { accounts, notes };
39
+ }
40
+
41
+ function readOrcaAccounts(timeoutMs = 5_000): { ok: true; result: unknown } | { ok: false; reason: string } {
42
+ const run = spawnSync("orca", ["account", "list", "--json"], { encoding: "utf8", timeout: timeoutMs, maxBuffer: 1024 * 1024, env: withoutOrcaEnv(childEnv(process.env)) });
43
+ const NEXT = "run `orca account list --json` to see Orca's own answer";
44
+ if (run.error) {
45
+ const code = (run.error as NodeJS.ErrnoException).code;
46
+ if (code === "ENOENT") return { ok: false, reason: "the orca command is not on the PATH; install Orca or add its command to the PATH" };
47
+ if (code === "ETIMEDOUT" || run.signal) return { ok: false, reason: `the orca command did not answer within ${Math.round(timeoutMs / 1000)} seconds; ${NEXT}` };
48
+ return { ok: false, reason: `the orca command could not be started (${code ?? "unknown error"}); ${NEXT}` };
49
+ }
50
+ if (run.status !== 0) return { ok: false, reason: `the orca command exited with status ${run.status}; ${NEXT}` };
51
+ try {
52
+ const parsed = JSON.parse(run.stdout) as { ok?: unknown; result?: unknown };
53
+ return parsed && parsed.ok !== false && parsed.result !== undefined ? { ok: true, result: parsed.result } : { ok: false, reason: "orca answered without a result; run `orca account list --json` and check that it prints { ok: true, result }" };
54
+ } catch { return { ok: false, reason: "orca answered with something that is not JSON; run `orca account list --json` and check that it prints { ok: true, result }" }; }
55
+ }
56
+
57
+ /** The block as pretty JSON text, built here so the print is plain text for the person to paste, not a data reply. */
58
+ function renderBlock(accounts: ImportedAccounts["accounts"]): string {
59
+ const entries = Object.entries(accounts).map(([label, { kind, home }]) => ` ${JSON.stringify(label)}: { "kind": ${JSON.stringify(kind)}, "home": ${JSON.stringify(home)} }`);
60
+ return `{\n "accounts": {\n${entries.join(",\n")}\n }\n}`;
61
+ }
62
+
63
+ export function runAccountsImport(args: string[], fail: (message: string) => never): void {
64
+ const from = args[0] === "--from" ? args[1] : args[0]?.startsWith("--from=") ? args[0].slice("--from=".length) : undefined;
65
+ if (from !== "orca" || args.length !== (args[0] === "--from" ? 2 : 1)) fail("usage: ahub accounts import --from orca");
66
+ const read = readOrcaAccounts();
67
+ if (!read.ok) return fail(`accounts import: ${read.reason}; nothing was read and nothing was written`);
68
+ const imported = importOrcaAccounts(read.result);
69
+ console.log(renderBlock(imported.accounts));
70
+ for (const note of imported.notes) warnLine("accounts import", note);
71
+ warnLine("accounts import wrote nothing", "paste the block into .agenthub/config.local.json (it is never read from the tracked config.json)");
72
+ }
@@ -0,0 +1,88 @@
1
+ import { COMPAT, type CompatId, type CompatPolicy } from "../adapters/compat.ts";
2
+ import type { AgentVersionRow } from "./agents.ts";
3
+ import type { LatestRow } from "./agents-output.ts";
4
+
5
+ /**
6
+ * #1808 T5: a release publishes its `COMPAT` table as data (`plugins/agent-hub/compat.json`, written by `scripts/build.mjs`), and `ahub agents --latest` reads the newest release's copy to say which
7
+ * release verifies the version installed here. It is advice only: it writes nothing, admits nothing and never changes a verdict on the running hub (admission stays per hub release). It is a person-run
8
+ * command (`src/cli/identity.ts` keeps an agent shell out), and the daemon never imports this file: no hub path makes a network request for it (test/compat-published-table-1808.test.ts).
9
+ */
10
+ const COMPAT_TABLE_PATH = "plugins/agent-hub/compat.json";
11
+ const REPO = "STAIxBWLB/agent-hub";
12
+ const MAX_BYTES = 256 * 1024;
13
+ const MAX_ENTRIES = 64;
14
+ const MAX_VERSIONS = 512;
15
+ const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
16
+ const ID = /^[a-z][a-z0-9-]{0,63}$/;
17
+
18
+ interface PublishedEntry { verified: string[]; gate: string; referenceOnly?: true; line?: { min: string; below: string } }
19
+ interface PublishedTable { schemaVersion: 1; release: string; entries: Record<string, PublishedEntry> }
20
+
21
+ /** The table a release publishes. Only data a reader needs to compare versions; no trust note, receipt path or executable. */
22
+ function publishedCompatTable(release: string, table: Record<string, CompatPolicy> = COMPAT): PublishedTable {
23
+ const entries: Record<string, PublishedEntry> = {};
24
+ for (const [id, policy] of Object.entries(table)) {
25
+ entries[id] = { verified: [...policy.verified], gate: policy.gate, ...(policy.referenceOnly ? { referenceOnly: true as const } : {}), ...(policy.line ? { line: { min: policy.line.min, below: policy.line.below } } : {}) };
26
+ }
27
+ return { schemaVersion: 1, release, entries };
28
+ }
29
+ // used-by: scripts/build.mjs
30
+ /** The bytes `scripts/build.mjs` writes and `--check` compares. `table` is the one parameter tests change. */
31
+ export const publishedCompatText = (release: string, table: Record<string, CompatPolicy> = COMPAT): string => `${JSON.stringify(publishedCompatTable(release, table), null, 2)}\n`;
32
+
33
+ const plain = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
34
+
35
+ /** A table from the network, checked as strictly as a file: anything unexpected is refused as a whole, never partly read. */
36
+ function parsePublishedTable(value: unknown): PublishedTable | undefined {
37
+ if (!plain(value) || value.schemaVersion !== 1 || typeof value.release !== "string" || !SEMVER.test(value.release) || value.release.length > 64 || !plain(value.entries)) return undefined;
38
+ const raw = Object.entries(value.entries);
39
+ if (raw.length > MAX_ENTRIES) return undefined;
40
+ const entries: Record<string, PublishedEntry> = {};
41
+ for (const [id, entry] of raw) {
42
+ if (!ID.test(id) || !plain(entry) || typeof entry.gate !== "string" || entry.gate.length > 16 || !Array.isArray(entry.verified) || entry.verified.length > MAX_VERSIONS
43
+ || entry.verified.some(version => typeof version !== "string" || version.length > 64 || !SEMVER.test(version))
44
+ || entry.referenceOnly !== undefined && entry.referenceOnly !== true) return undefined;
45
+ entries[id] = { verified: entry.verified as string[], gate: entry.gate, ...(entry.referenceOnly === true ? { referenceOnly: true as const } : {}) };
46
+ }
47
+ return { schemaVersion: 1, release: value.release, entries };
48
+ }
49
+
50
+ export type FetchText = (url: string) => Promise<{ ok: boolean; status: number; text: () => Promise<string> }>;
51
+ const realFetch: FetchText = url => fetch(url, { signal: AbortSignal.timeout(15_000), headers: { accept: "application/json", "user-agent": "ahub-agents-latest" } });
52
+
53
+ async function readJson(fetchText: FetchText, url: string): Promise<unknown> {
54
+ const response = await fetchText(url);
55
+ if (!response.ok) throw new Error(`${new URL(url).host} answered ${response.status}`);
56
+ const text = await response.text();
57
+ if (text.length > MAX_BYTES) throw new Error("the answer is larger than expected");
58
+ try { return JSON.parse(text); } catch { throw new Error("the answer is not JSON"); }
59
+ }
60
+
61
+ /**
62
+ * The newest published release's table: the GitHub release names the tag, and the table is read at that tag from the committed plugin directory. Two reads, both GitHub, both public.
63
+ * It throws a short sentence (no body text) when either read fails or the table is not the expected shape, so the command never shows more than that.
64
+ */
65
+ export async function readLatestTable(fetchText: FetchText = realFetch): Promise<PublishedTable> {
66
+ const release = await readJson(fetchText, `https://api.github.com/repos/${REPO}/releases/latest`).catch((error: Error) => { throw new Error(`could not read the newest release (${error.message})`); });
67
+ const name = plain(release) && typeof release.tag_name === "string" ? release.tag_name.replace(/^v/, "") : "";
68
+ if (!SEMVER.test(name) || name.length > 64) throw new Error("the newest release has no usable version tag");
69
+ const table = parsePublishedTable(await readJson(fetchText, `https://raw.githubusercontent.com/${REPO}/v${name}/${COMPAT_TABLE_PATH}`).catch((error: Error) => {
70
+ // A 404 is a release from before the first one that published compat.json: say so and name what shows the local verdicts meanwhile.
71
+ if (/ answered 404$/.test(error.message)) throw new Error(`release ${name} has no compat.json: releases before the first one that publishes it have no table, so there is nothing to compare yet; ahub agents shows the local verdicts meanwhile`);
72
+ throw new Error(`could not read compat.json of ${name} (${error.message})`);
73
+ }));
74
+ if (!table) throw new Error(`compat.json of ${name} is not a table this ahub can read`);
75
+ if (table.release !== name) throw new Error(`compat.json of ${name} names another release`);
76
+ return table;
77
+ }
78
+
79
+ /** Only a refused or trusted version needs the answer; the rest are shown as they are. A reference-only entry verifies no version. */
80
+ export function latestRows(rows: readonly AgentVersionRow[], table: PublishedTable): LatestRow[] {
81
+ return rows.map(row => {
82
+ const version = row.verdict.version, state = row.verdict.state;
83
+ if (!row.executable || version === undefined || !(state === "refused" || state === "trusted")) return { id: row.id, ...(version === undefined ? {} : { version }), state, answer: "-" };
84
+ const entry = table.entries[row.id];
85
+ return { id: row.id, version, state, answer: entry && entry.referenceOnly !== true && entry.verified.includes(version) ? `verified in ${table.release}` : "not verified in any release" };
86
+ });
87
+ }
88
+
@@ -0,0 +1,22 @@
1
+ import type { CompatId } from "../adapters/compat.ts";
2
+ import { agentVersions } from "./agents.ts";
3
+ import { latestRows, readLatestTable, type FetchText } from "./agents-latest-table.ts";
4
+ import { renderAgentsLatest } from "./agents-output.ts";
5
+ import { Report, asciiMarkers, resolveColor, streamEnv } from "./console-state.ts";
6
+ import { outputWidth } from "./output.ts";
7
+
8
+ /**
9
+ * The person-run command. `fetchText` is injectable so a test never reaches the network. It writes nothing and changes no verdict. Only `src/cli/commands/agents.ts` imports this file: the daemon
10
+ * imports `agents.ts` for its drift probe and never this, so no hub path can reach the network reader (AC7).
11
+ */
12
+ export async function runAgentsLatest(args: readonly string[], commands: Partial<Record<CompatId, readonly string[]>>, fail: (message: string) => never, fetchText?: FetchText): Promise<void> {
13
+ if (args.some(arg => arg !== "--latest" && arg !== "--json")) return fail("usage: ahub agents --latest [--json]");
14
+ const isTTY = !!process.stdout.isTTY;
15
+ const columns = outputWidth({ isTTY, columns: process.stdout.columns, COLUMNS: process.env.COLUMNS });
16
+ let table;
17
+ try { table = await readLatestTable(fetchText); } catch (error) { return fail(`ahub agents --latest: ${(error as Error).message}; nothing was changed`); }
18
+ const rows = latestRows(agentVersions(commands), table);
19
+ if (args.includes("--json")) return console.log(JSON.stringify({ release: table.release, agents: rows }, null, 2));
20
+ const ascii = asciiMarkers(process.env), color = resolveColor(undefined, streamEnv(isTTY), "ahub") === true;
21
+ console.log(new Report(columns, ascii).append(renderAgentsLatest(rows, table.release, columns, ascii)).render(color).join("\n"));
22
+ }