@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
package/src/hub/events.ts CHANGED
@@ -90,6 +90,8 @@ export type HubEvent =
90
90
  | { type: "tooling"; peer: string; addons: import("./tooling.ts").Addon[] }
91
91
  /** #258: a task brief handed to its owner: how many hub-memory items (and fails among them) and supplemental items (legacy claudeMem field), never their text. New local-library records identify source amem. */
92
92
  | { type: "memory_brief"; source?: "amem"; peer: string; task: number; native: number; fails: number; claudeMem: number }
93
+ /** #1810: a paused account's work moved to a peer on another account: peer ids and account labels only, never a home. */
94
+ | { type: "budget_handoff"; from: string; to: string; fromLabel: string; toLabel: string; role: "owner" | "reviewer" }
93
95
  /** #1330: the session preface a peer was given: its size in bytes, the number of memory lines in it, and whether observed use reordered the long-term section. Numbers and a boolean only, never a line. */
94
96
  | { type: "preface"; peer: string; bytes: number; lines: number; ordered: boolean }
95
97
  | { type: "split"; task: number; where?: "routing" | "cohort"; verdict: "split" | "single" | "unknown"; single?: string; splitS?: number; singleS?: number; reason?: string; trace?: string[] }
@@ -128,6 +130,7 @@ export type HubEvent =
128
130
  * `by` is who ended or began the pause: the coordinator (`hub`) or the console user (`person`, an override).
129
131
  */
130
132
  | { type: "budget_pause"; peer: string; reason: string; window: string; resetsAt: number; by: "hub" | "person" }
133
+ | { type: "budget_renew"; peer: string; mode: "reset" | "switched"; by: "person" }
131
134
  | { type: "budget_resume"; peer: string; reason: string; window: string; resetsAt: number; by: "hub" | "person" }
132
135
  /** A window's reset, derived from two readings of one window id: `resetsAt` moved forward, or `used` fell by 0.5 or more. */
133
136
  | { type: "quota_reset"; peer: string; window: string; cause: "resets_at_moved" | "used_dropped"; resetsAt?: number; previousResetsAt?: number; used: number; previousUsed: number; measuredAt?: string };
