@adhdev/mesh-shared 1.0.60-rc.7 → 1.0.60-rc.71

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 (53) hide show
  1. package/dist/brain-routing.d.ts +2 -2
  2. package/dist/index.d.ts +11 -0
  3. package/dist/index.js +3156 -48
  4. package/dist/index.js.map +1 -1
  5. package/dist/index.mjs +2827 -45
  6. package/dist/index.mjs.map +1 -1
  7. package/dist/interpolation.d.ts +0 -9
  8. package/dist/keyed-doc-delta.d.ts +105 -0
  9. package/dist/magi.d.ts +1 -1
  10. package/dist/mesh-tool-names.d.ts +27 -2
  11. package/dist/mesh-vocabulary.d.ts +67 -0
  12. package/dist/mission-brief.d.ts +62 -0
  13. package/dist/outbound-message.d.ts +202 -0
  14. package/dist/path-ownership.d.ts +101 -0
  15. package/dist/protocol/daemon-server.d.ts +379 -0
  16. package/dist/protocol/dashboard-daemon-p2p.d.ts +213 -0
  17. package/dist/protocol/dashboard-server.d.ts +240 -0
  18. package/dist/protocol/dashboard-wire-version.d.ts +21 -0
  19. package/dist/protocol/envelope.d.ts +55 -0
  20. package/dist/protocol/index.d.ts +16 -0
  21. package/dist/session-launch.d.ts +113 -0
  22. package/dist/session-status.d.ts +75 -0
  23. package/dist/slot-proposal.d.ts +1 -1
  24. package/dist/turn-evidence.d.ts +434 -0
  25. package/dist/turn-ipc.d.ts +1040 -0
  26. package/dist/types.d.ts +11 -0
  27. package/dist/worker-protocol.d.ts +69 -0
  28. package/dist/ws-protocol.d.ts +69 -41
  29. package/package.json +1 -1
  30. package/src/brain-routing.ts +3 -3
  31. package/src/index.ts +11 -0
  32. package/src/interpolation.ts +0 -18
  33. package/src/keyed-doc-delta.ts +413 -0
  34. package/src/magi.ts +1 -1
  35. package/src/mesh-tool-names.ts +65 -19
  36. package/src/mesh-vocabulary.ts +95 -0
  37. package/src/mission-brief.ts +153 -0
  38. package/src/outbound-message.ts +320 -0
  39. package/src/path-ownership.ts +271 -0
  40. package/src/protocol/daemon-server.ts +541 -0
  41. package/src/protocol/dashboard-daemon-p2p.ts +273 -0
  42. package/src/protocol/dashboard-server.ts +340 -0
  43. package/src/protocol/dashboard-wire-version.ts +27 -0
  44. package/src/protocol/envelope.ts +75 -0
  45. package/src/protocol/index.ts +17 -0
  46. package/src/session-launch.ts +247 -0
  47. package/src/session-status.ts +164 -0
  48. package/src/slot-proposal.ts +1 -1
  49. package/src/turn-evidence.ts +596 -0
  50. package/src/turn-ipc.ts +2330 -0
  51. package/src/types.ts +8 -0
  52. package/src/worker-protocol.ts +164 -0
  53. package/src/ws-protocol.ts +98 -93
package/dist/index.js CHANGED
@@ -20,52 +20,362 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ CANCEL_REASONS: () => CANCEL_REASONS,
23
24
  CANONICAL_MESH_TOOL_COUNT: () => CANONICAL_MESH_TOOL_COUNT,
24
25
  CANONICAL_MESH_TOOL_NAMES: () => CANONICAL_MESH_TOOL_NAMES,
25
26
  CLAUDE_TUI_REVIEW_PAGE_NOT_FOCUSED_PREFIX: () => CLAUDE_TUI_REVIEW_PAGE_NOT_FOCUSED_PREFIX,
26
27
  CLAUDE_TUI_REVIEW_UNCONFIRMED_PREFIX: () => CLAUDE_TUI_REVIEW_UNCONFIRMED_PREFIX,
27
28
  CLI_SLOT_RECIPES: () => CLI_SLOT_RECIPES,
29
+ COMMIT_STRENGTHS: () => COMMIT_STRENGTHS,
30
+ CONSUME_PROFILES: () => CONSUME_PROFILES,
31
+ COORDINATOR_ACK_OUTCOMES: () => COORDINATOR_ACK_OUTCOMES,
32
+ DAEMON_METADATA_DOC_SPEC: () => DAEMON_METADATA_DOC_SPEC,
33
+ DAEMON_P2P_SIGNAL_TYPES: () => DAEMON_P2P_SIGNAL_TYPES,
34
+ DAEMON_STATUS_EVENT_NAMES: () => DAEMON_STATUS_EVENT_NAMES,
35
+ DAEMON_TO_DASHBOARD_P2P_TYPES: () => DAEMON_TO_DASHBOARD_P2P_TYPES,
36
+ DAEMON_TO_SERVER_TYPES: () => DAEMON_TO_SERVER_TYPES,
28
37
  DAEMON_TO_SERVER_WS_MSGS: () => DAEMON_TO_SERVER_WS_MSGS,
38
+ DASHBOARD_P2P_MESSAGE_KINDS: () => DASHBOARD_P2P_MESSAGE_KINDS,
39
+ DASHBOARD_P2P_SIGNAL_TYPES: () => DASHBOARD_P2P_SIGNAL_TYPES,
40
+ DASHBOARD_STATUS_EVENT_NAMES: () => DASHBOARD_STATUS_EVENT_NAMES,
41
+ DASHBOARD_TO_DAEMON_P2P_TYPES: () => DASHBOARD_TO_DAEMON_P2P_TYPES,
42
+ DASHBOARD_TO_USER_SESSION_TYPES: () => DASHBOARD_TO_USER_SESSION_TYPES,
43
+ DASHBOARD_WIRE_VERSION: () => DASHBOARD_WIRE_VERSION,
29
44
  DEFAULT_DIFFICULTY_BRAINS: () => DEFAULT_DIFFICULTY_BRAINS,
45
+ DELIVERY_OUTCOMES: () => DELIVERY_OUTCOMES,
46
+ DELIVERY_VIAS: () => DELIVERY_VIAS,
47
+ DISPATCH_FAILURE_REASONS: () => DISPATCH_FAILURE_REASONS,
48
+ EVIDENCE_ENVELOPE_FIELD_SPECS: () => EVIDENCE_ENVELOPE_FIELD_SPECS,
49
+ EVIDENCE_SOURCE_IDS: () => EVIDENCE_SOURCE_IDS,
50
+ GRAPH_AUDIT_EVENTS: () => GRAPH_AUDIT_EVENTS,
51
+ HOLD_REASONS: () => HOLD_REASONS,
52
+ LIVENESS_RESULTS: () => LIVENESS_RESULTS,
30
53
  MAGI_RAW_ANSWER_CAP: () => MAGI_RAW_ANSWER_CAP,
54
+ MAX_MESH_RECORD_STRING: () => MAX_MESH_RECORD_STRING,
55
+ MAX_OWNED_PATHS: () => MAX_OWNED_PATHS,
31
56
  MESH_CHUNK_KIND: () => MESH_CHUNK_KIND,
32
57
  MESH_CHUNK_PAYLOAD_CHARS: () => MESH_CHUNK_PAYLOAD_CHARS,
33
58
  MESH_CHUNK_TTL_MS: () => MESH_CHUNK_TTL_MS,
59
+ MESH_DELIVERY_MODES: () => MESH_DELIVERY_MODES,
60
+ MESH_INDEX_QUERY_WRITER_SCOPES: () => MESH_INDEX_QUERY_WRITER_SCOPES,
34
61
  MESH_MAX_CHUNKS: () => MESH_MAX_CHUNKS,
35
62
  MESH_MAX_INLINE_FRAME_BYTES: () => MESH_MAX_INLINE_FRAME_BYTES,
36
63
  MESH_MAX_REASSEMBLED_BYTES: () => MESH_MAX_REASSEMBLED_BYTES,
64
+ MESH_MISSION_SOURCES: () => MESH_MISSION_SOURCES,
65
+ MESH_MISSION_STATUSES: () => MESH_MISSION_STATUSES,
66
+ MESH_P2P_SIGNAL_TYPES: () => MESH_P2P_SIGNAL_TYPES,
67
+ MESH_RECORD_PAYLOAD_KEYS: () => MESH_RECORD_PAYLOAD_KEYS,
68
+ MESH_SESSION_CLEANUP_MODES: () => MESH_SESSION_CLEANUP_MODES,
69
+ MESH_STATUS_DOC_SPEC: () => MESH_STATUS_DOC_SPEC,
37
70
  MESH_TASK_DIFFICULTIES: () => MESH_TASK_DIFFICULTIES,
71
+ MESH_TASK_MODES: () => MESH_TASK_MODES,
72
+ MESH_TASK_PRIORITIES: () => MESH_TASK_PRIORITIES,
73
+ MESH_TASK_STATUSES: () => MESH_TASK_STATUSES,
74
+ MESH_TERMINAL_TASK_STATUSES: () => MESH_TERMINAL_TASK_STATUSES,
75
+ MESH_THINKING_LEVELS: () => MESH_THINKING_LEVELS,
76
+ MESH_TOPIC_ENTRY_KINDS: () => MESH_TOPIC_ENTRY_KINDS,
77
+ MESH_TOPIC_PROTOCOL_VERSION: () => MESH_TOPIC_PROTOCOL_VERSION,
78
+ MISSION_BRIEF_RENDER_MAX_CHARS: () => MISSION_BRIEF_RENDER_MAX_CHARS,
79
+ MODEL_AXIS_SOURCES: () => MODEL_AXIS_SOURCES,
80
+ MODEL_SELECTION_HISTORY_LIMIT: () => MODEL_SELECTION_HISTORY_LIMIT,
38
81
  MeshChunkAssembler: () => MeshChunkAssembler,
82
+ NATIVE_TURN_OUTCOMES: () => NATIVE_TURN_OUTCOMES,
83
+ NOTIFY_KINDS: () => NOTIFY_KINDS,
84
+ NO_PROGRESS_OBSERVED_STATUSES: () => NO_PROGRESS_OBSERVED_STATUSES,
85
+ NPM_UPDATE_TAGS: () => NPM_UPDATE_TAGS,
86
+ OPERATING_NOTE_CATEGORIES: () => OPERATING_NOTE_CATEGORIES,
87
+ OPERATOR_STATUSES: () => OPERATOR_STATUSES,
88
+ OPERATOR_STATUS_REASONS: () => OPERATOR_STATUS_REASONS,
89
+ OPERATOR_STATUS_REASON_VALUES: () => OPERATOR_STATUS_REASON_VALUES,
90
+ OPERATOR_STATUS_VALUES: () => OPERATOR_STATUS_VALUES,
91
+ OUTBOUND_MESSAGE_ORIGINS: () => OUTBOUND_MESSAGE_ORIGINS,
92
+ P2P_SIGNAL_TYPES: () => P2P_SIGNAL_TYPES,
93
+ PROVIDER_FAILURES: () => PROVIDER_FAILURES,
39
94
  QUOTA_SUPPORTED_PROVIDERS: () => QUOTA_SUPPORTED_PROVIDERS,
95
+ RECENT_SESSION_BUCKETS: () => RECENT_SESSION_BUCKETS,
96
+ RECLAIMING_SEND_REFUSALS: () => RECLAIMING_SEND_REFUSALS,
97
+ RELEASE_CHANNELS: () => RELEASE_CHANNELS,
98
+ RETIRED_MESH_TOOLS: () => RETIRED_MESH_TOOLS,
99
+ SEND_POLICY_MODES: () => SEND_POLICY_MODES,
100
+ SEND_REFUSAL_REASONS: () => SEND_REFUSAL_REASONS,
101
+ SERVER_STATUS_EVENT_NAMES: () => SERVER_STATUS_EVENT_NAMES,
102
+ SERVER_TO_DAEMON_CONTROL_TYPES: () => SERVER_TO_DAEMON_CONTROL_TYPES,
40
103
  SERVER_TO_DAEMON_WS_MSGS: () => SERVER_TO_DAEMON_WS_MSGS,
104
+ SESSION_ERROR_REASONS: () => SESSION_ERROR_REASONS,
105
+ SESSION_LAUNCHED_BY: () => SESSION_LAUNCHED_BY,
106
+ SESSION_REBOUND_REASONS: () => SESSION_REBOUND_REASONS,
107
+ SESSION_STATUSES: () => SESSION_STATUSES,
108
+ SESSION_STATUS_ALIASES: () => SESSION_STATUS_ALIASES,
109
+ SESSION_STATUS_CLASS: () => SESSION_STATUS_CLASS,
110
+ SHARED_SESSION_TO_VIEWER_TYPES: () => SHARED_SESSION_TO_VIEWER_TYPES,
41
111
  STATUS_PROBE_ARG_KEY: () => STATUS_PROBE_ARG_KEY,
112
+ SUSPENSION_MODALS: () => SUSPENSION_MODALS,
113
+ SUSPENSION_RESOLUTIONS: () => SUSPENSION_RESOLUTIONS,
114
+ SUSPENSION_RESOLUTION_VIAS: () => SUSPENSION_RESOLUTION_VIAS,
115
+ SYSTEM_ANNOUNCEMENT_TYPES: () => SYSTEM_ANNOUNCEMENT_TYPES,
116
+ TERMINAL_CLASS_EVIDENCE_KINDS: () => TERMINAL_CLASS_EVIDENCE_KINDS,
117
+ TERMINAL_SESSION_RECORD_STATUSES: () => TERMINAL_SESSION_RECORD_STATUSES,
118
+ TOOL_CALLER_ROLES: () => TOOL_CALLER_ROLES,
119
+ TURN_END_BLOCK_REASONS: () => TURN_END_BLOCK_REASONS,
120
+ TURN_END_STRENGTHS: () => TURN_END_STRENGTHS,
121
+ TURN_EVIDENCE_FIELD_SPECS: () => TURN_EVIDENCE_FIELD_SPECS,
122
+ TURN_EVIDENCE_FLAGS: () => TURN_EVIDENCE_FLAGS,
123
+ TURN_EVIDENCE_KINDS: () => TURN_EVIDENCE_KINDS,
124
+ TURN_IPC_COMMANDS: () => TURN_IPC_COMMANDS,
125
+ TURN_IPC_ERROR_CODES: () => TURN_IPC_ERROR_CODES,
126
+ TURN_IPC_PROTOCOL_VERSION: () => TURN_IPC_PROTOCOL_VERSION,
127
+ TURN_OBSERVE_VERDICTS: () => TURN_OBSERVE_VERDICTS,
128
+ TURN_OUTCOMES: () => TURN_OUTCOMES,
129
+ TURN_REASONS: () => TURN_REASONS,
130
+ TURN_SCOPES: () => TURN_SCOPES,
42
131
  UNKNOWN_CLI_SLOT_RECIPE: () => UNKNOWN_CLI_SLOT_RECIPE,
132
+ USER_SESSION_TO_DASHBOARD_TYPES: () => USER_SESSION_TO_DASHBOARD_TYPES,
133
+ VERSION_UPDATE_REASONS: () => VERSION_UPDATE_REASONS,
134
+ VIEWER_TO_SHARED_SESSION_TYPES: () => VIEWER_TO_SHARED_SESSION_TYPES,
135
+ WORKER_BRANCH_STATES: () => WORKER_BRANCH_STATES,
136
+ WORKER_PROTOCOL_FOOTER_MARKER: () => WORKER_PROTOCOL_FOOTER_MARKER,
137
+ WORKER_REPORT_OUTCOMES: () => WORKER_REPORT_OUTCOMES,
138
+ WORKER_TOOLS: () => WORKER_TOOLS,
139
+ appendWorkerProtocolFooter: () => appendWorkerProtocolFooter,
43
140
  argsCarryStatusProbeMarker: () => argsCarryStatusProbeMarker,
44
141
  buildMagiPanelProposal: () => buildMagiPanelProposal,
45
142
  buildSlotProposal: () => buildSlotProposal,
46
143
  canonicalDaemonId: () => canonicalDaemonId,
144
+ classifySessionStatus: () => classifySessionStatus,
145
+ compareDashboardWireVersion: () => compareDashboardWireVersion,
47
146
  compareSemver: () => compareSemver,
48
147
  daemonIdsEquivalent: () => daemonIdsEquivalent,
148
+ decodeActiveWorkQueryRequest: () => decodeActiveWorkQueryRequest,
149
+ decodeActiveWorkQueryResponse: () => decodeActiveWorkQueryResponse,
150
+ decodeDaemonToDashboardP2P: () => decodeDaemonToDashboardP2P,
151
+ decodeDaemonToServer: () => decodeDaemonToServer,
152
+ decodeDashboardToDaemonP2P: () => decodeDashboardToDaemonP2P,
153
+ decodeDashboardToDaemonP2PChunk: () => decodeDashboardToDaemonP2PChunk,
154
+ decodeDashboardToUserSession: () => decodeDashboardToUserSession,
155
+ decodeDirectDispatchRecordRequest: () => decodeDirectDispatchRecordRequest,
156
+ decodeDirectDispatchRecordResponse: () => decodeDirectDispatchRecordResponse,
157
+ decodeGraphAuditRecordRequest: () => decodeGraphAuditRecordRequest,
158
+ decodeGraphAuditRecordResponse: () => decodeGraphAuditRecordResponse,
159
+ decodeGraphGateAbandonRequest: () => decodeGraphGateAbandonRequest,
160
+ decodeGraphGateAbandonResponse: () => decodeGraphGateAbandonResponse,
161
+ decodeGraphGateClaimRequest: () => decodeGraphGateClaimRequest,
162
+ decodeGraphGateClaimResponse: () => decodeGraphGateClaimResponse,
163
+ decodeGraphGateReleaseRequest: () => decodeGraphGateReleaseRequest,
164
+ decodeGraphGateReleaseResponse: () => decodeGraphGateReleaseResponse,
165
+ decodeGraphNodePatchRequest: () => decodeGraphNodePatchRequest,
166
+ decodeGraphNodePatchResponse: () => decodeGraphNodePatchResponse,
167
+ decodeGraphViewQueryRequest: () => decodeGraphViewQueryRequest,
168
+ decodeGraphViewQueryResponse: () => decodeGraphViewQueryResponse,
169
+ decodeLedgerQueryRequest: () => decodeLedgerQueryRequest,
170
+ decodeLedgerQueryResponse: () => decodeLedgerQueryResponse,
171
+ decodeMeshIndexQueryRequest: () => decodeMeshIndexQueryRequest,
172
+ decodeMeshIndexQueryResponse: () => decodeMeshIndexQueryResponse,
173
+ decodeMeshRecordRequest: () => decodeMeshRecordRequest,
174
+ decodeMeshRecordResponse: () => decodeMeshRecordResponse,
175
+ decodeMissionListQueryRequest: () => decodeMissionListQueryRequest,
176
+ decodeMissionListQueryResponse: () => decodeMissionListQueryResponse,
177
+ decodeMissionQueryRequest: () => decodeMissionQueryRequest,
178
+ decodeMissionQueryResponse: () => decodeMissionQueryResponse,
179
+ decodeMissionUpsertRequest: () => decodeMissionUpsertRequest,
180
+ decodeMissionUpsertResponse: () => decodeMissionUpsertResponse,
181
+ decodeNoteForgetRequest: () => decodeNoteForgetRequest,
182
+ decodeNoteForgetResponse: () => decodeNoteForgetResponse,
183
+ decodeNoteUpsertRequest: () => decodeNoteUpsertRequest,
184
+ decodeNoteUpsertResponse: () => decodeNoteUpsertResponse,
185
+ decodeOperatorStatusRequest: () => decodeOperatorStatusRequest,
186
+ decodeOperatorStatusResponse: () => decodeOperatorStatusResponse,
187
+ decodeOrphanedPinNotifyRequest: () => decodeOrphanedPinNotifyRequest,
188
+ decodeOrphanedPinNotifyResponse: () => decodeOrphanedPinNotifyResponse,
189
+ decodePruneStaleDirectRequest: () => decodePruneStaleDirectRequest,
190
+ decodePruneStaleDirectResponse: () => decodePruneStaleDirectResponse,
191
+ decodeQueueCancelRequest: () => decodeQueueCancelRequest,
192
+ decodeQueueCancelResponse: () => decodeQueueCancelResponse,
193
+ decodeQueueEnqueueGraphRequest: () => decodeQueueEnqueueGraphRequest,
194
+ decodeQueueEnqueueGraphResponse: () => decodeQueueEnqueueGraphResponse,
195
+ decodeQueueEnqueueRequest: () => decodeQueueEnqueueRequest,
196
+ decodeQueueEnqueueResponse: () => decodeQueueEnqueueResponse,
197
+ decodeQueueQueryRequest: () => decodeQueueQueryRequest,
198
+ decodeQueueQueryResponse: () => decodeQueueQueryResponse,
199
+ decodeQueueRequeueRequest: () => decodeQueueRequeueRequest,
200
+ decodeQueueRequeueResponse: () => decodeQueueRequeueResponse,
201
+ decodeRecordLocalRequest: () => decodeRecordLocalRequest,
202
+ decodeRecordLocalResponse: () => decodeRecordLocalResponse,
203
+ decodeRecoveryContextQueryRequest: () => decodeRecoveryContextQueryRequest,
204
+ decodeRecoveryContextQueryResponse: () => decodeRecoveryContextQueryResponse,
205
+ decodeServerToDaemon: () => decodeServerToDaemon,
206
+ decodeTaskStatsQueryRequest: () => decodeTaskStatsQueryRequest,
207
+ decodeTaskStatsQueryResponse: () => decodeTaskStatsQueryResponse,
208
+ decodeToolCallRecordRequest: () => decodeToolCallRecordRequest,
209
+ decodeToolCallRecordResponse: () => decodeToolCallRecordResponse,
210
+ decodeTurnCancelRequest: () => decodeTurnCancelRequest,
211
+ decodeTurnCancelResponse: () => decodeTurnCancelResponse,
212
+ decodeTurnObserveRequest: () => decodeTurnObserveRequest,
213
+ decodeTurnObserveResponse: () => decodeTurnObserveResponse,
214
+ decodeTurnQueryRequest: () => decodeTurnQueryRequest,
215
+ decodeTurnQueryResponse: () => decodeTurnQueryResponse,
216
+ decodeTypeField: () => decodeTypeField,
217
+ decodeUserSessionToDashboard: () => decodeUserSessionToDashboard,
218
+ decodeViewerToSharedSession: () => decodeViewerToSharedSession,
49
219
  deriveProviderPriorityFromSlots: () => deriveProviderPriorityFromSlots,
50
220
  deriveSlotsFromLegacy: () => deriveSlotsFromLegacy,
221
+ describeModelSelection: () => describeModelSelection,
222
+ diffKeyedDoc: () => diffKeyedDoc,
223
+ digestKeyedDoc: () => digestKeyedDoc,
224
+ effectiveModelSelectionValue: () => effectiveModelSelectionValue,
225
+ enumOf: () => enumOf,
51
226
  expandDaemonIdForms: () => expandDaemonIdForms,
227
+ findOwnershipConflicts: () => findOwnershipConflicts,
228
+ foldKeyedDoc: () => foldKeyedDoc,
52
229
  formatQuotaAccount: () => formatQuotaAccount,
53
230
  hasGitStatusEvidence: () => hasGitStatusEvidence,
54
- interpolateArgs: () => interpolateArgs,
231
+ hasWorkerProtocolFooter: () => hasWorkerProtocolFooter,
55
232
  interpolateString: () => interpolateString,
56
- isDaemonToServerWsMsg: () => isDaemonToServerWsMsg,
233
+ isActiveWorkQueryRequest: () => isActiveWorkQueryRequest,
234
+ isActiveWorkQueryResponse: () => isActiveWorkQueryResponse,
235
+ isBlockedStatus: () => isBlockedStatus,
236
+ isBusyStatus: () => isBusyStatus,
237
+ isChunkType: () => isChunkType,
238
+ isCommitStrength: () => isCommitStrength,
239
+ isDaemonDirectCommandType: () => isDaemonDirectCommandType,
240
+ isDaemonP2PSignalType: () => isDaemonP2PSignalType,
241
+ isDaemonStatusEventName: () => isDaemonStatusEventName,
242
+ isDaemonToDashboardP2PType: () => isDaemonToDashboardP2PType,
243
+ isDaemonToServerType: () => isDaemonToServerType,
244
+ isDashboardP2PSignalType: () => isDashboardP2PSignalType,
245
+ isDashboardStatusEventName: () => isDashboardStatusEventName,
246
+ isDashboardToDaemonChunkType: () => isDashboardToDaemonChunkType,
247
+ isDashboardToDaemonP2PType: () => isDashboardToDaemonP2PType,
248
+ isDashboardToUserSessionType: () => isDashboardToUserSessionType,
249
+ isDeadStatus: () => isDeadStatus,
250
+ isDirectDispatchRecordRequest: () => isDirectDispatchRecordRequest,
251
+ isDirectDispatchRecordResponse: () => isDirectDispatchRecordResponse,
57
252
  isDowngrade: () => isDowngrade,
253
+ isEvidenceIdentifier: () => isEvidenceIdentifier,
254
+ isFiniteNumber: () => isFiniteNumber,
255
+ isGraphAuditEvent: () => isGraphAuditEvent,
256
+ isGraphAuditRecordRequest: () => isGraphAuditRecordRequest,
257
+ isGraphAuditRecordResponse: () => isGraphAuditRecordResponse,
258
+ isGraphGateAbandonRequest: () => isGraphGateAbandonRequest,
259
+ isGraphGateAbandonResponse: () => isGraphGateAbandonResponse,
260
+ isGraphGateClaimRequest: () => isGraphGateClaimRequest,
261
+ isGraphGateClaimResponse: () => isGraphGateClaimResponse,
262
+ isGraphGateReleaseRequest: () => isGraphGateReleaseRequest,
263
+ isGraphGateReleaseResponse: () => isGraphGateReleaseResponse,
264
+ isGraphNodePatchRequest: () => isGraphNodePatchRequest,
265
+ isGraphNodePatchResponse: () => isGraphNodePatchResponse,
266
+ isGraphViewQueryRequest: () => isGraphViewQueryRequest,
267
+ isGraphViewQueryResponse: () => isGraphViewQueryResponse,
268
+ isIdleSessionState: () => isIdleSessionState,
269
+ isInputEnvelopeWire: () => isInputEnvelopeWire,
270
+ isLedgerQueryRequest: () => isLedgerQueryRequest,
271
+ isLedgerQueryResponse: () => isLedgerQueryResponse,
272
+ isMeshDeliveryMode: () => isMeshDeliveryMode,
273
+ isMeshIndexQueryRequest: () => isMeshIndexQueryRequest,
274
+ isMeshIndexQueryResponse: () => isMeshIndexQueryResponse,
275
+ isMeshIndexQueryWriterScope: () => isMeshIndexQueryWriterScope,
276
+ isMeshMissionSourceValue: () => isMeshMissionSourceValue,
277
+ isMeshMissionStatusValue: () => isMeshMissionStatusValue,
278
+ isMeshP2PSignalType: () => isMeshP2PSignalType,
279
+ isMeshRecordPayload: () => isMeshRecordPayload,
280
+ isMeshRecordRequest: () => isMeshRecordRequest,
281
+ isMeshRecordResponse: () => isMeshRecordResponse,
58
282
  isMeshTaskDifficulty: () => isMeshTaskDifficulty,
