@adhdev/mesh-shared 1.0.60-rc.6 → 1.0.60-rc.61

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 (47) hide show
  1. package/dist/brain-routing.d.ts +2 -2
  2. package/dist/index.d.ts +10 -0
  3. package/dist/index.js +2862 -35
  4. package/dist/index.js.map +1 -1
  5. package/dist/index.mjs +2536 -35
  6. package/dist/index.mjs.map +1 -1
  7. package/dist/magi.d.ts +1 -1
  8. package/dist/mesh-tool-names.d.ts +27 -2
  9. package/dist/mesh-vocabulary.d.ts +70 -0
  10. package/dist/mission-brief.d.ts +62 -0
  11. package/dist/outbound-message.d.ts +202 -0
  12. package/dist/path-ownership.d.ts +101 -0
  13. package/dist/protocol/daemon-server.d.ts +388 -0
  14. package/dist/protocol/dashboard-daemon-p2p.d.ts +212 -0
  15. package/dist/protocol/dashboard-server.d.ts +240 -0
  16. package/dist/protocol/envelope.d.ts +55 -0
  17. package/dist/protocol/index.d.ts +15 -0
  18. package/dist/session-launch.d.ts +113 -0
  19. package/dist/session-status.d.ts +61 -0
  20. package/dist/slot-proposal.d.ts +1 -1
  21. package/dist/turn-evidence.d.ts +438 -0
  22. package/dist/turn-ipc.d.ts +1040 -0
  23. package/dist/types.d.ts +11 -0
  24. package/dist/worker-protocol.d.ts +69 -0
  25. package/dist/ws-protocol.d.ts +71 -41
  26. package/package.json +1 -1
  27. package/src/brain-routing.ts +3 -3
  28. package/src/index.ts +10 -0
  29. package/src/magi.ts +1 -1
  30. package/src/mesh-tool-names.ts +65 -19
  31. package/src/mesh-vocabulary.ts +98 -0
  32. package/src/mission-brief.ts +153 -0
  33. package/src/outbound-message.ts +320 -0
  34. package/src/path-ownership.ts +271 -0
  35. package/src/protocol/daemon-server.ts +552 -0
  36. package/src/protocol/dashboard-daemon-p2p.ts +272 -0
  37. package/src/protocol/dashboard-server.ts +340 -0
  38. package/src/protocol/envelope.ts +75 -0
  39. package/src/protocol/index.ts +16 -0
  40. package/src/session-launch.ts +247 -0
  41. package/src/session-status.ts +140 -0
  42. package/src/slot-proposal.ts +1 -1
  43. package/src/turn-evidence.ts +602 -0
  44. package/src/turn-ipc.ts +2331 -0
  45. package/src/types.ts +8 -0
  46. package/src/worker-protocol.ts +164 -0
  47. package/src/ws-protocol.ts +102 -93
