@staix/agent-hub 0.51.0 → 0.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (299) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +1 -1
  3. package/docs/adding-an-ai-tool.md +24 -2
  4. package/docs/agent-notes/adapters.md +1 -0
  5. package/docs/agent-notes/budget.md +8 -2
  6. package/docs/agent-notes/daemon.md +13 -8
  7. package/docs/agent-notes/security-review.md +6 -5
  8. package/docs/agent-notes/tasks.md +5 -2
  9. package/docs/agent-notes/tests.md +4 -3
  10. package/docs/cooperbench.md +1 -1
  11. package/docs/design/adapters.md +4 -0
  12. package/docs/design/cli-output-inventory.md +162 -152
  13. package/docs/design/cli-output.md +4 -3
  14. package/docs/design/guidance-probes.md +1 -0
  15. package/docs/design/roadmap.md +2 -0
  16. package/docs/design/task-board.md +1 -0
  17. package/docs/dogfood.md +14 -0
  18. package/docs/events.md +4 -2
  19. package/docs/memory.md +5 -3
  20. package/docs/operations.md +210 -16
  21. package/docs/quickstart.md +12 -2
  22. package/docs/roles.md +1 -1
  23. package/docs/sdlc.md +26 -3
  24. package/docs/security.md +11 -5
  25. package/docs/specs/2026-09-19-agent-hub-design.md +43 -0
  26. package/docs/specs/2026-09-19-multi-project-design.md +4 -0
  27. package/docs/specs/2026-09-20-upgrade-recovery-design.md +17 -0
  28. package/docs/specs/mcp-endpoint.md +63 -0
  29. package/docs/verification/2026-11-30-capability-listing-shape-1808.md +45 -0
  30. package/docs/verification/2026-11-30-upgrade-keep-1807.md +174 -0
  31. package/docs/verification/2026-12-01-1811-confirmation-receipt.md +19 -0
  32. package/docs/verification/2026-12-01-1811-orca-agent-list.md +20 -0
  33. package/docs/verification/2026-12-01-1811-orca-pane-key.md +21 -0
  34. package/docs/verification/2026-12-02-1819-claude-process-after-renewal.md +54 -0
  35. package/docs/verification/2026-12-02-agy-1.5.21.md +74 -0
  36. package/docs/verification/2026-12-02-claude-implementer-2.1.334.md +44 -0
  37. package/docs/verification/2026-12-02-cli-import-graph.md +33 -0
  38. package/docs/verification/2026-12-03-0.52.0.md +150 -0
  39. package/docs/verification/2026-12-03-codex-0173-reviewer-isolation.md +53 -0
  40. package/docs/verification/2026-12-03-codex-0173-reviewer-tool-call.md +34 -0
  41. package/docs/verification/2026-12-03-jcode-1.3.0.md +25 -0
  42. package/docs/verification/agy/README.md +17 -0
  43. package/docs/verification/agy/cli-surface.ts +68 -0
  44. package/docs/verification/agy/interactive-bridge.ts +92 -0
  45. package/docs/verification/agy/interactive-session.ts +131 -0
  46. package/docs/verification/agy/launcher-nonce.ts +215 -0
  47. package/docs/verification/agy/native-hooks.ts +210 -0
  48. package/docs/verification/agy/originals/agent-hub-681/cli-surface.ts +87 -0
  49. package/docs/verification/agy/originals/agent-hub-681/native-hooks-adapted.ts +91 -0
  50. package/docs/verification/agy/originals/agent-hub-681/tui-actual.ts +200 -0
  51. package/docs/verification/agy/originals/agent-hub-684/probe.ts +107 -0
  52. package/docs/verification/agy/originals.json +25 -0
  53. package/docs/verification/agy/permission-new-functions.ts +128 -0
  54. package/docs/verification/agy/run-probe.py +108 -0
  55. package/docs/verification/agy/runtime.ts +171 -0
  56. package/docs/verification/agy/tmux-helper-control.ts +6 -0
  57. package/docs/verification/agy/tmux-session.ts +235 -0
  58. package/docs/verified.json +82 -41
  59. package/package.json +3 -3
  60. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  61. package/plugins/agent-hub/compat.json +157 -0
  62. package/plugins/agent-hub/kimi-hook.js +621 -865
  63. package/plugins/agent-hub/server.js +17423 -32962
  64. package/src/adapters/agy/definition.ts +7 -24
  65. package/src/adapters/channel-peer.ts +3 -1
  66. package/src/adapters/claude-channel.ts +38 -257
  67. package/src/adapters/claude-implementer.ts +3 -1
  68. package/src/adapters/codex-appserver.ts +77 -15
  69. package/src/adapters/compat.ts +74 -11
  70. package/src/adapters/configured-acp.ts +23 -163
  71. package/src/adapters/configured-adapter-policy.ts +160 -0
  72. package/src/adapters/configured-pull-entry.ts +53 -0
  73. package/src/adapters/configured-pull.ts +38 -0
  74. package/src/adapters/conformance/fakes/app-server.ts +9 -2
  75. package/src/adapters/declaration-catalog.ts +25 -0
  76. package/src/adapters/declaration-data.ts +342 -0
  77. package/src/adapters/declaration-resolution.ts +53 -0
  78. package/src/adapters/definitions/builtin-metadata.ts +61 -83
  79. package/src/adapters/definitions/jcode-launch.ts +13 -0
  80. package/src/adapters/definitions/native-adapter-policy.ts +390 -0
  81. package/src/adapters/definitions/native-cli-claude-launch.ts +3 -2
  82. package/src/adapters/definitions/native-cli-codex-launch.ts +2 -1
  83. package/src/adapters/definitions/native-cli-entry-jcode.ts +4 -2
  84. package/src/adapters/definitions/native-cli-entry-types.ts +9 -2
  85. package/src/adapters/definitions/native-cli-launch-common.ts +2 -2
  86. package/src/adapters/definitions/native-cli-retained.ts +1 -1
  87. package/src/adapters/definitions/native-configuration.ts +18 -0
  88. package/src/adapters/definitions/native-help.ts +24 -0
  89. package/src/adapters/definitions/native-launch-declarations.ts +34 -0
  90. package/src/adapters/definitions/native-launch-policy.ts +4 -0
  91. package/src/adapters/definitions/native-launch-settings.ts +72 -0
  92. package/src/adapters/definitions/native-light-cli.ts +18 -0
  93. package/src/adapters/definitions/native-light-preview.ts +10 -0
  94. package/src/adapters/definitions/native-wrapper-launch.ts +10 -0
  95. package/src/adapters/definitions/qwen.ts +6 -29
  96. package/src/adapters/definitions/reviewer-variants.ts +7 -8
  97. package/src/adapters/external-declarations.ts +31 -0
  98. package/src/adapters/external-modules.ts +4 -29
  99. package/src/adapters/jcode.ts +3 -12
  100. package/src/adapters/native-capabilities.ts +18 -8
  101. package/src/adapters/native-proof-ports.ts +1 -1
  102. package/src/adapters/presets.ts +136 -0
  103. package/src/adapters/qwen-dual.ts +2 -2
  104. package/src/adapters/registry-types.ts +3 -0
  105. package/src/adapters/registry.ts +20 -81
  106. package/src/adapters/reviewer-print.ts +26 -9
  107. package/src/adapters/role-eligibility.ts +2 -1
  108. package/src/cli/accounts-import.ts +72 -0
  109. package/src/cli/agents-latest-table.ts +88 -0
  110. package/src/cli/agents-latest.ts +22 -0
  111. package/src/cli/agents-output.ts +10 -0
  112. package/src/cli/agents-presets.ts +100 -0
  113. package/src/cli/agents.ts +1 -1
  114. package/src/cli/attention.ts +3 -2
  115. package/src/cli/autonomy-homes.ts +7 -2
  116. package/src/cli/budget-renew-guidance.ts +129 -0
  117. package/src/cli/claude-homes.ts +9 -5
  118. package/src/cli/command-context.ts +3 -0
  119. package/src/cli/command-table.ts +123 -0
  120. package/src/cli/commands/accounts.ts +8 -0
  121. package/src/cli/commands/agents.ts +18 -0
  122. package/src/cli/commands/answer.ts +28 -0
  123. package/src/cli/commands/ask.ts +17 -0
  124. package/src/cli/commands/autonomy.ts +83 -0
  125. package/src/cli/commands/backlog.ts +46 -0
  126. package/src/cli/commands/bench.ts +60 -0
  127. package/src/cli/commands/board.ts +48 -0
  128. package/src/cli/commands/broker.ts +9 -0
  129. package/src/cli/commands/budget.ts +96 -0
  130. package/src/cli/commands/capabilities.ts +12 -0
  131. package/src/cli/commands/check-path.ts +55 -0
  132. package/src/cli/commands/completion.ts +8 -0
  133. package/src/cli/commands/console.ts +12 -0
  134. package/src/cli/commands/daemon.ts +8 -0
  135. package/src/cli/commands/deliverables.ts +25 -0
  136. package/src/cli/commands/doctor.ts +249 -0
  137. package/src/cli/commands/down.ts +3 -0
  138. package/src/cli/commands/export.ts +15 -0
  139. package/src/cli/commands/facts.ts +15 -0
  140. package/src/cli/commands/goal.ts +22 -0
  141. package/src/cli/commands/guidance.ts +102 -0
  142. package/src/cli/commands/help.ts +17 -0
  143. package/src/cli/commands/host.ts +45 -0
  144. package/src/cli/commands/init.ts +121 -0
  145. package/src/cli/commands/instructed.ts +19 -0
  146. package/src/cli/commands/instruction-hook.ts +15 -0
  147. package/src/cli/commands/intake.ts +24 -0
  148. package/src/cli/commands/kill.ts +15 -0
  149. package/src/cli/commands/learn.ts +23 -0
  150. package/src/cli/commands/lineage.ts +30 -0
  151. package/src/cli/commands/logs.ts +21 -0
  152. package/src/cli/commands/manager.ts +15 -0
  153. package/src/cli/commands/memory.ts +21 -0
  154. package/src/cli/commands/model.ts +25 -0
  155. package/src/cli/commands/models.ts +40 -0
  156. package/src/cli/commands/native.ts +39 -0
  157. package/src/cli/commands/pause.ts +5 -0
  158. package/src/cli/commands/peer.ts +32 -0
  159. package/src/cli/commands/permission.ts +26 -0
  160. package/src/cli/commands/permit.ts +12 -0
  161. package/src/cli/commands/pet.ts +24 -0
  162. package/src/cli/commands/projects.ts +49 -0
  163. package/src/cli/commands/queue.ts +70 -0
  164. package/src/cli/commands/recovery-run.ts +13 -0
  165. package/src/cli/commands/recovery.ts +130 -0
  166. package/src/cli/commands/release.ts +23 -0
  167. package/src/cli/commands/releases.ts +9 -0
  168. package/src/cli/commands/remember.ts +6 -0
  169. package/src/cli/commands/report.ts +27 -0
  170. package/src/cli/commands/research.ts +53 -0
  171. package/src/cli/commands/reset.ts +89 -0
  172. package/src/cli/commands/restart.ts +5 -0
  173. package/src/cli/commands/results.ts +31 -0
  174. package/src/cli/commands/resume.ts +5 -0
  175. package/src/cli/commands/review.ts +24 -0
  176. package/src/cli/commands/roadmap.ts +21 -0
  177. package/src/cli/commands/role.ts +34 -0
  178. package/src/cli/commands/roles.ts +30 -0
  179. package/src/cli/commands/room.ts +14 -0
  180. package/src/cli/commands/roster.ts +48 -0
  181. package/src/cli/commands/route.ts +9 -0
  182. package/src/cli/commands/say.ts +21 -0
  183. package/src/cli/commands/schedule.ts +17 -0
  184. package/src/cli/commands/sdlc.ts +321 -0
  185. package/src/cli/commands/settings.ts +148 -0
  186. package/src/cli/commands/setup.ts +89 -0
  187. package/src/cli/commands/shared-refusals.ts +25 -0
  188. package/src/cli/commands/smoke.ts +44 -0
  189. package/src/cli/commands/source.ts +64 -0
  190. package/src/cli/commands/specs.ts +13 -0
  191. package/src/cli/commands/status.ts +28 -0
  192. package/src/cli/commands/stop.ts +17 -0
  193. package/src/cli/commands/structure.ts +60 -0
  194. package/src/cli/commands/study.ts +39 -0
  195. package/src/cli/commands/tail.ts +19 -0
  196. package/src/cli/commands/task.ts +114 -0
  197. package/src/cli/commands/title.ts +17 -0
  198. package/src/cli/commands/turns.ts +10 -0
  199. package/src/cli/commands/ui.ts +47 -0
  200. package/src/cli/commands/undo.ts +77 -0
  201. package/src/cli/commands/up.ts +39 -0
  202. package/src/cli/commands/upgrade.ts +5 -0
  203. package/src/cli/commands/usage.ts +33 -0
  204. package/src/cli/commands/version.ts +5 -0
  205. package/src/cli/commands/watch.ts +30 -0
  206. package/src/cli/commands/worktrees.ts +31 -0
  207. package/src/cli/console-state.ts +5 -138
  208. package/src/cli/console-versions.ts +1 -1
  209. package/src/cli/help.ts +37 -15
  210. package/src/cli/identity.ts +23 -4
  211. package/src/cli/launch-check.ts +1 -2
  212. package/src/cli/launch.ts +13 -82
  213. package/src/cli/light-dispatch.ts +29 -0
  214. package/src/cli/main.js +8 -1
  215. package/src/cli/main.ts +233 -2816
  216. package/src/cli/orca-probe.ts +119 -0
  217. package/src/cli/output.ts +31 -2
  218. package/src/cli/preview.ts +10 -5
  219. package/src/cli/recovery-version-preflight.ts +28 -9
  220. package/src/cli/replace-process.ts +22 -0
  221. package/src/cli/report-layout.ts +142 -0
  222. package/src/cli/roadmap-usage.ts +16 -0
  223. package/src/cli/roadmap.ts +3 -16
  224. package/src/cli/sdlc-doctor.ts +27 -0
  225. package/src/cli/sdlc-output.ts +55 -1
  226. package/src/cli/setup-homes.ts +1 -1
  227. package/src/cli/start-agents-run.ts +1 -1
  228. package/src/cli/statusline-tee.ts +25 -4
  229. package/src/cli/terminal-recovery.ts +53 -10
  230. package/src/cli/upgrade-interactive.ts +1 -0
  231. package/src/cli/upgrade-runtime.ts +11 -0
  232. package/src/cli/upgrade.ts +4 -15
  233. package/src/hub/accounts.ts +148 -0
  234. package/src/hub/addons.ts +20 -0
  235. package/src/hub/agent-drift.ts +2 -1
  236. package/src/hub/budget-projection.ts +39 -7
  237. package/src/hub/budget.ts +231 -16
  238. package/src/hub/channel-project.ts +3 -3
  239. package/src/hub/conductor-peer.ts +24 -0
  240. package/src/hub/conductor.ts +2 -21
  241. package/src/hub/config-apply.ts +24 -13
  242. package/src/hub/config-edit.ts +1 -1
  243. package/src/hub/config-tier.ts +2 -0
  244. package/src/hub/config.ts +31 -14
  245. package/src/hub/control-client.ts +48 -0
  246. package/src/hub/daemon.ts +421 -61
  247. package/src/hub/events.ts +3 -0
  248. package/src/hub/home-tag.ts +12 -0
  249. package/src/hub/host.ts +217 -0
  250. package/src/hub/hub-tools.ts +2 -1
  251. package/src/hub/instance-budget.ts +2 -2
  252. package/src/hub/instance-config.ts +15 -126
  253. package/src/hub/instances.ts +22 -6
  254. package/src/hub/instruction-receipt.ts +2 -2
  255. package/src/hub/kimi-usage.ts +38 -11
  256. package/src/hub/lifecycle.ts +86 -4
  257. package/src/hub/mcp-bridge-core.ts +98 -0
  258. package/src/hub/mcp-channel-push.ts +20 -0
  259. package/src/hub/mcp-endpoint-serve.ts +178 -0
  260. package/src/hub/mcp-endpoint.ts +226 -0
  261. package/src/hub/mcp-tool-call.ts +181 -0
  262. package/src/hub/operational-settings.ts +2 -0
  263. package/src/hub/orca-env.ts +6 -0
  264. package/src/hub/orca-state.ts +84 -0
  265. package/src/hub/peers.ts +5 -1
  266. package/src/hub/permission-mode.ts +2 -1
  267. package/src/hub/project.ts +20 -0
  268. package/src/hub/protocol-window.ts +58 -0
  269. package/src/hub/quota-origin.ts +20 -0
  270. package/src/hub/registry.ts +36 -2
  271. package/src/hub/report.ts +1 -1
  272. package/src/hub/research.ts +1 -1
  273. package/src/hub/review-brief.ts +47 -2
  274. package/src/hub/roster.ts +6 -3
  275. package/src/hub/routing.ts +9 -2
  276. package/src/hub/sdlc-check.ts +205 -0
  277. package/src/hub/sdlc-sync.ts +146 -0
  278. package/src/hub/sdlc.ts +33 -4
  279. package/src/hub/settings.ts +7 -4
  280. package/src/hub/start-agents.ts +1 -1
  281. package/src/hub/start-mode.ts +11 -4
  282. package/src/hub/structure-budget.ts +131 -0
  283. package/src/hub/structure-scan.ts +149 -0
  284. package/src/hub/tasks-experiment.ts +455 -0
  285. package/src/hub/tasks-guidance.ts +606 -0
  286. package/src/hub/tasks-roadmap-plan.ts +419 -0
  287. package/src/hub/tasks-roadmap.ts +491 -0
  288. package/src/hub/tasks-study.ts +661 -0
  289. package/src/hub/tasks-survey.ts +192 -0
  290. package/src/hub/tasks.ts +319 -2548
  291. package/src/hub/terminal-open.ts +5 -3
  292. package/src/hub/tooling.ts +3 -19
  293. package/src/hub/usage-rollup.ts +9 -3
  294. package/src/local/tools.ts +5 -0
  295. package/src/ui/index.html +1 -1
  296. package/src/ui/needs.ts +17 -5
  297. package/src/ui/peer-palette.ts +2 -4
  298. package/templates/presets/agents.json +60 -0
  299. package/templates/presets/confirmation-matrix.json +8 -8