283
+ isMeshTaskMode: () => isMeshTaskMode,
284
+ isMeshTaskPriority: () => isMeshTaskPriority,
285
+ isMeshTaskStatus: () => isMeshTaskStatus,
286
+ isMeshTerminalTaskStatus: () => isMeshTerminalTaskStatus,
287
+ isMeshTopicEntry: () => isMeshTopicEntry,
288
+ isMessageId: () => isMessageId,
289
+ isMissionListQueryRequest: () => isMissionListQueryRequest,
290
+ isMissionListQueryResponse: () => isMissionListQueryResponse,
291
+ isMissionQueryRequest: () => isMissionQueryRequest,
292
+ isMissionQueryResponse: () => isMissionQueryResponse,
293
+ isMissionUpsertRequest: () => isMissionUpsertRequest,
294
+ isMissionUpsertResponse: () => isMissionUpsertResponse,
295
+ isModelAxisSource: () => isModelAxisSource,
296
+ isNonEmptyString: () => isNonEmptyString,
297
+ isNoteForgetRequest: () => isNoteForgetRequest,
298
+ isNoteForgetResponse: () => isNoteForgetResponse,
299
+ isNoteUpsertRequest: () => isNoteUpsertRequest,
300
+ isNoteUpsertResponse: () => isNoteUpsertResponse,
301
+ isNotifyKind: () => isNotifyKind,
302
+ isOperatingNoteCategory: () => isOperatingNoteCategory,
303
+ isOperatorStatusReasonValue: () => isOperatorStatusReasonValue,
304
+ isOperatorStatusRequest: () => isOperatorStatusRequest,
305
+ isOperatorStatusResponse: () => isOperatorStatusResponse,
306
+ isOperatorStatusValue: () => isOperatorStatusValue,
307
+ isOrphanedPinNotifyRequest: () => isOrphanedPinNotifyRequest,
308
+ isOrphanedPinNotifyResponse: () => isOrphanedPinNotifyResponse,
309
+ isOutboundMessage: () => isOutboundMessage,
310
+ isOutboundMessageOrigin: () => isOutboundMessageOrigin,
311
+ isP2PSignalType: () => isP2PSignalType,
59
312
  isPhantomDaemonEntry: () => isPhantomDaemonEntry,
313
+ isPruneStaleDirectRequest: () => isPruneStaleDirectRequest,
314
+ isPruneStaleDirectResponse: () => isPruneStaleDirectResponse,
315
+ isQueueCancelRequest: () => isQueueCancelRequest,
316
+ isQueueCancelResponse: () => isQueueCancelResponse,
317
+ isQueueEnqueueGraphRequest: () => isQueueEnqueueGraphRequest,
318
+ isQueueEnqueueGraphResponse: () => isQueueEnqueueGraphResponse,
319
+ isQueueEnqueueRequest: () => isQueueEnqueueRequest,
320
+ isQueueEnqueueResponse: () => isQueueEnqueueResponse,
321
+ isQueueQueryRequest: () => isQueueQueryRequest,
322
+ isQueueQueryResponse: () => isQueueQueryResponse,
323
+ isQueueRequeueRequest: () => isQueueRequeueRequest,
324
+ isQueueRequeueResponse: () => isQueueRequeueResponse,
60
325
  isRawDaemonDoId: () => isRawDaemonDoId,
61
- isServerToDaemonWsMsg: () => isServerToDaemonWsMsg,
326
+ isReadyStatus: () => isReadyStatus,
327
+ isRecord: () => isRecord,
328
+ isRecordLocalRequest: () => isRecordLocalRequest,
329
+ isRecordLocalResponse: () => isRecordLocalResponse,
330
+ isRecoveryContextQueryRequest: () => isRecoveryContextQueryRequest,
331
+ isRecoveryContextQueryResponse: () => isRecoveryContextQueryResponse,
332
+ isSendPolicy: () => isSendPolicy,
333
+ isSendPolicyMode: () => isSendPolicyMode,
334
+ isSendRefusal: () => isSendRefusal,
335
+ isServerDirectCommandMsg: () => isServerDirectCommandMsg,
336
+ isServerToDaemonControlType: () => isServerToDaemonControlType,
337
+ isSessionLaunchedBy: () => isSessionLaunchedBy,
338
+ isSessionStatus: () => isSessionStatus,
339
+ isSharedSessionToViewerType: () => isSharedSessionToViewerType,
340
+ isSubmitOutcome: () => isSubmitOutcome,
341
+ isSummaryRef: () => isSummaryRef,
342
+ isTaskStatsQueryRequest: () => isTaskStatsQueryRequest,
343
+ isTaskStatsQueryResponse: () => isTaskStatsQueryResponse,
344
+ isTerminalSessionRecordStatus: () => isTerminalSessionRecordStatus,
345
+ isToolCallRecordRequest: () => isToolCallRecordRequest,
346
+ isToolCallRecordResponse: () => isToolCallRecordResponse,
347
+ isToolCallerRole: () => isToolCallerRole,
348
+ isTurnAttemptRef: () => isTurnAttemptRef,
349
+ isTurnCancelRequest: () => isTurnCancelRequest,
350
+ isTurnCancelResponse: () => isTurnCancelResponse,
351
+ isTurnEvidence: () => isTurnEvidence,
352
+ isTurnEvidenceKind: () => isTurnEvidenceKind,
353
+ isTurnIpcCommand: () => isTurnIpcCommand,
354
+ isTurnIpcError: () => isTurnIpcError,
355
+ isTurnIpcErrorCode: () => isTurnIpcErrorCode,
356
+ isTurnObserveRequest: () => isTurnObserveRequest,
357
+ isTurnObserveResponse: () => isTurnObserveResponse,
358
+ isTurnObserveVerdict: () => isTurnObserveVerdict,
359
+ isTurnOutcome: () => isTurnOutcome,
360
+ isTurnQueryRequest: () => isTurnQueryRequest,
361
+ isTurnQueryResponse: () => isTurnQueryResponse,
362
+ isTurnReason: () => isTurnReason,
363
+ isUserSessionToDashboardType: () => isUserSessionToDashboardType,
364
+ isViewerToSharedSessionType: () => isViewerToSharedSessionType,
365
+ isWorkerReportOutcome: () => isWorkerReportOutcome,
366
+ isWorkerTool: () => isWorkerTool,
367
+ isWorkingStatus: () => isWorkingStatus,
62
368
  joinRepoPath: () => joinRepoPath,
369
+ launchModelSelectionValue: () => launchModelSelectionValue,
63
370
  machineCoreFromDaemonId: () => machineCoreFromDaemonId,
371
+ makeTypeGuard: () => makeTypeGuard,
64
372
  measureWorstCaseChunkEnvelopeBytes: () => measureWorstCaseChunkEnvelopeBytes,
65
373
  meshFrameNeedsChunking: () => meshFrameNeedsChunking,
66
374
  meshNodeIdMatches: () => meshNodeIdMatches,
67
375
  meshUtf8ByteLength: () => meshUtf8ByteLength,
68
376
  meshWorkspacesEquivalent: () => meshWorkspacesEquivalent,
377
+ mintMessageId: () => mintMessageId,
378
+ normalizeAuthOkLimits: () => normalizeAuthOkLimits,
69
379
  normalizeBrainSlot: () => normalizeBrainSlot,
70
380
  normalizeDifficultyBrainMap: () => normalizeDifficultyBrainMap,
71
381
  normalizeGitStatus: () => normalizeGitStatus,
@@ -73,25 +383,41 @@ __export(index_exports, {
73
383
  normalizeMeshNodeId: () => normalizeMeshNodeId,
74
384
  normalizeMeshSessionRecord: () => normalizeMeshSessionRecord,
75
385
  normalizeMeshWorkspaceForCompare: () => normalizeMeshWorkspaceForCompare,
386
+ normalizeMissionBrief: () => normalizeMissionBrief,
76
387
  normalizeNodeCapabilitySlot: () => normalizeNodeCapabilitySlot,
77
388
  normalizeNodeCapabilitySlots: () => normalizeNodeCapabilitySlots,
389
+ normalizeOwnedPaths: () => normalizeOwnedPaths,
390
+ normalizeSessionStatus: () => normalizeSessionStatus,
78
391
  normalizeThinkingLevel: () => normalizeThinkingLevel,
79
392
  parseJsonRecord: () => parseJsonRecord,
80
393
  parseSemver: () => parseSemver,
394
+ parseSessionLaunchRecord: () => parseSessionLaunchRecord,
395
+ pathsOverlap: () => pathsOverlap,
81
396
  pickBestTransitGitStatus: () => pickBestTransitGitStatus,
397
+ projectTurnEvidenceEntry: () => projectTurnEvidenceEntry,
82
398
  readBoolean: () => readBoolean,
399
+ readEnvelopeFields: () => readEnvelopeFields,
83
400
  readGitSubmodules: () => readGitSubmodules,
84
401
  readNumber: () => readNumber,
85
402
  readRecord: () => readRecord,
86
403
  readString: () => readString,
87
404
  readStringArray: () => readStringArray,
405
+ renderCoordinatorWorkerSection: () => renderCoordinatorWorkerSection,
406
+ renderMissionBriefBlock: () => renderMissionBriefBlock,
407
+ renderWorkerProtocolFooter: () => renderWorkerProtocolFooter,
408
+ retiredMeshToolError: () => retiredMeshToolError,
409
+ sanitizeModelIdentifier: () => sanitizeModelIdentifier,
410
+ sanitizeRefusalCode: () => sanitizeRefusalCode,
88
411
  scoreGitStatusCandidate: () => scoreGitStatusCandidate,
89
412
  scoreGitUpstreamFreshness: () => scoreGitUpstreamFreshness,
90
413
  sessionIdsEquivalent: () => sessionIdsEquivalent,
91
414
  splitMeshFrame: () => splitMeshFrame,
415
+ statusesOfClass: () => statusesOfClass,
92
416
  stripStatusProbeMarker: () => stripStatusProbeMarker,
417
+ stripWorkerProtocolFooter: () => stripWorkerProtocolFooter,
93
418
  summarizeGitShape: () => summarizeGitShape,
94
419
  supportsQuota: () => supportsQuota,
420
+ touchedFilesOutsideOwnership: () => touchedFilesOutsideOwnership,
95
421
  withStatusProbeMarker: () => withStatusProbeMarker
96
422
  });
97
423
  module.exports = __toCommonJS(index_exports);
