@staix/agent-hub 0.51.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 (299) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +1 -1
  3. package/docs/adding-an-ai-tool.md +24 -2
  4. package/docs/agent-notes/adapters.md +1 -0
  5. package/docs/agent-notes/budget.md +8 -2
  6. package/docs/agent-notes/daemon.md +13 -8
  7. package/docs/agent-notes/security-review.md +6 -5
  8. package/docs/agent-notes/tasks.md +5 -2
  9. package/docs/agent-notes/tests.md +4 -3
  10. package/docs/cooperbench.md +1 -1
  11. package/docs/design/adapters.md +4 -0
  12. package/docs/design/cli-output-inventory.md +162 -152
  13. package/docs/design/cli-output.md +4 -3
  14. package/docs/design/guidance-probes.md +1 -0
  15. package/docs/design/roadmap.md +2 -0
  16. package/docs/design/task-board.md +1 -0
  17. package/docs/dogfood.md +14 -0
  18. package/docs/events.md +4 -2
  19. package/docs/memory.md +5 -3
  20. package/docs/operations.md +210 -16
  21. package/docs/quickstart.md +12 -2
  22. package/docs/roles.md +1 -1
  23. package/docs/sdlc.md +26 -3
  24. package/docs/security.md +11 -5
  25. package/docs/specs/2026-09-19-agent-hub-design.md +43 -0
  26. package/docs/specs/2026-09-19-multi-project-design.md +4 -0
  27. package/docs/specs/2026-09-20-upgrade-recovery-design.md +17 -0
  28. package/docs/specs/mcp-endpoint.md +63 -0
  29. package/docs/verification/2026-11-30-capability-listing-shape-1808.md +45 -0
  30. package/docs/verification/2026-11-30-upgrade-keep-1807.md +174 -0
  31. package/docs/verification/2026-12-01-1811-confirmation-receipt.md +19 -0
  32. package/docs/verification/2026-12-01-1811-orca-agent-list.md +20 -0
  33. package/docs/verification/2026-12-01-1811-orca-pane-key.md +21 -0
  34. package/docs/verification/2026-12-02-1819-claude-process-after-renewal.md +54 -0
  35. package/docs/verification/2026-12-02-agy-1.5.21.md +74 -0
  36. package/docs/verification/2026-12-02-claude-implementer-2.1.334.md +44 -0
  37. package/docs/verification/2026-12-02-cli-import-graph.md +33 -0
  38. package/docs/verification/2026-12-03-0.52.0.md +150 -0
  39. package/docs/verification/2026-12-03-codex-0173-reviewer-isolation.md +53 -0
  40. package/docs/verification/2026-12-03-codex-0173-reviewer-tool-call.md +34 -0
  41. package/docs/verification/2026-12-03-jcode-1.3.0.md +25 -0
  42. package/docs/verification/agy/README.md +17 -0
  43. package/docs/verification/agy/cli-surface.ts +68 -0
  44. package/docs/verification/agy/interactive-bridge.ts +92 -0
  45. package/docs/verification/agy/interactive-session.ts +131 -0
  46. package/docs/verification/agy/launcher-nonce.ts +215 -0
  47. package/docs/verification/agy/native-hooks.ts +210 -0
  48. package/docs/verification/agy/originals/agent-hub-681/cli-surface.ts +87 -0
  49. package/docs/verification/agy/originals/agent-hub-681/native-hooks-adapted.ts +91 -0
  50. package/docs/verification/agy/originals/agent-hub-681/tui-actual.ts +200 -0
  51. package/docs/verification/agy/originals/agent-hub-684/probe.ts +107 -0
  52. package/docs/verification/agy/originals.json +25 -0
  53. package/docs/verification/agy/permission-new-functions.ts +128 -0
  54. package/docs/verification/agy/run-probe.py +108 -0
  55. package/docs/verification/agy/runtime.ts +171 -0
  56. package/docs/verification/agy/tmux-helper-control.ts +6 -0
  57. package/docs/verification/agy/tmux-session.ts +235 -0
  58. package/docs/verified.json +82 -41
  59. package/package.json +3 -3
  60. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  61. package/plugins/agent-hub/compat.json +157 -0
  62. package/plugins/agent-hub/kimi-hook.js +621 -865
  63. package/plugins/agent-hub/server.js +17423 -32962
  64. package/src/adapters/agy/definition.ts +7 -24
  65. package/src/adapters/channel-peer.ts +3 -1
  66. package/src/adapters/claude-channel.ts +38 -257
  67. package/src/adapters/claude-implementer.ts +3 -1
  68. package/src/adapters/codex-appserver.ts +77 -15
  69. package/src/adapters/compat.ts +74 -11
  70. package/src/adapters/configured-acp.ts +23 -163
  71. package/src/adapters/configured-adapter-policy.ts +160 -0
  72. package/src/adapters/configured-pull-entry.ts +53 -0
  73. package/src/adapters/configured-pull.ts +38 -0
  74. package/src/adapters/conformance/fakes/app-server.ts +9 -2
  75. package/src/adapters/declaration-catalog.ts +25 -0
  76. package/src/adapters/declaration-data.ts +342 -0
  77. package/src/adapters/declaration-resolution.ts +53 -0
  78. package/src/adapters/definitions/builtin-metadata.ts +61 -83
  79. package/src/adapters/definitions/jcode-launch.ts +13 -0
  80. package/src/adapters/definitions/native-adapter-policy.ts +390 -0
  81. package/src/adapters/definitions/native-cli-claude-launch.ts +3 -2
  82. package/src/adapters/definitions/native-cli-codex-launch.ts +2 -1
  83. package/src/adapters/definitions/native-cli-entry-jcode.ts +4 -2
  84. package/src/adapters/definitions/native-cli-entry-types.ts +9 -2
  85. package/src/adapters/definitions/native-cli-launch-common.ts +2 -2
  86. package/src/adapters/definitions/native-cli-retained.ts +1 -1
  87. package/src/adapters/definitions/native-configuration.ts +18 -0
  88. package/src/adapters/definitions/native-help.ts +24 -0
  89. package/src/adapters/definitions/native-launch-declarations.ts +34 -0
  90. package/src/adapters/definitions/native-launch-policy.ts +4 -0
  91. package/src/adapters/definitions/native-launch-settings.ts +72 -0
  92. package/src/adapters/definitions/native-light-cli.ts +18 -0
  93. package/src/adapters/definitions/native-light-preview.ts +10 -0
  94. package/src/adapters/definitions/native-wrapper-launch.ts +10 -0
  95. package/src/adapters/definitions/qwen.ts +6 -29
  96. package/src/adapters/definitions/reviewer-variants.ts +7 -8
  97. package/src/adapters/external-declarations.ts +31 -0
  98. package/src/adapters/external-modules.ts +4 -29
  99. package/src/adapters/jcode.ts +3 -12
  100. package/src/adapters/native-capabilities.ts +18 -8
  101. package/src/adapters/native-proof-ports.ts +1 -1
  102. package/src/adapters/presets.ts +136 -0
  103. package/src/adapters/qwen-dual.ts +2 -2
  104. package/src/adapters/registry-types.ts +3 -0
  105. package/src/adapters/registry.ts +20 -81
  106. package/src/adapters/reviewer-print.ts +26 -9
  107. package/src/adapters/role-eligibility.ts +2 -1
  108. package/src/cli/accounts-import.ts +72 -0
  109. package/src/cli/agents-latest-table.ts +88 -0
  110. package/src/cli/agents-latest.ts +22 -0
  111. package/src/cli/agents-output.ts +10 -0
  112. package/src/cli/agents-presets.ts +100 -0
  113. package/src/cli/agents.ts +1 -1
  114. package/src/cli/attention.ts +3 -2
  115. package/src/cli/autonomy-homes.ts +7 -2
  116. package/src/cli/budget-renew-guidance.ts +129 -0
  117. package/src/cli/claude-homes.ts +9 -5
  118. package/src/cli/command-context.ts +3 -0
  119. package/src/cli/command-table.ts +123 -0
  120. package/src/cli/commands/accounts.ts +8 -0
  121. package/src/cli/commands/agents.ts +18 -0
  122. package/src/cli/commands/answer.ts +28 -0
  123. package/src/cli/commands/ask.ts +17 -0
  124. package/src/cli/commands/autonomy.ts +83 -0
  125. package/src/cli/commands/backlog.ts +46 -0
  126. package/src/cli/commands/bench.ts +60 -0
  127. package/src/cli/commands/board.ts +48 -0
  128. package/src/cli/commands/broker.ts +9 -0
  129. package/src/cli/commands/budget.ts +96 -0
  130. package/src/cli/commands/capabilities.ts +12 -0
  131. package/src/cli/commands/check-path.ts +55 -0
  132. package/src/cli/commands/completion.ts +8 -0
  133. package/src/cli/commands/console.ts +12 -0
  134. package/src/cli/commands/daemon.ts +8 -0
  135. package/src/cli/commands/deliverables.ts +25 -0
  136. package/src/cli/commands/doctor.ts +249 -0
  137. package/src/cli/commands/down.ts +3 -0
  138. package/src/cli/commands/export.ts +15 -0
  139. package/src/cli/commands/facts.ts +15 -0
  140. package/src/cli/commands/goal.ts +22 -0
  141. package/src/cli/commands/guidance.ts +102 -0
  142. package/src/cli/commands/help.ts +17 -0
  143. package/src/cli/commands/host.ts +45 -0
  144. package/src/cli/commands/init.ts +121 -0
  145. package/src/cli/commands/instructed.ts +19 -0
  146. package/src/cli/commands/instruction-hook.ts +15 -0
  147. package/src/cli/commands/intake.ts +24 -0
  148. package/src/cli/commands/kill.ts +15 -0
  149. package/src/cli/commands/learn.ts +23 -0
  150. package/src/cli/commands/lineage.ts +30 -0
  151. package/src/cli/commands/logs.ts +21 -0
  152. package/src/cli/commands/manager.ts +15 -0
  153. package/src/cli/commands/memory.ts +21 -0
  154. package/src/cli/commands/model.ts +25 -0
  155. package/src/cli/commands/models.ts +40 -0
  156. package/src/cli/commands/native.ts +39 -0
  157. package/src/cli/commands/pause.ts +5 -0
  158. package/src/cli/commands/peer.ts +32 -0
  159. package/src/cli/commands/permission.ts +26 -0
  160. package/src/cli/commands/permit.ts +12 -0
  161. package/src/cli/commands/pet.ts +24 -0
  162. package/src/cli/commands/projects.ts +49 -0
  163. package/src/cli/commands/queue.ts +70 -0
  164. package/src/cli/commands/recovery-run.ts +13 -0
  165. package/src/cli/commands/recovery.ts +130 -0
  166. package/src/cli/commands/release.ts +23 -0
  167. package/src/cli/commands/releases.ts +9 -0
  168. package/src/cli/commands/remember.ts +6 -0
  169. package/src/cli/commands/report.ts +27 -0
  170. package/src/cli/commands/research.ts +53 -0
  171. package/src/cli/commands/reset.ts +89 -0
  172. package/src/cli/commands/restart.ts +5 -0
  173. package/src/cli/commands/results.ts +31 -0
  174. package/src/cli/commands/resume.ts +5 -0
  175. package/src/cli/commands/review.ts +24 -0
  176. package/src/cli/commands/roadmap.ts +21 -0
  177. package/src/cli/commands/role.ts +34 -0
  178. package/src/cli/commands/roles.ts +30 -0
  179. package/src/cli/commands/room.ts +14 -0
  180. package/src/cli/commands/roster.ts +48 -0
  181. package/src/cli/commands/route.ts +9 -0
  182. package/src/cli/commands/say.ts +21 -0
  183. package/src/cli/commands/schedule.ts +17 -0
  184. package/src/cli/commands/sdlc.ts +321 -0
  185. package/src/cli/commands/settings.ts +148 -0
  186. package/src/cli/commands/setup.ts +89 -0
  187. package/src/cli/commands/shared-refusals.ts +25 -0
  188. package/src/cli/commands/smoke.ts +44 -0
  189. package/src/cli/commands/source.ts +64 -0
  190. package/src/cli/commands/specs.ts +13 -0
  191. package/src/cli/commands/status.ts +28 -0
  192. package/src/cli/commands/stop.ts +17 -0
  193. package/src/cli/commands/structure.ts +60 -0
  194. package/src/cli/commands/study.ts +39 -0
  195. package/src/cli/commands/tail.ts +19 -0
  196. package/src/cli/commands/task.ts +114 -0
  197. package/src/cli/commands/title.ts +17 -0
  198. package/src/cli/commands/turns.ts +10 -0
  199. package/src/cli/commands/ui.ts +47 -0
  200. package/src/cli/commands/undo.ts +77 -0
  201. package/src/cli/commands/up.ts +39 -0
  202. package/src/cli/commands/upgrade.ts +5 -0
  203. package/src/cli/commands/usage.ts +33 -0
  204. package/src/cli/commands/version.ts +5 -0
  205. package/src/cli/commands/watch.ts +30 -0
  206. package/src/cli/commands/worktrees.ts +31 -0
  207. package/src/cli/console-state.ts +5 -138
  208. package/src/cli/console-versions.ts +1 -1
  209. package/src/cli/help.ts +37 -15
  210. package/src/cli/identity.ts +23 -4
  211. package/src/cli/launch-check.ts +1 -2
  212. package/src/cli/launch.ts +13 -82
  213. package/src/cli/light-dispatch.ts +29 -0
  214. package/src/cli/main.js +8 -1
  215. package/src/cli/main.ts +233 -2816
  216. package/src/cli/orca-probe.ts +119 -0
  217. package/src/cli/output.ts +31 -2
  218. package/src/cli/preview.ts +10 -5
  219. package/src/cli/recovery-version-preflight.ts +28 -9
  220. package/src/cli/replace-process.ts +22 -0
  221. package/src/cli/report-layout.ts +142 -0
  222. package/src/cli/roadmap-usage.ts +16 -0
  223. package/src/cli/roadmap.ts +3 -16
  224. package/src/cli/sdlc-doctor.ts +27 -0
  225. package/src/cli/sdlc-output.ts +55 -1
  226. package/src/cli/setup-homes.ts +1 -1
  227. package/src/cli/start-agents-run.ts +1 -1
  228. package/src/cli/statusline-tee.ts +25 -4
  229. package/src/cli/terminal-recovery.ts +53 -10
  230. package/src/cli/upgrade-interactive.ts +1 -0
  231. package/src/cli/upgrade-runtime.ts +11 -0
  232. package/src/cli/upgrade.ts +4 -15
  233. package/src/hub/accounts.ts +148 -0
  234. package/src/hub/addons.ts +20 -0
  235. package/src/hub/agent-drift.ts +2 -1
  236. package/src/hub/budget-projection.ts +39 -7
  237. package/src/hub/budget.ts +231 -16
  238. package/src/hub/channel-project.ts +3 -3
  239. package/src/hub/conductor-peer.ts +24 -0
  240. package/src/hub/conductor.ts +2 -21
  241. package/src/hub/config-apply.ts +24 -13
  242. package/src/hub/config-edit.ts +1 -1
  243. package/src/hub/config-tier.ts +2 -0
  244. package/src/hub/config.ts +31 -14
  245. package/src/hub/control-client.ts +48 -0
  246. package/src/hub/daemon.ts +421 -61
  247. package/src/hub/events.ts +3 -0
  248. package/src/hub/home-tag.ts +12 -0
  249. package/src/hub/host.ts +217 -0
  250. package/src/hub/hub-tools.ts +2 -1
  251. package/src/hub/instance-budget.ts +2 -2
  252. package/src/hub/instance-config.ts +15 -126
  253. package/src/hub/instances.ts +22 -6
  254. package/src/hub/instruction-receipt.ts +2 -2
  255. package/src/hub/kimi-usage.ts +38 -11
  256. package/src/hub/lifecycle.ts +86 -4
  257. package/src/hub/mcp-bridge-core.ts +98 -0
  258. package/src/hub/mcp-channel-push.ts +20 -0
  259. package/src/hub/mcp-endpoint-serve.ts +178 -0
  260. package/src/hub/mcp-endpoint.ts +226 -0
  261. package/src/hub/mcp-tool-call.ts +181 -0
  262. package/src/hub/operational-settings.ts +2 -0
  263. package/src/hub/orca-env.ts +6 -0
  264. package/src/hub/orca-state.ts +84 -0
  265. package/src/hub/peers.ts +5 -1
  266. package/src/hub/permission-mode.ts +2 -1
  267. package/src/hub/project.ts +20 -0
  268. package/src/hub/protocol-window.ts +58 -0
  269. package/src/hub/quota-origin.ts +20 -0
  270. package/src/hub/registry.ts +36 -2
  271. package/src/hub/report.ts +1 -1
  272. package/src/hub/research.ts +1 -1
  273. package/src/hub/review-brief.ts +47 -2
  274. package/src/hub/roster.ts +6 -3
  275. package/src/hub/routing.ts +9 -2
  276. package/src/hub/sdlc-check.ts +205 -0
  277. package/src/hub/sdlc-sync.ts +146 -0
  278. package/src/hub/sdlc.ts +33 -4
  279. package/src/hub/settings.ts +7 -4
  280. package/src/hub/start-agents.ts +1 -1
  281. package/src/hub/start-mode.ts +11 -4
  282. package/src/hub/structure-budget.ts +131 -0
  283. package/src/hub/structure-scan.ts +149 -0
  284. package/src/hub/tasks-experiment.ts +455 -0
  285. package/src/hub/tasks-guidance.ts +606 -0
  286. package/src/hub/tasks-roadmap-plan.ts +419 -0
  287. package/src/hub/tasks-roadmap.ts +491 -0
  288. package/src/hub/tasks-study.ts +661 -0
  289. package/src/hub/tasks-survey.ts +192 -0
  290. package/src/hub/tasks.ts +319 -2548
  291. package/src/hub/terminal-open.ts +5 -3
  292. package/src/hub/tooling.ts +3 -19
  293. package/src/hub/usage-rollup.ts +9 -3
  294. package/src/local/tools.ts +5 -0
  295. package/src/ui/index.html +1 -1
  296. package/src/ui/needs.ts +17 -5
  297. package/src/ui/peer-palette.ts +2 -4
  298. package/templates/presets/agents.json +60 -0
  299. package/templates/presets/confirmation-matrix.json +8 -8
