@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
@@ -1,14 +1,16 @@
1
+ import { NATIVE_ADAPTER_POLICY, NATIVE_FRESH_REVIEWER_FACTORY } from "./definitions/native-adapter-policy.ts";
1
2
  import { AGY_DEFINITION } from "./agy/definition.ts";
2
3
  import { AGY_REVIEWER_VARIANT } from "./definitions/reviewer-variants.ts";
4
+ import { compareNativeRank } from "./definitions/native-help.ts";
3
5
  import { builtinCliEntries } from "./definitions/native-cli-entry.ts";
4
6
  import { builtinPreview } from "./definitions/native-cli-preview.ts";
5
7
  import { DAEMON_PORTS } from "./definitions/native-factories.ts";
6
8
  export { DAEMON_PORTS };
7
9
  import { NATIVE_BUILTIN_DEFINITIONS_WITHOUT_QWEN } from "./definitions/builtin-metadata.ts";
8
10
  import { QWEN_DEFINITION } from "./definitions/qwen.ts";
9
- import { configuredAcpDefinitions } from "./configured-acp.ts";
11
+ import { configuredAcpDefinitions, declaredConfiguredFactory } from "./configured-acp.ts";
10
12
  import type { AdapterDefinition, KindMap, ProjectAdapterCatalog } from "./registry-types.ts";
11
- import { types } from "node:util";
13
+ import { catalogFromDefinitions, declaredKind, resolvedDefinition } from "./declaration-resolution.ts";
12
14
 
13
15
  export type * from "./registry-types.ts";
14
16
  import { ADAPTER_API } from "./adapter-api.ts";
@@ -50,10 +52,7 @@ export function deriveAdapterLists(definitions: readonly AdapterDefinition[]): A
50
52
  const ordered = (field: "roleRank" | "startRank" | "helpRank", eligible = (_definition: AdapterDefinition) => true) => definitions
51
53
  .map((definition, index) => ({ definition, index })).filter(({ definition }) => eligible(definition))
52
54
  .sort((left, right) => {
53
- const a = left.definition.projection?.[field], b = right.definition.projection?.[field];
54
- if (a === undefined) return b === undefined ? left.index - right.index : 1;
55
- if (b === undefined) return -1;
56
- return a - b || left.index - right.index;
55
+ return compareNativeRank(left.definition.projection?.[field], right.definition.projection?.[field]) || left.index - right.index;
57
56
  }).map(({ definition }) => definition.kind);
58
57
  const KNOWN_PEERS = definitions.filter(definition => !definition.optional).map(definition => definition.kind);
59
58
  const OPTIONAL_PEERS = definitions.filter(definition => definition.optional).map(definition => definition.kind);
@@ -87,53 +86,29 @@ export const QUOTA_HANDOFF_PLATFORMS: Readonly<Record<string, string>> = Object.
87
86
  ADAPTERS.flatMap(adapter => adapter.hooks?.recallPlatform ? [[adapter.kind, adapter.hooks.recallPlatform]] : []),
88
87
  ));
89
88
 
90
- /** Own enumerable data field of a plain object, never a caller accessor or an inherited value. */
91
- function ownField(value: unknown, key: string): unknown {
92
- if (!value || typeof value !== "object" || types.isProxy(value) || Array.isArray(value)
93
- || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) return undefined;
94
- const field = Object.getOwnPropertyDescriptor(value, key);
95
- return field && Object.hasOwn(field, "value") && field.enumerable ? field.value : undefined;
96
- }
97
- /** Declaration reads never execute caller accessors or inherit another project's mapping. */
98
- function declaredKind(id: string, instances: KindMap | undefined, catalog: ReadonlyMap<string, AdapterDefinition> = definitions): string | undefined {
99
- if (!instances || typeof instances !== "object" || types.isProxy(instances) || Array.isArray(instances)
100
- || ![Object.prototype, null].includes(Object.getPrototypeOf(instances))) return undefined;
101
- const field = Object.getOwnPropertyDescriptor(instances, id);
102
- if (!field || !Object.hasOwn(field, "value") || !field.enumerable) return undefined;
103
- const entry: unknown = field.value;
104
- if (!entry || typeof entry !== "object" || types.isProxy(entry) || Array.isArray(entry)
105
- || ![Object.prototype, null].includes(Object.getPrototypeOf(entry))) return undefined;
106
- const kind = Object.getOwnPropertyDescriptor(entry, "kind");
107
- if (!kind || !Object.hasOwn(kind, "value") || !kind.enumerable || typeof kind.value !== "string" || !catalog.has(kind.value)) return undefined;
108
- const prefix = `${kind.value}-`;
109
- return /^[a-z][a-z0-9-]{0,31}$/.test(id) && id.startsWith(prefix) && /^[a-z0-9][a-z0-9-]*$/.test(id.slice(prefix.length)) ? kind.value : undefined;
110
- }
111
89
  /** Legacy ids retain their identity. Extra instances resolve only through the explicit project map. */
112
90
  export function kindOf(id: string, instances?: KindMap): string | undefined {
113
- return definitions.has(id) ? id : typeof id === "string" ? declaredKind(id, instances) : undefined;
91
+ return definitions.has(id) ? id : typeof id === "string" ? declaredKind(id, instances, definitions) : undefined;
114
92
  }
115
93
  export function definitionOf(id: string, instances?: KindMap): AdapterDefinition | undefined {
116
94
  const kind = kindOf(id, instances);
117
95
  return resolvedDefinition(id, kind, instances, definitions);
118
96
  }
119
- function resolvedDefinition(id: string, kind: string | undefined, instances: KindMap | undefined, catalog: ReadonlyMap<string, AdapterDefinition>): AdapterDefinition | undefined {
120
- const definition = kind === undefined ? undefined : catalog.get(kind);
121
- // #223: only a declared extra (never the builtin id) with start_mode "headless" runs as the kind's reviewer variant.
122
- const declaration = ownField(instances, id), roles = ownField(declaration, "roles");
123
- const reviewerOnly = Array.isArray(roles) && !types.isProxy(roles) && roles.length === 1 && Object.getOwnPropertyDescriptor(roles, "0")?.value === "reviewer";
124
- const variant = definition?.reviewerVariant;
125
- const fresh = variant?.reviewer?.declaration === "automatic" || ownField(declaration, "review_mode") === "fresh";
126
- const headless = kind !== id && ownField(declaration, "start_mode") === "headless";
127
- if (variant && headless && reviewerOnly && fresh) return variant;
128
- const roleValues = Array.isArray(roles) && !types.isProxy(roles) && roles.length <= 4 ? Array.from({ length: roles.length }, (_, index) => Object.getOwnPropertyDescriptor(roles, String(index))?.value) : [];
129
- const writerRoles = roleValues.includes("implementer") && roleValues.every(role => role === "implementer" || role === "verifier");
130
- return headless && writerRoles && definition?.headlessVariant ? definition.headlessVariant : definition;
131
- }
132
97
  export function familyOf(id: string, instances?: KindMap): string | undefined {
133
98
  return definitionOf(id, instances)?.family;
134
99
  }
