@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
@@ -1,3 +1,4 @@
1
+ import { objectSpan, skip, type ObjectSpan } from "./json-text-spans.ts";
1
2
  /**
2
3
  * #1065 T1: the settings `ahub init` can set, as one table. A row names the flag, the file and key it writes, the closed set of values it accepts and how
3
4
  * to read it back, so a new setting (the specs rows of #1064 T3) is one more row here and nothing else. Executables, secrets, models, providers, instances
@@ -43,6 +44,9 @@ const choice = <T extends string>(id: string, flag: string, values: readonly T[]
43
44
 
44
45
  /** #1645 T4: the commented `[risk]` example a newly created sdlc.toml carries, so the tier table is discoverable without a project being opted in. */
45
46
  const RISK_SCAFFOLD = [
47
+ "# Automatic reruns for one failed required shard on a ready PR (#1801). Default is 0 (off).",
48
+ "# ci_shard_retries = 0",
49
+ "",
46
50
  "# Minimum review by risk tier (#1645): globs that make a change high, or that keep it low. A path no pattern names is medium, and a",
47
51
  "# path under [security] is always high. With this table commented out no tier is derived and every review stays as it is today.",
48
52
  "# [risk]",
@@ -139,41 +143,6 @@ export function parseInitSettings(args: readonly string[]): { request: InitSetti
139
143
  const isObject = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
140
144
  const valueAt = (doc: Record<string, unknown>, path: readonly string[]): unknown => path.reduce<unknown>((at, key) => isObject(at) ? at[key] : undefined, doc);
141
145
 
142
- // ---- A text-level JSON editor: it changes one key and leaves every other byte of the file where it was (AC2: the formatting of untouched keys is preserved). ----
143
- // The input is always text JSON.parse already accepted, so the scanner only has to find where values start and end.
144
- const skip = (text: string, at: number): number => { while (at < text.length && /\s/.test(text[at]!)) at++; return at; };
145
- function stringEnd(text: string, at: number): number { at++; while (text[at] !== '"') { if (text[at] === "\\") at++; at++; } return at + 1; }
146
- interface Member { key: string; keyStart: number; valueStart: number; valueEnd: number }
147
- interface ObjectSpan { start: number; end: number; members: Member[] }
148
- function valueEnd(text: string, from: number): number {
149
- let at = skip(text, from);
150
- const c = text[at];
151
- if (c === '"') return stringEnd(text, at);
152
- if (c === "{") return objectSpan(text, at).end;
153
- if (c === "[") {
154
- at = skip(text, at + 1);
155
- if (text[at] === "]") return at + 1;
156
- for (;;) { at = skip(text, valueEnd(text, at)); if (text[at] === ",") { at = skip(text, at + 1); continue; } return at + 1; }
157
- }
158
- while (at < text.length && !/[\s,\]}]/.test(text[at]!)) at++;
159
- return at;
160
- }
161
- function objectSpan(text: string, start: number): ObjectSpan {
162
- const members: Member[] = [];
163
- let at = skip(text, start + 1);
164
- if (text[at] === "}") return { start, end: at + 1, members };
165
- for (;;) {
166
- at = skip(text, at);
167
- const keyStart = at, keyEnd = stringEnd(text, at);
168
- const key = JSON.parse(text.slice(keyStart, keyEnd)) as string;
169
- at = skip(text, skip(text, keyEnd) + 1);
170
- const end = valueEnd(text, at);
171
- members.push({ key, keyStart, valueStart: at, valueEnd: end });
172
- at = skip(text, end);
173
- if (text[at] === ",") { at++; continue; }
174
- return { start, end: at + 1, members };
175
- }
176
- }
177
146
  const indentOf = (text: string, at: number): string => { const lineStart = text.lastIndexOf("\n", at - 1) + 1; return /^[ \t]*/.exec(text.slice(lineStart))![0]; };
178
147
  /** A value as the project's own files write it: scalars as JSON, a list of scalars on one line, an object over lines (or one line when `inline`). */