@@ -0,0 +1,12 @@
1
+ import { createHash } from "node:crypto";
2
+ import { realPath } from "./project.ts";
3
+
4
+ /**
5
+ * A short tag of a home for a state file name (`claude-usage.<tag>.json`). A hash, so no path is in a file name, and equal for every spelling of one existing home (symlinks resolved).
6
+ * Kept in its own module: the statusline tee runs on every status redraw and may not import the adapter registry that `accounts.ts` reaches through `instances.ts`.
7
+ */
8
+ export const homeTag = (home: string): string => {
9
+ let path: string;
10
+ try { path = realPath(home); } catch { path = home; }
11
+ return createHash("sha256").update(path).digest("hex").slice(0, 16);
12
+ };
@@ -0,0 +1,217 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { chmodSync, existsSync, mkdirSync, rmSync } from "node:fs";
4
+ import { connect, createServer, type Server } from "node:net";
5
+ import { join } from "node:path";
6
+ import type { Project, Registry } from "./registry.ts";
7
+ import { hubHome } from "./project.ts";
8
+ import { processSignature } from "../pi/process-signature.ts";
9
+
10
+ /** #1779 T3a: one process that owns several project daemons of the same runtime. Off by default (`host.shared`). */
11
+
12
+ /** What a launched project gives the host: the daemon's stop and its end, and the registry claim to give back. */
13
+ export interface HostedDaemon { stop(): Promise<void>; stopped: Promise<unknown> }
14
+ export interface Launched { daemon: HostedDaemon; release(): void }
15
+ export type Launch = (project: Project, options: { unattended: boolean; hostId: string }) => Promise<Launched>;
16
+
17
+ export interface HostOptions {
18
+ launch: Launch;
19
+ log?: (line: string) => void;
20
+ /** Ends the process; a seam for tests. */
21
+ exit?: (code: number) => void;
22
+ /** The whole shutdown is bounded, as in `runProjectDaemon`; a project whose stop never settles escapes only through this deadline. */
23
+ deadlineMs?: number;
24
+ }
25
+
26
+ const HOST_SHUTDOWN_DEADLINE_MS = 15_000;
27
+ const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP", "SIGQUIT"] as const;
28
+
29
+ export class Host {
30
+ readonly id = randomUUID();
31
+ private readonly projects = new Map<string, { project: Project; launched: Launched; ended: Promise<void> }>();
32
+ private readonly attribution = new AsyncLocalStorage<string>();
33
+ private readonly log: (line: string) => void;
34
+ private readonly pending = new Set<string>();
35
+ private closing: Promise<void> | undefined;
36
+ private forced: ReturnType<typeof setTimeout> | undefined;
37
+ private everAdded = false;
38
+ private readonly finished: Promise<void>;
39
+ private finish!: () => void;
40
+ private removers: (() => void)[] = [];
41
+
42
+ constructor(private readonly options: HostOptions) {
43
+ this.log = options.log ?? (() => {});
44
+ this.finished = new Promise<void>(resolve => { this.finish = resolve; });
45
+ }
46
+
47
+ /** Resolves when the host has no project left after it had one, or after `stopAll`. */
48
+ get done(): Promise<void> { return this.finished; }
49
+ get ids(): string[] { return [...this.projects.keys()]; }
50
+ has(id: string): boolean { return this.projects.has(id); }
51
+
52
+ /** The project the running code belongs to, through timers and promises it started; undefined outside any project. */
53
+ currentProject(): string | undefined { return this.attribution.getStore(); }
54
+ /** Run `fn` as part of project `id`, so an uncaught error in what it starts is attributed to that project. */
55
+ within<T>(id: string, fn: () => T): T { return this.attribution.run(id, fn); }
56
+
57
+ async add(project: Project, unattended = false): Promise<void> {
58
+ if (this.closing) throw new Error("host is shutting down");
59
+ if (this.projects.has(project.id) || this.pending.has(project.id)) throw new Error("project already runs in this host");
60
+ this.pending.add(project.id); // reserve the id across the await
61
+ let launched: Launched;
62
+ try { launched = await this.within(project.id, () => this.options.launch(project, { unattended, hostId: this.id })); }
63
+ catch (error) { this.pending.delete(project.id); this.maybeFinish(); throw error; }
64
+ finally { this.pending.delete(project.id); }
65
+ this.everAdded = true;
66
+ const ended = Promise.resolve(launched.daemon.stopped).then(() => {}, () => {}).then(() => {
67
+ launched.release();
68
+ if (this.projects.get(project.id)?.launched === launched) this.projects.delete(project.id);
69
+ this.maybeFinish();
70
+ });
71
+ this.projects.set(project.id, { project, launched, ended });
72
+ }
73
+
74
+ /** Stop one project, leaving the others serving. Removes its listener, timers and children through the daemon's own stop. */
75
+ async stopProject(id: string): Promise<void> {
76
+ const row = this.projects.get(id);
77
+ if (!row) return;
78
+ try { await row.launched.daemon.stop(); } catch (error) { this.log(`project ${id} did not stop cleanly: ${(error as Error).message}`); }
79
+ await row.ended;
80
+ }
81
+
82
+ /** Stop every project in the order added, then end the host. The forced-exit timer applies to the whole shutdown. */
83
+ stopAll(): Promise<void> {
84
+ if (this.closing) return this.closing;
85
+ this.armForcedExit();
86
+ this.closing = (async () => {
87
+ for (const id of [...this.projects.keys()]) await this.stopProject(id);
88
+ this.uninstall();
89
+ if (this.forced) clearTimeout(this.forced);
90
+ this.finish();
91
+ })();
92
+ return this.closing;
93
+ }
94
+
95
+ private armForcedExit(): void {
96
+ if (this.forced) return;
97
+ const deadline = this.options.deadlineMs ?? HOST_SHUTDOWN_DEADLINE_MS;
98
+ this.forced = setTimeout(() => {
99
+ this.log(`host shutdown did not finish within ${deadline / 1000} s; exiting anyway`);
100
+ (this.options.exit ?? process.exit)(1);
101
+ }, deadline);
102
+ this.forced.unref();
103
+ }
104
+
105
+ private maybeFinish(): void {
106
+ if (this.everAdded && this.projects.size === 0 && this.pending.size === 0 && !this.closing) { this.uninstall(); this.finish(); }
107
+ }
108
+
109
+ /** An uncaught error: stops the project it belongs to, or, with no attribution, the host. */
110
+ async handleUncaught(error: unknown, kind = "uncaught exception"): Promise<void> {
111
+ const text = error instanceof Error ? error.message : String(error);
112
+ const id = this.currentProject();
113
+ if (id !== undefined && this.projects.has(id)) {
114
+ this.log(`${kind} in project ${id}; stopping that project only: ${text}`);
115
+ await this.stopProject(id);
116
+ return;
117
+ }
118
+ this.log(`${kind} outside any project; stopping the host: ${text}`);
119
+ await this.stopAll();
120
+ }
121
+
122
+ /** The process-wide hooks belong to the host: signals stop everything in order, errors are attributed. */
123
+ install(): void {
124
+ const stop = () => { void this.stopAll().catch(error => this.log(`shutdown incomplete: ${(error as Error).message}`)); };
125
+ for (const name of SIGNALS) { process.on(name, stop); this.removers.push(() => process.off(name, stop)); }
126
+ const uncaught = (error: unknown) => { void this.handleUncaught(error).catch(() => {}); };
127
+ const rejected = (error: unknown) => { void this.handleUncaught(error, "unhandled rejection").catch(() => {}); };
128
+ process.on("uncaughtException", uncaught); this.removers.push(() => process.off("uncaughtException", uncaught));
129
+ process.on("unhandledRejection", rejected); this.removers.push(() => process.off("unhandledRejection", rejected));
130
+ }
131
+
132
+ private uninstall(): void { for (const remove of this.removers.splice(0)) remove(); }
133
+ }
134
+
135
+ /** Where the host of a runtime listens: a socket in the owner-only hub home, named by a hash of the runtime root. */
136
+ export function hostSocketPath(runtimeRoot: string, home = hubHome()): string {
137
+ return join(home, "hosts", `${createHash("sha256").update(runtimeRoot).digest("hex").slice(0, 16)}.sock`);
138
+ }
139
+
140
+ export type HostRequest = { op: "ping" } | { op: "add"; project: Project; unattended?: boolean };
141
+ export type HostReply = { ok: true; hostId: string; ids?: string[] } | { ok: false; error: string };
142
+
143
+ /**
144
+ * Serve the host's requests on its socket. The directory is owner-only, so the file system is the authority. Call it only as the holder of the runtime's host claim
145
+ * (`claimHostSocket`): the holder is the only process that may remove a stale socket file, so no second starter can unlink a live host's socket.
146
+ */
147
+ export function serveHost(host: Host, runtimeRoot: string, home = hubHome(), admit: (project: Project) => Project = project => project): { path: string; server: Server; listening: Promise<void>; close(): void } {
148
+ const path = hostSocketPath(runtimeRoot, home);
149
+ mkdirSync(join(home, "hosts"), { recursive: true, mode: 0o700 });
150
+ rmSync(path, { force: true });
151
+ const server = createServer(socket => {
152
+ let buffer = "";
153
+ socket.on("error", () => {});
154
+ socket.on("data", chunk => {
155
+ buffer += chunk.toString("utf8");
156
+ if (buffer.length > 64 * 1024) { socket.destroy(); return; }
157
+ const end = buffer.indexOf("\n");
158
+ if (end < 0) return;
159
+ const line = buffer.slice(0, end); buffer = "";
160
+ void answer(host, line, admit).then(reply => socket.end(`${JSON.stringify(reply)}\n`));
161
+ });
162
+ });
163
+ const listening = new Promise<void>((resolve, reject) => {
164
+ server.once("error", reject);
165
+ server.listen(path, () => { try { chmodSync(path, 0o600); } catch { /* the owner-only directory still guards it */ } resolve(); });
166
+ });
167
+ return { path, server, listening, close() { server.close(); rmSync(path, { force: true }); } };
168
+ }
169
+
170
+ async function answer(host: Host, line: string, admit: (project: Project) => Project): Promise<HostReply> {
171
+ try {
172
+ const request = JSON.parse(line) as HostRequest;
173
+ if (request.op === "ping") return { ok: true, hostId: host.id, ids: host.ids };
174
+ if (request.op === "add") { await host.add(admit(request.project), request.unattended === true); return { ok: true, hostId: host.id }; }
175
+ return { ok: false, error: "unknown host request" };
176
+ } catch (error) { return { ok: false, error: (error as Error).message }; }
177
+ }
178
+
179
+ /** Ask the host of a runtime; undefined when none answers. */
180
+ export function askHost(runtimeRoot: string, request: HostRequest, home = hubHome(), timeoutMs = 3000): Promise<HostReply | undefined> {
181
+ const path = hostSocketPath(runtimeRoot, home);
182
+ if (!existsSync(path)) return Promise.resolve(undefined);
183
+ return new Promise(resolve => {
184
+ let buffer = "", settled = false;
185
+ const done = (value: HostReply | undefined) => { if (settled) return; settled = true; clearTimeout(timer); socket.destroy(); resolve(value); };
186
+ const socket = connect(path, () => socket.write(`${JSON.stringify(request)}\n`));
187
+ const timer = setTimeout(() => done(undefined), timeoutMs);
188
+ socket.on("error", () => done(undefined));
189
+ socket.on("data", chunk => {
190
+ buffer += chunk.toString("utf8");
191
+ const end = buffer.indexOf("\n");
192
+ if (end < 0) return;
193
+ try { done(JSON.parse(buffer.slice(0, end)) as HostReply); } catch { done(undefined); }
194
+ });
195
+ socket.on("close", () => done(undefined));
196
+ });
197
+ }
198
+
199
+ export type HostSocket = { served: { close(): void } } | { served?: undefined; holderPid: number };
200
+
201
+ /**
202
+ * One host per runtime root, claimed atomically in the registry. The winner serves; a loser gets the holder's pid and must join the host that answers or fail closed.
203
+ * A project the client names is admitted only as the registry holds it (same root and state directory), as `startProject` requires.
204
+ */
205
+ export async function claimHostSocket(host: Host, runtimeRoot: string, registry: Registry, home = hubHome()): Promise<HostSocket> {
206
+ const claim = registry.claimHost(runtimeRoot, host.id, process.pid, processSignature(process.pid));
207
+ if (!claim.claimed) return { holderPid: claim.holderPid };
208
+ const admit = (project: Project): Project => {
209
+ const row = registry.get(project.id);
210
+ if (!row || row.root !== project.root || row.stateDir !== project.stateDir) throw new Error("project registration changed; refresh before starting");
211
+ return row;
212
+ };
213
+ const server = serveHost(host, runtimeRoot, home, admit);
214
+ try { await server.listening; }
215
+ catch (error) { registry.releaseHost(runtimeRoot, host.id); throw error; }
216
+ return { served: { close() { server.close(); registry.releaseHost(runtimeRoot, host.id); } } };
217
+ }
@@ -1,3 +1,4 @@
1
+ import { defaultPeerRoles } from "../adapters/definitions/native-adapter-policy.ts";
1
2
  import { EXECUTION_REFERENCE_LIMITS } from "./execution-reference.ts";