@@ -0,0 +1,102 @@
1
+ import { terminalText } from "../console-state.ts";
2
+ import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
3
+ import { resolve } from "node:path";
4
+ import { guidanceProbeUsage } from "../help.ts";
5
+ import type { CommandContext } from "../command-context.ts";
6
+
7
+ export async function run(context: CommandContext) {
8
+ const { args, connect, invokedFrom, liveTest } = context;
9
+ const fail: CommandContext["fail"] = context.fail;
10
+ const { parseGuidanceCommand, validateGuidancePageReply, validateGuidanceDiffReply, validateGuidanceReceipt, renderGuidance, renderGuidanceReceipt } = await import("../guidance.ts");
11
+ const { parseGuidanceVariantV1, GUIDANCE_RECORD_MAX_BYTES } = await import("../../hub/guidance-variants.ts");
12
+ const { parseGuidanceProbeSubcommand, parseGuidanceProbeRegistration, GUIDANCE_PROBE_REGISTRATION_BYTES,
13
+ parseGuidanceProbePublicReceipt, parseGuidanceProbePublicStatus, parseGuidanceProbeReceiptExport, GUIDANCE_PROBE_LIVE_LIMITS, GUIDANCE_PROBE_STOP_TIMEOUT_MS } = await import("../../hub/guidance-probes.ts");
14
+ const { guidanceProbeStatusLines } = await import("../../ui/guidance-view.ts");
15
+ let probeCommand;
16
+ try { probeCommand = parseGuidanceProbeSubcommand(args); } catch { return fail(guidanceProbeUsage(args)); }
17
+ if (probeCommand) {
18
+ if (liveTest) return fail("live-test cannot perform guidance probe operations as the person; use a current person or configured conductor session");
19
+ let registration: ReturnType<typeof parseGuidanceProbeRegistration> | undefined;
20
+ if (probeCommand.op === "register") {
21
+ try {
22
+ const fd = openSync(resolve(invokedFrom, probeCommand.file), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
23
+ try {
24
+ if (!fstatSync(fd).isFile()) return fail("the guidance probe file must be a bounded regular JSON file");
25
+ const bytes = Buffer.alloc(GUIDANCE_PROBE_REGISTRATION_BYTES + 1); let got = 0;
26
+ while (got < bytes.length) { const read = readSync(fd, bytes, got, bytes.length - got, null); if (!read) break; got += read; }
27
+ if (got > GUIDANCE_PROBE_REGISTRATION_BYTES) return fail("the guidance probe registration exceeds its derived envelope bound");
28
+ registration = parseGuidanceProbeRegistration(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, got))));
29
+ if (!registration) return fail("invalid guidance probe registration; retain its complete bounded manifest and snapshots without trimming");
30
+ } finally { closeSync(fd); }
31
+ } catch { return fail("cannot read a valid bounded guidance probe registration; check its closed V1 manifest and snapshots"); }
32
+ }
33
+ const hub = await connect();
34
+ try {
35
+ if (!hub.features.includes("guidance_probes")) return fail("running hub lacks guidance_probes; upgrade and restart the hub, then retry ahub guidance");
36
+ if (probeCommand.op === "receipts" && !hub.features.includes("guidance_probe_receipts")) return fail("running hub lacks guidance_probe_receipts; upgrade and restart the hub, then retry ahub guidance probe receipts");
37
+ const request = probeCommand.op === "register" ? { t: "guidance_probe_register", registration: registration! }
38
+ : probeCommand.op === "start" ? { t: "guidance_probe_start", id: probeCommand.id, revision: probeCommand.revision, ...(probeCommand.variantId ? { variantId: probeCommand.variantId } : {}) }
39
+ : probeCommand.op === "cancel" ? { t: "guidance_probe_cancel", id: probeCommand.id, revision: probeCommand.revision }
40
+ : probeCommand.op === "receipts" ? { t: "guidance_probe_receipts", id: probeCommand.id }
41
+ : { t: "guidance_probe_show", id: probeCommand.id };
42
+ const result = await hub.request(request, probeCommand.op === "start" ? GUIDANCE_PROBE_LIVE_LIMITS.elapsedMs + GUIDANCE_PROBE_STOP_TIMEOUT_MS : undefined);
43
+ if (result.ok !== true) {
44
+ const detail = terminalText(result.error ?? "guidance probe outcome is unconfirmed").replace(/[\r\n]+/g, " ").slice(0, 512);
45
+ const nextStep = probeCommand.op === "register" ? "" : `; inspect ahub guidance probe show --id ${probeCommand.id} before any explicit retry`;
46
+ return fail(`${detail}${nextStep}`);
47
+ }
48
+ if (probeCommand.op === "receipts") {
49
+ const exported = parseGuidanceProbeReceiptExport(result.receipts);
50
+ if (!exported) return fail("guidance probe receipts are malformed or fail their digest check; inspect retained probe state before relying on them");
51
+ if (args.includes("--json")) console.log(JSON.stringify(exported, null, 2));
52
+ else for (const line of guidanceProbeStatusLines(exported)) console.log(terminalText(line));
53
+ } else if (probeCommand.op === "show") {
54
+ const status = parseGuidanceProbePublicStatus(result.status);
55
+ if (!status) return fail("guidance probe status is malformed; refresh its id and current task context");
56
+ if (args.includes("--json")) console.log(JSON.stringify(status, null, 2));
57
+ else console.log(`guidance probe ${status.id}: ${status.state}; revision ${status.revision}; evidence ${status.evidence}; workers ${status.counters.workerAttempts}; editors ${status.counters.editorAttempts}; model calls ${status.counters.modelCalls}; tool calls ${status.counters.toolCalls}; token usage ${status.counters.usageUnknown || status.counters.modelCalls === 0 ? "unknown" : status.counters.tokensObservedKnown}; cancelled ${status.cancelRequested ? "yes" : "no"}`);
58
+ } else {
59
+ const receipt = parseGuidanceProbePublicReceipt(result.receipt);
60
+ if (!receipt) return fail("guidance probe receipt is malformed; inspect retained probe state before retrying");
61
+ if (args.includes("--json")) console.log(JSON.stringify(receipt, null, 2));
62
+ else console.log(`guidance probe ${receipt.id}: ${receipt.state}; revision ${receipt.revision}; evidence ${receipt.evidence}${receipt.already ? "; already recorded" : ""}`);
63
+ }
64
+ } finally { hub.close(); }
65
+ return;
66
+ }
67
+ let command; try { command = parseGuidanceCommand(args); } catch (error) { return fail((error as Error).message); }
68
+ if (liveTest && (command.op === "create" || command.op === "withdraw")) return fail("live-test cannot write guidance declarations as the person; use the current task actor without --live-test");
69
+ let variant: ReturnType<typeof parseGuidanceVariantV1> | undefined;
70
+ if (command.op === "create") {
71
+ try {
72
+ const fd = openSync(resolve(invokedFrom, command.file), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
73
+ try {
74
+ if (!fstatSync(fd).isFile()) return fail("the guidance file must be a bounded regular JSON file");
75
+ const bytes = Buffer.alloc(GUIDANCE_RECORD_MAX_BYTES + 1); let got = 0;
76
+ while (got < bytes.length) { const read = readSync(fd, bytes, got, bytes.length - got, null); if (!read) break; got += read; }
77
+ if (got > GUIDANCE_RECORD_MAX_BYTES) return fail("the guidance file exceeds the 32 KiB input bound");
78
+ variant = parseGuidanceVariantV1(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, got))));
79
+ } finally { closeSync(fd); }
80
+ } catch { return fail("cannot read a valid bounded GuidanceVariantV1 file; check its shape, content id and protected role bytes"); }
81
+ }
82
+ const hub = await connect();
83
+ try {
84
+ if (!hub.features.includes("guidance_views")) return fail("running hub lacks guidance_views; upgrade and restart the hub and refresh the client plugin, then retry ahub guidance");
85
+ const { op, json, ...fields } = command;
86
+ const message = op === "create" ? { variant } : fields;
87
+ const result = await hub.request({ t: `guidance_${op}`, ...message });
88
+ if (result.ok !== true) return fail(`${terminalText(result.error ?? "guidance request is unconfirmed").replace(/[\r\n]+/g, " ").slice(0, 512)}; inspect ahub guidance list for the task before explicitly retrying a write`, result.refusalAudited === true, result.authorityRefused);
89
+ const options = { json };
90
+ if (command.op === "create" || command.op === "withdraw") {
91
+ let receipt;
92
+ try { receipt = validateGuidanceReceipt(result.receipt, command.op === "create" ? { id: variant!.id, taskId: variant!.taskId } : { id: command.id, taskId: command.taskId, status: "withdrawn" }); }
93
+ catch (error) { return fail((error as Error).message); }
94
+ if (options.json) console.log(JSON.stringify(receipt, null, 2)); else console.log(renderGuidanceReceipt(receipt).join("\n"));
95
+ } else {
96
+ let page;
97
+ try { page = command.op === "list" ? validateGuidancePageReply(result.guidance, command) : validateGuidanceDiffReply(result.guidance, command); }
98
+ catch { return fail("guidance reply is unavailable or malformed; refresh the task scope and upgrade the hub/client before retrying"); }
99
+ if (options.json) console.log(JSON.stringify(page, null, 2)); else console.log(renderGuidance(page).join("\n"));
100
+ }
101
+ } finally { hub.close(); }
102
+ }
@@ -0,0 +1,17 @@
1
+ import { isBuiltinAdapterKind } from "../../adapters/definitions/native-help.ts";
2
+ import { asciiMarkers, resolveColor, streamEnv } from "../console-state.ts";
3
+ import { renderHelp, configuredAcpHelp } from "../help.ts";
4
+ import type { CommandContext } from "../command-context.ts";
5
+
6
+ export function run(context: CommandContext) {
7
+ const { args, asksHelp, projectCatalog } = context;
8
+ const fail: CommandContext["fail"] = context.fail;
9
+ const color = resolveColor(undefined, streamEnv(!!process.stdout.isTTY), "ahub") === true;
10
+ const topic = asksHelp(args[0]) ? undefined : args[0];
11
+ const text = topic && !isBuiltinAdapterKind(topic) && projectCatalog.definitionOf(topic)?.start.daemonPort === "configured-print"
12
+ ? `ahub ${topic} [--mode headless] [--print-command | --dry-run]\nConfigured print runs one sandboxed process per public advisory request. Declare it in untracked .agenthub/config.local.json, restart the hub, then enable roster.${topic}.`
13
+ : topic && !isBuiltinAdapterKind(topic) && projectCatalog.definitionOf(topic)?.permission.genericAcp !== undefined
14
+ ? configuredAcpHelp(topic) : renderHelp(process.stdout.columns ?? 80, color, topic, undefined, asciiMarkers(process.env, args.includes("--ascii")));
15
+ if (!text) fail(`unknown command "${topic}"; run ahub help`);
16
+ console.log(text);
17
+ }
@@ -0,0 +1,45 @@
1
+ import { realPath } from "../../hub/project.ts";
2
+ import { launchHostedProject } from "../../hub/lifecycle.ts";
3
+ import { askHost, claimHostSocket, Host } from "../../hub/host.ts";
4
+ import { Registry } from "../../hub/registry.ts";
5
+ import { warnLine } from "../warn-line.ts";
6
+ import { resolve } from "node:path";
7
+ import type { CommandContext } from "../command-context.ts";
8
+
9
+ /** #1779 T3a: `ahub host --runtime <root> [--add-current] [--unattended]`, started by `ahub up` for a project with `host.shared`. Internal, like `ahub daemon`. */
10
+ export async function run({ args, registeredProject, unattendedEnv }: CommandContext) {
11
+ const at = args.indexOf("--runtime");
12
+ const runtimeArg = at >= 0 ? args[at + 1] : undefined;
13
+ if (!runtimeArg || runtimeArg.startsWith("--")) { warnLine("ahub host needs --runtime <root>"); process.exit(2); }
14
+ const runtimeRoot = realPath(resolve(runtimeArg));
15
+ // A host serves exactly the runtime it is running from: projects of another runtime belong to that runtime's host.
16
+ if (runtimeRoot !== realPath(resolve(import.meta.dir, "../../.."))) { warnLine("ahub host: --runtime is not the runtime this process runs from"); process.exit(2); }
17
+ const unattended = unattendedEnv || args.includes("--unattended");
18
+ const log = (line: string) => process.stderr.write(`${new Date().toISOString()} ${line}\n`);
19
+ const host = new Host({ log, launch: (project, options) => launchHostedProject(project, { ...options, env: process.env }) });
20
+ const registry = new Registry();
21
+ try {
22
+ const socket = await claimHostSocket(host, runtimeRoot, registry);
23
+ if (!socket.served) {
24
+ // Another host holds this runtime: join it while it answers, or fail closed and name the holder.
25
+ if (!args.includes("--add-current")) { warnLine(`another host (pid ${socket.holderPid}) already serves this runtime`, "stop it first, or add projects through ahub up"); process.exit(1); }
26
+ const project = registeredProject();
27
+ let reply = await askHost(runtimeRoot, { op: "add", project, unattended });
28
+ for (let attempt = 0; !reply && attempt < 20; attempt++) { await Bun.sleep(250); reply = await askHost(runtimeRoot, { op: "add", project, unattended }); }
29
+ if (!reply?.ok) {
30
+ warnLine(`the host of this runtime (pid ${socket.holderPid}) did not add the project: ${reply && !reply.ok ? reply.error : "no answer"}`, "wait for it to finish starting and run ahub up again, or stop that host");
31
+ process.exit(1);
32
+ }
33
+ return;
34
+ }
35
+ host.install();
36
+ try {
37
+ if (args.includes("--add-current")) await host.add(registeredProject(), unattended);
38
+ } catch (error) {
39
+ warnLine(`host could not start its first project: ${(error as Error).message}`);
40
+ await host.stopAll();
41
+ }
42
+ await host.done;
43
+ socket.served.close();
44
+ } finally { registry.close(); }
45
+ }
@@ -0,0 +1,121 @@
1
+ import { terminalText } from "../console-state.ts";
2
+ import { autonomyEnvironment } from "../autonomy.ts";
3
+ import { readAutonomyDefaults } from "../../hub/autonomy-defaults.ts";
4
+ import { inheritMachineAutonomy } from "../autonomy-projects.ts";
5
+ import { resolveProfile } from "../../hub/profiles.ts";
6
+ import { existsSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { hubHome } from "../../hub/project.ts";
9
+ import { Registry } from "../../hub/registry.ts";
10
+ import { autonomyInheritanceChange, init, initNextSteps, initResearchDefault, withInitResearch, initSettingRows, planInit } from "../init.ts";
11
+ import { discoverInitChecks, withInitChecks } from "../init-required-checks.ts";
12
+ import { INIT_USAGE, parseInitSettings } from "../init-settings.ts";
13
+ import { installedPeers } from "../init-roles.ts";
14
+ import { promptGate, runInitPrompt, settingLines, shadowOffered, type InitAnswers } from "../init-prompt.ts";
15
+ import { loadPacks } from "../../hub/packs.ts";
16
+ import { applyJcodeHome, installSkillsInJcodeHome, jcodeHomeBlocked, writeJcodeHomeConfig } from "../../adapters/definitions/native-cli-jcode-home-init.ts";
17
+ import { createInterface } from "node:readline/promises";
18
+ import { assertLifecycleAvailable } from "../../hub/recovery-store.ts";
19
+ import { inheritMachineStart } from "../start-agents-run.ts";
20
+ import { repoOf } from "../../hub/snapshots.ts";
21
+ import { errorLines } from "../error-format.ts";
22
+ import { asciiMarkers } from "../console-state.ts";
23
+ import type { CommandContext } from "../command-context.ts";
24
+
25
+ export async function run(context: CommandContext) {
26
+ const { args, cliDir, cwd, delegatedPeer, identity, initJcodeHome, liveTest, projectConfig, registeredProject, takeFlags, warn } = context;
27
+ const fail: CommandContext["fail"] = context.fail;
28
+ // #1065 T1: the settings flags come out first (a value flag takes the next word), then the older flags as before.
29
+ let settings: ReturnType<typeof parseInitSettings>;
30
+ try { settings = parseInitSettings(args); } catch (error) { return fail((error as Error).message); }
31
+ const flags = takeFlags(settings.rest.filter(arg => arg !== "--dry-run" && arg !== "--json" && arg !== "--shadow" && arg !== "--release-guard" && arg !== "--yes" && arg !== "--no-jcode-home"), ["--profile"], []);
32
+ if (flags.rest.length) fail(INIT_USAGE);
33
+ // A pack is a project file in .agenthub/roles/<name>.pack.json (#513a); init resolves the name and refuses an unknown one with the profiles and packs it knows.
34
+ let requestedProfile = flags.one["--profile"];
35
+ const newProject = !existsSync(join(cwd, ".agenthub/config.json"));
36
+ const initMachine = newProject ? readAutonomyDefaults(hubHome(), [cwd]) : undefined;
37
+ let request = settings.request, asked = Object.keys(request.values).length > 0;
38
+ let shadow = args.includes("--shadow"), releaseGuard = args.includes("--release-guard");
39
+ // #1065 T2: a person at a terminal on a new project, with no flag that sets anything and no --yes, is asked each setting (init-prompt.ts). Every other run, including a delegated peer, a live test and any run
40
+ // without a terminal, is never asked and gets defaults plus its flags. The gate is checked here, before any file is read or written, and --dry-run never prompts.
41
+ const flagGiven = asked || settings.request.autonomy !== undefined || requestedProfile !== undefined || shadow || releaseGuard;
42
+ if (promptGate({ newProject, flagGiven, yes: args.includes("--yes"), dryRun: args.includes("--dry-run"), stdinIsTTY: !!process.stdin.isTTY, stdoutIsTTY: !!process.stdout.isTTY, role: identity.role, delegated: !!delegatedPeer, liveTest })) {
43
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
44
+ // Ctrl-C closes the readline interface, which settles a pending question as null: the prompt ends with nothing written.
45
+ const interrupted = new Promise<null>(done => rl.once("close", () => done(null)));
46
+ const ask = (question: string): Promise<string | null> => Promise.race([rl.question(question).catch(() => null), interrupted]);
47
+ const machine = readAutonomyDefaults(hubHome(), [cwd]);
48
+ const preview = (answers: InitAnswers): string[] => {
49
+ const planned = withInitResearch(cwd, answers.request, initMachine?.researchEnabled);
50
+ const rows = initSettingRows(cwd, answers.profile, answers.shadow, answers.releaseGuard, planned);
51
+ const plan = planInit(cwd, answers.profile, answers.shadow, answers.releaseGuard, planned);
52
+ // The same autonomy-inheritance row `--dry-run` shows, from the one helper: a new project inherits the trusted machine preset after the writes unless the answer was off.
53
+ const inherit = autonomyInheritanceChange(cwd, machine.enabled, answers.request.autonomy);
54
+ if (inherit) plan.push(inherit);
55
+ return [...plan.map(change => `${change.action} ${change.path}: ${change.reason}${change.managedBlock ? ` (managed block: ${change.managedBlock})` : ""}`), ...settingLines(rows)];
56
+ };
57
+ let result: Awaited<ReturnType<typeof runInitPrompt>>;
58
+ try {
59
+ result = await runInitPrompt({ ask, print: line => console.log(terminalText(line)) },
60
+ { ...(machine.startAgents ? { machineAgents: machine.startAgents } : {}), machineResearch: initResearchDefault(cwd, initMachine?.researchEnabled), installedPeers: installedPeers(), packs: [...loadPacks(cwd).packs.keys()], discoverChecks: async () => (await discoverInitChecks(cwd)).names, shadowAvailable: shadowOffered(repoOf(cwd)) }, preview);
61
+ } finally { rl.close(); }
62
+ if (!result.ok) { if (result.reason === "refused") console.error(errorLines(`init: ${result.message}`, undefined, !!process.stderr.isTTY, asciiMarkers(process.env, process.argv.includes("--ascii"))).join("\n")); else warn(`init: ${result.reason === "interrupted" ? `interrupted: ${result.message}` : result.message}`); process.exitCode = result.reason === "refused" ? 1 : 0; return; }
63
+ requestedProfile = result.answers.profile; request = result.answers.request; asked = Object.keys(request.values).length > 0; shadow = result.answers.shadow; releaseGuard = result.answers.releaseGuard;
64
+ }
65
+ request = withInitResearch(cwd, request, initMachine?.researchEnabled);
66
+ try { request = await withInitChecks(cwd, request); } catch (error) { return fail((error as Error).message); }
67
+ // `--autonomy off` skips the machine inheritance on a new project; `inherit` is today's behaviour. Neither changes an existing project.
68
+ const inheritAutonomy = newProject && request.autonomy !== "off";
69
+ if (!newProject && request.autonomy !== undefined) warn("--autonomy applies to a new project only: this project already exists, so its autonomy settings are unchanged");
70
+ if (args.includes("--dry-run")) {
71
+ const plan = planInit(cwd, requestedProfile, shadow, releaseGuard, request);
72
+ const rows = initSettingRows(cwd, requestedProfile, shadow, releaseGuard, request);
73
+ const defaults = readAutonomyDefaults(hubHome(), [cwd]);
74
+ const inherit = inheritAutonomy ? autonomyInheritanceChange(cwd, defaults.enabled, request.autonomy) : undefined;
75
+ if (inherit) plan.push(inherit);
76
+ if (defaults.notice) warn(defaults.notice);
77
+ // #1627 A: the hub-owned jcode home is part of the plan, never written by a dry run.
78
+ const homePlan = args.includes("--no-jcode-home") ? undefined : initJcodeHome();
79
+ if (homePlan?.applicable) for (const line of homePlan.lines) plan.push({ action: homePlan.plan?.exists ? "modify" : "create", path: homePlan.plan!.home, reason: line.trim() });
80
+ // Without a settings flag the preview is the bare list of file rows, as it always was; with one it is { changes, settings }.
81
+ if (args.includes("--json")) return console.log(JSON.stringify(asked ? { changes: plan, settings: rows } : plan, null, 2));
82
+ const settingLines = rows.map(row => ` ${row.key}: ${row.from === undefined ? "(not set)" : JSON.stringify(row.from)} -> ${JSON.stringify(row.to)} (${row.file})`);
83
+ return console.log([...plan.map(change => `${change.action} ${change.path}: ${change.reason}${change.managedBlock ? ` (managed block: ${change.managedBlock})` : ""}`), ...settingLines].join("\n") || "already up to date");
84
+ }
85
+ assertLifecycleAvailable(cwd);
86
+ if (inheritAutonomy && delegatedPeer && readAutonomyDefaults(hubHome(), [cwd]).enabled) fail("machine autonomy inheritance is person-only; delegated live tests cannot apply it (ahub init --autonomy off skips it)");
87
+ let changed: string[], nextSteps: string[];
88
+ try { nextSteps = initNextSteps(cwd, request); changed = init(cwd, requestedProfile, shadow, releaseGuard, request); } catch (error) { return fail((error as Error).message); }
89
+ const project = registeredProject();
90
+ console.log(changed.length ? changed.map((p) => `${existsSync(p) ? "wrote" : "removed"} ${p}`).join("\n") : "already up to date");
91
+ // #1627 A: the hub-owned jcode home, after the project files exist. The person's own home is never written; a rerun reports drift only.
92
+ if (!args.includes("--no-jcode-home")) {
93
+ const homeInit = initJcodeHome();
94
+ if (homeInit.applicable && homeInit.plan) {
95
+ for (const line of homeInit.lines) console.log(terminalText(line));
96
+ if (homeInit.switchHome) { try { writeJcodeHomeConfig(cwd, homeInit.plan.home); console.log(`jcode_home now points at ${homeInit.plan.home}`); } catch (error) { warn((error as Error).message); process.exitCode = 1; } }
97
+ if (!homeInit.plan.exists) {
98
+ if (jcodeHomeBlocked(homeInit.plan.home)) warn(`jcode home ${homeInit.plan.home} is not a plain directory: nothing was created there`);
99
+ else {
100
+ try {
101
+ applyJcodeHome(homeInit.plan);
102
+ const installed = installSkillsInJcodeHome(join(cliDir, "..", "..", "plugins", "agent-hub", "skills"), homeInit.plan.home);
103
+ console.log(`wrote ${homeInit.plan.home}; hub skills: ${installed.filter(entry => entry.action === "install" || entry.action === "replace").length} installed`);
104
+ } catch (error) { warn(`jcode home was not fully set up: ${(error as Error).message}`); process.exitCode = 1; }
105
+ }
106
+ }
107
+ }
108
+ }
109
+ if (newProject) {
110
+ if (inheritAutonomy) {
111
+ const registry = new Registry();
112
+ try { for (const line of await inheritMachineAutonomy(project, hubHome(), autonomyEnvironment(process.env, !!process.stdin.isTTY), registry)) console.log(terminalText(line)); }
113
+ finally { registry.close(); }
114
+ }
115
+ // #608: the machine's default agent set, copied the same way (person-only: a delegated live test never inherits it). An explicit --agents is already in config.local.json, so it wins.
116
+ if (!delegatedPeer) { const roots = (() => { const r = new Registry(); try { return r.list().map(row => row.root); } finally { r.close(); } })(); for (const line of inheritMachineStart(cwd, hubHome(), [...roots, cwd])) console.log(terminalText(line)); }
117
+ }
118
+ const config = projectConfig(), examples = resolveProfile(config.profile, config.profile_overrides).example_checks;
119
+ if (examples.length) console.log(terminalText("Example checks (advisory):\n" + examples.map(example => "- " + example).join("\n")));
120
+ console.log(nextSteps.join("\n"));
121
+ }
@@ -0,0 +1,19 @@
1
+ import { INSTRUCTION_CONTROL_TIMEOUT_MS } from "../../hub/instructed-exact.ts";
2
+ import type { CommandContext } from "../command-context.ts";
3
+
4
+ export async function run(context: CommandContext) {
5
+ const { args, caller, connect, liveTest } = context;
6
+ const fail: CommandContext["fail"] = context.fail;
7
+ if (args[0] === "run") {
8
+ const session = process.env.CLAUDE_CODE_SESSION_ID;
9
+ if (caller.role !== "tools" || !session || liveTest) return fail("instruction requires the current managed Claude session");
10
+ const hub = await connect();
11
+ try {
12
+ const result = await hub.request({ t: "instruction_execute", session, ...(args.length > 1 ? { argv: args.slice(1) } : {}) }, INSTRUCTION_CONTROL_TIMEOUT_MS);
13
+ if (typeof result.output === "string") process.stdout.write(result.output);
14
+ if (result.ok !== true) fail(String(result.error ?? "instruction was not completed"));
15
+ } finally { hub.close(); }
16
+ return;
17
+ }
18
+ return fail("usage: ahub instructed run [<operation> <args...>]");
19
+ }
@@ -0,0 +1,15 @@
1
+ import { parseInstructionHook } from "../instruction-hook.ts";
2
+ import type { CommandContext } from "../command-context.ts";
3
+
4
+ export async function run({ args, caller, connect, liveTest }: CommandContext) {
5
+ if (args.length || caller.role !== "tools" || liveTest) return;
6
+ try {
7
+ const chunks: Buffer[] = []; let size = 0;
8
+ for await (const chunk of process.stdin) { const bytes = Buffer.from(chunk); size += bytes.length; if (size > 1024 * 1024) return; chunks.push(bytes); }
9
+ const input = Buffer.concat(chunks).toString("utf8");
10
+ const message = parseInstructionHook(input, process.env);
11
+ if (!message) return;
12
+ const hub = await connect(2000);
13
+ try { await hub.request(message, 2000); } finally { hub.close(); }
14
+ } catch { /* Hook failure never alters the native prompt or reveals it. */ }
15
+ }
@@ -0,0 +1,24 @@
1
+ import { renderIntake, renderIntakeChange } from "../intake-output.ts";
2
+ import type { CommandContext } from "../command-context.ts";
3
+
4
+ export async function run(context: CommandContext) {
5
+ const { args, outputOptions, showToolText, splitPresentation, taskOp } = context;
6
+ const fail: CommandContext["fail"] = context.fail;
7
+ // #334 (#511a): natural-language intake. Person only, except approve (#933: the configured conductor too, admitted and audited by the daemon).
8
+ // The request is a draft backlog card that nothing offers until `approve`; the hub, not this process, splits it.
9
+ const split = splitPresentation(args, { valueFlags: ["--source"] });
10
+ const present = outputOptions(split.flags); // before any request: an invalid --color must refuse before a mutation is sent
11
+ const usage = "usage: ahub intake \"<text>\" [--source <id>...] | approve <id> | discard <id> [--json] [--color=auto|always|never]";
12
+ const sources: string[] = [], words: string[] = [];
13
+ for (let i = 0; i < split.operands.length; i++) {
14
+ const arg = split.operands[i]!;
15
+ if (arg === "--source") { const id = split.operands[++i]; if (!id) return fail("--source needs a source id"); sources.push(id); } else words.push(arg);
16
+ }
17
+ const [sub, id] = words;
18
+ if ((sub === "approve" || sub === "discard") && words.length === 2 && !sources.length) {
19
+ if (!/^[1-9]\d*$/.test(id!)) return fail(usage);
20
+ return showToolText((data, _c, now, ascii) => renderIntakeChange(sub, data, present.columns, now, ascii), await taskOp(sub === "approve" ? "intake_approve" : "intake_discard", { id: Number(id) }), present);
21
+ }
22
+ if (words.length !== 1 || !words[0]!.trim()) return fail(usage);
23
+ return showToolText((data, _c, now, ascii) => renderIntake(data, present.columns, now, ascii), await taskOp("intake", { text: words[0], ...(sources.length ? { sources } : {}) }, false, undefined, 90_000), present);
24
+ }
@@ -0,0 +1,15 @@
1
+ import { stopProject } from "../../hub/lifecycle.ts";
2
+ import { renderLifecycleReceipt } from "../reset-output.ts";
3
+ import type { CommandContext } from "../command-context.ts";
4
+
5
+ export async function run(context: CommandContext) {
6
+ const { hubManifest, matchingProject, printOutput } = context;
7
+ const fail: CommandContext["fail"] = context.fail;
8
+ const project = matchingProject();
9
+ if (!project) {
10
+ if (!hubManifest()) return printOutput(renderLifecycleReceipt({ lines: ["hub is not running"] }), false);
11
+ fail("hub has no matching registration; use its matching CLI to stop it before upgrading");
12
+ }
13
+ await stopProject(project);
14
+ printOutput(renderLifecycleReceipt({ lines: ["hub stopped"] }), false);
15
+ }
@@ -0,0 +1,23 @@
1
+ import { renderLearnChange, renderLearnList } from "../learn-output.ts";
2
+ import type { CommandContext } from "../command-context.ts";
3
+
4
+ export async function run(context: CommandContext) {
5
+ const { args, outputOptions, showToolText, splitPresentation, taskOp } = context;
6
+ const fail: CommandContext["fail"] = context.fail;
7
+ // #514b: the person's verdict on a recurring-criterion candidate (#514a). Person only, end to end: `learn` is a `console` command for an agent shell (classifyPeerCommand has no entry for it, so the
8
+ // identity layer refuses it before this runs), and the daemon refuses any caller but the person again. `accept` writes ONE key (profile_overrides.review_checklist) to the machine-local
9
+ // config through the settings writer; nothing in a card's text is written.
10
+ const split = splitPresentation(args);
11
+ const present = outputOptions(split.flags); // before any request: an invalid --color must refuse before a mutation is sent
12
+ const usage = "usage: ahub learn list [--all] [--accepted] | accept <id> | reject <id> [--json] [--color=auto|always|never]";
13
+ const [sub, ...rest] = split.operands;
14
+ if (sub === "list" && rest.every(arg => arg === "--all" || arg === "--accepted")) {
15
+ const all = rest.includes("--all"), accepted = rest.includes("--accepted");
16
+ // #1642 T2: `--accepted` is the outcome view of the lines already accepted, so --all (the decided candidates) has nothing to add there.
17
+ if (all && accepted) return fail("usage: ahub learn list [--all] [--accepted] (pass one of them)");
18
+ return showToolText((data, _c, _now, ascii) => renderLearnList(data, present.columns, all, accepted, ascii), await taskOp("learn_list", { ...(all ? { all: true } : {}), ...(accepted ? { accepted: true } : {}) }), present);
19
+ }
20
+ const [id, ...extra] = rest;
21
+ if ((sub !== "accept" && sub !== "reject") || !id || extra.length || !/^[1-9]\d*$/.test(id)) return fail(usage);
22
+ return showToolText((data, _c, now, ascii) => renderLearnChange(sub, data, present.columns, now, ascii), await taskOp(sub === "accept" ? "learn_accept" : "learn_reject", { id: Number(id) }), present);
23
+ }
@@ -0,0 +1,30 @@
1
+ import { terminalText } from "../console-state.ts";
2
+ import type { CommandContext } from "../command-context.ts";
3
+
4
+ export async function run(context: CommandContext) {
5
+ const { args, connect, liveTest } = context;
6
+ const fail: CommandContext["fail"] = context.fail;
7
+ const { parseLineageCommand, renderExecutionLineage, validateLineageReply, validateLineageLink } = await import("../lineage.ts");
8
+ let command;
9
+ try { command = parseLineageCommand(args); } catch (error) { return fail((error as Error).message); }
10
+ if (liveTest && command.op === "link") return fail("live-test cannot register execution links; retry without --live-test as the task's authorized actor");
11
+ const hub = await connect();
12
+ try {
13
+ if (!hub.features.includes("execution_lineage")) return fail("running hub lacks execution_lineage support; upgrade and restart the hub, then retry ahub lineage");
14
+ const { op, json, ...message } = command;
15
+ const result = await hub.request({ t: op === "show" ? "lineage_show" : "lineage_link", ...message });
16
+ if (result.ok !== true) return fail(`${terminalText(result.error ?? "lineage request refused").replace(/[\r\n]+/g, " ").slice(0, 512)}; check task scope, current flow revision and source access before retrying ahub lineage`, result.refusalAudited === true, result.authorityRefused);
17
+ const options = { json };
18
+ if (op === "show") {
19
+ let lineage;
20
+ try { lineage = validateLineageReply(result.lineage); } catch (error) { return fail((error as Error).message); }
21
+ if (options.json) console.log(JSON.stringify(lineage, null, 2));
22
+ else console.log(renderExecutionLineage(lineage).join("\n"));
23
+ } else {
24
+ let link;
25
+ try { link = validateLineageLink(result.link, command); } catch (error) { return fail((error as Error).message); }
26
+ if (options.json) console.log(JSON.stringify(link, null, 2));
27
+ else console.log(`Declared execution metadata link ${link.already ? "already registered" : "registered"} for task #${link.taskId}; this does not attest to producer execution.`);
28
+ }
29
+ } finally { hub.close(); }
30
+ }
@@ -0,0 +1,21 @@
1
+ import { join } from "node:path";
2
+ import type { CommandContext } from "../command-context.ts";
3
+
4
+ export async function run(context: CommandContext) {
5
+ const { args, connect, exec, identity, operationalIncomplete, stateDir } = context;
6
+ const fail: CommandContext["fail"] = context.fail;
7
+ if (identity.role !== "tools") return exec("tail", [args.includes("-f") ? "-f" : "-n100", join(stateDir, "hub.log")]);
8
+ const hub=await connect();const pending:string[]=[];let ready=false,incompleteShown=false;
9
+ hub.onPush=message=>{if(message.t==="operational_log" && typeof message.line==="string"){if(message.complete===false && !incompleteShown){operationalIncomplete(message,"log");incompleteShown=true;}if(ready)console.log(message.line);else if(pending.length<100)pending.push(message.line);}};
10
+ try {
11
+ const result=await hub.request({t:"conductor_operational",op:"logs",follow:args.includes("-f")});
12
+ if(result.ok!==true)fail(String(result.error??"operational logs unavailable"),result.refusalAudited===true,result.authorityRefused);
13
+ for(const line of result.lines??[])console.log(line);
14
+ ready=true;for(const line of pending)console.log(line);
15
+ if(!incompleteShown){operationalIncomplete(result,"log");if(result.complete===false)incompleteShown=true;}
16
+ if(args.includes("-f"))await new Promise<void>(resolve=>{
17
+ const finish=()=>{process.off("SIGINT",finish);resolve();};
18
+ hub.onClose=finish;process.once("SIGINT",finish);
19
+ });
20
+ } finally {hub.close();}
21
+ }
@@ -0,0 +1,15 @@
1
+ import { loadConfig } from "../../hub/config.ts";
2
+ import { hubHome } from "../../hub/project.ts";
3
+ import { startManager } from "../../hub/manager.ts";
4
+ import { effectiveStartAgents, startProjectAgents } from "../start-agents-run.ts";
5
+ import type { CommandContext } from "../command-context.ts";
6
+
7
+ export async function run({ lifecycle }: CommandContext) {
8
+ // #608: the dashboard's "start" counts as the person's `ahub up`: the manager starts the project's default agent set after the hub is ready.
9
+ const manager = await startManager({ lifecycle, afterStart: async (project) => {
10
+ const chosen = effectiveStartAgents(project.root, loadConfig(project.root).start.agents, hubHome(), [project.root]);
11
+ return startProjectAgents(project, chosen.agents);
12
+ } });
13
+ for (const signal of ["SIGINT", "SIGTERM"] as const) process.on(signal, () => void manager.stop());
14
+ await manager.stopped;
15
+ }
@@ -0,0 +1,21 @@
1
+ import { memoryCommand } from "../memory.ts";
2
+ import { selectedMemoryProfile } from "../../hub/memory-profile.ts";
3
+ import { checkMemoryProfiles, formatMemoryProfileCheck } from "../../hub/memory-profile-check.ts";
4
+ import type { CommandContext } from "../command-context.ts";
5
+
6
+ export async function run(context: CommandContext) {
7
+ const { args, caller, cwd } = context;
8
+ const fail: CommandContext["fail"] = context.fail;
9
+ // #258: the hub's own memory on this machine; reads are anyone's, changes a person's.
10
+ if (args.filter(arg => arg !== "--json")[0] === "profile-check") {
11
+ if (args.some(arg => arg !== "profile-check" && arg !== "--json")) fail("usage: ahub memory profile-check [--json]");
12
+ let selected: ReturnType<typeof selectedMemoryProfile>;
13
+ try { selected = selectedMemoryProfile(); } catch (e) { return fail((e as Error).message); } // an inactive split names the resume remedy
14
+ const result = await checkMemoryProfiles(selected);
15
+ console.log(args.includes("--json") ? JSON.stringify(result, null, 2) : formatMemoryProfileCheck(result));
16
+ if (!result.ready) process.exitCode = 1;
17
+ return;
18
+ }
19
+ // #1522: an agent shell runs this as itself; its peer id, not the person, is what amem records for a change.
20
+ try { console.log(await memoryCommand(args, cwd, { person: caller.role === "console", ...(caller.role === "tools" ? { agent: caller.peer } : {}) })); } catch (e) { fail((e as Error).message); }
21
+ }
@@ -0,0 +1,25 @@
1
+ import { renderRuntimeModels } from "../output.ts";
2
+ import type { CommandContext } from "../command-context.ts";
3
+
4
+ export async function run(context: CommandContext) {
5
+ const { args, connect, printOutput } = context;
6
+ const fail: CommandContext["fail"] = context.fail;
7
+ const { parseModelCommand, projectModelStatus } = await import("../model.ts");
8
+ let command;
9
+ try { command = parseModelCommand(args); } catch (error) { return fail((error as Error).message); }
10
+ const hub = await connect();
11
+ try {
12
+ if (!hub.features.includes("model_overrides")) return fail("running hub lacks model_overrides support; upgrade and restart the hub, then retry ahub model list");
13
+ const { json, ...message } = command;
14
+ const result = await hub.request({ t: "model", ...message });
15
+ if (result.ok !== true) return fail(String(result.error ?? "model request refused; upgrade and restart the hub before retrying"), result.refusalAudited === true, result.authorityRefused);
16
+ if (command.op !== "list" && result.appliesFrom !== "next_turn") return fail("model change is unconfirmed; inspect ahub model list before retrying");
17
+ const values = command.op === "list" ? result.models : [result.model];
18
+ if (!Array.isArray(values) || values.length > 512) return fail("model reply is not a supported bounded row list; upgrade and restart the hub, then retry ahub model list");
19
+ const models = values.map(projectModelStatus);
20
+ if (models.some(row => row === null)) return fail("model reply invalid; upgrade and restart the hub, then retry ahub model list");
21
+ const options = { json };
22
+ if (options.json) console.log(JSON.stringify({ models }, null, 2));
23
+ else printOutput(renderRuntimeModels(models.filter((row): row is NonNullable<typeof row> => row !== null)), false);
24
+ } finally { hub.close(); }
25
+ }
@@ -0,0 +1,40 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join, resolve } from "node:path";
5
+ import { ensureMlx, inspectMlx, stopMlx } from "../../models/mlx.ts";
6
+ import { setupOllamaModel } from "../models-setup.ts";
7
+ import { renderModelsStatus } from "../output.ts";
8
+ import type { CommandContext } from "../command-context.ts";
9
+
10
+ export async function run(context: CommandContext) {
11
+ const { cwd, outputArguments, outputOptions, printOutput, projectConfig } = context;
12
+ const fail: CommandContext["fail"] = context.fail;
13
+ const action = outputArguments()[0] ?? "status";
14
+ const options = ["status", "start", "setup"].includes(action) ? outputOptions() : undefined;
15
+ const showStatus = (data: unknown) => options!.json ? console.log(JSON.stringify(data, null, 2)) : printOutput(renderModelsStatus(data, options!.columns, Date.now()), options!.color);
16
+ const configured = projectConfig().mlx;
17
+ if (configured.enabled === false) {
18
+ if (action === "status") return showStatus({ state: "disabled", enabled: false });
19
+ if (["setup", "start", "stop"].includes(action)) fail("MLX is disabled by mlx.enabled=false; models commands do not manage shared Ollama");
20
+ fail("usage: ahub models setup|status|start|stop");
21
+ }
22
+ const runtimeDir = configured.runtimeDir ? resolve(cwd, configured.runtimeDir) : join(homedir(), ".agenthub", "runtimes", "mlx");
23
+ const modelPath = configured.modelPath ? resolve(cwd, configured.modelPath) : join(homedir(), ".agenthub", "models", "qwen3-8b-mlx");
24
+ const mlxOptions = configured.provider === "ollama" ? configured : { ...configured, runtimeDir, modelPath };
25
+ if (action === "status") return showStatus(await inspectMlx(mlxOptions));
26
+ if (action === "start") { const handle = await ensureMlx(mlxOptions); return showStatus(handle.status()); }
27
+ if (action === "stop") { await stopMlx(mlxOptions); return console.log("MLX stopped"); }
28
+ if (action !== "setup") fail("usage: ahub models setup|status|start|stop");
29
+ if (configured.provider === "ollama") {
30
+ await setupOllamaModel(configured);
31
+ const handle = await ensureMlx(configured);
32
+ return showStatus(handle.status());
33
+ }
34
+ const python = join(runtimeDir, "bin", "python");
35
+ const run = (argv: string[]) => { const result = spawnSync(argv[0]!, argv.slice(1), { cwd, stdio: "inherit" }); if (result.status !== 0) fail(`models setup failed: ${argv.join(" ")}`); };
36
+ if (!existsSync(python)) run(["uv", "venv", "--python", "3.12", runtimeDir]);
37
+ run(["uv", "pip", "install", "--python", python, "mlx-lm==0.31.3"]);
38
+ run([python, "-c", `from huggingface_hub import snapshot_download; snapshot_download(repo_id='Qwen/Qwen3-8B-MLX-4bit', revision='383413e909f3bc5303ce195ebbdf0339c5a1a2a3', local_dir=${JSON.stringify(modelPath)}, token=False)`]);
39
+ console.log(`MLX runtime and pinned model prepared at ${runtimeDir}`);
40
+ }
@@ -0,0 +1,39 @@
1
+ import type { NativeCliDispatchEntry, NativeCliEntryContext } from "../../adapters/definitions/native-cli-entry-types.ts";
2
+ import type { CommandContext } from "../command-context.ts";
3
+
4
+ export async function runNative(commandContext: CommandContext, entry: NativeCliDispatchEntry): Promise<void> {
5
+ const { args, assertLifecycleAvailable, buildKimiTuiLaunch, buildLaunch, caller, childEnv,
6
+ claudeObservationHooks, cleanupClaudeSettings, cleanupStaleClaudeSettings, cliDir,
7
+ configureJcodeMcp, configureKimiMcp, connectLaunch, connectOnce, cwd, effectiveInstanceRoles, exec,
8
+ execWithEnv, launcherPreview, nativeLaunchEnv, nativeSelection, prepareTerminalLaunch,
9
+ processSignature, projectConfig, qwenSessionId, readControl, readInstanceRoleConfig,
10
+ recordClaudeLaunch, recordTerminalLaunch, recoveryLock, registerTerminalLaunch,
11
+ requireActiveInstance, requirePeerInstances, resolveInstanceExecutionCwd, runClaudeLaunch,
12
+ selectedInstance, startModeOf, stateDir, takeFlags, unattendedEnv } = commandContext;
13
+ const fail: CommandContext["fail"] = commandContext.fail;
14
+
15
+ // Preserve the original guard before native effects; previews remain read-only and precede this guard.
16
+ if (entry.lifecycleAdmission && !args.includes("--print-command") && !args.includes("--dry-run")) assertLifecycleAvailable(cwd);
17
+ const nativeConnect = async () => {
18
+ const hub = await connectLaunch();
19
+ try { if (selectedInstance) { requirePeerInstances(hub.features); requireActiveInstance((await hub.request({ t: "status" })).status, selectedInstance); } return hub; }
20
+ catch (error) { hub.close(); throw error; }
21
+ };
22
+ if (selectedInstance && !args.includes("--print-command") && !args.includes("--dry-run")) {
23
+ const hub = await nativeConnect(); hub.close();
24
+ }
25
+ const context: NativeCliEntryContext = { args, cwd, stateDir, cliDir, unattendedEnv, person: caller.role === "console", definition: entry.definition,
26
+ ...(selectedInstance ? { instance: selectedInstance } : {}), ...(nativeSelection.hubStarted ? { hubStarted: true as const } : {}),
27
+ projectConfig, connect: nativeConnect, connectOnce, fail,
28
+ exec: (bin, argv, tool) => exec(bin, argv, tool, context.executionCwd),
29
+ execWithEnv: (bin, argv, env, replace) => execWithEnv(bin, argv, env, selectedInstance ?? entry.command, context.executionCwd, replace === true), takeFlags,
30
+ helpers: { resolveExecutionCwd: peer => {
31
+ const current = readInstanceRoleConfig(cwd);
32
+ return resolveInstanceExecutionCwd(cwd, peer, current.instances, effectiveInstanceRoles(peer, current.instances, current.roles, current.catalog), current.catalog);
33
+ }, launcherPreview: (tool, raw, projectRoot, state, unattended) => launcherPreview(tool, raw, projectRoot, state, unattended, selectedInstance), readControl, recordTerminalLaunch, prepareTerminalLaunch, registerTerminalLaunch, recoveryLock, processSignature,
34
+ buildLaunch, claudeObservationHooks, recordClaudeLaunch, cleanupStaleClaudeSettings, cleanupClaudeSettings,
35
+ nativeLaunchEnv, runClaudeLaunch, childEnv, qwenSessionId, configureJcodeMcp, configureKimiMcp,
36
+ buildKimiTuiLaunch, startModeOf },
37
+ };
38
+ return entry.execute(context);
39
+ }
@@ -0,0 +1,5 @@
1
+ import type { CommandContext } from "../command-context.ts";
2
+
3
+ export function run({ hold }: CommandContext) {
4
+ return hold("pause");
5
+ }