135
100
 
136
101
  /** Compile one captured, host-trusted declaration set; never register native policy globally. */
102
+ const builtinFactories = new Map<AdapterDefinition, boolean>();
103
+ for (const definition of ADAPTERS) {
104
+ const kind = definition.kind as keyof typeof NATIVE_ADAPTER_POLICY;
105
+ builtinFactories.set(definition, NATIVE_ADAPTER_POLICY[kind].headlessFactory);
106
+ if (definition.headlessVariant) builtinFactories.set(definition.headlessVariant, NATIVE_ADAPTER_POLICY.claudeImplementer.headlessFactory);
107
+ if (definition.reviewerVariant) builtinFactories.set(definition.reviewerVariant, kind === "claude"
108
+ ? NATIVE_ADAPTER_POLICY.claudeReviewer.headlessFactory
109
+ : NATIVE_FRESH_REVIEWER_FACTORY[kind as keyof typeof NATIVE_FRESH_REVIEWER_FACTORY]);
110
+ }
111
+
137
112
  export function createProjectAdapterCatalog(rawAdapters?: unknown, externalDefinitions: readonly AdapterDefinition[] = []): ProjectAdapterCatalog {
138
113
  const configured = configuredAcpDefinitions(rawAdapters, [...definitions.keys()]);
139
114
  for (const definition of configured) { assertDefinitionCoherence(definition); assertNativeCapabilityScope(definition); }
@@ -145,51 +120,15 @@ export function createProjectAdapterCatalog(rawAdapters?: unknown, externalDefin
145
120
  }
146
121
  const external = immutable([...externalDefinitions]);
147
122
  const entries = Object.freeze([...ADAPTERS, ...configured, ...external]);
148
- const catalog = new Map([...definitions, ...[...configured, ...external].map(definition => [definition.kind, definition] as const)]);
149
- const kindOf = (id: string, instances?: KindMap): string | undefined => catalog.has(id) ? id : typeof id === "string" ? declaredKind(id, instances, catalog) : undefined;
150
- const definitionOf = (id: string, instances?: KindMap): AdapterDefinition | undefined => resolvedDefinition(id, kindOf(id, instances), instances, catalog);
151
- return Object.freeze({ definitions: entries, externalDefinitions: external, kindOf, definitionOf,
152
- familyOf: (id: string, instances?: KindMap) => definitionOf(id, instances)?.family,
153
- isSupportedPeer: (id: unknown, instances?: KindMap): id is string => {
154
- if (typeof id !== "string") return false;
155
- const kind = kindOf(id, instances), runtime = kind === undefined ? undefined : catalog.get(kind), resolved = definitionOf(id, instances);
156
- return runtime !== undefined && resolved !== undefined && (kind === id || resolved === runtime || resolved.reviewer?.unavailable === undefined);
157
- },
158
- });
123
+ return catalogFromDefinitions(entries, external, definition => builtinFactories.get(definition) ?? declaredConfiguredFactory(definition));
159
124
  }
160
125
 
161
126
  /** Compatibility projection order is observable in default role maps and planner selection. */
162
127
 
163
128
 
164
- /** Callers own their role arrays, independent of immutable native policy. */
165
- export function defaultPeerRoles(includeOptional = false): Record<string, string[]> {
166
- return Object.fromEntries(ROLE_ORDER.filter(peer => includeOptional || !definitionOf(peer)!.optional)
167
- .map(peer => [peer, [...definitionOf(peer)!.roles]]));
168
- }
169
-
170
- /** Preserve the tool schema's legacy preferred order without spreading native names into tools. */
171
- const CONDUCTOR_START_PRIORITY = ["local", "kimi", "pi"] as const;
172
- export const CONDUCTOR_START_PEERS = [
173
- ...CONDUCTOR_START_PRIORITY,
174
- ...ADAPTERS.filter(adapter => !(CONDUCTOR_START_PRIORITY as readonly string[]).includes(adapter.kind)).map(adapter => adapter.kind),
175
- ];
129
+ export { defaultPeerRoles } from "./definitions/native-adapter-policy.ts";
176
130
 
177
- /**
178
- * The words a person reads about which kinds a conductor may start, derived from the definitions in registry order so a new kind is named without a text edit (#1408 R5).
179
- * `refusal` keeps the sentence the conductor always got, with the kinds read from `conductorStartable` and `optional`.
180
- */
181
- export function conductorStartText(): { peers: string; refusal: string; tuiPeers: string } {
182
- const startable = SUPPORTED_PEERS.filter(peer => definitionOf(peer)?.start.conductorStartable === true);
183
- const list = (names: readonly string[], joiner: string) => names.length < 2 ? names.join("") : `${names.slice(0, names.length - 1).join(", ")} ${joiner} ${names[names.length - 1]}`;
184
- const optional = (peer: string) => definitionOf(peer)?.optional === true;
185
- // A kind opens in a terminal when its person-set start mode is tui, and a kind whose own default form is a terminal one starts that way.
186
- const tui = startable.filter(peer => definitionOf(peer)!.start.defaultForm === "tui" && definitionOf(peer)!.start.forms.includes("tui"));
187
- return {
188
- peers: list(startable, "or"),
189
- refusal: `only ${list(startable.filter(peer => !optional(peer)), "and")}, plus the opt-in ${list(startable.filter(optional), "and")}, may be started by the conductor`,
190
- tuiPeers: list(tui, "and"),
191
- };
192
- }
131
+ export { CONDUCTOR_START_PEERS, conductorStartText } from "./declaration-catalog.ts";
193
132
 
194
133
  /** A missing definition retains external-id admission; Pi's legacy enabled switch controls its default only. */