179
148
  function render(value: unknown, indent: string, inline: boolean): string {
package/src/cli/init.ts CHANGED
@@ -12,7 +12,7 @@ import { realPath } from "../hub/project.ts";
12
12
  import { hubGitArgv, hubGitEnv, hubGitSync } from "../hub/git.ts";
13
13
  import { KIMI_MCP_FILE } from "./kimi-mcp.ts";
14
14
  import { AGY_PLUGIN_FILES } from "./agy-mcp.ts";
15
- import { DEFAULT_CONFIG, loadConfig } from "../hub/daemon.ts";
15
+ import { DEFAULT_CONFIG, loadConfig } from "../hub/config.ts";
16
16
  import { ALL_MACHINE_LOCAL } from "../hub/config-trust.ts";
17
17
  import { requiredChecksFor } from "../hub/sdlc-merge.ts";
18
18
  import { githubOriginRepository } from "../hub/task-repository.ts";
@@ -0,0 +1,57 @@
1
+ // The input is always text JSON.parse already accepted, so the scanner only has to find where values start and end.
2
+ export const skip = (text: string, at: number): number => { while (at < text.length && /\s/.test(text[at]!)) at++; return at; };
3
+ function stringEnd(text: string, at: number): number { at++; while (text[at] !== '"') { if (text[at] === "\\") at++; at++; } return at + 1; }
4
+ interface Member { key: string; keyStart: number; valueStart: number; valueEnd: number }
5
+ export interface ObjectSpan { start: number; end: number; members: Member[] }
6
+ function valueEnd(text: string, from: number): number {
7
+ let at = skip(text, from);
8
+ const c = text[at];
9
+ if (c === '"') return stringEnd(text, at);
10
+ if (c === "{") return objectSpan(text, at).end;
11
+ if (c === "[") {
12
+ at = skip(text, at + 1);
13
+ if (text[at] === "]") return at + 1;
14
+ for (;;) { at = skip(text, valueEnd(text, at)); if (text[at] === ",") { at = skip(text, at + 1); continue; } return at + 1; }
15
+ }
16
+ while (at < text.length && !/[\s,\]}]/.test(text[at]!)) at++;
17
+ return at;
18
+ }
19
+ export function objectSpan(text: string, start: number): ObjectSpan {
20
+ const members: Member[] = [];
21
+ let at = skip(text, start + 1);
22
+ if (text[at] === "}") return { start, end: at + 1, members };
23
+ for (;;) {
24
+ at = skip(text, at);
25
+ const keyStart = at, keyEnd = stringEnd(text, at);
26
+ const key = JSON.parse(text.slice(keyStart, keyEnd)) as string;
27
+ at = skip(text, skip(text, keyEnd) + 1);
28
+ const end = valueEnd(text, at);
29
+ members.push({ key, keyStart, valueStart: at, valueEnd: end });
30
+ at = skip(text, end);
31
+ if (text[at] === ",") { at++; continue; }
32
+ return { start, end: at + 1, members };
33
+ }
34
+ }
35
+ /** Replace one existing value in validated JSON without re-encoding the surrounding text. */
36
+ export function replaceJsonValue(text: string, path: readonly (string | number)[], value: string): string {
37
+ let start = skip(text, 0);
38
+ let end = valueEnd(text, start);
39
+ for (const key of path) {
40
+ if (typeof key === "number" && text[start] === "[") {
41
+ let at = skip(text, start + 1);
42
+ for (let index = 0; index < key && text[at] !== "]"; index++) {
43
+ const separator = skip(text, valueEnd(text, at));
44
+ at = text[separator] === "," ? skip(text, separator + 1) : separator;
45
+ }
46
+ if (text[at] === "]") throw new Error("JSON array value is missing");
47
+ start = at;
48
+ end = valueEnd(text, start);
49
+ continue;
50
+ }
51
+ const member = text[start] === "{" ? objectSpan(text, start).members.findLast(item => item.key === key) : undefined;
52
+ if (!member) throw new Error("JSON object member is missing");
53
+ start = member.valueStart;
54
+ end = member.valueEnd;
55
+ }
56
+ return text.slice(0, start) + JSON.stringify(value) + text.slice(end);
57
+ }
@@ -0,0 +1,156 @@
1
+ import type { HubCheck } from "../hub/hub-check.ts";
2
+ import { HUB_CHECK_UNAVAILABLE, expectedHubLink, renderHubCheck, renderHubCheckUnavailable } from "../hub/hub-check.ts";
3
+ import type { AdapterDefinition, StartForm } from "../adapters/registry-types.ts";
4
+ import { plain } from "./warn-line.ts";
5
+
6
+ /**
7
+ * #1798 T3: the pre-launch and in-session surfaces render the one hub check the daemon returned in its status reply. Nothing here
8
+ * recomputes a link state or the expected link (`expectedHubLink` stays the only rule). A row carries ids, states, counts and commands.
9
+ */
10
+
11
+ /** One total bound for a launch-time read: connect, request and any retry share it. A slow or silent hub costs at most this long. */
12
+ const LAUNCH_CHECK_TOTAL_MS = 3_000;
13
+
14
+ /** One connection attempt (no retry, no instance check, no retry message) that gives up after `timeoutMs`. */
15
+ interface LaunchCheckClient { request(msg: { t: "status" }, timeoutMs?: number): Promise<{ status?: { hubCheck?: HubCheck } } | undefined>; close(): void }
16
+ type LaunchCheckConnect = (timeoutMs: number) => Promise<LaunchCheckClient>;
17
+
18
+ /**
19
+ * Read the check once under one total deadline: connecting gets the time left, the status request gets what is left after that. At the
20
+ * deadline any open client is closed, and a connection that opens late is closed at once with no request sent. It never throws and leaves
21
+ * no timer or socket behind, so nothing of it can outlive the launch it precedes.
22
+ */
23
+ export async function readLaunchCheck(connectOnce: LaunchCheckConnect, totalMs = LAUNCH_CHECK_TOTAL_MS): Promise<HubCheck | undefined> {
24
+ const deadline = Date.now() + totalMs;
25
+ let expired = false;
26
+ let open: LaunchCheckClient | undefined;
27
+ let timer: ReturnType<typeof setTimeout> | undefined;
28
+ const closeOpen = () => { const client = open; open = undefined; try { client?.close(); } catch { /* already closed */ } };
29
+ const attempt = (async (): Promise<HubCheck | undefined> => {
30
+ const client = await connectOnce(Math.max(1, deadline - Date.now()));
31
+ if (expired) { try { client.close(); } catch { /* already closed */ } return undefined; }
32
+ open = client;
33
+ const reply = await client.request({ t: "status" }, Math.max(1, deadline - Date.now()));
34
+ const check = reply?.status?.hubCheck;
35
+ return check && Array.isArray(check.peers) ? check : undefined;
36
+ })().catch(() => undefined);
37
+ try {
38
+ return await Promise.race([attempt, new Promise<undefined>(resolve => { timer = setTimeout(() => { expired = true; closeOpen(); resolve(undefined); }, totalMs); })]);
39
+ } catch { return undefined; }
40
+ finally { if (timer) clearTimeout(timer); closeOpen(); }
41
+ }
42
+
43
+ /** A daemon-supplied line cleaned for a terminal or a hook document: no control codes, and no line break that could add a line. */
44
+ export function cleanLine(line: string): string { return plain(line.replace(/[\r\n]+/g, " ")); }
45
+
46
+ /**
47
+ * The lines to print for one peer before it launches. The agent has not started, so nothing here is an OK or a warning about it: one neutral line says it is
48
+ * starting, with its expected link (from its row, else the shared rule for this definition and form), its queued count and `ahub status` to check after it
49
+ * starts. A row that is not offline adds its state, labelled as the state before this launch, without its mark or next step. A check that could not be read
50
+ * is the only warning, with its next step.
51
+ */
52
+ function renderLaunchCheck(check: HubCheck | undefined, peer: string, definition: Pick<AdapterDefinition, "transport" | "attach"> | undefined, form: StartForm): string[] {
53
+ if (!check) return renderHubCheckUnavailable(HUB_CHECK_UNAVAILABLE);
54
+ const row = check.peers.find(item => item.id === peer);
55
+ const expected = row?.expected ?? expectedHubLink(definition, form);
56
+ const lines = [renderHubCheck(check, [])[0]!, ` ${peer}: starting, expected link ${expected}, ${row ? `${row.queued} queued` : "queue unknown"}; check again after it starts: ahub status`];
57
+ if (row && row.observed !== "offline") lines.push(` state before this launch: ${row.observed}${row.cause ? `, ${row.cause}` : ""}`);
58
+ return lines;
59
+ }
60
+
61
+ /** The words the classifier rejects exactly (`DISABLING` in claude-channel-evidence.ts), printed only by these fixed names. */
62
+ const FIXED_WORDS = new Set(["--background", "--detach", "--daemon", "daemon", "bg", "bg-spare"]);
63
+ /** A fixed name for a rejected token, never the token itself: a prompt word or the text after `=` must not reach the check line (AC5). */
64
+ function fixedName(token: string | undefined): string | undefined {
65
+ if (token === undefined) return undefined;
66
+ if (token.startsWith("-p")) return "-p";
67
+ for (const flag of ["--print", "--output-format", "--dangerously-load-development-channels"]) if (token.startsWith(flag)) return flag;
68
+ return FIXED_WORDS.has(token) ? token : undefined;
69
+ }
70
+
71
+ /**
72
+ * The next step for a Claude launch whose final argv the channel classifier refused. `command` is the same flattened command the classifier read
73
+ * (`[cmd, ...args].join(" ")`) and `position` the index it rejected, undefined when the command was too long or held control characters.
74
+ * The classifier itself is unchanged; this words the advice by the one rejected token and prints only a fixed name for it.
75
+ */
76
+ export function claudeArgvNextStep(command: string, position: number | undefined): string {
77
+ if (position === undefined) return "Shorten the arguments passed to ahub claude (long command lines and control characters are not attested), then run it again.";
78
+ if (position <= 2) return `Try ahub claude --session-id "$(uuidgen | tr 'A-Z' 'a-z')" and report it on #1798`;
79
+ const name = fixedName(command.trim().split(/\s+/)[position]);
80
+ if (name === undefined) return "Remove the argument at that position, or start ahub claude without your prompt and type it in the session; the channel is not attested while it is there.";
81
+ return `${name} runs Claude without its channel or changes which channels load, so no hub link can attach; start without ${name}, and if it is a word in your prompt, start ahub claude without the prompt and type it in the session.`;
82
+ }
83
+
84
+ /** The reply of one status read, as the hook sees it: the hub's check and, for a Claude tools connection, the display hint. */
85
+ export interface StartHookReading { hubCheck?: HubCheck; thisLaunch?: boolean }
86
+
87
+ /** A check that must stay clearly below the hook entry's own timeout, process start included. */
88
+ export const START_HOOK_TOTAL_MS = 2_500;
89
+ export { START_HOOK_TIMEOUT_S } from "../adapters/definitions/native-launch-settings.ts";
90
+ const POLL_MS = 300;
91
+
92
+ export interface StartHookNotice {
93
+ /** One line for the person (`systemMessage`). */
94
+ line: string;
95
+ /** More lines for the model (`additionalContext`); the same facts, no more. */
96
+ lines: string[];
97
+ /** Whether the notice reports a healthy link. Only a verified, healthy Claude link is true. */
98
+ ok: boolean;
99
+ }
100
+
101
+ /** Startup and resume only: a clear or a compact is not a new session start. */
102
+ export function startHookShows(source: unknown): boolean {
103
+ return source === "startup" || source === "resume";
104
+ }
105
+
106
+ type Read = (timeoutMs: number) => Promise<StartHookReading | undefined>;
107
+ /**
108
+ * Read until this peer's link is judged, within one total deadline that covers every attempt. Claude: OK only when `thisLaunch` is true and the row is
109
+ * OK in the same reply; `thisLaunch` false keeps waiting, then ends `pending`; a missing field is "could not be verified", never OK. Nothing here computes a link state: it picks words for the row the daemon returned.
110
+ */
111
+ export async function startHookNotice(peer: string, read: Read, totalMs = START_HOOK_TOTAL_MS, now: () => number = Date.now, sleep: (ms: number) => Promise<unknown> = ms => Bun.sleep(ms)): Promise<StartHookNotice> {
112
+ const deadline = now() + totalMs;
113
+ let last: StartHookReading | undefined;
114
+ for (;;) {
115
+ const left = deadline - now();
116
+ if (left <= 0) break;
117
+ let timer: ReturnType<typeof setTimeout> | undefined;
118
+ try {
119
+ last = await Promise.race([read(left).catch(() => undefined), new Promise<undefined>(resolve => { timer = setTimeout(() => resolve(undefined), left); })]) ?? last;
120
+ } finally { if (timer) clearTimeout(timer); }
121
+ const row = last?.hubCheck?.peers.find(item => item.id === peer);
122
+ const settled = row !== undefined && row.observed !== "offline" && row.observed !== "pending" && last?.thisLaunch !== false;
123
+ if (settled) break;
124
+ if (deadline - now() <= POLL_MS) break;
125
+ await sleep(POLL_MS);
126
+ }
127
+ return startHookWords(peer, last);
128
+ }
129
+
130
+ function startHookWords(peer: string, reading: StartHookReading | undefined): StartHookNotice {
131
+ const check = reading?.hubCheck;
132
+ const row = check?.peers.find(item => item.id === peer);
133
+ const head = check ? `Hub check (agent-hub ${check.version})` : "Hub check";
134
+ const warn = (text: string): StartHookNotice => ({ line: `${head}: ⚠ ${text}`, lines: [`${head}: ⚠ ${text}`], ok: false });
135
+ if (!check || !row) return warn(`${peer}: the check could not be read from the hub; next: ahub status`);
136
+ const queued = row.queued ? `, ${row.queued} queued` : "";
137
+ if (!row.ok) return warn(`${peer}: ${row.observed}${row.cause ? `, ${row.cause}` : ""}${queued}${row.nextStep ? `; next: ${row.nextStep}` : ""}`);
138
+ if (row.observed === "offline" || row.observed === "pending") return warn(`${peer}: pending, not attached yet${queued}; next: ${row.nextStep ?? `ahub status`}`);
139
+ if (reading?.thisLaunch === undefined) return warn(`${peer}: this session's link could not be verified${queued}; next: ahub status`);
140
+ if (reading.thisLaunch === false) return warn(`${peer}: pending, this session has not attached yet${queued}; next: ahub status`);
141
+ const text = `✓ ${peer}: ${row.observed}${queued}`;
142
+ return { line: `${head}: ${text}`, lines: [`${head}: ${text}`], ok: true };
143
+ }
144
+
145
+ /**
146
+ * Pre-launch print from a status snapshot the wrapper already read for this launch (no second read). A snapshot without the check (an older hub), a failed
147
+ * read or a failed callback prints the unavailable warning. Stderr, so a wrapper's own stdout stays what it was.
148
+ */
149
+ export function printLaunchCheck(snapshot: { hubCheck?: HubCheck } | undefined, peer: string, definition?: Pick<AdapterDefinition, "transport" | "attach">, form: StartForm = "tui"): void {
150
+ // #1798 says the wrappers print the check to the terminal: with stderr redirected nothing prints (`ahub status` shows the same state).
151
+ if (process.stderr.isTTY !== true) return;
152
+ // A status snapshot has its own `peers` map: only its `hubCheck` field is the check.
153
+ const candidate = snapshot?.hubCheck;
154
+ const check = candidate && Array.isArray(candidate.peers) ? candidate : undefined;
155
+ for (const line of renderLaunchCheck(check, peer, definition, form)) console.error(cleanLine(line));
156
+ }
package/src/cli/launch.ts CHANGED
@@ -8,17 +8,20 @@ import { resolve, join, basename, dirname, isAbsolute } from "node:path";
8
8
  import { processLiveness, processSignature } from "../pi/process-signature.ts";
