@staix/agent-hub 0.52.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 (196) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +4 -3
  3. package/docs/addons/open-code-review.md +3 -6
  4. package/docs/agent-notes/README.md +1 -1
  5. package/docs/agent-notes/adapters.md +5 -4
  6. package/docs/agent-notes/budget.md +2 -2
  7. package/docs/agent-notes/bus.md +1 -0
  8. package/docs/agent-notes/daemon.md +6 -5
  9. package/docs/agent-notes/models.md +1 -1
  10. package/docs/agent-notes/tasks.md +3 -3
  11. package/docs/agent-notes/tests.md +4 -4
  12. package/docs/contracts/companion-cli-v2.json +90 -0
  13. package/docs/contracts/companion-cli-v3.json +348 -0
  14. package/docs/design/adapters.md +1 -1
  15. package/docs/design/agent-hub-architecture.md +8 -5
  16. package/docs/design/bus.md +1 -1
  17. package/docs/design/cli-output-inventory.md +4 -2
  18. package/docs/design/execution-reference.md +1 -1
  19. package/docs/design/guidance-experiments.md +1 -0
  20. package/docs/design/guidance-probes.md +1 -0
  21. package/docs/design/model-routes.md +20 -5
  22. package/docs/design/roadmap.md +6 -4
  23. package/docs/design/task-board.md +21 -2
  24. package/docs/dogfood.md +13 -6
  25. package/docs/events.md +1 -1
  26. package/docs/memory.md +2 -2
  27. package/docs/operations.md +158 -50
  28. package/docs/quickstart.md +14 -2
  29. package/docs/security.md +17 -9
  30. package/docs/specs/2026-09-19-agent-hub-design.md +5 -3
  31. package/docs/specs/2026-09-19-multi-project-design.md +1 -1
  32. package/docs/specs/2026-09-20-upgrade-recovery-design.md +24 -0
  33. package/docs/specs/2026-12-04-arev-adoption-design.md +84 -0
  34. package/docs/specs/mcp-endpoint.md +15 -4
  35. package/docs/specs/relay-contract.md +38 -0
  36. package/docs/verification/2026-12-04-host-shared-receipts.md +43 -0
  37. package/docs/verification/2026-12-05-0.53.0.md +101 -0
  38. package/docs/verification/2026-12-05-agy-1.5.24.md +55 -0
  39. package/docs/verification/2026-12-05-claude-implementer-2.1.337.md +43 -0
  40. package/docs/verification/2026-12-06-0.54.0.md +76 -0
  41. package/docs/verification/2026-12-06-codex-0174-reviewer-isolation.md +43 -0
  42. package/docs/verification/2026-12-06-codex-0174-reviewer-tool-call.md +34 -0
  43. package/docs/verification/2026-12-06-compat-codex-capabilities-0.174.0.md +25 -0
  44. package/docs/verification/2026-12-06-compat-pi-1.8.0.md +23 -0
  45. package/docs/verified.json +38 -29
  46. package/package.json +9 -3
  47. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  48. package/plugins/agent-hub/.mcp.json +1 -1
  49. package/plugins/agent-hub/compat.json +9 -5
  50. package/plugins/agent-hub/kimi-hook.js +892 -874
  51. package/plugins/agent-hub/relay-launcher.js +24 -0
  52. package/plugins/agent-hub/server.js +27271 -25146
  53. package/src/adapters/acp-session-model.ts +1 -1
  54. package/src/adapters/acp.ts +5 -4
  55. package/src/adapters/agy/definition.ts +1 -1
  56. package/src/adapters/agy/hooks.ts +1 -1
  57. package/src/adapters/channel-peer.ts +3 -1
  58. package/src/adapters/claude-channel-evidence.ts +26 -1
  59. package/src/adapters/claude-channel.ts +27 -30
  60. package/src/adapters/claude-connection-policy.ts +62 -0
  61. package/src/adapters/claude-relay.ts +255 -0
  62. package/src/adapters/codex-review-isolation.ts +1 -2
  63. package/src/adapters/compat.ts +28 -18
  64. package/src/adapters/definitions/native-cli-preview-pi.ts +2 -1
  65. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  66. package/src/adapters/definitions/native-context.ts +1 -2
  67. package/src/adapters/definitions/native-factories.ts +4 -1
  68. package/src/adapters/definitions/native-quota.ts +1 -1
  69. package/src/adapters/definitions/native-recovery.ts +3 -1
  70. package/src/adapters/external-modules.ts +2 -2
  71. package/src/adapters/kimi-review.ts +1 -1
  72. package/src/adapters/kimi-tui-facts.ts +1 -1
  73. package/src/adapters/local-worker.ts +3 -3
  74. package/src/adapters/native-capabilities.ts +1 -1
  75. package/src/adapters/pi.ts +26 -7
  76. package/src/adapters/registry-types.ts +2 -0
  77. package/src/adapters/relay-launcher.ts +27 -0
  78. package/src/adapters/reviewer-mcp.ts +1 -1
  79. package/src/cli/agents.ts +20 -8
  80. package/src/cli/agy-mcp.ts +1 -1
  81. package/src/cli/claude-profile-hook.ts +1 -1
  82. package/src/cli/command-table.ts +1 -0
  83. package/src/cli/commands/agents.ts +18 -1
  84. package/src/cli/commands/doctor.ts +18 -4
  85. package/src/cli/commands/launch-line.ts +32 -0
  86. package/src/cli/commands/status.ts +14 -3
  87. package/src/cli/help.ts +7 -4
  88. package/src/cli/identity.ts +1 -1
  89. package/src/cli/init-roles.ts +1 -1
  90. package/src/cli/init-settings.ts +1 -1
  91. package/src/cli/launch-line-plan.ts +82 -0
  92. package/src/cli/launch-line-project.ts +13 -0
  93. package/src/cli/main.ts +10 -9
  94. package/src/cli/pi-steps-warning.ts +14 -0
  95. package/src/cli/recovery-package.ts +60 -6
  96. package/src/cli/reset.ts +1 -1
  97. package/src/cli/shell-quote.ts +1 -3
  98. package/src/cli/upgrade-interactive.ts +7 -2
  99. package/src/cli/upgrade-keep-plan.ts +47 -0
  100. package/src/cli/upgrade-restore-state.ts +1 -1
  101. package/src/cli/upgrade-runtime.ts +119 -18
  102. package/src/cli/upgrade.ts +17 -2
  103. package/src/hub/accounts.ts +8 -4
  104. package/src/hub/action-class.ts +1 -3
  105. package/src/hub/adec-triage.ts +105 -0
  106. package/src/hub/autonomy.ts +1 -1
  107. package/src/hub/board.ts +3 -27
  108. package/src/hub/bus.ts +39 -6
  109. package/src/hub/capabilities.ts +1 -1
  110. package/src/hub/channel-project-base.ts +46 -0
  111. package/src/hub/channel-project.ts +21 -46
  112. package/src/hub/config-apply.ts +1 -1
  113. package/src/hub/config-edit.ts +1 -1
  114. package/src/hub/config-tier.ts +1 -1
  115. package/src/hub/config.ts +2 -2
  116. package/src/hub/confirmation-matrix.ts +1 -1
  117. package/src/hub/control/board-messages.ts +415 -0
  118. package/src/hub/control/dashboard-messages.ts +221 -0
  119. package/src/hub/control/delivery-messages.ts +356 -0
  120. package/src/hub/control/dispatch.ts +114 -0
  121. package/src/hub/control/hub-tool-helpers.ts +243 -0
  122. package/src/hub/control/hub-tools.ts +147 -0
  123. package/src/hub/control/native-messages.ts +665 -0
  124. package/src/hub/control/operations-messages.ts +269 -0
  125. package/src/hub/control/peer-messages.ts +126 -0
  126. package/src/hub/control/recovery-messages.ts +391 -0
  127. package/src/hub/control/recovery-operation.ts +480 -0
  128. package/src/hub/control/scope.ts +460 -0
  129. package/src/hub/control/sdlc-messages.ts +373 -0
  130. package/src/hub/control/task-ops-more.ts +245 -0
  131. package/src/hub/control/task-ops.ts +553 -0
  132. package/src/hub/control/ui-actions.ts +241 -0
  133. package/src/hub/control-write-trace.ts +1 -4
  134. package/src/hub/daemon.ts +485 -4324
  135. package/src/hub/delivery-hints.ts +2 -0
  136. package/src/hub/delivery-journal.ts +17 -6
  137. package/src/hub/events.ts +2 -1
  138. package/src/hub/execution-reference.ts +1 -1
  139. package/src/hub/host.ts +41 -9
  140. package/src/hub/hub-tools.ts +3 -4
  141. package/src/hub/invocations.ts +1 -1
  142. package/src/hub/lifecycle.ts +4 -3
  143. package/src/hub/mcp-endpoint-serve.ts +4 -3
  144. package/src/hub/mcp-endpoint.ts +15 -6
  145. package/src/hub/memory-profile-check.ts +1 -1
  146. package/src/hub/no-writes.ts +1 -1
  147. package/src/hub/peers.ts +2 -0
  148. package/src/hub/pi-exit-policy.ts +27 -0
  149. package/src/hub/progress.ts +1 -1
  150. package/src/hub/project-runtime-state.ts +17 -4
  151. package/src/hub/project-runtime.ts +3 -1
  152. package/src/hub/protocol-window.ts +1 -1
  153. package/src/hub/recovery-continuity.ts +3 -3
  154. package/src/hub/recovery-kept-roster.ts +50 -0
  155. package/src/hub/review-anchor.ts +13 -181
  156. package/src/hub/review-brief.ts +78 -28
  157. package/src/hub/review-findings.ts +15 -193
  158. package/src/hub/review-ledger.ts +162 -0
  159. package/src/hub/review-material.ts +3 -3
  160. package/src/hub/reviewer-pool.ts +4 -2
  161. package/src/hub/roadmap-issue-states.ts +65 -14
  162. package/src/hub/roadmap-sync.ts +39 -14
  163. package/src/hub/routing.ts +9 -0
  164. package/src/hub/runtime-capture-prune.ts +8 -2
  165. package/src/hub/runtime-package-assets.ts +3 -0
  166. package/src/hub/sdlc-release-policy.ts +1 -2
  167. package/src/hub/settings.ts +1 -1
  168. package/src/hub/spec-ack-tool.ts +4 -0
  169. package/src/hub/spec-report-history.ts +36 -0
  170. package/src/hub/specs.ts +1 -4
  171. package/src/hub/supervision.ts +33 -6
  172. package/src/hub/tasks-audit.ts +390 -0
  173. package/src/hub/tasks-backlog.ts +522 -0
  174. package/src/hub/tasks-handoff.ts +208 -0
  175. package/src/hub/tasks-release.ts +257 -0
  176. package/src/hub/tasks-roadmap.ts +17 -3
  177. package/src/hub/tasks-specs.ts +672 -0
  178. package/src/hub/tasks-types.ts +334 -0
  179. package/src/hub/tasks.ts +286 -1961
  180. package/src/hub/upgrade-session-contract.ts +11 -0
  181. package/src/local/probe-sandbox.ts +1 -2
  182. package/src/local/probe-workspace.ts +1 -1
  183. package/src/models/route/config.ts +4 -4
  184. package/src/models/route/decision.ts +18 -10
  185. package/src/models/route/observation-signals.ts +1 -2
  186. package/src/models/route/runtime.ts +8 -5
  187. package/src/npm-artifact.ts +76 -0
  188. package/src/omniroute/client.ts +6 -0
  189. package/src/pi/extension.ts +5 -2
  190. package/src/pi/install.ts +77 -0
  191. package/src/pi/pin.ts +49 -0
  192. package/src/primitives.ts +14 -0
  193. package/src/version.ts +2 -0
  194. package/templates/adec/README.md +10 -6
  195. package/templates/config.json +1 -1
  196. package/templates/specs.block.md +1 -0