@@ -385,8 +711,8 @@ function meshWorkspacesEquivalent(a, b) {
385
711
 
386
712
  // src/daemon-normalize.ts
387
713
  var DAEMON_ID_PREFIXES = ["daemon_", "standalone_"];
388
- function isRawDaemonDoId(id) {
389
- const trimmed = readString(id);
714
+ function isRawDaemonDoId(id2) {
715
+ const trimmed = readString(id2);
390
716
  return !!trimmed && /^[0-9a-f]{64}$/i.test(trimmed);
391
717
  }
392
718
  function isPhantomDaemonEntry(entry) {
@@ -397,8 +723,8 @@ function isPhantomDaemonEntry(entry) {
397
723
  );
398
724
  return !hasMachineEvidence;
399
725
  }
400
- function machineCoreFromDaemonId(id) {
401
- const trimmed = readString(id);
726
+ function machineCoreFromDaemonId(id2) {
727
+ const trimmed = readString(id2);
402
728
  if (!trimmed) return void 0;
403
729
  for (const prefix of DAEMON_ID_PREFIXES) {
404
730
  if (trimmed.startsWith(prefix)) {
@@ -408,8 +734,8 @@ function machineCoreFromDaemonId(id) {
408
734
  }
409
735
  return trimmed;
410
736
  }
411
- function canonicalDaemonId(id) {
412
- const core = machineCoreFromDaemonId(id);
737
+ function canonicalDaemonId(id2) {
738
+ const core = machineCoreFromDaemonId(id2);
413
739
  if (!core) return void 0;
414
740
  if (!core.startsWith("mach_")) return core;
415
741
  return `daemon_${core}`;
@@ -736,13 +1062,6 @@ function buildMagiPanelProposal(detected, opts = {}) {
736
1062
  }
737
1063
 
738
1064
  // src/interpolation.ts
739
- function interpolateArgs(args, context) {
740
- const result = {};
741
- for (const [k, v] of Object.entries(args)) {
742
- result[k] = typeof v === "string" ? interpolateString(v, context) : v;
743
- }
744
- return result;
745
- }
746
1065
  function interpolateString(template, ctx) {
747
1066
  return template.replace(/\{\{(\w+)\}\}/g, (_, key) => {
748
1067
  const val = ctx[key];
@@ -761,9 +1080,7 @@ var CANONICAL_MESH_TOOL_NAMES = [
761
1080
  "mesh_view_queue",
762
1081
  // GRAPH-ORCHESTRATION Phase E — the coordinator gate + graph view surface.
763
1082
  "mesh_graph_view",
764
- "mesh_graph_gate_claim",
765
- "mesh_graph_gate_release",
766
- "mesh_graph_gate_abandon",
1083
+ "mesh_graph_gate",
767
1084
  "mesh_graph_node_patch",
768
1085
  "mesh_queue_cancel",
769
1086
  "mesh_queue_requeue",
@@ -781,7 +1098,6 @@ var CANONICAL_MESH_TOOL_NAMES = [
781
1098
  "mesh_approve",
782
1099
  "mesh_answer_question",
783
1100
  "mesh_list_pending_approvals",
784
- "mesh_plan_onboarding",
785
1101
  "mesh_create",
786
1102
  "mesh_add_node",
787
1103
  "mesh_clone_node",
@@ -789,34 +1105,57 @@ var CANONICAL_MESH_TOOL_NAMES = [
789
1105
  "mesh_cleanup_worktree_nodes",
790
1106
  "mesh_refine_node",
791
1107
  "mesh_refine_batch",
792
- "mesh_refine_config",
793
- "mesh_change_impact_config",
1108
+ "mesh_config",
794
1109
  "mesh_init",
795
- "mesh_reinit",
796
- "mesh_write_mesh_json_config",
797
1110
  "mesh_refine_plan",
798
1111
  "mesh_cleanup_sessions",
799
- "mesh_prune_stale_direct",
800
1112
  "mesh_task_history",
801
1113
  "mesh_ledger_query",
802
- "mesh_record_note",
803
- "mesh_forget_note",
1114
+ "mesh_note",
804
1115
  "mesh_reconcile_ledger",
805
- "mesh_requeue_held_events",
806
1116
  "mesh_mission_upsert",
807
1117
  "mesh_mission_list",
808
1118
  "mesh_review_inbox",
809
1119
  "mesh_magi_review",
810
1120
  "mesh_magi_collect",
811
- "mesh_magi_kind_panel_set",
812
- "mesh_magi_kind_panel_list",
813
- "mesh_node_slots_set",
814
- "mesh_node_slots_list",
815
- "mesh_node_slots_propose",
816
- "mesh_coordinator_prompt_append_get",
817
- "mesh_coordinator_prompt_append_set"
1121
+ "mesh_magi_kind_panel",
1122
+ "mesh_node_slots",
1123
+ "mesh_coordinator_prompt_append"
818
1124
  ];
819
1125
  var CANONICAL_MESH_TOOL_COUNT = CANONICAL_MESH_TOOL_NAMES.length;
1126
+ var RETIRED_MESH_TOOLS = {
1127
+ mesh_graph_gate_claim: {
1128
+ tool: "mesh_graph_gate",
1129
+ args: { action: "claim" },
1130
+ note: 'The extend-only form (claim with extend_seconds) is now action: "extend" with the same extend_seconds.'
1131
+ },
1132
+ mesh_graph_gate_release: { tool: "mesh_graph_gate", args: { action: "release" } },
1133
+ mesh_graph_gate_abandon: { tool: "mesh_graph_gate", args: { action: "abandon" } },
1134
+ // Never a published tool (it is the daemon command behind the extend verb),
1135
+ // but an older gate-expiry notice told coordinators to call it by this name.
1136
+ mesh_graph_gate_extend: { tool: "mesh_graph_gate", args: { action: "extend" } },
1137
+ mesh_node_slots_set: { tool: "mesh_node_slots", args: { action: "set" } },
1138
+ mesh_node_slots_list: { tool: "mesh_node_slots", args: { action: "list" } },
1139
+ mesh_node_slots_propose: { tool: "mesh_node_slots", args: { action: "propose" } },
1140
+ mesh_magi_kind_panel_set: { tool: "mesh_magi_kind_panel", args: { action: "set" } },
1141
+ mesh_magi_kind_panel_list: { tool: "mesh_magi_kind_panel", args: { action: "list" } },
1142
+ mesh_coordinator_prompt_append_get: { tool: "mesh_coordinator_prompt_append", args: { action: "get" } },
1143
+ mesh_coordinator_prompt_append_set: { tool: "mesh_coordinator_prompt_append", args: { action: "set" } },
1144
+ mesh_record_note: { tool: "mesh_note", args: { action: "record" } },
1145
+ mesh_forget_note: { tool: "mesh_note", args: { action: "forget" } },
1146
+ mesh_reinit: { tool: "mesh_init", args: { mode: "reinit" } },
1147
+ mesh_refine_config: { tool: "mesh_config", args: { kind: "refine" } },
1148
+ mesh_change_impact_config: { tool: "mesh_config", args: { kind: "change_impact" } },
1149
+ mesh_write_mesh_json_config: { tool: "mesh_config", args: { kind: "mesh_json" } },
1150
+ mesh_plan_onboarding: { tool: "mesh_create", args: { mode: "plan" } },
1151
+ mesh_prune_stale_direct: { tool: "mesh_cleanup_sessions", args: { mode: "prune_stale_direct" } }
1152
+ };
1153
+ function retiredMeshToolError(name) {
1154
+ const entry = Object.prototype.hasOwnProperty.call(RETIRED_MESH_TOOLS, name) ? RETIRED_MESH_TOOLS[name] : void 0;
1155
+ if (!entry) return null;
1156
+ const discriminator = Object.entries(entry.args).map(([k, v]) => `${k}: "${v}"`).join(", ");
1157
+ return `Tool "${name}" was retired (merged into ${entry.tool}). Call ${entry.tool} with ${discriminator} and the same other arguments.` + (entry.note ? ` ${entry.note}` : "");
1158
+ }
820
1159
 
821
1160
  // src/mesh-status-probe.ts
822
1161
  var STATUS_PROBE_ARG_KEY = "_statusProbe";
@@ -1055,8 +1394,52 @@ function isDowngrade(current, target) {
1055
1394
  return direction < 0;
1056
1395
  }
1057
1396
 
1058
- // src/ws-protocol.ts
1059
- var DAEMON_TO_SERVER_WS_MSGS = [
1397
+ // src/protocol/envelope.ts
1398
+ function isRecord(value) {
1399
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1400
+ }
1401
+ function isNonEmptyString(value) {
1402
+ return typeof value === "string" && value.length > 0;
1403
+ }
1404
+ function isFiniteNumber(value) {
1405
+ return typeof value === "number" && Number.isFinite(value);
1406
+ }
1407
+ function makeTypeGuard(names) {
1408
+ const set = new Set(names);
1409
+ return (value) => typeof value === "string" && set.has(value);
1410
+ }
1411
+ function decodeTypeField(raw, isType) {
1412
+ if (!isRecord(raw)) return null;
1413
+ if (!isType(raw.type)) return null;
1414
+ return { type: raw.type, frame: raw };
1415
+ }
1416
+ function readEnvelopeFields(frame) {
1417
+ return {
1418
+ ...isNonEmptyString(frame.id) ? { id: frame.id } : {},
1419
+ ...isFiniteNumber(frame.timestamp) ? { timestamp: frame.timestamp } : {}
1420
+ };
1421
+ }
1422
+
1423
+ // src/protocol/daemon-server.ts
1424
+ var DAEMON_STATUS_EVENT_NAMES = [
1425
+ "agent:generating_started",
1426
+ "agent:waiting_approval",
1427
+ "agent:waiting_choice",
1428
+ "agent:generating_completed",
1429
+ "agent:stopped",
1430
+ "monitor:no_progress"
1431
+ ];
1432
+ var isDaemonStatusEventName = makeTypeGuard(DAEMON_STATUS_EVENT_NAMES);
1433
+ var RELEASE_CHANNELS = ["stable", "preview"];
1434
+ var NPM_UPDATE_TAGS = ["latest", "next"];
1435
+ var VERSION_UPDATE_REASONS = ["force_update_below", "major_minor_mismatch", "patch_mismatch", "daemon_ahead"];
1436
+ var P2P_SIGNAL_TYPES = ["p2p_ready", "p2p_offer", "p2p_answer", "p2p_ice"];
1437
+ var isP2PSignalType = makeTypeGuard(P2P_SIGNAL_TYPES);
1438
+ var DAEMON_P2P_SIGNAL_TYPES = ["p2p_offer", "p2p_ice"];
1439
+ var isDaemonP2PSignalType = makeTypeGuard(DAEMON_P2P_SIGNAL_TYPES);
1440
+ var MESH_P2P_SIGNAL_TYPES = ["mesh_p2p_ready", "mesh_p2p_offer", "mesh_p2p_answer", "mesh_p2p_ice"];
1441
+ var isMeshP2PSignalType = makeTypeGuard(MESH_P2P_SIGNAL_TYPES);
1442
+ var DAEMON_TO_SERVER_TYPES = [
1060
1443
  "auth",
1061
1444
  "status_report",
1062
1445
  "status_heartbeat",
@@ -1064,10 +1447,29 @@ var DAEMON_TO_SERVER_WS_MSGS = [
1064
1447
  "command_result",
1065
1448
  "error",
1066
1449
  "agent_event",
1067
- "log",
1068
- "beacon_vectors"
1450
+ "beacon_vectors",
1451
+ "daemon_mesh_command",
1452
+ "p2p_offer",
1453
+ "p2p_ice"
1069
1454
  ];
1070
- var SERVER_TO_DAEMON_WS_MSGS = [
1455
+ var isDaemonToServerType = makeTypeGuard(DAEMON_TO_SERVER_TYPES);
1456
+ function decodeDaemonToServer(raw) {
1457
+ if (!isRecord(raw) || !isDaemonToServerType(raw.type)) return null;
1458
+ if (raw.type === "daemon_mesh_command") {
1459
+ return {
1460
+ type: "daemon_mesh_command",
1461
+ requestId: typeof raw.requestId === "string" ? raw.requestId : String(raw.requestId ?? ""),
1462
+ targetDaemonId: typeof raw.targetDaemonId === "string" ? raw.targetDaemonId : "",
1463
+ command: raw.command,
1464
+ args: isRecord(raw.args) ? raw.args : {},
1465
+ timestamp: typeof raw.timestamp === "number" ? raw.timestamp : Date.now()
1466
+ };
1467
+ }
1468
+ if (!isRecord(raw.payload)) return null;
1469
+ if (raw.type === "auth" && !isNonEmptyString(raw.payload.token)) return null;
1470
+ return { type: raw.type, payload: raw.payload, ...readEnvelopeFields(raw) };
1471
+ }
1472
+ var SERVER_TO_DAEMON_CONTROL_TYPES = [
1071
1473
  "auth_ok",
1072
1474
  "auth_error",
1073
1475
  "machine_evicted",
@@ -1078,66 +1480,2756 @@ var SERVER_TO_DAEMON_WS_MSGS = [
1078
1480
  "command",
1079
1481
  "agent_command",
1080
1482
  "resolve_action",
1081
- "beacon_vectors_result"
1483
+ "beacon_vectors_result",
1484
+ "daemon_mesh_result",
1485
+ "p2p_ready",
1486
+ "p2p_offer",
1487
+ "p2p_answer",
1488
+ "p2p_ice",
1489
+ "mesh_p2p_ready",
1490
+ "mesh_p2p_offer",
1491
+ "mesh_p2p_answer",
1492
+ "mesh_p2p_ice"
1493
+ ];
1494
+ var isServerToDaemonControlType = makeTypeGuard(SERVER_TO_DAEMON_CONTROL_TYPES);
1495
+ function isServerDirectCommandMsg(msg) {
1496
+ return !isServerToDaemonControlType(msg.type);
1497
+ }
1498
+ var DIRECT_COMMAND_TYPE_PATTERN = /^[a-z][a-z0-9_:.-]{0,63}$/;
1499
+ function isDaemonDirectCommandType(value) {
1500
+ return typeof value === "string" && DIRECT_COMMAND_TYPE_PATTERN.test(value) && !isServerToDaemonControlType(value);
1501
+ }
1502
+ function decodeServerToDaemon(raw) {
1503
+ if (!isRecord(raw) || typeof raw.type !== "string") return null;
1504
+ const relay = {
1505
+ ...readEnvelopeFields(raw),
1506
+ ...isNonEmptyString(raw.source) ? { source: raw.source } : {}
1507
+ };
1508
+ if (raw.type === "beacon_vectors_result" || raw.type === "daemon_mesh_result") {
1509
+ if (!isNonEmptyString(raw.requestId)) return null;
1510
+ const base = { requestId: raw.requestId, success: raw.success === true };
1511
+ if (raw.type === "beacon_vectors_result") {
1512
+ return {
1513
+ type: "beacon_vectors_result",
1514
+ ...base,
1515
+ ...Array.isArray(raw.reports) ? { reports: raw.reports } : {},
1516
+ ...typeof raw.truncated === "number" ? { truncated: raw.truncated } : {},
1517
+ ...typeof raw.error === "string" ? { error: raw.error } : {}
1518
+ };
1519
+ }
1520
+ return {
1521
+ type: "daemon_mesh_result",
1522
+ ...base,
1523
+ ..."result" in raw ? { result: raw.result } : {},
1524
+ ...typeof raw.error === "string" ? { error: raw.error } : {}
1525
+ };
1526
+ }
1527
+ if (!isRecord(raw.payload)) return null;
1528
+ if (isServerToDaemonControlType(raw.type)) {
1529
+ return { type: raw.type, payload: raw.payload, ...relay };
1530
+ }
1531
+ if (!isDaemonDirectCommandType(raw.type)) return null;
1532
+ return { type: raw.type, payload: raw.payload, ...relay };
1533
+ }
1534
+
1535
+ // src/protocol/dashboard-server.ts
1536
+ var SERVER_STATUS_EVENT_NAMES = [
1537
+ "daemon:disconnect",
1538
+ "team:session_viewed",
1539
+ "team:view_request",
1540
+ "team:view_request_approved",
1541
+ "team:view_request_rejected"
1542
+ ];
1543
+ var DASHBOARD_STATUS_EVENT_NAMES = [...DAEMON_STATUS_EVENT_NAMES, ...SERVER_STATUS_EVENT_NAMES];
1544
+ var isDashboardStatusEventName = makeTypeGuard(DASHBOARD_STATUS_EVENT_NAMES);
1545
+ var SYSTEM_ANNOUNCEMENT_TYPES = ["info", "warning", "critical"];
1546
+ var USER_SESSION_TO_DASHBOARD_TYPES = [
1547
+ "connected",
1548
+ "initial_state",
1549
+ "daemon_status",
1550
+ "status_event",
1551
+ "system_announcement",
1552
+ "auth_error",
1553
+ "heartbeat",
1554
+ "p2p_offer",
1555
+ "p2p_ice"
1556
+ ];
1557
+ var isUserSessionToDashboardType = makeTypeGuard(USER_SESSION_TO_DASHBOARD_TYPES);
1558
+ function decodeUserSessionToDashboard(raw) {
1559
+ if (!isRecord(raw) || !isUserSessionToDashboardType(raw.type)) return null;
1560
+ if (raw.type === "heartbeat") {
1561
+ return { type: "heartbeat", payload: isRecord(raw.payload) ? raw.payload : {}, ...readEnvelopeFields(raw) };
1562
+ }
1563
+ if (!isRecord(raw.payload)) return null;
1564
+ return { type: raw.type, payload: raw.payload, ...readEnvelopeFields(raw) };
1565
+ }
1566
+ var DASHBOARD_TO_USER_SESSION_TYPES = ["heartbeat", "refresh", "p2p_ready", "p2p_answer", "p2p_ice"];
1567
+ var isDashboardToUserSessionType = makeTypeGuard(DASHBOARD_TO_USER_SESSION_TYPES);
1568
+ var DASHBOARD_P2P_SIGNAL_TYPES = ["p2p_ready", "p2p_answer", "p2p_ice"];
1569
+ var isDashboardP2PSignalType = makeTypeGuard(DASHBOARD_P2P_SIGNAL_TYPES);
1570
+ function decodeDashboardToUserSession(raw) {
1571
+ if (!isRecord(raw) || !isDashboardToUserSessionType(raw.type)) return null;
1572
+ if (raw.type === "heartbeat") return { type: "heartbeat", ...readEnvelopeFields(raw) };
1573
+ if (raw.type === "refresh") return { type: "refresh" };
1574
+ if (!isRecord(raw.payload) || typeof raw.payload.daemonId !== "string") return null;
1575
+ return { type: raw.type, payload: raw.payload, ...readEnvelopeFields(raw) };
1576
+ }
1577
+ var SHARED_SESSION_TO_VIEWER_TYPES = [
1578
+ "share:connected",
1579
+ "share:revoked",
1580
+ "share:expired",
1581
+ "share:error",
1582
+ "share:viewer_count",
1583
+ "p2p_offer",
1584
+ "p2p_ice"
1585
+ ];
1586
+ var isSharedSessionToViewerType = makeTypeGuard(SHARED_SESSION_TO_VIEWER_TYPES);
1587
+ var VIEWER_TO_SHARED_SESSION_TYPES = ["p2p_ready", "p2p_offer", "p2p_answer", "p2p_ice"];
1588
+ var isViewerToSharedSessionType = makeTypeGuard(VIEWER_TO_SHARED_SESSION_TYPES);
1589
+ function decodeViewerToSharedSession(raw) {
1590
+ if (!isRecord(raw) || !isViewerToSharedSessionType(raw.type)) return null;
1591
+ const payload = isRecord(raw.payload) ? raw.payload : {};
1592
+ return { type: raw.type, payload, ...readEnvelopeFields(raw) };
1593
+ }
1594
+
1595
+ // src/protocol/dashboard-daemon-p2p.ts
1596
+ function isChunkType(value) {
1597
+ return typeof value === "string" && value.endsWith("_chunk") && value.length > "_chunk".length;
1598
+ }
1599
+ function readChunkFields(frame) {
1600
+ if (!isNonEmptyString(frame.chunkId)) return null;
1601
+ if (!Number.isInteger(frame.index) || !Number.isInteger(frame.total)) return null;
1602
+ if (typeof frame.data !== "string") return null;
1603
+ return {
1604
+ ...isNonEmptyString(frame.id) ? { id: frame.id } : {},
1605
+ chunkId: frame.chunkId,
1606
+ index: frame.index,
1607
+ total: frame.total,
1608
+ data: frame.data
1609
+ };
1610
+ }
1611
+ var DASHBOARD_TO_DAEMON_P2P_TYPES = [
1612
+ "ping",
1613
+ "pong",
1614
+ "command",
1615
+ "input",
1616
+ "pty_input",
1617
+ "pty_resize",
1618
+ "screenshot_start",
1619
+ "screenshot_stop",
1620
+ "subscribe",
1621
+ "unsubscribe",
1622
+ "seqscribe_session_interest",
1623
+ "read",
1624
+ "write",
1625
+ "list"
1626
+ ];
1627
+ var isDashboardToDaemonP2PType = makeTypeGuard(DASHBOARD_TO_DAEMON_P2P_TYPES);
1628
+ function isDashboardToDaemonChunkType(value) {
1629
+ return isChunkType(value) && isDashboardToDaemonP2PType(value.slice(0, -"_chunk".length));
1630
+ }
1631
+ var DASHBOARD_REQUEST_TYPES = /* @__PURE__ */ new Set(["command", "input", "read", "write", "list"]);
1632
+ function decodeDashboardToDaemonP2PChunk(raw) {
1633
+ if (!isRecord(raw) || !isDashboardToDaemonChunkType(raw.type)) return null;
1634
+ const fields = readChunkFields(raw);
1635
+ return fields ? { type: raw.type, ...fields } : null;
1636
+ }
1637
+ function decodeDashboardToDaemonP2P(raw) {
1638
+ if (!isRecord(raw) || !isDashboardToDaemonP2PType(raw.type)) return null;
1639
+ if (DASHBOARD_REQUEST_TYPES.has(raw.type) && !isNonEmptyString(raw.id)) return null;
1640
+ return raw;
1641
+ }
1642
+ var DAEMON_TO_DASHBOARD_P2P_TYPES = [
1643
+ "ping",
1644
+ "pong",
1645
+ "p2p_evicted",
1646
+ "status_event",
1647
+ "topic_update",
1648
+ "topic_update_chunk",
1649
+ "session_output",
1650
+ "session_output_chunk",
1651
+ "session_io_error",
1652
+ "command_result",
1653
+ "command_result_chunk",
1654
+ "response",
1655
+ "transcript_topics_available"
1656
+ ];
1657
+ var isDaemonToDashboardP2PType = makeTypeGuard(DAEMON_TO_DASHBOARD_P2P_TYPES);
1658
+ function decodeDaemonToDashboardP2P(raw) {
1659
+ if (!isRecord(raw)) return null;
1660
+ if (!isDaemonToDashboardP2PType(raw.type)) return null;
1661
+ switch (raw.type) {
1662
+ case "ping":
1663
+ case "pong":
1664
+ case "p2p_evicted":
1665
+ return raw;
1666
+ case "status_event":
1667
+ return isRecord(raw.payload) ? raw : null;
1668
+ case "topic_update":
1669
+ return isRecord(raw.update) ? raw : null;
1670
+ case "topic_update_chunk":
1671
+ case "command_result_chunk":
1672
+ case "session_output_chunk": {
1673
+ const fields = readChunkFields(raw);
1674
+ if (!fields) return null;
1675
+ if (raw.type === "session_output_chunk") {
1676
+ return isNonEmptyString(raw.sessionId) ? { type: raw.type, sessionId: raw.sessionId, ...fields } : null;
1677
+ }
1678
+ return { type: raw.type, ...fields };
1679
+ }
1680
+ case "session_output":
1681
+ return isNonEmptyString(raw.sessionId) && typeof raw.data === "string" ? raw : null;
1682
+ case "session_io_error":
1683
+ return isNonEmptyString(raw.sessionId) ? raw : null;
1684
+ case "command_result":
1685
+ case "response":
1686
+ return isNonEmptyString(raw.id) ? raw : null;
1687
+ case "transcript_topics_available":
1688
+ return Array.isArray(raw.topics) && raw.topics.every((topic) => typeof topic === "string") ? { type: raw.type, topics: raw.topics } : null;
1689
+ }
1690
+ }
1691
+ var DASHBOARD_P2P_MESSAGE_KINDS = [
1692
+ .../* @__PURE__ */ new Set([...DASHBOARD_TO_DAEMON_P2P_TYPES, ...DAEMON_TO_DASHBOARD_P2P_TYPES])
1082
1693
  ];
1083
- function isDaemonToServerWsMsg(value) {
1084
- return typeof value === "string" && DAEMON_TO_SERVER_WS_MSGS.includes(value);
1694
+
1695
+ // src/protocol/dashboard-wire-version.ts
1696
+ var DASHBOARD_WIRE_VERSION = 2;
1697
+ function compareDashboardWireVersion(pageVersion, daemonVersion) {
1698
+ const daemon = typeof daemonVersion === "number" && Number.isFinite(daemonVersion) ? daemonVersion : 1;
1699
+ if (daemon === pageVersion) return "ok";
1700
+ return daemon > pageVersion ? "reload_required" : "daemon_update_required";
1085
1701
  }
1086
- function isServerToDaemonWsMsg(value) {
1087
- return typeof value === "string" && SERVER_TO_DAEMON_WS_MSGS.includes(value);
1702
+
1703
+ // src/ws-protocol.ts
1704
+ var DAEMON_TO_SERVER_WS_MSGS = DAEMON_TO_SERVER_TYPES;
1705
+ var SERVER_TO_DAEMON_WS_MSGS = SERVER_TO_DAEMON_CONTROL_TYPES;
1706
+ function normalizeAuthOkLimits(raw) {
1707
+ if (!raw || typeof raw !== "object") return null;
1708
+ const src = raw;
1709
+ const num = (value, fallback) => typeof value === "number" && Number.isFinite(value) ? value : fallback;
1710
+ return {
1711
+ maxP2Pconnections: num(
1712
+ src.maxP2Pconnections !== void 0 ? src.maxP2Pconnections : src.maxP2PConnections,
1713
+ -1
1714
+ ),
1715
+ screenshotIntervalSeconds: num(src.screenshotIntervalSeconds, 0),
1716
+ dailyScreenshotMinutes: num(src.dailyScreenshotMinutes, -1),
1717
+ maxMachines: num(src.maxMachines, -1)
1718
+ };
1088
1719
  }
1089
1720
 
1090
1721
  // src/interactive-prompt-constants.ts
1091
1722
  var CLAUDE_TUI_REVIEW_PAGE_NOT_FOCUSED_PREFIX = "Claude TUI review page is not focused";
1092
1723
  var CLAUDE_TUI_REVIEW_UNCONFIRMED_PREFIX = "Claude TUI answer delivered but not confirmed";
1724
+
1725
+ // src/session-status.ts
1726
+ var SESSION_STATUSES = [
1727
+ "idle",
1728
+ "generating",
1729
+ "waiting_approval",
1730
+ "waiting_choice",
1731
+ "finalizing",
1732
+ "error",
1733
+ "stopped",
1734
+ "starting",
1735
+ "panel_hidden",
1736
+ "not_monitored",
1737
+ "disconnected"
1738
+ ];
1739
+ var RECENT_SESSION_BUCKETS = ["needs_attention", "working", "task_complete", "idle"];
1740
+ var SESSION_STATUS_CLASS = {
1741
+ generating: "working",
1742
+ finalizing: "working",
1743
+ starting: "working",
1744
+ waiting_approval: "blocked",
1745
+ waiting_choice: "blocked",
1746
+ idle: "ready",
1747
+ panel_hidden: "ready",
1748
+ not_monitored: "ready",
1749
+ error: "dead",
1750
+ stopped: "dead",
1751
+ disconnected: "dead"
1752
+ };
1753
+ var SESSION_STATUS_ALIASES = {
1754
+ running: "generating",
1755
+ streaming: "generating",
1756
+ busy: "generating",
1757
+ working: "generating",
1758
+ loading: "generating",
1759
+ loading_reference: "generating",
1760
+ thinking: "generating",
1761
+ active: "generating",
1762
+ // Status-lane refinements of a turn that is still owned by the agent.
1763
+ no_progress: "generating",
1764
+ long_generating: "generating",
1765
+ initializing: "starting",
1766
+ waiting: "waiting_approval"
1767
+ };
1768
+ var SESSION_STATUS_SET = new Set(SESSION_STATUSES);
1769
+ function isSessionStatus(value) {
1770
+ return typeof value === "string" && SESSION_STATUS_SET.has(value);
1771
+ }
1772
+ function normalizeSessionStatus(raw) {
1773
+ if (typeof raw !== "string") return null;
1774
+ const value = raw.trim().toLowerCase();
1775
+ if (SESSION_STATUS_SET.has(value)) return value;
1776
+ return SESSION_STATUS_ALIASES[value] ?? null;
1777
+ }
1778
+ function classifySessionStatus(raw) {
1779
+ const status = normalizeSessionStatus(raw);
1780
+ return status ? SESSION_STATUS_CLASS[status] : "unknown";
1781
+ }
1782
+ function isWorkingStatus(raw) {
1783
+ return classifySessionStatus(raw) === "working";
1784
+ }
1785
+ function isBlockedStatus(raw) {
1786
+ return classifySessionStatus(raw) === "blocked";
1787
+ }
1788
+ function isReadyStatus(raw) {
1789
+ return classifySessionStatus(raw) === "ready";
1790
+ }
1791
+ function isDeadStatus(raw) {
1792
+ return classifySessionStatus(raw) === "dead";
1793
+ }
1794
+ function isBusyStatus(raw) {
1795
+ const cls = classifySessionStatus(raw);
1796
+ return cls === "working" || cls === "blocked";
1797
+ }
1798
+ function statusesOfClass(cls) {
1799
+ return SESSION_STATUSES.filter((status) => SESSION_STATUS_CLASS[status] === cls);
1800
+ }
1801
+ var TERMINAL_SESSION_RECORD_STATUSES = ["stopped", "failed", "terminated", "exited", "closed"];
1802
+ function isTerminalSessionRecordStatus(raw) {
1803
+ return typeof raw === "string" && TERMINAL_SESSION_RECORD_STATUSES.includes(raw.trim().toLowerCase());
1804
+ }
1805
+ function isIdleSessionState(state) {
1806
+ const record = state && typeof state === "object" ? state : {};
1807
+ const status = typeof record.status === "string" ? record.status.trim().toLowerCase() : "";
1808
+ if (isTerminalSessionRecordStatus(status) || isDeadStatus(status)) return false;
1809
+ return isReadyStatus(status) || record.activeChat?.status === "waiting_input";
1810
+ }
1811
+
1812
+ // src/mesh-vocabulary.ts
1813
+ var MESH_TASK_STATUSES = ["pending", "assigned", "completed", "failed", "cancelled"];
1814
+ var MESH_TERMINAL_TASK_STATUSES = ["completed", "failed", "cancelled"];
1815
+ var MESH_TASK_MODES = ["code_change", "validation", "live_debug_readonly", "launch_app", "convergence"];
1816
+ var MESH_TASK_PRIORITIES = ["low", "normal", "high"];
1817
+ var MESH_THINKING_LEVELS = ["low", "medium", "high"];
1818
+ var MESH_DELIVERY_MODES = ["when_idle", "interrupt"];
1819
+ var MESH_SESSION_CLEANUP_MODES = ["preserve", "stop", "delete_stopped", "stop_and_delete"];
1820
+ var WORKER_REPORT_OUTCOMES = ["completed", "blocked", "failed"];
1821
+ var WORKER_BRANCH_STATES = [
1822
+ "merged_to_main",
1823
+ "pushed_feature_branch_needs_merge",
1824
+ "blocked_review",
1825
+ "cleanup_candidate",
1826
+ "not_mergeable"
1827
+ ];
1828
+ function makeGuard(values) {
1829
+ const set = new Set(values);
1830
+ return (value) => typeof value === "string" && set.has(value);
1831
+ }
1832
+ var isMeshTaskStatus = makeGuard(MESH_TASK_STATUSES);
1833
+ var isMeshTerminalTaskStatus = makeGuard(MESH_TERMINAL_TASK_STATUSES);
1834
+ var isMeshTaskMode = makeGuard(MESH_TASK_MODES);
1835
+ var isMeshTaskPriority = makeGuard(MESH_TASK_PRIORITIES);
1836
+ var isMeshDeliveryMode = makeGuard(MESH_DELIVERY_MODES);
1837
+ var isWorkerReportOutcome = makeGuard(WORKER_REPORT_OUTCOMES);
1838
+ function enumOf(values, description) {
1839
+ return {
1840
+ type: "string",
1841
+ enum: [...values],
1842
+ ...description ? { description } : {}
1843
+ };
1844
+ }
1845
+
1846
+ // src/outbound-message.ts
1847
+ var outboundMessageIdCounter = 0;
1848
+ function mintMessageId(now = Date.now()) {
1849
+ try {
1850
+ const cryptoRef = typeof globalThis !== "undefined" ? globalThis.crypto : void 0;
1851
+ if (typeof cryptoRef?.randomUUID === "function") return `msg_${cryptoRef.randomUUID()}`;
1852
+ } catch {
1853
+ }
1854
+ outboundMessageIdCounter += 1;
1855
+ return `msg_${now}_${outboundMessageIdCounter}`;
1856
+ }
1857
+ var MESSAGE_ID_PREFIX = "msg_";
1858
+ function isMessageId(value) {
1859
+ return typeof value === "string" && value.length > MESSAGE_ID_PREFIX.length && value.startsWith(MESSAGE_ID_PREFIX);
1860
+ }
1861
+ var OUTBOUND_MESSAGE_ORIGINS = ["dashboard", "mcp", "mesh", "api", "cli"];
1862
+ function isOutboundMessageOrigin(value) {
1863
+ return typeof value === "string" && OUTBOUND_MESSAGE_ORIGINS.includes(value);
1864
+ }
1865
+ var SEND_POLICY_MODES = ["queue", "send_now", "interrupt"];
1866
+ function isSendPolicyMode(value) {
1867
+ return typeof value === "string" && SEND_POLICY_MODES.includes(value);
1868
+ }
1869
+ function isSendPolicy(value) {
1870
+ return !!value && typeof value === "object" && isSendPolicyMode(value.mode);
1871
+ }
1872
+ var SEND_REFUSAL_REASONS = [
1873
+ "not_ready",
1874
+ "send_in_flight",
1875
+ "not_generating",
1876
+ "not_supported",
1877
+ "platform_unsupported",
1878
+ "modal_parked",
1879
+ "interrupt_not_implemented",
1880
+ "interrupt_refused",
1881
+ "idle_timeout",
1882
+ "session_exited",
1883
+ "unsupported_input",
1884
+ "no_target",
1885
+ "bootstrap_pending",
1886
+ "duplicate_dispatch",
1887
+ "internal_error"
1888
+ ];
1889
+ function isSendRefusal(value) {
1890
+ return typeof value === "string" && SEND_REFUSAL_REASONS.includes(value);
1891
+ }
1892
+ var SUBMIT_OUTCOME_KINDS = ["delivered", "queued", "duplicate", "refused"];
1893
+ function isSubmitOutcome(value) {
1894
+ if (!value || typeof value !== "object") return false;
1895
+ const kind = value.kind;
1896
+ if (typeof kind !== "string" || !SUBMIT_OUTCOME_KINDS.includes(kind)) return false;
1897
+ if (kind === "queued") return typeof value.position === "number";
1898
+ if (kind === "duplicate") return typeof value.of === "string";
1899
+ if (kind === "refused") return isSendRefusal(value.reason);
1900
+ return true;
1901
+ }
1902
+ function isInputPartWire(value) {
1903
+ if (!value || typeof value !== "object") return false;
1904
+ const type = value.type;
1905
+ return type === "text" || type === "image" || type === "audio" || type === "video" || type === "resource" || type === "resource_link";
1906
+ }
1907
+ function isInputEnvelopeWire(value) {
1908
+ if (!value || typeof value !== "object") return false;
1909
+ const parts = value.parts;
1910
+ const textFallback = value.textFallback;
1911
+ return Array.isArray(parts) && parts.every(isInputPartWire) && typeof textFallback === "string";
1912
+ }
1913
+ function isOutboundMessage(value) {
1914
+ if (!value || typeof value !== "object") return false;
1915
+ const candidate = value;
1916
+ return isMessageId(candidate.messageId) && typeof candidate.sessionId === "string" && candidate.sessionId.length > 0 && isInputEnvelopeWire(candidate.input) && isOutboundMessageOrigin(candidate.origin) && isSendPolicy(candidate.policy) && typeof candidate.createdAt === "number";
1917
+ }
1918
+
1919
+ // src/mission-brief.ts
1920
+ var GOAL_MAX = 500;
1921
+ var LIST_ITEM_MAX = 200;
1922
+ var LIST_MAX_ITEMS = 12;
1923
+ var MISSION_BRIEF_RENDER_MAX_CHARS = 1200;
1924
+ function truncateString(value, max) {
1925
+ if (value.length <= max) return value;
1926
+ return `${value.slice(0, max - 1).trimEnd()}\u2026`;
1927
+ }
1928
+ function normalizeStringList(value, field, truncated) {
1929
+ if (value === void 0 || value === null) return void 0;
1930
+ if (!Array.isArray(value)) return void 0;
1931
+ const items = [];
1932
+ let itemTruncated = false;
1933
+ for (const raw of value) {
1934
+ if (typeof raw !== "string") continue;
1935
+ const trimmed = raw.trim();
1936
+ if (!trimmed) continue;
1937
+ if (trimmed.length > LIST_ITEM_MAX) itemTruncated = true;
1938
+ items.push(truncateString(trimmed, LIST_ITEM_MAX));
1939
+ }
1940
+ if (itemTruncated) truncated.push({ field, reason: "item_too_long" });
1941
+ if (items.length > LIST_MAX_ITEMS) {
1942
+ truncated.push({ field, reason: "list_too_long" });
1943
+ return items.slice(0, LIST_MAX_ITEMS);
1944
+ }
1945
+ return items.length > 0 ? items : void 0;
1946
+ }
1947
+ function normalizeMissionBrief(input) {
1948
+ const truncated = [];
1949
+ if (!input || typeof input !== "object") {
1950
+ return { brief: null, truncated };
1951
+ }
1952
+ const raw = input;
1953
+ const rawGoal = typeof raw.goal === "string" ? raw.goal.trim() : "";
1954
+ if (!rawGoal) {
1955
+ return { brief: null, truncated };
1956
+ }
1957
+ if (rawGoal.length > GOAL_MAX) truncated.push({ field: "goal", reason: "field_too_long" });
1958
+ const goal = truncateString(rawGoal, GOAL_MAX);
1959
+ const constraints = normalizeStringList(raw.constraints, "constraints", truncated);
1960
+ const doneCriteria = normalizeStringList(raw.doneCriteria ?? raw.done_criteria, "doneCriteria", truncated);
1961
+ const handoffNotes = normalizeStringList(raw.handoffNotes ?? raw.handoff_notes, "handoffNotes", truncated);
1962
+ const ownedPaths = normalizeStringList(raw.ownedPaths ?? raw.owned_paths, "ownedPaths", truncated);
1963
+ const brief = { goal };
1964
+ if (constraints) brief.constraints = constraints;
1965
+ if (doneCriteria) brief.doneCriteria = doneCriteria;
1966
+ if (handoffNotes) brief.handoffNotes = handoffNotes;
1967
+ if (ownedPaths) brief.ownedPaths = ownedPaths;
1968
+ return { brief, truncated };
1969
+ }
1970
+ function renderList(heading, items) {
1971
+ if (!items || items.length === 0) return [];
1972
+ return [`${heading}:`, ...items.map((item) => `- ${item}`)];
1973
+ }
1974
+ function renderMissionBriefBlock(brief) {
1975
+ const sections = [`Mission goal: ${brief.goal}`];
1976
+ sections.push(...renderList("Constraints", brief.constraints));
1977
+ sections.push(...renderList("Done when", brief.doneCriteria));
1978
+ sections.push(...renderList("Owned paths", brief.ownedPaths));
1979
+ sections.push(...renderList("Handoff notes", brief.handoffNotes));
1980
+ const full = sections.join("\n");
1981
+ if (full.length <= MISSION_BRIEF_RENDER_MAX_CHARS) return full;
1982
+ const marker = "\n(brief truncated)";
1983
+ const budget = MISSION_BRIEF_RENDER_MAX_CHARS - marker.length;
1984
+ const lines = full.split("\n");
1985
+ let acc = "";
1986
+ for (const line of lines) {
1987
+ const next = acc ? `${acc}
1988
+ ${line}` : line;
1989
+ if (next.length > budget) break;
1990
+ acc = next;
1991
+ }
1992
+ if (!acc) acc = truncateString(lines[0] ?? "", Math.max(budget, 0));
1993
+ return `${acc}${marker}`;
1994
+ }
1995
+
1996
+ // src/worker-protocol.ts
1997
+ var WORKER_TOOLS = [
1998
+ "report_completion",
1999
+ "progress_update",
2000
+ "peer_context_pull",
2001
+ "git_status",
2002
+ "git_log",
2003
+ "git_diff"
2004
+ ];
2005
+ var WORKER_TOOL_SET = new Set(WORKER_TOOLS);
2006
+ function isWorkerTool(value) {
2007
+ return typeof value === "string" && WORKER_TOOL_SET.has(value);
2008
+ }
2009
+ var WORKER_PROTOCOL_FOOTER_MARKER = "--- adhdev worker protocol ---";
2010
+ function hasWorkerProtocolFooter(body) {
2011
+ return typeof body === "string" && body.includes(WORKER_PROTOCOL_FOOTER_MARKER);
2012
+ }
2013
+ function renderWorkerProtocolFooter(input = {}) {
2014
+ const briefBlock = input.missionBrief ? renderMissionBriefBlock(input.missionBrief) : null;
2015
+ const lines = briefBlock ? [briefBlock, "", WORKER_PROTOCOL_FOOTER_MARKER] : [WORKER_PROTOCOL_FOOTER_MARKER];
2016
+ const scope = [];
2017
+ if (input.taskId) scope.push(`task ${input.taskId}`);
2018
+ if (input.taskMode) scope.push(`mode ${input.taskMode}`);
2019
+ if (input.difficulty) {
2020
+ if (isMeshTaskDifficulty(input.difficulty)) {
2021
+ scope.push(`difficulty ${input.difficulty}`);
2022
+ } else {
2023
+ console.warn(
2024
+ `[worker-protocol] task ${input.taskId ?? "(unknown)"}: dropping invalid difficulty '${input.difficulty}' from the worker footer (expected one of easy, medium, difficult, freeform)`
2025
+ );
2026
+ }
2027
+ }
2028
+ if (input.readonly) scope.push("read-only");
2029
+ if (scope.length) lines.push(`You are a delegated worker (${scope.join(", ")}).`);
2030
+ else lines.push("You are a delegated worker.");
2031
+ lines.push(
2032
+ "When your work is finished, blocked, or has failed, call `report_completion` exactly once. Its `summary` is recorded verbatim as the authoritative record of this task \u2014 your terminal is not scraped for it \u2014 so state what you did, what you found, and where you left the branch.",
2033
+ "For work that runs longer than a few minutes, call `progress_update` at natural checkpoints so the coordinator can see you are alive without polling.",
2034
+ "`peer_context_pull` shows what sibling tasks in this mission have reported; `git_status` / `git_diff` / `git_log` inspect your own workspace \u2014 all three REQUIRE the absolute path to it as `workspace`.",
2035
+ "You have no coordinator tools (no `mesh_*`) by design: do not enqueue, dispatch, or restart anything. If you need a decision from the coordinator, finish with `report_completion` and outcome `blocked`, listing what you need in `blockers`.",
2036
+ "On a code-changing task, `report_completion` with outcome `completed` requires `touched_files` \u2014 send `[]` if you changed nothing, omitting the field is what gets refused. `blocked`/`failed` never need it, and a read-only task should omit it or send `[]`.",
2037
+ "If `report_completion` is refused, the response carries `validationErrors` (or a `hint`) naming exactly what to fix \u2014 correct that field and call it again; a refusal records nothing."
2038
+ );
2039
+ if (input.enclosedHandoffNotes && input.enclosedHandoffNotes > 0) {
2040
+ lines.push(
2041
+ `The ${input.enclosedHandoffNotes} handoff note(s) above were written by agents who touched this code before you; honour their conflict guidance and add your own in \`handoff_notes\` when you report.`
2042
+ );
2043
+ }
2044
+ return lines.join("\n");
2045
+ }
2046
+ function stripWorkerProtocolFooter(body) {
2047
+ if (typeof body !== "string") return body;
2048
+ const at = body.indexOf(WORKER_PROTOCOL_FOOTER_MARKER);
2049
+ if (at < 0) return body;
2050
+ return body.slice(0, at).replace(/\s+$/, "");
2051
+ }
2052
+ function appendWorkerProtocolFooter(body, input = {}) {
2053
+ if (hasWorkerProtocolFooter(body)) return body;
2054
+ const trimmed = body.replace(/\s+$/, "");
2055
+ return `${trimmed}
2056
+
2057
+ ${renderWorkerProtocolFooter(input)}`;
2058
+ }
2059
+ function renderCoordinatorWorkerSection() {
2060
+ return [
2061
+ "## Workers",
2062
+ "",
2063
+ `Every task you dispatch is delivered with a worker protocol footer. Workers hold exactly these tools: ${WORKER_TOOLS.map((tool) => `\`${tool}\``).join(", ")} \u2014 and no \`mesh_*\` tools.`,
2064
+ "- A worker finishes by calling `report_completion`; its structured report (outcome, summary, touched files, branch state, handoff notes) is what reaches you as the completion event. Read that report \u2014 do not re-derive the outcome from `mesh_read_chat` or the terminal unless the report is missing.",
2065
+ "- `progress_update` from a worker arrives as a lightweight progress note. Do NOT poll `mesh_status`, `mesh_view_queue` or `mesh_read_chat` to check on a running worker; completion, progress, blocked and failure all arrive as events.",
2066
+ "- To reach a busy worker mid-task use `mesh_notify_worker`: the memo is delivered on the worker's next tool call (or when it becomes idle). A worker that reports `blocked` is asking you for a decision \u2014 answer it with `mesh_send_task` to the same session.",
2067
+ "- `mesh_status` is for node health and capacity before delegating, never for progress.",
2068
+ "- A `code_change` task's declared `owned_paths` (H1) is enforced at claim time: a second `code_change` task whose `owned_paths` overlaps an already-claimed task's is refused rather than silently racing it. A worker's `report_completion.touched_files` is compared against its own task's declaration afterward and any mismatch is surfaced back to you as evidence \u2014 it is never a validation failure, since a worker often cannot know its exact final file list at enqueue time."
2069
+ ].join("\n");
2070
+ }
2071
+
2072
+ // src/turn-evidence.ts
2073
+ var MESH_TOPIC_PROTOCOL_VERSION = 2;
2074
+ var EVIDENCE_SOURCE_IDS = [
2075
+ "fsm_edge",
2076
+ "short_gen_inline",
2077
+ "completion_flush_genuine",
2078
+ "completion_flush_weak",
2079
+ "monitor_final_summary",
2080
+ "pre_cleanup_transcript",
2081
+ "stall_transcript",
2082
+ "startup_grace_collapse",
2083
+ "acp_prompt_response",
2084
+ "cdp_state",
2085
+ "approval_gate",
2086
+ "modal_button",
2087
+ "mesh_stall_watchdog",
2088
+ "status_monitor",
2089
+ "pty_exit",
2090
+ "provider_error",
2091
+ "coordinator_probe",
2092
+ "mcp_probe",
2093
+ "worker_tool",
2094
+ "dispatch",
2095
+ "input_service",
2096
+ "operator",
2097
+ "intentional_cleanup",
2098
+ "scheduler",
2099
+ "git_probe",
2100
+ "session_registry"
2101
+ ];
2102
+ var TURN_SCOPES = ["mesh_queue", "mesh_direct", "plain"];
2103
+ var RECLAIMING_SEND_REFUSALS = ["session_exited", "no_target", "unsupported_input"];
2104
+ var DELIVERY_OUTCOMES = ["delivered", "queued"];
2105
+ var DELIVERY_VIAS = ["local", "p2p"];
2106
+ var DISPATCH_FAILURE_REASONS = ["worker_absent", "transport_error", "spawn_failed", "rejected_by_worker", "timeout"];
2107
+ function sanitizeRefusalCode(value) {
2108
+ if (typeof value !== "string") return void 0;
2109
+ const normalized = value.trim().toLowerCase().replace(/[^a-z_]/g, "_").replace(/_+/g, "_").replace(/^_+|_+$/g, "");
2110
+ if (!normalized) return void 0;
2111
+ return normalized.slice(0, 64);
2112
+ }
2113
+ var CONSUME_PROFILES = ["default", "native_source"];
2114
+ var SESSION_REBOUND_REASONS = ["restart", "live_holder"];
2115
+ var SUSPENSION_MODALS = ["approval", "choice"];
2116
+ var SUSPENSION_RESOLUTIONS = ["approved", "rejected", "answered"];
2117
+ var SUSPENSION_RESOLUTION_VIAS = ["modal_button", "auto_approve", "prompt_answer"];
2118
+ var TURN_END_STRENGTHS = ["genuine", "weak"];
2119
+ var TURN_END_BLOCK_REASONS = [
2120
+ "missing_final_assistant",
2121
+ "finalization_timeout",
2122
+ "terminal_block_hard_cap",
2123
+ "decoupled_completion"
2124
+ ];
2125
+ var NATIVE_TURN_OUTCOMES = ["completed", "aborted"];
2126
+ var LIVENESS_RESULTS = ["alive", "unknown", "read_failed", "dead"];
2127
+ var PROVIDER_FAILURES = ["auth_failed", "billing_failed"];
2128
+ var SESSION_ERROR_REASONS = ["provider_error", "adapter_error", "spawn_failed", "auth_failed", "billing_failed", "unknown", "daemon_restart"];
2129
+ var CANCEL_REASONS = ["operator_cancel", "intentional_cleanup", "task_removed", "mission_abandoned", "superseded"];
2130
+ var OPERATOR_STATUSES = ["completed", "failed"];
2131
+ var OPERATOR_STATUS_REASONS = ["operator_update", "refine_terminal", "validation_terminal"];
2132
+ var COORDINATOR_ACK_OUTCOMES = ["delivered", "queued", "duplicate"];
2133
+ var NO_PROGRESS_OBSERVED_STATUSES = [...SESSION_STATUSES, "unknown"];
2134
+ var HOLD_REASONS = [
2135
+ "await_delivery",
2136
+ "await_consume",
2137
+ "await_turn",
2138
+ "liveness",
2139
+ "hard_ceiling",
2140
+ "live_pending",
2141
+ "transcript_quiet",
2142
+ "weak_candidate",
2143
+ "suspension_before_consumed",
2144
+ // A genuine FSM end of a mesh turn whose worker holds a live worker-MCP bind:
2145
+ // the structured report is the primary evidence (design §F2), so the idle edge
2146
+ // only opens this hold (R9r) — a report commits (R17), a new busy edge cancels
2147
+ // it as a false idle (R12r), expiry commits weak (R13r).
2148
+ "await_report",
2149
+ // A worker report recorded while the session is still generating (R17g):
2150
+ // the report is the verdict, the idle edge is only awaited as corroboration
2151
+ // — a turn_end commits the report (R9t), expiry commits it anyway (R13t) so
2152
+ // a session whose FSM never shows the idle edge again does not wait for
2153
+ // liveness / hard_ceiling.
2154
+ "await_end"
2155
+ ];
2156
+ var TURN_OUTCOMES = ["completed", "failed", "cancelled"];
2157
+ var COMMIT_STRENGTHS = ["genuine", "weak", "tool_report", "operator"];
2158
+ var TURN_REASONS = [
2159
+ // commits
2160
+ "turn_end",
2161
+ "weak_end_confirmed",
2162
+ "transcript_final",
2163
+ "worker_reported",
2164
+ "finalization_timeout_no_response",
2165
+ "session_error",
2166
+ "provider_auth_failed",
2167
+ "provider_billing_failed",
2168
+ "operator_cancel",
2169
+ "intentional_cleanup",
2170
+ "task_removed",
2171
+ "mission_abandoned",
2172
+ "superseded",
2173
+ "operator_update",
2174
+ "refine_terminal",
2175
+ "validation_terminal",
2176
+ "hard_ceiling",
2177
+ "reclaim_budget_exhausted",
2178
+ "hollow_max_retries",
2179
+ "migration_orphan",
2180
+ // reclaims (generation + 1)
2181
+ "dispatch_refused_session_exited",
2182
+ "dispatch_refused_no_target",
2183
+ "dispatch_refused_unsupported_input",
2184
+ "dispatch_failed",
2185
+ "session_exit",
2186
+ "session_exit_before_turn",
2187
+ "session_dead",
2188
+ "hollow_completion",
2189
+ "assigned_stranded_dispatch_unconfirmed",
2190
+ "delivered_not_consumed_redrive",
2191
+ "delivered_no_turn_deadline"
2192
+ ];
2193
+ var NOTIFY_KINDS = [
2194
+ "completed",
2195
+ "failed",
2196
+ "cancelled",
2197
+ "stopped",
2198
+ "approval",
2199
+ "choice",
2200
+ "approval_resolved",
2201
+ "candidate",
2202
+ "no_progress",
2203
+ "progress",
2204
+ "late_completion",
2205
+ "mesh_event"
2206
+ ];
2207
+ var id = { t: "id" };
2208
+ var idOpt = { t: "id", optional: true };
2209
+ var bool = { t: "bool" };
2210
+ var boolOpt = { t: "bool", optional: true };
2211
+ var ms = { t: "ms" };
2212
+ var msOpt = { t: "ms", optional: true };
2213
+ var intOpt = { t: "int", optional: true };
2214
+ var en = (values) => ({ t: "enum", values });
2215
+ var enOpt = (values) => ({ t: "enum", values, optional: true });
2216
+ var EVIDENCE_ENVELOPE_FIELD_SPECS = {
2217
+ eventId: id,
2218
+ at: ms,
2219
+ source: en(EVIDENCE_SOURCE_IDS),
2220
+ sessionId: id,
2221
+ attemptRef: { t: "attempt_ref", optional: true },
2222
+ taskId: idOpt,
2223
+ observedBy: id
2224
+ };
2225
+ var TURN_EVIDENCE_FIELD_SPECS = {
2226
+ dispatch_accepted: {
2227
+ scope: en(TURN_SCOPES),
2228
+ messageId: id,
2229
+ meshId: idOpt,
2230
+ nodeId: idOpt,
2231
+ providerType: idOpt,
2232
+ attemptNo: intOpt,
2233
+ dispatchNonce: intOpt,
2234
+ consumeProfile: enOpt(CONSUME_PROFILES),
2235
+ maxTaskRetries: intOpt,
2236
+ coordinator: { t: "coordinator", optional: true }
2237
+ },
2238
+ delivered: { messageId: id, outcome: en(DELIVERY_OUTCOMES), via: en(DELIVERY_VIAS) },
2239
+ delivery_refused: { messageId: id, reason: en(SEND_REFUSAL_REASONS) },
2240
+ dispatch_failed: { workerAbsent: bool, reason: en(DISPATCH_FAILURE_REASONS), refusalCode: idOpt },
2241
+ duplicate_dispatch_refusal: { holderSessionId: id, holderAttemptId: idOpt },
2242
+ session_rebound: { toSessionId: id, reason: en(SESSION_REBOUND_REASONS) },
2243
+ turn_started: { retro: bool },
2244
+ suspension: { modal: en(SUSPENSION_MODALS), modalKey: idOpt },
2245
+ suspension_resolved: { resolution: en(SUSPENSION_RESOLUTIONS), via: en(SUSPENSION_RESOLUTION_VIAS) },
2246
+ turn_end: {
2247
+ strength: en(TURN_END_STRENGTHS),
2248
+ afterFinalizationTimeout: boolOpt,
2249
+ hollow: boolOpt,
2250
+ summary: { t: "summary_ref", optional: true },
2251
+ blockReason: enOpt(TURN_END_BLOCK_REASONS),
2252
+ releasedByHardCap: boolOpt,
2253
+ nativeOutcome: enOpt(NATIVE_TURN_OUTCOMES),
2254
+ live: { t: "live", optional: true },
2255
+ reportExpected: boolOpt
2256
+ },
2257
+ transcript_final: {
2258
+ selfAttributing: bool,
2259
+ nativeRead: bool,
2260
+ nativeMarker: { t: "native_marker", optional: true },
2261
+ live: { t: "live" },
2262
+ summary: { t: "summary_ref", optional: true },
2263
+ messageAt: msOpt
2264
+ },
2265
+ transcript_activity: { newestActivityAt: ms },
2266
+ no_progress: { stalledMs: ms, observedStatus: en(NO_PROGRESS_OBSERVED_STATUSES), finalAssistantPresent: bool },
2267
+ liveness: { result: en(LIVENESS_RESULTS) },
2268
+ process_exit: { exitCode: { t: "int", nullable: true }, providerFailure: enOpt(PROVIDER_FAILURES) },
2269
+ session_error: { reason: en(SESSION_ERROR_REASONS) },
2270
+ worker_report: {
2271
+ outcome: en(WORKER_REPORT_OUTCOMES),
2272
+ summary: { t: "summary_ref", optional: true },
2273
+ hasHandoffNotes: bool,
2274
+ branchState: enOpt(WORKER_BRANCH_STATES),
2275
+ touchedFileCount: intOpt
2276
+ },
2277
+ worker_progress: { note: { t: "summary_ref", optional: true } },
2278
+ git_side_effect: { dirty: bool, commitsSinceDispatch: { t: "int" }, attributable: bool },
2279
+ cancel: { reason: en(CANCEL_REASONS) },
2280
+ operator_status: { status: en(OPERATOR_STATUSES), reason: en(OPERATOR_STATUS_REASONS) },
2281
+ coordinator_ack: { notify: en(NOTIFY_KINDS), outcome: en(COORDINATOR_ACK_OUTCOMES) },
2282
+ hold_expired: { holdId: id, reason: en(HOLD_REASONS) }
2283
+ };
2284
+ var TURN_EVIDENCE_KINDS = Object.keys(TURN_EVIDENCE_FIELD_SPECS);
2285
+ var TERMINAL_CLASS_EVIDENCE_KINDS = [
2286
+ "turn_end",
2287
+ "transcript_final",
2288
+ "no_progress",
2289
+ "worker_report",
2290
+ "session_error",
2291
+ "process_exit",
2292
+ "cancel",
2293
+ "operator_status"
2294
+ ];
2295
+ var IDENTIFIER_RE = /^[^\s\u0000-\u001f\u007f]{1,256}$/;
2296
+ function makeGuard2(values) {
2297
+ const set = new Set(values);
2298
+ return (value) => typeof value === "string" && set.has(value);
2299
+ }
2300
+ var isTurnEvidenceKind = makeGuard2(TURN_EVIDENCE_KINDS);
2301
+ var isTurnReason = makeGuard2(TURN_REASONS);
2302
+ var isNotifyKind = makeGuard2(NOTIFY_KINDS);
2303
+ var isTurnOutcome = makeGuard2(TURN_OUTCOMES);
2304
+ var isCommitStrength = makeGuard2(COMMIT_STRENGTHS);
2305
+ function isRecord2(value) {
2306
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2307
+ }
2308
+ function isEvidenceIdentifier(value) {
2309
+ return typeof value === "string" && IDENTIFIER_RE.test(value);
2310
+ }
2311
+ function isFiniteNumber2(value) {
2312
+ return typeof value === "number" && Number.isFinite(value);
2313
+ }
2314
+ function isSummaryRef(value) {
2315
+ return isRecord2(value) && hasOnlyKeys(value, ["topic", "writer", "seq"]) && isEvidenceIdentifier(value.topic) && isEvidenceIdentifier(value.writer) && Number.isSafeInteger(value.seq) && value.seq >= 0;
2316
+ }
2317
+ function isTurnAttemptRef(value) {
2318
+ return isRecord2(value) && hasOnlyKeys(value, ["attemptId", "generation"]) && isEvidenceIdentifier(value.attemptId) && Number.isSafeInteger(value.generation) && value.generation >= 0;
2319
+ }
2320
+ function isLiveTurnPending(value) {
2321
+ return isRecord2(value) && hasOnlyKeys(value, ["modal", "adapterPending", "trailingTool", "newestActivityAt"]) && typeof value.modal === "boolean" && typeof value.adapterPending === "boolean" && typeof value.trailingTool === "boolean" && (value.newestActivityAt === void 0 || isFiniteNumber2(value.newestActivityAt));
2322
+ }
2323
+ function isNativeMarkerRef(value) {
2324
+ return isRecord2(value) && hasOnlyKeys(value, ["outcome", "turnId"]) && NATIVE_TURN_OUTCOMES.includes(value.outcome) && (value.turnId === void 0 || isEvidenceIdentifier(value.turnId));
2325
+ }
2326
+ function isCoordinatorIdentity(value) {
2327
+ return isRecord2(value) && hasOnlyKeys(value, ["daemonId", "coordinatorRunId", "sessionId"]) && isEvidenceIdentifier(value.daemonId) && isEvidenceIdentifier(value.coordinatorRunId) && (value.sessionId === void 0 || isEvidenceIdentifier(value.sessionId));
2328
+ }
2329
+ function hasOnlyKeys(value, allowed) {
2330
+ for (const key of Object.keys(value)) {
2331
+ if (!allowed.includes(key)) return false;
2332
+ }
2333
+ return true;
2334
+ }
2335
+ function fieldMatches(spec, value) {
2336
+ if (value === void 0) return spec.optional === true;
2337
+ switch (spec.t) {
2338
+ case "id":
2339
+ return isEvidenceIdentifier(value);
2340
+ case "enum":
2341
+ return typeof value === "string" && spec.values.includes(value);
2342
+ case "bool":
2343
+ return typeof value === "boolean";
2344
+ case "int":
2345
+ return value === null && spec.nullable === true || Number.isSafeInteger(value);
2346
+ case "ms":
2347
+ return isFiniteNumber2(value) && value >= 0;
2348
+ case "summary_ref":
2349
+ return isSummaryRef(value);
2350
+ case "attempt_ref":
2351
+ return isTurnAttemptRef(value);
2352
+ case "live":
2353
+ return isLiveTurnPending(value);
2354
+ case "native_marker":
2355
+ return isNativeMarkerRef(value);
2356
+ case "coordinator":
2357
+ return isCoordinatorIdentity(value);
2358
+ }
2359
+ }
2360
+ function isTurnEvidence(value) {
2361
+ if (!isRecord2(value) || !isTurnEvidenceKind(value.kind)) return false;
2362
+ const bodySpecs = TURN_EVIDENCE_FIELD_SPECS[value.kind];
2363
+ const envelopeSpecs = EVIDENCE_ENVELOPE_FIELD_SPECS;
2364
+ for (const key of Object.keys(value)) {
2365
+ if (key === "kind") continue;
2366
+ if (!(key in bodySpecs) && !(key in envelopeSpecs)) return false;
2367
+ }
2368
+ for (const [key, spec] of Object.entries(envelopeSpecs)) {
2369
+ if (!fieldMatches(spec, value[key])) return false;
2370
+ }
2371
+ for (const [key, spec] of Object.entries(bodySpecs)) {
2372
+ if (!fieldMatches(spec, value[key])) return false;
2373
+ }
2374
+ return true;
2375
+ }
2376
+ var TURN_EVIDENCE_FLAGS = ["hollow", "afterFinalizationTimeout", "nativeMarker", "selfAttributing"];
2377
+ var MESH_TOPIC_ENTRY_KINDS = ["turn.evidence", "turn.committed", "turn.notify", "mesh.record"];
2378
+ function isOptionalId(value) {
2379
+ return value === void 0 || isEvidenceIdentifier(value);
2380
+ }
2381
+ function isGeneration(value) {
2382
+ return Number.isSafeInteger(value) && value >= 0;
2383
+ }
2384
+ function isProjectedScalars(value) {
2385
+ if (!isRecord2(value)) return false;
2386
+ for (const v of Object.values(value)) {
2387
+ if (!(v === null || typeof v === "number" || typeof v === "boolean" || typeof v === "string")) return false;
2388
+ }
2389
+ return true;
2390
+ }
2391
+ function isMeshTopicEntry(value) {
2392
+ if (!isRecord2(value)) return false;
2393
+ if (value.v !== MESH_TOPIC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.eventId) || !isFiniteNumber2(value.at)) return false;
2394
+ switch (value.k) {
2395
+ case "turn.evidence": {
2396
+ if (!isEvidenceIdentifier(value.attemptId) || !isGeneration(value.generation)) return false;
2397
+ if (!isEvidenceIdentifier(value.ownerDaemonId) || !isEvidenceIdentifier(value.sessionId) || !isOptionalId(value.taskId)) return false;
2398
+ if (!isTurnEvidenceKind(value.ev)) return false;
2399
+ if (value.strength !== void 0 && !TURN_END_STRENGTHS.includes(value.strength)) return false;
2400
+ if (value.flags !== void 0) {
2401
+ if (!isRecord2(value.flags)) return false;
2402
+ for (const [flag, on] of Object.entries(value.flags)) {
2403
+ if (!TURN_EVIDENCE_FLAGS.includes(flag) || typeof on !== "boolean") return false;
2404
+ }
2405
+ }
2406
+ if (value.evidence !== void 0 && !(isTurnEvidence(value.evidence) && value.evidence.kind === value.ev)) return false;
2407
+ return true;
2408
+ }
2409
+ case "turn.committed":
2410
+ return isEvidenceIdentifier(value.attemptId) && isGeneration(value.generation) && isOptionalId(value.taskId) && isTurnOutcome(value.outcome) && isCommitStrength(value.strength) && isTurnReason(value.reason);
2411
+ case "turn.notify":
2412
+ return isOptionalId(value.attemptId) && isNotifyKind(value.notify) && isEvidenceIdentifier(value.targetDaemonId) && isOptionalId(value.targetSessionId) && isOptionalId(value.taskId);
2413
+ case "mesh.record":
2414
+ return isEvidenceIdentifier(value.ledgerKind) && isOptionalId(value.nodeId) && isOptionalId(value.sessionId) && isOptionalId(value.taskId) && isProjectedScalars(value.payload);
2415
+ default:
2416
+ return false;
2417
+ }
2418
+ }
2419
+ function projectTurnEvidenceEntry(evidence, attempt) {
2420
+ const flags = {};
2421
+ if (evidence.kind === "turn_end") {
2422
+ if (evidence.hollow) flags.hollow = true;
2423
+ if (evidence.afterFinalizationTimeout) flags.afterFinalizationTimeout = true;
2424
+ }
2425
+ if (evidence.kind === "transcript_final") {
2426
+ if (evidence.nativeMarker) flags.nativeMarker = true;
2427
+ if (evidence.selfAttributing) flags.selfAttributing = true;
2428
+ }
2429
+ const taskId = evidence.taskId;
2430
+ return {
2431
+ v: MESH_TOPIC_PROTOCOL_VERSION,
2432
+ eventId: evidence.eventId,
2433
+ at: evidence.at,
2434
+ k: "turn.evidence",
2435
+ attemptId: attempt.attemptId,
2436
+ generation: attempt.generation,
2437
+ ownerDaemonId: attempt.ownerDaemonId,
2438
+ ...taskId ? { taskId } : {},
2439
+ sessionId: evidence.sessionId,
2440
+ ev: evidence.kind,
2441
+ ...evidence.kind === "turn_end" ? { strength: evidence.strength } : {},
2442
+ ...Object.keys(flags).length > 0 ? { flags } : {},
2443
+ evidence
2444
+ };
2445
+ }
2446
+
2447
+ // src/session-launch.ts
2448
+ var MODEL_AXIS_SOURCES = [
2449
+ /** Picked explicitly for this launch (dashboard dropdown, coordinator dialog). */
2450
+ "user",
2451
+ /** The dashboard dialog restored it from the last launch (browser-local memory). */
2452
+ "remembered",
2453
+ /** A mesh capability slot supplied it (or a difficulty preset the slot outranked). */
2454
+ "mesh_slot",
2455
+ /** An explicit per-task model / thinking level on a mesh queue task. */
2456
+ "task_override",
2457
+ /** Nothing was requested; the provider's default is known (discovery / manifest). */
2458
+ "provider_default",
2459
+ /** A value was requested without saying where it came from, or nothing is known. */
2460
+ "unspecified"
2461
+ ];
2462
+ function isModelAxisSource(value) {
2463
+ return typeof value === "string" && MODEL_AXIS_SOURCES.includes(value);
2464
+ }
2465
+ var SESSION_LAUNCHED_BY = ["dashboard", "mesh", "cli", "api", "restore"];
2466
+ function isSessionLaunchedBy(value) {
2467
+ return typeof value === "string" && SESSION_LAUNCHED_BY.includes(value);
2468
+ }
2469
+ var MODEL_SELECTION_HISTORY_LIMIT = 20;
2470
+ function effectiveModelSelectionValue(selection) {
2471
+ if (!selection) return void 0;
2472
+ const last = Array.isArray(selection.history) ? selection.history[selection.history.length - 1] : void 0;
2473
+ return last?.value ?? selection.current ?? selection.observed ?? launchModelSelectionValue(selection);
2474
+ }
2475
+ function launchModelSelectionValue(selection) {
2476
+ if (!selection) return void 0;
2477
+ const launch = Array.isArray(selection.history) ? selection.history.find((entry) => entry.via === "launch") : void 0;
2478
+ return launch?.value ?? selection.launchValue ?? selection.requested ?? selection.resolvedDefault;
2479
+ }
2480
+ function describeModelSelection(selection) {
2481
+ const value = effectiveModelSelectionValue(selection);
2482
+ if (!selection || !value) return void 0;
2483
+ const launched = launchModelSelectionValue(selection);
2484
+ return {
2485
+ value,
2486
+ ...launched && launched !== value ? { changedFrom: launched } : {},
2487
+ source: isModelAxisSource(selection.source) ? selection.source : "unspecified"
2488
+ };
2489
+ }
2490
+ var MODEL_IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/@[\]+-]{0,95}$/;
2491
+ function sanitizeModelIdentifier(value) {
2492
+ if (typeof value !== "string") return void 0;
2493
+ const trimmed = value.trim();
2494
+ return MODEL_IDENTIFIER_PATTERN.test(trimmed) ? trimmed : void 0;
2495
+ }
2496
+ function readString2(value) {
2497
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
2498
+ }
2499
+ function readFiniteNumber(value) {
2500
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
2501
+ }
2502
+ function parseModelSelection(raw) {
2503
+ if (!raw || typeof raw !== "object") return void 0;
2504
+ const record = raw;
2505
+ const history = [];
2506
+ if (Array.isArray(record.history)) {
2507
+ for (const entry of record.history) {
2508
+ if (!entry || typeof entry !== "object") continue;
2509
+ const e = entry;
2510
+ const value = readString2(e.value);
2511
+ const at = readFiniteNumber(e.at);
2512
+ const via = e.via === "launch" || e.via === "change_model" || e.via === "observed" ? e.via : void 0;
2513
+ if (value && at !== void 0 && via) history.push({ at, value, via });
2514
+ }
2515
+ }
2516
+ const requested = readString2(record.requested);
2517
+ const launchValue = readString2(record.launchValue);
2518
+ const resolvedDefault = readString2(record.resolvedDefault);
2519
+ const current = readString2(record.current);
2520
+ const observed = readString2(record.observed);
2521
+ const observedAt = readFiniteNumber(record.observedAt);
2522
+ return {
2523
+ source: isModelAxisSource(record.source) ? record.source : "unspecified",
2524
+ ...requested ? { requested } : {},
2525
+ ...launchValue ? { launchValue } : {},
2526
+ ...resolvedDefault ? { resolvedDefault } : {},
2527
+ ...current ? { current } : {},
2528
+ ...observed ? { observed } : {},
2529
+ ...observedAt !== void 0 ? { observedAt } : {},
2530
+ history: history.slice(-MODEL_SELECTION_HISTORY_LIMIT)
2531
+ };
2532
+ }
2533
+ function parseSessionLaunchRecord(raw) {
2534
+ if (!raw || typeof raw !== "object") return void 0;
2535
+ const record = raw;
2536
+ const sessionId = readString2(record.sessionId);
2537
+ const providerType = readString2(record.providerType);
2538
+ const launchedAt = readFiniteNumber(record.launchedAt);
2539
+ const model = parseModelSelection(record.model);
2540
+ const thinkingLevel = parseModelSelection(record.thinkingLevel);
2541
+ if (!sessionId || !providerType || launchedAt === void 0 || !model || !thinkingLevel) return void 0;
2542
+ const providerVersion = readString2(record.providerVersion);
2543
+ const workspace = readString2(record.workspace);
2544
+ const autoApproveModeId = readString2(record.autoApproveModeId);
2545
+ return {
2546
+ sessionId,
2547
+ providerType,
2548
+ ...providerVersion ? { providerVersion } : {},
2549
+ ...record.providerChannel === "stable" || record.providerChannel === "preview" ? { providerChannel: record.providerChannel } : {},
2550
+ launchedBy: isSessionLaunchedBy(record.launchedBy) ? record.launchedBy : "api",
2551
+ launchedAt,
2552
+ ...workspace ? { workspace } : {},
2553
+ model,
2554
+ thinkingLevel,
2555
+ ...autoApproveModeId ? { autoApproveModeId } : {}
2556
+ };
2557
+ }
2558
+
2559
+ // src/turn-ipc.ts
2560
+ var TURN_IPC_PROTOCOL_VERSION = 1;
2561
+ function isFiniteNumber3(value) {
2562
+ return typeof value === "number" && Number.isFinite(value);
2563
+ }
2564
+ function isNonNegativeInt(value) {
2565
+ return Number.isSafeInteger(value) && value >= 0;
2566
+ }
2567
+ function isOptionalId2(value) {
2568
+ return value === void 0 || isEvidenceIdentifier(value);
2569
+ }
2570
+ function hasOnlyKeys2(value, allowed) {
2571
+ for (const key of Object.keys(value)) {
2572
+ if (!allowed.includes(key)) return false;
2573
+ }
2574
+ return true;
2575
+ }
2576
+ var TURN_IPC_ERROR_CODES = ["daemon_required", "turn_ledger_unavailable", "ledger_not_owner"];
2577
+ function makeGuard3(values) {
2578
+ const set = new Set(values);
2579
+ return (value) => typeof value === "string" && set.has(value);
2580
+ }
2581
+ var isTurnIpcErrorCode = makeGuard3(TURN_IPC_ERROR_CODES);
2582
+ function isTurnIpcError(value) {
2583
+ return isRecord(value) && hasOnlyKeys2(value, ["code", "detail"]) && isTurnIpcErrorCode(value.code) && (value.detail === void 0 || typeof value.detail === "string");
2584
+ }
2585
+ var TURN_OBSERVE_VERDICTS = ["applied", "recorded", "rejected"];
2586
+ var isTurnObserveVerdict = makeGuard3(TURN_OBSERVE_VERDICTS);
2587
+ function isTurnObserveRequest(value) {
2588
+ return isRecord(value) && hasOnlyKeys2(value, ["v", "evidence"]) && value.v === TURN_IPC_PROTOCOL_VERSION && isTurnEvidence(value.evidence);
2589
+ }
2590
+ function decodeTurnObserveRequest(value) {
2591
+ return isTurnObserveRequest(value) ? value : null;
2592
+ }
2593
+ function isTurnAttemptRefValue(value) {
2594
+ return isRecord(value) && hasOnlyKeys2(value, ["attemptId", "generation"]) && isEvidenceIdentifier(value.attemptId) && isNonNegativeInt(value.generation);
2595
+ }
2596
+ function isTurnObserveResponse(value) {
2597
+ return isRecord(value) && hasOnlyKeys2(value, ["verdict", "attemptRef", "outcome"]) && isTurnObserveVerdict(value.verdict) && isTurnAttemptRefValue(value.attemptRef) && (value.outcome === void 0 || isTurnOutcomeValue(value.outcome));
2598
+ }
2599
+ var TURN_OUTCOMES_LOCAL = ["completed", "failed", "cancelled"];
2600
+ function isTurnOutcomeValue(value) {
2601
+ return typeof value === "string" && TURN_OUTCOMES_LOCAL.includes(value);
2602
+ }
2603
+ function decodeTurnObserveResponse(value) {
2604
+ return isTurnObserveResponse(value) ? value : null;
2605
+ }
2606
+ var MESH_RECORD_PAYLOAD_KEYS = [
2607
+ // Identifiers
2608
+ "taskId",
2609
+ "deliveryId",
2610
+ "attemptId",
2611
+ "missionId",
2612
+ "checkpointId",
2613
+ "promptId",
2614
+ "providerSessionId",
2615
+ "targetNoteId",
2616
+ // Routing / addressing
2617
+ "nodeId",
2618
+ "sessionId",
2619
+ "providerType",
2620
+ "transport",
2621
+ "attemptedSessionId",
2622
+ "holderSessionId",
2623
+ // Outcome enums
2624
+ "reason",
2625
+ "status",
2626
+ "outcome",
2627
+ "terminalKind",
2628
+ "event",
2629
+ "source",
2630
+ "intentionalStopReason",
2631
+ // Booleans
2632
+ "retryable",
2633
+ "rebound",
2634
+ "forced",
2635
+ "fallback",
2636
+ "membershipRemoved",
2637
+ "requestedForce",
2638
+ "removedByRemoteDaemon",
2639
+ "completedViaReady",
2640
+ "intentional",
2641
+ "weak",
2642
+ // Counters
2643
+ "attempt",
2644
+ "attemptCount",
2645
+ "count"
2646
+ ];
2647
+ var MESH_RECORD_PAYLOAD_KEY_SET = new Set(MESH_RECORD_PAYLOAD_KEYS);
2648
+ var MAX_MESH_RECORD_STRING = 200;
2649
+ function isProjectedScalarsValue(value) {
2650
+ if (!isRecord(value)) return false;
2651
+ for (const v of Object.values(value)) {
2652
+ if (v === null) continue;
2653
+ if (typeof v === "boolean" || typeof v === "number") continue;
2654
+ if (typeof v === "string") {
2655
+ if (v.length > MAX_MESH_RECORD_STRING) return false;
2656
+ continue;
2657
+ }
2658
+ return false;
2659
+ }
2660
+ return true;
2661
+ }
2662
+ function isMeshRecordPayload(value) {
2663
+ if (!isProjectedScalarsValue(value)) return false;
2664
+ for (const key of Object.keys(value)) {
2665
+ if (!MESH_RECORD_PAYLOAD_KEY_SET.has(key)) return false;
2666
+ }
2667
+ return true;
2668
+ }
2669
+ function isMeshRecordRequest(value) {
2670
+ return isRecord(value) && hasOnlyKeys2(value, ["v", "meshId", "ledgerKind", "nodeId", "sessionId", "taskId", "payload"]) && value.v === TURN_IPC_PROTOCOL_VERSION && isEvidenceIdentifier(value.meshId) && isEvidenceIdentifier(value.ledgerKind) && isOptionalId2(value.nodeId) && isOptionalId2(value.sessionId) && isOptionalId2(value.taskId) && isMeshRecordPayload(value.payload);
2671
+ }
2672
+ function decodeMeshRecordRequest(value) {
2673
+ return isMeshRecordRequest(value) ? value : null;
2674
+ }
2675
+ function isMeshRecordResponse(value) {
2676
+ return isRecord(value) && hasOnlyKeys2(value, ["eventId", "seq"]) && isEvidenceIdentifier(value.eventId) && isNonNegativeInt(value.seq);
2677
+ }
2678
+ function decodeMeshRecordResponse(value) {
2679
+ return isMeshRecordResponse(value) ? value : null;
2680
+ }
2681
+ function isTurnCancelRequest(value) {
2682
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "attemptId", "taskId", "reason"])) return false;
2683
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION) return false;
2684
+ const hasAttempt = value.attemptId !== void 0;
2685
+ const hasTask = value.taskId !== void 0;
2686
+ if (hasAttempt === hasTask) return false;
2687
+ if (hasAttempt && !isEvidenceIdentifier(value.attemptId)) return false;
2688
+ if (hasTask && !isEvidenceIdentifier(value.taskId)) return false;
2689
+ return isTurnReason(value.reason);
2690
+ }
2691
+ function decodeTurnCancelRequest(value) {
2692
+ return isTurnCancelRequest(value) ? value : null;
2693
+ }
2694
+ function isTurnCancelResponse(value) {
2695
+ return isRecord(value) && hasOnlyKeys2(value, ["attemptRef", "verdict"]) && isTurnAttemptRefValue(value.attemptRef) && isTurnObserveVerdict(value.verdict);
2696
+ }
2697
+ function decodeTurnCancelResponse(value) {
2698
+ return isTurnCancelResponse(value) ? value : null;
2699
+ }
2700
+ var OPERATOR_STATUS_VALUES = ["completed", "failed"];
2701
+ var isOperatorStatusValue = makeGuard3(OPERATOR_STATUS_VALUES);
2702
+ var OPERATOR_STATUS_REASON_VALUES = ["operator_update", "refine_terminal", "validation_terminal"];
2703
+ var isOperatorStatusReasonValue = makeGuard3(OPERATOR_STATUS_REASON_VALUES);
2704
+ function isOperatorStatusRequest(value) {
2705
+ return isRecord(value) && hasOnlyKeys2(value, ["v", "taskId", "status", "reason"]) && value.v === TURN_IPC_PROTOCOL_VERSION && isEvidenceIdentifier(value.taskId) && isOperatorStatusValue(value.status) && isOperatorStatusReasonValue(value.reason);
2706
+ }
2707
+ function decodeOperatorStatusRequest(value) {
2708
+ return isOperatorStatusRequest(value) ? value : null;
2709
+ }
2710
+ function isOperatorStatusResponse(value) {
2711
+ return isRecord(value) && hasOnlyKeys2(value, ["accepted"]) && value.accepted === true;
2712
+ }
2713
+ function decodeOperatorStatusResponse(value) {
2714
+ return isOperatorStatusResponse(value) ? value : null;
2715
+ }
2716
+ function isTurnQueryRequest(value) {
2717
+ return isRecord(value) && hasOnlyKeys2(value, ["v", "meshId", "taskId", "attemptId", "sessionId", "state", "since", "tail"]) && value.v === TURN_IPC_PROTOCOL_VERSION && isEvidenceIdentifier(value.meshId) && isOptionalId2(value.taskId) && isOptionalId2(value.attemptId) && isOptionalId2(value.sessionId) && (value.state === void 0 || isEvidenceIdentifier(value.state)) && (value.since === void 0 || isFiniteNumber3(value.since)) && (value.tail === void 0 || isNonNegativeInt(value.tail));
2718
+ }
2719
+ function decodeTurnQueryRequest(value) {
2720
+ return isTurnQueryRequest(value) ? value : null;
2721
+ }
2722
+ var TURN_QUERY_ATTEMPT_ROW_KEYS = [
2723
+ "attemptId",
2724
+ "generation",
2725
+ "meshId",
2726
+ "taskId",
2727
+ "sessionId",
2728
+ "nodeId",
2729
+ "providerType",
2730
+ "state",
2731
+ "terminalOutcome",
2732
+ "terminalReason",
2733
+ "acceptedAt",
2734
+ "terminalAt"
2735
+ ];
2736
+ function isTurnQueryAttemptRow(value) {
2737
+ if (!isRecord(value) || !hasOnlyKeys2(value, TURN_QUERY_ATTEMPT_ROW_KEYS)) return false;
2738
+ if (!isEvidenceIdentifier(value.attemptId) || !isNonNegativeInt(value.generation)) return false;
2739
+ if (!isOptionalId2(value.meshId) || !isOptionalId2(value.taskId)) return false;
2740
+ if (!isEvidenceIdentifier(value.sessionId)) return false;
2741
+ if (!isOptionalId2(value.nodeId) || !isOptionalId2(value.providerType)) return false;
2742
+ if (typeof value.state !== "string") return false;
2743
+ if (value.terminalOutcome !== void 0 && !isTurnOutcomeValue(value.terminalOutcome)) return false;
2744
+ if (value.terminalReason !== void 0 && !isTurnReason(value.terminalReason)) return false;
2745
+ if (!isFiniteNumber3(value.acceptedAt)) return false;
2746
+ if (value.terminalAt !== void 0 && !isFiniteNumber3(value.terminalAt)) return false;
2747
+ return true;
2748
+ }
2749
+ var TURN_QUERY_EVENT_VERDICTS = ["applied", "recorded", "rejected", "forwarded"];
2750
+ var TURN_QUERY_EVENT_ROW_KEYS = ["eventId", "attemptId", "generation", "sessionId", "kind", "source", "verdict", "atMs"];
2751
+ function isTurnQueryEventRow(value) {
2752
+ if (!isRecord(value) || !hasOnlyKeys2(value, TURN_QUERY_EVENT_ROW_KEYS)) return false;
2753
+ if (!isEvidenceIdentifier(value.eventId)) return false;
2754
+ if (!isOptionalId2(value.attemptId)) return false;
2755
+ if (value.generation !== void 0 && !isNonNegativeInt(value.generation)) return false;
2756
+ if (!isEvidenceIdentifier(value.sessionId)) return false;
2757
+ if (typeof value.kind !== "string") return false;
2758
+ if (typeof value.source !== "string") return false;
2759
+ if (!TURN_QUERY_EVENT_VERDICTS.includes(value.verdict)) return false;
2760
+ if (!isFiniteNumber3(value.atMs)) return false;
2761
+ return true;
2762
+ }
2763
+ function isTurnQueryResponse(value) {
2764
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["attempts", "events", "replicationPending"])) return false;
2765
+ if (!Array.isArray(value.attempts) || !value.attempts.every(isTurnQueryAttemptRow)) return false;
2766
+ if (!Array.isArray(value.events) || !value.events.every(isTurnQueryEventRow)) return false;
2767
+ if (value.replicationPending !== void 0 && typeof value.replicationPending !== "boolean") return false;
2768
+ return true;
2769
+ }
2770
+ function decodeTurnQueryResponse(value) {
2771
+ return isTurnQueryResponse(value) ? value : null;
2772
+ }
2773
+ var MESH_INDEX_QUERY_WRITER_SCOPES = ["own", "fleet"];
2774
+ var isMeshIndexQueryWriterScope = makeGuard3(MESH_INDEX_QUERY_WRITER_SCOPES);
2775
+ function isMeshIndexQueryRequest(value) {
2776
+ return isRecord(value) && hasOnlyKeys2(value, ["v", "meshId", "ledgerKind", "sessionId", "taskId", "writer", "since", "tail"]) && value.v === TURN_IPC_PROTOCOL_VERSION && isEvidenceIdentifier(value.meshId) && isOptionalId2(value.ledgerKind) && isOptionalId2(value.sessionId) && isOptionalId2(value.taskId) && (value.writer === void 0 || isMeshIndexQueryWriterScope(value.writer)) && (value.since === void 0 || isFiniteNumber3(value.since)) && (value.tail === void 0 || isNonNegativeInt(value.tail));
2777
+ }
2778
+ function decodeMeshIndexQueryRequest(value) {
2779
+ return isMeshIndexQueryRequest(value) ? value : null;
2780
+ }
2781
+ var MESH_TOPIC_INDEX_ROW_KEYS = [
2782
+ "writer",
2783
+ "seq",
2784
+ "meshId",
2785
+ "eventId",
2786
+ "kind",
2787
+ "ledgerKind",
2788
+ "taskId",
2789
+ "sessionId",
2790
+ "nodeId",
2791
+ "atMs",
2792
+ "payload"
2793
+ ];
2794
+ function isMeshTopicIndexRow(value) {
2795
+ if (!isRecord(value) || !hasOnlyKeys2(value, MESH_TOPIC_INDEX_ROW_KEYS)) return false;
2796
+ if (!isEvidenceIdentifier(value.writer) || !isNonNegativeInt(value.seq)) return false;
2797
+ if (!isEvidenceIdentifier(value.meshId) || !isEvidenceIdentifier(value.eventId)) return false;
2798
+ if (typeof value.kind !== "string") return false;
2799
+ if (!isOptionalId2(value.ledgerKind) || !isOptionalId2(value.taskId) || !isOptionalId2(value.sessionId) || !isOptionalId2(value.nodeId)) return false;
2800
+ if (!isFiniteNumber3(value.atMs)) return false;
2801
+ if (!isMeshRecordPayload(value.payload)) return false;
2802
+ return true;
2803
+ }
2804
+ function isMeshIndexQueryResponse(value) {
2805
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["rows", "replicationPending"])) return false;
2806
+ if (!Array.isArray(value.rows) || !value.rows.every(isMeshTopicIndexRow)) return false;
2807
+ if (value.replicationPending !== void 0 && typeof value.replicationPending !== "boolean") return false;
2808
+ return true;
2809
+ }
2810
+ function decodeMeshIndexQueryResponse(value) {
2811
+ return isMeshIndexQueryResponse(value) ? value : null;
2812
+ }
2813
+ var MESH_MISSION_STATUSES = ["active", "paused", "completed", "abandoned"];
2814
+ var isMeshMissionStatusValue = makeGuard3(MESH_MISSION_STATUSES);
2815
+ var MESH_MISSION_SOURCES = ["magi", "coordinator"];
2816
+ var isMeshMissionSourceValue = makeGuard3(MESH_MISSION_SOURCES);
2817
+ function isStringArray(value) {
2818
+ return Array.isArray(value) && value.every((v) => typeof v === "string");
2819
+ }
2820
+ function isMissionBriefWire(value) {
2821
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["goal", "constraints", "doneCriteria", "handoffNotes", "ownedPaths"])) return false;
2822
+ if (typeof value.goal !== "string" || value.goal.trim().length === 0) return false;
2823
+ for (const k of ["constraints", "doneCriteria", "handoffNotes", "ownedPaths"]) {
2824
+ if (value[k] !== void 0 && !isStringArray(value[k])) return false;
2825
+ }
2826
+ return true;
2827
+ }
2828
+ function isMeshMissionRecordWire(value) {
2829
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["id", "meshId", "title", "goal", "status", "source", "brief"])) return false;
2830
+ if (!isEvidenceIdentifier(value.id) || !isEvidenceIdentifier(value.meshId)) return false;
2831
+ if (typeof value.title !== "string" || typeof value.goal !== "string") return false;
2832
+ if (!isMeshMissionStatusValue(value.status)) return false;
2833
+ if (value.source !== void 0 && !isMeshMissionSourceValue(value.source)) return false;
2834
+ if (value.brief !== void 0 && !isMissionBriefWire(value.brief)) return false;
2835
+ return true;
2836
+ }
2837
+ function isMissionUpsertRequest(value) {
2838
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "id", "title", "goal", "status", "source", "brief"])) return false;
2839
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION) return false;
2840
+ if (!isEvidenceIdentifier(value.meshId)) return false;
2841
+ if (value.id !== void 0 && !isEvidenceIdentifier(value.id)) return false;
2842
+ if (typeof value.title !== "string" || value.title.trim().length === 0) return false;
2843
+ if (value.goal !== void 0 && typeof value.goal !== "string") return false;
2844
+ if (value.status !== void 0 && !isMeshMissionStatusValue(value.status)) return false;
2845
+ if (value.source !== void 0 && !isMeshMissionSourceValue(value.source)) return false;
2846
+ if (value.brief !== void 0 && value.brief !== null && !isMissionBriefWire(value.brief)) return false;
2847
+ return true;
2848
+ }
2849
+ function decodeMissionUpsertRequest(value) {
2850
+ return isMissionUpsertRequest(value) ? value : null;
2851
+ }
2852
+ function isMissionUpsertResponse(value) {
2853
+ return isRecord(value) && hasOnlyKeys2(value, ["mission"]) && isMeshMissionRecordWire(value.mission);
2854
+ }
2855
+ function decodeMissionUpsertResponse(value) {
2856
+ return isMissionUpsertResponse(value) ? value : null;
2857
+ }
2858
+ function isMissionQueryRequest(value) {
2859
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "statuses", "id"])) return false;
2860
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION) return false;
2861
+ if (!isEvidenceIdentifier(value.meshId)) return false;
2862
+ if (value.id !== void 0 && !isEvidenceIdentifier(value.id)) return false;
2863
+ if (value.statuses !== void 0) {
2864
+ if (!Array.isArray(value.statuses) || value.statuses.length === 0) return false;
2865
+ if (!value.statuses.every(isMeshMissionStatusValue)) return false;
2866
+ }
2867
+ return true;
2868
+ }
2869
+ function decodeMissionQueryRequest(value) {
2870
+ return isMissionQueryRequest(value) ? value : null;
2871
+ }
2872
+ function isMissionQueryResponse(value) {
2873
+ return isRecord(value) && hasOnlyKeys2(value, ["missions"]) && Array.isArray(value.missions) && value.missions.every(isMeshMissionRecordWire);
2874
+ }
2875
+ function decodeMissionQueryResponse(value) {
2876
+ return isMissionQueryResponse(value) ? value : null;
2877
+ }
2878
+ function isMissionListQueryRequest(value) {
2879
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "statuses", "verbose", "includeMagi", "withStats", "limit", "historyIdLimit", "meshStatusView"])) return false;
2880
+ if (value.meshStatusView !== void 0 && value.meshStatusView !== "compact" && value.meshStatusView !== "verbose") return false;
2881
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION) return false;
2882
+ if (!isEvidenceIdentifier(value.meshId)) return false;
2883
+ if (value.statuses !== void 0) {
2884
+ if (!Array.isArray(value.statuses) || value.statuses.length === 0) return false;
2885
+ if (!value.statuses.every(isMeshMissionStatusValue)) return false;
2886
+ }
2887
+ if (value.verbose !== void 0 && typeof value.verbose !== "boolean") return false;
2888
+ if (value.includeMagi !== void 0 && typeof value.includeMagi !== "boolean") return false;
2889
+ if (value.withStats !== void 0 && typeof value.withStats !== "boolean") return false;
2890
+ if (value.limit !== void 0 && !isNonNegativeInt(value.limit)) return false;
2891
+ if (value.historyIdLimit !== void 0 && !isNonNegativeInt(value.historyIdLimit)) return false;
2892
+ return true;
2893
+ }
2894
+ function decodeMissionListQueryRequest(value) {
2895
+ return isMissionListQueryRequest(value) ? value : null;
2896
+ }
2897
+ function isMeshMissionTaskAggregateWire(value) {
2898
+ const keys = ["total", "pending", "assigned", "completed", "failed", "cancelled", "blocked", "lastActivityAt"];
2899
+ if (!isRecord(value) || !hasOnlyKeys2(value, keys)) return false;
2900
+ for (const k of ["total", "pending", "assigned", "completed", "failed", "cancelled", "blocked"]) {
2901
+ if (!isNonNegativeInt(value[k])) return false;
2902
+ }
2903
+ return value.lastActivityAt === null || typeof value.lastActivityAt === "string";
2904
+ }
2905
+ function isMeshMissionStatsWire(value) {
2906
+ const keys = ["missionId", "taskCount", "completed", "failed", "totalDurationMs", "wallClockMs", "retries", "incompleteTaskIds"];
2907
+ if (!isRecord(value) || !hasOnlyKeys2(value, keys)) return false;
2908
+ if (!isEvidenceIdentifier(value.missionId)) return false;
2909
+ for (const k of ["taskCount", "completed", "failed", "totalDurationMs", "retries"]) {
2910
+ if (!isNonNegativeInt(value[k])) return false;
2911
+ }
2912
+ if (value.wallClockMs !== null && !isNonNegativeInt(value.wallClockMs)) return false;
2913
+ if (!Array.isArray(value.incompleteTaskIds) || !value.incompleteTaskIds.every(isEvidenceIdentifier)) return false;
2914
+ return true;
2915
+ }
2916
+ function isMissionListSummaryWire(value) {
2917
+ if (!isRecord(value)) return false;
2918
+ const hasGoal = "goal" in value;
2919
+ const hasPreview = "goalPreview" in value && "goalTruncated" in value;
2920
+ if (hasGoal === hasPreview) return false;
2921
+ const baseKeys = ["id", "meshId", "title", "status", "source", "tasks", "stats", "brief", "createdAt", "updatedAt", "closeCandidateEmittedAt"];
2922
+ const allowed = hasGoal ? [...baseKeys, "goal"] : [...baseKeys, "goalPreview", "goalTruncated"];
2923
+ if (!hasOnlyKeys2(value, allowed)) return false;
2924
+ if (!isEvidenceIdentifier(value.id) || !isEvidenceIdentifier(value.meshId)) return false;
2925
+ if (typeof value.title !== "string") return false;
2926
+ if (!isMeshMissionStatusValue(value.status)) return false;
2927
+ if (value.source !== void 0 && !isMeshMissionSourceValue(value.source)) return false;
2928
+ if (!isMeshMissionTaskAggregateWire(value.tasks)) return false;
2929
+ if (value.stats !== void 0 && !isMeshMissionStatsWire(value.stats)) return false;
2930
+ if (value.brief !== void 0 && !isMissionBriefWire(value.brief)) return false;
2931
+ if (hasGoal && typeof value.goal !== "string") return false;
2932
+ if (hasPreview && (typeof value.goalPreview !== "string" || typeof value.goalTruncated !== "boolean")) return false;
2933
+ if (value.createdAt !== void 0 && typeof value.createdAt !== "string") return false;
2934
+ if (value.updatedAt !== void 0 && typeof value.updatedAt !== "string") return false;
2935
+ if (value.closeCandidateEmittedAt !== void 0 && value.closeCandidateEmittedAt !== null && typeof value.closeCandidateEmittedAt !== "string") return false;
2936
+ return true;
2937
+ }
2938
+ function isMeshMissionHistoryFoldWire(value) {
2939
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["count", "byStatus", "missionIds", "note"])) return false;
2940
+ if (!isNonNegativeInt(value.count)) return false;
2941
+ if (!isRecord(value.byStatus) || !Object.values(value.byStatus).every((n) => isNonNegativeInt(n))) return false;
2942
+ if (!Array.isArray(value.missionIds) || !value.missionIds.every(isEvidenceIdentifier)) return false;
2943
+ return typeof value.note === "string";
2944
+ }
2945
+ function isMissionListQueryResponse(value) {
2946
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["missions", "historyFold", "truncated", "matched", "overflowIds"])) return false;
2947
+ if (!Array.isArray(value.missions) || !value.missions.every(isMissionListSummaryWire)) return false;
2948
+ if (value.historyFold !== null && !isMeshMissionHistoryFoldWire(value.historyFold)) return false;
2949
+ if (typeof value.truncated !== "boolean") return false;
2950
+ if (!isNonNegativeInt(value.matched)) return false;
2951
+ if (value.overflowIds !== void 0 && (!Array.isArray(value.overflowIds) || !value.overflowIds.every(isEvidenceIdentifier))) return false;
2952
+ return true;
2953
+ }
2954
+ function decodeMissionListQueryResponse(value) {
2955
+ return isMissionListQueryResponse(value) ? value : null;
2956
+ }
2957
+ var OPERATING_NOTE_CATEGORIES = ["provider_quirk", "pattern_to_avoid", "recovery_lesson"];
2958
+ var isOperatingNoteCategory = makeGuard3(OPERATING_NOTE_CATEGORIES);
2959
+ function isOptionalShortString(value, max = 512) {
2960
+ return value === void 0 || typeof value === "string" && value.trim().length > 0 && value.length <= max;
2961
+ }
2962
+ function isNoteUpsertRequest(value) {
2963
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "text", "category", "pinned", "expiresAt", "supersedes", "subjectKey", "sourceCoordinator"])) return false;
2964
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION) return false;
2965
+ if (!isEvidenceIdentifier(value.meshId)) return false;
2966
+ if (typeof value.text !== "string" || value.text.trim().length === 0) return false;
2967
+ if (value.category !== void 0 && !isOperatingNoteCategory(value.category)) return false;
2968
+ if (value.pinned !== void 0 && typeof value.pinned !== "boolean") return false;
2969
+ if (value.expiresAt !== void 0 && (typeof value.expiresAt !== "string" || Number.isNaN(Date.parse(value.expiresAt)))) return false;
2970
+ return isOptionalShortString(value.supersedes) && isOptionalShortString(value.subjectKey) && isOptionalShortString(value.sourceCoordinator);
2971
+ }
2972
+ function decodeNoteUpsertRequest(value) {
2973
+ return isNoteUpsertRequest(value) ? value : null;
2974
+ }
2975
+ function isNoteUpsertResponse(value) {
2976
+ return isRecord(value) && hasOnlyKeys2(value, ["noteId", "deduped", "createdAt"]) && isEvidenceIdentifier(value.noteId) && typeof value.deduped === "boolean" && typeof value.createdAt === "string";
2977
+ }
2978
+ function decodeNoteUpsertResponse(value) {
2979
+ return isNoteUpsertResponse(value) ? value : null;
2980
+ }
2981
+ function isNoteForgetRequest(value) {
2982
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "noteId", "text", "reason"])) return false;
2983
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION) return false;
2984
+ if (!isEvidenceIdentifier(value.meshId)) return false;
2985
+ if (value.noteId !== void 0 && !isEvidenceIdentifier(value.noteId)) return false;
2986
+ if (value.text !== void 0 && (typeof value.text !== "string" || value.text.trim().length === 0)) return false;
2987
+ if (value.noteId === void 0 && value.text === void 0) return false;
2988
+ return value.reason === void 0 || typeof value.reason === "string";
2989
+ }
2990
+ function decodeNoteForgetRequest(value) {
2991
+ return isNoteForgetRequest(value) ? value : null;
2992
+ }
2993
+ function isNoteForgetResponse(value) {
2994
+ return isRecord(value) && hasOnlyKeys2(value, ["matched", "tombstoneId"]) && typeof value.matched === "number" && Number.isInteger(value.matched) && value.matched >= 0 && isEvidenceIdentifier(value.tombstoneId);
2995
+ }
2996
+ function decodeNoteForgetResponse(value) {
2997
+ return isNoteForgetResponse(value) ? value : null;
2998
+ }
2999
+ var TOOL_CALLER_ROLES = ["coordinator", "unknown"];
3000
+ var isToolCallerRole = makeGuard3(TOOL_CALLER_ROLES);
3001
+ function isToolCallRecordRequest(value) {
3002
+ return isRecord(value) && hasOnlyKeys2(value, ["v", "meshId", "tool", "sessionId", "callerRole"]) && value.v === TURN_IPC_PROTOCOL_VERSION && isEvidenceIdentifier(value.meshId) && isEvidenceIdentifier(value.tool) && isOptionalId2(value.sessionId) && isToolCallerRole(value.callerRole);
3003
+ }
3004
+ function decodeToolCallRecordRequest(value) {
3005
+ return isToolCallRecordRequest(value) ? value : null;
3006
+ }
3007
+ function isToolCallRecordResponse(value) {
3008
+ return isRecord(value) && hasOnlyKeys2(value, ["rateLimitExceeded", "callsInWindow", "advisory"]) && typeof value.rateLimitExceeded === "boolean" && isNonNegativeInt(value.callsInWindow) && (value.advisory === null || typeof value.advisory === "string");
3009
+ }
3010
+ function decodeToolCallRecordResponse(value) {
3011
+ return isToolCallRecordResponse(value) ? value : null;
3012
+ }
3013
+ function isLedgerQueryRequest(value) {
3014
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "kind", "since", "node", "tail", "includeSummary"])) return false;
3015
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION) return false;
3016
+ if (!isEvidenceIdentifier(value.meshId)) return false;
3017
+ if (value.kind !== void 0 && (!Array.isArray(value.kind) || value.kind.length === 0 || !value.kind.every(isEvidenceIdentifier))) return false;
3018
+ if (value.since !== void 0 && typeof value.since !== "string") return false;
3019
+ if (!isOptionalId2(value.node)) return false;
3020
+ if (value.tail !== void 0 && !isNonNegativeInt(value.tail)) return false;
3021
+ if (value.includeSummary !== void 0 && typeof value.includeSummary !== "boolean") return false;
3022
+ return true;
3023
+ }
3024
+ function decodeLedgerQueryRequest(value) {
3025
+ return isLedgerQueryRequest(value) ? value : null;
3026
+ }
3027
+ var LEDGER_QUERY_ENTRY_KEYS = ["id", "meshId", "timestamp", "kind", "nodeId", "sessionId", "providerType", "taskId", "payload"];
3028
+ function isLedgerQueryEntryWire(value) {
3029
+ if (!isRecord(value) || !hasOnlyKeys2(value, LEDGER_QUERY_ENTRY_KEYS)) return false;
3030
+ if (!isEvidenceIdentifier(value.id) || !isEvidenceIdentifier(value.meshId)) return false;
3031
+ if (typeof value.timestamp !== "string" || typeof value.kind !== "string") return false;
3032
+ if (!isOptionalId2(value.nodeId) || !isOptionalId2(value.sessionId) || !isOptionalId2(value.providerType) || !isOptionalId2(value.taskId)) return false;
3033
+ if (!isRecord(value.payload)) return false;
3034
+ return true;
3035
+ }
3036
+ function isLedgerQuerySummaryWire(value) {
3037
+ const keys = ["meshId", "totalEntries", "taskDispatched", "taskCompleted", "taskFailed", "taskStalled", "sessionLaunched", "checkpointCreated", "lastActivityAt", "recentFailures"];
3038
+ if (!isRecord(value) || !hasOnlyKeys2(value, keys)) return false;
3039
+ if (!isEvidenceIdentifier(value.meshId)) return false;
3040
+ for (const k of ["totalEntries", "taskDispatched", "taskCompleted", "taskFailed", "taskStalled", "sessionLaunched", "checkpointCreated", "recentFailures"]) {
3041
+ if (!isNonNegativeInt(value[k])) return false;
3042
+ }
3043
+ if (value.lastActivityAt !== null && typeof value.lastActivityAt !== "string") return false;
3044
+ return true;
3045
+ }
3046
+ function isLedgerQueryResponse(value) {
3047
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["entries", "summary"])) return false;
3048
+ if (!Array.isArray(value.entries) || !value.entries.every(isLedgerQueryEntryWire)) return false;
3049
+ if (value.summary !== void 0 && !isLedgerQuerySummaryWire(value.summary)) return false;
3050
+ return true;
3051
+ }
3052
+ function decodeLedgerQueryResponse(value) {
3053
+ return isLedgerQueryResponse(value) ? value : null;
3054
+ }
3055
+ function isRecordArray(value) {
3056
+ return Array.isArray(value) && value.every(isRecord);
3057
+ }
3058
+ function isOptionalRecord(value) {
3059
+ return value === void 0 || isRecord(value);
3060
+ }
3061
+ function isOptionalBoolean(value) {
3062
+ return value === void 0 || typeof value === "boolean";
3063
+ }
3064
+ function isOptionalString(value) {
3065
+ return value === void 0 || typeof value === "string";
3066
+ }
3067
+ function isQueueEntryWire(value) {
3068
+ return isRecord(value) && isEvidenceIdentifier(value.id) && typeof value.status === "string";
3069
+ }
3070
+ function isRecordLocalRequest(value) {
3071
+ return isRecord(value) && hasOnlyKeys2(value, ["v", "meshId", "kind", "nodeId", "sessionId", "providerType", "taskId", "payload"]) && value.v === TURN_IPC_PROTOCOL_VERSION && isEvidenceIdentifier(value.meshId) && isEvidenceIdentifier(value.kind) && isOptionalId2(value.nodeId) && isOptionalId2(value.sessionId) && isOptionalId2(value.providerType) && isOptionalId2(value.taskId) && isRecord(value.payload);
3072
+ }
3073
+ function decodeRecordLocalRequest(value) {
3074
+ return isRecordLocalRequest(value) ? value : null;
3075
+ }
3076
+ function isRecordLocalResponse(value) {
3077
+ return isRecord(value) && hasOnlyKeys2(value, ["eventId", "timestamp", "storedLocally", "published"]) && isEvidenceIdentifier(value.eventId) && typeof value.timestamp === "string" && typeof value.storedLocally === "boolean" && typeof value.published === "boolean";
3078
+ }
3079
+ function decodeRecordLocalResponse(value) {
3080
+ return isRecordLocalResponse(value) ? value : null;
3081
+ }
3082
+ function isQueueQueryRequest(value) {
3083
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "statuses", "taskId", "view", "withCounts", "historicalOlderThanMs", "withDependencyHeads"])) return false;
3084
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId)) return false;
3085
+ if (value.statuses !== void 0 && (!Array.isArray(value.statuses) || !value.statuses.every(isEvidenceIdentifier))) return false;
3086
+ if (value.historicalOlderThanMs !== void 0 && !isNonNegativeInt(value.historicalOlderThanMs)) return false;
3087
+ return isOptionalId2(value.taskId) && isOptionalBoolean(value.view) && isOptionalBoolean(value.withCounts) && isOptionalBoolean(value.withDependencyHeads);
3088
+ }
3089
+ function decodeQueueQueryRequest(value) {
3090
+ return isQueueQueryRequest(value) ? value : null;
3091
+ }
3092
+ function isQueueDependencyHeadWire(value) {
3093
+ return isRecord(value) && hasOnlyKeys2(value, ["id", "status", "blockedReason", "cancelReason"]) && typeof value.id === "string" && typeof value.status === "string" && (value.blockedReason === void 0 || typeof value.blockedReason === "string") && (value.cancelReason === void 0 || typeof value.cancelReason === "string");
3094
+ }
3095
+ function isQueueQueryResponse(value) {
3096
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["entries", "counts", "oldHistoricalCount", "dependencyHeads"])) return false;
3097
+ if (!Array.isArray(value.entries) || !value.entries.every(isQueueEntryWire)) return false;
3098
+ if (value.counts !== void 0 && (!isRecord(value.counts) || !Object.values(value.counts).every(isNonNegativeInt))) return false;
3099
+ if (value.oldHistoricalCount !== void 0 && !isNonNegativeInt(value.oldHistoricalCount)) return false;
3100
+ if (value.dependencyHeads !== void 0 && (!Array.isArray(value.dependencyHeads) || !value.dependencyHeads.every(isQueueDependencyHeadWire))) return false;
3101
+ return true;
3102
+ }
3103
+ function decodeQueueQueryResponse(value) {
3104
+ return isQueueQueryResponse(value) ? value : null;
3105
+ }
3106
+ function isQueueEnqueueRequest(value) {
3107
+ return isRecord(value) && hasOnlyKeys2(value, ["v", "meshId", "message", "options", "decision"]) && value.v === TURN_IPC_PROTOCOL_VERSION && isEvidenceIdentifier(value.meshId) && typeof value.message === "string" && isOptionalRecord(value.options) && isOptionalRecord(value.decision);
3108
+ }
3109
+ function decodeQueueEnqueueRequest(value) {
3110
+ return isQueueEnqueueRequest(value) ? value : null;
3111
+ }
3112
+ function isQueueEnqueueResponse(value) {
3113
+ return isRecord(value) && hasOnlyKeys2(value, ["entry"]) && isQueueEntryWire(value.entry);
3114
+ }
3115
+ function decodeQueueEnqueueResponse(value) {
3116
+ return isQueueEnqueueResponse(value) ? value : null;
3117
+ }
3118
+ function isQueueEnqueueGraphRequest(value) {
3119
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "mode", "specs", "plan", "audit"])) return false;
3120
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId)) return false;
3121
+ if (value.mode === "compat") return isRecordArray(value.specs) && value.plan === void 0 && isOptionalRecord(value.audit);
3122
+ if (value.mode === "graph") return isRecord(value.plan) && value.specs === void 0 && isOptionalRecord(value.audit);
3123
+ return false;
3124
+ }
3125
+ function decodeQueueEnqueueGraphRequest(value) {
3126
+ return isQueueEnqueueGraphRequest(value) ? value : null;
3127
+ }
3128
+ function isQueueEnqueueGraphResponse(value) {
3129
+ if (!isRecord(value)) return false;
3130
+ if (value.ok === true) {
3131
+ return hasOnlyKeys2(value, ["ok", "tasks", "graph"]) && Array.isArray(value.tasks) && value.tasks.every(isQueueEntryWire) && isOptionalRecord(value.graph);
3132
+ }
3133
+ if (value.ok === false) {
3134
+ return hasOnlyKeys2(value, ["ok", "refusalCode", "message", "extra"]) && typeof value.message === "string" && isOptionalString(value.refusalCode) && isOptionalRecord(value.extra);
3135
+ }
3136
+ return false;
3137
+ }
3138
+ function decodeQueueEnqueueGraphResponse(value) {
3139
+ return isQueueEnqueueGraphResponse(value) ? value : null;
3140
+ }
3141
+ function isQueueCancelRequest(value) {
3142
+ return isRecord(value) && hasOnlyKeys2(value, ["v", "meshId", "taskId", "reason"]) && value.v === TURN_IPC_PROTOCOL_VERSION && isEvidenceIdentifier(value.meshId) && isEvidenceIdentifier(value.taskId) && isOptionalString(value.reason);
3143
+ }
3144
+ function decodeQueueCancelRequest(value) {
3145
+ return isQueueCancelRequest(value) ? value : null;
3146
+ }
3147
+ function isQueueCancelResponse(value) {
3148
+ return isRecord(value) && hasOnlyKeys2(value, ["task", "before"]) && (value.task === null || isQueueEntryWire(value.task)) && (value.before === null || isQueueEntryWire(value.before));
3149
+ }
3150
+ function decodeQueueCancelResponse(value) {
3151
+ return isQueueCancelResponse(value) ? value : null;
3152
+ }
3153
+ function isQueueRequeueRequest(value) {
3154
+ return isRecord(value) && hasOnlyKeys2(value, ["v", "meshId", "taskId", "options"]) && value.v === TURN_IPC_PROTOCOL_VERSION && isEvidenceIdentifier(value.meshId) && isEvidenceIdentifier(value.taskId) && isOptionalRecord(value.options);
3155
+ }
3156
+ function decodeQueueRequeueRequest(value) {
3157
+ return isQueueRequeueRequest(value) ? value : null;
3158
+ }
3159
+ function isQueueRequeueResponse(value) {
3160
+ return isRecord(value) && hasOnlyKeys2(value, ["task"]) && (value.task === null || isQueueEntryWire(value.task));
3161
+ }
3162
+ function decodeQueueRequeueResponse(value) {
3163
+ return isQueueRequeueResponse(value) ? value : null;
3164
+ }
3165
+ function isDirectDispatchRecordRequest(value) {
3166
+ return isRecord(value) && hasOnlyKeys2(value, ["v", "meshId", "taskId", "message", "task", "decision"]) && value.v === TURN_IPC_PROTOCOL_VERSION && isEvidenceIdentifier(value.meshId) && isEvidenceIdentifier(value.taskId) && typeof value.message === "string" && isOptionalRecord(value.task) && isOptionalRecord(value.decision);
3167
+ }
3168
+ function decodeDirectDispatchRecordRequest(value) {
3169
+ return isDirectDispatchRecordRequest(value) ? value : null;
3170
+ }
3171
+ function isDirectDispatchRecordResponse(value) {
3172
+ return isRecord(value) && hasOnlyKeys2(value, ["taskRecorded", "decisionRecorded"]) && typeof value.taskRecorded === "boolean" && typeof value.decisionRecorded === "boolean";
3173
+ }
3174
+ function decodeDirectDispatchRecordResponse(value) {
3175
+ return isDirectDispatchRecordResponse(value) ? value : null;
3176
+ }
3177
+ var GRAPH_AUDIT_EVENTS = ["gate_claimed", "gate_released", "gate_abandoned", "node_patched"];
3178
+ var isGraphAuditEvent = makeGuard3(GRAPH_AUDIT_EVENTS);
3179
+ function isGraphAuditRecordRequest(value) {
3180
+ return isRecord(value) && hasOnlyKeys2(value, ["v", "meshId", "event", "fields"]) && value.v === TURN_IPC_PROTOCOL_VERSION && isEvidenceIdentifier(value.meshId) && isGraphAuditEvent(value.event) && isRecord(value.fields);
3181
+ }
3182
+ function decodeGraphAuditRecordRequest(value) {
3183
+ return isGraphAuditRecordRequest(value) ? value : null;
3184
+ }
3185
+ function isGraphAuditRecordResponse(value) {
3186
+ return isRecord(value) && hasOnlyKeys2(value, ["recorded"]) && typeof value.recorded === "boolean";
3187
+ }
3188
+ function decodeGraphAuditRecordResponse(value) {
3189
+ return isGraphAuditRecordResponse(value) ? value : null;
3190
+ }
3191
+ function isActiveWorkQueryRequest(value) {
3192
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "nodes", "queue", "recordTail", "includeTerminalDirect", "compute", "includeInputs", "includeSummary", "includeSchedulingRuntime", "mesh"])) return false;
3193
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId)) return false;
3194
+ if (value.nodes !== void 0 && !isRecordArray(value.nodes)) return false;
3195
+ if (value.queue !== void 0 && !isRecordArray(value.queue)) return false;
3196
+ if (value.recordTail !== void 0 && !isNonNegativeInt(value.recordTail)) return false;
3197
+ return isOptionalBoolean(value.includeTerminalDirect) && isOptionalBoolean(value.compute) && isOptionalBoolean(value.includeInputs) && isOptionalBoolean(value.includeSummary) && isOptionalBoolean(value.includeSchedulingRuntime) && isOptionalRecord(value.mesh);
3198
+ }
3199
+ function decodeActiveWorkQueryRequest(value) {
3200
+ return isActiveWorkQueryRequest(value) ? value : null;
3201
+ }
3202
+ function isActiveWorkQueryResponse(value) {
3203
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["activeWork", "records", "directDispatches", "summary", "schedulingRuntime"])) return false;
3204
+ if (value.records !== void 0 && !isRecordArray(value.records)) return false;
3205
+ if (value.directDispatches !== void 0 && !isRecordArray(value.directDispatches)) return false;
3206
+ return isOptionalRecord(value.activeWork) && isOptionalRecord(value.summary) && isOptionalRecord(value.schedulingRuntime);
3207
+ }
3208
+ function decodeActiveWorkQueryResponse(value) {
3209
+ return isActiveWorkQueryResponse(value) ? value : null;
3210
+ }
3211
+ function isRecoveryContextQueryRequest(value) {
3212
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "nodeId", "sessionId", "maxRetries", "nodeIds"])) return false;
3213
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId)) return false;
3214
+ if (!isOptionalId2(value.nodeId) || !isOptionalId2(value.sessionId)) return false;
3215
+ if (value.maxRetries !== void 0 && !isNonNegativeInt(value.maxRetries)) return false;
3216
+ if (value.nodeIds !== void 0) {
3217
+ if (!Array.isArray(value.nodeIds) || value.nodeIds.length === 0 || !value.nodeIds.every(isEvidenceIdentifier)) return false;
3218
+ return value.nodeId === void 0 && value.sessionId === void 0;
3219
+ }
3220
+ return value.nodeId !== void 0 || value.sessionId !== void 0;
3221
+ }
3222
+ function decodeRecoveryContextQueryRequest(value) {
3223
+ return isRecoveryContextQueryRequest(value) ? value : null;
3224
+ }
3225
+ function isRecoveryContextWire(value) {
3226
+ return isRecord(value) && typeof value.consecutiveNodeFailures === "number";
3227
+ }
3228
+ function isRecoveryContextQueryResponse(value) {
3229
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["context", "contexts"])) return false;
3230
+ if (value.context === void 0 && value.contexts === void 0) return false;
3231
+ if (value.context !== void 0 && !isRecoveryContextWire(value.context)) return false;
3232
+ if (value.contexts !== void 0 && (!isRecord(value.contexts) || !Object.values(value.contexts).every(isRecoveryContextWire))) return false;
3233
+ return true;
3234
+ }
3235
+ function decodeRecoveryContextQueryResponse(value) {
3236
+ return isRecoveryContextQueryResponse(value) ? value : null;
3237
+ }
3238
+ function isGraphGateClaimRequest(value) {
3239
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "gateId", "coordinatorSessionId", "leaseSeconds", "extendDeadlineSeconds", "probeConvergenceEvidence"])) return false;
3240
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId) || !isEvidenceIdentifier(value.gateId) || !isEvidenceIdentifier(value.coordinatorSessionId)) return false;
3241
+ if (value.leaseSeconds !== void 0 && !isFiniteNumber3(value.leaseSeconds)) return false;
3242
+ if (value.extendDeadlineSeconds !== void 0 && !isFiniteNumber3(value.extendDeadlineSeconds)) return false;
3243
+ return isOptionalBoolean(value.probeConvergenceEvidence);
3244
+ }
3245
+ function decodeGraphGateClaimRequest(value) {
3246
+ return isGraphGateClaimRequest(value) ? value : null;
3247
+ }
3248
+ function isGraphGateClaimResponse(value) {
3249
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["claimed", "reason", "gate", "leaseGeneration", "fencingToken", "leaseExpiresAt", "deadlineAt", "ambiguousExternalOutcome", "previousLeaseOwnerSessionId", "convergenceEvidence"])) return false;
3250
+ if (typeof value.claimed !== "boolean") return false;
3251
+ return isOptionalRecord(value.gate) && isOptionalRecord(value.convergenceEvidence) && isOptionalBoolean(value.ambiguousExternalOutcome);
3252
+ }
3253
+ function decodeGraphGateClaimResponse(value) {
3254
+ return isGraphGateClaimResponse(value) ? value : null;
3255
+ }
3256
+ function isGraphGateReleaseRequest(value) {
3257
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "gateId", "fencingToken", "leaseGeneration", "idempotencyKey", "outcome", "result", "evidence", "patches"])) return false;
3258
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId) || !isEvidenceIdentifier(value.gateId)) return false;
3259
+ if (typeof value.fencingToken !== "string" || !value.fencingToken) return false;
3260
+ if (!isFiniteNumber3(value.leaseGeneration)) return false;
3261
+ if (typeof value.idempotencyKey !== "string" || !value.idempotencyKey) return false;
3262
+ if (typeof value.outcome !== "string" || !value.outcome) return false;
3263
+ if (value.patches !== void 0) {
3264
+ if (!Array.isArray(value.patches)) return false;
3265
+ for (const p of value.patches) {
3266
+ if (!isRecord(p) || typeof p.node !== "string" || !p.node || !isRecord(p.baseSpecPatch)) return false;
3267
+ }
3268
+ }
3269
+ return true;
3270
+ }
3271
+ function decodeGraphGateReleaseRequest(value) {
3272
+ return isGraphGateReleaseRequest(value) ? value : null;
3273
+ }
3274
+ function isGraphGateReleaseResponse(value) {
3275
+ if (!isRecord(value)) return false;
3276
+ if (value.released === true) {
3277
+ if (!hasOnlyKeys2(value, ["released", "duplicate", "gate", "materializedNodeIds", "downstreamNodeCount", "graphCompleted"])) return false;
3278
+ if (typeof value.duplicate !== "boolean") return false;
3279
+ if (!Array.isArray(value.materializedNodeIds) || !value.materializedNodeIds.every((n) => typeof n === "string")) return false;
3280
+ if (value.downstreamNodeCount !== void 0 && !isNonNegativeInt(value.downstreamNodeCount)) return false;
3281
+ return isOptionalRecord(value.gate) && isOptionalBoolean(value.graphCompleted);
3282
+ }
3283
+ if (value.released === false) {
3284
+ return hasOnlyKeys2(value, ["released", "refusalCode", "message"]) && typeof value.message === "string" && isOptionalString(value.refusalCode);
3285
+ }
3286
+ return false;
3287
+ }
3288
+ function decodeGraphGateReleaseResponse(value) {
3289
+ return isGraphGateReleaseResponse(value) ? value : null;
3290
+ }
3291
+ function isGraphGateAbandonRequest(value) {
3292
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "gateId", "reason", "coordinatorSessionId", "force"])) return false;
3293
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId) || !isEvidenceIdentifier(value.gateId)) return false;
3294
+ if (typeof value.reason !== "string" || !value.reason) return false;
3295
+ if (value.coordinatorSessionId !== void 0 && !isEvidenceIdentifier(value.coordinatorSessionId)) return false;
3296
+ return isOptionalBoolean(value.force);
3297
+ }
3298
+ function decodeGraphGateAbandonRequest(value) {
3299
+ return isGraphGateAbandonRequest(value) ? value : null;
3300
+ }
3301
+ function isGraphGateAbandonResponse(value) {
3302
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["abandoned", "reason", "gate", "cancelledNodeIds", "cancelledTaskIds", "graphStatus"])) return false;
3303
+ if (typeof value.abandoned !== "boolean") return false;
3304
+ if (!Array.isArray(value.cancelledNodeIds) || !value.cancelledNodeIds.every((n) => typeof n === "string")) return false;
3305
+ if (!Array.isArray(value.cancelledTaskIds) || !value.cancelledTaskIds.every((n) => typeof n === "string")) return false;
3306
+ return isOptionalRecord(value.gate);
3307
+ }
3308
+ function decodeGraphGateAbandonResponse(value) {
3309
+ return isGraphGateAbandonResponse(value) ? value : null;
3310
+ }
3311
+ function isGraphNodePatchRequest(value) {
3312
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "node", "graphId", "baseSpecPatch"])) return false;
3313
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId)) return false;
3314
+ if (typeof value.node !== "string" || !value.node) return false;
3315
+ if (value.graphId !== void 0 && !isEvidenceIdentifier(value.graphId)) return false;
3316
+ return isRecord(value.baseSpecPatch) && Object.keys(value.baseSpecPatch).length > 0;
3317
+ }
3318
+ function decodeGraphNodePatchRequest(value) {
3319
+ return isGraphNodePatchRequest(value) ? value : null;
3320
+ }
3321
+ function isGraphNodePatchResponse(value) {
3322
+ if (!isRecord(value)) return false;
3323
+ if (value.patched === true) {
3324
+ if (!hasOnlyKeys2(value, ["patched", "graphId", "nodeId", "ref", "queueTaskId", "materializationVersion", "state", "outcomeKind", "skippedReason", "blockedReason"])) return false;
3325
+ if (!isEvidenceIdentifier(value.graphId) || !isEvidenceIdentifier(value.nodeId)) return false;
3326
+ if (!isNonNegativeInt(value.materializationVersion)) return false;
3327
+ return typeof value.state === "string" && typeof value.outcomeKind === "string";
3328
+ }
3329
+ if (value.patched === false) {
3330
+ return hasOnlyKeys2(value, ["patched", "refusalCode", "message"]) && typeof value.message === "string" && isOptionalString(value.refusalCode);
3331
+ }
3332
+ return false;
3333
+ }
3334
+ function decodeGraphNodePatchResponse(value) {
3335
+ return isGraphNodePatchResponse(value) ? value : null;
3336
+ }
3337
+ function isGraphViewQueryRequest(value) {
3338
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "graphId", "batchId", "activeOnly", "limit", "probeGateEvidence"])) return false;
3339
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId)) return false;
3340
+ if (value.graphId !== void 0 && !isEvidenceIdentifier(value.graphId)) return false;
3341
+ if (value.batchId !== void 0 && !isEvidenceIdentifier(value.batchId)) return false;
3342
+ if (value.limit !== void 0 && !isNonNegativeInt(value.limit)) return false;
3343
+ return isOptionalBoolean(value.activeOnly) && isOptionalBoolean(value.probeGateEvidence);
3344
+ }
3345
+ function decodeGraphViewQueryRequest(value) {
3346
+ return isGraphViewQueryRequest(value) ? value : null;
3347
+ }
3348
+ function isGraphViewQueryResponse(value) {
3349
+ return isRecord(value) && hasOnlyKeys2(value, ["graphs"]) && isRecordArray(value.graphs);
3350
+ }
3351
+ function decodeGraphViewQueryResponse(value) {
3352
+ return isGraphViewQueryResponse(value) ? value : null;
3353
+ }
3354
+ function isTaskStatsQueryRequest(value) {
3355
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "taskIds", "missionId", "tail", "rollup", "missionIds"])) return false;
3356
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId)) return false;
3357
+ if (value.taskIds !== void 0) {
3358
+ if (!Array.isArray(value.taskIds) || value.taskIds.length === 0 || !value.taskIds.every(isEvidenceIdentifier)) return false;
3359
+ }
3360
+ if (value.missionId !== void 0 && !isEvidenceIdentifier(value.missionId)) return false;
3361
+ if (value.tail !== void 0 && !isNonNegativeInt(value.tail)) return false;
3362
+ if (value.missionIds !== void 0) {
3363
+ if (!Array.isArray(value.missionIds) || value.missionIds.length === 0 || !value.missionIds.every(isEvidenceIdentifier)) return false;
3364
+ if (value.taskIds !== void 0 || value.missionId !== void 0) return false;
3365
+ }
3366
+ if (value.rollup === true && value.missionId === void 0) return false;
3367
+ return isOptionalBoolean(value.rollup);
3368
+ }
3369
+ function decodeTaskStatsQueryRequest(value) {
3370
+ return isTaskStatsQueryRequest(value) ? value : null;
3371
+ }
3372
+ function isTaskStatsQueryResponse(value) {
3373
+ return isRecord(value) && hasOnlyKeys2(value, ["tasks", "mission", "missions"]) && isRecordArray(value.tasks) && isOptionalRecord(value.mission) && (value.missions === void 0 || isRecord(value.missions) && Object.values(value.missions).every(isRecord));
3374
+ }
3375
+ function decodeTaskStatsQueryResponse(value) {
3376
+ return isTaskStatsQueryResponse(value) ? value : null;
3377
+ }
3378
+ function isPruneStaleDirectRequest(value) {
3379
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "execute", "includeTerminal", "source"])) return false;
3380
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId)) return false;
3381
+ if (value.source !== void 0 && typeof value.source !== "string") return false;
3382
+ return isOptionalBoolean(value.execute) && isOptionalBoolean(value.includeTerminal);
3383
+ }
3384
+ function decodePruneStaleDirectRequest(value) {
3385
+ return isPruneStaleDirectRequest(value) ? value : null;
3386
+ }
3387
+ function isPruneStaleDirectResponse(value) {
3388
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["mode", "includeTerminal", "candidateCount", "prunable", "prunedCount", "preservedUnacknowledged", "preservedLedgerOnly", "preservedNotOrphan"])) return false;
3389
+ if (value.mode !== "execute" && value.mode !== "dry_run") return false;
3390
+ if (typeof value.includeTerminal !== "boolean") return false;
3391
+ if (!isNonNegativeInt(value.candidateCount) || !isNonNegativeInt(value.prunedCount)) return false;
3392
+ return isRecordArray(value.prunable) && isRecordArray(value.preservedUnacknowledged) && isRecordArray(value.preservedLedgerOnly) && isRecordArray(value.preservedNotOrphan);
3393
+ }
3394
+ function decodePruneStaleDirectResponse(value) {
3395
+ return isPruneStaleDirectResponse(value) ? value : null;
3396
+ }
3397
+ function isOrphanedPinnedTaskWire(value) {
3398
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["taskId", "title", "targetSessionId", "targetNodeId", "missionId"])) return false;
3399
+ if (!isEvidenceIdentifier(value.taskId) || !isEvidenceIdentifier(value.targetSessionId)) return false;
3400
+ if (typeof value.title !== "string") return false;
3401
+ if (value.targetNodeId !== void 0 && !isEvidenceIdentifier(value.targetNodeId)) return false;
3402
+ return value.missionId === void 0 || isEvidenceIdentifier(value.missionId);
3403
+ }
3404
+ function isOrphanedPinNotifyRequest(value) {
3405
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "stoppedSessionId", "excludeTaskId", "cause", "nodeId", "coordinatorSessionId"])) return false;
3406
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId) || !isEvidenceIdentifier(value.stoppedSessionId)) return false;
3407
+ if (value.excludeTaskId !== void 0 && !isEvidenceIdentifier(value.excludeTaskId)) return false;
3408
+ if (value.cause !== void 0 && typeof value.cause !== "string") return false;
3409
+ if (value.nodeId !== void 0 && !isEvidenceIdentifier(value.nodeId)) return false;
3410
+ return value.coordinatorSessionId === void 0 || isEvidenceIdentifier(value.coordinatorSessionId);
3411
+ }
3412
+ function decodeOrphanedPinNotifyRequest(value) {
3413
+ return isOrphanedPinNotifyRequest(value) ? value : null;
3414
+ }
3415
+ function isOrphanedPinNotifyResponse(value) {
3416
+ return isRecord(value) && hasOnlyKeys2(value, ["orphans"]) && Array.isArray(value.orphans) && value.orphans.every(isOrphanedPinnedTaskWire);
3417
+ }
3418
+ function decodeOrphanedPinNotifyResponse(value) {
3419
+ return isOrphanedPinNotifyResponse(value) ? value : null;
3420
+ }
3421
+ var TURN_IPC_COMMANDS = [
3422
+ "turn_observe",
3423
+ "mesh_record",
3424
+ "turn_cancel",
3425
+ "operator_status",
3426
+ "turn_query",
3427
+ "mesh_index_query",
3428
+ "mission_upsert",
3429
+ "mission_query",
3430
+ "note_upsert",
3431
+ "note_forget",
3432
+ // C-W9b additions (2026-09-24 14:00 stamp "C-W9"):
3433
+ "tool_call_record",
3434
+ "ledger_query",
3435
+ "mission_list_query",
3436
+ // C-W9a additions (the event ledger retired; the queue behind IPC):
3437
+ "record_local",
3438
+ "queue_query",
3439
+ "queue_enqueue",
3440
+ "queue_enqueue_graph",
3441
+ "queue_cancel",
3442
+ "queue_requeue",
3443
+ "direct_dispatch_record",
3444
+ "graph_audit_record",
3445
+ "active_work_query",
3446
+ "recovery_context_query",
3447
+ // C-W9c additions (2026-09-24 19:00 stamp — the last mcp-server in-process
3448
+ // daemon-core paths: graph gates/plan/patch, mission reads (MAGI), task/
3449
+ // mission stats, orphaned-pin helpers, one prune audit):
3450
+ "graph_gate_claim",
3451
+ "graph_gate_release",
3452
+ "graph_gate_abandon",
3453
+ "graph_node_patch",
3454
+ "graph_view_query",
3455
+ "task_stats_query",
3456
+ "prune_stale_direct",
3457
+ "orphaned_pin_notify"
3458
+ ];
3459
+ var isTurnIpcCommand = makeGuard3(TURN_IPC_COMMANDS);
3460
+
3461
+ // src/path-ownership.ts
3462
+ var MAX_OWNED_PATHS = 64;
3463
+ function toPosix(raw) {
3464
+ return raw.replace(/\\/g, "/");
3465
+ }
3466
+ function normalizeOne(raw, rejected) {
3467
+ if (typeof raw !== "string") {
3468
+ rejected.push({ input: String(raw), reason: "not_a_string" });
3469
+ return null;
3470
+ }
3471
+ const trimmed = raw.trim();
3472
+ if (!trimmed) {
3473
+ rejected.push({ input: raw, reason: "empty" });
3474
+ return null;
3475
+ }
3476
+ let posix = toPosix(trimmed);
3477
+ if (posix.startsWith("/") || /^[a-zA-Z]:\//.test(posix) || posix.startsWith("~")) {
3478
+ rejected.push({ input: raw, reason: "absolute_path" });
3479
+ return null;
3480
+ }
3481
+ posix = posix.replace(/^\.\/+/, "");
3482
+ const segments = posix.split("/").filter(Boolean);
3483
+ if (segments.some((seg) => seg === "..")) {
3484
+ rejected.push({ input: raw, reason: "parent_traversal" });
3485
+ return null;
3486
+ }
3487
+ if (segments.length === 0) {
3488
+ rejected.push({ input: raw, reason: "empty" });
3489
+ return null;
3490
+ }
3491
+ let subtree = false;
3492
+ if (segments[segments.length - 1] === "**") {
3493
+ subtree = true;
3494
+ segments.pop();
3495
+ if (segments.length === 0) {
3496
+ }
3497
+ }
3498
+ if (segments.some((seg) => seg.includes("*") || seg.includes("?"))) {
3499
+ rejected.push({ input: raw, reason: "unsupported_glob" });
3500
+ return null;
3501
+ }
3502
+ return { path: segments.join("/"), subtree };
3503
+ }
3504
+ function normalizeOwnedPaths(input) {
3505
+ const rejected = [];
3506
+ if (input === void 0 || input === null) {
3507
+ return { declaration: { paths: [] }, rejected };
3508
+ }
3509
+ if (!Array.isArray(input)) {
3510
+ return { declaration: { paths: [] }, rejected: [{ input: String(input), reason: "not_an_array" }] };
3511
+ }
3512
+ const byPath = /* @__PURE__ */ new Map();
3513
+ for (const raw of input) {
3514
+ const entry = normalizeOne(raw, rejected);
3515
+ if (!entry) continue;
3516
+ const existing = byPath.get(entry.path);
3517
+ if (!existing) {
3518
+ byPath.set(entry.path, entry);
3519
+ } else if (entry.subtree && !existing.subtree) {
3520
+ byPath.set(entry.path, entry);
3521
+ }
3522
+ }
3523
+ const all = [...byPath.values()];
3524
+ const kept = all.slice(0, MAX_OWNED_PATHS);
3525
+ for (const dropped of all.slice(MAX_OWNED_PATHS)) {
3526
+ rejected.push({ input: dropped.path, reason: "over_cap" });
3527
+ }
3528
+ return { declaration: { paths: kept }, rejected };
3529
+ }
3530
+ function entryContains(base, path) {
3531
+ if (path === base.path) return true;
3532
+ if (base.subtree && (path === base.path || path.startsWith(`${base.path}/`))) return true;
3533
+ return false;
3534
+ }
3535
+ function entriesOverlap(a, b) {
3536
+ if (a.path === b.path) return true;
3537
+ if (a.subtree && (b.path === a.path || b.path.startsWith(`${a.path}/`))) return true;
3538
+ if (b.subtree && (a.path === b.path || a.path.startsWith(`${b.path}/`))) return true;
3539
+ return false;
3540
+ }
3541
+ function pathsOverlap(a, b) {
3542
+ if (a.paths.length === 0 || b.paths.length === 0) return false;
3543
+ for (const pa of a.paths) {
3544
+ for (const pb of b.paths) {
3545
+ if (entriesOverlap(pa, pb)) return true;
3546
+ }
3547
+ }
3548
+ return false;
3549
+ }
3550
+ function findOwnershipConflicts(candidate, inFlight) {
3551
+ if (candidate.paths.length === 0) return [];
3552
+ const conflicts = [];
3553
+ for (const other of inFlight) {
3554
+ if (other.paths.paths.length === 0) continue;
3555
+ const overlappingPaths = [];
3556
+ for (const pa of candidate.paths) {
3557
+ for (const pb of other.paths.paths) {
3558
+ if (entriesOverlap(pa, pb)) {
3559
+ const narrower = pa.path.length >= pb.path.length ? pa.path : pb.path;
3560
+ if (!overlappingPaths.includes(narrower)) overlappingPaths.push(narrower);
3561
+ }
3562
+ }
3563
+ }
3564
+ if (overlappingPaths.length > 0) {
3565
+ conflicts.push({ taskId: other.taskId, overlappingPaths });
3566
+ }
3567
+ }
3568
+ return conflicts;
3569
+ }
3570
+ function touchedFilesOutsideOwnership(touched, owned) {
3571
+ const undeclaredTouched = [];
3572
+ const usedDeclarations = /* @__PURE__ */ new Set();
3573
+ for (const raw of touched ?? []) {
3574
+ const rejectedSink = [];
3575
+ const entry = normalizeOne(raw, rejectedSink);
3576
+ if (!entry) {
3577
+ undeclaredTouched.push(raw);
3578
+ continue;
3579
+ }
3580
+ const matches = owned.paths.filter((base) => entryContains(base, entry.path));
3581
+ if (matches.length === 0) {
3582
+ undeclaredTouched.push(entry.path);
3583
+ } else {
3584
+ for (const m of matches) usedDeclarations.add(m.path);
3585
+ }
3586
+ }
3587
+ const unusedDeclarations = owned.paths.map((p) => p.path).filter((p) => !usedDeclarations.has(p));
3588
+ return { undeclaredTouched, unusedDeclarations };
3589
+ }
3590
+
3591
+ // src/keyed-doc-delta.ts
3592
+ function sig(value) {
3593
+ if (value === void 0) return void 0;
3594
+ try {
3595
+ return JSON.stringify(value);
3596
+ } catch {
3597
+ return void 0;
3598
+ }
3599
+ }
3600
+ function isRecord3(value) {
3601
+ return !!value && typeof value === "object" && !Array.isArray(value);
3602
+ }
3603
+ function readPath(doc, path) {
3604
+ const [head, tail] = splitPath(path);
3605
+ if (!tail) return doc[head];
3606
+ const parent = doc[head];
3607
+ return isRecord3(parent) ? parent[tail] : void 0;
3608
+ }
3609
+ function splitPath(path) {
3610
+ const dot = path.indexOf(".");
3611
+ return dot < 0 ? [path, void 0] : [path.slice(0, dot), path.slice(dot + 1)];
3612
+ }
3613
+ function stripCollections(doc, spec) {
3614
+ const out = { ...doc };
3615
+ for (const path of Object.keys(spec.collections)) {
3616
+ const [head, tail] = splitPath(path);
3617
+ if (!tail) {
3618
+ delete out[head];
3619
+ continue;
3620
+ }
3621
+ const parent = out[head];
3622
+ if (!isRecord3(parent) || !(tail in parent)) continue;
3623
+ const copy = { ...parent };
3624
+ delete copy[tail];
3625
+ out[head] = copy;
3626
+ }
3627
+ return out;
3628
+ }
3629
+ function fieldSigsOf(digest) {
3630
+ if (!digest.fieldSigs) {
3631
+ const sigs = /* @__PURE__ */ new Map();
3632
+ for (const [key, value] of Object.entries(digest.stable)) {
3633
+ const s = sig(value);
3634
+ if (s !== void 0) sigs.set(key, s);
3635
+ }
3636
+ digest.fieldSigs = sigs;
3637
+ }
3638
+ return digest.fieldSigs;
3639
+ }
3640
+ function digestKeyedDoc(doc, spec) {
3641
+ const top = /* @__PURE__ */ new Map();
3642
+ const topValues = {};
3643
+ const ignore = new Set(spec.ignore ?? []);
3644
+ const split = new Set(spec.splitObjects ?? []);
3645
+ const add = (path, value) => {
3646
+ if (ignore.has(path)) return;
3647
+ const s = sig(value);
3648
+ if (s === void 0) return;
3649
+ top.set(path, s);
3650
+ topValues[path] = value;
3651
+ };
3652
+ for (const [key, value] of Object.entries(stripCollections(doc, spec))) {
3653
+ if (split.has(key) && isRecord3(value)) {
3654
+ for (const [field, fieldValue] of Object.entries(value)) add(`${key}.${field}`, fieldValue);
3655
+ continue;
3656
+ }
3657
+ add(key, value);
3658
+ }
3659
+ const collections = /* @__PURE__ */ new Map();
3660
+ for (const [path, idField] of Object.entries(spec.collections)) {
3661
+ const list = readPath(doc, path);
3662
+ if (!Array.isArray(list)) continue;
3663
+ const rows = /* @__PURE__ */ new Map();
3664
+ const order = [];
3665
+ for (const row of list) {
3666
+ if (!isRecord3(row)) continue;
3667
+ const id2 = row[idField];
3668
+ if (typeof id2 !== "string" || !id2 || rows.has(id2)) continue;
3669
+ const stable = spec.stableRow ? spec.stableRow(path, row) : row;
3670
+ rows.set(id2, { value: row, stable, sig: sig(stable) ?? "" });
3671
+ order.push(id2);
3672
+ }
3673
+ collections.set(path, { rows, order });
3674
+ }
3675
+ return { top, topValues, collections, volatile: new Set(spec.volatileTopLevel ?? []) };
3676
+ }
3677
+ function sameOrder(a, b) {
3678
+ if (a.length !== b.length) return false;
3679
+ for (let i = 0; i < a.length; i += 1) if (a[i] !== b[i]) return false;
3680
+ return true;
3681
+ }
3682
+ function diffCollection(prev, next, idField) {
3683
+ if (!next) return prev ? { absent: true } : null;
3684
+ const delta = {};
3685
+ const prevRows = prev?.rows ?? /* @__PURE__ */ new Map();
3686
+ const nextRows = next?.rows ?? /* @__PURE__ */ new Map();
3687
+ for (const [id2, nextRow] of nextRows) {
3688
+ const prevRow = prevRows.get(id2);
3689
+ if (!prevRow) {
3690
+ ;
3691
+ (delta.upsert ??= []).push(nextRow.value);
3692
+ continue;
3693
+ }
3694
+ if (prevRow.sig === nextRow.sig) continue;
3695
+ const prevSigs = fieldSigsOf(prevRow);
3696
+ const nextSigs = fieldSigsOf(nextRow);
3697
+ const change = { [idField]: id2 };
3698
+ let changed = false;
3699
+ for (const [key, s] of nextSigs) {
3700
+ if (key === idField || prevSigs.get(key) === s) continue;
3701
+ change[key] = nextRow.value[key];
3702
+ changed = true;
3703
+ }
3704
+ if (changed) {
3705
+ for (const [key, value] of Object.entries(nextRow.value)) {
3706
+ if (key in nextRow.stable || key in change) continue;
3707
+ if (sig(prevRow.value[key]) !== sig(value)) change[key] = value;
3708
+ }
3709
+ }
3710
+ const gone = [];
3711
+ for (const key of prevSigs.keys()) if (!nextSigs.has(key) && !(key in nextRow.value)) gone.push(key);
3712
+ if (changed) (delta.upsert ??= []).push(change);
3713
+ if (gone.length > 0) (delta.unsetFields ??= {})[id2] = gone;
3714
+ }
3715
+ for (const id2 of prevRows.keys()) {
3716
+ if (!nextRows.has(id2)) (delta.removed ??= []).push(id2);
3717
+ }
3718
+ if (!sameOrder(prev?.order ?? [], next?.order ?? [])) delta.order = [...next?.order ?? []];
3719
+ return Object.keys(delta).length > 0 ? delta : null;
3720
+ }
3721
+ function diffKeyedDoc(prev, next, spec) {
3722
+ const delta = {};
3723
+ let meaningful = false;
3724
+ let set;
3725
+ let unset;
3726
+ const split = spec.splitObjects ?? [];
3727
+ const objectOf = (path) => {
3728
+ for (const object of split) {
3729
+ if (path.startsWith(`${object}.`)) return [object, path.slice(object.length + 1)];
3730
+ }
3731
+ return null;
3732
+ };
3733
+ const objects = {};
3734
+ for (const [path, s] of next.top) {
3735
+ if (prev.top.get(path) === s) continue;
3736
+ const inObject = objectOf(path);
3737
+ if (inObject) ((objects[inObject[0]] ??= {}).set ??= {})[inObject[1]] = next.topValues[path];
3738
+ else (set ??= {})[path] = next.topValues[path];
3739
+ if (!next.volatile.has(path)) meaningful = true;
3740
+ }
3741
+ for (const path of prev.top.keys()) {
3742
+ if (next.top.has(path)) continue;
3743
+ const inObject = objectOf(path);
3744
+ if (inObject) ((objects[inObject[0]] ??= {}).unset ??= []).push(inObject[1]);
3745
+ else (unset ??= []).push(path);
3746
+ if (!next.volatile.has(path)) meaningful = true;
3747
+ }
3748
+ for (const [path, idField] of Object.entries(spec.collections)) {
3749
+ const change = diffCollection(prev.collections.get(path), next.collections.get(path), idField);
3750
+ if (!change) continue;
3751
+ (delta.collections ??= {})[path] = change;
3752
+ meaningful = true;
3753
+ }
3754
+ if (!meaningful) return null;
3755
+ if (set) delta.set = set;
3756
+ if (unset) delta.unset = unset;
3757
+ if (Object.keys(objects).length > 0) delta.objects = objects;
3758
+ return delta;
3759
+ }
3760
+ function foldCollection(held, change, idField) {
3761
+ const byId = /* @__PURE__ */ new Map();
3762
+ const heldOrder = [];
3763
+ for (const row of Array.isArray(held) ? held : []) {
3764
+ if (!isRecord3(row) || typeof row[idField] !== "string") continue;
3765
+ byId.set(row[idField], row);
3766
+ heldOrder.push(row[idField]);
3767
+ }
3768
+ for (const id2 of change.removed ?? []) byId.delete(id2);
3769
+ for (const row of change.upsert ?? []) {
3770
+ const id2 = row[idField];
3771
+ if (typeof id2 !== "string") continue;
3772
+ const base = byId.get(id2);
3773
+ byId.set(id2, base ? { ...base, ...row } : { ...row });
3774
+ }
3775
+ for (const [id2, keys] of Object.entries(change.unsetFields ?? {})) {
3776
+ const base = byId.get(id2);
3777
+ if (!base) continue;
3778
+ const trimmed = { ...base };
3779
+ for (const key of keys) delete trimmed[key];
3780
+ byId.set(id2, trimmed);
3781
+ }
3782
+ const order = change.order ?? heldOrder;
3783
+ const out = [];
3784
+ const placed = /* @__PURE__ */ new Set();
3785
+ for (const id2 of order) {
3786
+ const row = byId.get(id2);
3787
+ if (!row || placed.has(id2)) continue;
3788
+ out.push(row);
3789
+ placed.add(id2);
3790
+ }
3791
+ for (const [id2, row] of byId) if (!placed.has(id2)) out.push(row);
3792
+ return out;
3793
+ }
3794
+ function foldKeyedDoc(held, delta, spec) {
3795
+ const heldCollections = /* @__PURE__ */ new Map();
3796
+ for (const path of Object.keys(spec.collections)) heldCollections.set(path, readPath(held, path));
3797
+ const next = stripCollections(held, spec);
3798
+ for (const key of delta.unset ?? []) delete next[key];
3799
+ Object.assign(next, delta.set ?? {});
3800
+ for (const [object, change] of Object.entries(delta.objects ?? {})) {
3801
+ const folded = isRecord3(next[object]) ? { ...next[object] } : {};
3802
+ for (const key of change.unset ?? []) delete folded[key];
3803
+ Object.assign(folded, change.set ?? {});
3804
+ next[object] = folded;
3805
+ }
3806
+ for (const [path, idField] of Object.entries(spec.collections)) {
3807
+ const change = delta.collections?.[path];
3808
+ const heldList = heldCollections.get(path);
3809
+ if (change?.absent) {
3810
+ const [head2, tail2] = splitPath(path);
3811
+ if (!tail2) delete next[head2];
3812
+ continue;
3813
+ }
3814
+ if (!change && heldList === void 0) continue;
3815
+ const list = change ? foldCollection(heldList, change, idField) : heldList;
3816
+ const [head, tail] = splitPath(path);
3817
+ if (!tail) {
3818
+ next[head] = list;
3819
+ continue;
3820
+ }
3821
+ const parent = isRecord3(next[head]) ? { ...next[head] } : {};
3822
+ parent[tail] = list;
3823
+ next[head] = parent;
3824
+ }
3825
+ return next;
3826
+ }
3827
+ var DAEMON_METADATA_DOC_SPEC = {
3828
+ collections: { "status.sessions": "id" },
3829
+ splitObjects: ["status"],
3830
+ ignore: ["daemonId", "status.timestamp"],
3831
+ stableRow: (_collection, row) => {
3832
+ if (!("lastUpdated" in row)) return row;
3833
+ const { lastUpdated: _stamp, ...stable } = row;
3834
+ return stable;
3835
+ }
3836
+ };
3837
+ var MESH_STATUS_DOC_SPEC = {
3838
+ collections: { nodes: "nodeId", "queue.tasks": "id", missions: "id" },
3839
+ volatileTopLevel: [
3840
+ "refreshedAt",
3841
+ "sourceOfTruth",
3842
+ "turnPresentationCounters",
3843
+ "meshProtocolV2Counters",
3844
+ "pendingRetentionCounters",
3845
+ "meshProtocolMetrics"
3846
+ ],
3847
+ stableRow: (collection, row) => collection === "nodes" ? stableMeshNodeRow(row) : row
3848
+ };
3849
+ function without(value, keys) {
3850
+ if (!isRecord3(value)) return value;
3851
+ const out = { ...value };
3852
+ for (const key of keys) delete out[key];
3853
+ return out;
3854
+ }
3855
+ function stableMeshNodeRow(row) {
3856
+ const out = { ...row };
3857
+ delete out.lastSeenAt;
3858
+ delete out.updatedAt;
3859
+ delete out.last_seen_at;
3860
+ delete out.updated_at;
3861
+ if ("dataFreshness" in out) out.dataFreshness = without(out.dataFreshness, ["ageMs", "lastProbeAt", "staleness"]);
3862
+ if ("connection" in out) out.connection = without(out.connection, ["lastStateChangeAt"]);
3863
+ if ("git" in out) {
3864
+ const git = without(out.git, ["lastCheckedAt"]);
3865
+ if (isRecord3(git) && Array.isArray(git.submodules) && git.submodules.length === 0) delete git.submodules;
3866
+ out.git = git;
3867
+ }
3868
+ if ("nodeFacts" in out) out.nodeFacts = without(out.nodeFacts, ["reportedAt"]);
3869
+ const observation = out.gitObservation;
3870
+ if (isRecord3(observation) && (observation.source === "self" || observation.source === "local")) {
3871
+ out.gitObservation = without(observation, ["observedAt"]);
3872
+ }
3873
+ return out;
3874
+ }
1093
3875
  // Annotate the CommonJS export names for ESM import in node:
1094
3876
  0 && (module.exports = {
3877
+ CANCEL_REASONS,
1095
3878
  CANONICAL_MESH_TOOL_COUNT,
1096
3879
  CANONICAL_MESH_TOOL_NAMES,
1097
3880
  CLAUDE_TUI_REVIEW_PAGE_NOT_FOCUSED_PREFIX,
1098
3881
  CLAUDE_TUI_REVIEW_UNCONFIRMED_PREFIX,
1099
3882
  CLI_SLOT_RECIPES,
3883
+ COMMIT_STRENGTHS,
3884
+ CONSUME_PROFILES,
3885
+ COORDINATOR_ACK_OUTCOMES,
3886
+ DAEMON_METADATA_DOC_SPEC,
3887
+ DAEMON_P2P_SIGNAL_TYPES,
3888
+ DAEMON_STATUS_EVENT_NAMES,
3889
+ DAEMON_TO_DASHBOARD_P2P_TYPES,
3890
+ DAEMON_TO_SERVER_TYPES,
1100
3891
  DAEMON_TO_SERVER_WS_MSGS,
3892
+ DASHBOARD_P2P_MESSAGE_KINDS,
3893
+ DASHBOARD_P2P_SIGNAL_TYPES,
3894
+ DASHBOARD_STATUS_EVENT_NAMES,
3895
+ DASHBOARD_TO_DAEMON_P2P_TYPES,
3896
+ DASHBOARD_TO_USER_SESSION_TYPES,
3897
+ DASHBOARD_WIRE_VERSION,
1101
3898
  DEFAULT_DIFFICULTY_BRAINS,
3899
+ DELIVERY_OUTCOMES,
3900
+ DELIVERY_VIAS,
3901
+ DISPATCH_FAILURE_REASONS,
3902
+ EVIDENCE_ENVELOPE_FIELD_SPECS,
3903
+ EVIDENCE_SOURCE_IDS,
3904
+ GRAPH_AUDIT_EVENTS,
3905
+ HOLD_REASONS,
3906
+ LIVENESS_RESULTS,
1102
3907
  MAGI_RAW_ANSWER_CAP,
3908
+ MAX_MESH_RECORD_STRING,
3909
+ MAX_OWNED_PATHS,
1103
3910
  MESH_CHUNK_KIND,
1104
3911
  MESH_CHUNK_PAYLOAD_CHARS,
1105
3912
  MESH_CHUNK_TTL_MS,
3913
+ MESH_DELIVERY_MODES,
3914
+ MESH_INDEX_QUERY_WRITER_SCOPES,
1106
3915
  MESH_MAX_CHUNKS,
1107
3916
  MESH_MAX_INLINE_FRAME_BYTES,
1108
3917
  MESH_MAX_REASSEMBLED_BYTES,
3918
+ MESH_MISSION_SOURCES,
3919
+ MESH_MISSION_STATUSES,
3920
+ MESH_P2P_SIGNAL_TYPES,
3921
+ MESH_RECORD_PAYLOAD_KEYS,
3922
+ MESH_SESSION_CLEANUP_MODES,
3923
+ MESH_STATUS_DOC_SPEC,
1109
3924
  MESH_TASK_DIFFICULTIES,
3925
+ MESH_TASK_MODES,
3926
+ MESH_TASK_PRIORITIES,
3927
+ MESH_TASK_STATUSES,
3928
+ MESH_TERMINAL_TASK_STATUSES,
3929
+ MESH_THINKING_LEVELS,
3930
+ MESH_TOPIC_ENTRY_KINDS,
3931
+ MESH_TOPIC_PROTOCOL_VERSION,
3932
+ MISSION_BRIEF_RENDER_MAX_CHARS,
3933
+ MODEL_AXIS_SOURCES,
3934
+ MODEL_SELECTION_HISTORY_LIMIT,
1110
3935
  MeshChunkAssembler,
3936
+ NATIVE_TURN_OUTCOMES,
3937
+ NOTIFY_KINDS,
3938
+ NO_PROGRESS_OBSERVED_STATUSES,
3939
+ NPM_UPDATE_TAGS,
3940
+ OPERATING_NOTE_CATEGORIES,
3941
+ OPERATOR_STATUSES,
3942
+ OPERATOR_STATUS_REASONS,
3943
+ OPERATOR_STATUS_REASON_VALUES,
3944
+ OPERATOR_STATUS_VALUES,
3945
+ OUTBOUND_MESSAGE_ORIGINS,
3946
+ P2P_SIGNAL_TYPES,
3947
+ PROVIDER_FAILURES,
1111
3948
  QUOTA_SUPPORTED_PROVIDERS,
3949
+ RECENT_SESSION_BUCKETS,
3950
+ RECLAIMING_SEND_REFUSALS,
3951
+ RELEASE_CHANNELS,
3952
+ RETIRED_MESH_TOOLS,
3953
+ SEND_POLICY_MODES,
3954
+ SEND_REFUSAL_REASONS,
3955
+ SERVER_STATUS_EVENT_NAMES,
3956
+ SERVER_TO_DAEMON_CONTROL_TYPES,
1112
3957
  SERVER_TO_DAEMON_WS_MSGS,
3958
+ SESSION_ERROR_REASONS,
3959
+ SESSION_LAUNCHED_BY,
3960
+ SESSION_REBOUND_REASONS,
3961
+ SESSION_STATUSES,
3962
+ SESSION_STATUS_ALIASES,
3963
+ SESSION_STATUS_CLASS,
3964
+ SHARED_SESSION_TO_VIEWER_TYPES,
1113
3965
  STATUS_PROBE_ARG_KEY,
3966
+ SUSPENSION_MODALS,
3967
+ SUSPENSION_RESOLUTIONS,
3968
+ SUSPENSION_RESOLUTION_VIAS,
3969
+ SYSTEM_ANNOUNCEMENT_TYPES,
3970
+ TERMINAL_CLASS_EVIDENCE_KINDS,
3971
+ TERMINAL_SESSION_RECORD_STATUSES,
3972
+ TOOL_CALLER_ROLES,
3973
+ TURN_END_BLOCK_REASONS,
3974
+ TURN_END_STRENGTHS,
3975
+ TURN_EVIDENCE_FIELD_SPECS,
3976
+ TURN_EVIDENCE_FLAGS,
3977
+ TURN_EVIDENCE_KINDS,
3978
+ TURN_IPC_COMMANDS,
3979
+ TURN_IPC_ERROR_CODES,
3980
+ TURN_IPC_PROTOCOL_VERSION,
3981
+ TURN_OBSERVE_VERDICTS,
3982
+ TURN_OUTCOMES,
3983
+ TURN_REASONS,
3984
+ TURN_SCOPES,
1114
3985
  UNKNOWN_CLI_SLOT_RECIPE,
3986
+ USER_SESSION_TO_DASHBOARD_TYPES,
3987
+ VERSION_UPDATE_REASONS,
3988
+ VIEWER_TO_SHARED_SESSION_TYPES,
3989
+ WORKER_BRANCH_STATES,
3990
+ WORKER_PROTOCOL_FOOTER_MARKER,
3991
+ WORKER_REPORT_OUTCOMES,
3992
+ WORKER_TOOLS,
3993
+ appendWorkerProtocolFooter,
1115
3994
  argsCarryStatusProbeMarker,
1116
3995
  buildMagiPanelProposal,
1117
3996
  buildSlotProposal,
1118
3997
  canonicalDaemonId,
3998
+ classifySessionStatus,
3999
+ compareDashboardWireVersion,
1119
4000
  compareSemver,
1120
4001
  daemonIdsEquivalent,
4002
+ decodeActiveWorkQueryRequest,
4003
+ decodeActiveWorkQueryResponse,
4004
+ decodeDaemonToDashboardP2P,
4005
+ decodeDaemonToServer,
4006
+ decodeDashboardToDaemonP2P,
4007
+ decodeDashboardToDaemonP2PChunk,
4008
+ decodeDashboardToUserSession,
4009
+ decodeDirectDispatchRecordRequest,
4010
+ decodeDirectDispatchRecordResponse,
4011
+ decodeGraphAuditRecordRequest,
4012
+ decodeGraphAuditRecordResponse,
4013
+ decodeGraphGateAbandonRequest,
4014
+ decodeGraphGateAbandonResponse,
4015
+ decodeGraphGateClaimRequest,
4016
+ decodeGraphGateClaimResponse,
4017
+ decodeGraphGateReleaseRequest,
4018
+ decodeGraphGateReleaseResponse,
4019
+ decodeGraphNodePatchRequest,
4020
+ decodeGraphNodePatchResponse,
4021
+ decodeGraphViewQueryRequest,
4022
+ decodeGraphViewQueryResponse,
4023
+ decodeLedgerQueryRequest,
4024
+ decodeLedgerQueryResponse,
4025
+ decodeMeshIndexQueryRequest,
4026
+ decodeMeshIndexQueryResponse,
4027
+ decodeMeshRecordRequest,
4028
+ decodeMeshRecordResponse,
4029
+ decodeMissionListQueryRequest,
4030
+ decodeMissionListQueryResponse,
4031
+ decodeMissionQueryRequest,
4032
+ decodeMissionQueryResponse,
4033
+ decodeMissionUpsertRequest,
4034
+ decodeMissionUpsertResponse,
4035
+ decodeNoteForgetRequest,
4036
+ decodeNoteForgetResponse,
4037
+ decodeNoteUpsertRequest,
4038
+ decodeNoteUpsertResponse,
4039
+ decodeOperatorStatusRequest,
4040
+ decodeOperatorStatusResponse,
4041
+ decodeOrphanedPinNotifyRequest,
4042
+ decodeOrphanedPinNotifyResponse,
4043
+ decodePruneStaleDirectRequest,
4044
+ decodePruneStaleDirectResponse,
4045
+ decodeQueueCancelRequest,
4046
+ decodeQueueCancelResponse,
4047
+ decodeQueueEnqueueGraphRequest,
4048
+ decodeQueueEnqueueGraphResponse,
4049
+ decodeQueueEnqueueRequest,
4050
+ decodeQueueEnqueueResponse,
4051
+ decodeQueueQueryRequest,
4052
+ decodeQueueQueryResponse,
4053
+ decodeQueueRequeueRequest,
4054
+ decodeQueueRequeueResponse,
4055
+ decodeRecordLocalRequest,
4056
+ decodeRecordLocalResponse,
4057
+ decodeRecoveryContextQueryRequest,
4058
+ decodeRecoveryContextQueryResponse,
4059
+ decodeServerToDaemon,
4060
+ decodeTaskStatsQueryRequest,
4061
+ decodeTaskStatsQueryResponse,
4062
+ decodeToolCallRecordRequest,
4063
+ decodeToolCallRecordResponse,
4064
+ decodeTurnCancelRequest,
4065
+ decodeTurnCancelResponse,
4066
+ decodeTurnObserveRequest,
4067
+ decodeTurnObserveResponse,
4068
+ decodeTurnQueryRequest,
4069
+ decodeTurnQueryResponse,
4070
+ decodeTypeField,
4071
+ decodeUserSessionToDashboard,
4072
+ decodeViewerToSharedSession,
1121
4073
  deriveProviderPriorityFromSlots,
1122
4074
  deriveSlotsFromLegacy,
4075
+ describeModelSelection,
4076
+ diffKeyedDoc,
4077
+ digestKeyedDoc,
4078
+ effectiveModelSelectionValue,
4079
+ enumOf,
1123
4080
  expandDaemonIdForms,
4081
+ findOwnershipConflicts,
4082
+ foldKeyedDoc,
1124
4083
  formatQuotaAccount,
1125
4084
  hasGitStatusEvidence,
1126
- interpolateArgs,
4085
+ hasWorkerProtocolFooter,
1127
4086
  interpolateString,
1128
- isDaemonToServerWsMsg,
4087
+ isActiveWorkQueryRequest,
4088
+ isActiveWorkQueryResponse,
4089
+ isBlockedStatus,
4090
+ isBusyStatus,
4091
+ isChunkType,
4092
+ isCommitStrength,
4093
+ isDaemonDirectCommandType,
4094
+ isDaemonP2PSignalType,
4095
+ isDaemonStatusEventName,
4096
+ isDaemonToDashboardP2PType,
4097
+ isDaemonToServerType,
4098
+ isDashboardP2PSignalType,
4099
+ isDashboardStatusEventName,
4100
+ isDashboardToDaemonChunkType,
4101
+ isDashboardToDaemonP2PType,
4102
+ isDashboardToUserSessionType,
4103
+ isDeadStatus,
4104
+ isDirectDispatchRecordRequest,
4105
+ isDirectDispatchRecordResponse,
1129
4106
  isDowngrade,
4107
+ isEvidenceIdentifier,
4108
+ isFiniteNumber,
4109
+ isGraphAuditEvent,
4110
+ isGraphAuditRecordRequest,
4111
+ isGraphAuditRecordResponse,
4112
+ isGraphGateAbandonRequest,
4113
+ isGraphGateAbandonResponse,
4114
+ isGraphGateClaimRequest,
4115
+ isGraphGateClaimResponse,
4116
+ isGraphGateReleaseRequest,
4117
+ isGraphGateReleaseResponse,
4118
+ isGraphNodePatchRequest,
4119
+ isGraphNodePatchResponse,
4120
+ isGraphViewQueryRequest,
4121
+ isGraphViewQueryResponse,
4122
+ isIdleSessionState,
4123
+ isInputEnvelopeWire,
4124
+ isLedgerQueryRequest,
4125
+ isLedgerQueryResponse,
4126
+ isMeshDeliveryMode,
4127
+ isMeshIndexQueryRequest,
4128
+ isMeshIndexQueryResponse,
4129
+ isMeshIndexQueryWriterScope,
4130
+ isMeshMissionSourceValue,
4131
+ isMeshMissionStatusValue,
4132
+ isMeshP2PSignalType,
4133
+ isMeshRecordPayload,
4134
+ isMeshRecordRequest,
4135
+ isMeshRecordResponse,
1130
4136
  isMeshTaskDifficulty,
4137
+ isMeshTaskMode,
4138
+ isMeshTaskPriority,
4139
+ isMeshTaskStatus,
4140
+ isMeshTerminalTaskStatus,
4141
+ isMeshTopicEntry,
4142
+ isMessageId,
4143
+ isMissionListQueryRequest,
4144
+ isMissionListQueryResponse,
4145
+ isMissionQueryRequest,
4146
+ isMissionQueryResponse,
4147
+ isMissionUpsertRequest,
4148
+ isMissionUpsertResponse,
4149
+ isModelAxisSource,
4150
+ isNonEmptyString,
4151
+ isNoteForgetRequest,
4152
+ isNoteForgetResponse,
4153
+ isNoteUpsertRequest,
4154
+ isNoteUpsertResponse,
4155
+ isNotifyKind,
4156
+ isOperatingNoteCategory,
4157
+ isOperatorStatusReasonValue,
4158
+ isOperatorStatusRequest,
4159
+ isOperatorStatusResponse,
4160
+ isOperatorStatusValue,
4161
+ isOrphanedPinNotifyRequest,
4162
+ isOrphanedPinNotifyResponse,
4163
+ isOutboundMessage,
4164
+ isOutboundMessageOrigin,
4165
+ isP2PSignalType,
1131
4166
  isPhantomDaemonEntry,
4167
+ isPruneStaleDirectRequest,
4168
+ isPruneStaleDirectResponse,
4169
+ isQueueCancelRequest,
4170
+ isQueueCancelResponse,
4171
+ isQueueEnqueueGraphRequest,
4172
+ isQueueEnqueueGraphResponse,
4173
+ isQueueEnqueueRequest,
4174
+ isQueueEnqueueResponse,
4175
+ isQueueQueryRequest,
4176
+ isQueueQueryResponse,
4177
+ isQueueRequeueRequest,
4178
+ isQueueRequeueResponse,
1132
4179
  isRawDaemonDoId,
1133
- isServerToDaemonWsMsg,
4180
+ isReadyStatus,
4181
+ isRecord,
4182
+ isRecordLocalRequest,
4183
+ isRecordLocalResponse,
4184
+ isRecoveryContextQueryRequest,
4185
+ isRecoveryContextQueryResponse,
4186
+ isSendPolicy,
4187
+ isSendPolicyMode,
4188
+ isSendRefusal,
4189
+ isServerDirectCommandMsg,
4190
+ isServerToDaemonControlType,
4191
+ isSessionLaunchedBy,
4192
+ isSessionStatus,
4193
+ isSharedSessionToViewerType,
4194
+ isSubmitOutcome,
4195
+ isSummaryRef,
4196
+ isTaskStatsQueryRequest,
4197
+ isTaskStatsQueryResponse,
4198
+ isTerminalSessionRecordStatus,
4199
+ isToolCallRecordRequest,
4200
+ isToolCallRecordResponse,
4201
+ isToolCallerRole,
4202
+ isTurnAttemptRef,
4203
+ isTurnCancelRequest,
4204
+ isTurnCancelResponse,
4205
+ isTurnEvidence,
4206
+ isTurnEvidenceKind,
4207
+ isTurnIpcCommand,
4208
+ isTurnIpcError,
4209
+ isTurnIpcErrorCode,
4210
+ isTurnObserveRequest,
4211
+ isTurnObserveResponse,
4212
+ isTurnObserveVerdict,
4213
+ isTurnOutcome,
4214
+ isTurnQueryRequest,
4215
+ isTurnQueryResponse,
4216
+ isTurnReason,
4217
+ isUserSessionToDashboardType,
4218
+ isViewerToSharedSessionType,
4219
+ isWorkerReportOutcome,
4220
+ isWorkerTool,
4221
+ isWorkingStatus,
1134
4222
  joinRepoPath,
4223
+ launchModelSelectionValue,
1135
4224
  machineCoreFromDaemonId,
4225
+ makeTypeGuard,
1136
4226
  measureWorstCaseChunkEnvelopeBytes,
1137
4227
  meshFrameNeedsChunking,
1138
4228
  meshNodeIdMatches,
1139
4229
  meshUtf8ByteLength,
1140
4230
  meshWorkspacesEquivalent,
4231
+ mintMessageId,
4232
+ normalizeAuthOkLimits,
1141
4233
  normalizeBrainSlot,
1142
4234
  normalizeDifficultyBrainMap,
1143
4235
  normalizeGitStatus,
@@ -1145,25 +4237,41 @@ var CLAUDE_TUI_REVIEW_UNCONFIRMED_PREFIX = "Claude TUI answer delivered but not
1145
4237
  normalizeMeshNodeId,
1146
4238
  normalizeMeshSessionRecord,
1147
4239
  normalizeMeshWorkspaceForCompare,
4240
+ normalizeMissionBrief,
1148
4241
  normalizeNodeCapabilitySlot,
1149
4242
  normalizeNodeCapabilitySlots,
4243
+ normalizeOwnedPaths,
4244
+ normalizeSessionStatus,
1150
4245
  normalizeThinkingLevel,
1151
4246
  parseJsonRecord,
1152
4247
  parseSemver,
4248
+ parseSessionLaunchRecord,
4249
+ pathsOverlap,
1153
4250
  pickBestTransitGitStatus,
4251
+ projectTurnEvidenceEntry,
1154
4252
  readBoolean,
4253
+ readEnvelopeFields,
1155
4254
  readGitSubmodules,
1156
4255
  readNumber,
1157
4256
  readRecord,
1158
4257
  readString,
1159
4258
  readStringArray,
4259
+ renderCoordinatorWorkerSection,
4260
+ renderMissionBriefBlock,
4261
+ renderWorkerProtocolFooter,
4262
+ retiredMeshToolError,
4263
+ sanitizeModelIdentifier,
4264
+ sanitizeRefusalCode,
1160
4265
  scoreGitStatusCandidate,
1161
4266
  scoreGitUpstreamFreshness,
1162
4267
  sessionIdsEquivalent,
1163
4268
  splitMeshFrame,
4269
+ statusesOfClass,
1164
4270
  stripStatusProbeMarker,
4271
+ stripWorkerProtocolFooter,
1165
4272
  summarizeGitShape,
1166
4273
  supportsQuota,
4274
+ touchedFilesOutsideOwnership,
1167
4275
  withStatusProbeMarker
1168
4276
  });
1169
4277
  //# sourceMappingURL=index.js.map