package/dist/index.mjs CHANGED
@@ -287,8 +287,8 @@ function meshWorkspacesEquivalent(a, b) {
287
287
 
288
288
  // src/daemon-normalize.ts
289
289
  var DAEMON_ID_PREFIXES = ["daemon_", "standalone_"];
290
- function isRawDaemonDoId(id) {
291
- const trimmed = readString(id);
290
+ function isRawDaemonDoId(id2) {
291
+ const trimmed = readString(id2);
292
292
  return !!trimmed && /^[0-9a-f]{64}$/i.test(trimmed);
293
293
  }
294
294
  function isPhantomDaemonEntry(entry) {
@@ -299,8 +299,8 @@ function isPhantomDaemonEntry(entry) {
299
299
  );
300
300
  return !hasMachineEvidence;
301
301
  }
302
- function machineCoreFromDaemonId(id) {
303
- const trimmed = readString(id);
302
+ function machineCoreFromDaemonId(id2) {
303
+ const trimmed = readString(id2);
304
304
  if (!trimmed) return void 0;
305
305
  for (const prefix of DAEMON_ID_PREFIXES) {
306
306
  if (trimmed.startsWith(prefix)) {
@@ -310,8 +310,8 @@ function machineCoreFromDaemonId(id) {
310
310
  }
311
311
  return trimmed;
312
312
  }
313
- function canonicalDaemonId(id) {
314
- const core = machineCoreFromDaemonId(id);
313
+ function canonicalDaemonId(id2) {
314
+ const core = machineCoreFromDaemonId(id2);
315
315
  if (!core) return void 0;
316
316
  if (!core.startsWith("mach_")) return core;
317
317
  return `daemon_${core}`;
@@ -663,9 +663,7 @@ var CANONICAL_MESH_TOOL_NAMES = [
663
663
  "mesh_view_queue",
664
664
  // GRAPH-ORCHESTRATION Phase E — the coordinator gate + graph view surface.
665
665
  "mesh_graph_view",
666
- "mesh_graph_gate_claim",
667
- "mesh_graph_gate_release",
668
- "mesh_graph_gate_abandon",
666
+ "mesh_graph_gate",
669
667
  "mesh_graph_node_patch",
670
668
  "mesh_queue_cancel",
671
669
  "mesh_queue_requeue",
@@ -683,7 +681,6 @@ var CANONICAL_MESH_TOOL_NAMES = [
683
681
  "mesh_approve",
684
682
  "mesh_answer_question",
685
683
  "mesh_list_pending_approvals",
686
- "mesh_plan_onboarding",
687
684
  "mesh_create",
688
685
  "mesh_add_node",
689
686
  "mesh_clone_node",
@@ -691,34 +688,57 @@ var CANONICAL_MESH_TOOL_NAMES = [
691
688
  "mesh_cleanup_worktree_nodes",
692
689
  "mesh_refine_node",
693
690
  "mesh_refine_batch",
694
- "mesh_refine_config",
695
- "mesh_change_impact_config",
691
+ "mesh_config",
696
692
  "mesh_init",
697
- "mesh_reinit",
698
- "mesh_write_mesh_json_config",
699
693
  "mesh_refine_plan",
700
694
  "mesh_cleanup_sessions",
701
- "mesh_prune_stale_direct",
702
695
  "mesh_task_history",
703
696
  "mesh_ledger_query",
704
- "mesh_record_note",
705
- "mesh_forget_note",
697
+ "mesh_note",
706
698
  "mesh_reconcile_ledger",
707
- "mesh_requeue_held_events",
708
699
  "mesh_mission_upsert",
709
700
  "mesh_mission_list",
710
701
  "mesh_review_inbox",
711
702
  "mesh_magi_review",
712
703
  "mesh_magi_collect",
713
- "mesh_magi_kind_panel_set",
714
- "mesh_magi_kind_panel_list",
715
- "mesh_node_slots_set",
716
- "mesh_node_slots_list",
717
- "mesh_node_slots_propose",
718
- "mesh_coordinator_prompt_append_get",
719
- "mesh_coordinator_prompt_append_set"
704
+ "mesh_magi_kind_panel",
705
+ "mesh_node_slots",
706
+ "mesh_coordinator_prompt_append"
720
707
  ];
721
708
  var CANONICAL_MESH_TOOL_COUNT = CANONICAL_MESH_TOOL_NAMES.length;
709
+ var RETIRED_MESH_TOOLS = {
710
+ mesh_graph_gate_claim: {
711
+ tool: "mesh_graph_gate",
712
+ args: { action: "claim" },
713
+ note: 'The extend-only form (claim with extend_seconds) is now action: "extend" with the same extend_seconds.'
714
+ },
715
+ mesh_graph_gate_release: { tool: "mesh_graph_gate", args: { action: "release" } },
716
+ mesh_graph_gate_abandon: { tool: "mesh_graph_gate", args: { action: "abandon" } },
717
+ // Never a published tool (it is the daemon command behind the extend verb),
718
+ // but an older gate-expiry notice told coordinators to call it by this name.
719
+ mesh_graph_gate_extend: { tool: "mesh_graph_gate", args: { action: "extend" } },
720
+ mesh_node_slots_set: { tool: "mesh_node_slots", args: { action: "set" } },
721
+ mesh_node_slots_list: { tool: "mesh_node_slots", args: { action: "list" } },
722
+ mesh_node_slots_propose: { tool: "mesh_node_slots", args: { action: "propose" } },
723
+ mesh_magi_kind_panel_set: { tool: "mesh_magi_kind_panel", args: { action: "set" } },
724
+ mesh_magi_kind_panel_list: { tool: "mesh_magi_kind_panel", args: { action: "list" } },
725
+ mesh_coordinator_prompt_append_get: { tool: "mesh_coordinator_prompt_append", args: { action: "get" } },
726
+ mesh_coordinator_prompt_append_set: { tool: "mesh_coordinator_prompt_append", args: { action: "set" } },
727
+ mesh_record_note: { tool: "mesh_note", args: { action: "record" } },
728
+ mesh_forget_note: { tool: "mesh_note", args: { action: "forget" } },
729
+ mesh_reinit: { tool: "mesh_init", args: { mode: "reinit" } },
730
+ mesh_refine_config: { tool: "mesh_config", args: { kind: "refine" } },
731
+ mesh_change_impact_config: { tool: "mesh_config", args: { kind: "change_impact" } },
732
+ mesh_write_mesh_json_config: { tool: "mesh_config", args: { kind: "mesh_json" } },
733
+ mesh_plan_onboarding: { tool: "mesh_create", args: { mode: "plan" } },
734
+ mesh_prune_stale_direct: { tool: "mesh_cleanup_sessions", args: { mode: "prune_stale_direct" } }
735
+ };
736
+ function retiredMeshToolError(name) {
737
+ const entry = Object.prototype.hasOwnProperty.call(RETIRED_MESH_TOOLS, name) ? RETIRED_MESH_TOOLS[name] : void 0;
738
+ if (!entry) return null;
739
+ const discriminator = Object.entries(entry.args).map(([k, v]) => `${k}: "${v}"`).join(", ");
740
+ return `Tool "${name}" was retired (merged into ${entry.tool}). Call ${entry.tool} with ${discriminator} and the same other arguments.` + (entry.note ? ` ${entry.note}` : "");
741
+ }
722
742
 
723
743
  // src/mesh-status-probe.ts
724
744
  var STATUS_PROBE_ARG_KEY = "_statusProbe";
@@ -957,8 +977,54 @@ function isDowngrade(current, target) {
957
977
  return direction < 0;
958
978
  }
959
979
 
960
- // src/ws-protocol.ts
961
- var DAEMON_TO_SERVER_WS_MSGS = [
980
+ // src/protocol/envelope.ts
981
+ function isRecord(value) {
982
+ return typeof value === "object" && value !== null && !Array.isArray(value);
983
+ }
984
+ function isNonEmptyString(value) {
985
+ return typeof value === "string" && value.length > 0;
986
+ }
987
+ function isFiniteNumber(value) {
988
+ return typeof value === "number" && Number.isFinite(value);
989
+ }
990
+ function makeTypeGuard(names) {
991
+ const set = new Set(names);
992
+ return (value) => typeof value === "string" && set.has(value);
993
+ }
994
+ function decodeTypeField(raw, isType) {
995
+ if (!isRecord(raw)) return null;
996
+ if (!isType(raw.type)) return null;
997
+ return { type: raw.type, frame: raw };
998
+ }
999
+ function readEnvelopeFields(frame) {
1000
+ return {
1001
+ ...isNonEmptyString(frame.id) ? { id: frame.id } : {},
1002
+ ...isFiniteNumber(frame.timestamp) ? { timestamp: frame.timestamp } : {}
1003
+ };
1004
+ }
1005
+
1006
+ // src/protocol/daemon-server.ts
1007
+ var DAEMON_STATUS_EVENT_NAMES = [
1008
+ "agent:generating_started",
1009
+ "agent:waiting_approval",
1010
+ "agent:waiting_choice",
1011
+ "agent:generating_completed",
1012
+ "agent:stopped",
1013
+ "monitor:no_progress",
1014
+ /** Legacy alias for `monitor:no_progress`, still emitted by older daemons. */
1015
+ "monitor:long_generating"
1016
+ ];
1017
+ var isDaemonStatusEventName = makeTypeGuard(DAEMON_STATUS_EVENT_NAMES);
1018
+ var RELEASE_CHANNELS = ["stable", "preview"];
1019
+ var NPM_UPDATE_TAGS = ["latest", "next"];
1020
+ var VERSION_UPDATE_REASONS = ["force_update_below", "major_minor_mismatch", "patch_mismatch", "daemon_ahead"];
1021
+ var P2P_SIGNAL_TYPES = ["p2p_ready", "p2p_offer", "p2p_answer", "p2p_ice"];
1022
+ var isP2PSignalType = makeTypeGuard(P2P_SIGNAL_TYPES);
1023
+ var DAEMON_P2P_SIGNAL_TYPES = ["p2p_offer", "p2p_ice"];
1024
+ var isDaemonP2PSignalType = makeTypeGuard(DAEMON_P2P_SIGNAL_TYPES);
1025
+ var MESH_P2P_SIGNAL_TYPES = ["mesh_p2p_ready", "mesh_p2p_offer", "mesh_p2p_answer", "mesh_p2p_ice"];
1026
+ var isMeshP2PSignalType = makeTypeGuard(MESH_P2P_SIGNAL_TYPES);
1027
+ var DAEMON_TO_SERVER_TYPES = [
962
1028
  "auth",
963
1029
  "status_report",
964
1030
  "status_heartbeat",
@@ -966,10 +1032,29 @@ var DAEMON_TO_SERVER_WS_MSGS = [
966
1032
  "command_result",
967
1033
  "error",
968
1034
  "agent_event",
969
- "log",
970
- "beacon_vectors"
1035
+ "beacon_vectors",
1036
+ "daemon_mesh_command",
1037
+ "p2p_offer",
1038
+ "p2p_ice"
971
1039
  ];
972
- var SERVER_TO_DAEMON_WS_MSGS = [
1040
+ var isDaemonToServerType = makeTypeGuard(DAEMON_TO_SERVER_TYPES);
1041
+ function decodeDaemonToServer(raw) {
1042
+ if (!isRecord(raw) || !isDaemonToServerType(raw.type)) return null;
1043
+ if (raw.type === "daemon_mesh_command") {
1044
+ return {
1045
+ type: "daemon_mesh_command",
1046
+ requestId: typeof raw.requestId === "string" ? raw.requestId : String(raw.requestId ?? ""),
1047
+ targetDaemonId: typeof raw.targetDaemonId === "string" ? raw.targetDaemonId : "",
1048
+ command: raw.command,
1049
+ args: isRecord(raw.args) ? raw.args : {},
1050
+ timestamp: typeof raw.timestamp === "number" ? raw.timestamp : Date.now()
1051
+ };
1052
+ }
1053
+ if (!isRecord(raw.payload)) return null;
1054
+ if (raw.type === "auth" && !isNonEmptyString(raw.payload.token)) return null;
1055
+ return { type: raw.type, payload: raw.payload, ...readEnvelopeFields(raw) };
1056
+ }
1057
+ var SERVER_TO_DAEMON_CONTROL_TYPES = [
973
1058
  "auth_ok",
974
1059
  "auth_error",
975
1060
  "machine_evicted",
@@ -980,65 +1065,2465 @@ var SERVER_TO_DAEMON_WS_MSGS = [
980
1065
  "command",
981
1066
  "agent_command",
982
1067
  "resolve_action",
983
- "beacon_vectors_result"
1068
+ "beacon_vectors_result",
1069
+ "daemon_mesh_result",
1070
+ "p2p_ready",
1071
+ "p2p_offer",
1072
+ "p2p_answer",
1073
+ "p2p_ice",
1074
+ "mesh_p2p_ready",
1075
+ "mesh_p2p_offer",
1076
+ "mesh_p2p_answer",
1077
+ "mesh_p2p_ice"
984
1078
  ];
985
- function isDaemonToServerWsMsg(value) {
986
- return typeof value === "string" && DAEMON_TO_SERVER_WS_MSGS.includes(value);
1079
+ var isServerToDaemonControlType = makeTypeGuard(SERVER_TO_DAEMON_CONTROL_TYPES);
1080
+ function isServerDirectCommandMsg(msg) {
1081
+ return !isServerToDaemonControlType(msg.type);
987
1082
  }
988
- function isServerToDaemonWsMsg(value) {
989
- return typeof value === "string" && SERVER_TO_DAEMON_WS_MSGS.includes(value);
1083
+ var DIRECT_COMMAND_TYPE_PATTERN = /^[a-z][a-z0-9_:.-]{0,63}$/;
1084
+ function isDaemonDirectCommandType(value) {
1085
+ return typeof value === "string" && DIRECT_COMMAND_TYPE_PATTERN.test(value) && !isServerToDaemonControlType(value);
1086
+ }
1087
+ function decodeServerToDaemon(raw) {
1088
+ if (!isRecord(raw) || typeof raw.type !== "string") return null;
1089
+ const relay = {
1090
+ ...readEnvelopeFields(raw),
1091
+ ...isNonEmptyString(raw.source) ? { source: raw.source } : {}
1092
+ };
1093
+ if (raw.type === "beacon_vectors_result" || raw.type === "daemon_mesh_result") {
1094
+ if (!isNonEmptyString(raw.requestId)) return null;
1095
+ const base = { requestId: raw.requestId, success: raw.success === true };
1096
+ if (raw.type === "beacon_vectors_result") {
1097
+ return {
1098
+ type: "beacon_vectors_result",
1099
+ ...base,
1100
+ ...Array.isArray(raw.reports) ? { reports: raw.reports } : {},
1101
+ ...typeof raw.truncated === "number" ? { truncated: raw.truncated } : {},
1102
+ ...typeof raw.error === "string" ? { error: raw.error } : {}
1103
+ };
1104
+ }
1105
+ return {
1106
+ type: "daemon_mesh_result",
1107
+ ...base,
1108
+ ..."result" in raw ? { result: raw.result } : {},
1109
+ ...typeof raw.error === "string" ? { error: raw.error } : {}
1110
+ };
1111
+ }
1112
+ if (!isRecord(raw.payload)) return null;
1113
+ if (isServerToDaemonControlType(raw.type)) {
1114
+ return { type: raw.type, payload: raw.payload, ...relay };
1115
+ }
1116
+ if (!isDaemonDirectCommandType(raw.type)) return null;
1117
+ return { type: raw.type, payload: raw.payload, ...relay };
1118
+ }
1119
+
1120
+ // src/protocol/dashboard-server.ts
1121
+ var SERVER_STATUS_EVENT_NAMES = [
1122
+ "daemon:disconnect",
1123
+ "team:session_viewed",
1124
+ "team:view_request",
1125
+ "team:view_request_approved",
1126
+ "team:view_request_rejected"
1127
+ ];
1128
+ var DASHBOARD_STATUS_EVENT_NAMES = [...DAEMON_STATUS_EVENT_NAMES, ...SERVER_STATUS_EVENT_NAMES];
1129
+ var isDashboardStatusEventName = makeTypeGuard(DASHBOARD_STATUS_EVENT_NAMES);
1130
+ var SYSTEM_ANNOUNCEMENT_TYPES = ["info", "warning", "critical"];
1131
+ var USER_SESSION_TO_DASHBOARD_TYPES = [
1132
+ "connected",
1133
+ "initial_state",
1134
+ "daemon_status",
1135
+ "status_event",
1136
+ "system_announcement",
1137
+ "auth_error",
1138
+ "heartbeat",
1139
+ "p2p_offer",
1140
+ "p2p_ice"
1141
+ ];
1142
+ var isUserSessionToDashboardType = makeTypeGuard(USER_SESSION_TO_DASHBOARD_TYPES);
1143
+ function decodeUserSessionToDashboard(raw) {
1144
+ if (!isRecord(raw) || !isUserSessionToDashboardType(raw.type)) return null;
1145
+ if (raw.type === "heartbeat") {
1146
+ return { type: "heartbeat", payload: isRecord(raw.payload) ? raw.payload : {}, ...readEnvelopeFields(raw) };
1147
+ }
1148
+ if (!isRecord(raw.payload)) return null;
1149
+ return { type: raw.type, payload: raw.payload, ...readEnvelopeFields(raw) };
1150
+ }
1151
+ var DASHBOARD_TO_USER_SESSION_TYPES = ["heartbeat", "refresh", "p2p_ready", "p2p_answer", "p2p_ice"];
1152
+ var isDashboardToUserSessionType = makeTypeGuard(DASHBOARD_TO_USER_SESSION_TYPES);
1153
+ var DASHBOARD_P2P_SIGNAL_TYPES = ["p2p_ready", "p2p_answer", "p2p_ice"];
1154
+ var isDashboardP2PSignalType = makeTypeGuard(DASHBOARD_P2P_SIGNAL_TYPES);
1155
+ function decodeDashboardToUserSession(raw) {
1156
+ if (!isRecord(raw) || !isDashboardToUserSessionType(raw.type)) return null;
1157
+ if (raw.type === "heartbeat") return { type: "heartbeat", ...readEnvelopeFields(raw) };
1158
+ if (raw.type === "refresh") return { type: "refresh" };
1159
+ if (!isRecord(raw.payload) || typeof raw.payload.daemonId !== "string") return null;
1160
+ return { type: raw.type, payload: raw.payload, ...readEnvelopeFields(raw) };
1161
+ }
1162
+ var SHARED_SESSION_TO_VIEWER_TYPES = [
1163
+ "share:connected",
1164
+ "share:revoked",
1165
+ "share:expired",
1166
+ "share:error",
1167
+ "share:viewer_count",
1168
+ "p2p_offer",
1169
+ "p2p_ice"
1170
+ ];
1171
+ var isSharedSessionToViewerType = makeTypeGuard(SHARED_SESSION_TO_VIEWER_TYPES);
1172
+ var VIEWER_TO_SHARED_SESSION_TYPES = ["p2p_ready", "p2p_offer", "p2p_answer", "p2p_ice"];
1173
+ var isViewerToSharedSessionType = makeTypeGuard(VIEWER_TO_SHARED_SESSION_TYPES);
1174
+ function decodeViewerToSharedSession(raw) {
1175
+ if (!isRecord(raw) || !isViewerToSharedSessionType(raw.type)) return null;
1176
+ const payload = isRecord(raw.payload) ? raw.payload : {};
1177
+ return { type: raw.type, payload, ...readEnvelopeFields(raw) };
1178
+ }
1179
+
1180
+ // src/protocol/dashboard-daemon-p2p.ts
1181
+ function isChunkType(value) {
1182
+ return typeof value === "string" && value.endsWith("_chunk") && value.length > "_chunk".length;
1183
+ }
1184
+ function readChunkFields(frame) {
1185
+ if (!isNonEmptyString(frame.chunkId)) return null;
1186
+ if (!Number.isInteger(frame.index) || !Number.isInteger(frame.total)) return null;
1187
+ if (typeof frame.data !== "string") return null;
1188
+ return {
1189
+ ...isNonEmptyString(frame.id) ? { id: frame.id } : {},
1190
+ chunkId: frame.chunkId,
1191
+ index: frame.index,
1192
+ total: frame.total,
1193
+ data: frame.data
1194
+ };
1195
+ }
1196
+ var DASHBOARD_TO_DAEMON_P2P_TYPES = [
1197
+ "ping",
1198
+ "pong",
1199
+ "command",
1200
+ "input",
1201
+ "pty_input",
1202
+ "pty_resize",
1203
+ "screenshot_start",
1204
+ "screenshot_stop",
1205
+ "subscribe",
1206
+ "unsubscribe",
1207
+ "seqscribe_session_interest",
1208
+ "read",
1209
+ "write",
1210
+ "list"
1211
+ ];
1212
+ var isDashboardToDaemonP2PType = makeTypeGuard(DASHBOARD_TO_DAEMON_P2P_TYPES);
1213
+ function isDashboardToDaemonChunkType(value) {
1214
+ return isChunkType(value) && isDashboardToDaemonP2PType(value.slice(0, -"_chunk".length));
1215
+ }
1216
+ var DASHBOARD_REQUEST_TYPES = /* @__PURE__ */ new Set(["command", "input", "read", "write", "list"]);
1217
+ function decodeDashboardToDaemonP2PChunk(raw) {
1218
+ if (!isRecord(raw) || !isDashboardToDaemonChunkType(raw.type)) return null;
1219
+ const fields = readChunkFields(raw);
1220
+ return fields ? { type: raw.type, ...fields } : null;
1221
+ }
1222
+ function decodeDashboardToDaemonP2P(raw) {
1223
+ if (!isRecord(raw) || !isDashboardToDaemonP2PType(raw.type)) return null;
1224
+ if (DASHBOARD_REQUEST_TYPES.has(raw.type) && !isNonEmptyString(raw.id)) return null;
1225
+ return raw;
1226
+ }
1227
+ var DAEMON_TO_DASHBOARD_P2P_TYPES = [
1228
+ "ping",
1229
+ "pong",
1230
+ "p2p_evicted",
1231
+ "status_report",
1232
+ "status_event",
1233
+ "topic_update",
1234
+ "topic_update_chunk",
1235
+ "session_output",
1236
+ "session_output_chunk",
1237
+ "session_io_error",
1238
+ "command_result",
1239
+ "command_result_chunk",
1240
+ "response"
1241
+ ];
1242
+ var isDaemonToDashboardP2PType = makeTypeGuard(DAEMON_TO_DASHBOARD_P2P_TYPES);
1243
+ function decodeDaemonToDashboardP2P(raw) {
1244
+ if (!isRecord(raw)) return null;
1245
+ if (raw.type === void 0 && isNonEmptyString(raw.id) && typeof raw.success === "boolean") {
1246
+ return { ...raw, type: "response" };
1247
+ }
1248
+ if (!isDaemonToDashboardP2PType(raw.type)) return null;
1249
+ switch (raw.type) {
1250
+ case "ping":
1251
+ case "pong":
1252
+ case "p2p_evicted":
1253
+ return raw;
1254
+ case "status_report":
1255
+ case "status_event":
1256
+ return isRecord(raw.payload) ? raw : null;
1257
+ case "topic_update":
1258
+ return isRecord(raw.update) ? raw : null;
1259
+ case "topic_update_chunk":
1260
+ case "command_result_chunk":
1261
+ case "session_output_chunk": {
1262
+ const fields = readChunkFields(raw);
1263
+ if (!fields) return null;
1264
+ if (raw.type === "session_output_chunk") {
1265
+ return isNonEmptyString(raw.sessionId) ? { type: raw.type, sessionId: raw.sessionId, ...fields } : null;
1266
+ }
1267
+ return { type: raw.type, ...fields };
1268
+ }
1269
+ case "session_output":
1270
+ return isNonEmptyString(raw.sessionId) && typeof raw.data === "string" ? raw : null;
1271
+ case "session_io_error":
1272
+ return isNonEmptyString(raw.sessionId) ? raw : null;
1273
+ case "command_result":
1274
+ case "response":
1275
+ return isNonEmptyString(raw.id) ? raw : null;
1276
+ }
1277
+ }
1278
+ var DASHBOARD_P2P_MESSAGE_KINDS = [
1279
+ .../* @__PURE__ */ new Set([...DASHBOARD_TO_DAEMON_P2P_TYPES, ...DAEMON_TO_DASHBOARD_P2P_TYPES])
1280
+ ];
1281
+
1282
+ // src/ws-protocol.ts
1283
+ var DAEMON_TO_SERVER_WS_MSGS = DAEMON_TO_SERVER_TYPES;
1284
+ var SERVER_TO_DAEMON_WS_MSGS = SERVER_TO_DAEMON_CONTROL_TYPES;
1285
+ var isDaemonToServerWsMsg = isDaemonToServerType;
1286
+ var isServerToDaemonWsMsg = isServerToDaemonControlType;
1287
+ function normalizeAuthOkLimits(raw) {
1288
+ if (!raw || typeof raw !== "object") return null;
1289
+ const src = raw;
1290
+ const num = (value, fallback) => typeof value === "number" && Number.isFinite(value) ? value : fallback;
1291
+ return {
1292
+ maxP2Pconnections: num(
1293
+ src.maxP2Pconnections !== void 0 ? src.maxP2Pconnections : src.maxP2PConnections,
1294
+ -1
1295
+ ),
1296
+ screenshotIntervalSeconds: num(src.screenshotIntervalSeconds, 0),
1297
+ dailyScreenshotMinutes: num(src.dailyScreenshotMinutes, -1),
1298
+ maxMachines: num(src.maxMachines, -1)
1299
+ };
990
1300
  }
991
1301
 
992
1302
  // src/interactive-prompt-constants.ts
993
1303
  var CLAUDE_TUI_REVIEW_PAGE_NOT_FOCUSED_PREFIX = "Claude TUI review page is not focused";
994
1304
  var CLAUDE_TUI_REVIEW_UNCONFIRMED_PREFIX = "Claude TUI answer delivered but not confirmed";
1305
+
1306
+ // src/session-status.ts
1307
+ var SESSION_STATUSES = [
1308
+ "idle",
1309
+ "generating",
1310
+ "waiting_approval",
1311
+ "waiting_choice",
1312
+ "finalizing",
1313
+ "error",
1314
+ "stopped",
1315
+ "starting",
1316
+ "panel_hidden",
1317
+ "not_monitored",
1318
+ "disconnected"
1319
+ ];
1320
+ var RECENT_SESSION_BUCKETS = ["needs_attention", "working", "task_complete", "idle"];
1321
+ var SESSION_STATUS_CLASS = {
1322
+ generating: "working",
1323
+ finalizing: "working",
1324
+ starting: "working",
1325
+ waiting_approval: "blocked",
1326
+ waiting_choice: "blocked",
1327
+ idle: "ready",
1328
+ panel_hidden: "ready",
1329
+ not_monitored: "ready",
1330
+ error: "dead",
1331
+ stopped: "dead",
1332
+ disconnected: "dead"
1333
+ };
1334
+ var SESSION_STATUS_ALIASES = {
1335
+ running: "generating",
1336
+ streaming: "generating",
1337
+ busy: "generating",
1338
+ working: "generating",
1339
+ loading: "generating",
1340
+ loading_reference: "generating",
1341
+ thinking: "generating",
1342
+ active: "generating",
1343
+ // Status-lane refinements of a turn that is still owned by the agent.
1344
+ no_progress: "generating",
1345
+ long_generating: "generating",
1346
+ initializing: "starting",
1347
+ waiting: "waiting_approval"
1348
+ };
1349
+ var SESSION_STATUS_SET = new Set(SESSION_STATUSES);
1350
+ function isSessionStatus(value) {
1351
+ return typeof value === "string" && SESSION_STATUS_SET.has(value);
1352
+ }
1353
+ function normalizeSessionStatus(raw) {
1354
+ if (typeof raw !== "string") return null;
1355
+ const value = raw.trim().toLowerCase();
1356
+ if (SESSION_STATUS_SET.has(value)) return value;
1357
+ return SESSION_STATUS_ALIASES[value] ?? null;
1358
+ }
1359
+ function classifySessionStatus(raw) {
1360
+ const status = normalizeSessionStatus(raw);
1361
+ return status ? SESSION_STATUS_CLASS[status] : "unknown";
1362
+ }
1363
+ function isWorkingStatus(raw) {
1364
+ return classifySessionStatus(raw) === "working";
1365
+ }
1366
+ function isBlockedStatus(raw) {
1367
+ return classifySessionStatus(raw) === "blocked";
1368
+ }
1369
+ function isReadyStatus(raw) {
1370
+ return classifySessionStatus(raw) === "ready";
1371
+ }
1372
+ function isDeadStatus(raw) {
1373
+ return classifySessionStatus(raw) === "dead";
1374
+ }
1375
+ function isBusyStatus(raw) {
1376
+ const cls = classifySessionStatus(raw);
1377
+ return cls === "working" || cls === "blocked";
1378
+ }
1379
+ function statusesOfClass(cls) {
1380
+ return SESSION_STATUSES.filter((status) => SESSION_STATUS_CLASS[status] === cls);
1381
+ }
1382
+
1383
+ // src/mesh-vocabulary.ts
1384
+ var MESH_TASK_STATUSES = ["pending", "assigned", "completed", "failed", "cancelled"];
1385
+ var MESH_TERMINAL_TASK_STATUSES = ["completed", "failed", "cancelled"];
1386
+ var MESH_TASK_MODES = ["code_change", "validation", "live_debug_readonly", "launch_app", "convergence"];
1387
+ var MESH_TASK_PRIORITIES = ["low", "normal", "high"];
1388
+ var MESH_THINKING_LEVELS = ["low", "medium", "high"];
1389
+ var MESH_DELIVERY_MODES = ["when_idle", "interrupt"];
1390
+ var MESH_SESSION_CLEANUP_MODES = ["preserve", "stop", "delete_stopped", "stop_and_delete"];
1391
+ var WORKER_REPORT_OUTCOMES = ["completed", "blocked", "failed"];
1392
+ var WORKER_BRANCH_STATES = [
1393
+ "merged_to_main",
1394
+ "pushed_feature_branch_needs_merge",
1395
+ "blocked_review",
1396
+ "cleanup_candidate",
1397
+ "not_mergeable"
1398
+ ];
1399
+ function makeGuard(values) {
1400
+ const set = new Set(values);
1401
+ return (value) => typeof value === "string" && set.has(value);
1402
+ }
1403
+ var isMeshTaskStatus = makeGuard(MESH_TASK_STATUSES);
1404
+ var isMeshTerminalTaskStatus = makeGuard(MESH_TERMINAL_TASK_STATUSES);
1405
+ var isMeshTaskMode = makeGuard(MESH_TASK_MODES);
1406
+ var isMeshTaskPriority = makeGuard(MESH_TASK_PRIORITIES);
1407
+ var isMeshThinkingLevel = makeGuard(MESH_THINKING_LEVELS);
1408
+ var isMeshDeliveryMode = makeGuard(MESH_DELIVERY_MODES);
1409
+ var isMeshSessionCleanupMode = makeGuard(MESH_SESSION_CLEANUP_MODES);
1410
+ var isWorkerReportOutcome = makeGuard(WORKER_REPORT_OUTCOMES);
1411
+ var isWorkerBranchState = makeGuard(WORKER_BRANCH_STATES);
1412
+ function enumOf(values, description) {
1413
+ return {
1414
+ type: "string",
1415
+ enum: [...values],
1416
+ ...description ? { description } : {}
1417
+ };
1418
+ }
1419
+
1420
+ // src/outbound-message.ts
1421
+ var outboundMessageIdCounter = 0;
1422
+ function mintMessageId(now = Date.now()) {
1423
+ try {
1424
+ const cryptoRef = typeof globalThis !== "undefined" ? globalThis.crypto : void 0;
1425
+ if (typeof cryptoRef?.randomUUID === "function") return `msg_${cryptoRef.randomUUID()}`;
1426
+ } catch {
1427
+ }
1428
+ outboundMessageIdCounter += 1;
1429
+ return `msg_${now}_${outboundMessageIdCounter}`;
1430
+ }
1431
+ var MESSAGE_ID_PREFIX = "msg_";
1432
+ function isMessageId(value) {
1433
+ return typeof value === "string" && value.length > MESSAGE_ID_PREFIX.length && value.startsWith(MESSAGE_ID_PREFIX);
1434
+ }
1435
+ var OUTBOUND_MESSAGE_ORIGINS = ["dashboard", "mcp", "mesh", "api", "cli"];
1436
+ function isOutboundMessageOrigin(value) {
1437
+ return typeof value === "string" && OUTBOUND_MESSAGE_ORIGINS.includes(value);
1438
+ }
1439
+ var SEND_POLICY_MODES = ["queue", "send_now", "interrupt"];
1440
+ function isSendPolicyMode(value) {
1441
+ return typeof value === "string" && SEND_POLICY_MODES.includes(value);
1442
+ }
1443
+ function isSendPolicy(value) {
1444
+ return !!value && typeof value === "object" && isSendPolicyMode(value.mode);
1445
+ }
1446
+ var SEND_REFUSAL_REASONS = [
1447
+ "not_ready",
1448
+ "send_in_flight",
1449
+ "not_generating",
1450
+ "not_supported",
1451
+ "platform_unsupported",
1452
+ "modal_parked",
1453
+ "interrupt_not_implemented",
1454
+ "interrupt_refused",
1455
+ "idle_timeout",
1456
+ "session_exited",
1457
+ "unsupported_input",
1458
+ "no_target",
1459
+ "bootstrap_pending",
1460
+ "duplicate_dispatch",
1461
+ "internal_error"
1462
+ ];
1463
+ function isSendRefusal(value) {
1464
+ return typeof value === "string" && SEND_REFUSAL_REASONS.includes(value);
1465
+ }
1466
+ var SUBMIT_OUTCOME_KINDS = ["delivered", "queued", "duplicate", "refused"];
1467
+ function isSubmitOutcome(value) {
1468
+ if (!value || typeof value !== "object") return false;
1469
+ const kind = value.kind;
1470
+ if (typeof kind !== "string" || !SUBMIT_OUTCOME_KINDS.includes(kind)) return false;
1471
+ if (kind === "queued") return typeof value.position === "number";
1472
+ if (kind === "duplicate") return typeof value.of === "string";
1473
+ if (kind === "refused") return isSendRefusal(value.reason);
1474
+ return true;
1475
+ }
1476
+ function isInputPartWire(value) {
1477
+ if (!value || typeof value !== "object") return false;
1478
+ const type = value.type;
1479
+ return type === "text" || type === "image" || type === "audio" || type === "video" || type === "resource" || type === "resource_link";
1480
+ }
1481
+ function isInputEnvelopeWire(value) {
1482
+ if (!value || typeof value !== "object") return false;
1483
+ const parts = value.parts;
1484
+ const textFallback = value.textFallback;
1485
+ return Array.isArray(parts) && parts.every(isInputPartWire) && typeof textFallback === "string";
1486
+ }
1487
+ function isOutboundMessage(value) {
1488
+ if (!value || typeof value !== "object") return false;
1489
+ const candidate = value;
1490
+ 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";
1491
+ }
1492
+
1493
+ // src/mission-brief.ts
1494
+ var GOAL_MAX = 500;
1495
+ var LIST_ITEM_MAX = 200;
1496
+ var LIST_MAX_ITEMS = 12;
1497
+ var MISSION_BRIEF_RENDER_MAX_CHARS = 1200;
1498
+ function truncateString(value, max) {
1499
+ if (value.length <= max) return value;
1500
+ return `${value.slice(0, max - 1).trimEnd()}\u2026`;
1501
+ }
1502
+ function normalizeStringList(value, field, truncated) {
1503
+ if (value === void 0 || value === null) return void 0;
1504
+ if (!Array.isArray(value)) return void 0;
1505
+ const items = [];
1506
+ let itemTruncated = false;
1507
+ for (const raw of value) {
1508
+ if (typeof raw !== "string") continue;
1509
+ const trimmed = raw.trim();
1510
+ if (!trimmed) continue;
1511
+ if (trimmed.length > LIST_ITEM_MAX) itemTruncated = true;
1512
+ items.push(truncateString(trimmed, LIST_ITEM_MAX));
1513
+ }
1514
+ if (itemTruncated) truncated.push({ field, reason: "item_too_long" });
1515
+ if (items.length > LIST_MAX_ITEMS) {
1516
+ truncated.push({ field, reason: "list_too_long" });
1517
+ return items.slice(0, LIST_MAX_ITEMS);
1518
+ }
1519
+ return items.length > 0 ? items : void 0;
1520
+ }
1521
+ function normalizeMissionBrief(input) {
1522
+ const truncated = [];
1523
+ if (!input || typeof input !== "object") {
1524
+ return { brief: null, truncated };
1525
+ }
1526
+ const raw = input;
1527
+ const rawGoal = typeof raw.goal === "string" ? raw.goal.trim() : "";
1528
+ if (!rawGoal) {
1529
+ return { brief: null, truncated };
1530
+ }
1531
+ if (rawGoal.length > GOAL_MAX) truncated.push({ field: "goal", reason: "field_too_long" });
1532
+ const goal = truncateString(rawGoal, GOAL_MAX);
1533
+ const constraints = normalizeStringList(raw.constraints, "constraints", truncated);
1534
+ const doneCriteria = normalizeStringList(raw.doneCriteria ?? raw.done_criteria, "doneCriteria", truncated);
1535
+ const handoffNotes = normalizeStringList(raw.handoffNotes ?? raw.handoff_notes, "handoffNotes", truncated);
1536
+ const ownedPaths = normalizeStringList(raw.ownedPaths ?? raw.owned_paths, "ownedPaths", truncated);
1537
+ const brief = { goal };
1538
+ if (constraints) brief.constraints = constraints;
1539
+ if (doneCriteria) brief.doneCriteria = doneCriteria;
1540
+ if (handoffNotes) brief.handoffNotes = handoffNotes;
1541
+ if (ownedPaths) brief.ownedPaths = ownedPaths;
1542
+ return { brief, truncated };
1543
+ }
1544
+ function renderList(heading, items) {
1545
+ if (!items || items.length === 0) return [];
1546
+ return [`${heading}:`, ...items.map((item) => `- ${item}`)];
1547
+ }
1548
+ function renderMissionBriefBlock(brief) {
1549
+ const sections = [`Mission goal: ${brief.goal}`];
1550
+ sections.push(...renderList("Constraints", brief.constraints));
1551
+ sections.push(...renderList("Done when", brief.doneCriteria));
1552
+ sections.push(...renderList("Owned paths", brief.ownedPaths));
1553
+ sections.push(...renderList("Handoff notes", brief.handoffNotes));
1554
+ const full = sections.join("\n");
1555
+ if (full.length <= MISSION_BRIEF_RENDER_MAX_CHARS) return full;
1556
+ const marker = "\n(brief truncated)";
1557
+ const budget = MISSION_BRIEF_RENDER_MAX_CHARS - marker.length;
1558
+ const lines = full.split("\n");
1559
+ let acc = "";
1560
+ for (const line of lines) {
1561
+ const next = acc ? `${acc}
1562
+ ${line}` : line;
1563
+ if (next.length > budget) break;
1564
+ acc = next;
1565
+ }
1566
+ if (!acc) acc = truncateString(lines[0] ?? "", Math.max(budget, 0));
1567
+ return `${acc}${marker}`;
1568
+ }
1569
+
1570
+ // src/worker-protocol.ts
1571
+ var WORKER_TOOLS = [
1572
+ "report_completion",
1573
+ "progress_update",
1574
+ "peer_context_pull",
1575
+ "git_status",
1576
+ "git_log",
1577
+ "git_diff"
1578
+ ];
1579
+ var WORKER_TOOL_SET = new Set(WORKER_TOOLS);
1580
+ function isWorkerTool(value) {
1581
+ return typeof value === "string" && WORKER_TOOL_SET.has(value);
1582
+ }
1583
+ var WORKER_PROTOCOL_FOOTER_MARKER = "--- adhdev worker protocol ---";
1584
+ function hasWorkerProtocolFooter(body) {
1585
+ return typeof body === "string" && body.includes(WORKER_PROTOCOL_FOOTER_MARKER);
1586
+ }
1587
+ function renderWorkerProtocolFooter(input = {}) {
1588
+ const briefBlock = input.missionBrief ? renderMissionBriefBlock(input.missionBrief) : null;
1589
+ const lines = briefBlock ? [briefBlock, "", WORKER_PROTOCOL_FOOTER_MARKER] : [WORKER_PROTOCOL_FOOTER_MARKER];
1590
+ const scope = [];
1591
+ if (input.taskId) scope.push(`task ${input.taskId}`);
1592
+ if (input.taskMode) scope.push(`mode ${input.taskMode}`);
1593
+ if (input.difficulty) {
1594
+ if (isMeshTaskDifficulty(input.difficulty)) {
1595
+ scope.push(`difficulty ${input.difficulty}`);
1596
+ } else {
1597
+ console.warn(
1598
+ `[worker-protocol] task ${input.taskId ?? "(unknown)"}: dropping invalid difficulty '${input.difficulty}' from the worker footer (expected one of easy, medium, difficult, freeform)`
1599
+ );
1600
+ }
1601
+ }
1602
+ if (input.readonly) scope.push("read-only");
1603
+ if (scope.length) lines.push(`You are a delegated worker (${scope.join(", ")}).`);
1604
+ else lines.push("You are a delegated worker.");
1605
+ lines.push(
1606
+ "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.",
1607
+ "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.",
1608
+ "`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`.",
1609
+ "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`.",
1610
+ "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 `[]`.",
1611
+ "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."
1612
+ );
1613
+ if (input.enclosedHandoffNotes && input.enclosedHandoffNotes > 0) {
1614
+ lines.push(
1615
+ `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.`
1616
+ );
1617
+ }
1618
+ return lines.join("\n");
1619
+ }
1620
+ function stripWorkerProtocolFooter(body) {
1621
+ if (typeof body !== "string") return body;
1622
+ const at = body.indexOf(WORKER_PROTOCOL_FOOTER_MARKER);
1623
+ if (at < 0) return body;
1624
+ return body.slice(0, at).replace(/\s+$/, "");
1625
+ }
1626
+ function appendWorkerProtocolFooter(body, input = {}) {
1627
+ if (hasWorkerProtocolFooter(body)) return body;
1628
+ const trimmed = body.replace(/\s+$/, "");
1629
+ return `${trimmed}
1630
+
1631
+ ${renderWorkerProtocolFooter(input)}`;
1632
+ }
1633
+ function renderCoordinatorWorkerSection() {
1634
+ return [
1635
+ "## Workers",
1636
+ "",
1637
+ `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.`,
1638
+ "- 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.",
1639
+ "- `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.",
1640
+ "- 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.",
1641
+ "- `mesh_status` is for node health and capacity before delegating, never for progress.",
1642
+ "- 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."
1643
+ ].join("\n");
1644
+ }
1645
+
1646
+ // src/turn-evidence.ts
1647
+ var MESH_TOPIC_PROTOCOL_VERSION = 2;
1648
+ var EVIDENCE_SOURCE_IDS = [
1649
+ "fsm_edge",
1650
+ "short_gen_inline",
1651
+ "completion_flush_genuine",
1652
+ "completion_flush_weak",
1653
+ "monitor_final_summary",
1654
+ "pre_cleanup_transcript",
1655
+ "stall_transcript",
1656
+ "startup_grace_collapse",
1657
+ "acp_prompt_response",
1658
+ "cdp_state",
1659
+ "approval_gate",
1660
+ "modal_button",
1661
+ "mesh_stall_watchdog",
1662
+ "status_monitor",
1663
+ "pty_exit",
1664
+ "provider_error",
1665
+ "coordinator_probe",
1666
+ "mcp_probe",
1667
+ "worker_tool",
1668
+ "dispatch",
1669
+ "input_service",
1670
+ "operator",
1671
+ "intentional_cleanup",
1672
+ "scheduler",
1673
+ "git_probe",
1674
+ "session_registry"
1675
+ ];
1676
+ var TURN_SCOPES = ["mesh_queue", "mesh_direct", "plain"];
1677
+ var RECLAIMING_SEND_REFUSALS = ["session_exited", "no_target", "unsupported_input"];
1678
+ var DELIVERY_OUTCOMES = ["delivered", "queued"];
1679
+ var DELIVERY_VIAS = ["local", "p2p"];
1680
+ var DISPATCH_FAILURE_REASONS = ["worker_absent", "transport_error", "spawn_failed", "rejected_by_worker", "timeout"];
1681
+ function sanitizeRefusalCode(value) {
1682
+ if (typeof value !== "string") return void 0;
1683
+ const normalized = value.trim().toLowerCase().replace(/[^a-z_]/g, "_").replace(/_+/g, "_").replace(/^_+|_+$/g, "");
1684
+ if (!normalized) return void 0;
1685
+ return normalized.slice(0, 64);
1686
+ }
1687
+ var CONSUME_PROFILES = ["default", "native_source"];
1688
+ var SESSION_REBOUND_REASONS = ["restart", "live_holder"];
1689
+ var SUSPENSION_MODALS = ["approval", "choice"];
1690
+ var SUSPENSION_RESOLUTIONS = ["approved", "rejected", "answered"];
1691
+ var SUSPENSION_RESOLUTION_VIAS = ["modal_button", "auto_approve", "prompt_answer"];
1692
+ var TURN_END_STRENGTHS = ["genuine", "weak"];
1693
+ var TURN_END_BLOCK_REASONS = [
1694
+ "missing_final_assistant",
1695
+ "finalization_timeout",
1696
+ "terminal_block_hard_cap",
1697
+ "decoupled_completion"
1698
+ ];
1699
+ var NATIVE_TURN_OUTCOMES = ["completed", "aborted"];
1700
+ var LIVENESS_RESULTS = ["alive", "unknown", "read_failed", "dead"];
1701
+ var PROVIDER_FAILURES = ["auth_failed", "billing_failed"];
1702
+ var SESSION_ERROR_REASONS = ["provider_error", "adapter_error", "spawn_failed", "auth_failed", "billing_failed", "unknown", "daemon_restart"];
1703
+ var CANCEL_REASONS = ["operator_cancel", "intentional_cleanup", "task_removed", "mission_abandoned", "superseded"];
1704
+ var OPERATOR_STATUSES = ["completed", "failed"];
1705
+ var OPERATOR_STATUS_REASONS = ["operator_update", "refine_terminal", "validation_terminal"];
1706
+ var COORDINATOR_ACK_OUTCOMES = ["delivered", "queued", "duplicate"];
1707
+ var NO_PROGRESS_OBSERVED_STATUSES = [...SESSION_STATUSES, "unknown"];
1708
+ var HOLD_REASONS = [
1709
+ "await_delivery",
1710
+ "await_consume",
1711
+ "await_turn",
1712
+ "liveness",
1713
+ "hard_ceiling",
1714
+ "live_pending",
1715
+ "transcript_quiet",
1716
+ "weak_candidate",
1717
+ "suspension_before_consumed",
1718
+ // A genuine FSM end of a mesh turn whose worker holds a live worker-MCP bind:
1719
+ // the structured report is the primary evidence (design §F2), so the idle edge
1720
+ // only opens this hold (R9r) — a report commits (R17), a new busy edge cancels
1721
+ // it as a false idle (R12r), expiry commits weak (R13r).
1722
+ "await_report",
1723
+ // A worker report recorded while the session is still generating (R17g):
1724
+ // the report is the verdict, the idle edge is only awaited as corroboration
1725
+ // — a turn_end commits the report (R9t), expiry commits it anyway (R13t) so
1726
+ // a session whose FSM never shows the idle edge again does not wait for
1727
+ // liveness / hard_ceiling.
1728
+ "await_end"
1729
+ ];
1730
+ var TURN_OUTCOMES = ["completed", "failed", "cancelled"];
1731
+ var COMMIT_STRENGTHS = ["genuine", "weak", "tool_report", "operator"];
1732
+ var TURN_REASONS = [
1733
+ // commits
1734
+ "turn_end",
1735
+ "weak_end_confirmed",
1736
+ "transcript_final",
1737
+ "worker_reported",
1738
+ "finalization_timeout_no_response",
1739
+ "session_error",
1740
+ "provider_auth_failed",
1741
+ "provider_billing_failed",
1742
+ "operator_cancel",
1743
+ "intentional_cleanup",
1744
+ "task_removed",
1745
+ "mission_abandoned",
1746
+ "superseded",
1747
+ "operator_update",
1748
+ "refine_terminal",
1749
+ "validation_terminal",
1750
+ "hard_ceiling",
1751
+ "reclaim_budget_exhausted",
1752
+ "hollow_max_retries",
1753
+ "migration_orphan",
1754
+ // reclaims (generation + 1)
1755
+ "dispatch_refused_session_exited",
1756
+ "dispatch_refused_no_target",
1757
+ "dispatch_refused_unsupported_input",
1758
+ "dispatch_failed",
1759
+ "session_exit",
1760
+ "session_exit_before_turn",
1761
+ "session_dead",
1762
+ "hollow_completion",
1763
+ "assigned_stranded_dispatch_unconfirmed",
1764
+ "delivered_not_consumed_redrive",
1765
+ "delivered_no_turn_deadline"
1766
+ ];
1767
+ var NOTIFY_KINDS = [
1768
+ "completed",
1769
+ "failed",
1770
+ "cancelled",
1771
+ "stopped",
1772
+ "approval",
1773
+ "choice",
1774
+ "approval_resolved",
1775
+ "candidate",
1776
+ "no_progress",
1777
+ "progress",
1778
+ "late_completion",
1779
+ "mesh_event"
1780
+ ];
1781
+ var id = { t: "id" };
1782
+ var idOpt = { t: "id", optional: true };
1783
+ var bool = { t: "bool" };
1784
+ var boolOpt = { t: "bool", optional: true };
1785
+ var ms = { t: "ms" };
1786
+ var msOpt = { t: "ms", optional: true };
1787
+ var intOpt = { t: "int", optional: true };
1788
+ var en = (values) => ({ t: "enum", values });
1789
+ var enOpt = (values) => ({ t: "enum", values, optional: true });
1790
+ var EVIDENCE_ENVELOPE_FIELD_SPECS = {
1791
+ eventId: id,
1792
+ at: ms,
1793
+ source: en(EVIDENCE_SOURCE_IDS),
1794
+ sessionId: id,
1795
+ attemptRef: { t: "attempt_ref", optional: true },
1796
+ taskId: idOpt,
1797
+ observedBy: id
1798
+ };
1799
+ var TURN_EVIDENCE_FIELD_SPECS = {
1800
+ dispatch_accepted: {
1801
+ scope: en(TURN_SCOPES),
1802
+ messageId: id,
1803
+ meshId: idOpt,
1804
+ nodeId: idOpt,
1805
+ providerType: idOpt,
1806
+ attemptNo: intOpt,
1807
+ dispatchNonce: intOpt,
1808
+ consumeProfile: enOpt(CONSUME_PROFILES),
1809
+ maxTaskRetries: intOpt,
1810
+ coordinator: { t: "coordinator", optional: true }
1811
+ },
1812
+ delivered: { messageId: id, outcome: en(DELIVERY_OUTCOMES), via: en(DELIVERY_VIAS) },
1813
+ delivery_refused: { messageId: id, reason: en(SEND_REFUSAL_REASONS) },
1814
+ dispatch_failed: { workerAbsent: bool, reason: en(DISPATCH_FAILURE_REASONS), refusalCode: idOpt },
1815
+ duplicate_dispatch_refusal: { holderSessionId: id, holderAttemptId: idOpt },
1816
+ session_rebound: { toSessionId: id, reason: en(SESSION_REBOUND_REASONS) },
1817
+ turn_started: { retro: bool },
1818
+ suspension: { modal: en(SUSPENSION_MODALS), modalKey: idOpt },
1819
+ suspension_resolved: { resolution: en(SUSPENSION_RESOLUTIONS), via: en(SUSPENSION_RESOLUTION_VIAS) },
1820
+ turn_end: {
1821
+ strength: en(TURN_END_STRENGTHS),
1822
+ afterFinalizationTimeout: boolOpt,
1823
+ hollow: boolOpt,
1824
+ summary: { t: "summary_ref", optional: true },
1825
+ blockReason: enOpt(TURN_END_BLOCK_REASONS),
1826
+ releasedByHardCap: boolOpt,
1827
+ nativeOutcome: enOpt(NATIVE_TURN_OUTCOMES),
1828
+ live: { t: "live", optional: true },
1829
+ reportExpected: boolOpt
1830
+ },
1831
+ transcript_final: {
1832
+ selfAttributing: bool,
1833
+ nativeRead: bool,
1834
+ nativeMarker: { t: "native_marker", optional: true },
1835
+ live: { t: "live" },
1836
+ summary: { t: "summary_ref", optional: true },
1837
+ messageAt: msOpt
1838
+ },
1839
+ transcript_activity: { newestActivityAt: ms },
1840
+ no_progress: { stalledMs: ms, observedStatus: en(NO_PROGRESS_OBSERVED_STATUSES), finalAssistantPresent: bool },
1841
+ liveness: { result: en(LIVENESS_RESULTS) },
1842
+ process_exit: { exitCode: { t: "int", nullable: true }, providerFailure: enOpt(PROVIDER_FAILURES) },
1843
+ session_error: { reason: en(SESSION_ERROR_REASONS) },
1844
+ worker_report: {
1845
+ outcome: en(WORKER_REPORT_OUTCOMES),
1846
+ summary: { t: "summary_ref", optional: true },
1847
+ hasHandoffNotes: bool,
1848
+ branchState: enOpt(WORKER_BRANCH_STATES),
1849
+ touchedFileCount: intOpt
1850
+ },
1851
+ worker_progress: { note: { t: "summary_ref", optional: true } },
1852
+ git_side_effect: { dirty: bool, commitsSinceDispatch: { t: "int" }, attributable: bool },
1853
+ cancel: { reason: en(CANCEL_REASONS) },
1854
+ operator_status: { status: en(OPERATOR_STATUSES), reason: en(OPERATOR_STATUS_REASONS) },
1855
+ coordinator_ack: { notify: en(NOTIFY_KINDS), outcome: en(COORDINATOR_ACK_OUTCOMES) },
1856
+ hold_expired: { holdId: id, reason: en(HOLD_REASONS) }
1857
+ };
1858
+ var TURN_EVIDENCE_KINDS = Object.keys(TURN_EVIDENCE_FIELD_SPECS);
1859
+ var TERMINAL_CLASS_EVIDENCE_KINDS = [
1860
+ "turn_end",
1861
+ "transcript_final",
1862
+ "no_progress",
1863
+ "worker_report",
1864
+ "session_error",
1865
+ "process_exit",
1866
+ "cancel",
1867
+ "operator_status"
1868
+ ];
1869
+ var IDENTIFIER_RE = /^[^\s\u0000-\u001f\u007f]{1,256}$/;
1870
+ function makeGuard2(values) {
1871
+ const set = new Set(values);
1872
+ return (value) => typeof value === "string" && set.has(value);
1873
+ }
1874
+ var isEvidenceSourceId = makeGuard2(EVIDENCE_SOURCE_IDS);
1875
+ var isTurnEvidenceKind = makeGuard2(TURN_EVIDENCE_KINDS);
1876
+ var isTurnReason = makeGuard2(TURN_REASONS);
1877
+ var isNotifyKind = makeGuard2(NOTIFY_KINDS);
1878
+ var isHoldReason = makeGuard2(HOLD_REASONS);
1879
+ var isTurnOutcome = makeGuard2(TURN_OUTCOMES);
1880
+ var isCommitStrength = makeGuard2(COMMIT_STRENGTHS);
1881
+ function isRecord2(value) {
1882
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1883
+ }
1884
+ function isEvidenceIdentifier(value) {
1885
+ return typeof value === "string" && IDENTIFIER_RE.test(value);
1886
+ }
1887
+ function isFiniteNumber2(value) {
1888
+ return typeof value === "number" && Number.isFinite(value);
1889
+ }
1890
+ function isSummaryRef(value) {
1891
+ return isRecord2(value) && hasOnlyKeys(value, ["topic", "writer", "seq"]) && isEvidenceIdentifier(value.topic) && isEvidenceIdentifier(value.writer) && Number.isSafeInteger(value.seq) && value.seq >= 0;
1892
+ }
1893
+ function isTurnAttemptRef(value) {
1894
+ return isRecord2(value) && hasOnlyKeys(value, ["attemptId", "generation"]) && isEvidenceIdentifier(value.attemptId) && Number.isSafeInteger(value.generation) && value.generation >= 0;
1895
+ }
1896
+ function isLiveTurnPending(value) {
1897
+ 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));
1898
+ }
1899
+ function isNativeMarkerRef(value) {
1900
+ return isRecord2(value) && hasOnlyKeys(value, ["outcome", "turnId"]) && NATIVE_TURN_OUTCOMES.includes(value.outcome) && (value.turnId === void 0 || isEvidenceIdentifier(value.turnId));
1901
+ }
1902
+ function isCoordinatorIdentity(value) {
1903
+ return isRecord2(value) && hasOnlyKeys(value, ["daemonId", "coordinatorRunId", "sessionId"]) && isEvidenceIdentifier(value.daemonId) && isEvidenceIdentifier(value.coordinatorRunId) && (value.sessionId === void 0 || isEvidenceIdentifier(value.sessionId));
1904
+ }
1905
+ function hasOnlyKeys(value, allowed) {
1906
+ for (const key of Object.keys(value)) {
1907
+ if (!allowed.includes(key)) return false;
1908
+ }
1909
+ return true;
1910
+ }
1911
+ function fieldMatches(spec, value) {
1912
+ if (value === void 0) return spec.optional === true;
1913
+ switch (spec.t) {
1914
+ case "id":
1915
+ return isEvidenceIdentifier(value);
1916
+ case "enum":
1917
+ return typeof value === "string" && spec.values.includes(value);
1918
+ case "bool":
1919
+ return typeof value === "boolean";
1920
+ case "int":
1921
+ return value === null && spec.nullable === true || Number.isSafeInteger(value);
1922
+ case "ms":
1923
+ return isFiniteNumber2(value) && value >= 0;
1924
+ case "summary_ref":
1925
+ return isSummaryRef(value);
1926
+ case "attempt_ref":
1927
+ return isTurnAttemptRef(value);
1928
+ case "live":
1929
+ return isLiveTurnPending(value);
1930
+ case "native_marker":
1931
+ return isNativeMarkerRef(value);
1932
+ case "coordinator":
1933
+ return isCoordinatorIdentity(value);
1934
+ }
1935
+ }
1936
+ function isTurnEvidence(value) {
1937
+ if (!isRecord2(value) || !isTurnEvidenceKind(value.kind)) return false;
1938
+ const bodySpecs = TURN_EVIDENCE_FIELD_SPECS[value.kind];
1939
+ const envelopeSpecs = EVIDENCE_ENVELOPE_FIELD_SPECS;
1940
+ for (const key of Object.keys(value)) {
1941
+ if (key === "kind") continue;
1942
+ if (!(key in bodySpecs) && !(key in envelopeSpecs)) return false;
1943
+ }
1944
+ for (const [key, spec] of Object.entries(envelopeSpecs)) {
1945
+ if (!fieldMatches(spec, value[key])) return false;
1946
+ }
1947
+ for (const [key, spec] of Object.entries(bodySpecs)) {
1948
+ if (!fieldMatches(spec, value[key])) return false;
1949
+ }
1950
+ return true;
1951
+ }
1952
+ function isTerminalClassEvidenceKind(kind) {
1953
+ return TERMINAL_CLASS_EVIDENCE_KINDS.includes(kind);
1954
+ }
1955
+ var TURN_EVIDENCE_FLAGS = ["hollow", "afterFinalizationTimeout", "nativeMarker", "selfAttributing"];
1956
+ var MESH_TOPIC_ENTRY_KINDS = ["turn.evidence", "turn.committed", "turn.notify", "mesh.record"];
1957
+ var isMeshTopicEntryKind = makeGuard2(MESH_TOPIC_ENTRY_KINDS);
1958
+ function isOptionalId(value) {
1959
+ return value === void 0 || isEvidenceIdentifier(value);
1960
+ }
1961
+ function isGeneration(value) {
1962
+ return Number.isSafeInteger(value) && value >= 0;
1963
+ }
1964
+ function isProjectedScalars(value) {
1965
+ if (!isRecord2(value)) return false;
1966
+ for (const v of Object.values(value)) {
1967
+ if (!(v === null || typeof v === "number" || typeof v === "boolean" || typeof v === "string")) return false;
1968
+ }
1969
+ return true;
1970
+ }
1971
+ function isMeshTopicEntry(value) {
1972
+ if (!isRecord2(value)) return false;
1973
+ if (value.v !== MESH_TOPIC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.eventId) || !isFiniteNumber2(value.at)) return false;
1974
+ switch (value.k) {
1975
+ case "turn.evidence": {
1976
+ if (!isEvidenceIdentifier(value.attemptId) || !isGeneration(value.generation)) return false;
1977
+ if (!isEvidenceIdentifier(value.ownerDaemonId) || !isEvidenceIdentifier(value.sessionId) || !isOptionalId(value.taskId)) return false;
1978
+ if (!isTurnEvidenceKind(value.ev)) return false;
1979
+ if (value.strength !== void 0 && !TURN_END_STRENGTHS.includes(value.strength)) return false;
1980
+ if (value.flags !== void 0) {
1981
+ if (!isRecord2(value.flags)) return false;
1982
+ for (const [flag, on] of Object.entries(value.flags)) {
1983
+ if (!TURN_EVIDENCE_FLAGS.includes(flag) || typeof on !== "boolean") return false;
1984
+ }
1985
+ }
1986
+ if (value.evidence !== void 0 && !(isTurnEvidence(value.evidence) && value.evidence.kind === value.ev)) return false;
1987
+ return true;
1988
+ }
1989
+ case "turn.committed":
1990
+ return isEvidenceIdentifier(value.attemptId) && isGeneration(value.generation) && isOptionalId(value.taskId) && isTurnOutcome(value.outcome) && isCommitStrength(value.strength) && isTurnReason(value.reason);
1991
+ case "turn.notify":
1992
+ return isOptionalId(value.attemptId) && isNotifyKind(value.notify) && isEvidenceIdentifier(value.targetDaemonId) && isOptionalId(value.targetSessionId) && isOptionalId(value.taskId);
1993
+ case "mesh.record":
1994
+ return isEvidenceIdentifier(value.ledgerKind) && isOptionalId(value.nodeId) && isOptionalId(value.sessionId) && isOptionalId(value.taskId) && isProjectedScalars(value.payload);
1995
+ default:
1996
+ return false;
1997
+ }
1998
+ }
1999
+ function projectTurnEvidenceEntry(evidence, attempt) {
2000
+ const flags = {};
2001
+ if (evidence.kind === "turn_end") {
2002
+ if (evidence.hollow) flags.hollow = true;
2003
+ if (evidence.afterFinalizationTimeout) flags.afterFinalizationTimeout = true;
2004
+ }
2005
+ if (evidence.kind === "transcript_final") {
2006
+ if (evidence.nativeMarker) flags.nativeMarker = true;
2007
+ if (evidence.selfAttributing) flags.selfAttributing = true;
2008
+ }
2009
+ const taskId = evidence.taskId;
2010
+ return {
2011
+ v: MESH_TOPIC_PROTOCOL_VERSION,
2012
+ eventId: evidence.eventId,
2013
+ at: evidence.at,
2014
+ k: "turn.evidence",
2015
+ attemptId: attempt.attemptId,
2016
+ generation: attempt.generation,
2017
+ ownerDaemonId: attempt.ownerDaemonId,
2018
+ ...taskId ? { taskId } : {},
2019
+ sessionId: evidence.sessionId,
2020
+ ev: evidence.kind,
2021
+ ...evidence.kind === "turn_end" ? { strength: evidence.strength } : {},
2022
+ ...Object.keys(flags).length > 0 ? { flags } : {},
2023
+ evidence
2024
+ };
2025
+ }
2026
+
2027
+ // src/session-launch.ts
2028
+ var MODEL_AXIS_SOURCES = [
2029
+ /** Picked explicitly for this launch (dashboard dropdown, coordinator dialog). */
2030
+ "user",
2031
+ /** The dashboard dialog restored it from the last launch (browser-local memory). */
2032
+ "remembered",
2033
+ /** A mesh capability slot supplied it (or a difficulty preset the slot outranked). */
2034
+ "mesh_slot",
2035
+ /** An explicit per-task model / thinking level on a mesh queue task. */
2036
+ "task_override",
2037
+ /** Nothing was requested; the provider's default is known (discovery / manifest). */
2038
+ "provider_default",
2039
+ /** A value was requested without saying where it came from, or nothing is known. */
2040
+ "unspecified"
2041
+ ];
2042
+ function isModelAxisSource(value) {
2043
+ return typeof value === "string" && MODEL_AXIS_SOURCES.includes(value);
2044
+ }
2045
+ var SESSION_LAUNCHED_BY = ["dashboard", "mesh", "cli", "api", "restore"];
2046
+ function isSessionLaunchedBy(value) {
2047
+ return typeof value === "string" && SESSION_LAUNCHED_BY.includes(value);
2048
+ }
2049
+ var MODEL_SELECTION_HISTORY_LIMIT = 20;
2050
+ function effectiveModelSelectionValue(selection) {
2051
+ if (!selection) return void 0;
2052
+ const last = Array.isArray(selection.history) ? selection.history[selection.history.length - 1] : void 0;
2053
+ return last?.value ?? selection.current ?? selection.observed ?? launchModelSelectionValue(selection);
2054
+ }
2055
+ function launchModelSelectionValue(selection) {
2056
+ if (!selection) return void 0;
2057
+ const launch = Array.isArray(selection.history) ? selection.history.find((entry) => entry.via === "launch") : void 0;
2058
+ return launch?.value ?? selection.launchValue ?? selection.requested ?? selection.resolvedDefault;
2059
+ }
2060
+ function describeModelSelection(selection) {
2061
+ const value = effectiveModelSelectionValue(selection);
2062
+ if (!selection || !value) return void 0;
2063
+ const launched = launchModelSelectionValue(selection);
2064
+ return {
2065
+ value,
2066
+ ...launched && launched !== value ? { changedFrom: launched } : {},
2067
+ source: isModelAxisSource(selection.source) ? selection.source : "unspecified"
2068
+ };
2069
+ }
2070
+ var MODEL_IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/@[\]+-]{0,95}$/;
2071
+ function sanitizeModelIdentifier(value) {
2072
+ if (typeof value !== "string") return void 0;
2073
+ const trimmed = value.trim();
2074
+ return MODEL_IDENTIFIER_PATTERN.test(trimmed) ? trimmed : void 0;
2075
+ }
2076
+ function readString2(value) {
2077
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
2078
+ }
2079
+ function readFiniteNumber(value) {
2080
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
2081
+ }
2082
+ function parseModelSelection(raw) {
2083
+ if (!raw || typeof raw !== "object") return void 0;
2084
+ const record = raw;
2085
+ const history = [];
2086
+ if (Array.isArray(record.history)) {
2087
+ for (const entry of record.history) {
2088
+ if (!entry || typeof entry !== "object") continue;
2089
+ const e = entry;
2090
+ const value = readString2(e.value);
2091
+ const at = readFiniteNumber(e.at);
2092
+ const via = e.via === "launch" || e.via === "change_model" || e.via === "observed" ? e.via : void 0;
2093
+ if (value && at !== void 0 && via) history.push({ at, value, via });
2094
+ }
2095
+ }
2096
+ const requested = readString2(record.requested);
2097
+ const launchValue = readString2(record.launchValue);
2098
+ const resolvedDefault = readString2(record.resolvedDefault);
2099
+ const current = readString2(record.current);
2100
+ const observed = readString2(record.observed);
2101
+ const observedAt = readFiniteNumber(record.observedAt);
2102
+ return {
2103
+ source: isModelAxisSource(record.source) ? record.source : "unspecified",
2104
+ ...requested ? { requested } : {},
2105
+ ...launchValue ? { launchValue } : {},
2106
+ ...resolvedDefault ? { resolvedDefault } : {},
2107
+ ...current ? { current } : {},
2108
+ ...observed ? { observed } : {},
2109
+ ...observedAt !== void 0 ? { observedAt } : {},
2110
+ history: history.slice(-MODEL_SELECTION_HISTORY_LIMIT)
2111
+ };
2112
+ }
2113
+ function parseSessionLaunchRecord(raw) {
2114
+ if (!raw || typeof raw !== "object") return void 0;
2115
+ const record = raw;
2116
+ const sessionId = readString2(record.sessionId);
2117
+ const providerType = readString2(record.providerType);
2118
+ const launchedAt = readFiniteNumber(record.launchedAt);
2119
+ const model = parseModelSelection(record.model);
2120
+ const thinkingLevel = parseModelSelection(record.thinkingLevel);
2121
+ if (!sessionId || !providerType || launchedAt === void 0 || !model || !thinkingLevel) return void 0;
2122
+ const providerVersion = readString2(record.providerVersion);
2123
+ const workspace = readString2(record.workspace);
2124
+ const autoApproveModeId = readString2(record.autoApproveModeId);
2125
+ return {
2126
+ sessionId,
2127
+ providerType,
2128
+ ...providerVersion ? { providerVersion } : {},
2129
+ ...record.providerChannel === "stable" || record.providerChannel === "preview" ? { providerChannel: record.providerChannel } : {},
2130
+ launchedBy: isSessionLaunchedBy(record.launchedBy) ? record.launchedBy : "api",
2131
+ launchedAt,
2132
+ ...workspace ? { workspace } : {},
2133
+ model,
2134
+ thinkingLevel,
2135
+ ...autoApproveModeId ? { autoApproveModeId } : {}
2136
+ };
2137
+ }
2138
+
2139
+ // src/turn-ipc.ts
2140
+ var TURN_IPC_PROTOCOL_VERSION = 1;
2141
+ function isFiniteNumber3(value) {
2142
+ return typeof value === "number" && Number.isFinite(value);
2143
+ }
2144
+ function isNonNegativeInt(value) {
2145
+ return Number.isSafeInteger(value) && value >= 0;
2146
+ }
2147
+ function isOptionalId2(value) {
2148
+ return value === void 0 || isEvidenceIdentifier(value);
2149
+ }
2150
+ function hasOnlyKeys2(value, allowed) {
2151
+ for (const key of Object.keys(value)) {
2152
+ if (!allowed.includes(key)) return false;
2153
+ }
2154
+ return true;
2155
+ }
2156
+ var TURN_IPC_ERROR_CODES = ["daemon_required", "turn_ledger_unavailable", "ledger_not_owner"];
2157
+ function makeGuard3(values) {
2158
+ const set = new Set(values);
2159
+ return (value) => typeof value === "string" && set.has(value);
2160
+ }
2161
+ var isTurnIpcErrorCode = makeGuard3(TURN_IPC_ERROR_CODES);
2162
+ function isTurnIpcError(value) {
2163
+ return isRecord(value) && hasOnlyKeys2(value, ["code", "detail"]) && isTurnIpcErrorCode(value.code) && (value.detail === void 0 || typeof value.detail === "string");
2164
+ }
2165
+ var TURN_OBSERVE_VERDICTS = ["applied", "recorded", "rejected"];
2166
+ var isTurnObserveVerdict = makeGuard3(TURN_OBSERVE_VERDICTS);
2167
+ function isTurnObserveRequest(value) {
2168
+ return isRecord(value) && hasOnlyKeys2(value, ["v", "evidence"]) && value.v === TURN_IPC_PROTOCOL_VERSION && isTurnEvidence(value.evidence);
2169
+ }
2170
+ function decodeTurnObserveRequest(value) {
2171
+ return isTurnObserveRequest(value) ? value : null;
2172
+ }
2173
+ function isTurnAttemptRefValue(value) {
2174
+ return isRecord(value) && hasOnlyKeys2(value, ["attemptId", "generation"]) && isEvidenceIdentifier(value.attemptId) && isNonNegativeInt(value.generation);
2175
+ }
2176
+ function isTurnObserveResponse(value) {
2177
+ return isRecord(value) && hasOnlyKeys2(value, ["verdict", "attemptRef", "outcome"]) && isTurnObserveVerdict(value.verdict) && isTurnAttemptRefValue(value.attemptRef) && (value.outcome === void 0 || isTurnOutcomeValue(value.outcome));
2178
+ }
2179
+ var TURN_OUTCOMES_LOCAL = ["completed", "failed", "cancelled"];
2180
+ function isTurnOutcomeValue(value) {
2181
+ return typeof value === "string" && TURN_OUTCOMES_LOCAL.includes(value);
2182
+ }
2183
+ function decodeTurnObserveResponse(value) {
2184
+ return isTurnObserveResponse(value) ? value : null;
2185
+ }
2186
+ var MESH_RECORD_PAYLOAD_KEYS = [
2187
+ // Identifiers
2188
+ "taskId",
2189
+ "deliveryId",
2190
+ "attemptId",
2191
+ "missionId",
2192
+ "checkpointId",
2193
+ "promptId",
2194
+ "providerSessionId",
2195
+ "targetNoteId",
2196
+ // Routing / addressing
2197
+ "nodeId",
2198
+ "sessionId",
2199
+ "providerType",
2200
+ "transport",
2201
+ "attemptedSessionId",
2202
+ "holderSessionId",
2203
+ // Outcome enums
2204
+ "reason",
2205
+ "status",
2206
+ "outcome",
2207
+ "terminalKind",
2208
+ "event",
2209
+ "source",
2210
+ "intentionalStopReason",
2211
+ // Booleans
2212
+ "retryable",
2213
+ "rebound",
2214
+ "forced",
2215
+ "fallback",
2216
+ "membershipRemoved",
2217
+ "requestedForce",
2218
+ "removedByRemoteDaemon",
2219
+ "completedViaReady",
2220
+ "intentional",
2221
+ "weak",
2222
+ // Counters
2223
+ "attempt",
2224
+ "attemptCount",
2225
+ "count"
2226
+ ];
2227
+ var MESH_RECORD_PAYLOAD_KEY_SET = new Set(MESH_RECORD_PAYLOAD_KEYS);
2228
+ var MAX_MESH_RECORD_STRING = 200;
2229
+ function isProjectedScalarsValue(value) {
2230
+ if (!isRecord(value)) return false;
2231
+ for (const v of Object.values(value)) {
2232
+ if (v === null) continue;
2233
+ if (typeof v === "boolean" || typeof v === "number") continue;
2234
+ if (typeof v === "string") {
2235
+ if (v.length > MAX_MESH_RECORD_STRING) return false;
2236
+ continue;
2237
+ }
2238
+ return false;
2239
+ }
2240
+ return true;
2241
+ }
2242
+ function isMeshRecordPayload(value) {
2243
+ if (!isProjectedScalarsValue(value)) return false;
2244
+ for (const key of Object.keys(value)) {
2245
+ if (!MESH_RECORD_PAYLOAD_KEY_SET.has(key)) return false;
2246
+ }
2247
+ return true;
2248
+ }
2249
+ function isMeshRecordRequest(value) {
2250
+ 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);
2251
+ }
2252
+ function decodeMeshRecordRequest(value) {
2253
+ return isMeshRecordRequest(value) ? value : null;
2254
+ }
2255
+ function isMeshRecordResponse(value) {
2256
+ return isRecord(value) && hasOnlyKeys2(value, ["eventId", "seq"]) && isEvidenceIdentifier(value.eventId) && isNonNegativeInt(value.seq);
2257
+ }
2258
+ function decodeMeshRecordResponse(value) {
2259
+ return isMeshRecordResponse(value) ? value : null;
2260
+ }
2261
+ function isTurnCancelRequest(value) {
2262
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "attemptId", "taskId", "reason"])) return false;
2263
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION) return false;
2264
+ const hasAttempt = value.attemptId !== void 0;
2265
+ const hasTask = value.taskId !== void 0;
2266
+ if (hasAttempt === hasTask) return false;
2267
+ if (hasAttempt && !isEvidenceIdentifier(value.attemptId)) return false;
2268
+ if (hasTask && !isEvidenceIdentifier(value.taskId)) return false;
2269
+ return isTurnReason(value.reason);
2270
+ }
2271
+ function decodeTurnCancelRequest(value) {
2272
+ return isTurnCancelRequest(value) ? value : null;
2273
+ }
2274
+ function isTurnCancelResponse(value) {
2275
+ return isRecord(value) && hasOnlyKeys2(value, ["attemptRef", "verdict"]) && isTurnAttemptRefValue(value.attemptRef) && isTurnObserveVerdict(value.verdict);
2276
+ }
2277
+ function decodeTurnCancelResponse(value) {
2278
+ return isTurnCancelResponse(value) ? value : null;
2279
+ }
2280
+ var OPERATOR_STATUS_VALUES = ["completed", "failed"];
2281
+ var isOperatorStatusValue = makeGuard3(OPERATOR_STATUS_VALUES);
2282
+ var OPERATOR_STATUS_REASON_VALUES = ["operator_update", "refine_terminal", "validation_terminal"];
2283
+ var isOperatorStatusReasonValue = makeGuard3(OPERATOR_STATUS_REASON_VALUES);
2284
+ function isOperatorStatusRequest(value) {
2285
+ return isRecord(value) && hasOnlyKeys2(value, ["v", "taskId", "status", "reason"]) && value.v === TURN_IPC_PROTOCOL_VERSION && isEvidenceIdentifier(value.taskId) && isOperatorStatusValue(value.status) && isOperatorStatusReasonValue(value.reason);
2286
+ }
2287
+ function decodeOperatorStatusRequest(value) {
2288
+ return isOperatorStatusRequest(value) ? value : null;
2289
+ }
2290
+ function isOperatorStatusResponse(value) {
2291
+ return isRecord(value) && hasOnlyKeys2(value, ["accepted"]) && value.accepted === true;
2292
+ }
2293
+ function decodeOperatorStatusResponse(value) {
2294
+ return isOperatorStatusResponse(value) ? value : null;
2295
+ }
2296
+ function isTurnQueryRequest(value) {
2297
+ 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));
2298
+ }
2299
+ function decodeTurnQueryRequest(value) {
2300
+ return isTurnQueryRequest(value) ? value : null;
2301
+ }
2302
+ var TURN_QUERY_ATTEMPT_ROW_KEYS = [
2303
+ "attemptId",
2304
+ "generation",
2305
+ "meshId",
2306
+ "taskId",
2307
+ "sessionId",
2308
+ "nodeId",
2309
+ "providerType",
2310
+ "state",
2311
+ "terminalOutcome",
2312
+ "terminalReason",
2313
+ "acceptedAt",
2314
+ "terminalAt"
2315
+ ];
2316
+ function isTurnQueryAttemptRow(value) {
2317
+ if (!isRecord(value) || !hasOnlyKeys2(value, TURN_QUERY_ATTEMPT_ROW_KEYS)) return false;
2318
+ if (!isEvidenceIdentifier(value.attemptId) || !isNonNegativeInt(value.generation)) return false;
2319
+ if (!isOptionalId2(value.meshId) || !isOptionalId2(value.taskId)) return false;
2320
+ if (!isEvidenceIdentifier(value.sessionId)) return false;
2321
+ if (!isOptionalId2(value.nodeId) || !isOptionalId2(value.providerType)) return false;
2322
+ if (typeof value.state !== "string") return false;
2323
+ if (value.terminalOutcome !== void 0 && !isTurnOutcomeValue(value.terminalOutcome)) return false;
2324
+ if (value.terminalReason !== void 0 && !isTurnReason(value.terminalReason)) return false;
2325
+ if (!isFiniteNumber3(value.acceptedAt)) return false;
2326
+ if (value.terminalAt !== void 0 && !isFiniteNumber3(value.terminalAt)) return false;
2327
+ return true;
2328
+ }
2329
+ var TURN_QUERY_EVENT_VERDICTS = ["applied", "recorded", "rejected", "forwarded"];
2330
+ var TURN_QUERY_EVENT_ROW_KEYS = ["eventId", "attemptId", "generation", "sessionId", "kind", "source", "verdict", "atMs"];
2331
+ function isTurnQueryEventRow(value) {
2332
+ if (!isRecord(value) || !hasOnlyKeys2(value, TURN_QUERY_EVENT_ROW_KEYS)) return false;
2333
+ if (!isEvidenceIdentifier(value.eventId)) return false;
2334
+ if (!isOptionalId2(value.attemptId)) return false;
2335
+ if (value.generation !== void 0 && !isNonNegativeInt(value.generation)) return false;
2336
+ if (!isEvidenceIdentifier(value.sessionId)) return false;
2337
+ if (typeof value.kind !== "string") return false;
2338
+ if (typeof value.source !== "string") return false;
2339
+ if (!TURN_QUERY_EVENT_VERDICTS.includes(value.verdict)) return false;
2340
+ if (!isFiniteNumber3(value.atMs)) return false;
2341
+ return true;
2342
+ }
2343
+ function isTurnQueryResponse(value) {
2344
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["attempts", "events", "replicationPending"])) return false;
2345
+ if (!Array.isArray(value.attempts) || !value.attempts.every(isTurnQueryAttemptRow)) return false;
2346
+ if (!Array.isArray(value.events) || !value.events.every(isTurnQueryEventRow)) return false;
2347
+ if (value.replicationPending !== void 0 && typeof value.replicationPending !== "boolean") return false;
2348
+ return true;
2349
+ }
2350
+ function decodeTurnQueryResponse(value) {
2351
+ return isTurnQueryResponse(value) ? value : null;
2352
+ }
2353
+ var MESH_INDEX_QUERY_WRITER_SCOPES = ["own", "fleet"];
2354
+ var isMeshIndexQueryWriterScope = makeGuard3(MESH_INDEX_QUERY_WRITER_SCOPES);
2355
+ function isMeshIndexQueryRequest(value) {
2356
+ 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));
2357
+ }
2358
+ function decodeMeshIndexQueryRequest(value) {
2359
+ return isMeshIndexQueryRequest(value) ? value : null;
2360
+ }
2361
+ var MESH_TOPIC_INDEX_ROW_KEYS = [
2362
+ "writer",
2363
+ "seq",
2364
+ "meshId",
2365
+ "eventId",
2366
+ "kind",
2367
+ "ledgerKind",
2368
+ "taskId",
2369
+ "sessionId",
2370
+ "nodeId",
2371
+ "atMs",
2372
+ "payload"
2373
+ ];
2374
+ function isMeshTopicIndexRow(value) {
2375
+ if (!isRecord(value) || !hasOnlyKeys2(value, MESH_TOPIC_INDEX_ROW_KEYS)) return false;
2376
+ if (!isEvidenceIdentifier(value.writer) || !isNonNegativeInt(value.seq)) return false;
2377
+ if (!isEvidenceIdentifier(value.meshId) || !isEvidenceIdentifier(value.eventId)) return false;
2378
+ if (typeof value.kind !== "string") return false;
2379
+ if (!isOptionalId2(value.ledgerKind) || !isOptionalId2(value.taskId) || !isOptionalId2(value.sessionId) || !isOptionalId2(value.nodeId)) return false;
2380
+ if (!isFiniteNumber3(value.atMs)) return false;
2381
+ if (!isMeshRecordPayload(value.payload)) return false;
2382
+ return true;
2383
+ }
2384
+ function isMeshIndexQueryResponse(value) {
2385
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["rows", "replicationPending"])) return false;
2386
+ if (!Array.isArray(value.rows) || !value.rows.every(isMeshTopicIndexRow)) return false;
2387
+ if (value.replicationPending !== void 0 && typeof value.replicationPending !== "boolean") return false;
2388
+ return true;
2389
+ }
2390
+ function decodeMeshIndexQueryResponse(value) {
2391
+ return isMeshIndexQueryResponse(value) ? value : null;
2392
+ }
2393
+ var MESH_MISSION_STATUSES = ["active", "paused", "completed", "abandoned"];
2394
+ var isMeshMissionStatusValue = makeGuard3(MESH_MISSION_STATUSES);
2395
+ var MESH_MISSION_SOURCES = ["magi", "coordinator"];
2396
+ var isMeshMissionSourceValue = makeGuard3(MESH_MISSION_SOURCES);
2397
+ function isStringArray(value) {
2398
+ return Array.isArray(value) && value.every((v) => typeof v === "string");
2399
+ }
2400
+ function isMissionBriefWire(value) {
2401
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["goal", "constraints", "doneCriteria", "handoffNotes", "ownedPaths"])) return false;
2402
+ if (typeof value.goal !== "string" || value.goal.trim().length === 0) return false;
2403
+ for (const k of ["constraints", "doneCriteria", "handoffNotes", "ownedPaths"]) {
2404
+ if (value[k] !== void 0 && !isStringArray(value[k])) return false;
2405
+ }
2406
+ return true;
2407
+ }
2408
+ function isMeshMissionRecordWire(value) {
2409
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["id", "meshId", "title", "goal", "status", "source", "brief"])) return false;
2410
+ if (!isEvidenceIdentifier(value.id) || !isEvidenceIdentifier(value.meshId)) return false;
2411
+ if (typeof value.title !== "string" || typeof value.goal !== "string") return false;
2412
+ if (!isMeshMissionStatusValue(value.status)) return false;
2413
+ if (value.source !== void 0 && !isMeshMissionSourceValue(value.source)) return false;
2414
+ if (value.brief !== void 0 && !isMissionBriefWire(value.brief)) return false;
2415
+ return true;
2416
+ }
2417
+ function isMissionUpsertRequest(value) {
2418
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "id", "title", "goal", "status", "source", "brief"])) return false;
2419
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION) return false;
2420
+ if (!isEvidenceIdentifier(value.meshId)) return false;
2421
+ if (value.id !== void 0 && !isEvidenceIdentifier(value.id)) return false;
2422
+ if (typeof value.title !== "string" || value.title.trim().length === 0) return false;
2423
+ if (value.goal !== void 0 && typeof value.goal !== "string") return false;
2424
+ if (value.status !== void 0 && !isMeshMissionStatusValue(value.status)) return false;
2425
+ if (value.source !== void 0 && !isMeshMissionSourceValue(value.source)) return false;
2426
+ if (value.brief !== void 0 && value.brief !== null && !isMissionBriefWire(value.brief)) return false;
2427
+ return true;
2428
+ }
2429
+ function decodeMissionUpsertRequest(value) {
2430
+ return isMissionUpsertRequest(value) ? value : null;
2431
+ }
2432
+ function isMissionUpsertResponse(value) {
2433
+ return isRecord(value) && hasOnlyKeys2(value, ["mission"]) && isMeshMissionRecordWire(value.mission);
2434
+ }
2435
+ function decodeMissionUpsertResponse(value) {
2436
+ return isMissionUpsertResponse(value) ? value : null;
2437
+ }
2438
+ function isMissionQueryRequest(value) {
2439
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "statuses", "id"])) return false;
2440
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION) return false;
2441
+ if (!isEvidenceIdentifier(value.meshId)) return false;
2442
+ if (value.id !== void 0 && !isEvidenceIdentifier(value.id)) return false;
2443
+ if (value.statuses !== void 0) {
2444
+ if (!Array.isArray(value.statuses) || value.statuses.length === 0) return false;
2445
+ if (!value.statuses.every(isMeshMissionStatusValue)) return false;
2446
+ }
2447
+ return true;
2448
+ }
2449
+ function decodeMissionQueryRequest(value) {
2450
+ return isMissionQueryRequest(value) ? value : null;
2451
+ }
2452
+ function isMissionQueryResponse(value) {
2453
+ return isRecord(value) && hasOnlyKeys2(value, ["missions"]) && Array.isArray(value.missions) && value.missions.every(isMeshMissionRecordWire);
2454
+ }
2455
+ function decodeMissionQueryResponse(value) {
2456
+ return isMissionQueryResponse(value) ? value : null;
2457
+ }
2458
+ function isMissionListQueryRequest(value) {
2459
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "statuses", "verbose", "includeMagi", "withStats", "limit", "historyIdLimit", "meshStatusView"])) return false;
2460
+ if (value.meshStatusView !== void 0 && value.meshStatusView !== "compact" && value.meshStatusView !== "verbose") return false;
2461
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION) return false;
2462
+ if (!isEvidenceIdentifier(value.meshId)) return false;
2463
+ if (value.statuses !== void 0) {
2464
+ if (!Array.isArray(value.statuses) || value.statuses.length === 0) return false;
2465
+ if (!value.statuses.every(isMeshMissionStatusValue)) return false;
2466
+ }
2467
+ if (value.verbose !== void 0 && typeof value.verbose !== "boolean") return false;
2468
+ if (value.includeMagi !== void 0 && typeof value.includeMagi !== "boolean") return false;
2469
+ if (value.withStats !== void 0 && typeof value.withStats !== "boolean") return false;
2470
+ if (value.limit !== void 0 && !isNonNegativeInt(value.limit)) return false;
2471
+ if (value.historyIdLimit !== void 0 && !isNonNegativeInt(value.historyIdLimit)) return false;
2472
+ return true;
2473
+ }
2474
+ function decodeMissionListQueryRequest(value) {
2475
+ return isMissionListQueryRequest(value) ? value : null;
2476
+ }
2477
+ function isMeshMissionTaskAggregateWire(value) {
2478
+ const keys = ["total", "pending", "assigned", "completed", "failed", "cancelled", "blocked", "lastActivityAt"];
2479
+ if (!isRecord(value) || !hasOnlyKeys2(value, keys)) return false;
2480
+ for (const k of ["total", "pending", "assigned", "completed", "failed", "cancelled", "blocked"]) {
2481
+ if (!isNonNegativeInt(value[k])) return false;
2482
+ }
2483
+ return value.lastActivityAt === null || typeof value.lastActivityAt === "string";
2484
+ }
2485
+ function isMeshMissionStatsWire(value) {
2486
+ const keys = ["missionId", "taskCount", "completed", "failed", "totalDurationMs", "wallClockMs", "retries", "incompleteTaskIds"];
2487
+ if (!isRecord(value) || !hasOnlyKeys2(value, keys)) return false;
2488
+ if (!isEvidenceIdentifier(value.missionId)) return false;
2489
+ for (const k of ["taskCount", "completed", "failed", "totalDurationMs", "retries"]) {
2490
+ if (!isNonNegativeInt(value[k])) return false;
2491
+ }
2492
+ if (value.wallClockMs !== null && !isNonNegativeInt(value.wallClockMs)) return false;
2493
+ if (!Array.isArray(value.incompleteTaskIds) || !value.incompleteTaskIds.every(isEvidenceIdentifier)) return false;
2494
+ return true;
2495
+ }
2496
+ function isMissionListSummaryWire(value) {
2497
+ if (!isRecord(value)) return false;
2498
+ const hasGoal = "goal" in value;
2499
+ const hasPreview = "goalPreview" in value && "goalTruncated" in value;
2500
+ if (hasGoal === hasPreview) return false;
2501
+ const baseKeys = ["id", "meshId", "title", "status", "source", "tasks", "stats", "brief", "createdAt", "updatedAt", "closeCandidateEmittedAt"];
2502
+ const allowed = hasGoal ? [...baseKeys, "goal"] : [...baseKeys, "goalPreview", "goalTruncated"];
2503
+ if (!hasOnlyKeys2(value, allowed)) return false;
2504
+ if (!isEvidenceIdentifier(value.id) || !isEvidenceIdentifier(value.meshId)) return false;
2505
+ if (typeof value.title !== "string") return false;
2506
+ if (!isMeshMissionStatusValue(value.status)) return false;
2507
+ if (value.source !== void 0 && !isMeshMissionSourceValue(value.source)) return false;
2508
+ if (!isMeshMissionTaskAggregateWire(value.tasks)) return false;
2509
+ if (value.stats !== void 0 && !isMeshMissionStatsWire(value.stats)) return false;
2510
+ if (value.brief !== void 0 && !isMissionBriefWire(value.brief)) return false;
2511
+ if (hasGoal && typeof value.goal !== "string") return false;
2512
+ if (hasPreview && (typeof value.goalPreview !== "string" || typeof value.goalTruncated !== "boolean")) return false;
2513
+ if (value.createdAt !== void 0 && typeof value.createdAt !== "string") return false;
2514
+ if (value.updatedAt !== void 0 && typeof value.updatedAt !== "string") return false;
2515
+ if (value.closeCandidateEmittedAt !== void 0 && value.closeCandidateEmittedAt !== null && typeof value.closeCandidateEmittedAt !== "string") return false;
2516
+ return true;
2517
+ }
2518
+ function isMeshMissionHistoryFoldWire(value) {
2519
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["count", "byStatus", "missionIds", "note"])) return false;
2520
+ if (!isNonNegativeInt(value.count)) return false;
2521
+ if (!isRecord(value.byStatus) || !Object.values(value.byStatus).every((n) => isNonNegativeInt(n))) return false;
2522
+ if (!Array.isArray(value.missionIds) || !value.missionIds.every(isEvidenceIdentifier)) return false;
2523
+ return typeof value.note === "string";
2524
+ }
2525
+ function isMissionListQueryResponse(value) {
2526
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["missions", "historyFold", "truncated", "matched", "overflowIds"])) return false;
2527
+ if (!Array.isArray(value.missions) || !value.missions.every(isMissionListSummaryWire)) return false;
2528
+ if (value.historyFold !== null && !isMeshMissionHistoryFoldWire(value.historyFold)) return false;
2529
+ if (typeof value.truncated !== "boolean") return false;
2530
+ if (!isNonNegativeInt(value.matched)) return false;
2531
+ if (value.overflowIds !== void 0 && (!Array.isArray(value.overflowIds) || !value.overflowIds.every(isEvidenceIdentifier))) return false;
2532
+ return true;
2533
+ }
2534
+ function decodeMissionListQueryResponse(value) {
2535
+ return isMissionListQueryResponse(value) ? value : null;
2536
+ }
2537
+ var OPERATING_NOTE_CATEGORIES = ["provider_quirk", "pattern_to_avoid", "recovery_lesson"];
2538
+ var isOperatingNoteCategory = makeGuard3(OPERATING_NOTE_CATEGORIES);
2539
+ function isOptionalShortString(value, max = 512) {
2540
+ return value === void 0 || typeof value === "string" && value.trim().length > 0 && value.length <= max;
2541
+ }
2542
+ function isNoteUpsertRequest(value) {
2543
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "text", "category", "pinned", "expiresAt", "supersedes", "subjectKey", "sourceCoordinator"])) return false;
2544
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION) return false;
2545
+ if (!isEvidenceIdentifier(value.meshId)) return false;
2546
+ if (typeof value.text !== "string" || value.text.trim().length === 0) return false;
2547
+ if (value.category !== void 0 && !isOperatingNoteCategory(value.category)) return false;
2548
+ if (value.pinned !== void 0 && typeof value.pinned !== "boolean") return false;
2549
+ if (value.expiresAt !== void 0 && (typeof value.expiresAt !== "string" || Number.isNaN(Date.parse(value.expiresAt)))) return false;
2550
+ return isOptionalShortString(value.supersedes) && isOptionalShortString(value.subjectKey) && isOptionalShortString(value.sourceCoordinator);
2551
+ }
2552
+ function decodeNoteUpsertRequest(value) {
2553
+ return isNoteUpsertRequest(value) ? value : null;
2554
+ }
2555
+ function isNoteUpsertResponse(value) {
2556
+ return isRecord(value) && hasOnlyKeys2(value, ["noteId", "deduped", "createdAt"]) && isEvidenceIdentifier(value.noteId) && typeof value.deduped === "boolean" && typeof value.createdAt === "string";
2557
+ }
2558
+ function decodeNoteUpsertResponse(value) {
2559
+ return isNoteUpsertResponse(value) ? value : null;
2560
+ }
2561
+ function isNoteForgetRequest(value) {
2562
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "noteId", "text", "reason"])) return false;
2563
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION) return false;
2564
+ if (!isEvidenceIdentifier(value.meshId)) return false;
2565
+ if (value.noteId !== void 0 && !isEvidenceIdentifier(value.noteId)) return false;
2566
+ if (value.text !== void 0 && (typeof value.text !== "string" || value.text.trim().length === 0)) return false;
2567
+ if (value.noteId === void 0 && value.text === void 0) return false;
2568
+ return value.reason === void 0 || typeof value.reason === "string";
2569
+ }
2570
+ function decodeNoteForgetRequest(value) {
2571
+ return isNoteForgetRequest(value) ? value : null;
2572
+ }
2573
+ function isNoteForgetResponse(value) {
2574
+ return isRecord(value) && hasOnlyKeys2(value, ["matched", "tombstoneId"]) && typeof value.matched === "number" && Number.isInteger(value.matched) && value.matched >= 0 && isEvidenceIdentifier(value.tombstoneId);
2575
+ }
2576
+ function decodeNoteForgetResponse(value) {
2577
+ return isNoteForgetResponse(value) ? value : null;
2578
+ }
2579
+ var TOOL_CALLER_ROLES = ["coordinator", "unknown"];
2580
+ var isToolCallerRole = makeGuard3(TOOL_CALLER_ROLES);
2581
+ function isToolCallRecordRequest(value) {
2582
+ 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);
2583
+ }
2584
+ function decodeToolCallRecordRequest(value) {
2585
+ return isToolCallRecordRequest(value) ? value : null;
2586
+ }
2587
+ function isToolCallRecordResponse(value) {
2588
+ return isRecord(value) && hasOnlyKeys2(value, ["rateLimitExceeded", "callsInWindow", "advisory"]) && typeof value.rateLimitExceeded === "boolean" && isNonNegativeInt(value.callsInWindow) && (value.advisory === null || typeof value.advisory === "string");
2589
+ }
2590
+ function decodeToolCallRecordResponse(value) {
2591
+ return isToolCallRecordResponse(value) ? value : null;
2592
+ }
2593
+ function isLedgerQueryRequest(value) {
2594
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "kind", "since", "node", "tail", "includeSummary"])) return false;
2595
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION) return false;
2596
+ if (!isEvidenceIdentifier(value.meshId)) return false;
2597
+ if (value.kind !== void 0 && (!Array.isArray(value.kind) || value.kind.length === 0 || !value.kind.every(isEvidenceIdentifier))) return false;
2598
+ if (value.since !== void 0 && typeof value.since !== "string") return false;
2599
+ if (!isOptionalId2(value.node)) return false;
2600
+ if (value.tail !== void 0 && !isNonNegativeInt(value.tail)) return false;
2601
+ if (value.includeSummary !== void 0 && typeof value.includeSummary !== "boolean") return false;
2602
+ return true;
2603
+ }
2604
+ function decodeLedgerQueryRequest(value) {
2605
+ return isLedgerQueryRequest(value) ? value : null;
2606
+ }
2607
+ var LEDGER_QUERY_ENTRY_KEYS = ["id", "meshId", "timestamp", "kind", "nodeId", "sessionId", "providerType", "taskId", "payload"];
2608
+ function isLedgerQueryEntryWire(value) {
2609
+ if (!isRecord(value) || !hasOnlyKeys2(value, LEDGER_QUERY_ENTRY_KEYS)) return false;
2610
+ if (!isEvidenceIdentifier(value.id) || !isEvidenceIdentifier(value.meshId)) return false;
2611
+ if (typeof value.timestamp !== "string" || typeof value.kind !== "string") return false;
2612
+ if (!isOptionalId2(value.nodeId) || !isOptionalId2(value.sessionId) || !isOptionalId2(value.providerType) || !isOptionalId2(value.taskId)) return false;
2613
+ if (!isRecord(value.payload)) return false;
2614
+ return true;
2615
+ }
2616
+ function isLedgerQuerySummaryWire(value) {
2617
+ const keys = ["meshId", "totalEntries", "taskDispatched", "taskCompleted", "taskFailed", "taskStalled", "sessionLaunched", "checkpointCreated", "lastActivityAt", "recentFailures"];
2618
+ if (!isRecord(value) || !hasOnlyKeys2(value, keys)) return false;
2619
+ if (!isEvidenceIdentifier(value.meshId)) return false;
2620
+ for (const k of ["totalEntries", "taskDispatched", "taskCompleted", "taskFailed", "taskStalled", "sessionLaunched", "checkpointCreated", "recentFailures"]) {
2621
+ if (!isNonNegativeInt(value[k])) return false;
2622
+ }
2623
+ if (value.lastActivityAt !== null && typeof value.lastActivityAt !== "string") return false;
2624
+ return true;
2625
+ }
2626
+ function isLedgerQueryResponse(value) {
2627
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["entries", "summary"])) return false;
2628
+ if (!Array.isArray(value.entries) || !value.entries.every(isLedgerQueryEntryWire)) return false;
2629
+ if (value.summary !== void 0 && !isLedgerQuerySummaryWire(value.summary)) return false;
2630
+ return true;
2631
+ }
2632
+ function decodeLedgerQueryResponse(value) {
2633
+ return isLedgerQueryResponse(value) ? value : null;
2634
+ }
2635
+ function isRecordArray(value) {
2636
+ return Array.isArray(value) && value.every(isRecord);
2637
+ }
2638
+ function isOptionalRecord(value) {
2639
+ return value === void 0 || isRecord(value);
2640
+ }
2641
+ function isOptionalBoolean(value) {
2642
+ return value === void 0 || typeof value === "boolean";
2643
+ }
2644
+ function isOptionalString(value) {
2645
+ return value === void 0 || typeof value === "string";
2646
+ }
2647
+ function isQueueEntryWire(value) {
2648
+ return isRecord(value) && isEvidenceIdentifier(value.id) && typeof value.status === "string";
2649
+ }
2650
+ function isRecordLocalRequest(value) {
2651
+ 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);
2652
+ }
2653
+ function decodeRecordLocalRequest(value) {
2654
+ return isRecordLocalRequest(value) ? value : null;
2655
+ }
2656
+ function isRecordLocalResponse(value) {
2657
+ return isRecord(value) && hasOnlyKeys2(value, ["eventId", "timestamp", "storedLocally", "published"]) && isEvidenceIdentifier(value.eventId) && typeof value.timestamp === "string" && typeof value.storedLocally === "boolean" && typeof value.published === "boolean";
2658
+ }
2659
+ function decodeRecordLocalResponse(value) {
2660
+ return isRecordLocalResponse(value) ? value : null;
2661
+ }
2662
+ function isQueueQueryRequest(value) {
2663
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "statuses", "taskId", "view", "withCounts", "historicalOlderThanMs", "withDependencyHeads"])) return false;
2664
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId)) return false;
2665
+ if (value.statuses !== void 0 && (!Array.isArray(value.statuses) || !value.statuses.every(isEvidenceIdentifier))) return false;
2666
+ if (value.historicalOlderThanMs !== void 0 && !isNonNegativeInt(value.historicalOlderThanMs)) return false;
2667
+ return isOptionalId2(value.taskId) && isOptionalBoolean(value.view) && isOptionalBoolean(value.withCounts) && isOptionalBoolean(value.withDependencyHeads);
2668
+ }
2669
+ function decodeQueueQueryRequest(value) {
2670
+ return isQueueQueryRequest(value) ? value : null;
2671
+ }
2672
+ function isQueueDependencyHeadWire(value) {
2673
+ 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");
2674
+ }
2675
+ function isQueueQueryResponse(value) {
2676
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["entries", "counts", "oldHistoricalCount", "dependencyHeads"])) return false;
2677
+ if (!Array.isArray(value.entries) || !value.entries.every(isQueueEntryWire)) return false;
2678
+ if (value.counts !== void 0 && (!isRecord(value.counts) || !Object.values(value.counts).every(isNonNegativeInt))) return false;
2679
+ if (value.oldHistoricalCount !== void 0 && !isNonNegativeInt(value.oldHistoricalCount)) return false;
2680
+ if (value.dependencyHeads !== void 0 && (!Array.isArray(value.dependencyHeads) || !value.dependencyHeads.every(isQueueDependencyHeadWire))) return false;
2681
+ return true;
2682
+ }
2683
+ function decodeQueueQueryResponse(value) {
2684
+ return isQueueQueryResponse(value) ? value : null;
2685
+ }
2686
+ function isQueueEnqueueRequest(value) {
2687
+ 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);
2688
+ }
2689
+ function decodeQueueEnqueueRequest(value) {
2690
+ return isQueueEnqueueRequest(value) ? value : null;
2691
+ }
2692
+ function isQueueEnqueueResponse(value) {
2693
+ return isRecord(value) && hasOnlyKeys2(value, ["entry"]) && isQueueEntryWire(value.entry);
2694
+ }
2695
+ function decodeQueueEnqueueResponse(value) {
2696
+ return isQueueEnqueueResponse(value) ? value : null;
2697
+ }
2698
+ function isQueueEnqueueGraphRequest(value) {
2699
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "mode", "specs", "plan", "audit"])) return false;
2700
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId)) return false;
2701
+ if (value.mode === "compat") return isRecordArray(value.specs) && value.plan === void 0 && isOptionalRecord(value.audit);
2702
+ if (value.mode === "graph") return isRecord(value.plan) && value.specs === void 0 && isOptionalRecord(value.audit);
2703
+ return false;
2704
+ }
2705
+ function decodeQueueEnqueueGraphRequest(value) {
2706
+ return isQueueEnqueueGraphRequest(value) ? value : null;
2707
+ }
2708
+ function isQueueEnqueueGraphResponse(value) {
2709
+ if (!isRecord(value)) return false;
2710
+ if (value.ok === true) {
2711
+ return hasOnlyKeys2(value, ["ok", "tasks", "graph"]) && Array.isArray(value.tasks) && value.tasks.every(isQueueEntryWire) && isOptionalRecord(value.graph);
2712
+ }
2713
+ if (value.ok === false) {
2714
+ return hasOnlyKeys2(value, ["ok", "refusalCode", "message", "extra"]) && typeof value.message === "string" && isOptionalString(value.refusalCode) && isOptionalRecord(value.extra);
2715
+ }
2716
+ return false;
2717
+ }
2718
+ function decodeQueueEnqueueGraphResponse(value) {
2719
+ return isQueueEnqueueGraphResponse(value) ? value : null;
2720
+ }
2721
+ function isQueueCancelRequest(value) {
2722
+ return isRecord(value) && hasOnlyKeys2(value, ["v", "meshId", "taskId", "reason"]) && value.v === TURN_IPC_PROTOCOL_VERSION && isEvidenceIdentifier(value.meshId) && isEvidenceIdentifier(value.taskId) && isOptionalString(value.reason);
2723
+ }
2724
+ function decodeQueueCancelRequest(value) {
2725
+ return isQueueCancelRequest(value) ? value : null;
2726
+ }
2727
+ function isQueueCancelResponse(value) {
2728
+ return isRecord(value) && hasOnlyKeys2(value, ["task", "before"]) && (value.task === null || isQueueEntryWire(value.task)) && (value.before === null || isQueueEntryWire(value.before));
2729
+ }
2730
+ function decodeQueueCancelResponse(value) {
2731
+ return isQueueCancelResponse(value) ? value : null;
2732
+ }
2733
+ function isQueueRequeueRequest(value) {
2734
+ return isRecord(value) && hasOnlyKeys2(value, ["v", "meshId", "taskId", "options"]) && value.v === TURN_IPC_PROTOCOL_VERSION && isEvidenceIdentifier(value.meshId) && isEvidenceIdentifier(value.taskId) && isOptionalRecord(value.options);
2735
+ }
2736
+ function decodeQueueRequeueRequest(value) {
2737
+ return isQueueRequeueRequest(value) ? value : null;
2738
+ }
2739
+ function isQueueRequeueResponse(value) {
2740
+ return isRecord(value) && hasOnlyKeys2(value, ["task"]) && (value.task === null || isQueueEntryWire(value.task));
2741
+ }
2742
+ function decodeQueueRequeueResponse(value) {
2743
+ return isQueueRequeueResponse(value) ? value : null;
2744
+ }
2745
+ function isDirectDispatchRecordRequest(value) {
2746
+ 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);
2747
+ }
2748
+ function decodeDirectDispatchRecordRequest(value) {
2749
+ return isDirectDispatchRecordRequest(value) ? value : null;
2750
+ }
2751
+ function isDirectDispatchRecordResponse(value) {
2752
+ return isRecord(value) && hasOnlyKeys2(value, ["taskRecorded", "decisionRecorded"]) && typeof value.taskRecorded === "boolean" && typeof value.decisionRecorded === "boolean";
2753
+ }
2754
+ function decodeDirectDispatchRecordResponse(value) {
2755
+ return isDirectDispatchRecordResponse(value) ? value : null;
2756
+ }
2757
+ var GRAPH_AUDIT_EVENTS = ["gate_claimed", "gate_released", "gate_abandoned", "node_patched"];
2758
+ var isGraphAuditEvent = makeGuard3(GRAPH_AUDIT_EVENTS);
2759
+ function isGraphAuditRecordRequest(value) {
2760
+ return isRecord(value) && hasOnlyKeys2(value, ["v", "meshId", "event", "fields"]) && value.v === TURN_IPC_PROTOCOL_VERSION && isEvidenceIdentifier(value.meshId) && isGraphAuditEvent(value.event) && isRecord(value.fields);
2761
+ }
2762
+ function decodeGraphAuditRecordRequest(value) {
2763
+ return isGraphAuditRecordRequest(value) ? value : null;
2764
+ }
2765
+ function isGraphAuditRecordResponse(value) {
2766
+ return isRecord(value) && hasOnlyKeys2(value, ["recorded"]) && typeof value.recorded === "boolean";
2767
+ }
2768
+ function decodeGraphAuditRecordResponse(value) {
2769
+ return isGraphAuditRecordResponse(value) ? value : null;
2770
+ }
2771
+ function isActiveWorkQueryRequest(value) {
2772
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "nodes", "queue", "recordTail", "includeTerminalDirect", "compute", "includeInputs", "includeSummary", "includeSchedulingRuntime", "mesh"])) return false;
2773
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId)) return false;
2774
+ if (value.nodes !== void 0 && !isRecordArray(value.nodes)) return false;
2775
+ if (value.queue !== void 0 && !isRecordArray(value.queue)) return false;
2776
+ if (value.recordTail !== void 0 && !isNonNegativeInt(value.recordTail)) return false;
2777
+ return isOptionalBoolean(value.includeTerminalDirect) && isOptionalBoolean(value.compute) && isOptionalBoolean(value.includeInputs) && isOptionalBoolean(value.includeSummary) && isOptionalBoolean(value.includeSchedulingRuntime) && isOptionalRecord(value.mesh);
2778
+ }
2779
+ function decodeActiveWorkQueryRequest(value) {
2780
+ return isActiveWorkQueryRequest(value) ? value : null;
2781
+ }
2782
+ function isActiveWorkQueryResponse(value) {
2783
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["activeWork", "records", "directDispatches", "summary", "schedulingRuntime"])) return false;
2784
+ if (value.records !== void 0 && !isRecordArray(value.records)) return false;
2785
+ if (value.directDispatches !== void 0 && !isRecordArray(value.directDispatches)) return false;
2786
+ return isOptionalRecord(value.activeWork) && isOptionalRecord(value.summary) && isOptionalRecord(value.schedulingRuntime);
2787
+ }
2788
+ function decodeActiveWorkQueryResponse(value) {
2789
+ return isActiveWorkQueryResponse(value) ? value : null;
2790
+ }
2791
+ function isRecoveryContextQueryRequest(value) {
2792
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "nodeId", "sessionId", "maxRetries", "nodeIds"])) return false;
2793
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId)) return false;
2794
+ if (!isOptionalId2(value.nodeId) || !isOptionalId2(value.sessionId)) return false;
2795
+ if (value.maxRetries !== void 0 && !isNonNegativeInt(value.maxRetries)) return false;
2796
+ if (value.nodeIds !== void 0) {
2797
+ if (!Array.isArray(value.nodeIds) || value.nodeIds.length === 0 || !value.nodeIds.every(isEvidenceIdentifier)) return false;
2798
+ return value.nodeId === void 0 && value.sessionId === void 0;
2799
+ }
2800
+ return value.nodeId !== void 0 || value.sessionId !== void 0;
2801
+ }
2802
+ function decodeRecoveryContextQueryRequest(value) {
2803
+ return isRecoveryContextQueryRequest(value) ? value : null;
2804
+ }
2805
+ function isRecoveryContextWire(value) {
2806
+ return isRecord(value) && typeof value.consecutiveNodeFailures === "number";
2807
+ }
2808
+ function isRecoveryContextQueryResponse(value) {
2809
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["context", "contexts"])) return false;
2810
+ if (value.context === void 0 && value.contexts === void 0) return false;
2811
+ if (value.context !== void 0 && !isRecoveryContextWire(value.context)) return false;
2812
+ if (value.contexts !== void 0 && (!isRecord(value.contexts) || !Object.values(value.contexts).every(isRecoveryContextWire))) return false;
2813
+ return true;
2814
+ }
2815
+ function decodeRecoveryContextQueryResponse(value) {
2816
+ return isRecoveryContextQueryResponse(value) ? value : null;
2817
+ }
2818
+ function isGraphGateClaimRequest(value) {
2819
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "gateId", "coordinatorSessionId", "leaseSeconds", "extendDeadlineSeconds", "probeConvergenceEvidence"])) return false;
2820
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId) || !isEvidenceIdentifier(value.gateId) || !isEvidenceIdentifier(value.coordinatorSessionId)) return false;
2821
+ if (value.leaseSeconds !== void 0 && !isFiniteNumber3(value.leaseSeconds)) return false;
2822
+ if (value.extendDeadlineSeconds !== void 0 && !isFiniteNumber3(value.extendDeadlineSeconds)) return false;
2823
+ return isOptionalBoolean(value.probeConvergenceEvidence);
2824
+ }
2825
+ function decodeGraphGateClaimRequest(value) {
2826
+ return isGraphGateClaimRequest(value) ? value : null;
2827
+ }
2828
+ function isGraphGateClaimResponse(value) {
2829
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["claimed", "reason", "gate", "leaseGeneration", "fencingToken", "leaseExpiresAt", "deadlineAt", "ambiguousExternalOutcome", "previousLeaseOwnerSessionId", "convergenceEvidence"])) return false;
2830
+ if (typeof value.claimed !== "boolean") return false;
2831
+ return isOptionalRecord(value.gate) && isOptionalRecord(value.convergenceEvidence) && isOptionalBoolean(value.ambiguousExternalOutcome);
2832
+ }
2833
+ function decodeGraphGateClaimResponse(value) {
2834
+ return isGraphGateClaimResponse(value) ? value : null;
2835
+ }
2836
+ function isGraphGateReleaseRequest(value) {
2837
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "gateId", "fencingToken", "leaseGeneration", "idempotencyKey", "outcome", "result", "evidence", "patches"])) return false;
2838
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId) || !isEvidenceIdentifier(value.gateId)) return false;
2839
+ if (typeof value.fencingToken !== "string" || !value.fencingToken) return false;
2840
+ if (!isFiniteNumber3(value.leaseGeneration)) return false;
2841
+ if (typeof value.idempotencyKey !== "string" || !value.idempotencyKey) return false;
2842
+ if (typeof value.outcome !== "string" || !value.outcome) return false;
2843
+ if (value.patches !== void 0) {
2844
+ if (!Array.isArray(value.patches)) return false;
2845
+ for (const p of value.patches) {
2846
+ if (!isRecord(p) || typeof p.node !== "string" || !p.node || !isRecord(p.baseSpecPatch)) return false;
2847
+ }
2848
+ }
2849
+ return true;
2850
+ }
2851
+ function decodeGraphGateReleaseRequest(value) {
2852
+ return isGraphGateReleaseRequest(value) ? value : null;
2853
+ }
2854
+ function isGraphGateReleaseResponse(value) {
2855
+ if (!isRecord(value)) return false;
2856
+ if (value.released === true) {
2857
+ if (!hasOnlyKeys2(value, ["released", "duplicate", "gate", "materializedNodeIds", "downstreamNodeCount", "graphCompleted"])) return false;
2858
+ if (typeof value.duplicate !== "boolean") return false;
2859
+ if (!Array.isArray(value.materializedNodeIds) || !value.materializedNodeIds.every((n) => typeof n === "string")) return false;
2860
+ if (value.downstreamNodeCount !== void 0 && !isNonNegativeInt(value.downstreamNodeCount)) return false;
2861
+ return isOptionalRecord(value.gate) && isOptionalBoolean(value.graphCompleted);
2862
+ }
2863
+ if (value.released === false) {
2864
+ return hasOnlyKeys2(value, ["released", "refusalCode", "message"]) && typeof value.message === "string" && isOptionalString(value.refusalCode);
2865
+ }
2866
+ return false;
2867
+ }
2868
+ function decodeGraphGateReleaseResponse(value) {
2869
+ return isGraphGateReleaseResponse(value) ? value : null;
2870
+ }
2871
+ function isGraphGateAbandonRequest(value) {
2872
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "gateId", "reason", "coordinatorSessionId", "force"])) return false;
2873
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId) || !isEvidenceIdentifier(value.gateId)) return false;
2874
+ if (typeof value.reason !== "string" || !value.reason) return false;
2875
+ if (value.coordinatorSessionId !== void 0 && !isEvidenceIdentifier(value.coordinatorSessionId)) return false;
2876
+ return isOptionalBoolean(value.force);
2877
+ }
2878
+ function decodeGraphGateAbandonRequest(value) {
2879
+ return isGraphGateAbandonRequest(value) ? value : null;
2880
+ }
2881
+ function isGraphGateAbandonResponse(value) {
2882
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["abandoned", "reason", "gate", "cancelledNodeIds", "cancelledTaskIds", "graphStatus"])) return false;
2883
+ if (typeof value.abandoned !== "boolean") return false;
2884
+ if (!Array.isArray(value.cancelledNodeIds) || !value.cancelledNodeIds.every((n) => typeof n === "string")) return false;
2885
+ if (!Array.isArray(value.cancelledTaskIds) || !value.cancelledTaskIds.every((n) => typeof n === "string")) return false;
2886
+ return isOptionalRecord(value.gate);
2887
+ }
2888
+ function decodeGraphGateAbandonResponse(value) {
2889
+ return isGraphGateAbandonResponse(value) ? value : null;
2890
+ }
2891
+ function isGraphNodePatchRequest(value) {
2892
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "node", "graphId", "baseSpecPatch"])) return false;
2893
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId)) return false;
2894
+ if (typeof value.node !== "string" || !value.node) return false;
2895
+ if (value.graphId !== void 0 && !isEvidenceIdentifier(value.graphId)) return false;
2896
+ return isRecord(value.baseSpecPatch) && Object.keys(value.baseSpecPatch).length > 0;
2897
+ }
2898
+ function decodeGraphNodePatchRequest(value) {
2899
+ return isGraphNodePatchRequest(value) ? value : null;
2900
+ }
2901
+ function isGraphNodePatchResponse(value) {
2902
+ if (!isRecord(value)) return false;
2903
+ if (value.patched === true) {
2904
+ if (!hasOnlyKeys2(value, ["patched", "graphId", "nodeId", "ref", "queueTaskId", "materializationVersion", "state", "outcomeKind", "skippedReason", "blockedReason"])) return false;
2905
+ if (!isEvidenceIdentifier(value.graphId) || !isEvidenceIdentifier(value.nodeId)) return false;
2906
+ if (!isNonNegativeInt(value.materializationVersion)) return false;
2907
+ return typeof value.state === "string" && typeof value.outcomeKind === "string";
2908
+ }
2909
+ if (value.patched === false) {
2910
+ return hasOnlyKeys2(value, ["patched", "refusalCode", "message"]) && typeof value.message === "string" && isOptionalString(value.refusalCode);
2911
+ }
2912
+ return false;
2913
+ }
2914
+ function decodeGraphNodePatchResponse(value) {
2915
+ return isGraphNodePatchResponse(value) ? value : null;
2916
+ }
2917
+ function isGraphViewQueryRequest(value) {
2918
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "graphId", "batchId", "activeOnly", "limit", "probeGateEvidence"])) return false;
2919
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId)) return false;
2920
+ if (value.graphId !== void 0 && !isEvidenceIdentifier(value.graphId)) return false;
2921
+ if (value.batchId !== void 0 && !isEvidenceIdentifier(value.batchId)) return false;
2922
+ if (value.limit !== void 0 && !isNonNegativeInt(value.limit)) return false;
2923
+ return isOptionalBoolean(value.activeOnly) && isOptionalBoolean(value.probeGateEvidence);
2924
+ }
2925
+ function decodeGraphViewQueryRequest(value) {
2926
+ return isGraphViewQueryRequest(value) ? value : null;
2927
+ }
2928
+ function isGraphViewQueryResponse(value) {
2929
+ return isRecord(value) && hasOnlyKeys2(value, ["graphs"]) && isRecordArray(value.graphs);
2930
+ }
2931
+ function decodeGraphViewQueryResponse(value) {
2932
+ return isGraphViewQueryResponse(value) ? value : null;
2933
+ }
2934
+ function isTaskStatsQueryRequest(value) {
2935
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "taskIds", "missionId", "tail", "rollup", "missionIds"])) return false;
2936
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId)) return false;
2937
+ if (value.taskIds !== void 0) {
2938
+ if (!Array.isArray(value.taskIds) || value.taskIds.length === 0 || !value.taskIds.every(isEvidenceIdentifier)) return false;
2939
+ }
2940
+ if (value.missionId !== void 0 && !isEvidenceIdentifier(value.missionId)) return false;
2941
+ if (value.tail !== void 0 && !isNonNegativeInt(value.tail)) return false;
2942
+ if (value.missionIds !== void 0) {
2943
+ if (!Array.isArray(value.missionIds) || value.missionIds.length === 0 || !value.missionIds.every(isEvidenceIdentifier)) return false;
2944
+ if (value.taskIds !== void 0 || value.missionId !== void 0) return false;
2945
+ }
2946
+ if (value.rollup === true && value.missionId === void 0) return false;
2947
+ return isOptionalBoolean(value.rollup);
2948
+ }
2949
+ function decodeTaskStatsQueryRequest(value) {
2950
+ return isTaskStatsQueryRequest(value) ? value : null;
2951
+ }
2952
+ function isTaskStatsQueryResponse(value) {
2953
+ 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));
2954
+ }
2955
+ function decodeTaskStatsQueryResponse(value) {
2956
+ return isTaskStatsQueryResponse(value) ? value : null;
2957
+ }
2958
+ function isPruneStaleDirectRequest(value) {
2959
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "execute", "includeTerminal", "source"])) return false;
2960
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId)) return false;
2961
+ if (value.source !== void 0 && typeof value.source !== "string") return false;
2962
+ return isOptionalBoolean(value.execute) && isOptionalBoolean(value.includeTerminal);
2963
+ }
2964
+ function decodePruneStaleDirectRequest(value) {
2965
+ return isPruneStaleDirectRequest(value) ? value : null;
2966
+ }
2967
+ function isPruneStaleDirectResponse(value) {
2968
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["mode", "includeTerminal", "candidateCount", "prunable", "prunedCount", "preservedUnacknowledged", "preservedLedgerOnly", "preservedNotOrphan"])) return false;
2969
+ if (value.mode !== "execute" && value.mode !== "dry_run") return false;
2970
+ if (typeof value.includeTerminal !== "boolean") return false;
2971
+ if (!isNonNegativeInt(value.candidateCount) || !isNonNegativeInt(value.prunedCount)) return false;
2972
+ return isRecordArray(value.prunable) && isRecordArray(value.preservedUnacknowledged) && isRecordArray(value.preservedLedgerOnly) && isRecordArray(value.preservedNotOrphan);
2973
+ }
2974
+ function decodePruneStaleDirectResponse(value) {
2975
+ return isPruneStaleDirectResponse(value) ? value : null;
2976
+ }
2977
+ function isOrphanedPinnedTaskWire(value) {
2978
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["taskId", "title", "targetSessionId", "targetNodeId", "missionId"])) return false;
2979
+ if (!isEvidenceIdentifier(value.taskId) || !isEvidenceIdentifier(value.targetSessionId)) return false;
2980
+ if (typeof value.title !== "string") return false;
2981
+ if (value.targetNodeId !== void 0 && !isEvidenceIdentifier(value.targetNodeId)) return false;
2982
+ return value.missionId === void 0 || isEvidenceIdentifier(value.missionId);
2983
+ }
2984
+ function isOrphanedPinNotifyRequest(value) {
2985
+ if (!isRecord(value) || !hasOnlyKeys2(value, ["v", "meshId", "stoppedSessionId", "excludeTaskId", "cause", "nodeId", "coordinatorSessionId"])) return false;
2986
+ if (value.v !== TURN_IPC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.meshId) || !isEvidenceIdentifier(value.stoppedSessionId)) return false;
2987
+ if (value.excludeTaskId !== void 0 && !isEvidenceIdentifier(value.excludeTaskId)) return false;
2988
+ if (value.cause !== void 0 && typeof value.cause !== "string") return false;
2989
+ if (value.nodeId !== void 0 && !isEvidenceIdentifier(value.nodeId)) return false;
2990
+ return value.coordinatorSessionId === void 0 || isEvidenceIdentifier(value.coordinatorSessionId);
2991
+ }
2992
+ function decodeOrphanedPinNotifyRequest(value) {
2993
+ return isOrphanedPinNotifyRequest(value) ? value : null;
2994
+ }
2995
+ function isOrphanedPinNotifyResponse(value) {
2996
+ return isRecord(value) && hasOnlyKeys2(value, ["orphans"]) && Array.isArray(value.orphans) && value.orphans.every(isOrphanedPinnedTaskWire);
2997
+ }
2998
+ function decodeOrphanedPinNotifyResponse(value) {
2999
+ return isOrphanedPinNotifyResponse(value) ? value : null;
3000
+ }
3001
+ var TURN_IPC_COMMANDS = [
3002
+ "turn_observe",
3003
+ "mesh_record",
3004
+ "turn_cancel",
3005
+ "operator_status",
3006
+ "turn_query",
3007
+ "mesh_index_query",
3008
+ "mission_upsert",
3009
+ "mission_query",
3010
+ "note_upsert",
3011
+ "note_forget",
3012
+ // C-W9b additions (2026-09-24 14:00 stamp "C-W9"):
3013
+ "tool_call_record",
3014
+ "ledger_query",
3015
+ "mission_list_query",
3016
+ // C-W9a additions (the event ledger retired; the queue behind IPC):
3017
+ "record_local",
3018
+ "queue_query",
3019
+ "queue_enqueue",
3020
+ "queue_enqueue_graph",
3021
+ "queue_cancel",
3022
+ "queue_requeue",
3023
+ "direct_dispatch_record",
3024
+ "graph_audit_record",
3025
+ "active_work_query",
3026
+ "recovery_context_query",
3027
+ // C-W9c additions (2026-09-24 19:00 stamp — the last mcp-server in-process
3028
+ // daemon-core paths: graph gates/plan/patch, mission reads (MAGI), task/
3029
+ // mission stats, orphaned-pin helpers, one prune audit):
3030
+ "graph_gate_claim",
3031
+ "graph_gate_release",
3032
+ "graph_gate_abandon",
3033
+ "graph_node_patch",
3034
+ "graph_view_query",
3035
+ "task_stats_query",
3036
+ "prune_stale_direct",
3037
+ "orphaned_pin_notify"
3038
+ ];
3039
+ var isTurnIpcCommand = makeGuard3(TURN_IPC_COMMANDS);
3040
+
3041
+ // src/path-ownership.ts
3042
+ var MAX_OWNED_PATHS = 64;
3043
+ function toPosix(raw) {
3044
+ return raw.replace(/\\/g, "/");
3045
+ }
3046
+ function normalizeOne(raw, rejected) {
3047
+ if (typeof raw !== "string") {
3048
+ rejected.push({ input: String(raw), reason: "not_a_string" });
3049
+ return null;
3050
+ }
3051
+ const trimmed = raw.trim();
3052
+ if (!trimmed) {
3053
+ rejected.push({ input: raw, reason: "empty" });
3054
+ return null;
3055
+ }
3056
+ let posix = toPosix(trimmed);
3057
+ if (posix.startsWith("/") || /^[a-zA-Z]:\//.test(posix) || posix.startsWith("~")) {
3058
+ rejected.push({ input: raw, reason: "absolute_path" });
3059
+ return null;
3060
+ }
3061
+ posix = posix.replace(/^\.\/+/, "");
3062
+ const segments = posix.split("/").filter(Boolean);
3063
+ if (segments.some((seg) => seg === "..")) {
3064
+ rejected.push({ input: raw, reason: "parent_traversal" });
3065
+ return null;
3066
+ }
3067
+ if (segments.length === 0) {
3068
+ rejected.push({ input: raw, reason: "empty" });
3069
+ return null;
3070
+ }
3071
+ let subtree = false;
3072
+ if (segments[segments.length - 1] === "**") {
3073
+ subtree = true;
3074
+ segments.pop();
3075
+ if (segments.length === 0) {
3076
+ }
3077
+ }
3078
+ if (segments.some((seg) => seg.includes("*") || seg.includes("?"))) {
3079
+ rejected.push({ input: raw, reason: "unsupported_glob" });
3080
+ return null;
3081
+ }
3082
+ return { path: segments.join("/"), subtree };
3083
+ }
3084
+ function normalizeOwnedPaths(input) {
3085
+ const rejected = [];
3086
+ if (input === void 0 || input === null) {
3087
+ return { declaration: { paths: [] }, rejected };
3088
+ }
3089
+ if (!Array.isArray(input)) {
3090
+ return { declaration: { paths: [] }, rejected: [{ input: String(input), reason: "not_an_array" }] };
3091
+ }
3092
+ const byPath = /* @__PURE__ */ new Map();
3093
+ for (const raw of input) {
3094
+ const entry = normalizeOne(raw, rejected);
3095
+ if (!entry) continue;
3096
+ const existing = byPath.get(entry.path);
3097
+ if (!existing) {
3098
+ byPath.set(entry.path, entry);
3099
+ } else if (entry.subtree && !existing.subtree) {
3100
+ byPath.set(entry.path, entry);
3101
+ }
3102
+ }
3103
+ const all = [...byPath.values()];
3104
+ const kept = all.slice(0, MAX_OWNED_PATHS);
3105
+ for (const dropped of all.slice(MAX_OWNED_PATHS)) {
3106
+ rejected.push({ input: dropped.path, reason: "over_cap" });
3107
+ }
3108
+ return { declaration: { paths: kept }, rejected };
3109
+ }
3110
+ function entryContains(base, path) {
3111
+ if (path === base.path) return true;
3112
+ if (base.subtree && (path === base.path || path.startsWith(`${base.path}/`))) return true;
3113
+ return false;
3114
+ }
3115
+ function entriesOverlap(a, b) {
3116
+ if (a.path === b.path) return true;
3117
+ if (a.subtree && (b.path === a.path || b.path.startsWith(`${a.path}/`))) return true;
3118
+ if (b.subtree && (a.path === b.path || a.path.startsWith(`${b.path}/`))) return true;
3119
+ return false;
3120
+ }
3121
+ function pathsOverlap(a, b) {
3122
+ if (a.paths.length === 0 || b.paths.length === 0) return false;
3123
+ for (const pa of a.paths) {
3124
+ for (const pb of b.paths) {
3125
+ if (entriesOverlap(pa, pb)) return true;
3126
+ }
3127
+ }
3128
+ return false;
3129
+ }
3130
+ function findOwnershipConflicts(candidate, inFlight) {
3131
+ if (candidate.paths.length === 0) return [];
3132
+ const conflicts = [];
3133
+ for (const other of inFlight) {
3134
+ if (other.paths.paths.length === 0) continue;
3135
+ const overlappingPaths = [];
3136
+ for (const pa of candidate.paths) {
3137
+ for (const pb of other.paths.paths) {
3138
+ if (entriesOverlap(pa, pb)) {
3139
+ const narrower = pa.path.length >= pb.path.length ? pa.path : pb.path;
3140
+ if (!overlappingPaths.includes(narrower)) overlappingPaths.push(narrower);
3141
+ }
3142
+ }
3143
+ }
3144
+ if (overlappingPaths.length > 0) {
3145
+ conflicts.push({ taskId: other.taskId, overlappingPaths });
3146
+ }
3147
+ }
3148
+ return conflicts;
3149
+ }
3150
+ function touchedFilesOutsideOwnership(touched, owned) {
3151
+ const undeclaredTouched = [];
3152
+ const usedDeclarations = /* @__PURE__ */ new Set();
3153
+ for (const raw of touched ?? []) {
3154
+ const rejectedSink = [];
3155
+ const entry = normalizeOne(raw, rejectedSink);
3156
+ if (!entry) {
3157
+ undeclaredTouched.push(raw);
3158
+ continue;
3159
+ }
3160
+ const matches = owned.paths.filter((base) => entryContains(base, entry.path));
3161
+ if (matches.length === 0) {
3162
+ undeclaredTouched.push(entry.path);
3163
+ } else {
3164
+ for (const m of matches) usedDeclarations.add(m.path);
3165
+ }
3166
+ }
3167
+ const unusedDeclarations = owned.paths.map((p) => p.path).filter((p) => !usedDeclarations.has(p));
3168
+ return { undeclaredTouched, unusedDeclarations };
3169
+ }
995
3170
  export {
3171
+ CANCEL_REASONS,
996
3172
  CANONICAL_MESH_TOOL_COUNT,
997
3173
  CANONICAL_MESH_TOOL_NAMES,
998
3174
  CLAUDE_TUI_REVIEW_PAGE_NOT_FOCUSED_PREFIX,
999
3175
  CLAUDE_TUI_REVIEW_UNCONFIRMED_PREFIX,
1000
3176
  CLI_SLOT_RECIPES,
3177
+ COMMIT_STRENGTHS,
3178
+ CONSUME_PROFILES,
3179
+ COORDINATOR_ACK_OUTCOMES,
3180
+ DAEMON_P2P_SIGNAL_TYPES,
3181
+ DAEMON_STATUS_EVENT_NAMES,
3182
+ DAEMON_TO_DASHBOARD_P2P_TYPES,
3183
+ DAEMON_TO_SERVER_TYPES,
1001
3184
  DAEMON_TO_SERVER_WS_MSGS,
3185
+ DASHBOARD_P2P_MESSAGE_KINDS,
3186
+ DASHBOARD_P2P_SIGNAL_TYPES,
3187
+ DASHBOARD_STATUS_EVENT_NAMES,
3188
+ DASHBOARD_TO_DAEMON_P2P_TYPES,
3189
+ DASHBOARD_TO_USER_SESSION_TYPES,
1002
3190
  DEFAULT_DIFFICULTY_BRAINS,
3191
+ DELIVERY_OUTCOMES,
3192
+ DELIVERY_VIAS,
3193
+ DISPATCH_FAILURE_REASONS,
3194
+ EVIDENCE_ENVELOPE_FIELD_SPECS,
3195
+ EVIDENCE_SOURCE_IDS,
3196
+ GRAPH_AUDIT_EVENTS,
3197
+ HOLD_REASONS,
3198
+ LIVENESS_RESULTS,
1003
3199
  MAGI_RAW_ANSWER_CAP,
3200
+ MAX_MESH_RECORD_STRING,
3201
+ MAX_OWNED_PATHS,
1004
3202
  MESH_CHUNK_KIND,
1005
3203
  MESH_CHUNK_PAYLOAD_CHARS,
1006
3204
  MESH_CHUNK_TTL_MS,
3205
+ MESH_DELIVERY_MODES,
3206
+ MESH_INDEX_QUERY_WRITER_SCOPES,
1007
3207
  MESH_MAX_CHUNKS,
1008
3208
  MESH_MAX_INLINE_FRAME_BYTES,
1009
3209
  MESH_MAX_REASSEMBLED_BYTES,
3210
+ MESH_MISSION_SOURCES,
3211
+ MESH_MISSION_STATUSES,
3212
+ MESH_P2P_SIGNAL_TYPES,
3213
+ MESH_RECORD_PAYLOAD_KEYS,
3214
+ MESH_SESSION_CLEANUP_MODES,
1010
3215
  MESH_TASK_DIFFICULTIES,
3216
+ MESH_TASK_MODES,
3217
+ MESH_TASK_PRIORITIES,
3218
+ MESH_TASK_STATUSES,
3219
+ MESH_TERMINAL_TASK_STATUSES,
3220
+ MESH_THINKING_LEVELS,
3221
+ MESH_TOPIC_ENTRY_KINDS,
3222
+ MESH_TOPIC_PROTOCOL_VERSION,
3223
+ MISSION_BRIEF_RENDER_MAX_CHARS,
3224
+ MODEL_AXIS_SOURCES,
3225
+ MODEL_SELECTION_HISTORY_LIMIT,
1011
3226
  MeshChunkAssembler,
3227
+ NATIVE_TURN_OUTCOMES,
3228
+ NOTIFY_KINDS,
3229
+ NO_PROGRESS_OBSERVED_STATUSES,
3230
+ NPM_UPDATE_TAGS,
3231
+ OPERATING_NOTE_CATEGORIES,
3232
+ OPERATOR_STATUSES,
3233
+ OPERATOR_STATUS_REASONS,
3234
+ OPERATOR_STATUS_REASON_VALUES,
3235
+ OPERATOR_STATUS_VALUES,
3236
+ OUTBOUND_MESSAGE_ORIGINS,
3237
+ P2P_SIGNAL_TYPES,
3238
+ PROVIDER_FAILURES,
1012
3239
  QUOTA_SUPPORTED_PROVIDERS,
3240
+ RECENT_SESSION_BUCKETS,
3241
+ RECLAIMING_SEND_REFUSALS,
3242
+ RELEASE_CHANNELS,
3243
+ RETIRED_MESH_TOOLS,
3244
+ SEND_POLICY_MODES,
3245
+ SEND_REFUSAL_REASONS,
3246
+ SERVER_STATUS_EVENT_NAMES,
3247
+ SERVER_TO_DAEMON_CONTROL_TYPES,
1013
3248
  SERVER_TO_DAEMON_WS_MSGS,
3249
+ SESSION_ERROR_REASONS,
3250
+ SESSION_LAUNCHED_BY,
3251
+ SESSION_REBOUND_REASONS,
3252
+ SESSION_STATUSES,
3253
+ SESSION_STATUS_ALIASES,
3254
+ SESSION_STATUS_CLASS,
3255
+ SHARED_SESSION_TO_VIEWER_TYPES,
1014
3256
  STATUS_PROBE_ARG_KEY,
3257
+ SUSPENSION_MODALS,
3258
+ SUSPENSION_RESOLUTIONS,
3259
+ SUSPENSION_RESOLUTION_VIAS,
3260
+ SYSTEM_ANNOUNCEMENT_TYPES,
3261
+ TERMINAL_CLASS_EVIDENCE_KINDS,
3262
+ TOOL_CALLER_ROLES,
3263
+ TURN_END_BLOCK_REASONS,
3264
+ TURN_END_STRENGTHS,
3265
+ TURN_EVIDENCE_FIELD_SPECS,
3266
+ TURN_EVIDENCE_FLAGS,
3267
+ TURN_EVIDENCE_KINDS,
3268
+ TURN_IPC_COMMANDS,
3269
+ TURN_IPC_ERROR_CODES,
3270
+ TURN_IPC_PROTOCOL_VERSION,
3271
+ TURN_OBSERVE_VERDICTS,
3272
+ TURN_OUTCOMES,
3273
+ TURN_REASONS,
3274
+ TURN_SCOPES,
1015
3275
  UNKNOWN_CLI_SLOT_RECIPE,
3276
+ USER_SESSION_TO_DASHBOARD_TYPES,
3277
+ VERSION_UPDATE_REASONS,
3278
+ VIEWER_TO_SHARED_SESSION_TYPES,
3279
+ WORKER_BRANCH_STATES,
3280
+ WORKER_PROTOCOL_FOOTER_MARKER,
3281
+ WORKER_REPORT_OUTCOMES,
3282
+ WORKER_TOOLS,
3283
+ appendWorkerProtocolFooter,
1016
3284
  argsCarryStatusProbeMarker,
1017
3285
  buildMagiPanelProposal,
1018
3286
  buildSlotProposal,
1019
3287
  canonicalDaemonId,
3288
+ classifySessionStatus,
1020
3289
  compareSemver,
1021
3290
  daemonIdsEquivalent,
3291
+ decodeActiveWorkQueryRequest,
3292
+ decodeActiveWorkQueryResponse,
3293
+ decodeDaemonToDashboardP2P,
3294
+ decodeDaemonToServer,
3295
+ decodeDashboardToDaemonP2P,
3296
+ decodeDashboardToDaemonP2PChunk,
3297
+ decodeDashboardToUserSession,
3298
+ decodeDirectDispatchRecordRequest,
3299
+ decodeDirectDispatchRecordResponse,
3300
+ decodeGraphAuditRecordRequest,
3301
+ decodeGraphAuditRecordResponse,
3302
+ decodeGraphGateAbandonRequest,
3303
+ decodeGraphGateAbandonResponse,
3304
+ decodeGraphGateClaimRequest,
3305
+ decodeGraphGateClaimResponse,
3306
+ decodeGraphGateReleaseRequest,
3307
+ decodeGraphGateReleaseResponse,
3308
+ decodeGraphNodePatchRequest,
3309
+ decodeGraphNodePatchResponse,
3310
+ decodeGraphViewQueryRequest,
3311
+ decodeGraphViewQueryResponse,
3312
+ decodeLedgerQueryRequest,
3313
+ decodeLedgerQueryResponse,
3314
+ decodeMeshIndexQueryRequest,
3315
+ decodeMeshIndexQueryResponse,
3316
+ decodeMeshRecordRequest,
3317
+ decodeMeshRecordResponse,
3318
+ decodeMissionListQueryRequest,
3319
+ decodeMissionListQueryResponse,
3320
+ decodeMissionQueryRequest,
3321
+ decodeMissionQueryResponse,
3322
+ decodeMissionUpsertRequest,
3323
+ decodeMissionUpsertResponse,
3324
+ decodeNoteForgetRequest,
3325
+ decodeNoteForgetResponse,
3326
+ decodeNoteUpsertRequest,
3327
+ decodeNoteUpsertResponse,
3328
+ decodeOperatorStatusRequest,
3329
+ decodeOperatorStatusResponse,
3330
+ decodeOrphanedPinNotifyRequest,
3331
+ decodeOrphanedPinNotifyResponse,
3332
+ decodePruneStaleDirectRequest,
3333
+ decodePruneStaleDirectResponse,
3334
+ decodeQueueCancelRequest,
3335
+ decodeQueueCancelResponse,
3336
+ decodeQueueEnqueueGraphRequest,
3337
+ decodeQueueEnqueueGraphResponse,
3338
+ decodeQueueEnqueueRequest,
3339
+ decodeQueueEnqueueResponse,
3340
+ decodeQueueQueryRequest,
3341
+ decodeQueueQueryResponse,
3342
+ decodeQueueRequeueRequest,
3343
+ decodeQueueRequeueResponse,
3344
+ decodeRecordLocalRequest,
3345
+ decodeRecordLocalResponse,
3346
+ decodeRecoveryContextQueryRequest,
3347
+ decodeRecoveryContextQueryResponse,
3348
+ decodeServerToDaemon,
3349
+ decodeTaskStatsQueryRequest,
3350
+ decodeTaskStatsQueryResponse,
3351
+ decodeToolCallRecordRequest,
3352
+ decodeToolCallRecordResponse,
3353
+ decodeTurnCancelRequest,
3354
+ decodeTurnCancelResponse,
3355
+ decodeTurnObserveRequest,
3356
+ decodeTurnObserveResponse,
3357
+ decodeTurnQueryRequest,
3358
+ decodeTurnQueryResponse,
3359
+ decodeTypeField,
3360
+ decodeUserSessionToDashboard,
3361
+ decodeViewerToSharedSession,
1022
3362
  deriveProviderPriorityFromSlots,
1023
3363
  deriveSlotsFromLegacy,
3364
+ describeModelSelection,
3365
+ effectiveModelSelectionValue,
3366
+ enumOf,
1024
3367
  expandDaemonIdForms,
3368
+ findOwnershipConflicts,
1025
3369
  formatQuotaAccount,
1026
3370
  hasGitStatusEvidence,
3371
+ hasWorkerProtocolFooter,
1027
3372
  interpolateArgs,
1028
3373
  interpolateString,
3374
+ isActiveWorkQueryRequest,
3375
+ isActiveWorkQueryResponse,
3376
+ isBlockedStatus,
3377
+ isBusyStatus,
3378
+ isChunkType,
3379
+ isCommitStrength,
3380
+ isDaemonDirectCommandType,
3381
+ isDaemonP2PSignalType,
3382
+ isDaemonStatusEventName,
3383
+ isDaemonToDashboardP2PType,
3384
+ isDaemonToServerType,
1029
3385
  isDaemonToServerWsMsg,
3386
+ isDashboardP2PSignalType,
3387
+ isDashboardStatusEventName,
3388
+ isDashboardToDaemonChunkType,
3389
+ isDashboardToDaemonP2PType,
3390
+ isDashboardToUserSessionType,
3391
+ isDeadStatus,
3392
+ isDirectDispatchRecordRequest,
3393
+ isDirectDispatchRecordResponse,
1030
3394
  isDowngrade,
3395
+ isEvidenceIdentifier,
3396
+ isEvidenceSourceId,
3397
+ isFiniteNumber,
3398
+ isGraphAuditEvent,
3399
+ isGraphAuditRecordRequest,
3400
+ isGraphAuditRecordResponse,
3401
+ isGraphGateAbandonRequest,
3402
+ isGraphGateAbandonResponse,
3403
+ isGraphGateClaimRequest,
3404
+ isGraphGateClaimResponse,
3405
+ isGraphGateReleaseRequest,
3406
+ isGraphGateReleaseResponse,
3407
+ isGraphNodePatchRequest,
3408
+ isGraphNodePatchResponse,
3409
+ isGraphViewQueryRequest,
3410
+ isGraphViewQueryResponse,
3411
+ isHoldReason,
3412
+ isInputEnvelopeWire,
3413
+ isLedgerQueryRequest,
3414
+ isLedgerQueryResponse,
3415
+ isMeshDeliveryMode,
3416
+ isMeshIndexQueryRequest,
3417
+ isMeshIndexQueryResponse,
3418
+ isMeshIndexQueryWriterScope,
3419
+ isMeshMissionSourceValue,
3420
+ isMeshMissionStatusValue,
3421
+ isMeshP2PSignalType,
3422
+ isMeshRecordPayload,
3423
+ isMeshRecordRequest,
3424
+ isMeshRecordResponse,
3425
+ isMeshSessionCleanupMode,
1031
3426
  isMeshTaskDifficulty,
3427
+ isMeshTaskMode,
3428
+ isMeshTaskPriority,
3429
+ isMeshTaskStatus,
3430
+ isMeshTerminalTaskStatus,
3431
+ isMeshThinkingLevel,
3432
+ isMeshTopicEntry,
3433
+ isMeshTopicEntryKind,
3434
+ isMessageId,
3435
+ isMissionListQueryRequest,
3436
+ isMissionListQueryResponse,
3437
+ isMissionQueryRequest,
3438
+ isMissionQueryResponse,
3439
+ isMissionUpsertRequest,
3440
+ isMissionUpsertResponse,
3441
+ isModelAxisSource,
3442
+ isNonEmptyString,
3443
+ isNoteForgetRequest,
3444
+ isNoteForgetResponse,
3445
+ isNoteUpsertRequest,
3446
+ isNoteUpsertResponse,
3447
+ isNotifyKind,
3448
+ isOperatingNoteCategory,
3449
+ isOperatorStatusReasonValue,
3450
+ isOperatorStatusRequest,
3451
+ isOperatorStatusResponse,
3452
+ isOperatorStatusValue,
3453
+ isOrphanedPinNotifyRequest,
3454
+ isOrphanedPinNotifyResponse,
3455
+ isOutboundMessage,
3456
+ isOutboundMessageOrigin,
3457
+ isP2PSignalType,
1032
3458
  isPhantomDaemonEntry,
3459
+ isPruneStaleDirectRequest,
3460
+ isPruneStaleDirectResponse,
3461
+ isQueueCancelRequest,
3462
+ isQueueCancelResponse,
3463
+ isQueueEnqueueGraphRequest,
3464
+ isQueueEnqueueGraphResponse,
3465
+ isQueueEnqueueRequest,
3466
+ isQueueEnqueueResponse,
3467
+ isQueueQueryRequest,
3468
+ isQueueQueryResponse,
3469
+ isQueueRequeueRequest,
3470
+ isQueueRequeueResponse,
1033
3471
  isRawDaemonDoId,
3472
+ isReadyStatus,
3473
+ isRecord,
3474
+ isRecordLocalRequest,
3475
+ isRecordLocalResponse,
3476
+ isRecoveryContextQueryRequest,
3477
+ isRecoveryContextQueryResponse,
3478
+ isSendPolicy,
3479
+ isSendPolicyMode,
3480
+ isSendRefusal,
3481
+ isServerDirectCommandMsg,
3482
+ isServerToDaemonControlType,
1034
3483
  isServerToDaemonWsMsg,
3484
+ isSessionLaunchedBy,
3485
+ isSessionStatus,
3486
+ isSharedSessionToViewerType,
3487
+ isSubmitOutcome,
3488
+ isSummaryRef,
3489
+ isTaskStatsQueryRequest,
3490
+ isTaskStatsQueryResponse,
3491
+ isTerminalClassEvidenceKind,
3492
+ isToolCallRecordRequest,
3493
+ isToolCallRecordResponse,
3494
+ isToolCallerRole,
3495
+ isTurnAttemptRef,
3496
+ isTurnCancelRequest,
3497
+ isTurnCancelResponse,
3498
+ isTurnEvidence,
3499
+ isTurnEvidenceKind,
3500
+ isTurnIpcCommand,
3501
+ isTurnIpcError,
3502
+ isTurnIpcErrorCode,
3503
+ isTurnObserveRequest,
3504
+ isTurnObserveResponse,
3505
+ isTurnObserveVerdict,
3506
+ isTurnOutcome,
3507
+ isTurnQueryRequest,
3508
+ isTurnQueryResponse,
3509
+ isTurnReason,
3510
+ isUserSessionToDashboardType,
3511
+ isViewerToSharedSessionType,
3512
+ isWorkerBranchState,
3513
+ isWorkerReportOutcome,
3514
+ isWorkerTool,
3515
+ isWorkingStatus,
1035
3516
  joinRepoPath,
3517
+ launchModelSelectionValue,
1036
3518
  machineCoreFromDaemonId,
3519
+ makeTypeGuard,
1037
3520
  measureWorstCaseChunkEnvelopeBytes,
1038
3521
  meshFrameNeedsChunking,
1039
3522
  meshNodeIdMatches,
1040
3523
  meshUtf8ByteLength,
1041
3524
  meshWorkspacesEquivalent,
3525
+ mintMessageId,
3526
+ normalizeAuthOkLimits,
1042
3527
  normalizeBrainSlot,
1043
3528
  normalizeDifficultyBrainMap,
1044
3529
  normalizeGitStatus,
@@ -1046,25 +3531,41 @@ export {
1046
3531
  normalizeMeshNodeId,
1047
3532
  normalizeMeshSessionRecord,
1048
3533
  normalizeMeshWorkspaceForCompare,
3534
+ normalizeMissionBrief,
1049
3535
  normalizeNodeCapabilitySlot,
1050
3536
  normalizeNodeCapabilitySlots,
3537
+ normalizeOwnedPaths,
3538
+ normalizeSessionStatus,
1051
3539
  normalizeThinkingLevel,
1052
3540
  parseJsonRecord,
1053
3541
  parseSemver,
3542
+ parseSessionLaunchRecord,
3543
+ pathsOverlap,
1054
3544
  pickBestTransitGitStatus,
3545
+ projectTurnEvidenceEntry,
1055
3546
  readBoolean,
3547
+ readEnvelopeFields,
1056
3548
  readGitSubmodules,
1057
3549
  readNumber,
1058
3550
  readRecord,
1059
3551
  readString,
1060
3552
  readStringArray,
3553
+ renderCoordinatorWorkerSection,
3554
+ renderMissionBriefBlock,
3555
+ renderWorkerProtocolFooter,
3556
+ retiredMeshToolError,
3557
+ sanitizeModelIdentifier,
3558
+ sanitizeRefusalCode,
1061
3559
  scoreGitStatusCandidate,
1062
3560
  scoreGitUpstreamFreshness,
1063
3561
  sessionIdsEquivalent,
1064
3562
  splitMeshFrame,
3563
+ statusesOfClass,
1065
3564
  stripStatusProbeMarker,
3565
+ stripWorkerProtocolFooter,
1066
3566
  summarizeGitShape,
1067
3567
  supportsQuota,
3568
+ touchedFilesOutsideOwnership,
1068
3569
  withStatusProbeMarker
1069
3570
  };
1070
3571
  //# sourceMappingURL=index.mjs.map