@@ -0,0 +1,226 @@
1
+ // #1780 T1: the per-project MCP endpoint socket. The daemon listens on `<hub home>/run/<projectId>/mcp.sock`, validates one hello line per connection
2
+ // before any MCP byte is read, and keeps a session record for T2. Nothing here serves MCP yet: a request after a valid hello gets a JSON-RPC error.
3
+ import { chmodSync, lstatSync, mkdirSync, unlinkSync } from "node:fs";
4
+ import { createConnection, createServer, type Server, type Socket } from "node:net";
5
+ import { timingSafeEqual, randomUUID } from "node:crypto";
6
+ import { join } from "node:path";
7
+ import { execFile } from "node:child_process";
8
+ import { isClaudeSessionUuid } from "./claude-state.ts";
9
+
10
+ type McpMode = "channel" | "tools";
11
+ /** What the hub keeps of one relay session: never the home path, only the account label it maps to. */
12
+ interface McpSession { id: string; peer: string; mode: McpMode; pid: number; ppid: number; accountLabel?: string; connectedAt: number }
13
+ /** #1780 T2a-2c: what serves one session once its hello is admitted. `handle` takes one line and answers through the `write` the endpoint gave `serve`; it is not awaited, so a slow call never blocks a later line. */
14
+ export interface McpSessionServer { handle(line: string): void; close(): void }
15
+ export interface McpEndpoint { path: string; sessions(): McpSession[]; stop(): Promise<void> }
16
+ interface McpEndpointOptions {
17
+ home: string; projectId: string; /** The control token a hello must carry. */ token: string;
18
+ /** Maps a hello's `home` to a declared account label and returns it, or undefined for the default; a path never leaves this call. */
19
+ accountLabel(home: unknown, peer: string): string | undefined;
20
+ log(line: string): void;
21
+ /** Tests replace the platform reads; the defaults ask the OS. */
22
+ daemonUid?: number; uidOfPid?: (pid: number) => number | undefined | Promise<number | undefined>; helloTimeoutMs?: number;
23
+ /** #1780 T2a: set only by a daemon that holds its project's fixed control port, which one daemon per project can bind; it alone lets a stale socket file be replaced. */
24
+ exclusiveOwner?: boolean;
25
+ /** #1780 T2a-2c: serves the session's JSON-RPC. Without it every request after the hello gets -32601 "not served yet". Returning undefined closes the connection (the serve step wrote its own reason). */
26
+ serve?: (session: McpSession, hello: McpHello, write: (line: string) => boolean, close: () => void) => Promise<McpSessionServer | undefined>;
27
+ onSession?: (session: McpSession, socket: Socket) => void; onClose?: (session: McpSession) => void;
28
+ }
29
+ type McpEndpointResult = { ok: true; endpoint: McpEndpoint } | { ok: false; refusal: string };
30
+
31
+ const HELLO_BYTES = 8192, LINE_BYTES = 1024 * 1024, HELLO_MS = 5000, PEER = /^[a-z][a-z0-9-]{0,31}$/;
32
+
33
+ /** The hello's optional fields mirror what the bridge sends on its control connect; roles, profile and catalog are never taken from it. */
34
+ export type McpHello = { v: 1; mode: McpMode; peer: string; pid: number; ppid: number; cwd: string; home?: string; token: string;
35
+ session?: string; claudeSessionId?: string; launchId?: string; projectRoot?: string; permissionTool?: boolean; deliveryOnly?: boolean };
36
+ type Hello = McpHello;
37
+ const HELLO_KEYS = new Set(["v", "mode", "peer", "pid", "ppid", "cwd", "home", "token", "session", "claudeSessionId", "launchId", "projectRoot", "permissionTool", "deliveryOnly"]);
38
+
39
+ /** One hello line, parsed. Anything unexpected is a refusal; the caller closes the connection without a reply. */
40
+ function validateHello(line: string, token: string): Hello | undefined {
41
+ let value: unknown;
42
+ try { value = JSON.parse(line); } catch { return undefined; }
43
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
44
+ const hello = value as Record<string, unknown>;
45
+ if (Object.keys(hello).some(key => !HELLO_KEYS.has(key))) return undefined;
46
+ if (hello.v !== 1 || (hello.mode !== "channel" && hello.mode !== "tools")) return undefined;
47
+ if (typeof hello.peer !== "string" || !PEER.test(hello.peer) || ["user", "hub", "digest"].includes(hello.peer)) return undefined;
48
+ for (const key of ["pid", "ppid"] as const) if (!Number.isSafeInteger(hello[key]) || (hello[key] as number) <= 0 || (hello[key] as number) > 2_147_483_647) return undefined;
49
+ if (typeof hello.cwd !== "string" || hello.cwd.length === 0 || hello.cwd.length > 4096) return undefined;
50
+ if (hello.home !== undefined && (typeof hello.home !== "string" || hello.home.length > 4096)) return undefined;
51
+ // The same limits the control path applies: a session label, a Claude session uuid, a launch id of at most 128 characters, a project root of at most 4096.
52
+ if (hello.session !== undefined && (typeof hello.session !== "string" || hello.session.length === 0 || hello.session.length > 64)) return undefined;
53
+ if (hello.claudeSessionId !== undefined && !isClaudeSessionUuid(hello.claudeSessionId)) return undefined;
54
+ if (hello.launchId !== undefined && (typeof hello.launchId !== "string" || hello.launchId.length === 0 || hello.launchId.length > 128)) return undefined;
55
+ if (hello.projectRoot !== undefined && (typeof hello.projectRoot !== "string" || hello.projectRoot.length === 0 || hello.projectRoot.length > 4096)) return undefined;
56
+ for (const key of ["permissionTool", "deliveryOnly"] as const) if (hello[key] !== undefined && typeof hello[key] !== "boolean") return undefined;
57
+ if (typeof hello.token !== "string") return undefined;
58
+ const given = Buffer.from(hello.token), expected = Buffer.from(token);
59
+ if (given.length !== expected.length || !timingSafeEqual(given, expected)) return undefined;
60
+ return value as Hello;
61
+ }
62
+
63
+ /** The owner of a process id, from `ps`, asked without blocking the daemon's loop; undefined when the process is gone or ps is unavailable. */
64
+ function uidOfProcess(pid: number): Promise<number | undefined> {
65
+ return new Promise(resolve => {
66
+ execFile("ps", ["-o", "uid=", "-p", String(pid)], { encoding: "utf8", timeout: 2000 }, (error, stdout) => {
67
+ const uid = error ? NaN : Number(String(stdout).trim());
68
+ resolve(Number.isSafeInteger(uid) ? uid : undefined);
69
+ });
70
+ });
71
+ }
72
+
73
+ /** `0700`, owned by this user, a real directory: the one rule for the run directory and the project directory. */
74
+ function privateDirectory(path: string, uid: number | undefined, label: string): string | undefined {
75
+ const info = lstatSync(path);
76
+ if (!info.isDirectory() || info.isSymbolicLink()) return `the MCP ${label} ${path} is not a plain directory; remove it and restart the hub`;
77
+ if (uid !== undefined && info.uid !== uid) return `the MCP ${label} ${path} belongs to another user; remove it and restart the hub`;
78
+ if ((info.mode & 0o077) !== 0) return `the MCP ${label} ${path} is group or world accessible (mode ${(info.mode & 0o777).toString(8)}); run chmod 700 ${path} and restart the hub`;
79
+ return undefined;
80
+ }
81
+
82
+ /** Create-or-verify without a check first: a second hub creating the same directory is not an error, and whoever made it, `privateDirectory` judges what is there. */
83
+ function ensurePrivateDirectory(path: string, uid: number | undefined, label: string): string | undefined {
84
+ try { mkdirSync(path, { mode: 0o700 }); chmodSync(path, 0o700); }
85
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }
86
+ return privateDirectory(path, uid, label);
87
+ }
88
+
89
+ /** What a probe of the socket path found: a hub that connected, a path nobody serves (only ECONNREFUSED or ENOENT), or a result that cannot be judged (a timeout, EACCES or any other error), which keeps the refusal and names itself. */
90
+ type Probe = { state: "live" } | { state: "stale" } | { state: "unknown"; detail: string };
91
+ function answers(path: string): Promise<Probe> {
92
+ return new Promise(resolve => {
93
+ const probe = createConnection(path);
94
+ const done = (result: Probe) => { probe.destroy(); resolve(result); };
95
+ probe.once("connect", () => done({ state: "live" }));
96
+ probe.once("error", error => {
97
+ const code = (error as NodeJS.ErrnoException).code ?? "error";
98
+ done(["ECONNREFUSED", "ENOENT"].includes(code) ? { state: "stale" } : { state: "unknown", detail: code });
99
+ });
100
+ probe.setTimeout(1000, () => done({ state: "unknown", detail: "no answer within 1 s" }));
101
+ });
102
+ }
103
+
104
+ /** The refusal for a probe that found a live hub or could not judge the path; undefined when the path is stale. */
105
+ function probeRefusal(path: string, probe: Probe): string | undefined {
106
+ if (probe.state === "live") return `another hub already serves the MCP socket ${path}; stop it before starting this one`;
107
+ if (probe.state === "unknown") return `the MCP socket ${path} could not be probed (${probe.detail}) and was left in place; check the socket's permissions or which process listens on it, then restart the hub`;
108
+ return undefined;
109
+ }
110
+
111
+ /** Recoverers of one socket path in this process, so they run one after another. */
112
+ const recovering = new Map<string, Promise<void>>();
113
+
114
+ export async function startMcpEndpoint(options: McpEndpointOptions): Promise<McpEndpointResult> {
115
+ const uid = options.daemonUid ?? (typeof process.getuid === "function" ? process.getuid() : undefined);
116
+ const uidOf = options.uidOfPid ?? uidOfProcess;
117
+ const run = join(options.home, "run"), directory = join(run, options.projectId), path = join(directory, "mcp.sock");
118
+ // The socket path limit (104 on macOS, 108 on Linux) is checked before anything is created.
119
+ if (Buffer.byteLength(path) > 100) return { ok: false, refusal: `the MCP socket path ${path} is longer than the platform allows; set AGENTHUB_HOME to a shorter path and restart the hub` };
120
+ try {
121
+ mkdirSync(options.home, { recursive: true, mode: 0o700 });
122
+ const refused = ensurePrivateDirectory(run, uid, "run directory") ?? ensurePrivateDirectory(directory, uid, "socket directory");
123
+ if (refused) return { ok: false, refusal: refused };
124
+ } catch (error) { return { ok: false, refusal: `the MCP socket directory ${directory} could not be prepared (${(error as NodeJS.ErrnoException).code ?? "error"}); fix its permissions and restart the hub` }; }
125
+
126
+ const sessions = new Map<string, McpSession>(), sockets = new Set<Socket>();
127
+ const server: Server = createServer(socket => {
128
+ sockets.add(socket);
129
+ socket.once("close", () => sockets.delete(socket));
130
+ let buffer = Buffer.alloc(0), session: McpSession | undefined, closed = false, served: McpSessionServer | undefined;
131
+ const close = () => { closed = true; socket.destroy(); };
132
+ const timer = setTimeout(close, options.helloTimeoutMs ?? HELLO_MS);
133
+ timer.unref?.();
134
+ socket.on("error", () => close());
135
+ socket.on("close", () => { closed = true; clearTimeout(timer); served?.close(); if (session) { sessions.delete(session.id); options.onClose?.(session); } });
136
+ // Lines are handled one at a time: the uid check awaits, and bytes that arrive meanwhile wait in the buffer.
137
+ let draining = false;
138
+ const drain = async () => {
139
+ if (draining) return;
140
+ draining = true;
141
+ try {
142
+ for (;;) {
143
+ if (closed) return;
144
+ const end = buffer.indexOf(0x0a);
145
+ if (end < 0) { if (buffer.length > (session ? LINE_BYTES : HELLO_BYTES)) close(); return; }
146
+ const line = buffer.subarray(0, end).toString("utf8");
147
+ buffer = buffer.subarray(end + 1);
148
+ if (!session) {
149
+ // Nothing but a valid hello from this user's own process opens a session; every other outcome closes with no reply.
150
+ const hello = line.length <= HELLO_BYTES ? validateHello(line, options.token) : undefined;
151
+ if (!hello) return close();
152
+ const owner = await uidOf(hello.pid);
153
+ if (closed || socket.destroyed) return;
154
+ if (uid !== undefined && owner !== uid) return close();
155
+ clearTimeout(timer);
156
+ const label = options.accountLabel(hello.home, hello.peer);
157
+ session = { id: randomUUID(), peer: hello.peer, mode: hello.mode, pid: hello.pid, ppid: hello.ppid, ...(label ? { accountLabel: label } : {}), connectedAt: Date.now() };
158
+ sessions.set(session.id, session);
159
+ options.onSession?.(session, socket);
160
+ if (options.serve) {
161
+ served = await options.serve(session, hello, text => { if (closed || socket.destroyed) return false; socket.write(`${text}\n`); return true; }, close);
162
+ // The serve step wrote its own reason; end the connection after it so the line is flushed.
163
+ if (!served) { closed = true; socket.end(); return; }
164
+ // The connection may have closed while the session was admitted: the close handler ran before `served` existed.
165
+ if (closed) { served.close(); return; }
166
+ }
167
+ continue;
168
+ }
169
+ if (served) { served.handle(line); continue; }
170
+ // Without a `serve` step every request is answered with an error and a notification is dropped.
171
+ let id: unknown = null, isRequest = false;
172
+ try { const message = JSON.parse(line); if (message && typeof message === "object" && "id" in message && message.method !== undefined) { id = message.id; isRequest = true; } } catch { isRequest = true; }
173
+ if (isRequest) socket.write(`${JSON.stringify({ jsonrpc: "2.0", id, error: { code: -32601, message: "not served yet" } })}\n`);
174
+ }
175
+ } finally { draining = false; }
176
+ };
177
+ socket.on("data", chunk => {
178
+ if (closed) return;
179
+ const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
180
+ // The same bound drain() applies to one line also holds while it awaits the uid check: a hello plus one request before the session, two lines after it.
181
+ if (buffer.length + bytes.length > (session ? LINE_BYTES + LINE_BYTES : HELLO_BYTES + LINE_BYTES)) return close();
182
+ buffer = Buffer.concat([buffer, bytes]);
183
+ void drain();
184
+ });
185
+ });
186
+
187
+ const bind = () => new Promise<void>((resolve, reject) => { server.once("error", reject); server.listen(path, () => { server.off("error", reject); resolve(); }); });
188
+ try { await bind(); }
189
+ catch (error) {
190
+ // bind() is the claim, and an existing path is replaced in one case only: a daemon that holds its project's fixed control port (`exclusiveOwner`) is the one process that can create this
191
+ // socket, so no second recoverer exists; it still refuses anything that answers, is not a socket of this user, or changed between the two looks (#329, #1780 T2a).
192
+ if ((error as NodeJS.ErrnoException).code !== "EADDRINUSE")
193
+ return { ok: false, refusal: `the MCP socket ${path} could not be opened (${(error as NodeJS.ErrnoException).code ?? "error"}); check the directory and restart the hub` };
194
+ // Recoverers in this process take turns: a second one looks only after the first has bound, and then finds a socket that answers. A recoverer in another process cannot exist; the port is the lock.
195
+ const previous = recovering.get(path) ?? Promise.resolve();
196
+ let release = () => {};
197
+ const mine = new Promise<void>(resolve => { release = resolve; });
198
+ recovering.set(path, mine);
199
+ await previous;
200
+ try {
201
+ const found = probeRefusal(path, await answers(path));
202
+ if (found) return { ok: false, refusal: found };
203
+ const stale = `a stale MCP socket ${path} is left from a hub that did not stop cleanly; delete that file and restart the hub`;
204
+ if (!options.exclusiveOwner) return { ok: false, refusal: stale };
205
+ try {
206
+ const first = lstatSync(path);
207
+ if (!first.isSocket() || (uid !== undefined && first.uid !== uid)) return { ok: false, refusal: stale };
208
+ const again = probeRefusal(path, await answers(path));
209
+ if (again) return { ok: false, refusal: again };
210
+ const second = lstatSync(path);
211
+ if (second.ino !== first.ino || second.dev !== first.dev) return { ok: false, refusal: stale };
212
+ unlinkSync(path);
213
+ } catch { return { ok: false, refusal: stale }; }
214
+ // The file is gone: a failed retry is its own error, not the stale-file instruction.
215
+ try { await bind(); }
216
+ catch (error) { return { ok: false, refusal: `the MCP socket ${path} could not be opened after replacing a stale file (${(error as NodeJS.ErrnoException).code ?? "error"}); check the directory and restart the hub` }; }
217
+ } finally { release(); if (recovering.get(path) === mine) recovering.delete(path); }
218
+ options.log(`mcp endpoint replaced a stale socket at ${path}`);
219
+ }
220
+ try { chmodSync(path, 0o600); } catch { server.close(); return { ok: false, refusal: `the MCP socket ${path} could not be made private; check the directory and restart the hub` }; }
221
+ options.log(`mcp endpoint listening on ${path}`);
222
+ return { ok: true, endpoint: {
223
+ path, sessions: () => [...sessions.values()],
224
+ stop: () => new Promise<void>(resolve => { for (const socket of sockets) socket.destroy(); server.close(() => resolve()); }),
225
+ } };
226
+ }
@@ -0,0 +1,181 @@
1
+ // #1780 T2a-2b: the bridge's tools/call translation, moved out of `src/adapters/claude-channel.ts` so the daemon's MCP endpoint can run the same code. Every control request, refusal text and result shape is the bridge's;
2
+ // only the reads of the bridge's module state go through an explicit `McpToolCallState` the caller builds (its control client, detach reason, inbox buffer, pending counts and launch facts). No module-level state.
3
+ import { renderHeldInbox } from "./delivery-public.ts";
4
+ import { renderHeldHint } from "./delivery-hints.ts";
5
+ import { frame, sanitize, type Envelope } from "./envelope.ts";
6
+ import { IMPLEMENTER_HUB_TOOL_NAMES, CONDUCTOR_TOOL_NAMES, TASK_TOOL_NAMES } from "./hub-tools.ts";
7
+ import { acceptsNativePermissionRequest, buildNativePermissionProbe, NATIVE_PERMISSION_PROBE_MAX_PER_LAUNCH } from "./native-permission-request.ts";
8
+ import { toolWriteOperation } from "./tool-request.ts";
9
+ import { INVOCATION_CONTROL_TIMEOUT_MS, QUESTION_CONTROL_TIMEOUT_MS, type ControlClient } from "./control-client.ts";
10
+
11
+ export const text = (s: string) => ({ content: [{ type: "text" as const, text: s }] });
12
+ /** Marks a tool result whose text already states the queued count (#221), so the fresh-count block does not repeat it. Symbol keys never reach the client. */
13
+ const QUEUED_COUNTED = Symbol("queuedCounted");
14
+ /** Marks an inbox result that already renders its own bounded held/accepted delivery metadata. */
15
+ const HELD_HINT_INCLUDED = Symbol("heldHintIncluded");
16
+ const heldMetadataUnavailable = (value: unknown): boolean => !!value && typeof value === "object" && !Array.isArray(value)
17
+ && Object.keys(value).length === 1 && (value as { unavailable?: unknown }).unavailable === true;
18
+ const heldMetadataNeedsReviewOnly = (value: unknown): boolean => {
19
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
20
+ const held = value as { count?: unknown; rows?: unknown; truncated?: unknown };
21
+ return Number.isSafeInteger(held.count) && (held.count as number) > 0 && held.truncated === false && Array.isArray(held.rows) && held.rows.length > 0
22
+ && held.rows.every(row => !!row && typeof row === "object" && !Array.isArray(row)
23
+ && ((row as { state?: unknown }).state === undefined || (row as { state?: unknown }).state === "needs_review"));
24
+ };
25
+
26
+ /** What the translation reads of its session. A getter reads the live value at the call, as the bridge's module variables were. */
27
+ export interface McpToolCallState {
28
+ readonly hub: Pick<ControlClient, "request" | "standby" | "features"> | undefined;
29
+ readonly detached: string | undefined;
30
+ offline(): string;
31
+ offlineToolResult(suffix?: string): ReturnType<typeof text> | { isError: true; content: ReturnType<typeof text>["content"] };
32
+ readonly unidentified: boolean; readonly own: boolean; readonly sessionJoin: boolean;
33
+ sessionSupported(): boolean;
34
+ readonly permissionTool: boolean; readonly toolsMode: boolean; readonly channel: boolean; readonly deliveryOnly: boolean; readonly peerId: string;
35
+ invalidPermissionAttempts: number;
36
+ readonly inbox: string[];
37
+ pendingQueued: { queued: number; important: number } | undefined;
38
+ readonly HELD: string; readonly NO_PROJECT: string; readonly NO_SESSION_SUPPORT: string; readonly UNIDENTIFIED: string;
39
+ }
40
+
41
+ export async function hubToolCall(s: McpToolCallState, req: { params: { name: string; arguments?: Record<string, unknown> } }, signal?: AbortSignal) {
42
+ const { name, arguments: args } = req.params;
43
+ if (s.hub?.standby) return text(s.detached ?? s.HELD);
44
+ if (s.unidentified) return { ...text(s.UNIDENTIFIED), isError: true };
45
+ if (!s.own) return { ...text(s.NO_PROJECT), isError: true };
46
+ if (s.sessionJoin && !s.sessionSupported()) return { ...text(s.NO_SESSION_SUPPORT), isError: true };
47
+ if (s.permissionTool && !IMPLEMENTER_HUB_TOOL_NAMES.includes(name)) return { ...text("tool unavailable to this owned implementer child"), isError: true };
48
+ if (name === "hub_permission_request") {
49
+ const deny = (message: string) => text(JSON.stringify({ behavior: "deny", message }));
50
+ if (!s.permissionTool || !s.hub) return deny("hub permission unavailable");
51
+ if (!acceptsNativePermissionRequest(args)) {
52
+ // Diagnostic validation only: its response can never authorize this invalid native request.
53
+ if (++s.invalidPermissionAttempts <= NATIVE_PERMISSION_PROBE_MAX_PER_LAUNCH) {
54
+ const probe = buildNativePermissionProbe(args);
55
+ if (probe) try { await s.hub.request(probe, 1000); } catch { /* Old or unavailable hubs still deny locally. */ }
56
+ }
57
+ return deny("invalid native permission request");
58
+ }
59
+ try {
60
+ // Only this fixed client capability permits host wrapper grants; older clients keep person approval.
61
+ const res = await s.hub.request({ t: "permission_request", tool: args?.tool_name, input: args?.input, wrapperProtocol: 1 }, 3_605_000);
62
+ if (res.ok !== true || res.behavior !== "allow") return deny(typeof res.message === "string" ? res.message : "permission denied");
63
+ if (res.wrapperProtocol !== undefined && res.wrapperProtocol !== 1) return deny("unsupported host execution response");
64
+ const updated = res.wrapperProtocol === 1 ? res.updatedInput : undefined;
65
+ if (res.wrapperProtocol === 1 && (args?.tool_name !== "Bash" || !updated || typeof updated !== "object" || Array.isArray(updated) || typeof updated.command !== "string")) return deny("invalid host execution response");
66
+ return text(JSON.stringify({ behavior: "allow", updatedInput: updated ?? args?.input }));
67
+ } catch { return deny("hub permission unavailable"); }
68
+ }
69
+ if (name === "hub_delivery_done" && s.channel) {
70
+ if (!s.hub) return s.offlineToolResult();
71
+ const a = args ?? {};
72
+ const result = await s.hub.request({ t: "delivery_complete", deliveryId: a.delivery_id, generation: a.delivery_generation });
73
+ if (result.outcome === "unknown") return text(typeof result.error === "string" ? result.error : "Write outcome unknown. Inspect the delivery before another write; call again only if it is absent, with the same delivery id and generation.");
74
+ return text(result.ok ? "delivery completed" : `not completed: ${result.error}`);
75
+ }
76
+ if (name === "hub_inbox" && (!s.toolsMode || s.permissionTool)) {
77
+ let remote: string[] = [], notice = "", polling = "", counted = false, heldHint = "", metadataWarning = "", heldBodies = "", heldMetadata: unknown;
78
+ if (s.hub) {
79
+ try {
80
+ const res = await s.hub.request({ t: "inbox" });
81
+ heldMetadata = res.held;
82
+ try { heldBodies = renderHeldInbox(res.heldRead); } catch { heldBodies = "Held message bodies are unavailable; inspect the queue before repeating an action."; }
83
+ const metadataUnavailable = heldMetadataUnavailable(res.held);
84
+ heldHint = renderHeldHint(res.held, Date.now(), !s.deliveryOnly);
85
+ if (metadataUnavailable) metadataWarning = `Delivery confirmation metadata is unavailable; inspect ahub queue list --peer ${sanitize(s.peerId)} before deciding whether anything is waiting.`;
86
+ if (!res.ok) notice = `not read: ${res.error}`;
87
+ else if (!Array.isArray(res.envs)) notice = "not read: malformed daemon inbox response";
88
+ else {
89
+ s.pendingQueued = { queued: typeof res.waiting === "number" ? res.waiting : 0, important: typeof res.waitingImportant === "number" ? res.waitingImportant : 0 };
90
+ remote = (res.envs as Envelope[]).map(frame);
91
+ if (!heldHint && !heldBodies && Number.isSafeInteger(res.pollingAdvice?.count) && res.pollingAdvice.count >= 3 && Number.isSafeInteger(res.pollingAdvice?.minutes) && res.pollingAdvice.minutes >= 0 && res.pollingAdvice.minutes <= 10) polling = `[polling detected] ${res.pollingAdvice.count} empty reads in ${res.pollingAdvice.minutes} min with no assigned work: end your turn`;
92
+ // #713: a pull drains what fits one read; what is left is said plainly, with what to do about it. The count already says how many remain, so the pending hint adds only the important ones (#221).
93
+ if (res.waiting) { notice = `(${res.waiting} more waiting: call hub_inbox again before you start work)`; counted = true; }
94
+ }
95
+ } catch { notice = "not read: daemon inbox unavailable; inspect the connection before another read"; }
96
+ } else notice = s.offline();
97
+ // Only pushes without a journal delivery id enter this buffer. Pull completion belongs to the daemon.
98
+ const out = [...s.inbox.splice(0), ...remote];
99
+ if (notice) out.push(notice);
100
+ if (heldHint) out.push(heldHint);
101
+ if (metadataWarning) out.push(metadataWarning);
102
+ let body = out.length ? out.join("\n\n") : heldBodies ? "(no queued hub messages)" : "(no queued hub messages)\nNothing is waiting. Do not poll: if you have no assigned task, report and end your turn; new work waits here for your next boundary.";
103
+ if (out.length === 1 && out[0] === heldHint && heldHint && heldMetadataNeedsReviewOnly(heldMetadata)) {
104
+ body = `(no queued hub messages)\n\n${body}`;
105
+ }
106
+ const result = text(polling ? `${body}\n${polling}` : body);
107
+ if (heldBodies) result.content.push({ type: "text", text: heldBodies });
108
+ if (counted) Object.defineProperty(result, QUEUED_COUNTED, { value: true });
109
+ if (heldHint || heldBodies || metadataWarning) Object.defineProperty(result, HELD_HINT_INCLUDED, { value: true });
110
+ return s.detached === "detached by the person" ? { ...result, isError: true } : result;
111
+ }
112
+ if (name === "hub_send") {
113
+ const { text: body, to, reply_to } = (args ?? {}) as { text?: string; to?: string[]; reply_to?: string };
114
+ if (!s.hub) return s.offlineToolResult(" Message not sent.");
115
+ const res = await s.hub.request({ t: "send", body, to, reply_to });
116
+ if (!res.ok) return text(`not sent: ${res.error}`);
117
+ if (res.recorded) return text("recorded only ([FYI]): it is on the hub console and log, and no peer spent a turn on it");
118
+ if (res.dropped === "hop") return text(res.notice);
119
+ const sent = `sent to: ${res.targets.join(", ") || "(no other peers attached)"}`;
120
+ return text(typeof res.notice === "string" ? `${sent}; ${res.notice}` : sent);
121
+ }
122
+ if (TASK_TOOL_NAMES.has(name) || CONDUCTOR_TOOL_NAMES.has(name)) {
123
+ if (!s.hub) return s.offlineToolResult();
124
+ // #445 C2: a daemon that predates invocations would answer with a generic unknown-operation error; say what is missing instead.
125
+ if (name === "hub_invoke" && !s.hub.features.includes("invocation")) return { ...text("error: this hub does not support invocations; restart it with the current agent-hub release (ahub restart)"), isError: true };
126
+ // #1053: a hub that predates questions would answer "unknown operation"; say what is missing, and what to do meanwhile.
127
+ if (name === "hub_ask" && !s.hub.features.includes("questions")) return { ...text("error: this hub does not support questions; restart it with the current agent-hub release (ahub restart), or ask the person with hub_send"), isError: true };
128
+ const rawArgs = args ?? {}, operation = toolWriteOperation({ t: "task", op: name });
129
+ let taskArgs = rawArgs, requestId: unknown;
130
+ if (operation && Object.hasOwn(rawArgs, "request_id")) {
131
+ requestId = rawArgs.request_id;
132
+ const { request_id: _requestId, ...withoutRequestId } = rawArgs;
133
+ taskArgs = withoutRequestId;
134
+ }
135
+ const res = await s.hub.request({ t: "task", op: name, args: taskArgs, ...(requestId !== undefined ? { requestId } : {}) }, name === "hub_invoke" ? INVOCATION_CONTROL_TIMEOUT_MS : name === "hub_ask" ? QUESTION_CONTROL_TIMEOUT_MS : undefined, name === "hub_invoke" || name === "hub_ask" ? signal : undefined);
136
+ if (res.outcome === "unknown") return text(typeof res.error === "string" ? res.error : "Write outcome unknown. Inspect the task before another write; call again only if it is absent, with the same request_id and arguments.");
137
+ return { ...text(res.ok ? res.text : `error: ${res.error}`), ...(res.ok ? {} : { isError: true }) };
138
+ }
139
+ return text(`unknown tool ${name}`);
140
+ }
141
+
142
+ /** Fresh own-peer counts accompany all tool modes; only old plain sessions use advisory queued nudges. */
143
+ export async function withPendingHint<T>(s: McpToolCallState, result: T, recommendInbox = true): Promise<T> {
144
+ if (s.hub?.standby) return result;
145
+ const r = result as { content?: { type: string; text?: string }[] };
146
+ const appendQueued = (hint: string) => {
147
+ // Preserve the inbox's existing first-block refusal/readback contract; counts remain separate advisory text.
148
+ if (!recommendInbox) { r.content?.push({ type: "text", text: hint }); return; }
149
+ const last = r.content?.[r.content.length - 1];
150
+ if (last?.type === "text" && typeof last.text === "string") last.text += `\n\n${hint}`;
151
+ else r.content?.push({ type: "text", text: hint });
152
+ };
153
+ if (s.hub && r.content) {
154
+ let freshCounts = false;
155
+ let hint = "";
156
+ try {
157
+ const response = await s.hub.request({ t: "delivery_holds" }, 1000);
158
+ // A hold that refuses pulls (#221): hub_inbox would only be refused again, so the counts stay and the advice goes.
159
+ hint = response?.ok ? renderHeldHint(response.held, Date.now(), !s.deliveryOnly) : "";
160
+ if (response?.ok && Number.isSafeInteger(response.queued) && response.queued >= 0
161
+ && Number.isSafeInteger(response.important) && response.important >= 0 && response.important <= response.queued) {
162
+ freshCounts = true;
163
+ s.pendingQueued = undefined; // A current zero must never resurrect an earlier queued nudge.
164
+ if (response.important > 0) {
165
+ const next = !recommendInbox || hint ? "" : s.toolsMode
166
+ ? ": use hub_inbox on a pull-capable peer session; otherwise finish the current turn to receive queued deliveries"
167
+ : ": call hub_inbox before starting long local work";
168
+ // One queued count per result (#221): a hub_inbox result that already says how many remain unread adds only the important count.
169
+ const counted = (result as { [QUEUED_COUNTED]?: boolean })[QUEUED_COUNTED] === true;
170
+ appendQueued(counted ? `(${response.important} important hub message(s) waiting${next})` : `(${response.queued} queued hub message(s), ${response.important} important hub message(s) waiting${next})`);
171
+ }
172
+ }
173
+ if (hint && (result as { [HELD_HINT_INCLUDED]?: boolean })[HELD_HINT_INCLUDED] !== true) r.content.push({ type: "text", text: hint });
174
+ } catch { /* advisory metadata can never change a saved tool result or its effect classification */ }
175
+ // A pre-#493 daemon sends held rows without counts; the legacy nudge must not advise a read the hold refuses (#221).
176
+ if (!freshCounts && !hint && recommendInbox && !s.channel && !s.toolsMode && s.pendingQueued && s.pendingQueued.important > 0) {
177
+ appendQueued(`(${s.pendingQueued.important} important hub message(s) waiting: call hub_inbox before starting long local work)`);
178
+ }
179
+ }
180
+ return result;
181
+ }
@@ -262,3 +262,5 @@ export function consoleOperationalSnapshot(rows: unknown) {
262
262
  };