195
134
  export function defaultRosterEnabled(peer: string, piEnabled: boolean): boolean {
@@ -294,7 +233,7 @@ export type SupportedPeer = typeof SUPPORTED_PEERS[number];
294
233
  export function isSupportedPeer(peer: unknown, instances?: KindMap): peer is string {
295
234
  if (typeof peer !== "string") return false;
296
235
  if (ADAPTERS.some(definition => definition.kind === peer)) return true;
297
- const kind = declaredKind(peer, instances);
236
+ const kind = declaredKind(peer, instances, definitions);
298
237
  const runtime = ADAPTERS.find(definition => definition.kind === kind), resolved = definitionOf(peer, instances);
299
238
  return runtime !== undefined && resolved !== undefined && (resolved === runtime || resolved.reviewer?.unavailable === undefined);
300
239
  }
@@ -162,13 +162,13 @@ export interface ReviewerPrintOptions {
162
162
  /** Host journal ACK before any usage-producing child is constructed; absent port refuses that launch. */
163
163
  usageIntent?(attempt: string, task: number): boolean;
164
164
  /** Proven native quota is account evidence, independent of whether this task later reroutes. */
165
- onQuota?(reading: NativeReviewerQuota, attempt: string, current: () => boolean): boolean;
165
+ onQuota?(reading: NativeReviewerQuota, attempt: string, current: () => boolean, turnStartedAt: number): boolean;
166
166
  /** Only after this attempt's owned group and watch have settled. Never grants task authority. */
167
167
  quotaSettled?(attempt: string): void;
168
168
  /** ACK after owned settlement and usage read; failed ACK retains the private profile for recovery. */
169
169
  usageSettled?(attempt: string, outcome: "complete" | "unknown", task: number): boolean;
170
170
  /** True confirms that the host re-offered the current review; void/false retains uncertainty. */
171
- onUnavailable?(failure: ReviewerFailure, current: () => boolean): boolean | void | Promise<boolean | void>;
171
+ onUnavailable?(failure: ReviewerFailure, current: () => boolean, turnStartedAt?: number): boolean | void | Promise<boolean | void>;
172
172
  onNoVerdict?(diagnostic: ReviewerNoVerdict, current: () => boolean): void;
173
173
  log?(line: string): void;
174
174
  taskMcp?(task: number, current: () => boolean): ReviewerMcpSession;
@@ -223,6 +223,16 @@ export class ReviewerPrintPeer extends BasePeer {
223
223
  private observerSessionIdValue: string | undefined;
224
224
  get isolationReceipt(): ReviewerIsolationReceipt | undefined { return this.receipt; }
225
225
  reviewObserverInputHeld(): boolean { return this.opts.reviewObserverHeld?.() ?? false; }
226
+
227
+ compareQuotaHome(): "unknown" | undefined {
228
+ return this.quotaLaunchInFlight() ? "unknown" : undefined;
229
+ }
230
+
231
+ /** An active attempt can still use a prior spawn environment, including during child cleanup. */
232
+ quotaLaunchInFlight(): boolean {
233
+ return this.activeDeliveryId !== undefined || this.preparation !== undefined
234
+ || this.child !== undefined || this.childCleanup !== undefined;
235
+ }
226
236
  /** The task whose review the running child was started for (R4: the hub records `fresh` for its verdict). */
227
237
  reviewing: number | undefined;
228
238
  /** Privacy-only identity for a fresh review profile; never part of resume or budget authority. */
@@ -259,6 +269,13 @@ export class ReviewerPrintPeer extends BasePeer {
259
269
  return this.reviewSeq;
260
270
  }
261
271
 
272
+ private readonly quotaFailureStarts = new WeakMap<ReviewerFailure, number>();
273
+
274
+ private rememberQuotaStart(failure: ReviewerFailure, turnStartedAt: number): ReviewerFailure {
275
+ if (failure.cause === "quota") this.quotaFailureStarts.set(failure, turnStartedAt);
276
+ return failure;
277
+ }
278
+
262
279
  constructor(id: string, private readonly opts: ReviewerPrintOptions) { super(id, opts.watchdogMs); }
263
280
 
264
281
  recoveryMetadata(): Record<string, unknown> { return { launch: { kind: "reviewer-print", peer: this.id } }; }
@@ -345,7 +362,7 @@ export class ReviewerPrintPeer extends BasePeer {
345
362
  if (env.private) { failure = { state: "needs_review", reason: "a private review is the person's, never a cloud reviewer's" }; break; }
346
363
  const since = Date.now();
347
364
  let result: { code: number | null; quota: boolean; quotaReadings?: readonly NativeReviewerQuota[]; trace: ReviewerTraceState };
348
- try { result = await this.review(env, task, generation); }
365
+ try { result = await this.review(env, task, generation, since); }
349
366
  catch (error) {
350
367
  if (generation !== this.generation) return;
351
368
  if (error instanceof ReviewerInputAdmissionError) {
@@ -391,9 +408,9 @@ export class ReviewerPrintPeer extends BasePeer {
391
408
  else this.opts.log?.(reviewerNoVerdictLine(this.id, diagnostic));
392
409
  } catch { this.opts.log?.(reviewerNoVerdictLine(this.id, { task, exitCode: result.code, reviewCalled: false }, undefined, true)); }
393
410
  const quotaMetadata = result.quotaReadings?.length ? { quota: result.quotaReadings } : {};
394
- if (target) reroute.push({ ...target, cause: result.quota ? "quota" : "no_verdict", ...quotaMetadata });
411
+ if (target) reroute.push(this.rememberQuotaStart({ ...target, cause: result.quota ? "quota" : "no_verdict", ...quotaMetadata }, since));
395
412
  if (result.quota) {
396
- reroute.push(...remainingFailures(batch, index + 1, "quota").map(failure => ({ ...failure, ...quotaMetadata })));
413
+ reroute.push(...remainingFailures(batch, index + 1, "quota").map(failure => this.rememberQuotaStart({ ...failure, ...quotaMetadata }, since)));
397
414
  batch.next = envs.length;
398
415
  break;
399
416
  }
@@ -419,7 +436,7 @@ export class ReviewerPrintPeer extends BasePeer {
419
436
  const identity = JSON.stringify([failed.task, failed.head, failed.flowRevision]);
420
437
  if (seen.has(identity)) continue;
421
438
  seen.add(identity);
422
- try { if (await this.opts.onUnavailable?.(failed, () => generation === this.generation) !== true) reoffered = false; }
439
+ try { if (await this.opts.onUnavailable?.(failed, () => generation === this.generation, this.quotaFailureStarts.get(failed)) !== true) reoffered = false; }
423
440
  catch { reoffered = false; this.opts.log?.(`[${this.id}] reviewer fallback could not be recorded; inspect the task`); }
424
441
  }
425
442
  return reoffered;
@@ -456,7 +473,7 @@ export class ReviewerPrintPeer extends BasePeer {
456
473
  if (this.opts.admit?.(env) === false) throw new ReviewerAdmissionError(this.opts.bindingCurrent?.(task, binding) === false ? "stale_binding" : "policy_changed");
457
474
  }
458
475
 
459
- private async review(env: Envelope, task: number, generation: number): Promise<{ code: number | null; quota: boolean; quotaReadings?: readonly NativeReviewerQuota[]; trace: ReviewerTraceState }> {
476
+ private async review(env: Envelope, task: number, generation: number, turnStartedAt: number): Promise<{ code: number | null; quota: boolean; quotaReadings?: readonly NativeReviewerQuota[]; trace: ReviewerTraceState }> {
460
477
  const revision=Number(env.refs?.reviewRevision);
461
478
  const binding: ReviewerReviewBinding=Object.freeze({head:env.refs?.commit,flowRevision:Number.isSafeInteger(revision)&&revision>0?revision:undefined});
462
479
  this.assertAdmission(env, task, binding);
@@ -539,13 +556,13 @@ export class ReviewerPrintPeer extends BasePeer {
539
556
  const observeQuota = (reading: NativeReviewerQuota) => {
540
557
  const key = JSON.stringify(reading);
541
558
  if (publishedQuota.has(key)) return;
542
- try { if (this.opts.onQuota?.(reading, quotaAttempt, () => generation === this.generation) === true) publishedQuota.add(key); }
559
+ try { if (this.opts.onQuota?.(reading, quotaAttempt, () => generation === this.generation, turnStartedAt) === true) publishedQuota.add(key); }
543
560
  catch { /* Retain the proven quota in the batch even if its immediate account write could not commit. */ }
544
561
  };
545
562
  const rememberQuota = () => {
546
563
  const batch = this.batch, target = batch?.targets[batch.next];
547
564
  if (!batch || generation !== this.generation || target?.task !== task) return;
548
- const failure: ReviewerFailure = { ...target, cause: "quota", ...(quotaReadings.size ? { quota: [...quotaReadings.values()] } : {}) };
565
+ const failure = this.rememberQuotaStart({ ...target, cause: "quota", ...(quotaReadings.size ? { quota: [...quotaReadings.values()] } : {}) }, turnStartedAt);
549
566
  const prior = batch.failures.findIndex(row => row.task === target.task && row.head === target.head && row.flowRevision === target.flowRevision && row.cause === "quota");
550
567
  if (prior < 0) batch.failures.push(failure); else batch.failures[prior] = failure;
551
568
  };
@@ -1,4 +1,5 @@
1
- import { SUPPORTED_PEERS, definitionOf, type ProjectAdapterCatalog } from "./registry.ts";
1
+ import { DECLARATION_SUPPORTED_PEERS as SUPPORTED_PEERS, builtinDeclarationOf as definitionOf } from "./declaration-catalog.ts";
2
+ import type { ProjectAdapterCatalog } from "./registry-types.ts";
2
3
  import type { StartMode } from "../hub/start-mode.ts";
3
4
 
4
5
  /**
@@ -0,0 +1,72 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { accountKinds, MAX_ACCOUNTS_PER_KIND } from "../hub/accounts.ts";
3
+ import { childEnv } from "../hub/child-process.ts";
4
+ import { warnLine } from "./warn-line.ts";
5
+ import { withoutOrcaEnv } from "../hub/orca-env.ts";
6
+
7
+ /**
8
+ * #1811 T4: `ahub accounts import --from orca` (person only, src/cli/identity.ts). One read of `orca account list --json`, then a printed `accounts` block for the accounts spec
9
+ * (#1810) in `.agenthub/config.local.json`. It writes nothing, and it prints no email, no account id, no organization and no workspace id: a label is `<kind>-<n>` only: Orca's workspace
10
+ * label can be a team or organization name, and the label is shown in status. A home is printed only when Orca's own output carries one; otherwise a placeholder the person must replace, which
11
+ * `readAccounts` refuses until they do.
12
+ */
13
+ const HOME_PLACEHOLDER = "/REPLACE/WITH/THE/ABSOLUTE/HOME";
14
+
15
+ interface ImportedAccounts { readonly accounts: Record<string, { kind: string; home: string }>; readonly notes: string[] }
16
+
17
+ /** Pure: Orca's `result` object (kind to `{ accounts: [...] }`) to a declaration. Only a kind the hub can bind to a home is read; the rest is ignored. */
18
+ function importOrcaAccounts(result: unknown): ImportedAccounts {
19
+ const accounts: Record<string, { kind: string; home: string }> = {};
20
+ const notes: string[] = [];
21
+ if (!result || typeof result !== "object" || Array.isArray(result)) return { accounts, notes: ["Orca returned no account list"] };
22
+ for (const kind of accountKinds()) {
23
+ const list = (result as Record<string, { accounts?: unknown }>)[kind]?.accounts;
24
+ if (!Array.isArray(list)) continue;
25
+ let counter = 0;
26
+ for (const entry of list) {
27
+ if (!entry || typeof entry !== "object") continue;
28
+ if (counter >= MAX_ACCOUNTS_PER_KIND) { notes.push(`${kind}: only the first ${MAX_ACCOUNTS_PER_KIND} accounts are listed (the limit per kind)`); break; }
29
+ counter++;
30
+ const row = entry as Record<string, unknown>;
31
+ const label = `${kind}-${counter}`;
32
+ const home = typeof row.home === "string" && row.home.startsWith("/") ? row.home : HOME_PLACEHOLDER;
33
+ accounts[label] = { kind, home };
34
+ }
35
+ }
36
+ if (Object.values(accounts).some(account => account.home === HOME_PLACEHOLDER)) notes.push(`replace ${HOME_PLACEHOLDER} with each account's absolute home before saving; the hub refuses the block until then`);
37
+ if (Object.keys(accounts).length === 0) notes.push("Orca lists no account for a kind the hub can bind");
38
+ return { accounts, notes };
39
+ }
40
+
41
+ function readOrcaAccounts(timeoutMs = 5_000): { ok: true; result: unknown } | { ok: false; reason: string } {
42
+ const run = spawnSync("orca", ["account", "list", "--json"], { encoding: "utf8", timeout: timeoutMs, maxBuffer: 1024 * 1024, env: withoutOrcaEnv(childEnv(process.env)) });
43
+ const NEXT = "run `orca account list --json` to see Orca's own answer";
44
+ if (run.error) {
45
+ const code = (run.error as NodeJS.ErrnoException).code;
46
+ if (code === "ENOENT") return { ok: false, reason: "the orca command is not on the PATH; install Orca or add its command to the PATH" };
47
+ if (code === "ETIMEDOUT" || run.signal) return { ok: false, reason: `the orca command did not answer within ${Math.round(timeoutMs / 1000)} seconds; ${NEXT}` };
48
+ return { ok: false, reason: `the orca command could not be started (${code ?? "unknown error"}); ${NEXT}` };
49
+ }
50
+ if (run.status !== 0) return { ok: false, reason: `the orca command exited with status ${run.status}; ${NEXT}` };
51
+ try {
52
+ const parsed = JSON.parse(run.stdout) as { ok?: unknown; result?: unknown };
53
+ return parsed && parsed.ok !== false && parsed.result !== undefined ? { ok: true, result: parsed.result } : { ok: false, reason: "orca answered without a result; run `orca account list --json` and check that it prints { ok: true, result }" };
54
+ } catch { return { ok: false, reason: "orca answered with something that is not JSON; run `orca account list --json` and check that it prints { ok: true, result }" }; }
55
+ }
56
+
57
+ /** The block as pretty JSON text, built here so the print is plain text for the person to paste, not a data reply. */
58
+ function renderBlock(accounts: ImportedAccounts["accounts"]): string {
59
+ const entries = Object.entries(accounts).map(([label, { kind, home }]) => ` ${JSON.stringify(label)}: { "kind": ${JSON.stringify(kind)}, "home": ${JSON.stringify(home)} }`);
60
+ return `{\n "accounts": {\n${entries.join(",\n")}\n }\n}`;
61
+ }
62
+
63
+ export function runAccountsImport(args: string[], fail: (message: string) => never): void {
64
+ const from = args[0] === "--from" ? args[1] : args[0]?.startsWith("--from=") ? args[0].slice("--from=".length) : undefined;
65
+ if (from !== "orca" || args.length !== (args[0] === "--from" ? 2 : 1)) fail("usage: ahub accounts import --from orca");
66
+ const read = readOrcaAccounts();
67
+ if (!read.ok) return fail(`accounts import: ${read.reason}; nothing was read and nothing was written`);
68
+ const imported = importOrcaAccounts(read.result);
69
+ console.log(renderBlock(imported.accounts));
70
+ for (const note of imported.notes) warnLine("accounts import", note);
71
+ warnLine("accounts import wrote nothing", "paste the block into .agenthub/config.local.json (it is never read from the tracked config.json)");
72
+ }
@@ -0,0 +1,88 @@
1
+ import { COMPAT, type CompatId, type CompatPolicy } from "../adapters/compat.ts";
2
+ import type { AgentVersionRow } from "./agents.ts";
3
+ import type { LatestRow } from "./agents-output.ts";
4
+
5
+ /**
6
+ * #1808 T5: a release publishes its `COMPAT` table as data (`plugins/agent-hub/compat.json`, written by `scripts/build.mjs`), and `ahub agents --latest` reads the newest release's copy to say which
7
+ * release verifies the version installed here. It is advice only: it writes nothing, admits nothing and never changes a verdict on the running hub (admission stays per hub release). It is a person-run
8
+ * command (`src/cli/identity.ts` keeps an agent shell out), and the daemon never imports this file: no hub path makes a network request for it (test/compat-published-table-1808.test.ts).
9
+ */
10
+ const COMPAT_TABLE_PATH = "plugins/agent-hub/compat.json";
11
+ const REPO = "STAIxBWLB/agent-hub";
12
+ const MAX_BYTES = 256 * 1024;
13
+ const MAX_ENTRIES = 64;
14
+ const MAX_VERSIONS = 512;
15
+ const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
16
+ const ID = /^[a-z][a-z0-9-]{0,63}$/;
17
+
18
+ interface PublishedEntry { verified: string[]; gate: string; referenceOnly?: true; line?: { min: string; below: string } }
19
+ interface PublishedTable { schemaVersion: 1; release: string; entries: Record<string, PublishedEntry> }
20
+
21
+ /** The table a release publishes. Only data a reader needs to compare versions; no trust note, receipt path or executable. */
22
+ function publishedCompatTable(release: string, table: Record<string, CompatPolicy> = COMPAT): PublishedTable {
23
+ const entries: Record<string, PublishedEntry> = {};
24
+ for (const [id, policy] of Object.entries(table)) {
25
+ entries[id] = { verified: [...policy.verified], gate: policy.gate, ...(policy.referenceOnly ? { referenceOnly: true as const } : {}), ...(policy.line ? { line: { min: policy.line.min, below: policy.line.below } } : {}) };
26
+ }
27
+ return { schemaVersion: 1, release, entries };
28
+ }
29
+ // used-by: scripts/build.mjs
30
+ /** The bytes `scripts/build.mjs` writes and `--check` compares. `table` is the one parameter tests change. */
31
+ export const publishedCompatText = (release: string, table: Record<string, CompatPolicy> = COMPAT): string => `${JSON.stringify(publishedCompatTable(release, table), null, 2)}\n`;
32
+
33
+ const plain = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
34
+
35
+ /** A table from the network, checked as strictly as a file: anything unexpected is refused as a whole, never partly read. */
36
+ function parsePublishedTable(value: unknown): PublishedTable | undefined {
37
+ if (!plain(value) || value.schemaVersion !== 1 || typeof value.release !== "string" || !SEMVER.test(value.release) || value.release.length > 64 || !plain(value.entries)) return undefined;
38
+ const raw = Object.entries(value.entries);
39
+ if (raw.length > MAX_ENTRIES) return undefined;
40
+ const entries: Record<string, PublishedEntry> = {};
41
+ for (const [id, entry] of raw) {
42
+ if (!ID.test(id) || !plain(entry) || typeof entry.gate !== "string" || entry.gate.length > 16 || !Array.isArray(entry.verified) || entry.verified.length > MAX_VERSIONS
43
+ || entry.verified.some(version => typeof version !== "string" || version.length > 64 || !SEMVER.test(version))
44
+ || entry.referenceOnly !== undefined && entry.referenceOnly !== true) return undefined;
45
+ entries[id] = { verified: entry.verified as string[], gate: entry.gate, ...(entry.referenceOnly === true ? { referenceOnly: true as const } : {}) };
46
+ }
47
+ return { schemaVersion: 1, release: value.release, entries };
48
+ }
49
+
50
+ export type FetchText = (url: string) => Promise<{ ok: boolean; status: number; text: () => Promise<string> }>;
51
+ const realFetch: FetchText = url => fetch(url, { signal: AbortSignal.timeout(15_000), headers: { accept: "application/json", "user-agent": "ahub-agents-latest" } });
52
+
53
+ async function readJson(fetchText: FetchText, url: string): Promise<unknown> {
54
+ const response = await fetchText(url);
55
+ if (!response.ok) throw new Error(`${new URL(url).host} answered ${response.status}`);
56
+ const text = await response.text();
57
+ if (text.length > MAX_BYTES) throw new Error("the answer is larger than expected");
58
+ try { return JSON.parse(text); } catch { throw new Error("the answer is not JSON"); }
59
+ }
60
+
61
+ /**
62
+ * The newest published release's table: the GitHub release names the tag, and the table is read at that tag from the committed plugin directory. Two reads, both GitHub, both public.
63
+ * It throws a short sentence (no body text) when either read fails or the table is not the expected shape, so the command never shows more than that.
64
+ */
65
+ export async function readLatestTable(fetchText: FetchText = realFetch): Promise<PublishedTable> {
66
+ const release = await readJson(fetchText, `https://api.github.com/repos/${REPO}/releases/latest`).catch((error: Error) => { throw new Error(`could not read the newest release (${error.message})`); });
67
+ const name = plain(release) && typeof release.tag_name === "string" ? release.tag_name.replace(/^v/, "") : "";
68
+ if (!SEMVER.test(name) || name.length > 64) throw new Error("the newest release has no usable version tag");
69
+ const table = parsePublishedTable(await readJson(fetchText, `https://raw.githubusercontent.com/${REPO}/v${name}/${COMPAT_TABLE_PATH}`).catch((error: Error) => {
70
+ // A 404 is a release from before the first one that published compat.json: say so and name what shows the local verdicts meanwhile.
71
+ if (/ answered 404$/.test(error.message)) throw new Error(`release ${name} has no compat.json: releases before the first one that publishes it have no table, so there is nothing to compare yet; ahub agents shows the local verdicts meanwhile`);
72
+ throw new Error(`could not read compat.json of ${name} (${error.message})`);
73
+ }));
74
+ if (!table) throw new Error(`compat.json of ${name} is not a table this ahub can read`);
75
+ if (table.release !== name) throw new Error(`compat.json of ${name} names another release`);
76
+ return table;
77
+ }
78
+
79
+ /** Only a refused or trusted version needs the answer; the rest are shown as they are. A reference-only entry verifies no version. */
80
+ export function latestRows(rows: readonly AgentVersionRow[], table: PublishedTable): LatestRow[] {
81
+ return rows.map(row => {
82
+ const version = row.verdict.version, state = row.verdict.state;
83
+ if (!row.executable || version === undefined || !(state === "refused" || state === "trusted")) return { id: row.id, ...(version === undefined ? {} : { version }), state, answer: "-" };
84
+ const entry = table.entries[row.id];
85
+ return { id: row.id, version, state, answer: entry && entry.referenceOnly !== true && entry.verified.includes(version) ? `verified in ${table.release}` : "not verified in any release" };
86
+ });
87
+ }
88
+
@@ -0,0 +1,22 @@
1
+ import type { CompatId } from "../adapters/compat.ts";
2
+ import { agentVersions } from "./agents.ts";
3
+ import { latestRows, readLatestTable, type FetchText } from "./agents-latest-table.ts";
4
+ import { renderAgentsLatest } from "./agents-output.ts";
5
+ import { Report, asciiMarkers, resolveColor, streamEnv } from "./console-state.ts";
6
+ import { outputWidth } from "./output.ts";
7
+
8
+ /**
9
+ * The person-run command. `fetchText` is injectable so a test never reaches the network. It writes nothing and changes no verdict. Only `src/cli/commands/agents.ts` imports this file: the daemon
10
+ * imports `agents.ts` for its drift probe and never this, so no hub path can reach the network reader (AC7).
11
+ */
12
+ export async function runAgentsLatest(args: readonly string[], commands: Partial<Record<CompatId, readonly string[]>>, fail: (message: string) => never, fetchText?: FetchText): Promise<void> {
13
+ if (args.some(arg => arg !== "--latest" && arg !== "--json")) return fail("usage: ahub agents --latest [--json]");
14
+ const isTTY = !!process.stdout.isTTY;
15
+ const columns = outputWidth({ isTTY, columns: process.stdout.columns, COLUMNS: process.env.COLUMNS });
16
+ let table;
17
+ try { table = await readLatestTable(fetchText); } catch (error) { return fail(`ahub agents --latest: ${(error as Error).message}; nothing was changed`); }
18
+ const rows = latestRows(agentVersions(commands), table);
19
+ if (args.includes("--json")) return console.log(JSON.stringify({ release: table.release, agents: rows }, null, 2));
20
+ const ascii = asciiMarkers(process.env), color = resolveColor(undefined, streamEnv(isTTY), "ahub") === true;
21
+ console.log(new Report(columns, ascii).append(renderAgentsLatest(rows, table.release, columns, ascii)).render(color).join("\n"));
22
+ }
@@ -1,4 +1,5 @@
1
1
  import type { AgentVersionRow } from "./agents.ts";
2
+ import type { CompatId } from "../adapters/compat.ts";
2
3
  import { Report, type Span } from "./console-state.ts";
3
4
  import { grid, s } from "./sdlc-output.ts";
4
5
 
@@ -11,3 +12,12 @@ export function renderAgents(rows: readonly AgentVersionRow[], columns?: number,
11
12
  return new Report(columns, ascii).titled("ahub", "Agents")
12
13
  .section("Versions", String(rows.length)).append(grid(["AGENT", "VERSION", "STATE", "POLICY", "DETAIL"], items, columns)).lines();
13
14
  }
15
+
16
+ export interface LatestRow { id: CompatId; version?: string; state: string; answer: string }
17
+ /** #1808 T5: what `ahub agents --latest` prints: per CLI, whether the newest release verifies the version installed here. Advice only. */
18
+ export function renderAgentsLatest(rows: readonly LatestRow[], release: string, columns?: number, ascii = false): Span[][] {
19
+ const items = rows.map(({ id, version, state, answer }) => [s(id, "info"), s(version ?? "-"), s(state, state === "refused" ? "attention" : "info"), s(answer, answer.startsWith("verified") ? "success" : "info")]);
20
+ return new Report(columns, ascii).titled("ahub", "Agents against the newest release")
21
+ .section("Release", release).append(grid(["AGENT", "VERSION", "STATE", "NEWEST RELEASE"], items, columns))
22
+ .note("Advice only: this changes nothing here. A version the newest release verifies is accepted after you move to that release; until then ahub agents trust <id> <version> accepts one exact version on this machine.").lines();
23
+ }
@@ -0,0 +1,100 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { mkdirSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { BRIDGE_BUNDLE, loadPresets, parseProbeVersion, presetDeclaration, presetPullDeclaration, presetRows, readJsonFile, registrationText, type AgentPreset } from "../adapters/presets.ts";
5
+ import { readConfiguredAdapters } from "../adapters/configured-adapter-policy.ts";
6
+ import { KNOWN_PEERS } from "../adapters/registry.ts";
7
+ import { childEnv } from "../hub/child-process.ts";
8
+ import { configTracked } from "../hub/config-trust.ts";
9
+ import { withoutOrcaEnv } from "../hub/orca-env.ts";
10
+ import { atomicPrivateJSON } from "../hub/recovery-store.ts";
11
+ import { Report, asciiMarkers, resolveColor, streamEnv } from "./console-state.ts";
12
+ import { outputWidth } from "./output.ts";
13
+ import { grid, s } from "./sdlc-output.ts";
14
+
15
+ type Fail = (message: string) => never;
16
+
17
+ /** The installed executable and its version, read with one bounded probe in a scrubbed environment; undefined for either when the CLI is not there or prints none. */
18
+ function installed(preset: AgentPreset): { path?: string; version?: string } {
19
+ const path = Bun.which(preset.executable, { PATH: process.env.PATH ?? "" }) ?? undefined;
20
+ if (!path) return {};
21
+ const run = spawnSync(path, preset.versionArgs, { encoding: "utf8", timeout: 10_000, maxBuffer: 64 * 1024, env: withoutOrcaEnv(childEnv(process.env)) });
22
+ return { path, ...(run.status === 0 ? { version: parseProbeVersion(run.stdout ?? "") } : {}) };
23
+ }
24
+
25
+ function printer(): { print: (report: Report) => void; columns: number | undefined; ascii: boolean } {
26
+ const isTTY = !!process.stdout.isTTY;
27
+ const columns = outputWidth({ isTTY, columns: process.stdout.columns, COLUMNS: process.env.COLUMNS });
28
+ const ascii = asciiMarkers(process.env), color = resolveColor(undefined, streamEnv(isTTY), "ahub") === true;
29
+ return { print: (report) => console.log(report.render(color).join("\n")), columns, ascii };
30
+ }
31
+
32
+ /** `ahub agents presets [--json]`: each preset with the version installed here and its status. Reads and runs a version probe; changes nothing. */
33
+ export function runAgentsPresets(args: string[], fail: Fail): void {
34
+ if (args.some(arg => arg !== "--json")) fail("usage: ahub agents presets [--json]");
35
+ const presets = loadPresets();
36
+ const rows = presetRows(presets).map(row => {
37
+ const found = installed(presets.find(preset => preset.id === row.id)!);
38
+ return { ...row, installed: found.path !== undefined, version: found.version ?? null };
39
+ });
40
+ if (args.includes("--json")) return console.log(JSON.stringify(rows.map(row => ({ id: row.id, displayName: row.displayName, executable: row.executable, installed: row.installed, version: row.version, headless: row.acp, status: row.status, receipt: row.receipt })), null, 2));
41
+ const { print, columns, ascii } = printer();
42
+ const items = rows.map(row => [s(row.id, "info"), s(row.installed ? row.version ?? "installed" : "not installed"), s(row.acp ? "headless" : "no headless line"), s(row.status, row.status === "verified" ? "success" : "attention")]);
43
+ print(new Report(columns, ascii).titled("ahub", "Agent presets").section("Presets", String(rows.length)).append(grid(["PRESET", "VERSION", "HEADLESS", "STATUS"], items, columns))
44
+ .note("untested means no receipt is committed for this preset; it gets exactly the limits a hand-written kind has. ahub agents add <preset> writes its declaration.").next("ahub agents add <preset> [--as <kind>]"));
45
+ }
46
+
47
+ /**
48
+ * `ahub agents add <preset> [--as <kind>]` (person only: src/cli/identity.ts refuses every `agents` form but a bare listing to an agent shell and to
49
+ * `--live-test`). It writes `adapters.<kind>` to the untracked `.agenthub/config.local.json` and nothing else, after the same validation a hand-written
50
+ * declaration gets, and writes nothing when any check fails. The hub reads the declaration at start, so the person restarts it.
51
+ */
52
+ export function runAgentsAdd(args: string[], cwd: string, fail: Fail, presets: readonly AgentPreset[] = loadPresets()): void {
53
+ const usage = "usage: ahub agents add <preset> [--as <kind>] [--pull]";
54
+ let id: string | undefined, as: string | undefined, pull = false;
55
+ for (let index = 0; index < args.length; index++) {
56
+ const arg = args[index]!;
57
+ if (arg === "--as") { as = args[++index]; if (!as) fail(usage); }
58
+ else if (arg.startsWith("--as=")) as = arg.slice(5);
59
+ else if (arg === "--pull") pull = true;
60
+ else if (arg.startsWith("-") || id !== undefined) fail(usage);
61
+ else id = arg;
62
+ }
63
+ const preset = presets.find(row => row.id === id);
64
+ if (!id) fail(usage);
65
+ if (!preset) return fail(`unknown preset ${id}: the presets are ${presets.map(row => row.id).join(", ")} (ahub agents presets)`);
66
+ if (!preset.acp && !pull) return fail(`${preset.id} has no headless launch line: ${preset.displayName} lists no ACP mode, so it can only join as a pull peer (ahub agents add ${preset.id} --pull)`);
67
+ const found = installed(preset);
68
+ if (!found.path) return fail(`${preset.executable} was not found on PATH, so nothing was written; install ${preset.displayName} first`);
69
+ if (!found.version && !pull) return fail(`${preset.executable} printed no version this command could read, so no identity pin can be written and nothing was written`);
70
+ const kind = as ?? preset.id;
71
+ const file = join(cwd, ".agenthub", "config.local.json");
72
+ // The hub ignores `adapters` in any file git does not confirm as untracked, so a write it would ignore is refused, never made.
73
+ if (configTracked(cwd, "config.local.json") !== false) return fail("git cannot confirm that .agenthub/config.local.json is untracked here, and the hub ignores adapters in a file it cannot confirm, so nothing was written; run this in a git repository that does not track that file");
74
+ let existing: Record<string, unknown> | undefined;
75
+ try { existing = readJsonFile(file); } catch (error) { return fail(`${(error as Error).message}; fix or move it, nothing was written`); }
76
+ const adapters = (existing?.adapters ?? {}) as Record<string, unknown>;
77
+ if (!adapters || typeof adapters !== "object" || Array.isArray(adapters)) return fail("adapters in .agenthub/config.local.json is not an object, so nothing was written");
78
+ if (Object.hasOwn(adapters, kind)) return fail(`adapters.${kind} already exists in .agenthub/config.local.json; nothing was changed (use --as <kind> for another name)`);
79
+ const merged = { ...adapters, [kind]: pull ? presetPullDeclaration(preset, found.path) : presetDeclaration(preset, found.path, found.version!) };
80
+ try { readConfiguredAdapters(merged, [...KNOWN_PEERS]); } catch (error) { return fail(`${(error as Error).message}; nothing was written`); }
81
+ mkdirSync(join(cwd, ".agenthub"), { recursive: true });
82
+ atomicPrivateJSON(file, { ...(existing ?? {}), adapters: merged });
83
+ const { print, columns, ascii } = printer();
84
+ if (pull) {
85
+ // The hub never writes another tool's configuration: the registration is printed for the person to run (#1809 AC6).
86
+ print(new Report(columns, ascii).titled("ahub", "Agent preset (pull)")
87
+ .section("Result").bullet("ok", `wrote adapters.${kind} as a pull kind from the ${preset.id} preset (${preset.status === "verified" ? "verified" : "untested"})`)
88
+ .kv([["file", ".agenthub/config.local.json"], ["command", found.path]])
89
+ .note(`Register the hub's bridge in ${preset.displayName} yourself; this command ran nothing and wrote nothing outside .agenthub: ${registrationText(preset, process.execPath, BRIDGE_BUNDLE)}`)
90
+ .note("Restart the hub (ahub restart) to load the kind. It starts off roster, as a cloud peer that owns no task and is never pushed to.")
91
+ .next(`ahub roster add ${kind}`));
92
+ return;
93
+ }
94
+ if (!preset.acp) return fail(`${preset.id} has no headless launch line`);
95
+ print(new Report(columns, ascii).titled("ahub", "Agent preset")
96
+ .section("Result").bullet("ok", `wrote adapters.${kind} from the ${preset.id} preset (${preset.status === "verified" ? "verified" : "untested"})`)
97
+ .kv([["file", ".agenthub/config.local.json"], ["command", found.path], ["pinned identity", `${preset.acp.identity.name} ${found.version}`]])
98
+ .note("The hub reads declarations at start: restart it (ahub restart) to load the kind. It starts off roster, headless, as a cloud peer that gets no PII work.")
99
+ .next(`ahub roster add ${kind}`));
100
+ }
package/src/cli/agents.ts CHANGED
@@ -106,7 +106,7 @@ export function runAgents(args: string[], commands: Partial<Record<CompatId, rea
106
106
  print(receipt);
107
107
  return;
108
108
  }
109
- if (sub !== undefined) fail("usage: ahub agents [--json] | ahub agents trust <id> <version> [--revoke]");
109
+ if (sub !== undefined) fail("usage: ahub agents [--json] | ahub agents --latest [--json] | ahub agents trust <id> <version> [--revoke] | ahub agents presets [--json] | ahub agents add <preset> [--as <kind>] [--pull]");
110
110
  const rows = agentVersions(commands);
111
111
  if (args.includes("--json")) return console.log(JSON.stringify(rows.map(row => ({ id: row.id, executable: row.executable ?? null, ...row.verdict, policy: row.policy })), null, 2));
112
112
  print(new Report(columns, ascii).append(renderAgents(rows, columns, ascii)));
@@ -4,7 +4,7 @@ export interface AttentionState {
4
4
  approvals: readonly { id: string; peer?: string; expiresAt: number }[];
5
5
  permissionDefaults: readonly { peer: string }[];
6
6
  peers: Record<string, { state?: string; attached?: boolean; needsReview?: number; heldBy?: string }>;
7
- budget: Record<string, { paused?: { since?: number; resetsAt?: number } }>;
7
+ budget: NonNullable<NeedsInput["budget"]>;
8
8
  attentionMessages?: readonly { id?: string; peer?: string; important: boolean; since?: number }[];
9
9
  storageBlocked?: boolean;
10
10
  recoveryNeed?: { id?: string; running: boolean; since?: number };
@@ -17,7 +17,7 @@ export interface AttentionState {
17
17
  }
18
18
  /** Allowlisted adapter between console-owned facts and the shared body-free model. */
19
19
  export function consoleNeeds(state: AttentionState, now: number): Needs {
20
- const input: NeedsInput = { approvals: state.approvals.map(row => ({ id: row.id, peer: row.peer, expiresAt: row.expiresAt })), defaults: state.permissionDefaults.map(row => ({ peer: row.peer })), peers: Object.fromEntries(Object.entries(state.peers).map(([peer,row]) => [peer,{ state: row.state, attached: row.attached, needsReview: row.needsReview, heldBy: row.heldBy }])), budget: Object.fromEntries(Object.entries(state.budget).map(([peer,row]) => [peer,{ ...(row.paused ? { paused: { since: row.paused.since, resetsAt: row.paused.resetsAt } } : {}) }])), messages: (state.attentionMessages ?? []).map(row => ({ id: row.id, peer: row.peer, important: row.important, since: row.since })), storageBlocked: state.storageBlocked, recovery: state.recoveryNeed, questions: (state.questions ?? []).map(row => ({ set: row.set, peer: row.peer, since: row.created })) };
20
+ const input: NeedsInput = { approvals: state.approvals.map(row => ({ id: row.id, peer: row.peer, expiresAt: row.expiresAt })), defaults: state.permissionDefaults.map(row => ({ peer: row.peer })), peers: Object.fromEntries(Object.entries(state.peers).map(([peer,row]) => [peer,{ state: row.state, attached: row.attached, needsReview: row.needsReview, heldBy: row.heldBy }])), budget: Object.fromEntries(Object.entries(state.budget).map(([peer,row]) => [peer,{ ...(row.paused ? { paused: { since: row.paused.since, resetsAt: row.paused.resetsAt } } : {}), ...(Array.isArray(row.warnings) ? { warnings: row.warnings.map(w => ({ window: w.window, at: w.at })) } : {}) }])), messages: (state.attentionMessages ?? []).map(row => ({ id: row.id, peer: row.peer, important: row.important, since: row.since })), storageBlocked: state.storageBlocked, recovery: state.recoveryNeed, questions: (state.questions ?? []).map(row => ({ set: row.set, peer: row.peer, since: row.created })) };
21
21
  const result = needs({ ...input, facts: state.attentionFacts, results: state.results }, now);
22
22
  // Panel snapshots know each held row; enrich only ids, without changing the status-derived count.
23
23
  const used = new Set<string | number>();
@@ -70,6 +70,7 @@ export function attentionCommand(item: NeedItem): string {
70
70
  if (item.kind === "delivery") return `ahub queue list${item.id ? `; ahub queue show ${item.id}` : ""}`;
71
71
  if (item.kind === "review") return `ahub task show ${item.id}; ahub review ${item.id} approved|changes_requested`;
72
72
  if (item.kind === "offline") return `ahub status; ahub task show ${item.id}; ahub task assign ${item.id} <peer>`;
73
+ if (item.kind === "pane") return `${item.peer} waits for you in Orca: orca terminal switch --terminal ${item.id}`;
73
74
  if (item.kind === "storage") return "ahub doctor";
74
75
  if (item.kind === "recovery") return `ahub recovery status${item.id ? ` ${item.id}` : ""}`;
75
76
  if (item.kind === "budget") return "ahub budget";