9
9
  import { realPath } from "../hub/project.ts";
10
10
  import { peerChildEnv, processTable } from "../hub/child-process.ts";
11
- import { definitionOf } from "../adapters/registry.ts";
11
+ import { nativeLaunchDeclaration } from "../adapters/definitions/native-launch-declarations.ts";
12
+ import { nativeWrapperLaunch } from "../adapters/definitions/native-wrapper-launch.ts";
13
+ import type { FactsHook, Launch, StatusLineTee } from "../adapters/definitions/native-launch-settings.ts";
12
14
  import type { InstancesConfig } from "../hub/instances.ts";
13
15
  import { kimiAcpCommand } from "../adapters/definitions/native-daemon-kimi.ts";
14
16
  import { warnLine } from "./warn-line.ts";
15
- export const CLAUDE_CHANNEL = "plugin:agent-hub@agent-hub";
17
+ export { CLAUDE_CHANNEL, sessionSettings, statusLineSettings, UNATTENDED_WARNING } from "../adapters/definitions/native-launch-settings.ts";
18
+ export type { FactsHook, Launch, StatusLineTee } from "../adapters/definitions/native-launch-settings.ts";
16
19
 
17
20
  export { retainedLaunchWarning } from "../adapters/definitions/native-cli-retained.ts";