263
263
  return Object.freeze({ pollMs: read(CONSOLE_POLL_SETTING), noticeMs: read(CONSOLE_NOTICE_SETTING), historyLimit: read(CONSOLE_HISTORY_SETTING), pendingStreamLimit: read(CONSOLE_PENDING_STREAM_SETTING), attentionLimit: read(CONSOLE_ATTENTION_SETTING) });
264
264
  }
265
+
266
+ export const ESCALATE_AFTER = 3;
@@ -8,6 +8,12 @@
8
8
  */
9
9
  export const ORCA_LAUNCHER_ENV: readonly string[] = Object.freeze(["ORCA_CLI_COMMAND", "ORCA_DEV_REPO_ROOT", "ORCA_TERMINAL_HANDLE", "ORCA_WORKTREE_ID"]);
10
10
 
11
+ /**
12
+ * #1811: the pane identity an Orca agent process carries beside the launcher's four names. Recorded with a launch and never
13
+ * read to decide anything about Orca itself, so it stays out of the launcher list; `withoutOrcaEnv` still scrubs it.
14
+ */
15
+ export const ORCA_PANE_ENV = Object.freeze({ paneKey: "ORCA_PANE_KEY", tabId: "ORCA_TAB_ID", workspaceId: "ORCA_WORKSPACE_ID" } as const);
16
+
11
17
  /** Every variable an Orca terminal exports: the launcher's four and the rest of the pane's environment. */