@@ -0,0 +1,221 @@
1
+ // #1830 S2d: moved onMessage bodies and their private helpers. The daemon owns all state.
2
+ import { isAcpPeer } from "../../adapters/acp.ts";
3
+ import { isWsPeer } from "../../adapters/channel-peer.ts";
4
+ import { conductorPeer } from "../conductor.ts";
5
+ import { OPERATIONAL_PERSON_GUIDANCE, OperationalAuthorityError, operationalRosterSetting, operationalSetting } from "../operational-authority.ts";
6
+ import { loadSdlc } from "../sdlc.ts";
7
+ import { NEVER_EDITABLE } from "../settings.ts";
8
+ import { dashboardView, startDashboard } from "../ui.ts";
9
+ import type { ControlMessage, DaemonScope } from "./scope.ts";
10
+
11
+ function publicSettingsView(scope: DaemonScope) {
12
+ const view = scope.settingsView();
13
+ const rows = view.rows.flatMap(row => {
14
+ if (!scope.tasks.publicMetadataText(row.key)) return [];
15
+ const def = scope.settingDef(row.key);
16
+ if (typeof def === "string") return [];
17
+ // Program/credential/location configuration is never a public value, even when its text passes screening.
18
+ // Route ids locate person-defined execution configuration; keep them opaque too.
19
+ const opaque = NEVER_EDITABLE.some(key => def.key === key || def.key.startsWith(`${key}.`))
20
+ || def.store === "routing" && def.path.at(-1) === "route";
21
+ const safeValue = (value: unknown): unknown => {
22
+ if (opaque) return "[withheld]";
23
+ if (typeof value === "string" && (!/^[A-Za-z0-9_.:-]{1,128}$/.test(value) || !scope.tasks.publicMetadataText(value))) return "[withheld]";
24
+ if (Array.isArray(value)) return value.slice(0, 128).map(safeValue);
25
+ return scope.publicReadValue(value);
26
+ };
27
+ return [{ key: row.key, group: row.group, label: scope.publicReadValue(row.label), type: row.type,
28
+ file: "[withheld]", source: "[withheld]", applies: row.applies, risk: row.risk,
29
+ value: safeValue(row.value), fileValue: safeValue(row.fileValue),
30
+ ...(row.pending !== undefined ? { pending: safeValue(row.pending) } : {}),
31
+ ...(row.values ? { values: opaque ? [] : row.values.map(safeValue) } : {}),
32
+ ...(row.min !== undefined ? { min: row.min } : {}), ...(row.max !== undefined ? { max: row.max } : {}),
33
+ ...(row.locked ? { locked: "read-only" } : {}), ...(opaque ? { withheld: true } : {}) }];
34
+ });
35
+ return { rows, sdlc: Object.fromEntries(Object.entries(sdlcSettingsView(scope)).map(([key, value]) => [key, scope.publicReadValue(value)])), roster: scope.rosterView().map(row => ({ peer: row.peer, on: row.on, startMode: row.startMode, state: row.state, queued: row.queued, tasks: row.tasks })), public: true, withheld: ["file", "source", "notes", "undo", "configEdit"] };
36
+ }
37
+
38
+ function sdlcSettingsView(scope: DaemonScope) {
39
+ let file: ReturnType<typeof loadSdlc> | undefined;
40
+ try { file = scope.readSdlcFile(); } catch { /* unreadable file stays unknown */ }
41
+ return {
42
+ "sdlc.mode": { value: scope.lifecycleConfig.mode, fileValue: file?.mode ?? null, ...(!file ? { problem: "file unavailable" } : {}) },
43
+ "sdlc.required_checks": { value: scope.lifecycleConfig.requiredChecks, fileValue: file?.requiredChecks ?? null, ...(!file ? { problem: "file unavailable" } : {}) },
44
+ };
45
+ }
46
+
47
+ export function silencedMessage(scope: DaemonScope, m: ControlMessage): void {
48
+ const { c, msg, reply } = m;
49
+ // `ahub check-path` (issue #107): which of these owners the asking peer shares a silent cohort with.
50
+ if (!c.peer) return void reply({ t: "silenced", ok: false, error: "silenced is for a peer" });
51
+ const owners = Array.isArray(msg.owners) ? msg.owners.filter((o: unknown): o is string => typeof o === "string").slice(0, 20) : [];
52
+ return void reply({ t: "silenced", ok: true, owners: owners.filter((o: string) => !!scope.tasks.silenced(c.peer!, o)) });
53
+ }
54
+
55
+ export function watchMessage(scope: DaemonScope, m: ControlMessage): void {
56
+ const { sock, c, msg, reply } = m;
57
+ if (c.role !== "console") return void reply({ ok: false, error: "watch is a person-only console command" });
58
+ if (typeof msg.peer !== "string" || !scope.definitionOf(msg.peer)?.capabilities?.watch) return void reply({ ok: false, error: "watch supports headless kimi and qwen only" });
59
+ const peer = msg.peer;
60
+ // Judged by the live owner: a headless Kimi started by --mode headless is watchable under a TUI start mode.
61
+ const owner = scope.bus.peers.get(peer);
62
+ const admission = scope.definitionOf(peer)?.attach?.admission;
63
+ if (admission && !isAcpPeer(owner) && (isWsPeer(owner) || (scope.kimiSessionMode ?? scope.startMode(peer)) === "tui")) return void reply({ ok: false, error: admission.watchRefusal });
64
+ if (!scope.membershipAllowed(peer)) return void reply({ ok: false, error: `${peer} is off roster` });
65
+ c.watch?.();
66
+ c.watch = scope.activityRings[peer]!.subscribe(item => {
67
+ // Bound slow observers instead of accumulating command output on the socket.
68
+ if (sock.getBufferedAmount() > 256 * 1024) { sock.close(1013, "watch observer is too slow"); return; }
69
+ sock.send(JSON.stringify({ t: "activity", peer, item }));
70
+ });
71
+ return void reply({ ok: true, t: "watch", peer });
72
+ }
73
+
74
+ export function tailMessage(scope: DaemonScope, m: ControlMessage): void {
75
+ const { sock, c } = m;
76
+ if (c.role !== "console" || c.tail) return;
77
+ c.tail = scope.bus.tap((e) => sock.send(JSON.stringify({ t: "event", e: scope.redact(e) })));
78
+ for (const p of scope.permissions.values()) sock.send(p.push);
79
+ for (const peer of scope.bus.knownPeers()) sock.send(JSON.stringify({ t: "context", peer, reading: scope.contexts.view(peer, scope.contextSession(peer), scope.bus.peers.has(peer) && ["idle", "busy", "paused"].includes(scope.bus.stateOf(peer))) }));
80
+ return;
81
+ }
82
+
83
+ export function uiMessage(scope: DaemonScope, m: ControlMessage): void {
84
+ const { c, msg, reply } = m;
85
+ if (c.role !== "console") return void reply({ t: "ui", ok: false, error: "ui is a console command" });
86
+ try {
87
+ scope.dashboard ??= startDashboard({ snapshot: scope.dashboardSnapshot, action: scope.uiAction });
88
+ scope.writeStatus();
89
+ // #269: `ahub ui --settings` is the same person's command; its ticket marks the session it opens.
90
+ if (msg.settings === true) scope.notify("settings session opened from ahub ui --settings: for 15 minutes that dashboard session may change permission modes, routing and start settings");
91
+ return void reply({ t: "ui", ok: true, url: scope.dashboard.issue(msg.settings === true, msg.liveTest === true), ...(msg.settings === true ? { settings: true } : {}), ...(msg.liveTest === true ? { liveTest: true } : {}) });
92
+ } catch {
93
+ return void reply({ t: "ui", ok: false, error: "could not start the dashboard" });
94
+ }
95
+ }
96
+
97
+ export function statusMessage(scope: DaemonScope, m: ControlMessage): void {
98
+ const { sock, c, msg, reply } = m;
99
+ const sendStatus = () => {
100
+ const current = scope.status(c.role === "console", false, true, c.role === "console" || (c.role === "tools" || c.role === "peer") && c.peer === conductorPeer(scope.config.roles), c.role === "console");
101
+ if (c.role === "console" && msg.companion === true) for (const [id, row] of Object.entries(current.peers)) {
102
+ const label = scope.peerAccountLabel(id);
103
+ if (label !== undefined) Object.assign(row, { accountLabel: label });
104
+ }
105
+ // #1798 T3, display only: whether this tools connection runs under the launch the peer's current channel socket attached with. It labels a startup
106
+ // notice and decides nothing: not admission, routing, delivery or permissions. Anyone holding the control token can send any launch id, so it is
107
+ // a hint, never evidence. Per request, never cached or stored; the launch id itself is never returned, logged or recorded. Absent for every
108
+ // other requester: a console, a minted session, a hub-owned tools child, a connection with no launch id, or a peer that is not a Claude channel.
109
+ const thisLaunch = c.role === "tools" && !c.session && !c.toolsOwner && c.peer && c.launchId && scope.definitionOf(c.peer)?.transport === "claude-channel"
110
+ ? { thisLaunch: (scope.bus.peers.get(c.peer) as { managedLaunchId?: unknown } | undefined)?.managedLaunchId === c.launchId } : {};
111
+ if ((c.role === "console" || c.role === "tools") && msg.specs === true) {
112
+ const summary = scope.projectSpecs.status();
113
+ if (summary) {
114
+ const missingBlockHint = !scope.specsMissingBlockHintShown && scope.projectSpecs.missingBlock() === true;
115
+ if (missingBlockHint) scope.specsMissingBlockHintShown = true;
116
+ return void reply({ t: "status", status: { ...current, ...thisLaunch, specs: { ...summary, ...(missingBlockHint ? { missingBlockHint: true } : {}) } } });
117
+ }
118
+ }
119
+ return void reply({ t: "status", status: { ...current, ...thisLaunch } });
120
+ };
121
+ if (scope.orphanChecks && !scope.startupSpecPending()) return sendStatus();
122
+ void Promise.all([scope.orphanSweep, scope.firstSpecProbe]).then(() => {
123
+ if (scope.stopping) return void reply({ ok: false, error: "hub stopping; run ahub status again after it restarts" });
124
+ sendStatus();
125
+ }).catch(error => scope.controlOperationFailed(sock, msg, error));
126
+ return;
127
+ }
128
+
129
+ export function cliAuditAckMessage(scope: DaemonScope, m: ControlMessage): void {
130
+ const { c, msg, reply } = m;
131
+ if (c.role !== "console") return void reply({ ok: false, error: "cli_audit_ack is a console command" });
132
+ if (typeof msg.auditId !== "string" || !/^[a-f0-9-]{36}$/.test(msg.auditId)) return void reply({ ok: false, error: "invalid audit id" });
133
+ try { scope.drainCliAuditsNow(); }
134
+ catch { return void reply({ ok: false, error: "CLI audit was not retained" }); }
135
+ return void reply({ ok: scope.retainedCliAudits.has(msg.auditId), auditId: msg.auditId, instanceId: scope.instanceId });
136
+ }
137
+
138
+ export function uiSnapshotMessage(scope: DaemonScope, m: ControlMessage): void {
139
+ const { c, msg, reply } = m;
140
+ if (c.role !== "console") return void reply({ ok: false, error: "ui_snapshot is a console command" });
141
+ if (!Number.isSafeInteger(msg.after ?? 0) || (msg.after ?? 0) < 0) return void reply({ ok: false, error: "invalid cursor" });
142
+ void scope.dashboardSnapshot(msg.after ?? 0, msg.memory !== undefined || msg.reviewRefresh === true || dashboardView(msg.view) || msg.visual !== undefined || msg.visualTask !== undefined || msg.visualAsset !== undefined ? { ...(msg.visual !== undefined ? { visual: msg.visual } : {}), ...(msg.visualTask !== undefined ? { visualTask: msg.visualTask } : {}), ...(msg.visualAsset !== undefined ? { visualAsset: msg.visualAsset } : {}), ...(msg.memory !== undefined ? { memory: msg.memory } : {}), ...(msg.reviewRefresh === true && msg.reviewTask !== undefined ? { reviewTask: msg.reviewTask, reviewRefresh: true } : {}), ...(dashboardView(msg.view) ? { view: msg.view } : {}) } : undefined).then(value => reply(value), () => reply({ ok: false, error: "memory view unavailable" }));
143
+ return;
144
+ }
145
+
146
+ export function uiActionMessage(scope: DaemonScope, m: ControlMessage): void {
147
+ const { c, msg, reply } = m;
148
+ if (c.role !== "console") return void reply({ ok: false, error: "ui_action is a console command" });
149
+ if (scope.recoveryActive()) return void reply({ ok: false, error: "recovery is holding mutations" });
150
+ if (msg.instanceId !== scope.instanceId) return void reply({ ok: false, error: "hub restarted; refresh before acting" });
151
+ if (!msg.action || typeof msg.action !== "object" || Array.isArray(msg.action)) return void reply({ ok: false, error: "invalid dashboard action" });
152
+ void scope.uiAction(msg.action).then((result) => reply(result as Record<string, unknown>), () => reply({ ok: false, error: "dashboard action failed; check its inputs" }));
153
+ return;
154
+ }
155
+
156
+ export function autonomyMessage(scope: DaemonScope, m: ControlMessage): void {
157
+ const { c, msg, reply } = m;
158
+ if (c.role !== "console") return void reply({ ok: false, error: "autonomy is a person-only command; run ahub autonomy in a person's terminal" });
159
+ void scope.autonomyCommand(msg.action, msg.environment, msg.confirmed, msg.confirmation).then(reply, () => reply({ ok: false, error: "project autonomy could not be changed" }));
160
+ return;
161
+ }
162
+
163
+ export function modelMessage(ds: DaemonScope, m: ControlMessage): void {
164
+ const { sock, c, msg, reply } = m;
165
+ if (c.role !== "console") return void reply(ds.modelFailure("model overrides are person-only; run ahub model in a person's terminal"));
166
+ return void reply(ds.modelCommandSafe(msg, { source: "cli", scope: c, current: () => { try { c.instructed?.current(); } catch { return false; } return c.authed === true && !c.closed && c.role === "console" && sock.readyState === WebSocket.OPEN; } }));
167
+ }
168
+
169
+ export function settingsGetMessage(scope: DaemonScope, m: ControlMessage): void {
170
+ const { sock, c, reply } = m;
171
+ if (c.role !== "console") {
172
+ try { const current = scope.publicReadCurrent(sock); current(); const view = publicSettingsView(scope); current(); return void reply({ ok: true, ...view }); }
173
+ catch { return void reply({ ok: false, error: "public settings read unavailable for this caller" }); }
174
+ }
175
+ return void reply({ ok: true, ...scope.settingsView(), sdlc: sdlcSettingsView(scope), roster: scope.rosterView(), configEdit: (() => { const view = scope.configEditor!.view(); return { revisions: view.revisions, known: view.known }; })() });
176
+ }
177
+
178
+ export function settingsReloadMessage(scope: DaemonScope, m: ControlMessage): void {
179
+ const { c, msg, reply } = m;
180
+ if (c.role !== "console") return void reply({ ok: false, error: "settings are a person command" });
181
+ return void scope.reloadConfig("terminal", undefined, msg.confirm).then(reply, () => reply({ ok: false, error: "configuration reload could not be confirmed; inspect hub.log" }));
182
+ }
183
+
184
+ export function settingsPreviewMessage(scope: DaemonScope, m: ControlMessage): void {
185
+ const { sock, c, msg, reply } = m;
186
+ if(c.role!=="console")try {const def=scope.settingDef(msg.key);if(msg.undo===true || typeof def==="string" || !(operationalSetting(def)||operationalRosterSetting(def)))throw new OperationalAuthorityError(`this setting is reserved for the person; ${OPERATIONAL_PERSON_GUIDANCE}`,"person");scope.operationalCurrent(sock)();}catch(error){return void reply(scope.operationalFailure(error));}
187
+ return void reply(msg.undo === true ? scope.settingsUndoPreview() : scope.settingsPreview(msg.key, msg.value));
188
+ }
189
+
190
+ export function settingsSetMessage(scope: DaemonScope, m: ControlMessage): void {
191
+ const { sock, c, msg, reply } = m;
192
+ let settingsCurrent:(()=>void)|undefined;
193
+ if(c.role!=="console")try {const def=scope.settingDef(msg.key);if(typeof def==="string" || !(operationalSetting(def)||operationalRosterSetting(def)))throw new OperationalAuthorityError(`this setting is reserved for the person; ${OPERATIONAL_PERSON_GUIDANCE}`,"person");settingsCurrent=scope.admitOperational(sock,"settings set");}catch(error){return void reply(scope.operationalFailure(error));}
194
+ void scope.operationalContext.run(settingsCurrent?{actor:c.peer!,current:settingsCurrent}:undefined,()=>scope.settingsSet(msg.key,msg.value,settingsCurrent?"conductor":"terminal",msg.confirm,msg.now,msg.reason)).then(reply, error => reply(scope.operationalFailure(error,"the setting could not be changed; inspect hub.log")));
195
+ return;
196
+ }
197
+
198
+ export function settingsUndoMessage(scope: DaemonScope, m: ControlMessage): void {
199
+ const { c, msg, reply } = m;
200
+ if (c.role !== "console") return void reply({ ok: false, error: "settings are a person's: run ahub settings in a terminal" });
201
+ return void scope.settingsUndo("terminal", msg.confirm, msg.now, msg.reason, msg.key, msg.undoDigest).then(reply, () => reply({ ok: false, error: "the setting could not be undone; inspect hub.log" }));
202
+ }
203
+
204
+ export function configEditGetMessage(scope: DaemonScope, m: ControlMessage): void {
205
+ const { c, reply } = m;
206
+ if (c.role !== "console") return void reply({ ok: false, error: "config edits are a person's: run ahub settings edit in a terminal" });
207
+ return void reply({ ok: true, ...scope.configEditor!.view() });
208
+ }
209
+
210
+ export function configEditPreviewMessage(scope: DaemonScope, m: ControlMessage): void {
211
+ const { c, msg, reply } = m;
212
+ if (c.role !== "console") return void reply({ ok: false, error: "config edits are a person's: run ahub settings edit in a terminal" });
213
+ return void reply(scope.configEditor!.preview(msg.edit, "terminal"));
214
+ }
215
+
216
+ export function configEditApplyMessage(scope: DaemonScope, m: ControlMessage): void {
217
+ const { c, msg, reply } = m;
218
+ if (c.role !== "console") return void reply({ ok: false, error: "config edits are a person's: run ahub settings edit in a terminal" });
219
+ void scope.configEditor!.apply(msg.edit, "terminal", msg.confirm, msg.reason).then(reply, () => reply({ ok: false, error: "the config edit could not be completed; inspect hub.log" }));
220
+ return;
221
+ }
@@ -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
+ }