@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
package/src/hub/daemon.ts CHANGED
@@ -1,4 +1,8 @@
1
+ import { hostedControlWebSocket, type HostLaunchOptions } from "./host.ts";
2
+ import { PiRestartLedger, piExitReason, piRestartableReason } from "./pi-exit-policy.ts";
3
+ import { dispatchControlMessage } from "./control/dispatch.ts";
1
4
  import { PeerActivityTracker } from "./peer-activity.ts";
5
+ import { TriageAdec } from "./adec-triage.ts";
2
6
  import { codexActivityServers } from "../adapters/definitions/native-activity.ts";
3
7
  import { QuotaEventFilter } from "./quota-events.ts";
4
8
  import { piFailureText } from "./pi-failure.ts";
@@ -6,7 +10,6 @@ import { nativeReviewerQuota } from "../adapters/definitions/native-quota.ts";
6
10
  import { GuidanceProbeStore } from "./guidance-probe-store.ts";
7
11
  import { GuidanceProbeError, probeSessionGeneration, probeSha256, type ProbePublicReceipt, type ProbePublicStatus, type ProbeReceiptExport } from "./guidance-probes.ts";
8
12
  import { executionText, EXECUTION_REFERENCE_LIMITS } from "./execution-reference.ts";
9
- import { publicDeliveryBodies, publicDeliveryReason } from "./delivery-public.ts";
10
13
  import { GeneratedNoteRegistry, type GeneratedNoteProof } from "../memory/record-provenance.ts";
11
14
  import { RecordCapture, type RecordCapturePolicy } from "../memory/records.ts";
12
15
  import { VisualStore, validateVisualPayload, VISUAL_ID_PATTERN, type VisualRecord, type VisualSummary } from "./visual.ts";