12
18
  export const isOrcaEnvName = (name: string): boolean => name.startsWith("ORCA_");
13
19
 
@@ -0,0 +1,84 @@
1
+ /**
2
+ * #1811 T2: a peer whose delivery stays unaccepted in an Orca pane may be waiting for the person at a prompt. The hub asks
3
+ * Orca for that pane's state with one bounded read of a public command and shows `blocked` or `waiting` as an Attention item.
4
+ * It reads only (`orca agent list --json --worktree id:<worktree id>`) and never answers the prompt.
5
+ *
6
+ * Shape verified on Orca 1.4.283 (docs/verification/2026-12-01-1811-orca-agent-list.md): `result.agents[]` rows carry `paneKey`
7
+ * (the pane's `tabId:leafId`), `state` (`working`, `blocked`, `waiting` or `done`) and `worktreeId`; the `--worktree` selector
8
+ * takes `id:<worktreeId>`, which the launch record holds.
9
+ */
10
+
11
+ type OrcaPaneState = "blocked" | "waiting";
12
+ interface OrcaRead { status: number; stdout: string }
13
+ /** Runs the Orca CLI with `argv`; rejects or answers a nonzero status when it cannot. Replaced in tests. */
14
+ type OrcaAgentRunner = (argv: readonly string[], boundMs: number) => Promise<OrcaRead>;
15
+ interface WatchedPane { handle: string; paneKey: string; worktreeId: string }
16
+ interface BlockedPane { peer: string; handle: string; state: OrcaPaneState; since: number }
17
+
18
+ /** How long a delivery stays unaccepted before the pane is asked, the bound of one read, and the least gap between two reads for a peer. */
19
+ const PANE_UNACCEPTED_MS = 120_000;
20
+ const PANE_READ_BOUND_MS = 5_000;
21
+ const PANE_READ_GAP_MS = 60_000;
22
+
23
+ /** The state of the agent in `paneKey`, or undefined when the answer has no such row or is not the shape read here. */
24
+ function paneStateOf(stdout: string, paneKey: string): OrcaPaneState | "other" | undefined {
25
+ let value: unknown;
26
+ try { value = JSON.parse(stdout); } catch { return undefined; }
27
+ const result = (value as { result?: { agents?: unknown } } | null)?.result;
28
+ if (!result || !Array.isArray(result.agents)) return undefined;
29
+ const rows = result.agents.filter((row): row is { paneKey: string; state?: unknown } => !!row && typeof row === "object" && (row as { paneKey?: unknown }).paneKey === paneKey);
30
+ if (rows.length !== 1) return undefined; // none or ambiguous: Orca does not say
31
+ const state = rows[0]!.state;
32
+ return state === "blocked" || state === "waiting" ? state : "other";
33
+ }
34
+
35
+ /** The default runner: the public CLI, killed at the bound, never run when its executable is not on the path. */
36
+ export function orcaAgentRunner(executable: () => string): OrcaAgentRunner {
37
+ return async (argv, boundMs) => {
38
+ const bin = executable();
39
+ if (!Bun.which(bin)) throw new Error("orca is not on the path");
40
+ const child = Bun.spawn([bin, ...argv], { stdout: "pipe", stderr: "ignore" });
41
+ // The bound covers the output too: a killed process whose child keeps the pipe open must not hold the read.
42
+ let timer: ReturnType<typeof setTimeout> | undefined;
43
+ const bound = new Promise<never>((_, reject) => { timer = setTimeout(() => { child.kill(); reject(new Error("orca read timed out")); }, boundMs); });
44
+ try { return await Promise.race([Promise.all([child.stdout.text(), child.exited]).then(([stdout, status]) => ({ stdout, status })), bound]); }
45
+ finally { clearTimeout(timer); }
46
+ };
47
+ }
48
+
49
+ export class OrcaPaneWatch {
50
+ private readonly lastRead = new Map<string, number>();
51
+ private readonly blockedBy = new Map<string, BlockedPane>();
52
+ private readonly reading = new Set<string>();
53
+ constructor(private readonly options: { run: OrcaAgentRunner; now?: () => number; unacceptedMs?: number; boundMs?: number; gapMs?: number }) {}
54
+
55
+ /** Whether a delivery queued at `oldestUnacceptedAt` has waited long enough to ask Orca about its pane; the daemon checks it before it reads a launch record. */
56
+ due(oldestUnacceptedAt: number | undefined): boolean {
57
+ return oldestUnacceptedAt !== undefined && (this.options.now ?? Date.now)() - oldestUnacceptedAt >= (this.options.unacceptedMs ?? PANE_UNACCEPTED_MS);
58
+ }
59
+
60
+ /** The panes that wait for the person now, one per peer. */
61
+ blocked(): BlockedPane[] { return [...this.blockedBy.values()]; }
62
+
63
+ /**
64
+ * One peer: `oldestUnacceptedAt` is when its oldest delivery was queued (undefined when none waits) and `pane` its recorded
65
+ * Orca pane (undefined when it has none, which is never read). Settles to nothing on an error, a timeout or any other state.
66
+ */
67
+ async check(peer: string, oldestUnacceptedAt: number | undefined, pane: WatchedPane | undefined): Promise<void> {
68
+ const now = (this.options.now ?? Date.now)();
69
+ if (!pane || oldestUnacceptedAt === undefined || now - oldestUnacceptedAt < (this.options.unacceptedMs ?? PANE_UNACCEPTED_MS)) { this.blockedBy.delete(peer); return; }
70
+ const last = this.lastRead.get(peer);
71
+ if (this.reading.has(peer) || last !== undefined && now - last < (this.options.gapMs ?? PANE_READ_GAP_MS)) return; // keep what the last read said
72
+ this.lastRead.set(peer, now);
73
+ this.reading.add(peer);
74
+ try {
75
+ const answer = await this.options.run(["agent", "list", "--json", "--worktree", `id:${pane.worktreeId}`], this.options.boundMs ?? PANE_READ_BOUND_MS);
76
+ const state = answer.status === 0 ? paneStateOf(answer.stdout, pane.paneKey) : undefined;
77
+ if (state === "blocked" || state === "waiting") {
78
+ const was = this.blockedBy.get(peer);
79
+ this.blockedBy.set(peer, { peer, handle: pane.handle, state, since: was && was.state === state ? was.since : now });
80
+ } else this.blockedBy.delete(peer);
81
+ } catch { this.blockedBy.delete(peer); }
82
+ finally { this.reading.delete(peer); }
83
+ }
84
+ }
package/src/hub/peers.ts CHANGED
@@ -50,6 +50,10 @@ export interface FrontendProxyPort {
50
50
 
51
51
  export interface PeerAdapter {
52
52
  readonly id: PeerId;
53
+ /** Fixed builtin only. Synchronously compare the caller's home in memory. Undefined delegates to the next-launch comparison. */
54
+ compareQuotaHome?(callerHome: string | undefined): "same" | "different" | "unknown" | undefined;
55
+ /** Fixed builtin only. Ask the current process for a bounded quota reading after a saved renewal. */
56
+ readQuotaNow?(): void;
53
57
  /** Live waiting sessions, for display only; ids and pids grant no native identity or authority. */
54
58
  readonly standbySessions?: readonly PeerStandbySession[];
55
59
  /** The current owner's attachment facts, for display only; absent unless a socket is attached and no newer claim is arriving (#1310). */
@@ -110,7 +114,7 @@ export interface PeerAdapter {
110
114
  readonly statusNotice?: { code: "unidentified-cancellation" | "qwen-detached" | "qwen-stalled" | "qwen-deny-quiescence" | "jcode-headless-after-recovery"; message: string };
111
115
  /** Fixed builtins with session.nativeRevert only. Native conversation effects remain in the adapter. */
112
116
  revertTurn?(nativeTurn: string): Promise<void>;
113
- /** #445 C1: what this peer's native source lists right now (a probed version only), or an empty manifest. Never throws for an unprobed version; a transport failure rejects. */
117
+ /** #445 C1: what this peer's native source lists right now (a verified version, or an exact version the person trusted with `ahub agents trust`), or an empty manifest. Never throws for an unprobed version; a transport failure rejects. */
114
118
  capabilityManifest?(): Promise<CapabilityManifest>;
115
119
  /** Leave the roster without stopping a person's terminal. */
116
120
  detachForRoster?(resetMode: PermissionMode): void | Promise<void>;
@@ -1,4 +1,5 @@
1
- import { definitionOf, type ProjectAdapterCatalog, type KindMap } from "../adapters/registry.ts";
1
+ import { builtinPolicyOf as definitionOf } from "../adapters/declaration-data.ts";
2
+ import type { ProjectAdapterCatalog, KindMap } from "../adapters/registry-types.ts";
2
3
  import { isPermissionMode, type PermissionMode } from "./permission-paths.ts";
3
4
  export * from "./permission-paths.ts";
4
5
  export { KIMI_MODE_IDS } from "../adapters/definitions/kimi-native.ts";
@@ -61,6 +61,26 @@ export interface ProjectContext {
61
61
  stateDir: string;
62
62
  }
63
63
 
64
+ /** #1779 T2: what a daemon knows about its project, passed down explicitly. `env` is the environment its children inherit. */
65
+ export interface DaemonProjectContext extends ProjectContext {
66
+ readonly env: NodeJS.ProcessEnv;
67
+ }
68
+
69
+ /** The one place a daemon takes its project identity and child environment from the process; everything below `startDaemon` reads the returned context. */
70
+ export function daemonProjectContext(root: string, stateDir: string, env: NodeJS.ProcessEnv): DaemonProjectContext {
71
+ return Object.freeze({ root, stateDir, env: Object.freeze({ ...env }) });
72
+ }
73
+
74
+ /** A hosted project's context: the host's environment with this project's own state and project directories, never another project's. */
75
+ export function hostedProjectContext(project: ProjectContext, hostEnv: NodeJS.ProcessEnv): DaemonProjectContext {
76
+ return daemonProjectContext(project.root, project.stateDir, { ...hostEnv, ...projectChildEnv(project) });
77
+ }
78
+
79
+ /** The two variables that bind a child process (a tool server, a hook) to this project. */
80
+ export function projectChildEnv(context: ProjectContext): { AGENTHUB_STATE_DIR: string; AGENTHUB_PROJECT_DIR: string } {
81
+ return { AGENTHUB_STATE_DIR: context.stateDir, AGENTHUB_PROJECT_DIR: context.root };
82
+ }
83
+
64
84
  /** Resolve a project and accept an inherited state directory only with an ownership proof. */
65
85
  export function projectContext(cwd: string, env: NodeJS.ProcessEnv = process.env): ProjectContext {
66
86
  const root = projectRoot(cwd);