@staix/agent-hub 0.53.0 → 0.54.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 (88) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +4 -3
  3. package/docs/agent-notes/README.md +1 -1
  4. package/docs/agent-notes/adapters.md +4 -3
  5. package/docs/agent-notes/budget.md +2 -2
  6. package/docs/agent-notes/bus.md +1 -0
  7. package/docs/agent-notes/daemon.md +1 -1
  8. package/docs/agent-notes/models.md +1 -1
  9. package/docs/agent-notes/tests.md +4 -4
  10. package/docs/contracts/companion-cli-v3.json +348 -0
  11. package/docs/design/adapters.md +1 -1
  12. package/docs/design/agent-hub-architecture.md +8 -5
  13. package/docs/design/bus.md +1 -1
  14. package/docs/design/cli-output-inventory.md +2 -2
  15. package/docs/design/model-routes.md +20 -5
  16. package/docs/dogfood.md +7 -3
  17. package/docs/events.md +1 -1
  18. package/docs/memory.md +2 -2
  19. package/docs/operations.md +122 -45
  20. package/docs/quickstart.md +8 -2
  21. package/docs/security.md +11 -7
  22. package/docs/specs/2026-09-19-agent-hub-design.md +5 -3
  23. package/docs/specs/2026-09-19-multi-project-design.md +1 -1
  24. package/docs/specs/2026-12-04-arev-adoption-design.md +3 -3
  25. package/docs/specs/mcp-endpoint.md +1 -1
  26. package/docs/specs/relay-contract.md +38 -0
  27. package/docs/verification/2026-12-06-0.54.0.md +76 -0
  28. package/docs/verification/2026-12-06-codex-0174-reviewer-isolation.md +43 -0
  29. package/docs/verification/2026-12-06-codex-0174-reviewer-tool-call.md +34 -0
  30. package/docs/verification/2026-12-06-compat-codex-capabilities-0.174.0.md +25 -0
  31. package/docs/verification/2026-12-06-compat-pi-1.8.0.md +23 -0
  32. package/docs/verified.json +27 -28
  33. package/package.json +5 -4
  34. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  35. package/plugins/agent-hub/.mcp.json +1 -1
  36. package/plugins/agent-hub/compat.json +5 -3
  37. package/plugins/agent-hub/kimi-hook.js +5 -4
  38. package/plugins/agent-hub/relay-launcher.js +24 -0
  39. package/plugins/agent-hub/server.js +5112 -4737
  40. package/src/adapters/acp.ts +5 -4
  41. package/src/adapters/compat.ts +22 -12
  42. package/src/adapters/definitions/native-cli-preview-pi.ts +2 -1
  43. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  44. package/src/adapters/definitions/native-factories.ts +4 -1
  45. package/src/adapters/local-worker.ts +3 -3
  46. package/src/adapters/pi.ts +26 -7
  47. package/src/adapters/relay-launcher.ts +27 -0
  48. package/src/cli/agents.ts +20 -8
  49. package/src/cli/commands/agents.ts +18 -1
  50. package/src/cli/commands/doctor.ts +18 -4
  51. package/src/cli/commands/launch-line.ts +13 -5
  52. package/src/cli/help.ts +4 -2
  53. package/src/cli/launch-line-plan.ts +82 -0
  54. package/src/cli/pi-steps-warning.ts +14 -0
  55. package/src/hub/accounts.ts +8 -4
  56. package/src/hub/adec-triage.ts +105 -0
  57. package/src/hub/bus.ts +39 -6
  58. package/src/hub/config-apply.ts +1 -1
  59. package/src/hub/config.ts +2 -2
  60. package/src/hub/control/dashboard-messages.ts +221 -0
  61. package/src/hub/control/delivery-messages.ts +356 -0
  62. package/src/hub/control/dispatch.ts +114 -0
  63. package/src/hub/control/operations-messages.ts +269 -0
  64. package/src/hub/control/peer-messages.ts +126 -0
  65. package/src/hub/control/scope.ts +79 -2
  66. package/src/hub/daemon.ts +111 -918
  67. package/src/hub/delivery-hints.ts +2 -0
  68. package/src/hub/delivery-journal.ts +17 -6
  69. package/src/hub/events.ts +2 -1
  70. package/src/hub/host.ts +41 -9
  71. package/src/hub/lifecycle.ts +3 -2
  72. package/src/hub/peers.ts +2 -0
  73. package/src/hub/pi-exit-policy.ts +27 -0
  74. package/src/hub/protocol-window.ts +1 -1
  75. package/src/hub/routing.ts +9 -0
  76. package/src/hub/supervision.ts +33 -6
  77. package/src/hub/tasks-types.ts +4 -1
  78. package/src/hub/tasks.ts +35 -1
  79. package/src/models/route/config.ts +4 -4
  80. package/src/models/route/decision.ts +18 -10
  81. package/src/models/route/runtime.ts +8 -5
  82. package/src/npm-artifact.ts +76 -0
  83. package/src/omniroute/client.ts +6 -0
  84. package/src/pi/extension.ts +5 -2
  85. package/src/pi/install.ts +77 -0
  86. package/src/pi/pin.ts +49 -0
  87. package/templates/adec/README.md +10 -6
  88. package/templates/config.json +1 -1