18
21
 
19
22
  /** Consume only ahub's selector, never native arguments after the passthrough delimiter. */
20
23
  export function instanceLaunchArguments(command: string, raw: readonly string[], instances?: InstancesConfig): { instance?: string; args: string[]; hubStarted?: true } {
21
- if (!definitionOf(command)) return { args: [...raw] };
24
+ if (!nativeLaunchDeclaration(command)) return { args: [...raw] };
22
25
  const args: string[] = [];
23
26
  let instance: string | undefined, hubStarted = false;
24
27
  for (let index = 0; index < raw.length; index++) {
@@ -29,14 +32,14 @@ export function instanceLaunchArguments(command: string, raw: readonly string[],
29
32
  const id = arg === "--as" ? raw[++index] : arg.slice("--as=".length);
30
33
  if (!id || id.startsWith("--")) throw new Error("--as needs a declared instance id");
31
34
  const declaration = instances && Object.hasOwn(instances, id) ? instances[id] : undefined;
32
- if (!declaration || declaration.kind !== command || !definitionOf(id, instances)) throw new Error("--as must name a declared instance of this command's native kind");
35
+ if (!declaration || declaration.kind !== command || !nativeLaunchDeclaration(id, instances)) throw new Error("--as must name a declared instance of this command's native kind");
33
36
  // #223: a headless reviewer is started by the hub, never from this terminal.
34
- const runtime = definitionOf(id, instances), base = definitionOf(command);
37
+ const runtime = nativeLaunchDeclaration(id, instances), base = nativeLaunchDeclaration(command);
35
38
  hubStarted = runtime === base?.reviewerVariant || runtime === base?.headlessVariant;
36
39
  instance = id;
37
40
  }
38
41
  if (hubStarted && args.some(arg => arg !== "--print-command" && arg !== "--dry-run")) {
39
- const writer = definitionOf(instance!, instances) === definitionOf(command)?.headlessVariant;
42
+ const writer = nativeLaunchDeclaration(instance!, instances) === nativeLaunchDeclaration(command)?.headlessVariant;
40
43
  throw new Error(`${instance} is a headless ${writer ? "implementer the hub runs per task" : "reviewer the hub runs per review"}: ahub ${command} --as ${instance} takes no launch arguments`);
41
44
  }
42
45
  return { ...(instance ? { instance } : {}), args, ...(hubStarted ? { hubStarted: true as const } : {}) };
@@ -61,25 +64,12 @@ export function nativeLaunchEnv(tool: string, source: NodeJS.ProcessEnv, instanc
61
64
  const env = peerChildEnv(tool, source, { preserveOrca: true });
62
65
  delete env.AGENTHUB_UNATTENDED;
63
66
  // Channel evidence for the plugin (issue #205): set beside the development-channel flag `buildLaunch` always passes.
64
- const definition = definitionOf(tool, instances);
65
- if (definition?.identity.mcp === "channel-plugin" && !definition.attach?.pullOnlyForms?.includes("tui")) env.AGENTHUB_CHANNEL = "1";
66
- if (definition?.attach?.pullOnlyForms?.includes("tui")) delete env.AGENTHUB_MODE; // its MCP child must attach pull-only, never as a tools socket
67
+ const definition = nativeLaunchDeclaration(tool, instances);
68
+ if (definition?.identity.mcp === "channel-plugin" && !definition.pullOnly) env.AGENTHUB_CHANNEL = "1";
69
+ if (definition?.pullOnly) delete env.AGENTHUB_MODE; // its MCP child must attach pull-only, never as a tools socket
67
70
  return env;
68
71
  }
69
72
 
70
- export const UNATTENDED_WARNING =
71
- "WARNING: --unattended disables permission prompts. Other agents' messages are untrusted input and this agent will act on its own judgment without asking you.";
72
-
73
- export interface Launch {
74
- cmd: string;
75
- args: string[];
76
- warning?: string;
77
- permissionHook?: boolean;
78
- hookPurpose?: FactsHook["purpose"];
79
- settingsFile?: string;
80
- unattended?: boolean;
81
- }
82
-
83
73
  /** Retire only our prior private Claude settings file, after the replacement launch record is committed. */
84
74
  export function cleanupClaudeSettings(stateDir: string, previous: unknown): void {
85
75
  if (typeof previous !== "string" || !isAbsolute(previous) || !/^claude-settings-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.json$/.test(basename(previous))) return;
@@ -256,7 +246,12 @@ function directNativeExecutable(command: string, cwd: string, env: NodeJS.Proces
256
246
  }
257
247
 
258
248
  /** Same native stdio/environment and exit result as spawnSync, with a live child identity before it exits. */
259
- export async function runClaudeLaunch(launch: Launch, options: { cwd: string; env: NodeJS.ProcessEnv; stateDir: string; record?: ClaudeLaunchRecord }): Promise<{ status: number | null; signal: NodeJS.Signals | null; error?: Error }> {
249
+ export async function runClaudeLaunch(launch: Launch, options: { cwd: string; env: NodeJS.ProcessEnv; stateDir: string; record?: ClaudeLaunchRecord; beforeSpawn?: () => Promise<void> | void }): Promise<{ status: number | null; signal: NodeJS.Signals | null; error?: Error }> {
250
+ // #1798 T3: the pre-launch Hub check runs here, at the spawn boundary, next to the executable check it must not outlive. Without the callback there is no added await.
251
+ if (options.beforeSpawn) {
252
+ try { await options.beforeSpawn(); }
253
+ catch { warnLine("the Hub check could not run before the launch", "ahub status"); }
254
+ }
260
255
  const direct = directNativeExecutable(launch.cmd, options.cwd, options.env);
261
256
  return new Promise(resolveResult => {
262
257
  let attestation: Promise<unknown> | undefined;
@@ -284,35 +279,6 @@ export async function runClaudeLaunch(launch: Launch, options: { cwd: string; en
284
279
  });
285
280
  }
286
281
 
287
- export interface StatusLineTee {
288
- /** absolute path of src/cli/statusline-tee.ts */
289
- script: string;
290
- stateDir: string;
291
- /** the user's own statusLine setting, wrapped so the status line looks the same */
292
- original?: { command?: string; refreshInterval?: number; padding?: number };
293
- }
294
-
295
- const sh = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`;
296
-
297
- /**
298
- * Settings for one session that put the tee in front of the user's status line command. Claude Code's status line
299
- * input carries `rate_limits`; this is the hub's Claude quota source. `~/.claude/settings.json` is never edited.
300
- */
301
- export function statusLineSettings(tee: StatusLineTee): string {
302
- const command = `AGENTHUB_STATE_DIR=${sh(tee.stateDir)} AGENTHUB_STATUSLINE_CMD=${sh(tee.original?.command ?? "")} bun ${sh(tee.script)}`;
303
- return JSON.stringify({ statusLine: { type: "command", command, refreshInterval: tee.original?.refreshInterval ?? 10, ...(tee.original?.padding !== undefined ? { padding: tee.original.padding } : {}) } });
304
- }
305
-
306
- /** Shared facts, native observation and permission hook transport. */
307
- export interface FactsHook {
308
- script: string;
309
- stateDir: string;
310
- /** The same hook transport can observe native turns without injecting facts. */
311
- purpose?: "facts" | "idle" | "facts-and-idle" | "permission";
312
- /** Observe native sessions/turns for every enabled facts, idle or conductor hook configuration. */
313
- observeNative?: boolean;
314
- }
315
-
316
282
  /** Shared by actual launch and preview; permissions are always enabled, advisory facts remain disabled. */
317
283
  export function claudeObservationHooks(config: { coordination?: string; task_sweep?: { enabled: boolean }; roles?: Record<string, string[]> }, paths: Pick<FactsHook, "script" | "stateDir">): FactsHook {
318
284
  const facts = config.coordination === "turn-free";
@@ -321,29 +287,12 @@ export function claudeObservationHooks(config: { coordination?: string; task_swe
321
287
  return { ...paths, purpose: facts ? (idle ? "facts-and-idle" : "facts") : idle || observeNative ? "idle" : "permission", ...(observeNative ? { observeNative: true } : {}) };
322
288
  }
323
289
 
324
- /**
325
- * The one `--settings` value of a hub-launched Claude session: the status line tee, and in a turn-free project the
326
- * facts hook before and after every tool call and at the end of each turn (issue #108; the turn end is the quiescence
327
- * evidence of issue #107).
328
- */
329
- export function sessionSettings(tee?: StatusLineTee, facts?: FactsHook): string {
330
- const settings = (tee ? JSON.parse(statusLineSettings(tee)) : {}) as Record<string, unknown>;
331
- if (facts) {
332
- const hooks = [{ type: "command", command: `AGENTHUB_STATE_DIR=${sh(facts.stateDir)} AGENTHUB_HOOK_PURPOSE=${sh(facts.purpose ?? "facts")} bun ${sh(facts.script)}`, timeout: 5 }];
333
- settings.hooks = { PreToolUse: [{ matcher: "*", hooks }], ...(facts.purpose !== "permission" ? { PostToolUse: [{ matcher: "*", hooks }], Stop: [{ hooks }] } : {}) };
334
- if (facts.observeNative) Object.assign(settings.hooks as object, { SessionStart: [{ matcher: "*", hooks }], UserPromptSubmit: [{ hooks }] });
335
- }
336
- return JSON.stringify(settings);
337
- }
338
-
339
290
  export function buildLaunch(
340
291
  tool: "claude" | "codex",
341
292
  userArgs: string[],
342
293
  ctx: { instance?: string; unattended: boolean; proxyUrl?: string; launchTokenEnv?: string; codexBin?: string; statusLine?: StatusLineTee; facts?: FactsHook; preview?: boolean },
343
294
  ): Launch {
344
- const adapter = definitionOf(tool);
345
- if (!adapter) throw new Error("native launch definition unavailable");
346
- const { metadata: _metadata, ...launch } = adapter.start.launch!({
295
+ const { metadata: _metadata, ...launch } = nativeWrapperLaunch(tool, {
347
296
  instance: ctx.instance ?? tool, form: "tui", projectRoot: process.cwd(), stateDir: ctx.facts?.stateDir ?? ctx.statusLine?.stateDir ?? "",
348
297
  entrypoint: resolve(import.meta.dir, "main.js"), userArgs, env: {}, ...ctx,
349
298
  });
@@ -0,0 +1,29 @@
1
+ // #1778 T7: the light path of `src/cli/main.js`. A command that needs nothing from the shared invocation setup in `main.ts`
2
+ // (project selection, caller identity, audit) reaches its command module from here, and never loads `main.ts` or `hub/config.ts`.
3
+ // Anything else returns false and `main.js` falls through to `main.ts`, so no command changes behavior.
4
+ import { commandLoader } from "./command-table.ts";
5
+ import type { CommandContext } from "./command-context.ts";
6
+
7
+ /** The environment markers `detectCliIdentity` reads. With none set, and no recovery, instructed-child or project marker, the caller is the person's own shell (`role: "console"`). */
8
+ const MARKER = /^(?:AGENTHUB_(?:PEER_ID|PROJECT_DIR|INSTRUCTED|RECOVERY)|CLAUDECODE$|CLAUDE_CODE_SESSION_ID$|CODEX_THREAD_ID$)/;
9
+
10
+ /** The commands whose behavior for that caller is exactly what their module does: `version` prints, `instruction-hook` returns unless the caller is an agent. */
11
+ const LIGHT = new Set(["version", "--version", "instruction-hook"]);
12
+
13
+ // used-by: src/cli/main.js (through runLight)
14
+ export function isLightInvocation(argv: readonly string[], env: Readonly<Record<string, string | undefined>>): boolean {
15
+ if (argv.length !== 1 || !LIGHT.has(argv[0]!)) return false;
16
+ return !Object.keys(env).some(key => MARKER.test(key));
17
+ }
18
+
19
+ // used-by: src/cli/main.js
20
+ /** Runs the command and answers true, or answers false without side effects when the invocation is not a light one. */
21
+ export async function runLight(argv: readonly string[], env: Readonly<Record<string, string | undefined>>): Promise<boolean> {
22
+ if (!isLightInvocation(argv, env)) return false;
23
+ const load = commandLoader(argv[0]!, []);
24
+ if (!load) return false;
25
+ // Only what these modules read: the person's shell has no hub connection to make.
26
+ const context = { args: [], caller: { role: "console" }, liveTest: false, connect: async () => { throw new Error("no hub connection on the light path"); } } as unknown as CommandContext;
27
+ await (await load()).run(context);
28
+ return true;
29
+ }
package/src/cli/main.js CHANGED
@@ -18,4 +18,11 @@ if (process.env.AGENTHUB_INSTRUCTED_IPC !== undefined) {
18
18
  if (process.argv[2] === "__complete") {
19
19
  const { completeWords } = await import("./completion.ts");
20
20
  console.log(completeWords(process.argv.slice(process.argv[3] === "--" ? 4 : 3)).join("\n"));
21
- } else await import("./main.ts");
21
+ } else if (!lightEligible() || !await (await import("./light-dispatch.ts")).runLight(process.argv.slice(2), process.env)) await import("./main.ts");
22
+
23
+ // #1778 T7: the cheap half of the light gate, so nothing else is imported for a call that cannot be light. src/cli/light-dispatch.ts holds the same marker pattern and re-checks it.
24
+ function lightEligible() {
25
+ const argv = process.argv.slice(2);
26
+ if (argv.length !== 1 || !["version", "--version", "instruction-hook"].includes(argv[0])) return false;
27
+ return !Object.keys(process.env).some(key => /^(?:AGENTHUB_(?:PEER_ID|PROJECT_DIR|INSTRUCTED|RECOVERY)|CLAUDECODE$|CLAUDE_CODE_SESSION_ID$|CODEX_THREAD_ID$)/.test(key));
28
+ }