2
3
  import { CHECKPOINT_FIELDS, CHECKPOINT_FIELDS_SENTENCE, CHECKPOINT_FIELD_MAX_LINES, CHECKPOINT_FIELD_MAX_LINE_CHARS, CHECKPOINT_HEADINGS } from "./checkpoint-fields.ts";
3
4
  import { MILESTONE_LIMITS, MILESTONE_STATES, MILESTONE_HORIZONS, MILESTONE_LINK_KINDS } from "./roadmap.ts";
@@ -7,7 +8,7 @@ import { redFirstSchema } from "./test-integrity.ts";
7
8
  import { SDLC_STAGES } from "./sdlc.ts";
8
9
  import { projectProfile, profileData, PROFILE_CLASS_NAMES, type ProfileName, type ProfileSelection } from "./profiles.ts";
9
10
  import { catalogSection, type CatalogRole } from "./roles.ts";
10
- import { CONDUCTOR_START_PEERS, conductorStartText, defaultPeerRoles } from "../adapters/registry.ts";
11
+ import { CONDUCTOR_START_PEERS, conductorStartText } from "../adapters/declaration-data.ts";
11
12
  // The hub's task tools, defined once: the MCP server (Claude plugin, Kimi, Codex) and the local worker both read this.
12
13
  import { NOTE_KINDS } from "./envelope.ts";