@@ -0,0 +1,269 @@
1
+ // #1830 S2d: moved onMessage bodies and their private helpers. The daemon owns all state.
2
+ import { compareNextCodexQuotaHome } from "../../adapters/codex-appserver.ts";
3
+ import { isFixedBuiltinDefinition } from "../../adapters/registry.ts";
4
+ import { RoomRotationHoldError } from "../../rooms/commands.ts";
5
+ import { RoomStoreError } from "../../rooms/store.ts";
6
+ import { conductorPeer, publicPeerBudget } from "../conductor.ts";
7
+ import { sanitize } from "../envelope.ts";
8
+ import { QUESTION_SURFACES, questionView } from "../questions.ts";
9
+ import { LIMITS_MAX, USAGE_GROUPS } from "../usage-rollup.ts";
10
+ import type { ReceiptSurface } from "../control/scope.ts";
11
+ import type { UsageGroup } from "../usage-rollup.ts";
12
+ import type { ControlMessage, DaemonScope } from "./scope.ts";
13
+
14
+ const receiptSurface = (value: unknown): ReceiptSurface => (["terminal", "console", "dashboard", "acon"] as const).find(known => known === value) ?? "console";
15
+
16
+ export function roomMessage(scope: DaemonScope, m: ControlMessage): void {
17
+ const { sock, c, msg, reply } = m;
18
+ const client = sock.data;
19
+ const personRoom = c.role === "console";
20
+ const roomCurrent = () => !scope.stopping && !scope.recoveryActive() && !scope.bus.isRecoveryHeld
21
+ && sock.data === client && sock.readyState === WebSocket.OPEN && personRoom;
22
+ const roomFailure = (error?: unknown) => error instanceof RoomRotationHoldError
23
+ ? reply({ ok: false, code: "epoch_rotated_hold_unavailable", error: error.message })
24
+ : reply({ ok: false, error: "room operation refused; check room state, authority and arguments" });
25
+ if (msg.op === "list" || msg.op === "status") {
26
+ if (msg.input !== undefined && (!msg.input || typeof msg.input !== "object" || Array.isArray(msg.input)
27
+ || Object.keys(msg.input).some(key => key !== "name") || (msg.input.name !== undefined && typeof msg.input.name !== "string"))) return roomFailure();
28
+ void scope.roomCommands.rows(msg.input?.name, msg.op === "status").then(rooms => reply({ ok: true, rooms }), error => {
29
+ const roomsUnavailable = scope.roomCommands.unavailable();
30
+ if (roomsUnavailable) reply({ ok: false, code: "rooms_unavailable", roomsUnavailable });
31
+ else roomFailure(error);
32
+ });
33
+ return;
34
+ }
35
+ if (["inbox_list", "inbox_show", "inbox_done", "inbox_discard"].includes(msg.op)) {
36
+ if (!personRoom) return void reply({ ok: false, error: "room inbox is person-only" });
37
+ if (!roomCurrent() || Object.keys(msg).some(key => !["t", "op", "input", "rid"].includes(key))) return roomFailure();
38
+ const input = msg.input;
39
+ if (!input || typeof input !== "object" || Array.isArray(input)) return roomFailure();
40
+ if (msg.op === "inbox_list") {
41
+ if (Object.keys(input).some(key => key !== "name") || (input.name !== undefined && typeof input.name !== "string")) return roomFailure();
42
+ void scope.roomCommands.inboxRows(input.name, roomCurrent).then(inbox => {
43
+ if (!roomCurrent()) return roomFailure();
44
+ reply({ ok: true, inbox });
45
+ }, error => {
46
+ if (!roomCurrent()) return roomFailure();
47
+ if (error instanceof RoomStoreError && error.code === "inbox_list_limit") return reply({ ok: false, code: "inbox_list_limit" });
48
+ roomFailure();
49
+ });
50
+ return;
51
+ }
52
+ if (Object.keys(input).length !== 1 || typeof input.id !== "string" || !Object.hasOwn(input, "id")) return roomFailure();
53
+ const operation = msg.op === "inbox_show" ? scope.roomCommands.inboxShow(input.id, roomCurrent)
54
+ : scope.roomCommands.inboxDispose(input.id, msg.op === "inbox_done" ? "done" : "discard", roomCurrent);
55
+ void operation.then(item => {
56
+ if (!roomCurrent()) return roomFailure();
57
+ if (!item) return reply({ ok: false, code: "inbox_not_found" });
58
+ reply({ ok: true, item });
59
+ if (msg.op !== "inbox_show") scope.roomCommands.retryInboxPending();
60
+ }, roomFailure);
61
+ return;
62
+ }
63
+ if (!personRoom) return void reply({ ok: false, error: "room mutations are person-only" });
64
+ if (!roomCurrent()) return roomFailure();
65
+ if (msg.op === "preview") {
66
+ scope.roomTickets.delete(sock);
67
+ void scope.roomCommands.preview(msg.action, msg.input, roomCurrent).then(preview => {
68
+ if (!roomCurrent()) return roomFailure();
69
+ const ticket = crypto.randomUUID();
70
+ scope.roomTickets.set(sock, { id: ticket, expires: Date.now() + 30_000, preview });
71
+ reply({ ok: true, owner: preview.owner, member: preview.member, ticket, ...(preview.outstanding ? { outstanding: preview.outstanding } : {}) });
72
+ }, roomFailure);
73
+ return;
74
+ }
75
+ if (msg.op === "execute") {
76
+ const ticket = scope.roomTickets.get(sock); scope.roomTickets.delete(sock);
77
+ if (!ticket || msg.ticket !== ticket.id || Date.now() >= ticket.expires
78
+ || typeof msg.confirm !== "string" || !/^[0-9a-f]{16,64}$/.test(msg.confirm) || !ticket.preview.member.startsWith(msg.confirm)
79
+ || Object.keys(msg).some(key => !["t", "op", "ticket", "confirm", "rid"].includes(key))) return roomFailure();
80
+ void ticket.preview.commit().then(result => reply({ ok: true, ...result }), roomFailure);
81
+ return;
82
+ }
83
+ return void reply({ ok: false, error: "unknown room operation" });
84
+ }
85
+
86
+ export function budgetRenewMessage(scope: DaemonScope, m: ControlMessage): void {
87
+ const { c, msg, reply } = m;
88
+ // Authenticate the person before reading even the shape of the optional home field.
89
+ if (c.role !== "console" || c.instructed) {
90
+ return void reply({ t: "budget_renew", ok: false, error: "only the person may renew quota; run ahub budget renew in a person terminal" });
91
+ }
92
+ const peer = typeof msg.peer === "string" && scope.peerIdPattern.test(msg.peer) ? msg.peer : undefined;
93
+ const mode = msg.mode;
94
+ if (!peer || (mode !== "reset" && mode !== "switched")) {
95
+ return void reply({ t: "budget_renew", ok: false, error: "renew requires a peer and exactly one mode; run ahub budget renew <peer> --reset or --switched" });
96
+ }
97
+ const def = scope.definitionOf(peer);
98
+ if (!def) return void reply({ t: "budget_renew", ok: false, error: "unknown peer; choose a peer shown by ahub budget" });
99
+ if (!def.budget || def.budget.quotaExempt) return void reply({ t: "budget_renew", ok: false, error: "this peer has no renewable quota; inspect ahub budget" });
100
+ const account = scope.accountOf(peer);
101
+ const accountBase = def.budget.account;
102
+ const compareHomes = mode === "switched" && scope.definitionOf(accountBase)?.start.daemonPort === "codex-appserver";
103
+ const quotaRuntime = (id: string) => isFixedBuiltinDefinition(scope.definitionOf(id)) ? scope.bus.peers.get(id) : undefined;
104
+ const compare = () => {
105
+ if (!compareHomes) return [];
106
+ const caller = typeof msg.callerHome === "string" ? msg.callerHome : undefined;
107
+ return scope.accountMembers(account).map(id => {
108
+ try {
109
+ const result = quotaRuntime(id)?.compareQuotaHome?.(caller) ?? compareNextCodexQuotaHome(id, caller);
110
+ return { peer: id, result };
111
+ } catch {
112
+ return { peer: id, result: "unknown" as const };
113
+ }
114
+ });
115
+ };
116
+ const refused = (matches: ReturnType<typeof compare>) => {
117
+ const mismatches = matches.filter(match => match.result !== "same");
118
+ if (!mismatches.length) return false;
119
+ reply({ t: "budget_renew", ok: false, homes: mismatches, error: "Codex home differs or could not be verified; quota was not renewed" });
120
+ return true;
121
+ };
122
+ if (scope.recoveryActive() || scope.stopping) return void reply({ t: "budget_renew", ok: false, error: "quota was not renewed during recovery or shutdown; retry when the hub is ready" });
123
+ if (refused(compare())) return;
124
+ const changed = new Error("renewal home comparison changed");
125
+ void scope.budget.renew(peer, mode, () => {
126
+ if (refused(compare())) throw changed;
127
+ }).then(result => {
128
+ const members = scope.accountMembers(account);
129
+ if (scope.definitionOf(accountBase)?.start.daemonPort === "codex-appserver") {
130
+ for (const id of members) {
131
+ try { quotaRuntime(id)?.readQuotaNow?.(); }
132
+ catch { /* The renewal is already saved. A failed read must not replace its reply. */ }
133
+ }
134
+ }
135
+ reply({ t: "budget_renew", ok: true, ...result, ...(compareHomes ? { homeComparison: "same" } : {}),
136
+ ...(compareHomes ? { pending: members.filter(id => scope.definitionOf(id)?.start.daemonPort === "codex-appserver") } : {}),
137
+ ...(mode === "switched" && scope.definitionOf(accountBase)?.transport === "claude-channel" ? {
138
+ softQuota: "Claude quota stays unknown after switching. Its soft gate is off. A hard refusal still pauses Claude, and you can supply a value with ahub budget set.",
139
+ } : {}) });
140
+ }, error => {
141
+ if (error === changed) return;
142
+ const stalled = error instanceof Error && error.message.startsWith("budget renewal was not saved;");
143
+ reply({ t: "budget_renew", ok: false, error: stalled ? error.message : "quota renewal did not finish; inspect ahub budget and retry when the hub is ready" });
144
+ });
145
+ return;
146
+ }
147
+
148
+ export function budgetMessage(scope: DaemonScope, m: ControlMessage): void {
149
+ const { c, msg, reply } = m;
150
+ if (c.role !== "console") {
151
+ if (msg.resume !== undefined || msg.set !== undefined) return void reply({ t: "budget", ok: false, error: "budget mutations are console commands" });
152
+ return void reply({ t: "budget", ok: true, budget: publicPeerBudget(scope.budgetViews(scope.budget.status()), text => scope.tasks.nameable(text)), peers: scope.budgetPeerNotes(), kimiSource: scope.kimiUsage.status(), gate: scope.config.budget.gate, review: scope.reviewerBudgetView() });
153
+ }
154
+ if (scope.recoveryActive()) return void reply({ t: "budget", ok: false, error: "recovery is holding mutations" });
155
+ if (msg.resume) {
156
+ if (!scope.budget.override(String(msg.resume))) return void reply({ t: "budget", ok: false, error: `${msg.resume} is not paused by the budget coordinator` });
157
+ } else if (msg.set) {
158
+ if (c.instructed) return void reply({ t: "budget", ok: false, error: "only the person may set quota; use ahub budget in a person terminal" });
159
+ const used = Number(msg.set.used);
160
+ if (!scope.bus.peers.has(String(msg.set.peer)) && !scope.budget.record(String(msg.set.peer)) && scope.budget.renewalAt(String(msg.set.peer)) === undefined) return void reply({ t: "budget", ok: false, error: `unknown peer: ${msg.set.peer}` });
161
+ if (!(used >= 0 && used <= 1)) return void reply({ t: "budget", ok: false, error: "used must be between 0 and 1" });
162
+ scope.budget.report(String(msg.set.peer), [{ id: msg.set.window === "week" ? "week" : "5h", kind: "manual", used, ...(msg.set.resetsInMs ? { resetsAt: Date.now() + Number(msg.set.resetsInMs) } : {}), source: "ahub budget set" }]);
163
+ }
164
+ return void reply({ t: "budget", ok: true, budget: scope.budgetViews(scope.budget.status()), peers: scope.budgetPeerNotes(), kimiSource: scope.kimiUsage.status(), gate: scope.config.budget.gate, review: scope.reviewerBudgetView() });
165
+ }
166
+
167
+ export function usageMessage(scope: DaemonScope, m: ControlMessage): void {
168
+ const { c, msg, reply } = m;
169
+ // #683 U2: the console, the person and a configured planner read usage; every other agent is refused. Always answered (rid).
170
+ const planner = c.role === "tools" && !!c.peer && !!scope.config.roles[c.peer]?.includes("planner");
171
+ if (c.role !== "console" && !planner) return void reply({ t: "usage", ok: false, error: "usage is read by the person and a configured planner" });
172
+ if (planner && c.peer && scope.turns.get(c.peer)?.private) return void reply({ t: "usage", ok: false, error: "usage is unavailable during a private turn" });
173
+ const op = msg.op === undefined ? "query" : msg.op;
174
+ const num = (v: unknown): number | undefined | null => v === undefined ? undefined : typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : null;
175
+ const since = num(msg.since), until = num(msg.until);
176
+ if (since === null || until === null) return void reply({ t: "usage", ok: false, error: "since and until are epoch milliseconds" });
177
+ if (msg.task !== undefined && !(Number.isSafeInteger(msg.task) && (msg.task as number) > 0)) return void reply({ t: "usage", ok: false, error: "task is a positive task id" });
178
+ try {
179
+ // Fold what the log has now, within a time budget: a hub that has just started is still behind a large log, and an answer built from the
180
+ // part folded so far would read as "no records" for a peer that did use tokens. `behind` says so when the budget ran out (#683 U3).
181
+ // ponytail: catchUp runs synchronously on the daemon loop, so a request on a log far behind stalls it for up to this budget (about 250 ms
182
+ // folds the real 47 MB log). Ceiling: a log several times larger answers `behind` and finishes over the 10 s polls; move the fold to a worker if a stall is felt.
183
+ const behind = !scope.usageRollup.catchUp(250);
184
+ const reply_ = (body: Record<string, unknown>) => reply({ ...body, ...(behind ? { behind: true } : {}) });
185
+ if (op === "limits") {
186
+ if (msg.peer !== undefined && (typeof msg.peer !== "string" || !scope.peerIdPattern.test(msg.peer))) return void reply({ t: "usage", ok: false, error: "peer must be a peer id" });
187
+ if (msg.limit !== undefined && !(Number.isInteger(msg.limit) && (msg.limit as number) >= 1 && (msg.limit as number) <= LIMITS_MAX)) return void reply({ t: "usage", ok: false, error: `limit is an integer from 1 to ${LIMITS_MAX}` });
188
+ const status = scope.budget.status();
189
+ // The pauses the hub holds now: an event-open pause it no longer holds (an `ahub reset` cleared it) is reported as ended, not open.
190
+ const live = new Set(Object.entries(status).filter(([, v]) => v.paused).map(([peer]) => peer));
191
+ return void reply_({ t: "usage", ok: true, op, limits: scope.usageRollup.limits(msg.peer, { ...(msg.limit !== undefined ? { limit: msg.limit as number } : {}), live }), current: publicPeerBudget(status, text => scope.tasks.nameable(text)) });
192
+ }
193
+ if (op === "total") return void reply_({ t: "usage", ok: true, op, total: scope.usageRollup.total() });
194
+ if (op !== "query") return void reply({ t: "usage", ok: false, error: "op is query, limits or total" });
195
+ const by = (msg.by ?? "peer") as UsageGroup;
196
+ if (!USAGE_GROUPS.includes(by)) return void reply({ t: "usage", ok: false, error: `by is one of ${USAGE_GROUPS.join(", ")}` });
197
+ // issue, pr and release are the board's current links of each task (ids only, never a title).
198
+ const board_ = new Map(scope.board.list().map(t => [t.id, t]));
199
+ const links = (id: number) => { const t = board_.get(id); return t ? { ...(t.sdlc?.issue ? { issue: t.sdlc.issue } : {}), ...(t.sdlc?.pr ? { pr: t.sdlc.pr } : {}), ...(t.release ? { release: t.release } : {}) } : undefined; };
200
+ return void reply_({ t: "usage", ok: true, op, usage: scope.usageRollup.query({ by, ...(since !== undefined ? { since } : {}), ...(until !== undefined ? { until } : {}), ...(msg.task !== undefined ? { task: msg.task as number } : {}) }, links) });
201
+ } catch (error) { return void reply({ t: "usage", ok: false, error: `usage unavailable: ${(error as Error).message.slice(0, 120)}` }); }
202
+ }
203
+
204
+ export function permitMessage(scope: DaemonScope, m: ControlMessage): void {
205
+ const { c, msg, reply } = m;
206
+ if (c.role !== "console") return void reply({ t: "permit", ok: false, error: "permit is a console command" });
207
+ return void reply({ t: "permit", ok: scope.permissions.get(String(msg.id))?.done(msg.option ? String(msg.option) : undefined, msg.surface === "console" ? "console" : "terminal") === true });
208
+ }
209
+
210
+ // #1053: a person's answer to a question a peer asked. Console role ONLY, like `permit`: a peer's connection, a `hub_send` body or a tool result that quotes an answer
211
+ // is text and never reaches this case. The reply is always sent (rid), and a refusal names the row's terminal state, never its text.
212
+ export function answerMessage(scope: DaemonScope, m: ControlMessage): void {
213
+ const { c, msg, reply } = m;
214
+ if (c.role !== "console" || msg.instructed !== undefined) {
215
+ if (c.role !== "tools" || !c.peer || conductorPeer(scope.config.roles) !== c.peer) return void reply({ t: "answer", ok: false, error: "answer is a console command unless explicitly instructed through the configured conductor; use ahub console" });
216
+ if (c.toolsOwner || c.externalOwner) return void reply({ t: "answer", ok: false, error: "delegated runs cannot record person answers; use ahub console" });
217
+ if (scope.readOnlyPeer(c.peer)) return void reply({ t: "answer", ok: false, error: "read-only sessions cannot record person answers; use ahub console" });
218
+ if (scope.turns.get(c.peer)?.private || scope.contextPii(c.peer) || scope.reviewObserverInput(c.peer)) return void reply({ t: "answer", ok: false, error: "private or observer context cannot record person answers; use ahub console" });
219
+ const result = scope.questionDesk.instructedAnswer(msg.questionSet, msg.answers, msg.instructed, c.peer);
220
+ return void reply(result.ok ? { t: "answer", ok: true, questionSet: result.row.set, state: result.row.state, actor: c.peer, instructed: true } : { t: "answer", ok: false, error: result.error });
221
+ }
222
+ if (scope.recoveryActive() || scope.stopping) return void reply({ t: "answer", ok: false, error: "recovery or shutdown is holding answers; answer again once the hub is back" });
223
+ const surface = msg.surface !== "conductor" && QUESTION_SURFACES.includes(msg.surface as never) ? msg.surface : "console";
224
+ // The verified identity the acon plugin read from its console's `ActionMeta` rides only on the `acon` surface, one line and bounded, never text of the question or the answer.
225
+ const person = surface === "acon" && typeof msg.person === "string" && msg.person.trim() ? sanitize(msg.person).replace(/\s+/g, " ").trim().slice(0, 200) : undefined;
226
+ const result = scope.questionDesk.answer(msg.questionSet, msg.answers, surface, person);
227
+ return void reply(result.ok ? { t: "answer", ok: true, questionSet: result.row.set, state: result.row.state } : { t: "answer", ok: false, error: `${result.error}; the questions read lists the open ones (console)`, ...(result.state ? { state: result.state } : {}) });
228
+ }
229
+
230
+ // The person's read of the open questions (the console, `ahub`, the panel). Question text is the person's surface only: a tools connection is refused.
231
+ export function questionsMessage(scope: DaemonScope, m: ControlMessage): void {
232
+ const { c, msg, reply } = m;
233
+ if (c.role !== "console") return void reply({ t: "questions", ok: false, error: "questions are shown to the person: use the console" });
234
+ return void reply({ t: "questions", ok: true, questions: scope.questionStore.list(msg.state === "all" ? {} : { state: "open" }, 100).map(questionView), answeredQuestions: scope.instructedQuestionViews() });
235
+ }
236
+
237
+ // #1054: a person's receipt for a result. Console role ONLY, like `permit`: a peer's connection, a `hub_send` body or a tool result that quotes a receipt is text and never reaches
238
+ // the store. A snapshot or a `results` read never writes one. Every message gets a reply (rid), a refusal included.
239
+ export function resultSeenMessage(scope: DaemonScope, m: ControlMessage): void {
240
+ const { c, msg, reply } = m;
241
+ if (c.role !== "console") return void reply({ t: "result_seen", ok: false, error: "result_seen is a console command: only the person marks a result read" });
242
+ const marked = scope.markResultSeen(msg.id, receiptSurface(msg.surface));
243
+ return void reply({ t: "result_seen", ...marked });
244
+ }
245
+
246
+ export function resultsMessage(scope: DaemonScope, m: ControlMessage): void {
247
+ const { c, msg, reply } = m;
248
+ if (c.role !== "console") return void reply({ t: "results", ok: false, error: "results are shown to the person: use the console" });
249
+ if (msg.action === "read-all" || msg.action === "unread-last") {
250
+ return void reply({ t: "results", ...(msg.action === "read-all" ? scope.markAllResultsSeen(receiptSurface(msg.surface)) : scope.unmarkLastResult()) });
251
+ }
252
+ const unreadOnly = msg.unread === true;
253
+ const rows = scope.completionStore.listWithState(100, unreadOnly).map(scope.resultView);
254
+ // Say so when the listing is shorter than the truth, instead of letting "no unread results" hide an older one status still counts.
255
+ const more = unreadOnly ? Math.max(0, scope.completionStore.unreadCount() - rows.length) : 0;
256
+ return void reply({ t: "results", ok: true, results: rows, ...(more ? { more } : {}) });
257
+ }
258
+
259
+ // #1057: the worktree shelf. `worktrees` is a read (facts and the derived partition, never a GitHub call); `worktree_override_set|clear` write the person's
260
+ // park or pin; `worktrees_refresh_prs` is the one explicit action that reads GitHub. Console role only except the read, always answered (rid). The daemon deletes
261
+ // no worktree and no branch: removal is the person's CLI process (AC4).
262
+ export function worktreesRefreshPrsMessage(scope: DaemonScope, m: ControlMessage): void {
263
+ const { c, msg, reply } = m;
264
+ // The read is open to an agent (it can preview a tidy); setting or clearing an override and the GitHub refresh are the person's.
265
+ const person = c.role === "console";
266
+ if (!person && (msg.t !== "worktrees" || c.role !== "tools" || !c.peer || scope.turns.get(c.peer)?.private)) return void reply({ t: msg.t, ok: false, error: "the worktree shelf is the person's: ask them to run ahub worktrees" });
267
+ void scope.worktreeShelf({ t: msg.t, path: msg.path, value: msg.value }).then(reply, () => reply({ t: msg.t, ok: false, error: "the worktree shelf could not be read; inspect the hub log" }));
268
+ return;
269
+ }
@@ -0,0 +1,126 @@
1
+ // #1830 S2d: moved onMessage bodies and their private helpers. The daemon owns all state.
2
+ import { JcodeOptionMismatch, JcodeTuiRefusal, isJcodePeer } from "../../adapters/jcode.ts";
3
+ import { jcodeMcpReady } from "../../cli/jcode-mcp.ts";
4
+ import { terminalLaunchCandidate } from "../../cli/terminal-recovery.ts";
5
+ import { USER } from "../envelope.ts";
6
+ import { valueAt } from "../settings.ts";
7
+ import type { Sock } from "../daemon.ts";
8
+ import type { PeerId } from "../envelope.ts";
9
+ import type { ControlMessage, DaemonScope } from "./scope.ts";
10
+
11
+ const includeRetainedLaunchConfig = (scope: DaemonScope, peer: string, result: Record<string, unknown>): Record<string, unknown> => {
12
+ const values = retainedLaunchConfig(scope, peer);
13
+ return values ? { ...result, retainedLaunchConfig: values } : result;
14
+ };
15
+
16
+ function retainedLaunchConfig(scope: DaemonScope, peer: string): Record<string, unknown> | undefined {
17
+ const keys = scope.definitionOf(peer)?.cli.launchConfigKeys ?? [];
18
+ const pending = scope.retainedConfig.filter(row => keys.some(key => row.key === key || row.key.startsWith(`${key}.`)));
19
+ if (!pending.length) return;
20
+ return Object.fromEntries(pending.map(row => [row.key, valueAt(scope.config, row.key.split("."))]));
21
+ }
22
+
23
+ export function peerTakeoverMessage(scope: DaemonScope, m: ControlMessage): void {
24
+ const { c, msg, reply } = m;
25
+ if (c.role !== "console") return void reply({ t: "peer_takeover", ok: false, error: "peer takeover is a person-only command; run it from the console or a terminal" });
26
+ if (Object.keys(msg).some(key => !["t", "rid", "peer", "standbyId"].includes(key))
27
+ || typeof msg.peer !== "string" || !scope.peerIdPattern.test(msg.peer)
28
+ || msg.standbyId !== undefined && (typeof msg.standbyId !== "string" || msg.standbyId.length > 64 || /[\p{Cc}\p{Cf}]/u.test(msg.standbyId))) {
29
+ return void reply({ t: "peer_takeover", ok: false, error: "peer takeover needs a peer id and optional live standby id; usage: ahub peer takeover <peer> [standby-id]" });
30
+ }
31
+ const peerId = msg.peer as PeerId;
32
+ if (scope.stopping || scope.recoveryActive() || scope.rosterChanging === peerId || scope.requestedPeerStops.has(peerId) || scope.starting.has(peerId)
33
+ || !scope.membershipAllowed(peerId) || !scope.recoveryPeerAllowed(peerId)) {
34
+ return void reply({ t: "peer_takeover", ok: false, error: "peer takeover is unavailable while the hub, peer or roster is changing; retry ahub peer takeover <peer> once ahub status shows the peer attached and idle" });
35
+ }
36
+ const peer = scope.bus.peers.get(peerId), claim = peer?.takeover?.(msg.standbyId as string | undefined, socket => scope.channelTakeoverAdmission(peerId, socket as Sock));
37
+ if (!peer || !claim) return void reply({ t: "peer_takeover", ok: false, error: "no eligible standby session is available; inspect ahub status and reconnect the intended standby session" });
38
+ scope.revokeTerminalExecution(peerId);
39
+ scope.startPeerTakeover(peer, claim);
40
+ return void reply({ t: "peer_takeover", ok: true, outcome: "requested", standbyId: claim.standbyId });
41
+ }
42
+
43
+ export function kimiLaunchEndMessage(scope: DaemonScope, m: ControlMessage): void {
44
+ const { c, msg, reply } = m;
45
+ if (c.role !== "console") return void reply({ ok: false, error: "Kimi launch cleanup is console only" });
46
+ if (typeof msg.admissionId === "string" && msg.admissionId === scope.kimiAdmissionId) scope.clearKimiAdmission();
47
+ return void reply({ ok: true });
48
+ }
49
+
50
+ export function terminalLaunchMessage(scope: DaemonScope, m: ControlMessage): void {
51
+ const { c, msg, reply } = m;
52
+ if (c.role !== "console") return void reply({ ok: false, error: "terminal launch registration is console only" });
53
+ if (scope.stopping || scope.recoveryActive() && !(scope.recoveryPhase === "restored" && msg.operationId === scope.recoveryOperationId)) return void reply({ ok: false, error: "recovery is holding terminal launches" });
54
+ const row = terminalLaunchCandidate(msg.launch, scope.opts.cwd, scope.opts.stateDir, scope.instanceId);
55
+ if (!row || !scope.membershipAllowed(row.peer) || !scope.definitionOf(row.peer)?.session.launchRecord || scope.recoveryActive() && !scope.recoveryPeerAllowed(row.peer)) return void reply({ ok: false, error: "terminal launch identity unavailable" });
56
+ try { scope.terminalLaunches.register(row); return void reply({ ok: true }); }
57
+ catch { return void reply({ ok: false, error: "terminal launch could not be registered; managed recovery is unavailable" }); }
58
+ }
59
+
60
+ export function nativeTuiLaunchMessage(scope: DaemonScope, m: ControlMessage): void {
61
+ const { c, msg, reply } = m;
62
+ if (c.role !== "console") return void reply({ ok: false, error: "native TUI launch is console only" });
63
+ const peer = String(msg.peer), owner = scope.bus.peers.get(peer);
64
+ // #1085: every refusal names its cause class, in the reply and as one hub.log line. The class is a closed word: never a session id, launch id, socket or path.
65
+ const refuseTui = (code: string, error: string, resumed?: boolean) => { scope.log(`native_tui_launch jcode refused: ${code}${resumed ? " (resumed session)" : ""}`); return void reply({ ok: false, code, ...(resumed ? { resumed: true } : {}), error }); };
66
+ if (scope.stopping || scope.recoveryActive() || !scope.membershipAllowed(peer) || scope.rosterChanging === peer || scope.requestedPeerStops.has(peer)) return refuseTui("hub_busy", "owned native TUI launch is unavailable");
67
+ if (peer !== scope.definitionOf(peer)?.kind || !isJcodePeer(owner)) return refuseTui("not_running", "owned native TUI launch is unavailable");
68
+ if (!jcodeMcpReady(scope.opts.cwd, scope.opts.stateDir, scope.SERVER_JS)) return refuseTui("mcp_stale", "owned native TUI launch is unavailable");
69
+ try {
70
+ if (msg.binding !== undefined && (!msg.binding || typeof msg.binding.launchId !== "string" || typeof msg.binding.sessionId !== "string")) throw new Error("invalid binding");
71
+ const options = msg.args ?? {};
72
+ for (const key of ["model", "providerProfile", "sessionId"]) if (options[key] !== undefined && typeof options[key] !== "string") throw new Error("invalid option");
73
+ return void reply({ ok: true, ...owner.tuiLaunch(msg.binding, options) });
74
+ } catch (error) {
75
+ if (error instanceof JcodeOptionMismatch) return void reply({ ok: false, option: error.option, error: `owned Jcode launch differs from its running session in ${error.option}; start without it or stop jcode first` });
76
+ if (error instanceof JcodeTuiRefusal) return refuseTui(error.code, "owned Jcode launch or saved session could not be verified; details withheld", owner.resumedSession);
77
+ return refuseTui("bad_request", "owned Jcode launch or saved session could not be verified; details withheld");
78
+ }
79
+ }
80
+
81
+ export function peerStartMessage(scope: DaemonScope, m: ControlMessage): void {
82
+ const { c, msg, reply } = m;
83
+ if (c.role !== "console") return void reply({ ok: false, error: "peer_start is a console command; use hub_peer_start with the conductor role" });
84
+ void scope.hubStart(msg.peer, "the console", true).then(result => reply(includeRetainedLaunchConfig(scope, String(msg.peer), result)), (error) => { scope.log(`peer_start ${String(msg.peer)} failed: ${(error as Error).message}`); reply({ ok: false, error: "peer start failed; inspect ahub status and hub.log" }); });
85
+ return;
86
+ }
87
+
88
+ export function peerStopMessage(scope: DaemonScope, m: ControlMessage): void {
89
+ const { sock, c, msg, reply } = m;
90
+ let stopCurrent:(()=>void)|undefined = c.instructed?.current;
91
+ if(c.role!=="console")try{stopCurrent=scope.admitOperational(sock,"stop");}catch(error){return void reply(scope.operationalFailure(error));}
92
+ void scope.stopPeer(msg.peer,false,stopCurrent?{actor:c.instructed ? USER : c.peer!,current:stopCurrent}:undefined).then(reply).catch(error => reply(scope.operationalFailure(error,"peer stop failed; inspect ahub status and logs before retrying")));
93
+ return;
94
+ }
95
+
96
+ export function startMessage(scope: DaemonScope, m: ControlMessage): void {
97
+ const { c, msg, reply } = m;
98
+ if (c.role !== "console") return void reply({ t: "started", ok: false, error: "start is a console command; use hub_peer_start with the conductor role" });
99
+ if (scope.recoveryActive() && !(scope.recoveryPhase === "restored" && msg.operationId === scope.recoveryOperationId)) return void reply({ t: "started", ok: false, error: scope.startHeldByRecovery(msg.peer) });
100
+ if (scope.recoveryActive() && !scope.recoveryPeerAllowed(String(msg.peer))) return void reply({ t: "started", ok: false, error: "peer is not part of the recovery roster" });
101
+ scope.startPeer(String(msg.peer), msg.args ?? {}, msg.args?.replaceSession === true ? scope.piReplacementAuthority : undefined)
102
+ .catch((e: Error) => ({ ok: false, error: e.message }))
103
+ .then((r) => {
104
+ if (!r.ok) scope.log(`start ${msg.peer} failed: ${r.error}`);
105
+ reply({ t: "started", ...includeRetainedLaunchConfig(scope, String(msg.peer), r) });
106
+ });
107
+ return;
108
+ }
109
+
110
+ export function resumeMessage(scope: DaemonScope, m: ControlMessage): void {
111
+ const { c, msg, reply } = m;
112
+ if (c.role !== "console") return void reply({ t: msg.t, ok: false, error: "pause/resume is a console command; use the conductor hold/release tools" });
113
+ if (scope.recoveryActive()) return void reply({ t: msg.t, ok: false, error: "recovery is holding mutations" });
114
+ void scope.holdPeer(msg.t, String(msg.peer)).then((result) => reply({ t: msg.t, ...result }), () => reply({ t: msg.t, ok: false, error: "peer resume validation failed" }));
115
+ return;
116
+ }
117
+
118
+ export function killMessage(scope: DaemonScope, m: ControlMessage): void {
119
+ const { c, msg, reply } = m;
120
+ if (c.role !== "console") return void reply({ ok: false, error: "kill is a console command" });
121
+ if (msg.instanceId !== undefined && msg.instanceId !== scope.instanceId) return void reply({ ok: false, error: "hub restarted; refresh before stopping" });
122
+ reply({ t: "stopping", ok: true, instanceId: scope.instanceId });
123
+ // Let the acknowledgement flush before closing the control listener.
124
+ setTimeout(() => void scope.stop().catch((error) => scope.log(`shutdown incomplete: ${(error as Error).message}`)), 0);
125
+ return;
126
+ }
@@ -1,3 +1,25 @@
1
+ // #1830 S2a: the startDaemon-scope names the control handlers read. Every field is a getter over the daemon's own binding (see `daemonScope` in daemon.ts); nothing is copied.
2
+ // Fields are read-only unless a moved handler assigns to the binding. Add a setter in daemon.ts and drop `readonly` only for a name a handler must write.
3
+ import type { ActivityRing } from "../activity.ts";
4
+ import type { BudgetPeerNote } from "../budget-notes.ts";
5
+ import type { ContextWindows } from "../context-window.ts";
6
+ import type { InboxPolling } from "../inbox-polling.ts";
7
+ import type { Inference } from "../inference.ts";
8
+ import type { KimiUsage } from "../kimi-usage.ts";
9
+ import type { View as MemoryView } from "@staix/agent-mem";
10
+ import type { Origin } from "../provenance.ts";
11
+ import type { OwnedInputContext } from "../../adapters/claude-print-child.ts";
12
+ import type { PeerTakeoverClaim } from "../peers.ts";
13
+ import type { RoomChat } from "../../rooms/service.ts";
14
+ import type { RoomCommands } from "../../rooms/commands.ts";
15
+ import type { RoomPreview } from "../../rooms/commands.ts";
16
+ import type { SettingRow } from "../settings.ts";
17
+ import type { SpecTaskInspector } from "../specs-task.ts";
18
+ import type { StartMode } from "../start-mode.ts";
19
+ import type { TerminalLaunches } from "../terminal-launch.ts";
20
+ import type { UsageRollup } from "../usage-rollup.ts";
21
+ import type { redactBusEvent } from "../operational-view.ts";
22
+ import type { DashboardSession } from "../ui.ts";
1
23
  import type { ActionBudgets } from "../action-policy.ts";