@@ -18,8 +21,7 @@ import { createReviewMaterialReader, type ReviewReadRequest, type ReviewMaterial
18
21
  import { readSdlcPr } from "./sdlc.ts";
19
22
  import type { ActionMeta } from "@staix/agent-console/contract";
20
23
  import { isReviewObserverExcluded, reviewCaptureExcluded } from "./memory-policy.ts";
21
- import { RoomStoreError } from "../rooms/store.ts";
22
- import { RoomCommands, RoomRotationHoldError, type RoomPreview } from "../rooms/commands.ts";
24
+ import { RoomCommands, type RoomPreview } from "../rooms/commands.ts";
23
25
  import { queueBackpressurePolicy } from "./queue-backpressure.ts";
24
26
  import { RoomChat, type RoomInvocationIngress } from "../rooms/service.ts";
25
27
  import { RoomInvocations, roomInvocationHash } from "./room-invocations.ts";
@@ -27,7 +29,7 @@ import { parseRemotePeerId, roomInvocationArgs, encodeRoomInvocationBody, type R
27
29
  import { assertNativeProofPorts } from "../adapters/native-proof-ports.ts";
28
30
  import { externalInstanceCatalog } from "../adapters/external-metadata.ts";
29
31
  import { externalInstanceBinding, sameExternalInstanceBinding, externalInstanceStateDir, readExternalInstanceRecord, writeExternalInstanceRecord, type ExternalInstanceBinding } from "./external-instance.ts";
30
- import { OperationalAuthorityError, OPERATIONAL_PERSON_GUIDANCE, operationalRosterSetting, operationalSetting, operationalRefusal, operationalRequestLabel, CONDUCTOR_DAEMON_OPERATIONS, CONDUCTOR_TASK_OPS, conductorLocalOperation } from "./operational-authority.ts";
32
+ import { OperationalAuthorityError, OPERATIONAL_PERSON_GUIDANCE, operationalRefusal, operationalRequestLabel, CONDUCTOR_DAEMON_OPERATIONS, CONDUCTOR_TASK_OPS, conductorLocalOperation } from "./operational-authority.ts";
31
33
  import { operationalView, redactBusEvent } from "./operational-view.ts";
32
34
  import { inspectSelectedOrphans, stopSelectedOrphan, orphanProcessPorts } from "./orphan-process.ts";
33
35
  import { lastEventTime, rotateEventsIfLarge, textLogRotator } from "./log-rotation.ts";
@@ -87,7 +89,7 @@ import { profileName, resolveProfile } from "./profiles.ts";
87
89
  import { catalogAssignments, loadRoleCatalog, selectedRoles, roleIdentity } from "./roles.ts";
88
90
  import { ActivityRing } from "./activity.ts";
89
91
  import { buildHubCheck, expectedHubLink } from "./hub-check.ts";
90
- import { JcodeOptionMismatch, JcodeTuiRefusal, isJcodePeer, jcodeDetachedNotice, jcodeToolCeilingCause, jcodeVersionAsync, refusedHelloProcess, type JcodePeer } from "../adapters/jcode.ts";
92
+ import { jcodeDetachedNotice, jcodeToolCeilingCause, jcodeVersionAsync, refusedHelloProcess, type JcodePeer } from "../adapters/jcode.ts";
91
93
  import { VERSION_REFUSAL, configuredCommands, describe, isCompatId } from "../adapters/compat.ts";
92
94
  import { agentVersionsAsync, type AgentVersionRow } from "../cli/agents.ts";
93
95
  import { driftedAgents, noticeDrift, type DriftedAgent } from "./agent-drift.ts";
@@ -130,7 +132,7 @@ import { busOperationalReaders } from "./operational-settings.ts";
130
132
  import { scheduleKeyOf, scheduleViews, ScheduleStore, type ScheduleEntry } from "./schedules.ts";
131
133
  import { MEMORY_REVIEW_DEFAULTS, memoryReviewEntry, memoryReviewTask, reviewBudgetNote, reviewBudgetStop, reviewCheckpointRequest, type ReviewSpend } from "./memory-review.ts";
132
134
  import { FolderStore, registerScanned, scanFolder, type FolderPolicy } from "./folder-trigger.ts";
133
- import { QuestionStore, QUESTION_SURFACES, questionView } from "./questions.ts";
135
+ import { QuestionStore, questionView } from "./questions.ts";
134
136
  import { RunTracker, outcomeOf, settleVerdict, type Run } from "./completions.ts";
135
137
  import { resultDetail, type ResultDetail } from "./completion-detail.ts";
136
138
  import { CompletionStore } from "./completions-store.ts";
@@ -160,7 +162,7 @@ import { ExecutionBudget } from "./execution-budget.ts";
160
162
  import { claudeReportedTokens, readClaudeTranscriptUsage, waitForClaudeCompletion } from "./usage.ts";
161
163
  import type { ServerWebSocket, WebSocketHandler } from "bun";
162
164
  import { isAcpPeer, managedAcpLaunch, verifyManagedAcpLaunch, type AcpOptions, type AcpPeer, QwenIdentityError, ACTION_BUDGET_OPTION, type PermissionRequest, type ActionGateVerdict } from "../adapters/acp.ts";
163
- import { compareNextCodexQuotaHome, isCodexPeer, type CodexPeer } from "../adapters/codex-appserver.ts";
165
+ import { isCodexPeer, type CodexPeer } from "../adapters/codex-appserver.ts";
164
166
  import { isPiPeer, PiVersionRefusal, type PiPeer } from "../adapters/pi.ts";
165
167
  import { isQwenDualPeer, qwenDualVersionAsync, type QwenDualPeer } from "../adapters/qwen-dual.ts";
166
168
  import { startModelRelay, type ModelRelay } from "../models/relay.ts";
@@ -199,7 +201,7 @@ import { CorpusIndex } from "./corpus.ts";
199
201
  import { corpusEvidence } from "./corpus-evidence.ts";
200
202
  import { Briefs, preferRecordItems, type NativeItem, type BriefTask } from "../memory/brief.ts";
201
203
  import { Board, isClosedTaskState, taskProposalAt, taskHasStarted, CLASSES, type Task, type TaskClass } from "./board.ts";
202
- import { UsageRollup, USAGE_GROUPS, LIMITS_MAX, type UsageGroup } from "./usage-rollup.ts";
204
+ import { UsageRollup } from "./usage-rollup.ts";
203
205
  import { Budget, readNativeQuota } from "./budget.ts";
204
206
  import { earlyBudgetWarning, projectExhaustion, windowLeft, WINDOW_MINS, type ExhaustionProjection } from "./budget-projection.ts";
205
207
  import { remoteEnvelope, HUB } from "./envelope.ts";
@@ -215,37 +217,37 @@ import type { BusEvent, PublishResult } from "./bus.ts";
215
217
  import { QUESTION_TOOLS, CONDUCTOR_TOOLS, CONDUCTOR_TOOL_NAMES, IMPLEMENTER_HUB_TOOL_NAMES, roleContract, TASK_TOOL_NAMES, TASK_TOOLS, GUIDANCE_TOOL_NAMES, DEFAULT_ROLES, profileTaskTools, sessionTitleTools } from "./hub-tools.ts";
216
218
  import { readShare, shareView, type CapabilityManifest, effectiveClass } from "./capabilities.ts";
217
219
  import { invocationApproval, checkArgs, DEFAULT_TIMEOUT_S, InvocationLedger, invocationRefusal, refusedBy, renderInvocationResult, requestText, type InvocationOutcome, type InvocationRow } from "./invocations.ts";
218
- import { Conductor, ConductorHolds, conductorPeer, requireConductor, conductorProgressSink, publicPeerBudget, type ConductEvent } from "./conductor.ts";
219
- import { SupervisionFeed } from "./supervision.ts";
220
+ import { Conductor, ConductorHolds, conductorPeer, requireConductor, conductorProgressSink, type ConductEvent } from "./conductor.ts";
221
+ import { SupervisionFeed, holdNoticeDelivery } from "./supervision.ts";
220
222
  import { MAX_REFS, taskRevision, type SupervisionFacts, type SupervisionHistoryFact } from "./supervision-rules.ts";
221
223
  import { ProposalStore, SupervisionProposals, type SupervisionProposal } from "./supervision-proposals.ts";
222
224
  import { drainCliAudits } from "../cli/identity-audit.ts";
223
225
  import { launcherPreview } from "../cli/preview.ts";
224
226
  import { AssignmentUndeliveredError, ESCALATE_AFTER, Tasks } from "./tasks.ts";
225
227
  import { DIGEST, Inference, screenPii, type PiiVerdict } from "./inference.ts";
226
- import { taskEvidencePrivacy, type TaskEvidencePrivacy, ask, ASK_NOTE_TITLE, RUN_START } from "./ask.ts";
227
- import { currentRouting, detectSignals, OVERLAY_FILE, overlayToml, parseRouting, routingText, type Routing } from "./routing.ts";
228
+ import { ASK_NOTE_TITLE, RUN_START } from "./ask.ts";
229
+ import { currentRouting, OVERLAY_FILE, overlayToml, parseRouting, routingText, type Routing } from "./routing.ts";
228
230
  import { autonomyConsentStateDir, createAutonomyConsent, type AutonomyConsentValues } from "./autonomy-consent.ts";
229
231
  import { insideRoot } from "./path-policy.ts";
230
232
  import { autonomyPreset, autonomyEnvironment, planAutonomy, autonomyRemovalKeys, autonomyStatus, type AutonomyEnvironment, type AutonomyPeer } from "./autonomy.ts";
231
233
  import { readAutonomyDefaults } from "./autonomy-defaults.ts";
232
- import { AUTONOMY_UNDO, autonomyOwnershipDigest, autonomyUndoKeys, writeAutonomyPreset, LEARN_CHECKLIST, NEVER_EDITABLE, projectSettings, checkSettingValue, pendingUndo, pendingUndoIdentity, readOverlay, restoredValue, routingCandidate, storedLocally, sharedValue, settingDef as instanceSettingDef, settingRefusal, settingRows, settingText, undoSetting, valueAt, writeConfigSetting, writeRoutingSetting, type SettingAuthority, type SettingSource, type SettingDef, type SettingRow, type SettingValue, type UndoIdentity, ignoredLine } from "./settings.ts";
234
+ import { AUTONOMY_UNDO, autonomyOwnershipDigest, autonomyUndoKeys, writeAutonomyPreset, LEARN_CHECKLIST, projectSettings, checkSettingValue, pendingUndo, pendingUndoIdentity, readOverlay, restoredValue, routingCandidate, storedLocally, sharedValue, settingDef as instanceSettingDef, settingRefusal, settingRows, settingText, undoSetting, valueAt, writeConfigSetting, writeRoutingSetting, type SettingAuthority, type SettingSource, type SettingDef, type SettingRow, type SettingValue, type UndoIdentity, ignoredLine } from "./settings.ts";
233
235
  import { githubOriginRepository, githubRemoteRepository } from "./task-repository.ts";
234
236
  import { TaskWorktrees, originVerdict } from "./task-worktree.ts";
235
237
  import { displayPath, shelfInsideRoot, partition, readWorktreeFacts, type ShelfRow } from "./worktree-shelf.ts";
236
238
  import { PrObservations, refreshPrStates, refreshTargets } from "./worktree-prs.ts";
237
- import { Bus, ReviewInputHandoffError } from "./bus.ts";
239
+ import { Bus } from "./bus.ts";
238
240
  import { queueResolveChoices, queueResolveCommand } from "./person-command.ts";
239
241
  import { attribute, deliveryTask, type TaskAttribution } from "./attribution.ts";
240
242
  import { ACCEPTED_SETTLE_TIMEOUT_REASON, DeliveryJournal } from "./delivery-journal.ts";
241
243
  import { assertHubDbCompatible } from "./db-schema.ts";
242
- import { startDashboard, dashboardView, type DashboardSession } from "./ui.ts";
244
+ import { startDashboard, type DashboardSession } from "./ui.ts";
243
245
  import { codeGroup } from "./task-code-group.ts";
244
246
  import { ControlClient, DAEMON_FEATURES, HANDOFF_LOOKUP_CONNECT_MS, HANDOFF_LOOKUP_REQUEST_MS, PROTOCOL, PROTOCOL_MIN, readControl, stateDirFor } from "./control-client.ts";
245
247
  import { BRIDGE_PROTOCOL_RELEASES, DEFAULT_BRIDGE_WINDOW, bridgeProtocolWindow, bridgeWindowSettings, negotiateProtocol, protocolWindow } from "./protocol-window.ts";
246
248
  import { attachEvent, originOf, type Origin } from "./provenance.ts";
247
249
  import { mintSessionId, sessionGate } from "./session-identity.ts";
248
- import { MAX_HOP, isInvocationKind, newEnvelope, parseMarker, replyParent, sanitize, USER, type Envelope, type PeerId } from "./envelope.ts";
250
+ import { MAX_HOP, isInvocationKind, newEnvelope, replyParent, sanitize, USER, type Envelope, type PeerId } from "./envelope.ts";
249
251
  import { BasePeer, type FrontendProxyPort, type PeerAdapter, type PeerTakeoverClaim } from "./peers.ts";
250
252
  import { ClaudeTodoSource, DoingTracker, DOING_STUB, SESSION_TITLE_HINT, sessionTitleText, sessionTitleBindings, unnamedSessionLabel, type DoingKind, type PeerDoing, type TitleCursor } from "./peer-doing.ts";
251
253
  import { MemoryClient } from "../memory/client.ts";
@@ -266,7 +268,7 @@ import { Limiter, PROJECT_LIMITS, type LimitsConfig } from "./limits.ts";
266
268
  import { soleWorktree, branchHeads, changedPaths, dirtySubmodules, submodulePaths, knownChangedPaths, hasTree, headState, headMoveCursor, incomingHeadPaths, repoOf, snapshot, SnapshotBudgetExceeded, SnapshotCooldown, budgetNow, Turns, type SnapshotBudget, type HeadMoveCursor, type Repo, type TurnRecord } from "./snapshots.ts";
267
269
  import { readRecoveryWaivers, readRestartSnapshot, restartPath, type RecoveryPhase, type RestartPeerSnapshot } from "./restart.ts";
268
270
  import { consumeRecoveryContinuity, readRecoveryContinuity, retireRecoveryContinuity } from "./recovery-continuity.ts";
269
- import { shellQuote, publishTerminalLaunch, terminalLaunchCandidate, launcherOf, orcaExecutable } from "../cli/terminal-recovery.ts";
271
+ import { shellQuote, publishTerminalLaunch, launcherOf, orcaExecutable } from "../cli/terminal-recovery.ts";
270
272
  import { OrcaPaneWatch, orcaAgentRunner } from "./orca-state.ts";
271
273
  import { TerminalLaunches, terminalOwnerReads } from "./terminal-launch.ts";
272
274
 
@@ -291,11 +293,7 @@ import { createMemorySyncPolicy, inspectDeclinedMemoryRows } from "./memory-sync
291
293
 
292
294
  import { CONFIG_FILES, DEFAULT_CONFIG as declarationDefaults, loadConfig as loadDeclarationConfig, loadConductorPolicy, mlxLaunchProblem, type HubConfig } from "./config.ts";
293
295
  import { taskOpBody as runTaskOpBody } from "./control/hub-tools.ts";
294
- import { boardRevision, conductorOperational, goalLink, guidanceMessage, guidanceProbeMessage, lineageMessage, reviewBlob, reviewCommentWrite, reviewCommentsRead, taskCatalogRole, taskHandoff, taskHandoffByKey, taskHandoffEvent, taskHandoffStates, taskMessage } from "./control/board-messages.ts";
295
- import { sdlcMessage } from "./control/sdlc-messages.ts";
296
296
  import { uiAction as runUiAction } from "./control/ui-actions.ts";
297
- import { requestCancelMessage, permissionFailureProbeMessage, permissionRequestMessage, permissionDefaultMessage, permissionMessage, executionBudgetMessage, recoveryRestoreMessage, recoveryAuthorityMessage, recoveryMessage } from "./control/recovery-messages.ts";
298
- import { nativeHookLaunchMessage, nativeFactsMessage, instructionExecuteMessage, instructionHookMessage, factsMessage } from "./control/native-messages.ts";
299
297
  import type { DaemonScope, NativeTurnStart, ImplementerFailureEntry, GuidanceProbeRequestContext, ModelGrant, ReceiptSurface, RoadmapDrift, TitleResult, VisualFilePolicy } from "./control/scope.ts";
300
298
 
301
299
  export { loadConductorPolicy, type ConfigLayer, type HubConfig } from "./config.ts";
@@ -357,6 +355,8 @@ export interface DaemonOptions {
357
355
  context?: DaemonProjectContext;
358
356
  /** #1779 T3a: set by a host process; reported in `status.json` and the status reply. */
359
357
  hostId?: string;
358
+ /** Host-only containment at the Bun control WebSocket boundary. */
359
+ runControlWebSocket?: HostLaunchOptions["runControlWebSocket"];
360
360
  /** Host-only fixture override; production reads the active memory home's and execution repository's public Record policy. */
361
361
  effectiveRecordPolicy?: (cwd: string) => { enabled: boolean; version: string } | undefined;
362
362
  /** Host-only test trigger; production schedules its own unreferenced settlement interval. */
@@ -658,7 +658,6 @@ export async function startDaemon(opts: DaemonOptions) {
658
658
  const envelopeOrigins = new Map<string, Origin>();
659
659
  /** agent-hub#1036: the ids this daemon minted for live distinct sessions. Only the daemon makes them, so `PEER_ID` is not widened and no `@` reaches the remote-room paths. */
660
660
  const sessionIds = new Set<string>();
661
- const rememberOrigin = (id: string, origin: Origin): void => { envelopeOrigins.set(id, origin); if (envelopeOrigins.size > 1024) envelopeOrigins.delete(envelopeOrigins.keys().next().value as string); };
662
661
  const takeOrigin = (id: string): Origin | undefined => { const origin = envelopeOrigins.get(id); envelopeOrigins.delete(id); return origin; };
663
662
  /**
664
663
  * agent-hub#1036: the origin of an envelope that no control connection sent, one an adapter published itself (a native peer's final answer goes through `peer.onMessage`, not the `send` case).
@@ -813,17 +812,18 @@ export async function startDaemon(opts: DaemonOptions) {
813
812
  };
814
813
  // #514b: undo resolves the managed checklist key, which is not a settings row, and every other key through the project-scoped lookup above (declared instances, the adapter catalog, a stale roster key).
815
814
  const undoableDef = (key: unknown): SettingDef | string => key === AUTONOMY_UNDO.key ? AUTONOMY_UNDO : key === LEARN_CHECKLIST.key ? LEARN_CHECKLIST : settingDef(key);
816
- // #1810: the budget key of a peer is its account, plus `:<label>` when its session runs under a declared account. An undeclared home keeps the bare key (today's), a key built here
817
- // resolves to itself (the budget requires an idempotent resolver), and no peer id contains a colon.
815
+ // #1810/#1941: declared kinds use `<kind>:<label>` or `<kind>:default`; other kinds keep the bare key.
816
+ // An account key resolves to itself, and no peer id contains a colon.
818
817
  // Any peer that carries an `accountLabel` (the channel peer does) reports it; this is a read of a display label, not a host branch on the peer class.
819
818
  // A session's label comes from its home; a daemon-owned instance's from its declared `account` (#1810 AC3), so both budget under `<kind>:<label>`.
820
819
  const peerAccountLabel = (peer: string): string | undefined => (bus.peers.get(peer) as { accountLabel?: string } | undefined)?.accountLabel ?? declarations[peer]?.account;
821
- const accountOf = (peer: string): string => accountKeyFor(peer, definitionOf(peer)?.budget?.account, declarations[peer]?.kind, peerAccountLabel(peer));
820
+ const defaultAccountNamed = (account: string): boolean => Object.values(config.accounts ?? {}).some(declared => declared.kind === account); // #1941
821
+ const accountOf = (peer: string): string => accountKeyFor(peer, definitionOf(peer)?.budget?.account, declarations[peer]?.kind, peerAccountLabel(peer), defaultAccountNamed);
822
822
  // The account a handoff compares: the budget key, or just its kind when `budget.cross_account_handoff` is off (two labels of one kind are then siblings).
823
823
  const handoffAccountOf = (peer: string): string => config.budget.cross_account_handoff === false ? baseAccount(accountOf(peer)) : accountOf(peer);
824
824
  // #1810 AC3: a daemon-owned instance that names an account starts with that account's home in its kind's own variable. The home is read here from the loaded config and goes only into the child's environment.
825
825
  const instanceAccountEnv = (peer: string): NodeJS.ProcessEnv | undefined => instanceAccountEnvOf(declarations[peer]?.account, config.accounts, definitionOf(peer)?.session.configDirEnv);
826
- const accountMembers = (account: string) => [...new Set([...SUPPORTED_PEERS, ...Object.keys(declarations)])].filter(peer => accountOf(peer) === account);
826
+ const accountMembers = (account: string, keyOf = accountOf) => [...new Set([...SUPPORTED_PEERS, ...Object.keys(declarations)])].filter(peer => keyOf(peer) === account);
827
827
  let rosterChanging: string | undefined;
828
828
  let kimiSessionMode: StartMode | undefined;
829
829
  let kimiAdmissionId: string | undefined;
@@ -882,16 +882,6 @@ export async function startDaemon(opts: DaemonOptions) {
882
882
  for (const row of rejected) rows.set(sanitize(row.key).slice(0, 160), sanitize(row.reason).slice(0, 1200));
883
883
  return [...rows].map(([key, reason]) => ({ key, reason })).sort((left, right) => left.key.localeCompare(right.key));
884
884
  }
885
- function retainedLaunchConfig(peer: string): Record<string, unknown> | undefined {
886
- const keys = definitionOf(peer)?.cli.launchConfigKeys ?? [];
887
- const pending = retainedConfig.filter(row => keys.some(key => row.key === key || row.key.startsWith(`${key}.`)));
888
- if (!pending.length) return;
889
- return Object.fromEntries(pending.map(row => [row.key, valueAt(config, row.key.split("."))]));
890
- }
891
- const includeRetainedLaunchConfig = (peer: string, result: Record<string, unknown>): Record<string, unknown> => {
892
- const values = retainedLaunchConfig(peer);
893
- return values ? { ...result, retainedLaunchConfig: values } : result;
894
- };
895
885
  let lastReloadFailure: string | undefined;
896
886
  let reloadDebounce: ReturnType<typeof setTimeout> | undefined;
897
887
  let configWatchPending = false;
@@ -1051,7 +1041,7 @@ export async function startDaemon(opts: DaemonOptions) {
1051
1041
  if (new URL(req.url).pathname === "/healthz") return new Response("ok");
1052
1042
  return srv.upgrade(req, { data: { authed: false } }) ? undefined : new Response("agent-hub control");
1053
1043
  },
1054
- websocket: controlWebsocket = {
1044
+ websocket: controlWebsocket = hostedControlWebSocket({
1055
1045
  message(sock, data) {
1056
1046
  let parsed: any;
1057
1047
  try {
@@ -1091,7 +1081,7 @@ export async function startDaemon(opts: DaemonOptions) {
1091
1081
  writeStatus();
1092
1082
  }
1093
1083
  },
1094
- },
1084
+ }, opts.runControlWebSocket),
1095
1085
  }), opts.controlPort === 0 ? [opts.codexAppPort, opts.codexProxyPort] : []);
1096
1086
  // Written once this run owns the port, before any connection can attach a peer: a daemon that fails to bind (another
1097
1087
  // is running) never marks a run boundary in the live one's events.
@@ -2593,13 +2583,13 @@ export async function startDaemon(opts: DaemonOptions) {
2593
2583
  const headroom = budget.headroom(), rows = [...bus.peers].filter(([, peer]) => peer.state !== "offline");
2594
2584
  const reasons: string[] = [], notes: string[] = [];
2595
2585
  for (const [id] of rows) {
2596
- const definition = definitionOf(id), account = definition?.budget?.account ?? id;
2586
+ const definition = definitionOf(id), account = accountOf(id);
2597
2587
  if (manualPaused.has(id)) reasons.push(`${id}: manual pause; ahub resume ${id}`);
2598
2588
  if (budget.record(account)) reasons.push(`${id}: paused quota window; inspect ahub budget or ahub budget resume ${id}`);
2599
2589
  if (definition && (!definition.budget || definition.budget.quotaExempt)) continue;
2600
- // Source availability belongs to the shared account, including its offline base and reviewer variants.
2601
- // The soft token window uses the same definition capability that resets it on resume.
2602
- const hasSource = accountMembers(account).some(member => {
2590
+ // Quota reader capability belongs to the kind, even if its offline base has no account label.
2591
+ // Read the pause and headroom under the exact account, including its label.
2592
+ const hasSource = accountMembers(baseAccount(account), peer => baseAccount(accountOf(peer))).some(member => {
2603
2593
  const policy = definitionOf(member)?.budget;
2604
2594
  return !!policy?.reader || !!policy?.resetSoftTokensOnResume && config.budget.kimi_tokens_5h > 0;
2605
2595
  });
@@ -2866,6 +2856,7 @@ export async function startDaemon(opts: DaemonOptions) {
2866
2856
  () => boundedSafe(`${title}\n${detail}`)) : classify();
2867
2857
  },
2868
2858
  onCampus: () => controlWriteTelemetry ? controlWriteTelemetry.observe("external", controlWritePrivacyGuard(true, true), () => onCampus()) : onCampus(),
2859
+ adec: new TriageAdec({ mode: () => currentRouting(opts.cwd, log).inference.triage_adec, endpoint: () => currentRouting(opts.cwd, log).inference.triage_adec_endpoint, log }),
2869
2860
  },
2870
2861
  // #334: the hub model's split, validated against the same `hub_backlog_split` parts schema a planner's call is, and the source registry for `--source`.
2871
2862
  intake: { split: (system, user, opts) => {
@@ -3079,7 +3070,7 @@ export async function startDaemon(opts: DaemonOptions) {
3079
3070
  const key = env.refs.supervisionKey ?? "";
3080
3071
  const approval = key.match(/:approval:([^:]+)$/)?.[1];
3081
3072
  if (approval) { const pending = permissions.get(approval); return !!pending && pending.expiresAt > Date.now(); }
3082
- const delivery = key.match(/:hold:[^:]+:([^:]+)$/)?.[1];
3073
+ const delivery = holdNoticeDelivery(key);
3083
3074
  if (delivery) return bus.queueShow(delivery)?.state === "needs_review";
3084
3075
  if (env.refs.task && config.conductor.feed === "own") { const task = board.get(Number(env.refs.task)); return !!task && supervision.includes(task); }
3085
3076
  return true;
@@ -4661,7 +4652,7 @@ export async function startDaemon(opts: DaemonOptions) {
4661
4652
  if (agentDrift.length && !stopping && !recoveryActive()) try { offerAgentDrift(); } catch { /* the next tick tries again */ }
4662
4653
  for (const pending of checkpointWaits.values()) if (!pending.valid()) pending.done(undefined);
4663
4654
  for (const [id, request] of permissions) if (request.expiresAt > Date.now()) supervision.approvalWaiting({ id, peer: request.peer, tool: request.tool ?? "unknown", createdAt: request.createdAt });
4664
- for (const row of bus.queueList(undefined, true)) if (row.state === "needs_review" && row.reason !== ACCEPTED_SETTLE_TIMEOUT_REASON) supervision.needsReview(row.peer, row.id, () => holdCommand(row.peer, row.id));
4655
+ for (const row of bus.queueList(undefined, true)) if (row.state === "needs_review" && row.reason !== ACCEPTED_SETTLE_TIMEOUT_REASON) supervision.needsReview(row.peer, row.id, () => holdCommand(row.peer, row.id), selfHold(row.holdsSelf === true, row.originals.some(isInvocationKind)));
4665
4656
  feedBudgetPauses();
4666
4657
  supervision.checkRound();
4667
4658
  try {
@@ -4738,7 +4729,7 @@ export async function startDaemon(opts: DaemonOptions) {
4738
4729
  // The file's own timestamp, not "now": a file left behind by yesterday's session is a stale reading, not a fresh one.
4739
4730
  for (const adapter of ADAPTERS.filter(adapter => adapter.transport === "claude-channel")) {
4740
4731
  const windows = readNativeQuota(adapter, usage.rate_limits);
4741
- if (windows) budget.report(adapter.kind, windows, false, Number(usage.at) || mtime, undefined,
4732
+ if (windows) budget.report(accountKeyFor(adapter.kind, adapter.budget?.account, undefined, DEFAULT_ACCOUNT_LABEL, defaultAccountNamed), windows, false, Number(usage.at) || mtime, undefined,
4742
4733
  { forecastSession: { sessionId: usage.sessionId, launchId: usage.launchId } });
4743
4734
  }
4744
4735
  } catch {
@@ -5119,10 +5110,6 @@ export async function startDaemon(opts: DaemonOptions) {
5119
5110
  try { return renderHeldHint(bus.heldDeliveryHints(peer), Date.now(), deliveryRetryAllowed(bus.peers.get(peer))); }
5120
5111
  catch { return ""; } // unavailable telemetry is not a zero count or a reason to fail the tool itself
5121
5112
  }
5122
- function inboxHeldMetadata(peer: PeerId, includeAccepted = false) {
5123
- try { return bus.heldDeliveryHints(peer, includeAccepted) ?? { unavailable: true as const }; }
5124
- catch { return { unavailable: true as const }; } // advisory failure is explicit without exposing an error or hiding a settled pull
5125
- }
5126
5113
  /** A model-written peer argument: a peer id, or nothing for absent, null or "". Anything else is refused. */
5127
5114
  const peerArg = (v: unknown, name: string): PeerId | undefined => {
5128
5115
  if (v == null || v === "") return undefined;
@@ -5675,6 +5662,65 @@ export async function startDaemon(opts: DaemonOptions) {
5675
5662
  set transcriptRead(value) { transcriptRead = value; },
5676
5663
  get turnEnded() { return turnEnded; },
5677
5664
  get writeStatus() { return writeStatus; },
5665
+ get SERVER_JS() { return SERVER_JS; },
5666
+ get accountMembers() { return accountMembers; },
5667
+ get accountOf() { return accountOf; },
5668
+ get activityRings() { return activityRings; },
5669
+ get autonomyCommand() { return autonomyCommand; },
5670
+ get budgetPeerNotes() { return budgetPeerNotes; },
5671
+ get budgetViews() { return budgetViews; },
5672
+ get channelTakeoverAdmission() { return channelTakeoverAdmission; },
5673
+ get clearKimiAdmission() { return clearKimiAdmission; },
5674
+ get contextSession() { return contextSession; },
5675
+ get contexts() { return contexts; },
5676
+ get controlOperationFailed() { return controlOperationFailed; },
5677
+ get corpusPolicyVersion() { return corpusPolicyVersion; },
5678
+ get dashboard() { return dashboard; },
5679
+ set dashboard(value) { dashboard = value; },
5680
+ get dashboardSnapshot() { return dashboardSnapshot; },
5681
+ get drainCliAuditsNow() { return drainCliAuditsNow; },
5682
+ get envelopeOrigins() { return envelopeOrigins; },
5683
+ get implementerChatTask() { return implementerChatTask; },
5684
+ get inboxPolling() { return inboxPolling; },
5685
+ get inference() { return inference; },
5686
+ get instructedQuestionViews() { return instructedQuestionViews; },
5687
+ get kimiAdmissionId() { return kimiAdmissionId; },
5688
+ get kimiSessionMode() { return kimiSessionMode; },
5689
+ get kimiUsage() { return kimiUsage; },
5690
+ get logFile() { return logFile; },
5691
+ get memoryLine() { return memoryLine; },
5692
+ get noteSteeredReviewInput() { return noteSteeredReviewInput; },
5693
+ get orphanChecks() { return orphanChecks; },
5694
+ get ownedObserverInputs() { return ownedObserverInputs; },
5695
+ get peerAccountLabel() { return peerAccountLabel; },
5696
+ get piReplacementAuthority() { return piReplacementAuthority; },
5697
+ get projectSpecs() { return projectSpecs; },
5698
+ get publicCorpus() { return publicCorpus; },
5699
+ get recoveryPeerAllowed() { return recoveryPeerAllowed; },
5700
+ get redact() { return redact; },
5701
+ get resolutionRefusal() { return resolutionRefusal; },
5702
+ get resultView() { return resultView; },
5703
+ get retainedCliAudits() { return retainedCliAudits; },
5704
+ get retainedConfig() { return retainedConfig; },
5705
+ get reviewInputHeld() { return reviewInputHeld; },
5706
+ get reviewOnlyItem() { return reviewOnlyItem; },
5707
+ get reviewerBudgetView() { return reviewerBudgetView; },
5708
+ get revokeTerminalExecution() { return revokeTerminalExecution; },
5709
+ get roomChat() { return roomChat; },
5710
+ get roomCommands() { return roomCommands; },
5711
+ get roomTickets() { return roomTickets; },
5712
+ get rosterView() { return rosterView; },
5713
+ get settingsView() { return settingsView; },
5714
+ get specsMissingBlockHintShown() { return specsMissingBlockHintShown; },
5715
+ set specsMissingBlockHintShown(value) { specsMissingBlockHintShown = value; },
5716
+ get startHeldByRecovery() { return startHeldByRecovery; },
5717
+ get startMode() { return startMode; },
5718
+ get startPeerTakeover() { return startPeerTakeover; },
5719
+ get status() { return status; },
5720
+ get stopPeer() { return stopPeer; },
5721
+ get terminalLaunches() { return terminalLaunches; },
5722
+ get uiAction() { return uiAction; },
5723
+ get usageRollup() { return usageRollup; },
5678
5724
  };
5679
5725
  async function taskOpBody(by: PeerId, op: string, a: Record<string, any>, inProcess = false, piiTurn = false, toolSocket?: Sock): Promise<string> {
5680
5726
  return runTaskOpBody(daemonScope, by, op, a, inProcess, piiTurn, toolSocket);
@@ -6050,7 +6096,6 @@ export async function startDaemon(opts: DaemonOptions) {
6050
6096
  * `uiAction`. A receipt is only ever the person's: the callers check the role or the session before they get here. Each write is held during recovery or shutdown, names its
6051
6097
  * refusal, and emits `completion_seen` (id and surface, no text) for exactly the rows it changed.
6052
6098
  */
6053
- const receiptSurface = (value: unknown): ReceiptSurface => (["terminal", "console", "dashboard", "acon"] as const).find(known => known === value) ?? "console";
6054
6099
  const receiptHeld = () => recoveryActive() || stopping;
6055
6100
  const markResultSeen = (id: unknown, surface: ReceiptSurface): { ok: true; id: string } | { ok: false; error: string } => {
6056
6101
  if (receiptHeld()) return { ok: false, error: "recovery or shutdown is holding receipts; mark it read again once the hub is back" };
@@ -6193,10 +6238,6 @@ export async function startDaemon(opts: DaemonOptions) {
6193
6238
  return { importantWaitingSince: since, importantWaitingNote: `${count} important message${count === 1 ? "" : "s"} waiting on a busy ACP peer for ${minutes} min; its turn is never cancelled to deliver, so decide whether to stop it` };
6194
6239
  };
6195
6240
  /** Why a paused peer gets nothing; the bus pause itself is the hold. */
6196
- const pauseReason = (id: PeerId) => {
6197
- const r = budget.record(id), hold = conductorHolds.get(id);
6198
- return r ? `paused by the budget coordinator: ${r.reason}; to override: ahub budget resume ${id}` : 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";
6199
- };
6200
6241
  let releasing = false; // gone-owner release (#6) and the ready sweep (#34): one run at a time, and a recovery commit waits for it
6201
6242
  const recoveryReady = () => {
6202
6243
  if (!recoveryActive() || releasing || taskOpsInFlight !== 0 || tasks.checksPending() !== 0 || piCallsInFlight() !== 0 || permissions.size !== 0 || starting.size !== 0 || requestedPeerStops.size !== 0 || rosterChanging !== undefined || !budget.recoverySettled || [...bus.peers.values()].filter(peer => !peer.id.includes("@")).some((peer) => recoveryBusy(peer) || ("recoveryReady" in peer && peer.recoveryReady !== true))) return false;
@@ -6547,7 +6588,8 @@ export async function startDaemon(opts: DaemonOptions) {
6547
6588
  const modelCommandSafe = (input: Record<string, unknown>, grant: ModelGrant): Record<string, unknown> => {
6548
6589
  try { return modelCommand(input, grant); } catch { return modelFailure("model override state could not be read or written; inspect ahub status and hub.db before retrying"); }
6549
6590
  };
6550
- const queueHoldStatus = (peer: PeerId, heldBy?: string) => heldBy ? { heldBy, holdNote: queueHold(peer), heldRows: heldRows(peer) } : {};
6591
+ // #1946: a plain local needs_review row no longer holds the peer, but it stays listed (and resolvable) in status.
6592
+ const queueHoldStatus = (peer: PeerId, heldBy?: string, needsReview = 0) => heldBy ? { heldBy, holdNote: queueHold(peer), heldRows: heldRows(peer) } : needsReview > 0 ? { heldRows: heldRows(peer) } : {};
6551
6593
  const logPermissionStart = (peer: string) => {
6552
6594
  const requested = defaultSources[peer];
6553
6595
  const selected = permissionMode(peer), pending = pendingPermissionDefaults.has(peer);
@@ -6679,7 +6721,7 @@ export async function startDaemon(opts: DaemonOptions) {
6679
6721
  ...(dashboard ? { uiOrigin: dashboard.origin } : {}),
6680
6722
  codexProxyPort: opts.codexProxyPort,
6681
6723
  peers: Object.fromEntries(
6682
- peerIds.map((id) => { const p = bus.peers.get(id); const summary = bus.queueSummary(id); const pressure = queueBackpressure?.peers[id]; const oldestQueuedAt = pressure ? pressure.oldestQueuedAt : summary.oldestQueuedAt; const context = contexts.view(id, contextSession(id), !!p && ["idle", "busy", "paused"].includes(bus.stateOf(id))); const statusNotice = isFixedBuiltinDefinition(definitionOf(id)) ? p?.statusNotice : undefined; const reviewObserverHoldNote = reviewObserverSessionIdentityHoldNote(id); const detached = jcodeDetached.get(id); return [id, { state: bus.stateOf(id), ...(includeAttentionItems && isExternalInstance(id) && !externalRefusedRows.has(id) && retainedExternalBinding(id) ? { externalInstance: retainedExternalBinding(id) } : {}), ...(!membershipAllowed(id) ? { rostered: false, rosterNote: "off roster" } : {}), ...permissionStatus(id, p), ...(statusNotice ? { statusNotice } : {}), ...(detached ? { detached } : {}), ...(jcodeRefusedHello.has(id) && ownedLaunchServing(id) ? { refusedHello: jcodeRefusedHello.get(id) } : {}), ...(reviewObserverHoldNote ? { reviewObserverHoldNote } : {}), ...(context.source !== null || context.measuredAt !== null ? { context } : {}), queued: bus.queued(id), ...(p ? {} : { attached: false }), ...(includeAttentionItems && p?.standbySessions?.length ? { standbySessions: p.standbySessions } : {}), ...(includeAttentionItems && p?.ownerAttachment ? { ownerAttachment: p.ownerAttachment } : {}), ...(declarations[id] && config.roles[id]?.includes("implementer") && definitionOf(id)?.transport === "claude-channel" ? { ownerIsolation: ownerIsolation[id] === true, ...(ownerIsolation[id] !== true ? { ownerIsolationNote: "terminal execution root not verified; owner admission refused" } : {}) } : {}), ...presetStatusRow(id), ...(summary.needsReview ? { needsReview: summary.needsReview } : {}), ...(summary.liveAccepted ? { liveAccepted: summary.liveAccepted, settlementNote: "awaiting adapter completion (Claude: correlated reply or hub_delivery_done); task state is independent" } : {}), ...queueHoldStatus(id, summary.heldBy), ...(typeof oldestQueuedAt === "number" ? { oldestQueuedAt } : {}), ...(bus.queuedImportant(id) ? { queuedImportant: bus.queuedImportant(id) } : {}), ...importantWaitingStatus(id, p), ...pausedNote(id), ...(reviewerUnavailable.has(id) ? { reviewerUnavailable: reviewerUnavailable.get(id) } : {}), ...jcodeModelSource(id), ...(reviewOnlyPeer(id) ? { reviewScope: reviewScopeOf(id) } : {}), ...(isLocalPeer(p) && p.lastServedBy ? { servedBy: p.lastServedBy } : {}), ...(isWsPeer(p) ? { ...(p.claiming ? { claiming: true } : {}), ...(definitionOf(id)?.transport === "claude-channel" && p.attached ? { attachMode: p.attachMode, attachEvidence: p.attachEvidence } : {}) } : {}), ...(isWsPeer(p) && p.pullOnly ? { pullOnly: true, toolsOnly: definitionOf(id)?.attach?.pullOnlyNotice ?? "tools-only: messages wait for hub_inbox; for pushes restart Claude with ahub claude", lastInboxAt: p.lastInboxAt ?? null } : {}), ...(isPiPeer(p) ? { requestedModel: p.getRequestedModel(), backends: modelRelays.get(id)?.status().backends ?? [] } : {}) }]; }),
6724
+ peerIds.map((id) => { const p = bus.peers.get(id); const summary = bus.queueSummary(id); const pressure = queueBackpressure?.peers[id]; const oldestQueuedAt = pressure ? pressure.oldestQueuedAt : summary.oldestQueuedAt; const context = contexts.view(id, contextSession(id), !!p && ["idle", "busy", "paused"].includes(bus.stateOf(id))); const statusNotice = isFixedBuiltinDefinition(definitionOf(id)) ? p?.statusNotice : undefined; const reviewObserverHoldNote = reviewObserverSessionIdentityHoldNote(id); const detached = jcodeDetached.get(id); return [id, { state: bus.stateOf(id), ...(includeAttentionItems && isExternalInstance(id) && !externalRefusedRows.has(id) && retainedExternalBinding(id) ? { externalInstance: retainedExternalBinding(id) } : {}), ...(!membershipAllowed(id) ? { rostered: false, rosterNote: "off roster" } : {}), ...permissionStatus(id, p), ...(statusNotice ? { statusNotice } : {}), ...(detached ? { detached } : {}), ...(jcodeRefusedHello.has(id) && ownedLaunchServing(id) ? { refusedHello: jcodeRefusedHello.get(id) } : {}), ...(reviewObserverHoldNote ? { reviewObserverHoldNote } : {}), ...(context.source !== null || context.measuredAt !== null ? { context } : {}), queued: bus.queued(id), ...(p ? {} : { attached: false }), ...(includeAttentionItems && p?.standbySessions?.length ? { standbySessions: p.standbySessions } : {}), ...(includeAttentionItems && p?.ownerAttachment ? { ownerAttachment: p.ownerAttachment } : {}), ...(declarations[id] && config.roles[id]?.includes("implementer") && definitionOf(id)?.transport === "claude-channel" ? { ownerIsolation: ownerIsolation[id] === true, ...(ownerIsolation[id] !== true ? { ownerIsolationNote: "terminal execution root not verified; owner admission refused" } : {}) } : {}), ...presetStatusRow(id), ...(summary.needsReview ? { needsReview: summary.needsReview } : {}), ...(summary.liveAccepted ? { liveAccepted: summary.liveAccepted, settlementNote: "awaiting adapter completion (Claude: correlated reply or hub_delivery_done); task state is independent" } : {}), ...queueHoldStatus(id, summary.heldBy, summary.needsReview), ...(typeof oldestQueuedAt === "number" ? { oldestQueuedAt } : {}), ...(bus.queuedImportant(id) ? { queuedImportant: bus.queuedImportant(id) } : {}), ...importantWaitingStatus(id, p), ...pausedNote(id), ...(reviewerUnavailable.has(id) ? { reviewerUnavailable: reviewerUnavailable.get(id) } : {}), ...jcodeModelSource(id), ...(reviewOnlyPeer(id) ? { reviewScope: reviewScopeOf(id) } : {}), ...(isLocalPeer(p) && p.lastServedBy ? { servedBy: p.lastServedBy } : {}), ...(isWsPeer(p) ? { ...(p.claiming ? { claiming: true } : {}), ...(definitionOf(id)?.transport === "claude-channel" && p.attached ? { attachMode: p.attachMode, attachEvidence: p.attachEvidence } : {}) } : {}), ...(isWsPeer(p) && p.pullOnly ? { pullOnly: true, toolsOnly: definitionOf(id)?.attach?.pullOnlyNotice ?? "tools-only: messages wait for hub_inbox; for pushes restart Claude with ahub claude", lastInboxAt: p.lastInboxAt ?? null } : {}), ...(isPiPeer(p) ? { requestedModel: p.getRequestedModel(), backends: modelRelays.get(id)?.status().backends ?? [] } : {}) }]; }),
6683
6725
  ),
6684
6726
  peerVersions,
6685
6727
  taskWip: tasks.wipBreakdown(peerIds),
@@ -6797,7 +6839,7 @@ export async function startDaemon(opts: DaemonOptions) {
6797
6839
  return bus.queueList(peer, true).filter(row => row.state === "needs_review").map(row => ({
6798
6840
  id: row.id, senders: [...new Set(row.originals.map(env => sanitize(env.from)))],
6799
6841
  kinds: [...new Set(row.originals.map(env => env.kind))], createdAt: row.createdAt,
6800
- reason: row.reason, revision: row.revision,
6842
+ reason: row.reason, revision: row.revision, holdsSelf: row.holdsSelf === true,
6801
6843
  context: deliveryTaskContext(row.originals, board, peer),
6802
6844
  }));
6803
6845
  }
@@ -6825,6 +6867,9 @@ export async function startDaemon(opts: DaemonOptions) {
6825
6867
  }
6826
6868
  } finally { settlingSuperseded = false; }
6827
6869
  }
6870
+ // #1946: bus.hold_notice_ms, the one repeat of an unresolved hold notice.
6871
+ const holdNoticeMs = (): number => config.bus?.hold_notice_ms ?? 1_800_000;
6872
+ const selfHold = (holdsSelf: boolean | undefined, invocation: boolean) => holdsSelf === true && !invocation ? { afterMs: holdNoticeMs() } : undefined;
6828
6873
  const noticedHolds = new Set<string>();
6829
6874
  let reportingQueues = false;
6830
6875
  let queuePressureStatusQueued = false;
@@ -6839,7 +6884,7 @@ export async function startDaemon(opts: DaemonOptions) {
6839
6884
  for (const peer of bus.knownPeers()) {
6840
6885
  const rows = heldRows(peer);
6841
6886
  if (!rows.some(row => !noticedHolds.has(row.id))) continue;
6842
- for (const row of rows) { noticedHolds.add(row.id); if (row.reason !== ACCEPTED_SETTLE_TIMEOUT_REASON) supervision.needsReview(peer, row.id, () => holdCommand(peer, row.id)); }
6887
+ for (const row of rows) { noticedHolds.add(row.id); if (row.reason !== ACCEPTED_SETTLE_TIMEOUT_REASON) supervision.needsReview(peer, row.id, () => holdCommand(peer, row.id), selfHold(row.holdsSelf, row.kinds.some(kind => isInvocationKind({ kind })))); }
6843
6888
  notify(`${peer} queue ${queueHold(peer)}`);
6844
6889
  }
6845
6890
  writeStatus();
@@ -7480,6 +7525,7 @@ export async function startDaemon(opts: DaemonOptions) {
7480
7525
  const starting = new Map<string, Promise<Record<string, unknown>>>();
7481
7526
  let piAutoRestartAt = -Infinity;
7482
7527
  let piAutoRestartPending = false;
7528
+ const piRestartLedger = new PiRestartLedger(); // #1967 T1
7483
7529
  const replacingPi = new Set<PiPeer>();
7484
7530
  const piReplacementAuthority = Symbol("console Pi replacement");
7485
7531
  /** pi.auto_start at hub start (#269): in Pi's start mode, and said out loud when it could not be done. */
@@ -8344,21 +8390,25 @@ export async function startDaemon(opts: DaemonOptions) {
8344
8390
  },
8345
8391
  onExit: (exit) => {
8346
8392
  const cause = exit.signal ? `signal ${exit.signal}` : exit.code !== null ? `code ${exit.code}` : exit.cause;
8393
+ // #1967 T1: a killed or self-shut-down owner restarts once; the same cause inside ten minutes does not restart again.
8394
+ const reason = piExitReason(exit), restartable = piRestartableReason(reason);
8347
8395
  let action = "start it with ahub pi";
8348
8396
  if (stopping) action = "hub is stopping; requested stop, no automatic restart";
8349
8397
  else if (requestedPeerStops.has(peer)) action = "requested stop; no automatic restart, start it again with ahub pi";
8350
8398
  else if (replacingPi.has(pi)) action = "stopped for a new Pi owner; inspect ahub status for the replacement";
8351
8399
  else if (exit.expected) action = "owner teardown; inspect its session, then ahub pi";
8352
8400
  else if (bus.peers.get(peer) !== pi) action = "superseded owner; no automatic restart";
8353
- else if (recoveryActive()) action = "recovery holds automatic restart; inspect ahub status";
8401
+ else if (restartable ? !!recoveryOperationId && recoveryPhase !== "released" : recoveryActive()) action = "recovery holds automatic restart; inspect ahub status";
8354
8402
  else if (!exit.started || starting.has(peer)) action = "startup failed; inspect its session, then ahub pi";
8355
- else if (exit.turnActive || exit.toolActive) action = "turn/tool effects may be partial; inspect its session, then ahub pi";
8403
+ else if (!restartable && (exit.turnActive || exit.toolActive)) action = "turn/tool effects may be partial; inspect its session, then ahub pi";
8356
8404
  else if (declarations[peer] || !piAutoStart()) action = "pi.auto_start is off; start it with ahub pi";
8357
8405
  else if (mode !== "headless") action = "native terminal ended; start it with ahub pi";
8406
+ else if (restartable && !piRestartLedger.allow(peer, reason, Date.now())) action = `pi.auto_start restart limit (the same cause ${reason} repeated within 10 minutes); start it with ahub pi`;
8358
8407
  else if (piAutoRestartPending || Date.now() - piAutoRestartAt < 60_000) action = "pi.auto_start restart limit (one in 60 s); start it with ahub pi";
8359
8408
  else {
8360
8409
  piAutoRestartPending = true;
8361
8410
  piAutoRestartAt = Date.now();
8411
+ if (restartable) piRestartLedger.record(peer, reason, Date.now());
8362
8412
  action = "pi.auto_start will try its recorded session once";
8363
8413
  void (async () => {
8364
8414
  await piReceipts?.drain();
@@ -8877,54 +8927,8 @@ export async function startDaemon(opts: DaemonOptions) {
8877
8927
  });
8878
8928
 
8879
8929
  // Queue diagnostics are public metadata by default. Private bodies stay behind the existing task console.
8880
- function queueView(row: ReturnType<Bus["queueShow"]>, detail = false, publicOnly = false) {
8881
- if (!row) return undefined;
8882
- const originals = row.originals;
8883
-
8884
- return {
8885
- id: row.id, peer: row.peer, state: row.state, revision: row.revision,
8886
- ...(row.failureCause ? { failureCause: row.failureCause } : {}),
8887
- // #1795: the stored reason of a failed or held delivery, through the same private and public rules as its bodies.
8888
- ...(detail && row.reason ? { reason: publicDeliveryReason(originals, row.reason, { publicOnly, taskPrivate: id => { const task = board.get(Number(id)); return !task || tasks.isPii(task); }, publicMetadataText: text => tasks.publicMetadataText(text) }) } : {}),
8889
- ...roomChat.evidence(row.peer, row.id),
8890
- ...(detail && bus.deliveryResolution(row.id) ? { resolvedBy: bus.deliveryResolution(row.id) } : {}),
8891
- ...(!membershipAllowed(row.peer) ? { rostered: false, holdReason: "off roster" } : {}),
8892
- createdAt: row.createdAt, updatedAt: row.updatedAt,
8893
- envelopeIds: originals.map((env) => env.id),
8894
- important: originals.some((env) => env.priority === "important"),
8895
- ...(detail ? { messages: publicDeliveryBodies(originals, { publicOnly, taskPrivate: id => { const task = board.get(Number(id)); return !task || tasks.isPii(task); }, publicMetadataText: text => tasks.publicMetadataText(text) }) } : {}),
8896
- };
8897
- }
8898
8930
 
8899
8931
  /** Separate from pull: failure here must never discard an already committed normal handout. */
8900
- function inboxHeldRead(c: Client, current: () => boolean) {
8901
- try {
8902
- const peer = c.peer;
8903
- if (!peer || !current() || contextPii(peer)) throw new Error("held inbox authority unavailable");
8904
- const policy = config, configVersion = configRevision, boardVersion = board.statusRevision();
8905
- const held = bus.heldInbox(peer);
8906
- const launch = c.toolsOwner ? currentImplementerTools(c) : undefined;
8907
- const rows = held.rows.map(row => {
8908
- if (!current() || reviewOnlyPeer(peer) && row.originals.some(env => !reviewOnlyItem(peer, env))) throw new Error("held inbox scope unavailable");
8909
- if (c.toolsOwner && (!launch || row.originals.some(env => (env.refs?.task === undefined ? implementerChatTask(peer) : Number(env.refs.task)) !== launch.task))) throw new Error("held inbox belongs to another task session");
8910
- return { id: row.id, revision: row.revision, state: row.state, messages: publicDeliveryBodies(row.originals, {
8911
- publicOnly: true, taskPrivate: id => { const task = board.get(Number(id)); return !task || tasks.isPii(task); },
8912
- publicMetadataText: text => tasks.publicMetadataText(text),
8913
- }) };
8914
- });
8915
- // Screening may consult host ports. Revalidate the exact caller and current privacy before exposure.
8916
- if (!current() || contextPii(peer) || config !== policy || configRevision !== configVersion || board.statusRevision() !== boardVersion) throw new Error("held inbox changed during projection");
8917
- for (const row of held.rows) {
8918
- if (reviewInputHeld(peer, row.originals)) {
8919
- const owner = bus.peers.get(peer), active = ownedObserverInputs.get(peer);
8920
- if (active && active.owner === owner) active.supersededByReviewInput = true;
8921
- noteSteeredReviewInput(peer, row.originals); // RAM observation only: no ACK or durable handoff.
8922
- }
8923
- }
8924
- if (!current() || contextPii(peer)) throw new Error("held inbox authority changed");
8925
- return { count: held.count, rows, truncated: held.truncated, ...(held.unavailable ? { unavailable: true } : {}) };
8926
- } 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." }; }
8927
- }
8928
8932
 
8929
8933
  let operationalViewCache: { board: number; config: number; routing: ReturnType<typeof activeRouting>; privacy: string; view: ReturnType<typeof operationalView> } | undefined;
8930
8934
  function publicOperationalView() {
@@ -8954,40 +8958,6 @@ export async function startDaemon(opts: DaemonOptions) {
8954
8958
  if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).slice(0, 128).filter(([key]) => /^[A-Za-z][A-Za-z0-9_]*$/.test(key)).map(([key, item]) => [key, publicReadValue(item, depth + 1)]));
8955
8959
  return null;
8956
8960
  }
8957
- function sdlcSettingsView() {
8958
- let file: ReturnType<typeof loadSdlc> | undefined;
8959
- try { file = readSdlcFile(); } catch { /* unreadable file stays unknown */ }
8960
- return {
8961
- "sdlc.mode": { value: lifecycleConfig.mode, fileValue: file?.mode ?? null, ...(!file ? { problem: "file unavailable" } : {}) },
8962
- "sdlc.required_checks": { value: lifecycleConfig.requiredChecks, fileValue: file?.requiredChecks ?? null, ...(!file ? { problem: "file unavailable" } : {}) },
8963
- };
8964
- }
8965
- function publicSettingsView() {
8966
- const view = settingsView();
8967
- const rows = view.rows.flatMap(row => {
8968
- if (!tasks.publicMetadataText(row.key)) return [];
8969
- const def = settingDef(row.key);
8970
- if (typeof def === "string") return [];
8971
- // Program/credential/location configuration is never a public value, even when its text passes screening.
8972
- // Route ids locate person-defined execution configuration; keep them opaque too.
8973
- const opaque = NEVER_EDITABLE.some(key => def.key === key || def.key.startsWith(`${key}.`))
8974
- || def.store === "routing" && def.path.at(-1) === "route";
8975
- const safeValue = (value: unknown): unknown => {
8976
- if (opaque) return "[withheld]";
8977
- if (typeof value === "string" && (!/^[A-Za-z0-9_.:-]{1,128}$/.test(value) || !tasks.publicMetadataText(value))) return "[withheld]";
8978
- if (Array.isArray(value)) return value.slice(0, 128).map(safeValue);
8979
- return publicReadValue(value);
8980
- };
8981
- return [{ key: row.key, group: row.group, label: publicReadValue(row.label), type: row.type,
8982
- file: "[withheld]", source: "[withheld]", applies: row.applies, risk: row.risk,
8983
- value: safeValue(row.value), fileValue: safeValue(row.fileValue),
8984
- ...(row.pending !== undefined ? { pending: safeValue(row.pending) } : {}),
8985
- ...(row.values ? { values: opaque ? [] : row.values.map(safeValue) } : {}),
8986
- ...(row.min !== undefined ? { min: row.min } : {}), ...(row.max !== undefined ? { max: row.max } : {}),
8987
- ...(row.locked ? { locked: "read-only" } : {}), ...(opaque ? { withheld: true } : {}) }];
8988
- });
8989
- return { rows, sdlc: Object.fromEntries(Object.entries(sdlcSettingsView()).map(([key, value]) => [key, publicReadValue(value)])), roster: 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"] };
8990
- }
8991
8961
  function operationalCurrent(sock:Sock,acceptedAfterClose=false,committedRecovery=false):()=>void {
8992
8962
  const client=sock.data,peer=client.peer;
8993
8963
  return ()=>{
@@ -10456,784 +10426,7 @@ export async function startDaemon(opts: DaemonOptions) {
10456
10426
  const refusal = sessionGate(c.peer!, msg);
10457
10427
  if (refusal) return void reply({ t: msg.t, ok: false, error: refusal });
10458
10428
  }
10459
- switch (msg.t) {
10460
- case "request_cancel": requestCancelMessage(daemonScope, { sock, c, msg, reply }); break;
10461
- case "permission_failure_probe": permissionFailureProbeMessage(daemonScope, { sock, c, msg, reply }); break;
10462
- case "permission_request": permissionRequestMessage(daemonScope, { sock, c, msg, reply }); break;
10463
- case "conductor_operational": conductorOperational(daemonScope, { sock, c, msg, reply });
10464
- break;
10465
- case "permission_default": permissionDefaultMessage(daemonScope, { sock, c, msg, reply }); break;
10466
- case "permission": permissionMessage(daemonScope, { sock, c, msg, reply }); break;
10467
- case "title": {
10468
- if (c.role !== "console" || msg.liveTest === true) return void reply({ ok: false, reason: "invalid", error: "session titles are person console commands" });
10469
- if (typeof msg.peer !== "string" || !PEER_ID.test(msg.peer)) return void reply({ ok: false, reason: "invalid", error: "invalid peer id; choose a Pi or local-worker peer from ahub status" });
10470
- if (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" });
10471
- if (!bus.peers.has(msg.peer) || 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` });
10472
- if (stopping || recoveryActive()) return void reply({ ok: false, reason: "invalid", error: "recovery or shutdown is holding titles; wait for ahub status to settle, then retry" });
10473
- if (!sessionTitleText(msg.title)) return void reply({ ok: false, reason: "invalid", error: "title needs 1-80 normalized characters; enter a short public title" });
10474
- const instruction = c.instructed;
10475
- const titleOwner = bus.peers.get(msg.peer), previousTitle = titleOwner?.sessionTitle;
10476
- if (instruction && (!isLocalPeer(titleOwner) || !previousTitle || 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" });
10477
- const instructionCurrent = instruction ? () => { try { instruction.current(); return titleOwner?.sessionTitle === previousTitle; } catch { return false; } } : undefined;
10478
- void 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" }));
10479
- return;
10480
- }
10481
- case "queue": {
10482
- if (c.role !== "console" && msg.op === "list") {
10483
- try { publicReadCurrent(sock)(); } catch { return void reply({ ok: false, error: "public queue read unavailable for this caller" }); }
10484
- } else if(c.role!=="console") {
10485
- try {if(!["show","resolve","discard"].includes(msg.op))throw new Error("queue inspection and resolution are console-only");const current=msg.op==="show"?operationalCurrent(sock):admitOperational(sock,`queue ${msg.op}`);current();}catch(error){return void reply(operationalFailure(error));}
10486
- }
10487
- if(c.role!=="console" && msg.reason!==undefined && (typeof msg.reason!=="string" || !tasks.publicMetadataText(msg.reason)))return void reply({ok:false,error:"queue reason withheld by privacy policy"});
10488
- if (msg.op === "list") {
10489
- if (msg.peer !== undefined && (typeof msg.peer !== "string" || !PEER_ID.test(msg.peer) && !parseRemotePeerId(msg.peer))) return void reply({ ok: false, error: "invalid peer" });
10490
- if (msg.all !== undefined && typeof msg.all !== "boolean") return void reply({ ok: false, error: "all is true or false" });
10491
- // #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`.
10492
- const everything = bus.queueList(msg.peer), settled = msg.all === true ? new Set<string>() : bus.settledIds();
10493
- const shown = everything.filter((row) => !settled.has(row.id));
10494
- return void reply({ ok: true, deliveries: shown.map((row) => queueView(row,false,c.role!=="console")), ...(shown.length < everything.length ? { hiddenSettled: everything.length - shown.length } : {}) });
10495
- }
10496
- if (msg.op === "discard") {
10497
- // #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
10498
- // 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
10499
- // because only the named peer is read. Refused while recovery or shutdown holds queue mutations, like every queue resolution.
10500
- if (typeof msg.peer !== "string" || !PEER_ID.test(msg.peer) && !parseRemotePeerId(msg.peer)) return void reply({ ok: false, error: "peer must be a peer id" });
10501
- if (msg.peer.includes("@") && c.role !== "console") return void reply({ ok: false, error: "remote delivery disposition is person-only" });
10502
- // #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.
10503
- const KINDS = ["queued", "needs_review", "failed"] as const;
10504
- if (msg.states !== undefined && msg.state !== undefined) return void reply({ ok: false, error: "give state or states, not both" });
10505
- 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(", ")}` });
10506
- 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" });
10507
- const wanted: readonly string[] = msg.states ?? [msg.state === undefined ? "queued" : msg.state];
10508
- const settledRows = wanted.includes("failed") ? bus.settledIds() : new Set<string>();
10509
- const rows = bus.queueList(msg.peer).filter((row) => wanted.includes(row.state) && !(row.state === "failed" && settledRows.has(row.id)));
10510
- const byState = Object.fromEntries(wanted.map((kind) => [kind, rows.filter((row) => row.state === kind).length]));
10511
- const state = wanted.length === 1 ? wanted[0]! : wanted.join("+");
10512
- const many = msg.states !== undefined ? { states: wanted, byState } : {};
10513
- if (msg.confirmed !== true) return void reply({ ok: true, op: "discard", peer: msg.peer, state, ...many, count: rows.length, discarded: 0, refused: 0 });
10514
- if (typeof msg.reason !== "string" || !msg.reason.trim() || msg.reason.length > 2000) return void reply({ ok: false, error: "discard needs a reason" });
10515
- if (recoveryActive() || stopping) return void reply({ ok: false, error: "recovery or shutdown is holding queue mutations" });
10516
- let discarded = 0; const refused: Record<string, number> = {};
10517
- for (const row of rows) {
10518
- // 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
10519
- // 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.
10520
- const current = bus.queueShow(row.id) ?? bus.queueList(msg.peer).find((r) => r.id === row.id);
10521
- try {
10522
- if (!current || current.state !== row.state) throw new Error("unknown delivery");
10523
- bus.resolveDelivery(row.id, current.revision, "discard", msg.reason.trim());
10524
- if (row.peer.includes("@")) roomChat.disposition(row.peer, row.id, "discard");
10525
- discarded++;
10526
- }
10527
- catch (error) { const why = resolutionRefusal(error).split(":")[0]!; refused[why] = (refused[why] ?? 0) + 1; }
10528
- }
10529
- writeStatus();
10530
- 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 } : {}) });
10531
- }
10532
- if (typeof msg.id !== "string" || !msg.id || msg.id.length > 256) return void reply({ ok: false, error: "invalid delivery ID" });
10533
- if (msg.op === "show") {
10534
- const row = bus.queueShow(msg.id);
10535
- return void reply(row ? { ok: true, delivery: queueView(row, true,c.role!=="console") } : { ok: false, error: "delivery not found" });
10536
- }
10537
- 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" });
10538
- if (recoveryActive() || stopping) return void reply({ ok: false, error: "recovery or shutdown is holding queue mutations" });
10539
- try {
10540
- const before = bus.queueShow(msg.id);
10541
- if (before?.peer.includes("@") && c.role !== "console") return void reply({ ok: false, error: "remote delivery disposition is person-only" });
10542
- bus.resolveDelivery(msg.id, msg.revision, msg.action, msg.reason.trim());
10543
- if (before?.peer.includes("@")) roomChat.disposition(before.peer, msg.id, msg.action);
10544
- writeStatus();
10545
- return void reply({ ok: true, delivery: queueView(bus.queueShow(msg.id),false,c.role!=="console") });
10546
- } catch (error) { return void reply({ ok: false, error: resolutionRefusal(error) }); }
10547
- }
10548
- case "delivery_holds": {
10549
- if (!c.peer || (c.role !== "peer" && c.role !== "tools")) return void reply({ ok: false, error: "held metadata requires a peer identity" });
10550
- try {
10551
- const held = bus.heldDeliveryHints(c.peer);
10552
- return void reply(held ? { ok: true, held, queued: bus.queued(c.peer), important: bus.queuedImportant(c.peer) } : { ok: false, error: "held metadata unavailable" });
10553
- } catch { return void reply({ ok: false, error: "held metadata unavailable" }); }
10554
- }
10555
- case "delivery_receipt": {
10556
- const peer = c.peer ? bus.peers.get(c.peer) : undefined;
10557
- 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" });
10558
- if (msg.state === "failed_safe" && (!peer.pullOnly || bus.queueShow(msg.deliveryId)?.state !== "dispatching")) return void reply({ ok: false, error: "safe failure requires an unseen push to a pull-only session" });
10559
- const reason = typeof msg.reason === "string" ? sanitize(msg.reason).replace(/\s+/g, " ").trim().slice(0, 300) : "";
10560
- 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" } : {}) });
10561
- return void reply({ ok: true });
10562
- }
10563
- case "inbox": {
10564
- 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" });
10565
- if (stopping || 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" });
10566
- if (c.toolsOwner) {
10567
- const peer = c.peer!, current = captureImplementerTools(c), launch = currentImplementerTools(c);
10568
- const heldRead = () => inboxHeldRead(c, current);
10569
- try {
10570
- // Inspect the still-pending batch before pull commits/removes it: private work never reaches this native child.
10571
- const pending = bus.pendingEnvelopes(peer);
10572
- if (!current() || pending.some(env => { const task = env.refs?.task === undefined ? undefined : board.get(Number(env.refs.task)); return env.private || contextPii(peer) || !!task && tasks.isPii(task); })) return void reply({ ok: false, error: "private inbox delivery refused" });
10573
- if (!launch || pending.some(env => (env.refs?.task === undefined ? implementerChatTask(peer) : Number(env.refs.task)) !== launch.task)) return void reply({ ok: false, error: "inbox delivery belongs to another task session" });
10574
- const envs = bus.pull(peer, { allowNeedsReviewHold: true });
10575
- if (!envs) return void reply({ ok: false, error: queueHold(peer) ?? "delivery held", held: inboxHeldMetadata(peer, true), heldRead: heldRead(), waiting: bus.queued(peer), waitingImportant: bus.queuedImportant(peer) });
10576
- return void reply({ ok: true, envs, held: inboxHeldMetadata(peer, true), heldRead: heldRead(), waiting: bus.queued(peer), waitingImportant: bus.queuedImportant(peer) });
10577
- } catch (error) {
10578
- if (error instanceof ReviewInputHandoffError) return void reply({ ok: false, error: error.message, held: inboxHeldMetadata(peer, true), heldRead: heldRead(), waiting: bus.queued(peer), waitingImportant: bus.queuedImportant(peer) });
10579
- return void reply({ ok: false, error: "delivery journal unavailable" });
10580
- }
10581
- }
10582
- // The attached session can explicitly claim queued work even during a native turn (#493).
10583
- // Pull and push share holds and journal settlement; work read here is completed, never pushed again.
10584
- const peer = c.peer ? bus.peers.get(c.peer) : undefined;
10585
- 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" });
10586
- const current = () => sock.data === c && sock.readyState === WebSocket.OPEN && c.role === "peer" && c.peer === peer.id && membershipAllowed(peer.id) && bus.peers.get(peer.id) === peer && peer.owns(sock) && !stopping && !recoveryActive();
10587
- const heldRead = () => inboxHeldRead(c, current);
10588
- try {
10589
- const envs = bus.pull(peer.id, { allowNeedsReviewHold: true });
10590
- if (!envs) {
10591
- const held = inboxHeldMetadata(peer.id, true);
10592
- const heldRows = held && typeof held === "object" && !Array.isArray(held) && Array.isArray((held as { rows?: unknown }).rows)
10593
- ? (held as { rows: { state?: unknown }[] }).rows : undefined;
10594
- const accepted = heldRows?.some(row => row.state === "accepted") === true;
10595
- const blockingCause = queueHold(peer.id)
10596
- ?? (bus.isRecoveryHeld ? "recovery is holding deliveries" : undefined)
10597
- ?? (bus.stateOf(peer.id) === "paused" ? pauseReason(peer.id) : undefined);
10598
- const error = blockingCause ?? (accepted ? "an accepted delivery is awaiting your explicit confirmation" : "delivery held");
10599
- return void reply({ ok: false, error, held, heldRead: heldRead(), waiting: bus.queued(peer.id), waitingImportant: bus.queuedImportant(peer.id) });
10600
- }
10601
- peer.lastInboxAt = Date.now();
10602
- let polling: ReturnType<InboxPolling["read"]>;
10603
- try {
10604
- const assigned = peer.pullOnly && board.statusTasks().some(task => !isClosedTaskState(task.state) && task.state !== "backlog" && (task.owner === peer.id || task.reviewer === peer.id));
10605
- polling = peer.pullOnly ? inboxPolling.read(peer.id, envs.length === 0, assigned, peer.lastInboxAt) : undefined;
10606
- if (polling?.notice) notify(`${peer.id} is polling an empty inbox with no task (${polling.count} empty reads in ${polling.minutes} min)`);
10607
- } catch { polling = undefined; } // The pull already completed: advice must never discard its envelopes.
10608
- writeStatus();
10609
- if (envs.length) log(`${peer.id} read ${envs.length} queued message(s) through hub_inbox`);
10610
- return void reply({ ok: true, envs, held: inboxHeldMetadata(peer.id, true), heldRead: heldRead(), waiting: bus.queued(peer.id), waitingImportant: bus.queuedImportant(peer.id), ...(polling ? { pollingAdvice: { count: polling.count, minutes: polling.minutes } } : {}) });
10611
- } catch (error) {
10612
- if (error instanceof ReviewInputHandoffError) return void reply({ ok: false, error: error.message, held: inboxHeldMetadata(peer.id, true), heldRead: heldRead(), waiting: bus.queued(peer.id), waitingImportant: bus.queuedImportant(peer.id) });
10613
- return void reply({ ok: false, error: "delivery journal unavailable" });
10614
- }
10615
- }
10616
- case "delivery_complete": {
10617
- const peer = c.peer ? bus.peers.get(c.peer) : undefined;
10618
- 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" });
10619
- return void reply(bus.completeDelivery(peer.id, msg.deliveryId) ? { ok: true } : { ok: false, error: "delivery is not live and accepted; inspect ahub queue show before resolving" });
10620
- }
10621
- case "execution_budget": executionBudgetMessage(daemonScope, { sock, c, msg, reply }); break;
10622
- case "recovery_restore": recoveryRestoreMessage(daemonScope, { sock, c, msg, reply }); break;
10623
- case "recovery_authority": recoveryAuthorityMessage(daemonScope, { sock, c, msg, reply }); break;
10624
- case "recovery": recoveryMessage(daemonScope, { sock, c, msg, reply }); break;
10625
- case "send": {
10626
- if (recoveryActive()) return void reply({ t: "sent", ok: false, error: "recovery is holding new deliveries" });
10627
- // A human at the console should not wait out the batch window; agents default to status.
10628
- const { priority, body } = parseMarker(String(msg.body ?? ""), c.peer ? "status" : "important");
10629
- if (!body) return void reply({ t: "sent", ok: false, error: "empty body" });
10630
- const recipients = typeof msg.to === "string" && msg.to.length ? [msg.to] : msg.to;
10631
- if (Object.hasOwn(msg, "to") && (!Array.isArray(recipients) || recipients.some(id => typeof id !== "string" || !id.length))) {
10632
- return void reply({ t: "sent", ok: false, error: "to must be an array of peer ids" });
10633
- }
10634
- const to: PeerId[] | undefined = Array.isArray(recipients) && recipients.length ? [...new Set<string>(recipients)] : undefined;
10635
- const unknown = to?.filter((id) => !bus.knownPeers().includes(id) && membershipAllowed(id)) ?? [];
10636
- if (unknown.length) return void reply({ t: "sent", ok: false, error: `unknown peer: ${unknown.join(", ")}` });
10637
- const inReplyTo = msg.reply_to ? bus.get(String(msg.reply_to)) : undefined;
10638
- // #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.
10639
- if (c.peer && inReplyTo?.kind === "invocation" && inReplyTo.from === HUB) {
10640
- bus.onAnswer?.(c.peer, body, [inReplyTo]);
10641
- bus.completeReply(c.peer, inReplyTo.id);
10642
- return void reply({ t: "sent", ok: true, targets: [], recorded: false });
10643
- }
10644
- // Built first: limits count the audience it really has (a reply goes to the parent's sender).
10645
- let env = newEnvelope(c.peer ?? USER, body, { priority, ...(to ? { to } : {}), ...(inReplyTo ? { inReplyTo } : {}) });
10646
- 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
10647
- env = bus.reviewResponse(env, inReplyTo?.id);
10648
- rememberOrigin(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)
10649
- try { bus.checkRemotePublication(env); }
10650
- 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" }); }
10651
- const offRoster = bus.offRosterRecipients(env);
10652
- 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(", ")}` });
10653
- const admittedEnv = offRoster.length ? { ...env, to: env.to!.filter(id => !offRoster.includes(id)) } : env;
10654
- // A silent cohort (issue #107): the members it is held back from are left out, the rest get it; the sender is
10655
- // told. Held back from everyone, it costs the sender nothing against its limits.
10656
- const hushed = bus.hushed(env);
10657
- const heldBack = hushed.length > 0 && hushed.length === bus.audience(env).length;
10658
- const refused = c.peer && !heldBack ? admit(admittedEnv, inReplyTo?.id) : undefined;
10659
- if (refused) return void reply({ t: "sent", ok: false, error: refused });
10660
- let published: ReturnType<Bus["publishResult"]>;
10661
- try { published = bus.publishResult(env); }
10662
- 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" }); }
10663
- const { targets, dropped } = published;
10664
- if (c.peer && inReplyTo) bus.completeReply(c.peer, inReplyTo.id); // the delivery it answers was handled all the same
10665
- if (dropped === "hop") return void reply({ t: "sent", ok: true, targets, dropped, recorded: priority === "fyi",
10666
- notice: `not delivered: reply chain reached the hop cap (${MAX_HOP}); send a new message without reply_to` });
10667
- 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}` });
10668
- 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("; ") } : {}) });
10669
- }
10670
- case "native_hook_launch": nativeHookLaunchMessage(daemonScope, { sock, c, msg, reply }); break;
10671
- case "native_facts": nativeFactsMessage(daemonScope, { sock, c, msg, reply }); break;
10672
- case "instruction_execute": instructionExecuteMessage(daemonScope, { sock, c, msg, reply }); break;
10673
- case "instruction_hook": instructionHookMessage(daemonScope, { sock, c, msg, reply }); break;
10674
- case "facts": factsMessage(daemonScope, { sock, c, msg, reply }); break;
10675
- case "silenced": {
10676
- // `ahub check-path` (issue #107): which of these owners the asking peer shares a silent cohort with.
10677
- if (!c.peer) return void reply({ t: "silenced", ok: false, error: "silenced is for a peer" });
10678
- const owners = Array.isArray(msg.owners) ? msg.owners.filter((o: unknown): o is string => typeof o === "string").slice(0, 20) : [];
10679
- return void reply({ t: "silenced", ok: true, owners: owners.filter((o: string) => !!tasks.silenced(c.peer!, o)) });
10680
- }
10681
- case "watch": {
10682
- if (c.role !== "console") return void reply({ ok: false, error: "watch is a person-only console command" });
10683
- if (typeof msg.peer !== "string" || !definitionOf(msg.peer)?.capabilities?.watch) return void reply({ ok: false, error: "watch supports headless kimi and qwen only" });
10684
- const peer = msg.peer;
10685
- // Judged by the live owner: a headless Kimi started by --mode headless is watchable under a TUI start mode.
10686
- const owner = bus.peers.get(peer);
10687
- const admission = definitionOf(peer)?.attach?.admission;
10688
- if (admission && !isAcpPeer(owner) && (isWsPeer(owner) || (kimiSessionMode ?? startMode(peer)) === "tui")) return void reply({ ok: false, error: admission.watchRefusal });
10689
- if (!membershipAllowed(peer)) return void reply({ ok: false, error: `${peer} is off roster` });
10690
- c.watch?.();
10691
- c.watch = activityRings[peer]!.subscribe(item => {
10692
- // Bound slow observers instead of accumulating command output on the socket.
10693
- if (sock.getBufferedAmount() > 256 * 1024) { sock.close(1013, "watch observer is too slow"); return; }
10694
- sock.send(JSON.stringify({ t: "activity", peer, item }));
10695
- });
10696
- return void reply({ ok: true, t: "watch", peer });
10697
- }
10698
- case "tail":
10699
- if (c.role !== "console" || c.tail) return;
10700
- c.tail = bus.tap((e) => sock.send(JSON.stringify({ t: "event", e: redact(e) })));
10701
- for (const p of permissions.values()) sock.send(p.push);
10702
- for (const peer of bus.knownPeers()) sock.send(JSON.stringify({ t: "context", peer, reading: contexts.view(peer, contextSession(peer), bus.peers.has(peer) && ["idle", "busy", "paused"].includes(bus.stateOf(peer))) }));
10703
- return;
10704
- case "ui":
10705
- if (c.role !== "console") return void reply({ t: "ui", ok: false, error: "ui is a console command" });
10706
- try {
10707
- dashboard ??= startDashboard({ snapshot: dashboardSnapshot, action: uiAction });
10708
- writeStatus();
10709
- // #269: `ahub ui --settings` is the same person's command; its ticket marks the session it opens.
10710
- if (msg.settings === true) notify("settings session opened from ahub ui --settings: for 15 minutes that dashboard session may change permission modes, routing and start settings");
10711
- return void reply({ t: "ui", ok: true, url: dashboard.issue(msg.settings === true, msg.liveTest === true), ...(msg.settings === true ? { settings: true } : {}), ...(msg.liveTest === true ? { liveTest: true } : {}) });
10712
- } catch {
10713
- return void reply({ t: "ui", ok: false, error: "could not start the dashboard" });
10714
- }
10715
- case "sdlc": sdlcMessage(daemonScope, { sock, c, msg, reply });
10716
- break;
10717
- case "room": {
10718
- const client = sock.data;
10719
- const personRoom = c.role === "console";
10720
- const roomCurrent = () => !stopping && !recoveryActive() && !bus.isRecoveryHeld
10721
- && sock.data === client && sock.readyState === WebSocket.OPEN && personRoom;
10722
- const roomFailure = (error?: unknown) => error instanceof RoomRotationHoldError
10723
- ? reply({ ok: false, code: "epoch_rotated_hold_unavailable", error: error.message })
10724
- : reply({ ok: false, error: "room operation refused; check room state, authority and arguments" });
10725
- if (msg.op === "list" || msg.op === "status") {
10726
- if (msg.input !== undefined && (!msg.input || typeof msg.input !== "object" || Array.isArray(msg.input)
10727
- || Object.keys(msg.input).some(key => key !== "name") || (msg.input.name !== undefined && typeof msg.input.name !== "string"))) return roomFailure();
10728
- void roomCommands.rows(msg.input?.name, msg.op === "status").then(rooms => reply({ ok: true, rooms }), error => {
10729
- const roomsUnavailable = roomCommands.unavailable();
10730
- if (roomsUnavailable) reply({ ok: false, code: "rooms_unavailable", roomsUnavailable });
10731
- else roomFailure(error);
10732
- });
10733
- return;
10734
- }
10735
- if (["inbox_list", "inbox_show", "inbox_done", "inbox_discard"].includes(msg.op)) {
10736
- if (!personRoom) return void reply({ ok: false, error: "room inbox is person-only" });
10737
- if (!roomCurrent() || Object.keys(msg).some(key => !["t", "op", "input", "rid"].includes(key))) return roomFailure();
10738
- const input = msg.input;
10739
- if (!input || typeof input !== "object" || Array.isArray(input)) return roomFailure();
10740
- if (msg.op === "inbox_list") {
10741
- if (Object.keys(input).some(key => key !== "name") || (input.name !== undefined && typeof input.name !== "string")) return roomFailure();
10742
- void roomCommands.inboxRows(input.name, roomCurrent).then(inbox => {
10743
- if (!roomCurrent()) return roomFailure();
10744
- reply({ ok: true, inbox });
10745
- }, error => {
10746
- if (!roomCurrent()) return roomFailure();
10747
- if (error instanceof RoomStoreError && error.code === "inbox_list_limit") return reply({ ok: false, code: "inbox_list_limit" });
10748
- roomFailure();
10749
- });
10750
- return;
10751
- }
10752
- if (Object.keys(input).length !== 1 || typeof input.id !== "string" || !Object.hasOwn(input, "id")) return roomFailure();
10753
- const operation = msg.op === "inbox_show" ? roomCommands.inboxShow(input.id, roomCurrent)
10754
- : roomCommands.inboxDispose(input.id, msg.op === "inbox_done" ? "done" : "discard", roomCurrent);
10755
- void operation.then(item => {
10756
- if (!roomCurrent()) return roomFailure();
10757
- if (!item) return reply({ ok: false, code: "inbox_not_found" });
10758
- reply({ ok: true, item });
10759
- if (msg.op !== "inbox_show") roomCommands.retryInboxPending();
10760
- }, roomFailure);
10761
- return;
10762
- }
10763
- if (!personRoom) return void reply({ ok: false, error: "room mutations are person-only" });
10764
- if (!roomCurrent()) return roomFailure();
10765
- if (msg.op === "preview") {
10766
- roomTickets.delete(sock);
10767
- void roomCommands.preview(msg.action, msg.input, roomCurrent).then(preview => {
10768
- if (!roomCurrent()) return roomFailure();
10769
- const ticket = crypto.randomUUID();
10770
- roomTickets.set(sock, { id: ticket, expires: Date.now() + 30_000, preview });
10771
- reply({ ok: true, owner: preview.owner, member: preview.member, ticket, ...(preview.outstanding ? { outstanding: preview.outstanding } : {}) });
10772
- }, roomFailure);
10773
- return;
10774
- }
10775
- if (msg.op === "execute") {
10776
- const ticket = roomTickets.get(sock); roomTickets.delete(sock);
10777
- if (!ticket || msg.ticket !== ticket.id || Date.now() >= ticket.expires
10778
- || typeof msg.confirm !== "string" || !/^[0-9a-f]{16,64}$/.test(msg.confirm) || !ticket.preview.member.startsWith(msg.confirm)
10779
- || Object.keys(msg).some(key => !["t", "op", "ticket", "confirm", "rid"].includes(key))) return roomFailure();
10780
- void ticket.preview.commit().then(result => reply({ ok: true, ...result }), roomFailure);
10781
- return;
10782
- }
10783
- return void reply({ ok: false, error: "unknown room operation" });
10784
- }
10785
- case "status": {
10786
- const sendStatus = () => {
10787
- const current = status(c.role === "console", false, true, c.role === "console" || (c.role === "tools" || c.role === "peer") && c.peer === conductorPeer(config.roles), c.role === "console");
10788
- if (c.role === "console" && msg.companion === true) for (const [id, row] of Object.entries(current.peers)) {
10789
- const label = peerAccountLabel(id);
10790
- if (label !== undefined) Object.assign(row, { accountLabel: label });
10791
- }
10792
- // #1798 T3, display only: whether this tools connection runs under the launch the peer's current channel socket attached with. It labels a startup
10793
- // notice and decides nothing: not admission, routing, delivery or permissions. Anyone holding the control token can send any launch id, so it is
10794
- // a hint, never evidence. Per request, never cached or stored; the launch id itself is never returned, logged or recorded. Absent for every
10795
- // 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.
10796
- const thisLaunch = c.role === "tools" && !c.session && !c.toolsOwner && c.peer && c.launchId && definitionOf(c.peer)?.transport === "claude-channel"
10797
- ? { thisLaunch: (bus.peers.get(c.peer) as { managedLaunchId?: unknown } | undefined)?.managedLaunchId === c.launchId } : {};
10798
- if ((c.role === "console" || c.role === "tools") && msg.specs === true) {
10799
- const summary = projectSpecs.status();
10800
- if (summary) {
10801
- const missingBlockHint = !specsMissingBlockHintShown && projectSpecs.missingBlock() === true;
10802
- if (missingBlockHint) specsMissingBlockHintShown = true;
10803
- return void reply({ t: "status", status: { ...current, ...thisLaunch, specs: { ...summary, ...(missingBlockHint ? { missingBlockHint: true } : {}) } } });
10804
- }
10805
- }
10806
- return void reply({ t: "status", status: { ...current, ...thisLaunch } });
10807
- };
10808
- if (orphanChecks && !startupSpecPending()) return sendStatus();
10809
- void Promise.all([orphanSweep, firstSpecProbe]).then(() => {
10810
- if (stopping) return void reply({ ok: false, error: "hub stopping; run ahub status again after it restarts" });
10811
- sendStatus();
10812
- }).catch(error => controlOperationFailed(sock, msg, error));
10813
- return;
10814
- }
10815
- case "peer_takeover": {
10816
- if (c.role !== "console") return void reply({ t: "peer_takeover", ok: false, error: "peer takeover is a person-only command; run it from the console or a terminal" });
10817
- if (Object.keys(msg).some(key => !["t", "rid", "peer", "standbyId"].includes(key))
10818
- || typeof msg.peer !== "string" || !PEER_ID.test(msg.peer)
10819
- || msg.standbyId !== undefined && (typeof msg.standbyId !== "string" || msg.standbyId.length > 64 || /[\p{Cc}\p{Cf}]/u.test(msg.standbyId))) {
10820
- return void reply({ t: "peer_takeover", ok: false, error: "peer takeover needs a peer id and optional live standby id; usage: ahub peer takeover <peer> [standby-id]" });
10821
- }
10822
- const peerId = msg.peer as PeerId;
10823
- if (stopping || recoveryActive() || rosterChanging === peerId || requestedPeerStops.has(peerId) || starting.has(peerId)
10824
- || !membershipAllowed(peerId) || !recoveryPeerAllowed(peerId)) {
10825
- return void reply({ t: "peer_takeover", ok: false, error: "peer takeover is unavailable while the hub, peer or roster is changing; retry ahub peer takeover <peer> once ahub status shows the peer attached and idle" });
10826
- }
10827
- const peer = bus.peers.get(peerId), claim = peer?.takeover?.(msg.standbyId as string | undefined, socket => channelTakeoverAdmission(peerId, socket as Sock));
10828
- if (!peer || !claim) return void reply({ t: "peer_takeover", ok: false, error: "no eligible standby session is available; inspect ahub status and reconnect the intended standby session" });
10829
- revokeTerminalExecution(peerId);
10830
- startPeerTakeover(peer, claim);
10831
- return void reply({ t: "peer_takeover", ok: true, outcome: "requested", standbyId: claim.standbyId });
10832
- }
10833
- case "cli_audit_ack": {
10834
- if (c.role !== "console") return void reply({ ok: false, error: "cli_audit_ack is a console command" });
10835
- if (typeof msg.auditId !== "string" || !/^[a-f0-9-]{36}$/.test(msg.auditId)) return void reply({ ok: false, error: "invalid audit id" });
10836
- try { drainCliAuditsNow(); }
10837
- catch { return void reply({ ok: false, error: "CLI audit was not retained" }); }
10838
- return void reply({ ok: retainedCliAudits.has(msg.auditId), auditId: msg.auditId, instanceId });
10839
- }
10840
- case "review_comment_put":
10841
- case "review_comment_delete":
10842
- case "review_comment_send": reviewCommentWrite(daemonScope, { sock, c, msg, reply });
10843
- break;
10844
- case "review_comments":
10845
- reviewCommentsRead(daemonScope, { sock, c, msg, reply });
10846
- break;
10847
- case "review_blob": reviewBlob(daemonScope, { sock, c, msg, reply });
10848
- break;
10849
- case "ui_snapshot":
10850
- if (c.role !== "console") return void reply({ ok: false, error: "ui_snapshot is a console command" });
10851
- if (!Number.isSafeInteger(msg.after ?? 0) || (msg.after ?? 0) < 0) return void reply({ ok: false, error: "invalid cursor" });
10852
- void 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" }));
10853
- return;
10854
- case "ui_action":
10855
- if (c.role !== "console") return void reply({ ok: false, error: "ui_action is a console command" });
10856
- if (recoveryActive()) return void reply({ ok: false, error: "recovery is holding mutations" });
10857
- if (msg.instanceId !== instanceId) return void reply({ ok: false, error: "hub restarted; refresh before acting" });
10858
- if (!msg.action || typeof msg.action !== "object" || Array.isArray(msg.action)) return void reply({ ok: false, error: "invalid dashboard action" });
10859
- void uiAction(msg.action).then((result) => reply(result as Record<string, unknown>), () => reply({ ok: false, error: "dashboard action failed; check its inputs" }));
10860
- return;
10861
- case "task_catalog_role":
10862
- // #933: an agent changes its own task's role (Tasks.setRole refuses another peer's task); a child, read-only or private context never does.
10863
- taskCatalogRole(daemonScope, { sock, c, msg, reply });
10864
- break;
10865
- case "autonomy":
10866
- if (c.role !== "console") return void reply({ ok: false, error: "autonomy is a person-only command; run ahub autonomy in a person's terminal" });
10867
- void autonomyCommand(msg.action, msg.environment, msg.confirmed, msg.confirmation).then(reply, () => reply({ ok: false, error: "project autonomy could not be changed" }));
10868
- return;
10869
- case "guidance_list":
10870
- case "guidance_show":
10871
- case "guidance_create":
10872
- case "guidance_withdraw": guidanceMessage(daemonScope, { sock, c, msg, reply });
10873
- break;
10874
- case "guidance_probe_register":
10875
- case "guidance_probe_start":
10876
- case "guidance_probe_show":
10877
- case "guidance_probe_receipts":
10878
- case "guidance_probe_cancel": guidanceProbeMessage(daemonScope, { sock, c, msg, reply });
10879
- break;
10880
- case "lineage_show":
10881
- case "lineage_link": lineageMessage(daemonScope, { sock, c, msg, reply });
10882
- break;
10883
- case "model":
10884
- if (c.role !== "console") return void reply(modelFailure("model overrides are person-only; run ahub model in a person's terminal"));
10885
- return void reply(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; } }));
10886
- case "settings_get":
10887
- if (c.role !== "console") {
10888
- try { const current = publicReadCurrent(sock); current(); const view = publicSettingsView(); current(); return void reply({ ok: true, ...view }); }
10889
- catch { return void reply({ ok: false, error: "public settings read unavailable for this caller" }); }
10890
- }
10891
- return void reply({ ok: true, ...settingsView(), sdlc: sdlcSettingsView(), roster: rosterView(), configEdit: (() => { const view = configEditor!.view(); return { revisions: view.revisions, known: view.known }; })() });
10892
- case "settings_reload":
10893
- if (c.role !== "console") return void reply({ ok: false, error: "settings are a person command" });
10894
- return void reloadConfig("terminal", undefined, msg.confirm).then(reply, () => reply({ ok: false, error: "configuration reload could not be confirmed; inspect hub.log" }));
10895
- case "settings_preview":
10896
- if(c.role!=="console")try {const def=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");operationalCurrent(sock)();}catch(error){return void reply(operationalFailure(error));}
10897
- return void reply(msg.undo === true ? settingsUndoPreview() : settingsPreview(msg.key, msg.value));
10898
- case "settings_set":
10899
- let settingsCurrent:(()=>void)|undefined;
10900
- if(c.role!=="console")try {const def=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=admitOperational(sock,"settings set");}catch(error){return void reply(operationalFailure(error));}
10901
- void operationalContext.run(settingsCurrent?{actor:c.peer!,current:settingsCurrent}:undefined,()=>settingsSet(msg.key,msg.value,settingsCurrent?"conductor":"terminal",msg.confirm,msg.now,msg.reason)).then(reply, error => reply(operationalFailure(error,"the setting could not be changed; inspect hub.log")));
10902
- return;
10903
- case "settings_undo":
10904
- if (c.role !== "console") return void reply({ ok: false, error: "settings are a person's: run ahub settings in a terminal" });
10905
- return void 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" }));
10906
- case "config_edit_get":
10907
- if (c.role !== "console") return void reply({ ok: false, error: "config edits are a person's: run ahub settings edit in a terminal" });
10908
- return void reply({ ok: true, ...configEditor!.view() });
10909
- case "config_edit_preview":
10910
- if (c.role !== "console") return void reply({ ok: false, error: "config edits are a person's: run ahub settings edit in a terminal" });
10911
- return void reply(configEditor!.preview(msg.edit, "terminal"));
10912
- case "config_edit_apply":
10913
- if (c.role !== "console") return void reply({ ok: false, error: "config edits are a person's: run ahub settings edit in a terminal" });
10914
- void 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" }));
10915
- return;
10916
- case "kimi_launch_end": {
10917
- if (c.role !== "console") return void reply({ ok: false, error: "Kimi launch cleanup is console only" });
10918
- if (typeof msg.admissionId === "string" && msg.admissionId === kimiAdmissionId) clearKimiAdmission();
10919
- return void reply({ ok: true });
10920
- }
10921
- case "terminal_launch": {
10922
- if (c.role !== "console") return void reply({ ok: false, error: "terminal launch registration is console only" });
10923
- if (stopping || recoveryActive() && !(recoveryPhase === "restored" && msg.operationId === recoveryOperationId)) return void reply({ ok: false, error: "recovery is holding terminal launches" });
10924
- const row = terminalLaunchCandidate(msg.launch, opts.cwd, opts.stateDir, instanceId);
10925
- if (!row || !membershipAllowed(row.peer) || !definitionOf(row.peer)?.session.launchRecord || recoveryActive() && !recoveryPeerAllowed(row.peer)) return void reply({ ok: false, error: "terminal launch identity unavailable" });
10926
- try { terminalLaunches.register(row); return void reply({ ok: true }); }
10927
- catch { return void reply({ ok: false, error: "terminal launch could not be registered; managed recovery is unavailable" }); }
10928
- }
10929
- case "native_tui_launch": {
10930
- if (c.role !== "console") return void reply({ ok: false, error: "native TUI launch is console only" });
10931
- const peer = String(msg.peer), owner = bus.peers.get(peer);
10932
- // #1085: every refusal names its cause class, in the reply and as one hub.log line. The class is a closed word: never a session id, launch id, socket or path.
10933
- const refuseTui = (code: string, error: string, resumed?: boolean) => { log(`native_tui_launch jcode refused: ${code}${resumed ? " (resumed session)" : ""}`); return void reply({ ok: false, code, ...(resumed ? { resumed: true } : {}), error }); };
10934
- if (stopping || recoveryActive() || !membershipAllowed(peer) || rosterChanging === peer || requestedPeerStops.has(peer)) return refuseTui("hub_busy", "owned native TUI launch is unavailable");
10935
- if (peer !== definitionOf(peer)?.kind || !isJcodePeer(owner)) return refuseTui("not_running", "owned native TUI launch is unavailable");
10936
- if (!jcodeMcpReady(opts.cwd, opts.stateDir, SERVER_JS)) return refuseTui("mcp_stale", "owned native TUI launch is unavailable");
10937
- try {
10938
- if (msg.binding !== undefined && (!msg.binding || typeof msg.binding.launchId !== "string" || typeof msg.binding.sessionId !== "string")) throw new Error("invalid binding");
10939
- const options = msg.args ?? {};
10940
- for (const key of ["model", "providerProfile", "sessionId"]) if (options[key] !== undefined && typeof options[key] !== "string") throw new Error("invalid option");
10941
- return void reply({ ok: true, ...owner.tuiLaunch(msg.binding, options) });
10942
- } catch (error) {
10943
- if (error instanceof JcodeOptionMismatch) return void reply({ ok: false, option: error.option, error: `owned Jcode launch differs from its running session in ${error.option}; start without it or stop jcode first` });
10944
- if (error instanceof JcodeTuiRefusal) return refuseTui(error.code, "owned Jcode launch or saved session could not be verified; details withheld", owner.resumedSession);
10945
- return refuseTui("bad_request", "owned Jcode launch or saved session could not be verified; details withheld");
10946
- }
10947
- }
10948
- case "peer_start":
10949
- // #269: a start the hub makes in the peer's start mode, for a console child with no terminal of its own.
10950
- if (c.role !== "console") return void reply({ ok: false, error: "peer_start is a console command; use hub_peer_start with the conductor role" });
10951
- void hubStart(msg.peer, "the console", true).then(result => reply(includeRetainedLaunchConfig(String(msg.peer), result)), (error) => { log(`peer_start ${String(msg.peer)} failed: ${(error as Error).message}`); reply({ ok: false, error: "peer start failed; inspect ahub status and hub.log" }); });
10952
- return;
10953
- case "peer_stop":
10954
- let stopCurrent:(()=>void)|undefined = c.instructed?.current;
10955
- if(c.role!=="console")try{stopCurrent=admitOperational(sock,"stop");}catch(error){return void reply(operationalFailure(error));}
10956
- void stopPeer(msg.peer,false,stopCurrent?{actor:c.instructed ? USER : c.peer!,current:stopCurrent}:undefined).then(reply).catch(error => reply(operationalFailure(error,"peer stop failed; inspect ahub status and logs before retrying")));
10957
- return;
10958
- case "start":
10959
- if (c.role !== "console") return void reply({ t: "started", ok: false, error: "start is a console command; use hub_peer_start with the conductor role" });
10960
- if (recoveryActive() && !(recoveryPhase === "restored" && msg.operationId === recoveryOperationId)) return void reply({ t: "started", ok: false, error: startHeldByRecovery(msg.peer) });
10961
- if (recoveryActive() && !recoveryPeerAllowed(String(msg.peer))) return void reply({ t: "started", ok: false, error: "peer is not part of the recovery roster" });
10962
- startPeer(String(msg.peer), msg.args ?? {}, msg.args?.replaceSession === true ? piReplacementAuthority : undefined)
10963
- .catch((e: Error) => ({ ok: false, error: e.message }))
10964
- .then((r) => {
10965
- if (!r.ok) log(`start ${msg.peer} failed: ${r.error}`);
10966
- reply({ t: "started", ...includeRetainedLaunchConfig(String(msg.peer), r) });
10967
- });
10968
- return;
10969
- case "task":
10970
- taskMessage(daemonScope, { sock, c, msg, reply });
10971
- break;
10972
- case "pause":
10973
- case "resume": {
10974
- if (c.role !== "console") return void reply({ t: msg.t, ok: false, error: "pause/resume is a console command; use the conductor hold/release tools" });
10975
- if (recoveryActive()) return void reply({ t: msg.t, ok: false, error: "recovery is holding mutations" });
10976
- void holdPeer(msg.t, String(msg.peer)).then((result) => reply({ t: msg.t, ...result }), () => reply({ t: msg.t, ok: false, error: "peer resume validation failed" }));
10977
- return;
10978
- }
10979
- case "goal_link":
10980
- // #258: a person links a board task to a long-term task (`ahub goal link`); the link goes through Tasks. #933: the configured conductor too, admitted and audited here.
10981
- goalLink(daemonScope, { sock, c, msg, reply });
10982
- break;
10983
- case "ask": {
10984
- // Console only: the evidence may hold PII task text (on campus), and the answer is for the person at the terminal.
10985
- if (c.role !== "console") return void reply({ t: "ask", ok: false, error: "ask is a console command" });
10986
- const client = sock.data, revision = configRevision, policy = corpusPolicyVersion();
10987
- const callerPrivate = () => !!client.peer && contextPii(client.peer);
10988
- const initialPrivate = callerPrivate();
10989
- const isPiiText = (text: string) => activeRouting().constraints.pii === "local_only" && detectSignals({ title: text, detail: "", refs: {} }, activeRouting(), opts.cwd).includes("pii");
10990
- let evidencePrivacy: readonly TaskEvidencePrivacy[] = [];
10991
- const askCurrent = () => !stopping && sock.data === client && sock.readyState === WebSocket.OPEN
10992
- && configRevision === revision && corpusPolicyVersion() === policy && callerPrivate() === initialPrivate
10993
- && evidencePrivacy.every(previous => {
10994
- const latest = board.get(previous.id);
10995
- if (!latest || latest.created !== previous.created) return false;
10996
- const privacy = taskEvidencePrivacy(latest, { isPii: task => tasks.isPii(task), isPiiText });
10997
- return privacy.pii === previous.pii && privacy.notePii === previous.notePii;
10998
- });
10999
- ask(String(msg.question ?? ""), {
11000
- board,
11001
- isPii: (t) => tasks.isPii(t),
11002
- onCampus,
11003
- current: askCurrent,
11004
- privateContext: callerPrivate,
11005
- bindTaskEvidence: rows => { evidencePrivacy = rows; },
11006
- corpus: keys => publicCorpus(keys.join(" "), askCurrent),
11007
- isPiiText,
11008
- ...(config.memory.enabled ? { memory } : {}),
11009
- // #258: entries that match the question, then the graph neighbourhood of what they are about.
11010
- ...(memoryStore ? { native: (keys: string[]) => {
11011
- checkMemory();
11012
- const score = (v: MemoryView) => keys.filter((k) => `${v.title ?? ""} ${v.text} ${v.about.join(" ")}`.toLowerCase().includes(k)).length;
11013
- // Screened before the caps: withheld entries never crowd out readable evidence.
11014
- const hits = screenMemory(memoryStore!.list({ project: 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);
11015
- const near = screenMemory(memoryStore!.related(memoryProject, [...new Set(hits.flatMap((v) => v.about))], Number.MAX_SAFE_INTEGER)).slice(0, 6);
11016
- return [...hits, ...near].map((v) => ({ id: `mem:${v.id}`, text: memoryLine(v).slice(13) }));
11017
- } } : {}),
11018
- project: chain.at(-1)!,
11019
- logFile,
11020
- ...(inference ? { inference } : {}),
11021
- })
11022
- .then(async (res) => {
11023
- if (!askCurrent()) return void reply({ t: "ask", ok: true, found: false, evidence: [], pii: true, note: "evidence context changed" });
11024
- let saved: string | undefined;
11025
- if (msg.remember) {
11026
- if (res.pii) saved = "not saved: PII is involved";
11027
- else if (!res.found) saved = "not saved: there was no answer to save";
11028
- else if (!config.memory.enabled) saved = "not saved: memory is disabled";
11029
- else {
11030
- // Saved as what it is: a model's answer, attributed to the hub, under a title later asks exclude from their evidence.
11031
- const ok = await memory.save({
11032
- title: `${ASK_NOTE_TITLE}: ${String(msg.question).slice(0, 80)}`,
11033
- 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)}`,
11034
- project: chain.at(-1)!,
11035
- metadata: { peer: "hub", asked_by: USER, kind: "finding", source: "ahub ask" },
11036
- });
11037
- saved = ok ? "saved as a candidate model-written answer; a person must review it" : "memory store unavailable; nothing saved";
11038
- }
11039
- }
11040
- reply({ t: "ask", ok: true, ...res, ...(saved ? { saved } : {}) });
11041
- })
11042
- .catch((e: Error) => reply({ t: "ask", ok: false, error: e.message }));
11043
- return;
11044
- }
11045
- case "budget_renew": {
11046
- // Authenticate the person before reading even the shape of the optional home field.
11047
- if (c.role !== "console" || c.instructed) {
11048
- return void reply({ t: "budget_renew", ok: false, error: "only the person may renew quota; run ahub budget renew in a person terminal" });
11049
- }
11050
- const peer = typeof msg.peer === "string" && PEER_ID.test(msg.peer) ? msg.peer : undefined;
11051
- const mode = msg.mode;
11052
- if (!peer || (mode !== "reset" && mode !== "switched")) {
11053
- return void reply({ t: "budget_renew", ok: false, error: "renew requires a peer and exactly one mode; run ahub budget renew <peer> --reset or --switched" });
11054
- }
11055
- const def = definitionOf(peer);
11056
- if (!def) return void reply({ t: "budget_renew", ok: false, error: "unknown peer; choose a peer shown by ahub budget" });
11057
- if (!def.budget || def.budget.quotaExempt) return void reply({ t: "budget_renew", ok: false, error: "this peer has no renewable quota; inspect ahub budget" });
11058
- const account = accountOf(peer);
11059
- const accountBase = def.budget.account;
11060
- const compareHomes = mode === "switched" && definitionOf(accountBase)?.start.daemonPort === "codex-appserver";
11061
- const quotaRuntime = (id: string) => isFixedBuiltinDefinition(definitionOf(id)) ? bus.peers.get(id) : undefined;
11062
- const compare = () => {
11063
- if (!compareHomes) return [];
11064
- const caller = typeof msg.callerHome === "string" ? msg.callerHome : undefined;
11065
- return accountMembers(account).map(id => {
11066
- try {
11067
- const result = quotaRuntime(id)?.compareQuotaHome?.(caller) ?? compareNextCodexQuotaHome(id, caller);
11068
- return { peer: id, result };
11069
- } catch {
11070
- return { peer: id, result: "unknown" as const };
11071
- }
11072
- });
11073
- };
11074
- const refused = (matches: ReturnType<typeof compare>) => {
11075
- const mismatches = matches.filter(match => match.result !== "same");
11076
- if (!mismatches.length) return false;
11077
- reply({ t: "budget_renew", ok: false, homes: mismatches, error: "Codex home differs or could not be verified; quota was not renewed" });
11078
- return true;
11079
- };
11080
- if (recoveryActive() || stopping) return void reply({ t: "budget_renew", ok: false, error: "quota was not renewed during recovery or shutdown; retry when the hub is ready" });
11081
- if (refused(compare())) return;
11082
- const changed = new Error("renewal home comparison changed");
11083
- void budget.renew(peer, mode, () => {
11084
- if (refused(compare())) throw changed;
11085
- }).then(result => {
11086
- const members = accountMembers(account);
11087
- if (definitionOf(accountBase)?.start.daemonPort === "codex-appserver") {
11088
- for (const id of members) {
11089
- try { quotaRuntime(id)?.readQuotaNow?.(); }
11090
- catch { /* The renewal is already saved. A failed read must not replace its reply. */ }
11091
- }
11092
- }
11093
- reply({ t: "budget_renew", ok: true, ...result, ...(compareHomes ? { homeComparison: "same" } : {}),
11094
- ...(compareHomes ? { pending: members.filter(id => definitionOf(id)?.start.daemonPort === "codex-appserver") } : {}),
11095
- ...(mode === "switched" && definitionOf(accountBase)?.transport === "claude-channel" ? {
11096
- softQuota: "Claude quota stays unknown after switching. Its soft gate is off. A hard refusal still pauses Claude, and you can supply a value with ahub budget set.",
11097
- } : {}) });
11098
- }, error => {
11099
- if (error === changed) return;
11100
- const stalled = error instanceof Error && error.message.startsWith("budget renewal was not saved;");
11101
- reply({ t: "budget_renew", ok: false, error: stalled ? error.message : "quota renewal did not finish; inspect ahub budget and retry when the hub is ready" });
11102
- });
11103
- return;
11104
- }
11105
- case "budget":
11106
- if (c.role !== "console") {
11107
- if (msg.resume !== undefined || msg.set !== undefined) return void reply({ t: "budget", ok: false, error: "budget mutations are console commands" });
11108
- return void reply({ t: "budget", ok: true, budget: publicPeerBudget(budgetViews(budget.status()), text => tasks.nameable(text)), peers: budgetPeerNotes(), kimiSource: kimiUsage.status(), gate: config.budget.gate, review: reviewerBudgetView() });
11109
- }
11110
- if (recoveryActive()) return void reply({ t: "budget", ok: false, error: "recovery is holding mutations" });
11111
- if (msg.resume) {
11112
- if (!budget.override(String(msg.resume))) return void reply({ t: "budget", ok: false, error: `${msg.resume} is not paused by the budget coordinator` });
11113
- } else if (msg.set) {
11114
- if (c.instructed) return void reply({ t: "budget", ok: false, error: "only the person may set quota; use ahub budget in a person terminal" });
11115
- const used = Number(msg.set.used);
11116
- if (!bus.peers.has(String(msg.set.peer)) && !budget.record(String(msg.set.peer)) && budget.renewalAt(String(msg.set.peer)) === undefined) return void reply({ t: "budget", ok: false, error: `unknown peer: ${msg.set.peer}` });
11117
- if (!(used >= 0 && used <= 1)) return void reply({ t: "budget", ok: false, error: "used must be between 0 and 1" });
11118
- budget.report(String(msg.set.peer), [{ id: msg.set.window === "week" ? "week" : "5h", kind: "manual", used, ...(msg.set.resetsInMs ? { resetsAt: Date.now() + Number(msg.set.resetsInMs) } : {}), source: "ahub budget set" }]);
11119
- }
11120
- return void reply({ t: "budget", ok: true, budget: budgetViews(budget.status()), peers: budgetPeerNotes(), kimiSource: kimiUsage.status(), gate: config.budget.gate, review: reviewerBudgetView() });
11121
- case "usage": {
11122
- // #683 U2: the console, the person and a configured planner read usage; every other agent is refused. Always answered (rid).
11123
- const planner = c.role === "tools" && !!c.peer && !!config.roles[c.peer]?.includes("planner");
11124
- if (c.role !== "console" && !planner) return void reply({ t: "usage", ok: false, error: "usage is read by the person and a configured planner" });
11125
- if (planner && c.peer && turns.get(c.peer)?.private) return void reply({ t: "usage", ok: false, error: "usage is unavailable during a private turn" });
11126
- const op = msg.op === undefined ? "query" : msg.op;
11127
- const num = (v: unknown): number | undefined | null => v === undefined ? undefined : typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : null;
11128
- const since = num(msg.since), until = num(msg.until);
11129
- if (since === null || until === null) return void reply({ t: "usage", ok: false, error: "since and until are epoch milliseconds" });
11130
- if (msg.task !== undefined && !(Number.isSafeInteger(msg.task) && (msg.task as number) > 0)) return void reply({ t: "usage", ok: false, error: "task is a positive task id" });
11131
- try {
11132
- // Fold what the log has now, within a time budget: a hub that has just started is still behind a large log, and an answer built from the
11133
- // part folded so far would read as "no records" for a peer that did use tokens. `behind` says so when the budget ran out (#683 U3).
11134
- // ponytail: catchUp runs synchronously on the daemon loop, so a request on a log far behind stalls it for up to this budget (about 250 ms
11135
- // folds the real 47 MB log). Ceiling: a log several times larger answers `behind` and finishes over the 10 s polls; move the fold to a worker if a stall is felt.
11136
- const behind = !usageRollup.catchUp(250);
11137
- const reply_ = (body: Record<string, unknown>) => reply({ ...body, ...(behind ? { behind: true } : {}) });
11138
- if (op === "limits") {
11139
- if (msg.peer !== undefined && (typeof msg.peer !== "string" || !PEER_ID.test(msg.peer))) return void reply({ t: "usage", ok: false, error: "peer must be a peer id" });
11140
- if (msg.limit !== undefined && !(Number.isInteger(msg.limit) && (msg.limit as number) >= 1 && (msg.limit as number) <= LIMITS_MAX)) return void reply({ t: "usage", ok: false, error: `limit is an integer from 1 to ${LIMITS_MAX}` });
11141
- const status = budget.status();
11142
- // The pauses the hub holds now: an event-open pause it no longer holds (an `ahub reset` cleared it) is reported as ended, not open.
11143
- const live = new Set(Object.entries(status).filter(([, v]) => v.paused).map(([peer]) => peer));
11144
- return void reply_({ t: "usage", ok: true, op, limits: usageRollup.limits(msg.peer, { ...(msg.limit !== undefined ? { limit: msg.limit as number } : {}), live }), current: publicPeerBudget(status, text => tasks.nameable(text)) });
11145
- }
11146
- if (op === "total") return void reply_({ t: "usage", ok: true, op, total: usageRollup.total() });
11147
- if (op !== "query") return void reply({ t: "usage", ok: false, error: "op is query, limits or total" });
11148
- const by = (msg.by ?? "peer") as UsageGroup;
11149
- if (!USAGE_GROUPS.includes(by)) return void reply({ t: "usage", ok: false, error: `by is one of ${USAGE_GROUPS.join(", ")}` });
11150
- // issue, pr and release are the board's current links of each task (ids only, never a title).
11151
- const board_ = new Map(board.list().map(t => [t.id, t]));
11152
- const links = (id: number) => { const t = board_.get(id); return t ? { ...(t.sdlc?.issue ? { issue: t.sdlc.issue } : {}), ...(t.sdlc?.pr ? { pr: t.sdlc.pr } : {}), ...(t.release ? { release: t.release } : {}) } : undefined; };
11153
- return void reply_({ t: "usage", ok: true, op, usage: usageRollup.query({ by, ...(since !== undefined ? { since } : {}), ...(until !== undefined ? { until } : {}), ...(msg.task !== undefined ? { task: msg.task as number } : {}) }, links) });
11154
- } catch (error) { return void reply({ t: "usage", ok: false, error: `usage unavailable: ${(error as Error).message.slice(0, 120)}` }); }
11155
- }
11156
- case "permit":
11157
- if (c.role !== "console") return void reply({ t: "permit", ok: false, error: "permit is a console command" });
11158
- return void reply({ t: "permit", ok: permissions.get(String(msg.id))?.done(msg.option ? String(msg.option) : undefined, msg.surface === "console" ? "console" : "terminal") === true });
11159
- // #1053: a person's answer to a question a peer asked. Console role ONLY, like `permit`: a peer's connection, a `hub_send` body or a tool result that quotes an answer
11160
- // is text and never reaches this case. The reply is always sent (rid), and a refusal names the row's terminal state, never its text.
11161
- case "answer": {
11162
- if (c.role !== "console" || msg.instructed !== undefined) {
11163
- if (c.role !== "tools" || !c.peer || conductorPeer(config.roles) !== c.peer) return void reply({ t: "answer", ok: false, error: "answer is a console command unless explicitly instructed through the configured conductor; use ahub console" });
11164
- if (c.toolsOwner || c.externalOwner) return void reply({ t: "answer", ok: false, error: "delegated runs cannot record person answers; use ahub console" });
11165
- if (readOnlyPeer(c.peer)) return void reply({ t: "answer", ok: false, error: "read-only sessions cannot record person answers; use ahub console" });
11166
- if (turns.get(c.peer)?.private || contextPii(c.peer) || reviewObserverInput(c.peer)) return void reply({ t: "answer", ok: false, error: "private or observer context cannot record person answers; use ahub console" });
11167
- const result = questionDesk.instructedAnswer(msg.questionSet, msg.answers, msg.instructed, c.peer);
11168
- return void reply(result.ok ? { t: "answer", ok: true, questionSet: result.row.set, state: result.row.state, actor: c.peer, instructed: true } : { t: "answer", ok: false, error: result.error });
11169
- }
11170
- if (recoveryActive() || stopping) return void reply({ t: "answer", ok: false, error: "recovery or shutdown is holding answers; answer again once the hub is back" });
11171
- const surface = msg.surface !== "conductor" && QUESTION_SURFACES.includes(msg.surface as never) ? msg.surface : "console";
11172
- // The verified identity the acon plugin read from its console's `ActionMeta` rides only on the `acon` surface, one line and bounded, never text of the question or the answer.
11173
- const person = surface === "acon" && typeof msg.person === "string" && msg.person.trim() ? sanitize(msg.person).replace(/\s+/g, " ").trim().slice(0, 200) : undefined;
11174
- const result = questionDesk.answer(msg.questionSet, msg.answers, surface, person);
11175
- return void reply(result.ok ? { t: "answer", ok: true, questionSet: result.row.set, state: result.row.state } : { t: "answer", ok: false, error: `${result.error}; the questions read lists the open ones (console)`, ...(result.state ? { state: result.state } : {}) });
11176
- }
11177
- // The person's read of the open questions (the console, `ahub`, the panel). Question text is the person's surface only: a tools connection is refused.
11178
- case "questions": {
11179
- if (c.role !== "console") return void reply({ t: "questions", ok: false, error: "questions are shown to the person: use the console" });
11180
- return void reply({ t: "questions", ok: true, questions: questionStore.list(msg.state === "all" ? {} : { state: "open" }, 100).map(questionView), answeredQuestions: instructedQuestionViews() });
11181
- }
11182
- // #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).
11183
- case "board_revision": boardRevision(daemonScope, { sock, c, msg, reply });
11184
- break;
11185
- // #1054: a person's receipt for a result. Console role ONLY, like `permit`: a peer's connection, a `hub_send` body or a tool result that quotes a receipt is text and never reaches
11186
- // the store. A snapshot or a `results` read never writes one. Every message gets a reply (rid), a refusal included.
11187
- case "result_seen": {
11188
- if (c.role !== "console") return void reply({ t: "result_seen", ok: false, error: "result_seen is a console command: only the person marks a result read" });
11189
- const marked = markResultSeen(msg.id, receiptSurface(msg.surface));
11190
- return void reply({ t: "result_seen", ...marked });
11191
- }
11192
- case "results": {
11193
- if (c.role !== "console") return void reply({ t: "results", ok: false, error: "results are shown to the person: use the console" });
11194
- if (msg.action === "read-all" || msg.action === "unread-last") {
11195
- return void reply({ t: "results", ...(msg.action === "read-all" ? markAllResultsSeen(receiptSurface(msg.surface)) : unmarkLastResult()) });
11196
- }
11197
- const unreadOnly = msg.unread === true;
11198
- const rows = completionStore.listWithState(100, unreadOnly).map(resultView);
11199
- // Say so when the listing is shorter than the truth, instead of letting "no unread results" hide an older one status still counts.
11200
- const more = unreadOnly ? Math.max(0, completionStore.unreadCount() - rows.length) : 0;
11201
- return void reply({ t: "results", ok: true, results: rows, ...(more ? { more } : {}) });
11202
- }
11203
- case "kill":
11204
- if (c.role !== "console") return void reply({ ok: false, error: "kill is a console command" });
11205
- if (msg.instanceId !== undefined && msg.instanceId !== instanceId) return void reply({ ok: false, error: "hub restarted; refresh before stopping" });
11206
- reply({ t: "stopping", ok: true, instanceId });
11207
- // Let the acknowledgement flush before closing the control listener.
11208
- setTimeout(() => void stop().catch((error) => log(`shutdown incomplete: ${(error as Error).message}`)), 0);
11209
- return;
11210
- // #1057: the worktree shelf. `worktrees` is a read (facts and the derived partition, never a GitHub call); `worktree_override_set|clear` write the person's
11211
- // park or pin; `worktrees_refresh_prs` is the one explicit action that reads GitHub. Console role only except the read, always answered (rid). The daemon deletes
11212
- // no worktree and no branch: removal is the person's CLI process (AC4).
11213
- case "worktrees":
11214
- case "worktree_override_set":
11215
- case "worktree_override_clear":
11216
- case "worktrees_refresh_prs": {
11217
- // The read is open to an agent (it can preview a tidy); setting or clearing an override and the GitHub refresh are the person's.
11218
- const person = c.role === "console";
11219
- if (!person && (msg.t !== "worktrees" || c.role !== "tools" || !c.peer || turns.get(c.peer)?.private)) return void reply({ t: msg.t, ok: false, error: "the worktree shelf is the person's: ask them to run ahub worktrees" });
11220
- void worktreeShelf({ t: msg.t, path: msg.path, value: msg.value }).then(reply, () => reply({ t: msg.t, ok: false, error: "the worktree shelf could not be read; inspect the hub log" }));
11221
- return;
11222
- }
11223
- // #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
11224
- // 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.
11225
- case "task_handoff": taskHandoff(daemonScope, { sock, c, msg, reply });
11226
- break;
11227
- case "task_handoff_event": taskHandoffEvent(daemonScope, { sock, c, msg, reply });
11228
- break;
11229
- case "task_handoff_by_key": taskHandoffByKey(daemonScope, { sock, c, msg, reply });
11230
- break;
11231
- case "task_handoff_states": taskHandoffStates(daemonScope, { sock, c, msg, reply });
11232
- break;
11233
- default:
11234
- // A newer CLI talking to an older hub must get an answer, not wait forever.
11235
- 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)` });
11236
- }
10429
+ dispatchControlMessage(daemonScope, { sock, c, msg, reply });
11237
10430
  }
11238
10431
 
11239
10432