@adhdev/mesh-shared 1.0.60-rc.9 → 1.0.61-rc.1

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