2
24
  import type { ApprovalObserver } from "../../local/tools.ts";
3
25
  import type { ClaudeFailureTrace } from "../claude-failure-stage.ts";
@@ -31,8 +53,6 @@ import type { TitleCursor } from "../peer-doing.ts";
31
53
  import type { TokenWindow } from "../token-window.ts";
32
54
  import type { loadConfig } from "../daemon.ts";
33
55
  import type { waitForClaudeCompletion } from "../usage.ts";
34
- // #1830 S2a: the startDaemon-scope names the control handlers read. Every field is a getter over the daemon's own binding (see `daemonScope` in daemon.ts); nothing is copied.
35
- // Fields are read-only unless a moved handler assigns to the binding. Add a setter in daemon.ts and drop `readonly` only for a name a handler must write.
36
56
  import type { createProjectAdapterCatalog } from "../../adapters/registry.ts";
37
57
  import type { NativeItem } from "../../memory/brief.ts";
38
58
  import type { MemoryClient } from "../../memory/client.ts";
@@ -380,4 +400,61 @@ export interface DaemonScope {
380
400
  transcriptRead: { path: string; offset: number; };
381
401
  readonly turnEnded: Map<string, number>;
382
402
  readonly writeStatus: () => void;
403
+ readonly SERVER_JS: string;
404
+ readonly accountMembers: (account: string) => string[];
405
+ readonly accountOf: (peer: string) => string;
406
+ readonly activityRings: Record<string, ActivityRing>;
407
+ readonly autonomyCommand: (action: unknown, environment: unknown, confirmed: unknown, confirmation?: unknown) => Promise<Record<string, unknown>>;
408
+ readonly budgetPeerNotes: () => BudgetPeerNote[];
409
+ readonly budgetViews: (status: ReturnType<Budget["status"]>) => ReturnType<Budget["status"]>;
410
+ readonly channelTakeoverAdmission: (peerId: string, socket: Sock) => boolean;
411
+ readonly clearKimiAdmission: () => void;
412
+ readonly contextSession: (peer: PeerId) => string | undefined;
413
+ readonly contexts: ContextWindows;
414
+ readonly controlOperationFailed: (sock: Sock, parsed: any, e: unknown) => void;
415
+ readonly corpusPolicyVersion: () => string;
416
+ dashboard: ReturnType<typeof import("../ui.ts").startDashboard> | undefined;
417
+ readonly dashboardSnapshot: (after: number, input?: Record<string, unknown>, session?: DashboardSession) => Promise<Record<string, unknown>>;
418
+ readonly drainCliAuditsNow: () => void;
419
+ readonly envelopeOrigins: Map<string, Origin>;
420
+ readonly implementerChatTask: (peer: string) => number | undefined;
421
+ readonly inboxPolling: InboxPolling;
422
+ readonly inference: Inference | undefined;
423
+ readonly instructedQuestionViews: () => (Omit<import("../questions.ts").QuestionRow, "instruction"> & { provenance?: string; })[];
424
+ readonly kimiAdmissionId: string | undefined;
425
+ readonly kimiSessionMode: "tui" | "headless" | undefined;
426
+ readonly kimiUsage: KimiUsage;
427
+ readonly logFile: string;
428
+ readonly memoryLine: (v: MemoryView) => string;
429
+ readonly noteSteeredReviewInput: (peer: PeerId, envs: readonly Envelope[]) => void;
430
+ readonly orphanChecks: string[] | undefined;
431
+ readonly ownedObserverInputs: Map<string, { owner: PeerAdapter; context: OwnedInputContext; sessionHash: string; inputHash: string; deliveryKey: string; reviewScoped: boolean; heldSameTurnAtAdmission: boolean; reviewerEphemeral?: true; closed?: boolean; supersededByReviewInput?: boolean; released: boolean; }>;
432
+ readonly peerAccountLabel: (peer: string) => string | undefined;
433
+ readonly piReplacementAuthority: symbol;
434
+ readonly projectSpecs: SpecTaskInspector;
435
+ readonly publicCorpus: (query: string, allowed: () => boolean) => import("../corpus-evidence.ts").CorpusEvidence[];
436
+ readonly recoveryPeerAllowed: (id: PeerId) => boolean;
437
+ readonly redact: typeof redactBusEvent;
438
+ readonly resolutionRefusal: typeof import("../daemon.ts").resolutionRefusal;
439
+ readonly resultView: (row: ReturnType<CompletionStore["listWithState"]>[number]) => { seenAt?: number | undefined; surface?: string | undefined; id: string; peer: string; outcome: "failed" | "done" | "limit" | "interrupted"; settledAt: number; startedAt: number; ms: number; private: boolean; title: string; read: boolean; };
440
+ readonly retainedCliAudits: Set<string>;
441
+ readonly retainedConfig: { key: string; reason: string; }[];
442
+ readonly reviewInputHeld: (peer: PeerId, envs: readonly Envelope[]) => boolean;
443
+ readonly reviewOnlyItem: (peer: string, env: Envelope) => boolean;
444
+ readonly reviewerBudgetView: () => { gate: import("../review-budget.ts").ReviewGate; unknown_quota: import("../review-budget.ts").ReviewUnknownQuota; rule: string; } | undefined;
445
+ readonly revokeTerminalExecution: (peer: string) => void;
446
+ readonly roomChat: RoomChat;
447
+ readonly roomCommands: RoomCommands;
448
+ readonly roomTickets: WeakMap<Sock, { id: string; expires: number; preview: RoomPreview; }>;
449
+ readonly rosterView: () => { peer: string; on: boolean; startMode: "tui" | "headless"; state: import("../envelope.ts").PeerState; queued: number; tasks: number; }[];
450
+ readonly settingsView: () => { rows: SettingRow[]; undo?: string; pendingRestart: { key: string; reason: string; }[]; retainedConfig: { key: string; reason: string; }[]; };
451
+ specsMissingBlockHintShown: boolean;
452
+ readonly startHeldByRecovery: (peer: unknown) => string;
453
+ readonly startMode: (peer: string) => StartMode;
454
+ readonly startPeerTakeover: (peer: PeerAdapter, claim: PeerTakeoverClaim) => void;
455
+ readonly status: (includeAttentionItems?: boolean, includeAttentionInput?: boolean, includeDoing?: boolean, includeIncomingLabels?: boolean, includeActivity?: boolean) => Record<string, unknown> & { peers: Record<string, object> };
456
+ readonly stopPeer: (peer: unknown, rosterRemoval?: boolean, operational?: { actor: string; current: () => void; }) => Promise<Record<string, unknown>>;
457
+ readonly terminalLaunches: TerminalLaunches;
458
+ readonly uiAction: (a: Record<string, unknown>, session?: DashboardSession) => Promise<unknown>;
459
+ readonly usageRollup: UsageRollup;
383
460
  }