@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,356 @@
1
+ // #1830 S2d: moved onMessage bodies and their private helpers. The daemon owns all state.
2
+ import { isWsPeer } from "../../adapters/channel-peer.ts";
3
+ import { isLocalPeer } from "../../adapters/local-worker.ts";
4
+ import { parseRemotePeerId } from "../../rooms/application.ts";
5
+ import { ASK_NOTE_TITLE, ask, taskEvidencePrivacy } from "../ask.ts";
6
+ import { isClosedTaskState } from "../board.ts";
7
+ import { Bus, ReviewInputHandoffError } from "../bus.ts";
8
+ import { publicDeliveryBodies, publicDeliveryReason } from "../delivery-public.ts";
9
+ import { HUB, MAX_HOP, USER, newEnvelope, parseMarker, sanitize } from "../envelope.ts";
10
+ import { InboxPolling } from "../inbox-polling.ts";
11
+ import { sessionTitleText } from "../peer-doing.ts";
12
+ import { originOf } from "../provenance.ts";
13
+ import { detectSignals } from "../routing.ts";
14
+ import type { TaskEvidencePrivacy } from "../ask.ts";
15
+ import type { Sock } from "../daemon.ts";
16
+ import type { PeerId } from "../envelope.ts";
17
+ import type { Origin } from "../provenance.ts";
18
+ import type { View as MemoryView } from "@staix/agent-mem";
19
+ import type { ControlMessage, DaemonScope } from "./scope.ts";
20
+
21
+ function queueView(scope: DaemonScope, row: ReturnType<Bus["queueShow"]>, detail = false, publicOnly = false) {
22
+ if (!row) return undefined;
23
+ const originals = row.originals;
24
+
25
+ return {
26
+ id: row.id, peer: row.peer, state: row.state, revision: row.revision,
27
+ ...(row.failureCause ? { failureCause: row.failureCause } : {}),
28
+ // #1795: the stored reason of a failed or held delivery, through the same private and public rules as its bodies.
29
+ ...(detail && row.reason ? { reason: publicDeliveryReason(originals, row.reason, { publicOnly, taskPrivate: id => { const task = scope.board.get(Number(id)); return !task || scope.tasks.isPii(task); }, publicMetadataText: text => scope.tasks.publicMetadataText(text) }) } : {}),
30
+ ...scope.roomChat.evidence(row.peer, row.id),
31
+ ...(detail && scope.bus.deliveryResolution(row.id) ? { resolvedBy: scope.bus.deliveryResolution(row.id) } : {}),
32
+ ...(!scope.membershipAllowed(row.peer) ? { rostered: false, holdReason: "off roster" } : {}),
33
+ createdAt: row.createdAt, updatedAt: row.updatedAt,
34
+ envelopeIds: originals.map((env) => env.id),
35
+ important: originals.some((env) => env.priority === "important"),
36
+ ...(detail ? { messages: publicDeliveryBodies(originals, { publicOnly, taskPrivate: id => { const task = scope.board.get(Number(id)); return !task || scope.tasks.isPii(task); }, publicMetadataText: text => scope.tasks.publicMetadataText(text) }) } : {}),
37
+ };
38
+ }
39
+
40
+ function inboxHeldRead(scope: DaemonScope, c: Sock["data"], current: () => boolean) {
41
+ try {
42
+ const peer = c.peer;
43
+ if (!peer || !current() || scope.contextPii(peer)) throw new Error("held inbox authority unavailable");
44
+ const policy = scope.config, configVersion = scope.configRevision, boardVersion = scope.board.statusRevision();
45
+ const held = scope.bus.heldInbox(peer);
46
+ const launch = c.toolsOwner ? scope.currentImplementerTools(c) : undefined;
47
+ const rows = held.rows.map(row => {
48
+ if (!current() || scope.reviewOnlyPeer(peer) && row.originals.some(env => !scope.reviewOnlyItem(peer, env))) throw new Error("held inbox scope unavailable");
49
+ if (c.toolsOwner && (!launch || row.originals.some(env => (env.refs?.task === undefined ? scope.implementerChatTask(peer) : Number(env.refs.task)) !== launch.task))) throw new Error("held inbox belongs to another task session");
50
+ return { id: row.id, revision: row.revision, state: row.state, messages: publicDeliveryBodies(row.originals, {
51
+ publicOnly: true, taskPrivate: id => { const task = scope.board.get(Number(id)); return !task || scope.tasks.isPii(task); },
52
+ publicMetadataText: text => scope.tasks.publicMetadataText(text),
53
+ }) };
54
+ });
55
+ // Screening may consult host ports. Revalidate the exact caller and current privacy before exposure.
56
+ if (!current() || scope.contextPii(peer) || scope.config !== policy || scope.configRevision !== configVersion || scope.board.statusRevision() !== boardVersion) throw new Error("held inbox changed during projection");
57
+ for (const row of held.rows) {
58
+ if (scope.reviewInputHeld(peer, row.originals)) {
59
+ const owner = scope.bus.peers.get(peer), active = scope.ownedObserverInputs.get(peer);
60
+ if (active && active.owner === owner) active.supersededByReviewInput = true;
61
+ scope.noteSteeredReviewInput(peer, row.originals); // RAM observation only: no ACK or durable handoff.
62
+ }
63
+ }
64
+ if (!current() || scope.contextPii(peer)) throw new Error("held inbox authority changed");
65
+ return { count: held.count, rows, truncated: held.truncated, ...(held.unavailable ? { unavailable: true } : {}) };
66
+ } catch { return { unavailable: true, next: "Held bodies were not read; inspect ahub queue list for this peer, then retry hub_inbox after authority or storage recovers." }; }
67
+ }
68
+
69
+ function inboxHeldMetadata(scope: DaemonScope, peer: PeerId, includeAccepted = false) {
70
+ try { return scope.bus.heldDeliveryHints(peer, includeAccepted) ?? { unavailable: true as const }; }
71
+ catch { return { unavailable: true as const }; } // advisory failure is explicit without exposing an error or hiding a settled pull
72
+ }
73
+
74
+ const pauseReason = (scope: DaemonScope, id: PeerId) => {
75
+ const r = scope.budget.record(id), hold = scope.conductorHolds.get(id);
76
+ return r ? `paused by the budget coordinator: ${r.reason}; to override: ahub budget resume ${id}` : scope.manualPaused.has(id) ? `paused by the console user; ahub resume ${id}` : hold ? `held by the conductor ${hold.actor}; it releases it with hub_peer_release, or the console user with ahub resume ${id}` : "paused";
77
+ };
78
+
79
+ const rememberOrigin = (scope: DaemonScope, id: string, origin: Origin): void => { scope.envelopeOrigins.set(id, origin); if (scope.envelopeOrigins.size > 1024) scope.envelopeOrigins.delete(scope.envelopeOrigins.keys().next().value as string); };
80
+
81
+ export function titleMessage(scope: DaemonScope, m: ControlMessage): void {
82
+ const { c, msg, reply } = m;
83
+ if (c.role !== "console" || msg.liveTest === true) return void reply({ ok: false, reason: "invalid", error: "session titles are person console commands" });
84
+ if (typeof msg.peer !== "string" || !scope.peerIdPattern.test(msg.peer)) return void reply({ ok: false, reason: "invalid", error: "invalid peer id; choose a Pi or local-worker peer from ahub status" });
85
+ if (scope.definitionOf(msg.peer)?.title !== "hub") return void reply({ ok: false, reason: "invalid", error: "this peer has no hub-owned title slot; choose a Pi/local peer from ahub status or rename its session in its own UI" });
86
+ if (!scope.bus.peers.has(msg.peer) || scope.bus.stateOf(msg.peer) === "offline") return void reply({ ok: false, reason: "invalid", error: `peer is offline; start it with ahub ${msg.peer}, then retry ahub title` });
87
+ if (scope.stopping || scope.recoveryActive()) return void reply({ ok: false, reason: "invalid", error: "recovery or shutdown is holding titles; wait for ahub status to settle, then retry" });
88
+ if (!sessionTitleText(msg.title)) return void reply({ ok: false, reason: "invalid", error: "title needs 1-80 normalized characters; enter a short public title" });
89
+ const instruction = c.instructed;
90
+ const titleOwner = scope.bus.peers.get(msg.peer), previousTitle = titleOwner?.sessionTitle;
91
+ if (instruction && (!isLocalPeer(titleOwner) || !previousTitle || scope.titlePrivate(msg.peer, previousTitle))) return void reply({ ok: false, reason: "invalid", error: "this title cannot be safely restored or fenced; run the command in a terminal" });
92
+ const instructionCurrent = instruction ? () => { try { instruction.current(); return titleOwner?.sessionTitle === previousTitle; } catch { return false; } } : undefined;
93
+ void scope.setSessionTitle(msg.peer, msg.title, false, false, instructionCurrent).then(result => reply(result.ok && instruction ? { ...result, previousTitle } : result), () => reply({ ok: false, reason: "invalid", mayHaveApplied: true, error: "session title result is unconfirmed; the title may have been applied; check ahub status before retrying" }));
94
+ return;
95
+ }
96
+
97
+ export function queueMessage(scope: DaemonScope, m: ControlMessage): void {
98
+ const { sock, c, msg, reply } = m;
99
+ if (c.role !== "console" && msg.op === "list") {
100
+ try { scope.publicReadCurrent(sock)(); } catch { return void reply({ ok: false, error: "public queue read unavailable for this caller" }); }
101
+ } else if(c.role!=="console") {
102
+ try {if(!["show","resolve","discard"].includes(msg.op))throw new Error("queue inspection and resolution are console-only");const current=msg.op==="show"?scope.operationalCurrent(sock):scope.admitOperational(sock,`queue ${msg.op}`);current();}catch(error){return void reply(scope.operationalFailure(error));}
103
+ }
104
+ if(c.role!=="console" && msg.reason!==undefined && (typeof msg.reason!=="string" || !scope.tasks.publicMetadataText(msg.reason)))return void reply({ok:false,error:"queue reason withheld by privacy policy"});
105
+ if (msg.op === "list") {
106
+ if (msg.peer !== undefined && (typeof msg.peer !== "string" || !scope.peerIdPattern.test(msg.peer) && !parseRemotePeerId(msg.peer))) return void reply({ ok: false, error: "invalid peer" });
107
+ if (msg.all !== undefined && typeof msg.all !== "boolean") return void reply({ ok: false, error: "all is true or false" });
108
+ // #1096: a row an operator action already settled (a retry parent left `failed` for good, a discarded or completed row) is history, not open work: hidden unless `all`.
109
+ const everything = scope.bus.queueList(msg.peer), settled = msg.all === true ? new Set<string>() : scope.bus.settledIds();
110
+ const shown = everything.filter((row) => !settled.has(row.id));
111
+ return void reply({ ok: true, deliveries: shown.map((row) => queueView(scope, row,false,c.role!=="console")), ...(shown.length < everything.length ? { hiddenSettled: everything.length - shown.length } : {}) });
112
+ }
113
+ if (msg.op === "discard") {
114
+ // #713: the person's bulk clear of one peer's backlog. Without `confirmed` it only counts; with it, every queued (or needs_review) delivery of that peer is discarded
115
+ // through the same `resolveDelivery` as one by one, each with the reason, so the journal records each as a `resolve ... discard`. Push peers' queues are never touched
116
+ // because only the named peer is read. Refused while recovery or shutdown holds queue mutations, like every queue resolution.
117
+ if (typeof msg.peer !== "string" || !scope.peerIdPattern.test(msg.peer) && !parseRemotePeerId(msg.peer)) return void reply({ ok: false, error: "peer must be a peer id" });
118
+ if (msg.peer.includes("@") && c.role !== "console") return void reply({ ok: false, error: "remote delivery disposition is person-only" });
119
+ // #1096: `states` (a list of queued, needs_review, failed) clears several kinds in one call, and a `failed` row counts only while no resolution settled it. The older single `state` keeps its meaning.
120
+ const KINDS = ["queued", "needs_review", "failed"] as const;
121
+ if (msg.states !== undefined && msg.state !== undefined) return void reply({ ok: false, error: "give state or states, not both" });
122
+ if (msg.states !== undefined && (!Array.isArray(msg.states) || !msg.states.length || msg.states.some((entry: unknown) => !(KINDS as readonly unknown[]).includes(entry)) || new Set(msg.states).size !== msg.states.length)) return void reply({ ok: false, error: `states is a list of ${KINDS.join(", ")}` });
123
+ if (msg.states === undefined && msg.state !== undefined && msg.state !== "queued" && msg.state !== "needs_review") return void reply({ ok: false, error: "state is queued or needs_review" });
124
+ const wanted: readonly string[] = msg.states ?? [msg.state === undefined ? "queued" : msg.state];
125
+ const settledRows = wanted.includes("failed") ? scope.bus.settledIds() : new Set<string>();
126
+ const rows = scope.bus.queueList(msg.peer).filter((row) => wanted.includes(row.state) && !(row.state === "failed" && settledRows.has(row.id)));
127
+ const byState = Object.fromEntries(wanted.map((kind) => [kind, rows.filter((row) => row.state === kind).length]));
128
+ const state = wanted.length === 1 ? wanted[0]! : wanted.join("+");
129
+ const many = msg.states !== undefined ? { states: wanted, byState } : {};
130
+ if (msg.confirmed !== true) return void reply({ ok: true, op: "discard", peer: msg.peer, state, ...many, count: rows.length, discarded: 0, refused: 0 });
131
+ if (typeof msg.reason !== "string" || !msg.reason.trim() || msg.reason.length > 2000) return void reply({ ok: false, error: "discard needs a reason" });
132
+ if (scope.recoveryActive() || scope.stopping) return void reply({ ok: false, error: "recovery or shutdown is holding queue mutations" });
133
+ let discarded = 0; const refused: Record<string, number> = {};
134
+ for (const row of rows) {
135
+ // A queued row with no journal record of its own carries the journal's global revision, which every discard moves: read the row's current revision just before
136
+ // discarding it, so the 12th discard is not refused as stale because of the 11 before it. A row that is gone or changed state meanwhile is counted as refused.
137
+ const current = scope.bus.queueShow(row.id) ?? scope.bus.queueList(msg.peer).find((r) => r.id === row.id);
138
+ try {
139
+ if (!current || current.state !== row.state) throw new Error("unknown delivery");
140
+ scope.bus.resolveDelivery(row.id, current.revision, "discard", msg.reason.trim());
141
+ if (row.peer.includes("@")) scope.roomChat.disposition(row.peer, row.id, "discard");
142
+ discarded++;
143
+ }
144
+ catch (error) { const why = scope.resolutionRefusal(error).split(":")[0]!; refused[why] = (refused[why] ?? 0) + 1; }
145
+ }
146
+ scope.writeStatus();
147
+ return void reply({ ok: true, op: "discard", peer: msg.peer, state, ...many, count: rows.length, discarded, refused: rows.length - discarded, ...(rows.length - discarded ? { refusedBy: refused } : {}) });
148
+ }
149
+ if (typeof msg.id !== "string" || !msg.id || msg.id.length > 256) return void reply({ ok: false, error: "invalid delivery ID" });
150
+ if (msg.op === "show") {
151
+ const row = scope.bus.queueShow(msg.id);
152
+ return void reply(row ? { ok: true, delivery: queueView(scope, row, true,c.role!=="console") } : { ok: false, error: "delivery not found" });
153
+ }
154
+ if (msg.op !== "resolve" || !["completed", "retry", "discard"].includes(msg.action) || !Number.isSafeInteger(msg.revision) || msg.revision < 0 || typeof msg.reason !== "string" || !msg.reason.trim() || msg.reason.length > 2000) return void reply({ ok: false, error: "resolution needs an action, observed revision and reason" });
155
+ if (scope.recoveryActive() || scope.stopping) return void reply({ ok: false, error: "recovery or shutdown is holding queue mutations" });
156
+ try {
157
+ const before = scope.bus.queueShow(msg.id);
158
+ if (before?.peer.includes("@") && c.role !== "console") return void reply({ ok: false, error: "remote delivery disposition is person-only" });
159
+ scope.bus.resolveDelivery(msg.id, msg.revision, msg.action, msg.reason.trim());
160
+ if (before?.peer.includes("@")) scope.roomChat.disposition(before.peer, msg.id, msg.action);
161
+ scope.writeStatus();
162
+ return void reply({ ok: true, delivery: queueView(scope, scope.bus.queueShow(msg.id),false,c.role!=="console") });
163
+ } catch (error) { return void reply({ ok: false, error: scope.resolutionRefusal(error) }); }
164
+ }
165
+
166
+ export function deliveryHoldsMessage(scope: DaemonScope, m: ControlMessage): void {
167
+ const { c, reply } = m;
168
+ if (!c.peer || (c.role !== "peer" && c.role !== "tools")) return void reply({ ok: false, error: "held metadata requires a peer identity" });
169
+ try {
170
+ const held = scope.bus.heldDeliveryHints(c.peer);
171
+ return void reply(held ? { ok: true, held, queued: scope.bus.queued(c.peer), important: scope.bus.queuedImportant(c.peer) } : { ok: false, error: "held metadata unavailable" });
172
+ } catch { return void reply({ ok: false, error: "held metadata unavailable" }); }
173
+ }
174
+
175
+ export function deliveryReceiptMessage(scope: DaemonScope, m: ControlMessage): void {
176
+ const { sock, c, msg, reply } = m;
177
+ const peer = c.peer ? scope.bus.peers.get(c.peer) : undefined;
178
+ if (c.role !== "peer" || !isWsPeer(peer) || typeof msg.deliveryId !== "string" || !peer.ownsDelivery(sock, msg.generation, msg.deliveryId) || !["accepted", "needs_review", "failed_safe"].includes(msg.state)) return void reply({ ok: false, error: "invalid delivery receipt" });
179
+ if (msg.state === "failed_safe" && (!peer.pullOnly || scope.bus.queueShow(msg.deliveryId)?.state !== "dispatching")) return void reply({ ok: false, error: "safe failure requires an unseen push to a pull-only session" });
180
+ const reason = typeof msg.reason === "string" ? sanitize(msg.reason).replace(/\s+/g, " ").trim().slice(0, 300) : "";
181
+ scope.bus.deliveryReceipt(peer.id, { id: msg.deliveryId, state: msg.state, ...(msg.state !== "accepted" ? { reason: reason || "Claude bridge could not confirm notification delivery", failureCause: msg.state === "failed_safe" ? "adapter refused" : "push error" } : {}) });
182
+ return void reply({ ok: true });
183
+ }
184
+
185
+ export function inboxMessage(scope: DaemonScope, m: ControlMessage): void {
186
+ const { sock, c, msg, reply } = m;
187
+ if (msg.peer !== undefined && msg.peer !== c.peer) return void reply({ ok: false, error: "hub_inbox reads only your authenticated peer; omit peer and ask the person to inspect another peer's queue" });
188
+ if (scope.stopping || scope.recoveryActive()) return void reply({ ok: false, error: "the hub is not serving inbox reads now (recovery or shutdown); run ahub status, then call hub_inbox again after it recovers" });
189
+ if (c.toolsOwner) {
190
+ const peer = c.peer!, current = scope.captureImplementerTools(c), launch = scope.currentImplementerTools(c);
191
+ const heldRead = () => inboxHeldRead(scope, c, current);
192
+ try {
193
+ // Inspect the still-pending batch before pull commits/removes it: private work never reaches this native child.
194
+ const pending = scope.bus.pendingEnvelopes(peer);
195
+ if (!current() || pending.some(env => { const task = env.refs?.task === undefined ? undefined : scope.board.get(Number(env.refs.task)); return env.private || scope.contextPii(peer) || !!task && scope.tasks.isPii(task); })) return void reply({ ok: false, error: "private inbox delivery refused" });
196
+ if (!launch || pending.some(env => (env.refs?.task === undefined ? scope.implementerChatTask(peer) : Number(env.refs.task)) !== launch.task)) return void reply({ ok: false, error: "inbox delivery belongs to another task session" });
197
+ const envs = scope.bus.pull(peer, { allowNeedsReviewHold: true });
198
+ if (!envs) return void reply({ ok: false, error: scope.queueHold(peer) ?? "delivery held", held: inboxHeldMetadata(scope, peer, true), heldRead: heldRead(), waiting: scope.bus.queued(peer), waitingImportant: scope.bus.queuedImportant(peer) });
199
+ return void reply({ ok: true, envs, held: inboxHeldMetadata(scope, peer, true), heldRead: heldRead(), waiting: scope.bus.queued(peer), waitingImportant: scope.bus.queuedImportant(peer) });
200
+ } catch (error) {
201
+ if (error instanceof ReviewInputHandoffError) return void reply({ ok: false, error: error.message, held: inboxHeldMetadata(scope, peer, true), heldRead: heldRead(), waiting: scope.bus.queued(peer), waitingImportant: scope.bus.queuedImportant(peer) });
202
+ return void reply({ ok: false, error: "delivery journal unavailable" });
203
+ }
204
+ }
205
+ // The attached session can explicitly claim queued work even during a native turn (#493).
206
+ // Pull and push share holds and journal settlement; work read here is completed, never pushed again.
207
+ const peer = c.peer ? scope.bus.peers.get(c.peer) : undefined;
208
+ if (c.role !== "peer" || !isWsPeer(peer) || !peer.owns(sock)) return void reply({ ok: false, error: "not attached to the hub yet; retry hub_inbox in a moment" });
209
+ const current = () => sock.data === c && sock.readyState === WebSocket.OPEN && c.role === "peer" && c.peer === peer.id && scope.membershipAllowed(peer.id) && scope.bus.peers.get(peer.id) === peer && peer.owns(sock) && !scope.stopping && !scope.recoveryActive();
210
+ const heldRead = () => inboxHeldRead(scope, c, current);
211
+ try {
212
+ const envs = scope.bus.pull(peer.id, { allowNeedsReviewHold: true });
213
+ if (!envs) {
214
+ const held = inboxHeldMetadata(scope, peer.id, true);
215
+ const heldRows = held && typeof held === "object" && !Array.isArray(held) && Array.isArray((held as { rows?: unknown }).rows)
216
+ ? (held as { rows: { state?: unknown }[] }).rows : undefined;
217
+ const accepted = heldRows?.some(row => row.state === "accepted") === true;
218
+ const blockingCause = scope.queueHold(peer.id)
219
+ ?? (scope.bus.isRecoveryHeld ? "recovery is holding deliveries" : undefined)
220
+ ?? (scope.bus.stateOf(peer.id) === "paused" ? pauseReason(scope, peer.id) : undefined);
221
+ const error = blockingCause ?? (accepted ? "an accepted delivery is awaiting your explicit confirmation" : "delivery held");
222
+ return void reply({ ok: false, error, held, heldRead: heldRead(), waiting: scope.bus.queued(peer.id), waitingImportant: scope.bus.queuedImportant(peer.id) });
223
+ }
224
+ peer.lastInboxAt = Date.now();
225
+ let polling: ReturnType<InboxPolling["read"]>;
226
+ try {
227
+ const assigned = peer.pullOnly && scope.board.statusTasks().some(task => !isClosedTaskState(task.state) && task.state !== "backlog" && (task.owner === peer.id || task.reviewer === peer.id));
228
+ polling = peer.pullOnly ? scope.inboxPolling.read(peer.id, envs.length === 0, assigned, peer.lastInboxAt) : undefined;
229
+ if (polling?.notice) scope.notify(`${peer.id} is polling an empty inbox with no task (${polling.count} empty reads in ${polling.minutes} min)`);
230
+ } catch { polling = undefined; } // The pull already completed: advice must never discard its envelopes.
231
+ scope.writeStatus();
232
+ if (envs.length) scope.log(`${peer.id} read ${envs.length} queued message(s) through hub_inbox`);
233
+ return void reply({ ok: true, envs, held: inboxHeldMetadata(scope, peer.id, true), heldRead: heldRead(), waiting: scope.bus.queued(peer.id), waitingImportant: scope.bus.queuedImportant(peer.id), ...(polling ? { pollingAdvice: { count: polling.count, minutes: polling.minutes } } : {}) });
234
+ } catch (error) {
235
+ if (error instanceof ReviewInputHandoffError) return void reply({ ok: false, error: error.message, held: inboxHeldMetadata(scope, peer.id, true), heldRead: heldRead(), waiting: scope.bus.queued(peer.id), waitingImportant: scope.bus.queuedImportant(peer.id) });
236
+ return void reply({ ok: false, error: "delivery journal unavailable" });
237
+ }
238
+ }
239
+
240
+ export function deliveryCompleteMessage(scope: DaemonScope, m: ControlMessage): void {
241
+ const { sock, c, msg, reply } = m;
242
+ const peer = c.peer ? scope.bus.peers.get(c.peer) : undefined;
243
+ if (c.role !== "peer" || !isWsPeer(peer) || typeof msg.deliveryId !== "string" || !peer.ownsDelivery(sock, msg.generation, msg.deliveryId)) return void reply({ ok: false, error: "delivery does not belong to this connection generation" });
244
+ return void reply(scope.bus.completeDelivery(peer.id, msg.deliveryId) ? { ok: true } : { ok: false, error: "delivery is not live and accepted; inspect ahub queue show before resolving" });
245
+ }
246
+
247
+ export function sendMessage(scope: DaemonScope, m: ControlMessage): void {
248
+ const { c, msg, reply } = m;
249
+ if (scope.recoveryActive()) return void reply({ t: "sent", ok: false, error: "recovery is holding new deliveries" });
250
+ // A human at the console should not wait out the batch window; agents default to status.
251
+ const { priority, body } = parseMarker(String(msg.body ?? ""), c.peer ? "status" : "important");
252
+ if (!body) return void reply({ t: "sent", ok: false, error: "empty body" });
253
+ const recipients = typeof msg.to === "string" && msg.to.length ? [msg.to] : msg.to;
254
+ if (Object.hasOwn(msg, "to") && (!Array.isArray(recipients) || recipients.some(id => typeof id !== "string" || !id.length))) {
255
+ return void reply({ t: "sent", ok: false, error: "to must be an array of peer ids" });
256
+ }
257
+ const to: PeerId[] | undefined = Array.isArray(recipients) && recipients.length ? [...new Set<string>(recipients)] : undefined;
258
+ const unknown = to?.filter((id) => !scope.bus.knownPeers().includes(id) && scope.membershipAllowed(id)) ?? [];
259
+ if (unknown.length) return void reply({ t: "sent", ok: false, error: `unknown peer: ${unknown.join(", ")}` });
260
+ const inReplyTo = msg.reply_to ? scope.bus.get(String(msg.reply_to)) : undefined;
261
+ // #445 C2: an explicit hub_send that answers an invocation request is the answer, not a message: it is settled like any other answer and published nowhere.
262
+ if (c.peer && inReplyTo?.kind === "invocation" && inReplyTo.from === HUB) {
263
+ scope.bus.onAnswer?.(c.peer, body, [inReplyTo]);
264
+ scope.bus.completeReply(c.peer, inReplyTo.id);
265
+ return void reply({ t: "sent", ok: true, targets: [], recorded: false });
266
+ }
267
+ // Built first: limits count the audience it really has (a reply goes to the parent's sender).
268
+ let env = newEnvelope(c.peer ?? USER, body, { priority, ...(to ? { to } : {}), ...(inReplyTo ? { inReplyTo } : {}) });
269
+ if (c.session) env = { ...env, session: true }; // agent-hub#1036: sent by a distinct session; `from` is its minted id, and the header a recipient reads shows it as is
270
+ env = scope.bus.reviewResponse(env, inReplyTo?.id);
271
+ rememberOrigin(scope, env.id, originOf({ role: c.role, peer: c.peer, launchId: c.launchId, ...(c.session ? { session: true } : {}) })); // the connection that sent it, for events.jsonl (never a path or text)
272
+ try { scope.bus.checkRemotePublication(env); }
273
+ catch (error) { return void reply({ t: "sent", ok: false, error: error instanceof Error && /^(?:room|remote) /.test(error.message) ? sanitize(error.message).slice(0, 8192) : "message admission unavailable" }); }
274
+ const offRoster = scope.bus.offRosterRecipients(env);
275
+ if (offRoster.length && offRoster.length === new Set(env.to?.filter(id => id !== env.from)).size) return void reply({ t: "sent", ok: false, error: `off roster: ${offRoster.join(", ")}` });
276
+ const admittedEnv = offRoster.length ? { ...env, to: env.to!.filter(id => !offRoster.includes(id)) } : env;
277
+ // A silent cohort (issue #107): the members it is held back from are left out, the rest get it; the sender is
278
+ // told. Held back from everyone, it costs the sender nothing against its limits.
279
+ const hushed = scope.bus.hushed(env);
280
+ const heldBack = hushed.length > 0 && hushed.length === scope.bus.audience(env).length;
281
+ const refused = c.peer && !heldBack ? scope.admit(admittedEnv, inReplyTo?.id) : undefined;
282
+ if (refused) return void reply({ t: "sent", ok: false, error: refused });
283
+ let published: ReturnType<Bus["publishResult"]>;
284
+ try { published = scope.bus.publishResult(env); }
285
+ catch (error) { return void reply({ t: "sent", ok: false, error: error instanceof Error && /^(?:room|remote) /.test(error.message) ? sanitize(error.message).slice(0, 8192) : "message admission unavailable" }); }
286
+ const { targets, dropped } = published;
287
+ if (c.peer && inReplyTo) scope.bus.completeReply(c.peer, inReplyTo.id); // the delivery it answers was handled all the same
288
+ if (dropped === "hop") return void reply({ t: "sent", ok: true, targets, dropped, recorded: priority === "fyi",
289
+ notice: `not delivered: reply chain reached the hop cap (${MAX_HOP}); send a new message without reply_to` });
290
+ if (hushed.length && !targets.length) return void reply({ t: "sent", ok: false, error: `not delivered to ${hushed.map((h) => h.peer).join(", ")}: ${hushed[0]!.reason}` });
291
+ return void reply({ t: "sent", ok: true, targets, recorded: priority === "fyi", ...(offRoster.length ? { offRoster } : {}), ...(hushed.length ? { hushed: hushed.map((h) => h.peer) } : {}), ...((offRoster.length || hushed.length) ? { notice: [offRoster.length ? `retained off roster for ${offRoster.join(", ")}` : "", hushed.length ? `not delivered to ${hushed.map((h) => h.peer).join(", ")}: ${hushed[0]!.reason}` : ""].filter(Boolean).join("; ") } : {}) });
292
+ }
293
+
294
+ export function askMessage(scope: DaemonScope, m: ControlMessage): void {
295
+ const { sock, c, msg, reply } = m;
296
+ // Console only: the evidence may hold PII task text (on campus), and the answer is for the person at the terminal.
297
+ if (c.role !== "console") return void reply({ t: "ask", ok: false, error: "ask is a console command" });
298
+ const client = sock.data, revision = scope.configRevision, policy = scope.corpusPolicyVersion();
299
+ const callerPrivate = () => !!client.peer && scope.contextPii(client.peer);
300
+ const initialPrivate = callerPrivate();
301
+ const isPiiText = (text: string) => scope.activeRouting().constraints.pii === "local_only" && detectSignals({ title: text, detail: "", refs: {} }, scope.activeRouting(), scope.opts.cwd).includes("pii");
302
+ let evidencePrivacy: readonly TaskEvidencePrivacy[] = [];
303
+ const askCurrent = () => !scope.stopping && sock.data === client && sock.readyState === WebSocket.OPEN
304
+ && scope.configRevision === revision && scope.corpusPolicyVersion() === policy && callerPrivate() === initialPrivate
305
+ && evidencePrivacy.every(previous => {
306
+ const latest = scope.board.get(previous.id);
307
+ if (!latest || latest.created !== previous.created) return false;
308
+ const privacy = taskEvidencePrivacy(latest, { isPii: task => scope.tasks.isPii(task), isPiiText });
309
+ return privacy.pii === previous.pii && privacy.notePii === previous.notePii;
310
+ });
311
+ ask(String(msg.question ?? ""), {
312
+ board: scope.board,
313
+ isPii: (t) => scope.tasks.isPii(t),
314
+ onCampus: scope.onCampus,
315
+ current: askCurrent,
316
+ privateContext: callerPrivate,
317
+ bindTaskEvidence: rows => { evidencePrivacy = rows; },
318
+ corpus: keys => scope.publicCorpus(keys.join(" "), askCurrent),
319
+ isPiiText,
320
+ ...(scope.config.memory.enabled ? { memory: scope.memory } : {}),
321
+ // #258: entries that match the question, then the graph neighbourhood of what they are about.
322
+ ...(scope.memoryStore ? { native: (keys: string[]) => {
323
+ scope.checkMemory();
324
+ const score = (v: MemoryView) => keys.filter((k) => `${v.title ?? ""} ${v.text} ${v.about.join(" ")}`.toLowerCase().includes(k)).length;
325
+ // Screened before the caps: withheld entries never crowd out readable evidence.
326
+ const hits = scope.screenMemory(scope.memoryStore!.list({ project: scope.memoryProject, limit: Number.MAX_SAFE_INTEGER })).map((v) => [v, score(v)] as const).filter(([, n]) => n > 0).sort((a, b) => b[1] - a[1]).slice(0, 6).map(([v]) => v);
327
+ const near = scope.screenMemory(scope.memoryStore!.related(scope.memoryProject, [...new Set(hits.flatMap((v) => v.about))], Number.MAX_SAFE_INTEGER)).slice(0, 6);
328
+ return [...hits, ...near].map((v) => ({ id: `mem:${v.id}`, text: scope.memoryLine(v).slice(13) }));
329
+ } } : {}),
330
+ project: scope.chain.at(-1)!,
331
+ logFile: scope.logFile,
332
+ ...(scope.inference ? { inference: scope.inference } : {}),
333
+ })
334
+ .then(async (res) => {
335
+ if (!askCurrent()) return void reply({ t: "ask", ok: true, found: false, evidence: [], pii: true, note: "evidence context changed" });
336
+ let saved: string | undefined;
337
+ if (msg.remember) {
338
+ if (res.pii) saved = "not saved: PII is involved";
339
+ else if (!res.found) saved = "not saved: there was no answer to save";
340
+ else if (!scope.config.memory.enabled) saved = "not saved: memory is disabled";
341
+ else {
342
+ // Saved as what it is: a model's answer, attributed to the hub, under a title later asks exclude from their evidence.
343
+ const ok = await scope.memory.save({
344
+ title: `${ASK_NOTE_TITLE}: ${String(msg.question).slice(0, 80)}`,
345
+ text: `Model-written answer from ahub ask, not a person's own finding.\nQ: ${String(msg.question).slice(0, 300)}\nA: ${res.answer}\nEvidence ids: ${res.evidence.map((e) => e.id).join(", ").slice(0, 600)}`,
346
+ project: scope.chain.at(-1)!,
347
+ metadata: { peer: "hub", asked_by: USER, kind: "finding", source: "ahub ask" },
348
+ });
349
+ saved = ok ? "saved as a candidate model-written answer; a person must review it" : "memory store unavailable; nothing saved";
350
+ }
351
+ }
352
+ reply({ t: "ask", ok: true, ...res, ...(saved ? { saved } : {}) });
353
+ })
354
+ .catch((e: Error) => reply({ t: "ask", ok: false, error: e.message }));
355
+ return;
356
+ }
@@ -0,0 +1,114 @@
1
+ // #1830 S2d: exact control message labels, with shared handlers for the original case groups.
2
+ import { titleMessage, queueMessage, deliveryHoldsMessage, deliveryReceiptMessage, inboxMessage, deliveryCompleteMessage, sendMessage, askMessage } from "./delivery-messages.ts";
3
+ import { silencedMessage, watchMessage, tailMessage, uiMessage, statusMessage, cliAuditAckMessage, uiSnapshotMessage, uiActionMessage, autonomyMessage, modelMessage, settingsGetMessage, settingsReloadMessage, settingsPreviewMessage, settingsSetMessage, settingsUndoMessage, configEditGetMessage, configEditPreviewMessage, configEditApplyMessage } from "./dashboard-messages.ts";
4
+ import { peerTakeoverMessage, kimiLaunchEndMessage, terminalLaunchMessage, nativeTuiLaunchMessage, peerStartMessage, peerStopMessage, startMessage, resumeMessage, killMessage } from "./peer-messages.ts";
5
+ import { roomMessage, budgetRenewMessage, budgetMessage, usageMessage, permitMessage, answerMessage, questionsMessage, resultSeenMessage, resultsMessage, worktreesRefreshPrsMessage } from "./operations-messages.ts";
6
+ import { nativeHookLaunchMessage, nativeFactsMessage, instructionExecuteMessage, instructionHookMessage, factsMessage } from "./native-messages.ts";
7
+ import { requestCancelMessage, permissionFailureProbeMessage, permissionRequestMessage, permissionDefaultMessage, permissionMessage, executionBudgetMessage, recoveryRestoreMessage, recoveryAuthorityMessage, recoveryMessage } from "./recovery-messages.ts";
8
+ import { boardRevision, conductorOperational, goalLink, guidanceMessage, guidanceProbeMessage, lineageMessage, reviewBlob, reviewCommentWrite, reviewCommentsRead, taskCatalogRole, taskHandoff, taskHandoffByKey, taskHandoffEvent, taskHandoffStates, taskMessage } from "./board-messages.ts";
9
+ import { sdlcMessage } from "./sdlc-messages.ts";
10
+ import type { ControlMessage, DaemonScope } from "./scope.ts";
11
+
12
+ const handlers = Object.freeze({
13
+ request_cancel: requestCancelMessage,
14
+ permission_failure_probe: permissionFailureProbeMessage,
15
+ permission_request: permissionRequestMessage,
16
+ conductor_operational: conductorOperational,
17
+ permission_default: permissionDefaultMessage,
18
+ permission: permissionMessage,
19
+ title: titleMessage,
20
+ queue: queueMessage,
21
+ delivery_holds: deliveryHoldsMessage,
22
+ delivery_receipt: deliveryReceiptMessage,
23
+ inbox: inboxMessage,
24
+ delivery_complete: deliveryCompleteMessage,
25
+ execution_budget: executionBudgetMessage,
26
+ recovery_restore: recoveryRestoreMessage,
27
+ recovery_authority: recoveryAuthorityMessage,
28
+ recovery: recoveryMessage,
29
+ send: sendMessage,
30
+ native_hook_launch: nativeHookLaunchMessage,
31
+ native_facts: nativeFactsMessage,
32
+ instruction_execute: instructionExecuteMessage,
33
+ instruction_hook: instructionHookMessage,
34
+ facts: factsMessage,
35
+ silenced: silencedMessage,
36
+ watch: watchMessage,
37
+ tail: tailMessage,
38
+ ui: uiMessage,
39
+ sdlc: sdlcMessage,
40
+ room: roomMessage,
41
+ status: statusMessage,
42
+ peer_takeover: peerTakeoverMessage,
43
+ cli_audit_ack: cliAuditAckMessage,
44
+ review_comment_put: reviewCommentWrite,
45
+ review_comment_delete: reviewCommentWrite,
46
+ review_comment_send: reviewCommentWrite,
47
+ review_comments: reviewCommentsRead,
48
+ review_blob: reviewBlob,
49
+ ui_snapshot: uiSnapshotMessage,
50
+ ui_action: uiActionMessage,
51
+ task_catalog_role: taskCatalogRole,
52
+ autonomy: autonomyMessage,
53
+ guidance_list: guidanceMessage,
54
+ guidance_show: guidanceMessage,
55
+ guidance_create: guidanceMessage,
56
+ guidance_withdraw: guidanceMessage,
57
+ guidance_probe_register: guidanceProbeMessage,
58
+ guidance_probe_start: guidanceProbeMessage,
59
+ guidance_probe_show: guidanceProbeMessage,
60
+ guidance_probe_receipts: guidanceProbeMessage,
61
+ guidance_probe_cancel: guidanceProbeMessage,
62
+ lineage_show: lineageMessage,
63
+ lineage_link: lineageMessage,
64
+ model: modelMessage,
65
+ settings_get: settingsGetMessage,
66
+ settings_reload: settingsReloadMessage,
67
+ settings_preview: settingsPreviewMessage,
68
+ settings_set: settingsSetMessage,
69
+ settings_undo: settingsUndoMessage,
70
+ config_edit_get: configEditGetMessage,
71
+ config_edit_preview: configEditPreviewMessage,
72
+ config_edit_apply: configEditApplyMessage,
73
+ kimi_launch_end: kimiLaunchEndMessage,
74
+ terminal_launch: terminalLaunchMessage,
75
+ native_tui_launch: nativeTuiLaunchMessage,
76
+ peer_start: peerStartMessage,
77
+ peer_stop: peerStopMessage,
78
+ start: startMessage,
79
+ task: taskMessage,
80
+ pause: resumeMessage,
81
+ resume: resumeMessage,
82
+ goal_link: goalLink,
83
+ ask: askMessage,
84
+ budget_renew: budgetRenewMessage,
85
+ budget: budgetMessage,
86
+ usage: usageMessage,
87
+ permit: permitMessage,
88
+ answer: answerMessage,
89
+ questions: questionsMessage,
90
+ // #1635: the board's write counter alone, for acon's revision polling. A console-role read of one bare number: no task, title or text, and no board write. An older hub answers an unknown message with ok:false, which the plugin maps to "0" (always fetch).
91
+ board_revision: boardRevision,
92
+ result_seen: resultSeenMessage,
93
+ results: resultsMessage,
94
+ kill: killMessage,
95
+ worktrees: worktreesRefreshPrsMessage,
96
+ worktree_override_set: worktreesRefreshPrsMessage,
97
+ worktree_override_clear: worktreesRefreshPrsMessage,
98
+ worktrees_refresh_prs: worktreesRefreshPrsMessage,
99
+ // #604 (agent-hub#1030): another project's daemon hands us a task, or reports a state change of one we handed it. Console role only (the same token and the same machine user as every
100
+ // control message): an agent connection never reaches these. The origin peer named in the request is a record, never an identity here, and nothing in it grants a role.
101
+ task_handoff: taskHandoff,
102
+ task_handoff_event: taskHandoffEvent,
103
+ task_handoff_by_key: taskHandoffByKey,
104
+ task_handoff_states: taskHandoffStates,
105
+ });
106
+
107
+ export function dispatchControlMessage(scope: DaemonScope, message: ControlMessage): void {
108
+ const { msg, reply } = message;
109
+ const type = msg.t;
110
+ const handle = typeof type === "string" && Object.hasOwn(handlers, type) ? handlers[type as keyof typeof handlers] : undefined;
111
+ if (handle) return handle(scope, message);
112
+ // A newer CLI talking to an older hub must get an answer, not wait forever.
113
+ if (msg.rid !== undefined) reply({ t: String(msg.t), ok: false, error: `this hub does not know "${msg.t}" (restart it: ahub kill && ahub up)` });
114
+ }