13
14
 
@@ -58,10 +58,10 @@ export function instanceBudgetHooks(base: BudgetHooks, members: BudgetAccountMem
58
58
  partialMoves.delete(key);
59
59
  return moved;
60
60
  },
61
- resumed(record) {
61
+ resumed(record, renewal) {
62
62
  const key = account(record.peer), peers = ids(record.peer), partial = partialMoves.get(key);
63
63
  const resumed: PauseRecord = partial ? { ...record, moved: mergeMoves(record.moved, partial) } : record;
64
- for (const member of peers) base.resumed(member === resumed.peer ? resumed : { ...resumed, peer: member });
64
+ for (const member of peers) base.resumed(member === resumed.peer ? resumed : { ...resumed, peer: member }, renewal);
65
65
  partialMoves.delete(key);
66
66
  },
67
67
  };
@@ -1,134 +1,23 @@
1
- import { readFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { createProjectAdapterCatalog, defaultPeerRoles, definitionOf, type ProjectAdapterCatalog, type AdapterDefinition } from "../adapters/registry.ts";
4
- import { readAdapterModuleDeclarations, type AdapterModuleDeclaration } from "../adapters/external-modules.ts";
5
- import { externalMetadataDefinitions, moduleArray, moduleDataObject, moduleText } from "../adapters/external-metadata.ts";
6
- import { readControl, stateDirFor } from "./control-client.ts";
7
- import { conductorPeer } from "./conductor.ts";
8
- import { configRefusal } from "./config-trust.ts";
9
- import { isPermissionMode } from "./permission-mode.ts";
10
- import { validateInstances, type InstancesConfig } from "./instances.ts";
1
+ import { createProjectDeclarationCatalog } from "../adapters/declaration-catalog.ts";
2
+ import { readInstanceConfigLayers, readInstanceConfigWithCatalog, readInstanceRoles, type InstanceConfigLayer, type InstanceRoleConfig } from "../adapters/declaration-data.ts";
3
+ import type { AdapterDefinition } from "../adapters/registry-types.ts";
4
+ export { INSTANCE_CONFIG_FILES, readInstanceConfigLayers, withoutInertInstancePolicy, type InstanceConfigLayer, type InstanceRoleConfig, type DeclaredExternalInstance } from "../adapters/declaration-data.ts";
11
5
 
12
- export const INSTANCE_CONFIG_FILES = ["config.json", "config.local.json"] as const;
13
- export interface InstanceConfigLayer { name: typeof INSTANCE_CONFIG_FILES[number]; raw: Record<string, unknown> }
14
-
15
- /** One source capture can feed declaration validation and the ordinary config loader. */
16
- export function readInstanceConfigLayers(cwd: string): InstanceConfigLayer[] {
17
- return INSTANCE_CONFIG_FILES.flatMap(name => {
18
- try { return [{ name, raw: JSON.parse(readFileSync(join(cwd, ".agenthub", name), "utf8")) as Record<string, unknown> }]; }
19
- catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
20
- });
21
- }
22
-
23
- /** Declaration authority is file provenance, never a suffix or a claim made by a native child. */
24
- export interface DeclaredExternalInstance {
25
- readonly id: string;
26
- readonly kind: string;
27
- readonly availability: "declared-unknown" | "refused";
28
- readonly refusalCode: "catalog-unavailable" | "module-refused" | "kind-unavailable";
29
- }
30
- export interface InstanceRoleConfig {
31
- adapter_modules?: readonly AdapterModuleDeclaration[];
32
- adapters?: Readonly<Record<string, import("../adapters/configured-acp.ts").ConfiguredAdapterConfig>>;
33
- instances?: InstancesConfig;
34
- /** Unresolved or refused module declarations, excluded from executable policy. */
35
- declaredExternalInstances?: readonly DeclaredExternalInstance[];
36
- catalog: ProjectAdapterCatalog;
37
- ignored: string[];
38
- }
39
- /** Keep valid dormant policy on disk, but never admit it through an unavailable module's identity. */
40
- export function withoutInertInstancePolicy(raw: Record<string, unknown>, rows: readonly DeclaredExternalInstance[] = []): Record<string, unknown> {
41
- if (!rows.length) return raw;
42
- const ids = new Set(rows.flatMap(row => [row.id, row.kind]));
43
- const result = { ...raw };
44
- for (const key of ["permission_modes", "peers"] as const) {
45
- if (raw[key] === undefined) continue;
46
- const block = moduleDataObject(raw[key]);
47
- result[key] = Object.fromEntries(Object.entries(block).filter(([id, value]) => {
48
- if (!ids.has(id)) return true;
49
- if (key === "permission_modes") {
50
- if (!isPermissionMode(value)) throw new Error(`permission_modes.${id}: invalid dormant mode`);
51
- } else {
52
- const settings = moduleDataObject(value);
53
- if (Object.keys(settings).some(field => field !== "start_mode") || settings.start_mode !== undefined && settings.start_mode !== "headless") throw new Error(`peers.${id}: invalid dormant headless setting`);
54
- }
55
- return false;
56
- }));
57
- }
58
- return result;
6
+ export function readInstanceConfig(cwd: string, layers: readonly InstanceConfigLayer[] = readInstanceConfigLayers(cwd), externalDefinitions?: readonly AdapterDefinition[]): InstanceRoleConfig {
7
+ const { createProjectAdapterCatalog } = require("../adapters/registry.ts") as typeof import("../adapters/registry.ts");
8
+ return readInstanceConfigWithCatalog(cwd, layers, externalDefinitions, createProjectAdapterCatalog);
59
9
  }
60
10
 
61
- export function readInstanceConfig(cwd: string, layers: readonly InstanceConfigLayer[] = readInstanceConfigLayers(cwd), externalDefinitions?: readonly AdapterDefinition[]): InstanceRoleConfig {
62
- const moduleConfig = readAdapterModuleDeclarations(cwd, layers);
63
- const ignored: string[] = [...moduleConfig.ignored];
64
- let adapters: Readonly<Record<string, import("../adapters/configured-acp.ts").ConfiguredAdapterConfig>> | undefined, rawInstances: unknown;
65
- for (const { name, raw } of layers) {
66
- const keys = ["adapters", "instances"].filter(key => raw[key] !== undefined);
67
- if (!keys.length) continue;
68
- const refusal = name !== "config.local.json" ? "declarations are machine-local config.local.json values" : configRefusal(cwd, name);
69
- if (refusal) { ignored.push(`${keys.join(", ")} in .agenthub/${name} ignored: ${refusal}`); continue; }
70
- if (raw.adapters !== undefined) adapters = raw.adapters as Readonly<Record<string, import("../adapters/configured-acp.ts").ConfiguredAdapterConfig>>;
71
- if (raw.instances !== undefined) rawInstances = raw.instances;
72
- }
73
- let external = externalDefinitions;
74
- if (external === undefined) {
75
- // Metadata discovery is optional: retained recovery receipts may name a project that no longer exists.
76
- let metadata;
77
- try { metadata = readControl(stateDirFor(cwd))?.externalAdapters; } catch { /* no running catalog available */ }
78
- external = externalMetadataDefinitions(metadata);
79
- }
80
- const catalog = createProjectAdapterCatalog(adapters, external);
81
- // A descriptor on disk is display evidence only. It cannot turn module kinds into executable
82
- // definitions or establish live policy. Only the daemon's explicit captured definitions can.
83
- const runtimeDefinitions = new Set(externalDefinitions?.filter(definition => typeof definition.start.create === "function"));
84
- const declaredExternalInstances: DeclaredExternalInstance[] = [];
85
- let executableInstances = rawInstances;
86
- if (moduleConfig.modules.length && rawInstances !== undefined) {
87
- const entries = moduleDataObject(rawInstances);
88
- if (Object.keys(entries).length > 64) throw new Error("instances: at most 64 extra instances are supported");
89
- const executable: Record<string, unknown> = Object.create(null);
90
- for (const [id, value] of Object.entries(entries)) {
91
- const row = moduleDataObject(value), kind = row.kind;
92
- const definition = typeof kind === "string" ? catalog.definitionOf(kind) : undefined;
93
- const inert = !definition || catalog.externalDefinitions.includes(definition) && !runtimeDefinitions.has(definition);
94
- if (!inert) { executable[id] = value; continue; }
95
- if (!/^[a-z][a-z0-9-]{0,31}$/.test(id) || typeof kind !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(kind)
96
- || !id.startsWith(`${kind}-`) || !/^[a-z0-9][a-z0-9-]*$/.test(id.slice(kind.length + 1))) throw new Error("instances: invalid unresolved module instance declaration");
97
- if (Object.keys(row).some(key => !["kind", "roles", "start_mode", "permission_mode", "worktree", "readOnly"].includes(key))) throw new Error("instances: unsupported external instance field");
98
- if (Object.hasOwn(row, "roles")) {
99
- const roles = moduleArray(row.roles, 3);
100
- if (roles.some(role => typeof role !== "string" || !["implementer", "verifier", "reviewer"].includes(role)) || new Set(roles).size !== roles.length) throw new Error("instances: unsupported external instance role");
101
- }
102
- if (Object.hasOwn(row, "start_mode") && row.start_mode !== "headless") throw new Error("instances: external instances require headless mode");
103
- if (Object.hasOwn(row, "readOnly") && typeof row.readOnly !== "boolean") throw new Error("instances: readOnly must be a boolean");
104
- if (Object.hasOwn(row, "permission_mode") && (typeof row.permission_mode !== "string" || !["ask", "ask-when-needed", "never-ask"].includes(row.permission_mode))) throw new Error("instances: unknown permission mode");
105
- if (row.readOnly === true && Object.hasOwn(row, "permission_mode")) throw new Error("instances: read-only instances cannot select a permission mode");
106
- if (Object.hasOwn(row, "worktree")) moduleText(row.worktree, 4096);
107
- declaredExternalInstances.push(Object.freeze(externalDefinitions === undefined
108
- ? { id, kind, availability: "declared-unknown", refusalCode: "catalog-unavailable" }
109
- : { id, kind, availability: "refused", refusalCode: "kind-unavailable" }));
110
- }
111
- executableInstances = executable;
112
- }
113
- const instances = validateInstances(executableInstances, catalog);
114
- return { ...(moduleConfig.modules.length ? { adapter_modules: moduleConfig.modules } : {}), ...(adapters !== undefined ? { adapters } : {}), ...(Object.keys(instances).length ? { instances } : {}), ...(declaredExternalInstances.length ? { declaredExternalInstances: Object.freeze(declaredExternalInstances) } : {}), catalog, ignored };
11
+ /** A CLI declaration lookup carries policy, with no external execution authority. */
12
+ export function readStartupInstanceConfig(cwd: string, layers: readonly InstanceConfigLayer[] = readInstanceConfigLayers(cwd)): InstanceRoleConfig {
13
+ return readInstanceConfigWithCatalog(cwd, layers, undefined, createProjectDeclarationCatalog);
115
14
  }
116
15
 
117
16
  /** Capture ordinary role policy and trusted instance declarations together, without loading daemon configuration. */
118
17
  export function readInstanceRoleConfig(cwd: string, layers: readonly InstanceConfigLayer[] = readInstanceConfigLayers(cwd)): InstanceRoleConfig & { roles: Record<string, string[]> } {
119
- const declarationConfig = readInstanceConfig(cwd, layers);
120
- const roles = defaultPeerRoles(false);
121
- for (const definition of declarationConfig.catalog.definitions) if (!definitionOf(definition.kind)) roles[definition.kind] = [...definition.roles];
122
- for (const name of INSTANCE_CONFIG_FILES) {
123
- const raw = layers.find(layer => layer.name === name)?.raw;
124
- if (raw?.roles !== undefined) {
125
- conductorPeer(raw.roles); // Preserve the ordinary loader's ids, role-list and conductor validation exactly.
126
- for (const [id, list] of Object.entries(raw.roles as Record<string, string[]>)) roles[id] = [...list];
127
- }
128
- }
129
- // Unresolved rows and display-only module definitions grant no roles through id or kind aliases.
130
- for (const row of declarationConfig.declaredExternalInstances ?? []) { delete roles[row.id]; delete roles[row.kind]; }
131
- for (const definition of declarationConfig.catalog.externalDefinitions) delete roles[definition.kind];
132
- conductorPeer(roles);
133
- return { ...declarationConfig, roles };
18
+ return readInstanceRoles(readInstanceConfig(cwd, layers), layers);
19
+ }
20
+
21
+ export function readStartupInstanceRoleConfig(cwd: string, layers: readonly InstanceConfigLayer[] = readInstanceConfigLayers(cwd)): InstanceRoleConfig & { roles: Record<string, string[]> } {
22
+ return readInstanceRoles(readStartupInstanceConfig(cwd, layers), layers);
134
23
  }
@@ -2,8 +2,10 @@ import { types } from "node:util";
2
2
  import { statSync } from "node:fs";
3
3
  import { dirname, isAbsolute, resolve, sep } from "node:path";
4
4
  import { canonicalPath, realPath } from "./project.ts";
5
- import { defaultPeerRoles, definitionOf, type AdapterDefinition, type StartForm, type ProjectAdapterCatalog } from "../adapters/registry.ts";
6
- import { isPermissionMode, type PermissionMode } from "./permission-mode.ts";
5
+ import { defaultPeerRoles } from "../adapters/definitions/native-adapter-policy.ts";
6
+ import { isBuiltinAdapterKind } from "../adapters/definitions/native-help.ts";
7
+ import type { AdapterDefinition, StartForm, ProjectAdapterCatalog } from "../adapters/registry-types.ts";
8
+ import { isPermissionMode, type PermissionMode } from "./permission-paths.ts";
7
9
  import { isReviewScope } from "./review-scope.ts";
8
10
  import { isNativeModelToken } from "../adapters/model-token.ts";
9
11
 
@@ -24,6 +26,8 @@ export interface InstanceConfig {
24
26
  provider?: string;
25
27
  model?: string;
26
28
  provider_profile?: string;
29
+ /** #1810: the declared account (a label from `accounts`) this instance runs under. Only a kind whose native home variable the hub handles takes it; checked against `accounts` at config load. */
30
+ account?: string;
27
31
  }
28
32
  const JCODE_FIELDS = ["jcode_home", "jcode_mcp_allow", "provider", "model", "provider_profile"] as const;
29
33
  /** At most this many extra Jcode instances per project (#685). */
@@ -88,7 +92,7 @@ function jcodeInstanceFields(entry: Record<string, PropertyDescriptor>, path: st
88
92
  * `realPath` (never `realpathSync`, which Bun fails on a backslash path), and for a home that does not exist yet the nearest existing
89
93
  * ancestor resolved the same way. Compared case-folded when the volume folds case, so a case-only alias is the same home.
90
94
  */
91
- function canonicalHome(home: string): { path: string; key: string; identity?: string } {
95
+ export function canonicalHome(home: string): { path: string; key: string; identity?: string } {
92
96
  let path: string;
93
97
  try { path = realPath(home); } catch { path = canonicalPath(home); }
94
98
  const stat = (target: string) => { try { return statSync(target); } catch { return undefined; } };
@@ -137,6 +141,11 @@ export function instanceDefinitionOf(id: string, declarations: InstancesConfig |
137
141
  /** Pure I2 validation; physical worktree and startup authority stay host-bound. */
138
142
  export function validateInstances(raw: unknown, catalog: ProjectAdapterCatalog): InstancesConfig {
139
143
  const resolve = catalog.definitionOf;
144
+ const supportsDeclaredHeadless = (definition: AdapterDefinition): boolean => {
145
+ const declared = catalog.declaredHeadlessFactory?.(definition);
146
+ return declared === undefined ? supportsHeadlessInstances(definition)
147
+ : declared && definition.instances?.mode === "headless" && definition.start.forms.includes("headless");
148
+ };
140
149
  const result: Record<string, InstanceConfig> = Object.create(null);
141
150
  if (raw === undefined) return Object.freeze(result);
142
151
  const declarations = fields(raw, "instances");
@@ -149,7 +158,9 @@ export function validateInstances(raw: unknown, catalog: ProjectAdapterCatalog):
149
158
  const jcodeFields = typeof declaredKind === "string" && resolve(declaredKind)?.instances?.nativeHome === true;
150
159
  // #844: a kind whose headless variant declares `instances.modelSelect` may name its model; no other kind but Jcode has the field.
151
160
  const modelSelect = typeof declaredKind === "string" && resolve(declaredKind)?.headlessVariant?.instances?.modelSelect === true;
152
- if (Object.keys(entry).some(key => !["kind", "roles", "start_mode", "permission_mode", "worktree", "review_mode", "readOnly", "review_scope", ...(jcodeFields ? JCODE_FIELDS : []), ...(modelSelect ? ["model"] : [])].includes(key))) return fail(path, "unsupported field");
161
+ // #1810: the kinds whose home variable the hub already handles (`session.configDirEnv`) may name a declared account.
162
+ const accountable = typeof declaredKind === "string" && resolve(declaredKind)?.session.configDirEnv !== undefined;
163
+ if (Object.keys(entry).some(key => !["kind", "roles", "start_mode", "permission_mode", "worktree", "review_mode", "readOnly", "review_scope", ...(jcodeFields ? JCODE_FIELDS : []), ...(modelSelect ? ["model"] : []), ...(accountable ? ["account"] : [])].includes(key))) return fail(path, "unsupported field");
153
164
  const kind: unknown = entry.kind?.value;
154
165
  if (typeof kind !== "string") return fail(`${path}.kind`, "must name a native kind");
155
166
  const definition = resolve(kind), prefix = `${kind}-`;
@@ -187,7 +198,7 @@ export function validateInstances(raw: unknown, catalog: ProjectAdapterCatalog):
187
198
  if (headlessWriter && entry.permission_mode && entry.permission_mode.value !== "ask" && entry.permission_mode.value !== "ask-when-needed") return fail(`${path}.permission_mode`, "a headless implementer permits only ask or ask-when-needed");
188
199
  const runtime = freshReviewer ? definition.reviewerVariant ?? definition : headlessWriter ? definition.headlessVariant! : definition;
189
200
  const unavailableReviewer = freshReviewer && !!(definition.reviewerVariant ?? definition).reviewer?.unavailable;
190
- if (!unavailableReviewer && runtime.instances?.mode !== "external" && !supportsHeadlessInstances(runtime)) return fail(`${path}.kind`, definition.reviewerVariant ? 'unsupported; this kind only declares headless reviewer instances with roles exactly ["reviewer"]' : "unsupported; explicit external instance policy or a headless instance policy with a headless factory is required");
201
+ if (!unavailableReviewer && runtime.instances?.mode !== "external" && !supportsDeclaredHeadless(runtime)) return fail(`${path}.kind`, definition.reviewerVariant ? 'unsupported; this kind only declares headless reviewer instances with roles exactly ["reviewer"]' : "unsupported; explicit external instance policy or a headless instance policy with a headless factory is required");
191
202
  if (declaredRoles.includes("planner") && definition.projection?.plannerEligible !== true) return fail(`${path}.roles`, "this kind cannot plan");
192
203
  if (external) {
193
204
  const declared = entry.roles ? roles(entry.roles.value, `${path}.roles`) : [];
@@ -222,6 +233,11 @@ export function validateInstances(raw: unknown, catalog: ProjectAdapterCatalog):
222
233
  if (++jcodeCount > MAX_JCODE_INSTANCES) return fail("instances", `at most ${MAX_JCODE_INSTANCES} extra Jcode instances are supported per project`);
223
234
  Object.assign(value, jcodeInstanceFields(entry, path));
224
235
  }
236
+ if (entry.account) {
237
+ const label: unknown = entry.account.value;
238
+ if (typeof label !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(label) || label === "default") return fail(`${path}.account`, "must name a declared account label (a lowercase word, not default)");
239
+ value.account = label;
240
+ }
225
241
  if (entry.model && modelSelect) {
226
242
  if (!headlessWriter) return fail(`${path}.model`, "only a headless implementer takes a model");
227
243
  const word: unknown = entry.model.value;
@@ -264,7 +280,7 @@ export function instanceCatalog(declarations: InstancesConfig | undefined, catal
264
280
  export function instancePeerIds(declarations: InstancesConfig | undefined, catalog: ProjectAdapterCatalog): string[] { return instanceCatalog(declarations, catalog).map(entry => entry.id); }
265
281
  export function instanceDefaultRoles(declarations: InstancesConfig | undefined, includeOptional: boolean, catalog: ProjectAdapterCatalog): Record<string, string[]> {
266
282
  const result = defaultPeerRoles(includeOptional);
267
- for (const definition of catalog.definitions) if (!definitionOf(definition.kind) && (includeOptional || !definition.optional)) result[definition.kind] = [...definition.roles];
283
+ for (const definition of catalog.definitions) if (!isBuiltinAdapterKind(definition.kind) && (includeOptional || !definition.optional)) result[definition.kind] = [...definition.roles];
268
284
  const instances = validateInstances(declarations, catalog);
269
285
  for (const [id, config] of Object.entries(instances)) result[id] = [...(config.roles ?? catalog.definitionOf(id, instances)!.roles)];
270
286
  return result;
@@ -1,10 +1,10 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
3
3
  import { isAbsolute, join } from "node:path";
4
+ import { INSTRUCTION_PROBED_VERSIONS } from "../adapters/compat.ts";
4
5
  import { openHubDatabase, type Database } from "./db-schema.ts";
5
6
  import { realPath } from "./project.ts";
6
7
 
7
- export const INSTRUCTION_PROBED_VERSIONS = ["2.1.328", "2.1.329"] as const;
8
8
  export const INSTRUCTION_PREFIX = "/agent-hub:ahub";
9
9
  export const MAX_PROMPT_BYTES = 16 * 1024;
10
10
  const MAX_TRANSCRIPT_TAIL = 1024 * 1024;
@@ -62,7 +62,7 @@ function commandRecord(raw: unknown, row: Row, now: number): { uuid: string; arg
62
62
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return;
63
63
  const record = raw as Record<string, any>, message = record.message;
64
64
  if (record.type !== "user" || (record.isMeta !== undefined && record.isMeta !== false) || record.isSidechain !== false || record.origin?.kind !== "human" || Object.hasOwn(record, "promptSource")
65
- || record.sessionId !== row.session || record.cwd !== row.cwd || !INSTRUCTION_PROBED_VERSIONS.includes(record.version as typeof INSTRUCTION_PROBED_VERSIONS[number]) || record.promptId !== row.prompt_id || !UUID.test(record.uuid ?? "") || !message || message.role !== "user" || typeof message.content !== "string") return;
65
+ || record.sessionId !== row.session || record.cwd !== row.cwd || !INSTRUCTION_PROBED_VERSIONS.includes(record.version) || record.promptId !== row.prompt_id || !UUID.test(record.uuid ?? "") || !message || message.role !== "user" || typeof message.content !== "string") return;
66
66
  if (typeof record.timestamp !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(record.timestamp)) return;
67
67
  const at = Date.parse(record.timestamp);
68
68
  if (!Number.isFinite(at) || at < row.created || at > now) return;