@adhdev/daemon-core 0.9.82-rc.27 → 0.9.82-rc.271

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 (277) hide show
  1. package/dist/boot/daemon-lifecycle.d.ts +4 -0
  2. package/dist/boot/process-hardening.d.ts +50 -0
  3. package/dist/build-info.d.ts +37 -0
  4. package/dist/chat/source-machine.d.ts +166 -0
  5. package/dist/chat/source-resolver.d.ts +104 -0
  6. package/dist/chat/subscription-updates.d.ts +1 -0
  7. package/dist/cli-adapter-types.d.ts +23 -2
  8. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  9. package/dist/cli-adapters/cli-state-engine.d.ts +198 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +106 -63
  11. package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
  12. package/dist/cli-adapters/provider-cli-shared.d.ts +38 -0
  13. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  14. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
  15. package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
  16. package/dist/cli-adapters/terminal-screen.d.ts +4 -11
  17. package/dist/commands/cli-manager.d.ts +2 -1
  18. package/dist/commands/handler.d.ts +110 -0
  19. package/dist/commands/mesh-coordinator.d.ts +85 -1
  20. package/dist/commands/router.d.ts +160 -1
  21. package/dist/config/chat-history.d.ts +9 -0
  22. package/dist/config/config.d.ts +5 -0
  23. package/dist/config/mesh-config.d.ts +72 -1
  24. package/dist/git/git-commands.d.ts +9 -1
  25. package/dist/git/git-diff.d.ts +6 -0
  26. package/dist/git/git-status.d.ts +7 -0
  27. package/dist/git/git-types.d.ts +2 -50
  28. package/dist/index.d.ts +51 -12
  29. package/dist/index.js +33378 -12150
  30. package/dist/index.js.map +1 -1
  31. package/dist/index.mjs +37922 -16795
  32. package/dist/index.mjs.map +1 -1
  33. package/dist/installer.d.ts +1 -4
  34. package/dist/ipc/local-ipc-server.d.ts +91 -0
  35. package/dist/launch.d.ts +1 -1
  36. package/dist/logging/async-batch-writer.d.ts +10 -0
  37. package/dist/mesh/contracts.d.ts +164 -0
  38. package/dist/mesh/coordinator-prompt.d.ts +36 -0
  39. package/dist/mesh/coordinator-registry.d.ts +59 -0
  40. package/dist/mesh/mesh-active-work.d.ts +108 -0
  41. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  42. package/dist/mesh/mesh-events-coordinator.d.ts +152 -0
  43. package/dist/mesh/mesh-events-pending.d.ts +40 -0
  44. package/dist/mesh/mesh-events-stale.d.ts +40 -0
  45. package/dist/mesh/mesh-events-utils.d.ts +47 -0
  46. package/dist/mesh/mesh-events.d.ts +5 -49
  47. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  48. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  49. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -3
  50. package/dist/mesh/mesh-ledger.d.ts +77 -1
  51. package/dist/mesh/mesh-missions.d.ts +58 -0
  52. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  53. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  54. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  55. package/dist/mesh/mesh-routing.d.ts +70 -0
  56. package/dist/mesh/mesh-runtime-store.d.ts +333 -0
  57. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  58. package/dist/mesh/mesh-work-queue.d.ts +166 -5
  59. package/dist/mesh/preview-freshness.d.ts +18 -0
  60. package/dist/mesh/refine-config.d.ts +215 -0
  61. package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
  62. package/dist/providers/acp-provider-instance.d.ts +2 -0
  63. package/dist/providers/approval-utils.d.ts +13 -0
  64. package/dist/providers/cli-provider-instance.d.ts +61 -3
  65. package/dist/providers/contracts.d.ts +130 -6
  66. package/dist/providers/external-sources.d.ts +71 -0
  67. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  68. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  69. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  70. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  71. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  72. package/dist/providers/native-history/index.d.ts +13 -0
  73. package/dist/providers/provider-instance-manager.d.ts +13 -0
  74. package/dist/providers/provider-instance.d.ts +13 -1
  75. package/dist/providers/provider-loader.d.ts +26 -4
  76. package/dist/providers/provider-trust.d.ts +31 -0
  77. package/dist/providers/read-chat-contract.d.ts +29 -0
  78. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  79. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +85 -0
  80. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  81. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  82. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  83. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  84. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  85. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  86. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  87. package/dist/providers/sdk/v1/index.d.ts +30 -0
  88. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  89. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  90. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  91. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  92. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  93. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  94. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  95. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  96. package/dist/providers/spec/adapter.d.ts +59 -0
  97. package/dist/providers/spec/cli-adapter.d.ts +140 -0
  98. package/dist/providers/spec/evaluator.d.ts +23 -0
  99. package/dist/providers/spec/fsm-driver.d.ts +278 -0
  100. package/dist/providers/spec/fsm-evaluator.d.ts +72 -0
  101. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  102. package/dist/providers/spec/fsm-types.d.ts +106 -0
  103. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  104. package/dist/providers/spec/route.d.ts +4 -0
  105. package/dist/providers/spec/types.d.ts +144 -0
  106. package/dist/providers/transcript-v2.d.ts +176 -0
  107. package/dist/providers/types/interactive-prompt.d.ts +48 -0
  108. package/dist/repo-mesh-types.d.ts +146 -13
  109. package/dist/sessions/registry.d.ts +6 -0
  110. package/dist/shared-types-extra.d.ts +2 -4
  111. package/dist/shared-types.d.ts +42 -1
  112. package/dist/status/normalize.d.ts +1 -1
  113. package/dist/status/normalize.js +1 -0
  114. package/dist/status/normalize.js.map +1 -1
  115. package/dist/status/normalize.mjs +1 -0
  116. package/dist/status/normalize.mjs.map +1 -1
  117. package/dist/status/reporter.d.ts +2 -0
  118. package/dist/status/snapshot.d.ts +1 -0
  119. package/dist/types.d.ts +5 -0
  120. package/package.json +7 -3
  121. package/src/agent-stream/poller.ts +2 -3
  122. package/src/boot/daemon-lifecycle.ts +30 -10
  123. package/src/boot/process-hardening.ts +89 -0
  124. package/src/build-info.ts +73 -0
  125. package/src/chat/source-machine.ts +534 -0
  126. package/src/chat/source-resolver.ts +0 -0
  127. package/src/chat/subscription-updates.ts +20 -1
  128. package/src/cli-adapter-types.d.ts +1 -0
  129. package/src/cli-adapter-types.ts +22 -2
  130. package/src/cli-adapters/cli-script-runner.ts +421 -0
  131. package/src/cli-adapters/cli-state-engine.ts +1215 -0
  132. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  133. package/src/cli-adapters/provider-cli-adapter.ts +674 -1139
  134. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  135. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  136. package/src/cli-adapters/provider-cli-runtime.ts +3 -1
  137. package/src/cli-adapters/provider-cli-shared.d.ts +2 -0
  138. package/src/cli-adapters/provider-cli-shared.ts +68 -11
  139. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  140. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -29
  141. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  142. package/src/cli-adapters/terminal-screen.ts +16 -81
  143. package/src/commands/chat-commands.ts +1813 -60
  144. package/src/commands/cli-manager.ts +286 -14
  145. package/src/commands/handler.ts +809 -2
  146. package/src/commands/mesh-coordinator.ts +332 -122
  147. package/src/commands/router.ts +5730 -550
  148. package/src/config/chat-history.ts +229 -24
  149. package/src/config/config.ts +12 -0
  150. package/src/config/mesh-config.ts +303 -3
  151. package/src/config/recent-activity.ts +8 -2
  152. package/src/daemon/dev-auto-implement.ts +3 -2
  153. package/src/daemon/dev-cli-debug.ts +10 -1
  154. package/src/detection/ide-detector.ts +26 -16
  155. package/src/git/git-commands.ts +42 -12
  156. package/src/git/git-diff.ts +53 -0
  157. package/src/git/git-status.ts +198 -7
  158. package/src/git/git-types.ts +14 -62
  159. package/src/git/git-worktree.ts +8 -1
  160. package/src/index.ts +131 -11
  161. package/src/installer.d.ts +1 -1
  162. package/src/installer.ts +8 -6
  163. package/src/ipc/local-ipc-server.ts +278 -0
  164. package/src/launch.d.ts +1 -1
  165. package/src/launch.ts +37 -28
  166. package/src/logging/async-batch-writer.ts +55 -0
  167. package/src/logging/logger.ts +2 -1
  168. package/src/mesh/contracts.ts +329 -0
  169. package/src/mesh/coordinator-prompt.ts +219 -31
  170. package/src/mesh/coordinator-registry.ts +121 -0
  171. package/src/mesh/mesh-active-work.ts +468 -0
  172. package/src/mesh/mesh-delivery-policy.ts +315 -0
  173. package/src/mesh/mesh-events-coordinator.ts +1650 -0
  174. package/src/mesh/mesh-events-pending.ts +439 -0
  175. package/src/mesh/mesh-events-stale.ts +283 -0
  176. package/src/mesh/mesh-events-utils.ts +254 -0
  177. package/src/mesh/mesh-events.ts +26 -1035
  178. package/src/mesh/mesh-fast-forward.ts +839 -0
  179. package/src/mesh/mesh-host-ownership.ts +73 -0
  180. package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
  181. package/src/mesh/mesh-ledger.ts +589 -102
  182. package/src/mesh/mesh-missions.ts +151 -0
  183. package/src/mesh/mesh-refine-batch.ts +197 -0
  184. package/src/mesh/mesh-refine-status.ts +231 -0
  185. package/src/mesh/mesh-review-inbox.ts +307 -0
  186. package/src/mesh/mesh-routing.ts +272 -0
  187. package/src/mesh/mesh-runtime-store.ts +1361 -0
  188. package/src/mesh/mesh-task-stats.ts +154 -0
  189. package/src/mesh/mesh-work-queue.ts +586 -145
  190. package/src/mesh/preview-freshness.ts +118 -0
  191. package/src/mesh/refine-config.ts +403 -0
  192. package/src/mesh/worktree-bootstrap-config.ts +326 -0
  193. package/src/providers/acp-provider-instance.ts +15 -1
  194. package/src/providers/approval-utils.d.ts +4 -0
  195. package/src/providers/approval-utils.ts +47 -5
  196. package/src/providers/chat-message-normalization.ts +4 -11
  197. package/src/providers/cli-provider-instance.ts +897 -81
  198. package/src/providers/contracts.d.ts +55 -0
  199. package/src/providers/contracts.ts +141 -6
  200. package/src/providers/external-sources.ts +218 -0
  201. package/src/providers/ide-provider-instance.ts +19 -5
  202. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  203. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  204. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  205. package/src/providers/native-history/dispatcher.ts +340 -0
  206. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  207. package/src/providers/native-history/index.ts +30 -0
  208. package/src/providers/provider-instance-manager.ts +30 -0
  209. package/src/providers/provider-instance.ts +10 -1
  210. package/src/providers/provider-loader.ts +584 -50
  211. package/src/providers/provider-schema.ts +87 -14
  212. package/src/providers/provider-trust.ts +114 -0
  213. package/src/providers/read-chat-contract.ts +76 -16
  214. package/src/providers/sdk/README.md +49 -0
  215. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  216. package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
  217. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  218. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  219. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  220. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  221. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  222. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  223. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  224. package/src/providers/sdk/v1/index.ts +152 -0
  225. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  226. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  227. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  228. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  229. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  230. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  231. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  232. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  233. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  234. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  235. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  236. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  237. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  238. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  239. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  240. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  241. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  242. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  243. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  244. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  245. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  246. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  247. package/src/providers/sdk/v1/validators/index.ts +19 -0
  248. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  249. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  250. package/src/providers/spec/adapter.ts +155 -0
  251. package/src/providers/spec/cli-adapter.ts +730 -0
  252. package/src/providers/spec/evaluator.ts +345 -0
  253. package/src/providers/spec/fsm-driver.ts +868 -0
  254. package/src/providers/spec/fsm-evaluator.ts +255 -0
  255. package/src/providers/spec/fsm-loader.ts +102 -0
  256. package/src/providers/spec/fsm-types.ts +199 -0
  257. package/src/providers/spec/native-history-executor.ts +943 -0
  258. package/src/providers/spec/route.ts +51 -0
  259. package/src/providers/spec/types.ts +189 -0
  260. package/src/providers/transcript-v2.ts +567 -0
  261. package/src/providers/types/interactive-prompt.ts +446 -0
  262. package/src/providers/version-archive.ts +38 -20
  263. package/src/repo-mesh-types.ts +175 -13
  264. package/src/sessions/registry.ts +6 -0
  265. package/src/shared-types-extra.ts +2 -4
  266. package/src/shared-types.ts +45 -1
  267. package/src/status/builders.ts +26 -6
  268. package/src/status/normalize.ts +2 -0
  269. package/src/status/reporter.ts +15 -0
  270. package/src/status/snapshot.ts +84 -25
  271. package/src/system/host-memory.ts +29 -12
  272. package/src/types.ts +5 -0
  273. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  274. package/dist/mesh/mesh-sync.d.ts +0 -53
  275. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  276. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  277. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,1650 @@
1
+ import { existsSync } from 'fs';
2
+ import type { DaemonComponents } from '../boot/daemon-lifecycle.js';
3
+ import { loadConfig } from '../config/config.js';
4
+ import { getMesh, getMeshByRepo } from '../config/mesh-config.js';
5
+ import { detectCLI } from '../detection/cli-detector.js';
6
+ import { LOG } from '../logging/logger.js';
7
+ import { appendLedgerEntry, buildTaskCompletionEvidence, getSessionRecoveryContext, isIntentionalCleanupStopEntry, readLedgerEntries } from './mesh-ledger.js';
8
+ import type { MeshLedgerKind, SessionRecoveryContext } from './mesh-ledger.js';
9
+ import { buildMeshNodeCapabilityTags, nodeSatisfiesRequiredTags, claimNextTask, updateSessionTaskStatus, enqueueTask, updateTaskStatus, getQueue, recordTaskAutoLaunch, updateDirectDispatchStatus, cleanupTerminalDirectDispatches, getActiveDirectDispatches, hasPendingDependents } from './mesh-work-queue.js';
10
+ import { fastForwardMeshNode } from './mesh-fast-forward.js';
11
+ import { createSessionDelivery, markSessionDeliveriesTerminal, updateSessionDeliveryStatus, recordCompletionConflict } from './mesh-delivery-policy.js';
12
+ import { MeshRuntimeStore } from './mesh-runtime-store.js';
13
+ import { queuePendingMeshCoordinatorEvent, drainPendingMeshCoordinatorEvents, markMeshCoordinatorEventDirectDelivered } from './mesh-events-pending.js';
14
+ import type { PendingMeshCoordinatorEvent } from './mesh-events-pending.js';
15
+ import { resolveWorkerDelegateRouting, recordUnroutableDelegateEvent } from './mesh-routing.js';
16
+ import { resolveDelegatedWorkerAutoApprove } from '../repo-mesh-types.js';
17
+ import {
18
+ findRecentTerminalLedgerEvidence,
19
+ hasDispatchAfterTerminal,
20
+ hasUnterminalDirectDispatchLedgerEntry,
21
+ buildLongGeneratingCompletionReconciliation,
22
+ } from './mesh-events-stale.js';
23
+ import {
24
+ buildMeshSystemMessage,
25
+ readNonEmptyString,
26
+ readRecord,
27
+ resolveEventSessionId,
28
+ readRefineJobId,
29
+ readWorkerResultMetadata,
30
+ sameDaemonId,
31
+ } from './mesh-events-utils.js';
32
+
33
+ // ---------------------------------------------------------------------------
34
+ // Remote Node Idle Session Tracking
35
+ // ---------------------------------------------------------------------------
36
+ const REMOTE_IDLE_SESSION_TTL_MS = 5 * 60 * 1000; // 5 minutes
37
+
38
+ // ---------------------------------------------------------------------------
39
+ // Workspace-to-mesh lookup cache
40
+ // ---------------------------------------------------------------------------
41
+ const meshByWorkspaceCache = new Map<string, { mesh: any; cachedAt: number }>();
42
+ const MESH_WORKSPACE_CACHE_TTL_MS = 5_000;
43
+ const IDLE_AUTO_FAST_FORWARD_THROTTLE_MS = 30 * 60 * 1000;
44
+ const idleAutoFastForwardLastAttempt = new Map<string, number>();
45
+
46
+ function getCachedMeshByWorkspace(workspace: string): any {
47
+ const now = Date.now();
48
+ const cached = meshByWorkspaceCache.get(workspace);
49
+ if (cached && now - cached.cachedAt < MESH_WORKSPACE_CACHE_TTL_MS) return cached.mesh;
50
+ const mesh = getMeshByRepo(workspace);
51
+ meshByWorkspaceCache.set(workspace, { mesh, cachedAt: now });
52
+ return mesh;
53
+ }
54
+
55
+ export function __resetIdleAutoFastForwardForTests(): void {
56
+ idleAutoFastForwardLastAttempt.clear();
57
+ }
58
+
59
+ export function __resetMeshWorkspaceCacheForTests(): void {
60
+ meshByWorkspaceCache.clear();
61
+ }
62
+
63
+ function sweepExpiredRemoteIdleSessions(): void {
64
+ try {
65
+ MeshRuntimeStore.getInstance().pruneExpiredRemoteIdleSessions();
66
+ } catch { /* best-effort */ }
67
+ }
68
+
69
+ function getMeshWithCache(components: DaemonComponents, meshId: string): any | undefined {
70
+ const localMesh = getMesh(meshId);
71
+ if (localMesh) return localMesh;
72
+ return components.router?.getCachedInlineMesh(meshId);
73
+ }
74
+
75
+ const INTENTIONAL_CLEANUP_STOP_SUPPRESSION_MS = 30 * 60 * 1000;
76
+
77
+ function isIntentionalCleanupStopMetadata(event: Record<string, unknown>): boolean {
78
+ return event.intentional === true
79
+ || event.intentionalStop === true
80
+ || event.operatorCleanup === true
81
+ || event.reason === 'operator_cleanup'
82
+ || event.stopReason === 'operator_cleanup'
83
+ || event.cleanupReason === 'operator_cleanup'
84
+ || event.source === 'mesh_cleanup_sessions'
85
+ || event.source === 'mesh_remove_node';
86
+ }
87
+
88
+ function hasRecentIntentionalCleanupStop(meshId: string, sessionId?: string, nodeId?: string): boolean {
89
+ if (!sessionId && !nodeId) return false;
90
+ const cutoff = Date.now() - INTENTIONAL_CLEANUP_STOP_SUPPRESSION_MS;
91
+ const entries = readLedgerEntries(meshId, { tail: 200 });
92
+ for (let i = entries.length - 1; i >= 0; i--) {
93
+ const entry = entries[i];
94
+ const timestamp = new Date(entry.timestamp).getTime();
95
+ if (!Number.isNaN(timestamp) && timestamp < cutoff) break;
96
+ if (!isIntentionalCleanupStopEntry(entry)) continue;
97
+ if (sessionId && entry.sessionId === sessionId) return true;
98
+ if (!sessionId && nodeId && entry.nodeId === nodeId) return true;
99
+ }
100
+ return false;
101
+ }
102
+
103
+ function shouldSuppressIntentionalCleanupStop(args: {
104
+ event: string;
105
+ meshId: string;
106
+ metadataEvent: Record<string, unknown>;
107
+ sessionId?: string;
108
+ nodeId?: string;
109
+ }): boolean {
110
+ if (args.event !== 'agent:stopped' && args.event !== 'monitor:long_generating') return false;
111
+ if (isIntentionalCleanupStopMetadata(args.metadataEvent)) return true;
112
+ return hasRecentIntentionalCleanupStop(args.meshId, args.sessionId, args.nodeId);
113
+ }
114
+
115
+ const RECENT_COMPLETION_FINGERPRINT_TTL_MS = 10 * 60 * 1000;
116
+
117
+ function hasFingerprintSeen(fingerprint: string): boolean {
118
+ try {
119
+ return MeshRuntimeStore.getInstance().hasCompletionFingerprint(fingerprint);
120
+ } catch {
121
+ return false;
122
+ }
123
+ }
124
+
125
+ function recordFingerprintSeen(fingerprint: string): void {
126
+ try {
127
+ const db = MeshRuntimeStore.getInstance();
128
+ db.recordCompletionFingerprint(fingerprint, RECENT_COMPLETION_FINGERPRINT_TTL_MS);
129
+ db.sweepExpiredFingerprints();
130
+ } catch { /* best-effort; duplicate events are preferable to a crash */ }
131
+ }
132
+
133
+ function readEventTimestamp(value: unknown): number | null {
134
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
135
+ if (typeof value === 'string' && value.trim()) {
136
+ const numeric = Number(value);
137
+ if (Number.isFinite(numeric)) return numeric;
138
+ const parsed = Date.parse(value);
139
+ if (Number.isFinite(parsed)) return parsed;
140
+ }
141
+ return null;
142
+ }
143
+
144
+ function buildMeshCompletionFingerprint(args: {
145
+ meshId: string;
146
+ event: string;
147
+ sessionId: string;
148
+ providerType?: string;
149
+ providerSessionId?: string;
150
+ timestamp?: number | null;
151
+ finalSummary?: string;
152
+ coordinatorDaemonId?: string;
153
+ }): string {
154
+ const timestampPart = Number.isFinite(args.timestamp)
155
+ ? String(args.timestamp)
156
+ : readNonEmptyString(args.finalSummary).slice(0, 200);
157
+ return [
158
+ args.meshId,
159
+ args.event,
160
+ args.sessionId,
161
+ args.providerType || '',
162
+ args.providerSessionId || '',
163
+ timestampPart,
164
+ args.coordinatorDaemonId || '',
165
+ ].join('::');
166
+ }
167
+
168
+ function isDuplicateMeshCompletionEvent(args: {
169
+ meshId: string;
170
+ event: string;
171
+ sessionId: string;
172
+ providerType?: string;
173
+ providerSessionId?: string;
174
+ timestamp?: number | null;
175
+ finalSummary?: string;
176
+ coordinatorDaemonId?: string;
177
+ taskId?: string;
178
+ nodeId?: string;
179
+ }): boolean {
180
+ const fingerprint = buildMeshCompletionFingerprint(args);
181
+ if (!fingerprint) return false;
182
+ if (hasFingerprintSeen(fingerprint)) {
183
+ if (args.taskId) {
184
+ recordCompletionConflict({
185
+ meshId: args.meshId,
186
+ fingerprint,
187
+ conflictingTaskId: args.taskId,
188
+ conflictingSessionId: args.sessionId,
189
+ event: args.event,
190
+ });
191
+ }
192
+ return true;
193
+ }
194
+ recordFingerprintSeen(fingerprint);
195
+ return false;
196
+ }
197
+
198
+ function isDuplicateMeshApprovalEvent(args: {
199
+ meshId: string;
200
+ sessionId: string;
201
+ providerType?: string;
202
+ timestamp?: number | null;
203
+ modalMessage?: string;
204
+ modalButtons?: unknown;
205
+ }): boolean {
206
+ const modalButtons = Array.isArray(args.modalButtons)
207
+ ? args.modalButtons.map(button => String(button).trim()).filter(Boolean)
208
+ : [];
209
+ const approvalIdentity = Number.isFinite(args.timestamp)
210
+ ? String(args.timestamp)
211
+ : JSON.stringify({ message: args.modalMessage || '', buttons: modalButtons });
212
+ if (!approvalIdentity || approvalIdentity === '{"message":"","buttons":[]}') return false;
213
+ const fingerprint = [
214
+ args.meshId,
215
+ 'agent:waiting_approval',
216
+ args.sessionId,
217
+ args.providerType || '',
218
+ approvalIdentity,
219
+ ].join('::');
220
+ if (hasFingerprintSeen(fingerprint)) return true;
221
+ recordFingerprintSeen(fingerprint);
222
+ return false;
223
+ }
224
+
225
+ function isDuplicateRefineTerminalEvent(meshId: string, eventName: string, metadataEvent: Record<string, unknown>): boolean {
226
+ const jobId = readRefineJobId({ metadataEvent });
227
+ const fingerprint = jobId && new Set(['refine:completed', 'refine:failed']).has(eventName) ? `${meshId}::${eventName}::${jobId}` : '';
228
+ if (!fingerprint) return false;
229
+ if (hasFingerprintSeen(fingerprint)) return true;
230
+ recordFingerprintSeen(fingerprint);
231
+ return false;
232
+ }
233
+
234
+ // ---------------------------------------------------------------------------
235
+ // Queue assignment
236
+ // ---------------------------------------------------------------------------
237
+
238
+ export function tryAssignQueueTask(
239
+ components: DaemonComponents,
240
+ meshId: string,
241
+ nodeId: string,
242
+ sessionId: string,
243
+ providerType: string
244
+ ): boolean {
245
+ const mesh = getMeshWithCache(components, meshId);
246
+ const node = mesh?.nodes.find((n: any) => n.id === nodeId);
247
+ const capabilityTags = buildMeshNodeCapabilityTags(node, providerType);
248
+ const task = claimNextTask(meshId, nodeId, sessionId, capabilityTags);
249
+ if (!task) {
250
+ return false;
251
+ }
252
+
253
+ LOG.info('MeshQueue', `Node ${nodeId} (${sessionId}) pulled task ${task.id}`);
254
+
255
+ if (node?.daemonId && components.dispatchMeshCommand) {
256
+ const isLocalNode = components.cliManager.adapters.has(sessionId);
257
+ if (!isLocalNode) {
258
+ const delivery = createSessionDelivery({
259
+ meshId,
260
+ nodeId,
261
+ sessionId,
262
+ providerType,
263
+ taskId: task.id,
264
+ kind: 'task',
265
+ message: task.message,
266
+ status: 'delivering',
267
+ });
268
+ const localDaemonIdForDispatch = readNonEmptyString(loadConfig().machineId) || undefined;
269
+ components.dispatchMeshCommand(node.daemonId, 'agent_command', {
270
+ targetSessionId: sessionId,
271
+ cliType: providerType,
272
+ action: 'send_chat',
273
+ message: task.message,
274
+ meshContext: {
275
+ meshId,
276
+ nodeId,
277
+ taskId: task.id,
278
+ ...(localDaemonIdForDispatch ? { coordinatorDaemonId: localDaemonIdForDispatch } : {}),
279
+ },
280
+ }).then(() => {
281
+ updateSessionDeliveryStatus(delivery.id, 'delivered');
282
+ }).catch((e: any) => {
283
+ LOG.error('MeshQueue', `Failed to dispatch task via P2P to remote node ${nodeId}: ${e?.message}`);
284
+ updateSessionDeliveryStatus(delivery.id, 'failed', { lastError: e?.message, incrementAttempt: true });
285
+ updateTaskStatus(meshId, task.id, 'pending');
286
+ try {
287
+ appendLedgerEntry(meshId, {
288
+ kind: 'dispatch_failed' as any,
289
+ nodeId,
290
+ sessionId,
291
+ payload: { taskId: task.id, deliveryId: delivery.id, error: e?.message, retryable: true },
292
+ });
293
+ } catch { /* ledger write is best-effort */ }
294
+ });
295
+ return true;
296
+ }
297
+ }
298
+
299
+ // Stamp mesh context onto the session so completion events route correctly
300
+ // via setupMeshEventForwarding. Without this, manually-opened idle sessions
301
+ // (mesh_launch_session without auto-launch) lack meshNodeFor/meshNodeId and
302
+ // agent:generating_completed is silently dropped as isMeshDelegate=false.
303
+ try {
304
+ const inst = components.instanceManager.getInstance(sessionId);
305
+ if (inst && typeof inst.updateSettings === 'function') {
306
+ // Adopting a (possibly manually-opened) local session as a worker: apply the
307
+ // delegated-worker auto-approve policy here too, so a session that was launched
308
+ // without autoApprove still auto-approves once the coordinator dispatches a task
309
+ // to it (the "approval notification fires only for certain delegated sessions"
310
+ // case). updateSettings preserves runtime mesh keys; passing autoApprove keeps it.
311
+ //
312
+ // This local-dispatch branch also runs on the coordinator daemon for a co-located
313
+ // session, so the coordinator daemon id IS this daemon's id. Stamp it alongside
314
+ // the node identity so the session is fully relay-safe (meshCoordinatorDaemonId is
315
+ // the anchor the forwarder keys on), matching what mesh_launch_session stamps.
316
+ const localDaemonId = readNonEmptyString(loadConfig().machineId);
317
+ inst.updateSettings({
318
+ meshNodeFor: meshId,
319
+ meshNodeId: nodeId,
320
+ launchedByCoordinator: true,
321
+ autoApprove: resolveDelegatedWorkerAutoApprove(mesh?.policy, node?.policy),
322
+ ...(localDaemonId ? { meshCoordinatorDaemonId: localDaemonId } : {}),
323
+ });
324
+ }
325
+ } catch { /* best-effort — dispatch still proceeds */ }
326
+
327
+ const delivery = createSessionDelivery({
328
+ meshId,
329
+ nodeId,
330
+ sessionId,
331
+ providerType,
332
+ taskId: task.id,
333
+ kind: 'task',
334
+ message: task.message,
335
+ status: 'delivering',
336
+ });
337
+ components.cliManager.handleCliCommand('agent_command', {
338
+ targetSessionId: sessionId,
339
+ cliType: providerType,
340
+ action: 'send_chat',
341
+ message: task.message,
342
+ }).then(() => {
343
+ updateSessionDeliveryStatus(delivery.id, 'delivered');
344
+ }).catch((e: any) => {
345
+ LOG.error('MeshQueue', `Failed to dispatch task locally to node ${nodeId}: ${e?.message}`);
346
+ updateSessionDeliveryStatus(delivery.id, 'failed', { lastError: e?.message, incrementAttempt: true });
347
+ updateTaskStatus(meshId, task.id, 'failed');
348
+ });
349
+
350
+ return true;
351
+ }
352
+
353
+ const autoLaunchInProgress = new Set<string>();
354
+ const autoLaunchCooldownUntil = new Map<string, number>();
355
+ const AUTO_LAUNCH_COOLDOWN_MS = 5_000;
356
+
357
+ function sweepExpiredCooldowns(): void {
358
+ const now = Date.now();
359
+ for (const [key, until] of autoLaunchCooldownUntil) {
360
+ if (now >= until) autoLaunchCooldownUntil.delete(key);
361
+ }
362
+ }
363
+
364
+ function normalizeProviderPriority(policy: unknown): string[] {
365
+ const raw = policy && typeof policy === 'object' && !Array.isArray(policy)
366
+ ? (policy as Record<string, unknown>).providerPriority
367
+ : undefined;
368
+ if (!Array.isArray(raw)) return [];
369
+ const seen = new Set<string>();
370
+ return raw
371
+ .map(type => typeof type === 'string' ? type.trim() : '')
372
+ .filter(Boolean)
373
+ .filter(type => {
374
+ if (seen.has(type)) return false;
375
+ seen.add(type);
376
+ return true;
377
+ });
378
+ }
379
+
380
+ function isTerminalSessionStatus(status: string): boolean {
381
+ return ['stopped', 'failed', 'terminated', 'exited', 'closed'].includes(status);
382
+ }
383
+
384
+ function isIdleSessionState(state: any): boolean {
385
+ const status = readNonEmptyString(state?.status).toLowerCase();
386
+ if (isTerminalSessionStatus(status)) return false;
387
+ return status === 'idle' || state?.activeChat?.status === 'waiting_input';
388
+ }
389
+
390
+ function isDirtyNode(node: any): boolean {
391
+ return node?.health === 'dirty' || node?.git?.dirty === true;
392
+ }
393
+
394
+ function resolveAutoFastForwardPolicy(mesh: any): { enabled: boolean; maxBehind?: number; requireCleanSubmodules: boolean } {
395
+ const record = mesh?.policy?.autoFastForward && typeof mesh.policy.autoFastForward === 'object' && !Array.isArray(mesh.policy.autoFastForward)
396
+ ? mesh.policy.autoFastForward as Record<string, unknown>
397
+ : {};
398
+ const maxBehind = Number(record.maxBehind);
399
+ return {
400
+ enabled: record.enabled !== false,
401
+ ...(Number.isFinite(maxBehind) && maxBehind >= 0 ? { maxBehind: Math.floor(maxBehind) } : {}),
402
+ requireCleanSubmodules: record.requireCleanSubmodules !== false,
403
+ };
404
+ }
405
+
406
+ function sessionStateLooksActive(state: any): boolean {
407
+ const status = readNonEmptyString(state?.status).toLowerCase();
408
+ const chatStatus = readNonEmptyString(state?.activeChat?.status).toLowerCase();
409
+ const active = new Set(['generating', 'streaming', 'long_generating', 'working', 'starting', 'waiting_approval']);
410
+ return active.has(status) || active.has(chatStatus);
411
+ }
412
+
413
+ function nodeHasActiveMeshWork(components: DaemonComponents, meshId: string, nodeId: string, currentSessionId?: string): boolean {
414
+ if (nodeHasActiveAssignment(meshId, nodeId)) return true;
415
+ return components.instanceManager.getByCategory('cli').some((inst: any) => {
416
+ const state = inst.getState();
417
+ const settings = state.settings as Record<string, unknown> || {};
418
+ if (readNonEmptyString(settings.meshNodeFor) !== meshId) return false;
419
+ const instNodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
420
+ if (instNodeId !== nodeId) return false;
421
+ const sessionId = readNonEmptyString(state.instanceId);
422
+ if (currentSessionId && sessionId === currentSessionId && isIdleSessionState(state)) return false;
423
+ return sessionStateLooksActive(state);
424
+ });
425
+ }
426
+
427
+ function isLaunchableNode(node: any): boolean {
428
+ if (!node || node.status === 'disabled' || node.status === 'removed') return false;
429
+ const health = readNonEmptyString(node.health).toLowerCase();
430
+ if (!health) return true;
431
+ return health === 'online' || health === 'unknown';
432
+ }
433
+
434
+ function localAutoLaunchSkipReason(node: any): string | null {
435
+ const daemonId = readNonEmptyString(node?.daemonId);
436
+ const machineId = readNonEmptyString(node?.machineId);
437
+ const appConfig = loadConfig();
438
+ const localMachineId = readNonEmptyString(appConfig.machineId) || readNonEmptyString(appConfig.registeredMachineId);
439
+ const cloudDaemonId = localMachineId ? `daemon_${localMachineId}` : '';
440
+ const standaloneDaemonId = localMachineId ? `standalone_${localMachineId}` : '';
441
+
442
+ const daemonMatchesLocal = !daemonId || daemonId === cloudDaemonId || daemonId === standaloneDaemonId;
443
+ const machineMatchesLocal = !machineId || (localMachineId && machineId === localMachineId);
444
+
445
+ if (node?.isLocalWorktree === true) {
446
+ return daemonMatchesLocal && machineMatchesLocal ? null : 'remote_auto_launch_unsupported';
447
+ }
448
+
449
+ if (daemonId || machineId) {
450
+ return daemonMatchesLocal && machineMatchesLocal ? null : 'remote_auto_launch_unsupported';
451
+ }
452
+
453
+ return null;
454
+ }
455
+
456
+ function activeAssignedCount(meshId: string): number {
457
+ return getQueue(meshId, { status: ['assigned'] as any }).length;
458
+ }
459
+
460
+ function nodeHasActiveAssignment(meshId: string, nodeId: string): boolean {
461
+ return getQueue(meshId, { status: ['assigned'] as any }).some(task => task.assignedNodeId === nodeId);
462
+ }
463
+
464
+ function sessionHasActiveAssignment(meshId: string, sessionId: string): boolean {
465
+ if (getQueue(meshId, { status: ['assigned'] as any }).some(task => task.assignedSessionId === sessionId)) {
466
+ return true;
467
+ }
468
+ // Direct dispatches (mesh_send_task) are tracked in mesh_direct_dispatches, not the
469
+ // work queue. A session completing a still-active direct dispatch IS an active
470
+ // assignment — without this, findRecentTerminalLedgerEvidence dedup wrongly suppresses
471
+ // the canonical agent:generating_completed for direct-dispatch tasks (validation/general),
472
+ // so the coordinator polling get_pending_mesh_events never observes task_completed and the
473
+ // session goes silently idle. This check runs before markSessionTerminal marks the
474
+ // dispatch terminal, so the in-flight dispatch is still observable here.
475
+ try {
476
+ if (getActiveDirectDispatches(meshId).some(d => d.sessionId === sessionId)) return true;
477
+ if (hasUnterminalDirectDispatchLedgerEntry(meshId, sessionId)) return true;
478
+ } catch { /* best-effort — fall through to false */ }
479
+ return false;
480
+ }
481
+
482
+ function liveSessionCountForNode(components: DaemonComponents, meshId: string, nodeId: string): number {
483
+ return components.instanceManager.getByCategory('cli').filter((inst: any) => {
484
+ const state = inst.getState();
485
+ const settings = state.settings as Record<string, unknown> || {};
486
+ if (readNonEmptyString(settings.meshNodeFor) !== meshId) return false;
487
+ const instNodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
488
+ if (instNodeId !== nodeId) return false;
489
+ const status = readNonEmptyString(state.status).toLowerCase();
490
+ return !isTerminalSessionStatus(status);
491
+ }).length;
492
+ }
493
+
494
+ function recordAutoLaunchEvent(meshId: string, args: {
495
+ phase: 'skipped' | 'started' | 'failed' | 'completed';
496
+ taskId: string;
497
+ nodeId?: string;
498
+ providerType?: string;
499
+ sessionId?: string;
500
+ reason?: string;
501
+ error?: string;
502
+ }) {
503
+ try {
504
+ appendLedgerEntry(meshId, {
505
+ kind: 'session_auto_launch',
506
+ nodeId: args.nodeId,
507
+ sessionId: args.sessionId,
508
+ providerType: args.providerType,
509
+ payload: {
510
+ phase: args.phase,
511
+ taskId: args.taskId,
512
+ reason: args.reason,
513
+ error: args.error,
514
+ },
515
+ });
516
+ } catch (e: any) {
517
+ LOG.warn('MeshQueue', `Failed to record auto-launch ledger event: ${e?.message || e}`);
518
+ }
519
+ }
520
+
521
+ function markAutoLaunch(meshId: string, taskId: string, args: {
522
+ status: 'skipped' | 'started' | 'failed' | 'completed';
523
+ reason?: string;
524
+ nodeId?: string;
525
+ providerType?: string;
526
+ sessionId?: string;
527
+ error?: string;
528
+ }) {
529
+ recordTaskAutoLaunch(meshId, taskId, {
530
+ status: args.status,
531
+ reason: args.reason || args.error,
532
+ nodeId: args.nodeId,
533
+ providerType: args.providerType,
534
+ sessionId: args.sessionId,
535
+ });
536
+ recordAutoLaunchEvent(meshId, {
537
+ phase: args.status,
538
+ taskId,
539
+ nodeId: args.nodeId,
540
+ providerType: args.providerType,
541
+ sessionId: args.sessionId,
542
+ reason: args.reason,
543
+ error: args.error,
544
+ });
545
+ }
546
+
547
+ async function resolveUsableProvider(
548
+ components: DaemonComponents,
549
+ nodeId: string,
550
+ node: any,
551
+ requiredTags?: string[],
552
+ ): Promise<{ providerType?: string; reason?: string }> {
553
+ const providerPriority = normalizeProviderPriority(node?.policy);
554
+ if (!providerPriority.length) return { reason: 'missing_provider_priority' };
555
+ const providerLoader = components.providerLoader;
556
+ if (!providerLoader) return { reason: 'provider_loader_unavailable' };
557
+
558
+ const failed: string[] = [];
559
+ for (const requestedType of providerPriority) {
560
+ const normalizedType = typeof providerLoader.resolveAlias === 'function'
561
+ ? providerLoader.resolveAlias(requestedType)
562
+ : requestedType;
563
+ // Skip providers that can't satisfy the task's requiredTags (e.g. provider=hermes-cli
564
+ // means only hermes-cli qualifies, not any other type in providerPriority).
565
+ if (requiredTags?.length && !nodeSatisfiesRequiredTags(requiredTags, buildMeshNodeCapabilityTags(node, normalizedType))) {
566
+ failed.push(`${requestedType}: required_tags_mismatch`);
567
+ continue;
568
+ }
569
+ if (typeof providerLoader.isMachineProviderEnabled === 'function' && !providerLoader.isMachineProviderEnabled(normalizedType)) {
570
+ failed.push(`${requestedType}: disabled`);
571
+ continue;
572
+ }
573
+ let detected: any;
574
+ try {
575
+ detected = await detectCLI(normalizedType, providerLoader, { includeVersion: false });
576
+ } catch (e: any) {
577
+ failed.push(`${requestedType}: detect failed: ${e?.message || e}`);
578
+ continue;
579
+ }
580
+ if (typeof providerLoader.setCliDetectionResults === 'function') {
581
+ providerLoader.setCliDetectionResults([{
582
+ id: normalizedType,
583
+ installed: !!detected,
584
+ path: detected?.path,
585
+ }], false);
586
+ }
587
+ (components as any).onStatusChange?.();
588
+ if (detected) return { providerType: normalizedType };
589
+ failed.push(`${requestedType}: not detected`);
590
+ }
591
+ return { reason: `provider_priority_unusable: ${failed.join('; ') || nodeId}` };
592
+ }
593
+
594
+ async function maybeAutoLaunchOneQueueSession(components: DaemonComponents, meshId: string, mesh: any): Promise<boolean> {
595
+ const queue = getQueue(meshId);
596
+ const pending = queue.filter(task => task.status === 'pending');
597
+ if (!pending.length) return false;
598
+
599
+ const maxParallelTasks = Math.max(1, Math.floor(Number(mesh?.policy?.maxParallelTasks) || 2));
600
+ for (const task of pending) {
601
+ if (activeAssignedCount(meshId) >= maxParallelTasks) {
602
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_parallel_tasks_reached' });
603
+ return false;
604
+ }
605
+ if (task.targetSessionId) {
606
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'target_session_constraint' });
607
+ continue;
608
+ }
609
+
610
+ const candidateNodes = Array.isArray(mesh?.nodes)
611
+ ? mesh.nodes.filter((node: any) => {
612
+ if (task.targetNodeId && node?.id !== task.targetNodeId) return false;
613
+ // Skip nodes that can never satisfy requiredTags regardless of which provider
614
+ // from providerPriority is selected. A node satisfies tags if at least one
615
+ // provider in its priority list would produce matching capability tags.
616
+ if (task.requiredTags?.length) {
617
+ const priorities = normalizeProviderPriority(node?.policy);
618
+ const providerCandidates = priorities.length ? priorities : [undefined as unknown as string];
619
+ return providerCandidates.some(p =>
620
+ nodeSatisfiesRequiredTags(task.requiredTags, buildMeshNodeCapabilityTags(node, p))
621
+ );
622
+ }
623
+ return true;
624
+ })
625
+ : [];
626
+ if (!candidateNodes.length) {
627
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'no_node_satisfies_required_tags', nodeId: task.targetNodeId });
628
+ continue;
629
+ }
630
+
631
+ for (const node of candidateNodes) {
632
+ const nodeId = readNonEmptyString(node?.id);
633
+ if (!nodeId) continue;
634
+ const launchKey = `${meshId}:${nodeId}`;
635
+ const now = Date.now();
636
+ const cooldownUntil = autoLaunchCooldownUntil.get(launchKey) || 0;
637
+ if (cooldownUntil > 0 && now >= cooldownUntil) autoLaunchCooldownUntil.delete(launchKey);
638
+ if (autoLaunchInProgress.has(launchKey)) {
639
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'auto_launch_in_progress', nodeId });
640
+ continue;
641
+ }
642
+ if (now < cooldownUntil) {
643
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'auto_launch_cooldown', nodeId });
644
+ continue;
645
+ }
646
+ if (isDirtyNode(node)) {
647
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'dirty_workspace', nodeId });
648
+ continue;
649
+ }
650
+ if (!isLaunchableNode(node)) {
651
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'node_not_launch_ready', nodeId });
652
+ continue;
653
+ }
654
+ const localSkipReason = localAutoLaunchSkipReason(node);
655
+ if (localSkipReason) {
656
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: localSkipReason, nodeId });
657
+ continue;
658
+ }
659
+ if (nodeHasActiveAssignment(meshId, nodeId)) {
660
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'node_has_active_assignment', nodeId });
661
+ continue;
662
+ }
663
+ const maxConcurrentSessions = Number(node?.policy?.maxConcurrentSessions);
664
+ if (Number.isFinite(maxConcurrentSessions) && maxConcurrentSessions >= 0 && liveSessionCountForNode(components, meshId, nodeId) >= maxConcurrentSessions) {
665
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_concurrent_sessions_reached', nodeId });
666
+ continue;
667
+ }
668
+
669
+ autoLaunchInProgress.add(launchKey);
670
+ try {
671
+ const resolved = await resolveUsableProvider(components, nodeId, node, task.requiredTags);
672
+ if (!resolved.providerType) {
673
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: resolved.reason || 'provider_unusable', nodeId });
674
+ continue;
675
+ }
676
+
677
+ markAutoLaunch(meshId, task.id, { status: 'started', nodeId, providerType: resolved.providerType });
678
+ const launchResult: any = await components.cliManager.handleCliCommand('launch_cli', {
679
+ cliType: resolved.providerType,
680
+ dir: node.workspace,
681
+ settings: {
682
+ // Worker launch envelope: role + mesh context so worker can route completion events.
683
+ role: 'worker',
684
+ meshNodeFor: meshId,
685
+ meshNodeId: nodeId,
686
+ spawnedSessionVisibility: mesh?.policy?.spawnedSessionVisibility || 'hidden',
687
+ // Coordinator-dispatched worker: auto-approve unless mesh/node policy
688
+ // opts out (default true). Lands in settingsOverride and beats the
689
+ // global per-provider-type autoApprove config (see shouldAutoApprove).
690
+ autoApprove: resolveDelegatedWorkerAutoApprove(mesh?.policy, node?.policy),
691
+ launchedByCoordinator: true,
692
+ autoLaunchedForQueueTaskId: task.id,
693
+ },
694
+ });
695
+ if (!launchResult?.success) {
696
+ const reason = launchResult?.error || 'launch_cli_failed';
697
+ markAutoLaunch(meshId, task.id, { status: 'failed', reason, nodeId, providerType: resolved.providerType });
698
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
699
+ return false;
700
+ }
701
+ const sessionId = readNonEmptyString(launchResult.sessionId) || readNonEmptyString(launchResult.id) || readNonEmptyString(launchResult.runtimeSessionId);
702
+ if (!sessionId) {
703
+ markAutoLaunch(meshId, task.id, { status: 'failed', reason: 'launch_missing_session_id', nodeId, providerType: resolved.providerType });
704
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
705
+ return false;
706
+ }
707
+ markAutoLaunch(meshId, task.id, { status: 'completed', nodeId, providerType: resolved.providerType, sessionId });
708
+ tryAssignQueueTask(components, meshId, nodeId, sessionId, resolved.providerType);
709
+ return true;
710
+ } catch (e: any) {
711
+ markAutoLaunch(meshId, task.id, { status: 'failed', error: e?.message || String(e), nodeId });
712
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS);
713
+ return false;
714
+ } finally {
715
+ autoLaunchInProgress.delete(launchKey);
716
+ }
717
+ }
718
+ }
719
+ return false;
720
+ }
721
+
722
+ export interface MeshQueueTriggerResult {
723
+ success: true;
724
+ meshId: string;
725
+ pendingBefore: number;
726
+ assignedBefore: number;
727
+ pendingAfter: number;
728
+ assignedAfter: number;
729
+ claimed: boolean;
730
+ newlyAssignedTasks: Array<{
731
+ id: string;
732
+ nodeId?: string;
733
+ sessionId?: string;
734
+ }>;
735
+ localIdleSessionsChecked: number;
736
+ remoteIdleSessionsChecked: number;
737
+ skippedSessions: Array<{
738
+ nodeId?: string;
739
+ sessionId?: string;
740
+ reason: string;
741
+ status?: string;
742
+ }>;
743
+ autoLaunchStarted: boolean;
744
+ noIdleMeshSessionAvailable?: boolean;
745
+ }
746
+
747
+ function countQueueStatus(meshId: string, status: 'pending' | 'assigned'): number {
748
+ return getQueue(meshId, { status: [status] as any }).length;
749
+ }
750
+
751
+ function getQueueStatusById(meshId: string): Map<string, string> {
752
+ return new Map(getQueue(meshId).map(task => [task.id, task.status]));
753
+ }
754
+
755
+ export async function triggerMeshQueue(components: DaemonComponents, meshId: string): Promise<MeshQueueTriggerResult> {
756
+ const mesh = getMeshWithCache(components, meshId);
757
+ const pendingBefore = countQueueStatus(meshId, 'pending');
758
+ const assignedBefore = countQueueStatus(meshId, 'assigned');
759
+ const beforeStatus = getQueueStatusById(meshId);
760
+ const skippedSessions: MeshQueueTriggerResult['skippedSessions'] = [];
761
+ let localIdleSessionsChecked = 0;
762
+ let remoteIdleSessionsChecked = 0;
763
+ let autoLaunchStarted = false;
764
+ if (!mesh) {
765
+ return {
766
+ success: true,
767
+ meshId,
768
+ pendingBefore,
769
+ assignedBefore,
770
+ pendingAfter: pendingBefore,
771
+ assignedAfter: assignedBefore,
772
+ claimed: false,
773
+ newlyAssignedTasks: [],
774
+ localIdleSessionsChecked,
775
+ remoteIdleSessionsChecked,
776
+ skippedSessions: [{ reason: 'mesh_not_found' }],
777
+ autoLaunchStarted,
778
+ noIdleMeshSessionAvailable: true,
779
+ };
780
+ }
781
+
782
+ const cliInstances = components.instanceManager.getByCategory('cli');
783
+ for (const inst of cliInstances) {
784
+ const state = inst.getState();
785
+ const settings = state.settings as Record<string, unknown> || {};
786
+
787
+ const instMeshId = readNonEmptyString(settings.meshNodeFor);
788
+ if (instMeshId !== meshId) continue;
789
+
790
+ const nodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
791
+ if (!nodeId) continue;
792
+
793
+ if (!isIdleSessionState(state)) {
794
+ const status = readNonEmptyString(state.status).toLowerCase();
795
+ skippedSessions.push({
796
+ nodeId,
797
+ sessionId: readNonEmptyString(state.instanceId),
798
+ reason: isTerminalSessionStatus(status) ? 'terminal_session' : 'session_not_idle',
799
+ status: status || undefined,
800
+ });
801
+ continue;
802
+ }
803
+
804
+ const sessionId = state.instanceId;
805
+ const providerType = state.type || readNonEmptyString(settings.providerType);
806
+
807
+ if (providerType) {
808
+ localIdleSessionsChecked += 1;
809
+ tryAssignQueueTask(components, meshId, nodeId, sessionId, providerType);
810
+ } else {
811
+ skippedSessions.push({
812
+ nodeId,
813
+ sessionId,
814
+ reason: 'provider_type_missing',
815
+ });
816
+ }
817
+ }
818
+
819
+ let remoteSessions: Array<{ nodeId: string; sessionId: string; providerType: string }> = [];
820
+ try {
821
+ remoteSessions = MeshRuntimeStore.getInstance().getRemoteIdleSessions();
822
+ } catch { /* best-effort */ }
823
+
824
+ for (const idle of remoteSessions) {
825
+ const node = mesh.nodes.find((n: any) => n.id === idle.nodeId);
826
+ if (node) {
827
+ remoteIdleSessionsChecked += 1;
828
+ const assigned = tryAssignQueueTask(components, meshId, idle.nodeId, idle.sessionId, idle.providerType);
829
+ if (assigned) {
830
+ try {
831
+ MeshRuntimeStore.getInstance().deleteRemoteIdleSession(idle.nodeId, idle.sessionId);
832
+ } catch { /* best-effort */ }
833
+ }
834
+ }
835
+ }
836
+
837
+ autoLaunchStarted = await maybeAutoLaunchOneQueueSession(components, meshId, mesh);
838
+ const afterQueue = getQueue(meshId);
839
+ const pendingAfter = afterQueue.filter(task => task.status === 'pending').length;
840
+ const assignedAfter = afterQueue.filter(task => task.status === 'assigned').length;
841
+ const newlyAssignedTasks = afterQueue
842
+ .filter(task => task.status === 'assigned' && beforeStatus.get(task.id) !== 'assigned')
843
+ .map(task => ({
844
+ id: task.id,
845
+ nodeId: task.assignedNodeId,
846
+ sessionId: task.assignedSessionId,
847
+ }));
848
+ return {
849
+ success: true,
850
+ meshId,
851
+ pendingBefore,
852
+ assignedBefore,
853
+ pendingAfter,
854
+ assignedAfter,
855
+ claimed: newlyAssignedTasks.length > 0,
856
+ newlyAssignedTasks,
857
+ localIdleSessionsChecked,
858
+ remoteIdleSessionsChecked,
859
+ skippedSessions,
860
+ autoLaunchStarted,
861
+ ...(pendingAfter > 0 && newlyAssignedTasks.length === 0 && localIdleSessionsChecked === 0 && remoteIdleSessionsChecked === 0 && !autoLaunchStarted
862
+ ? { noIdleMeshSessionAvailable: true }
863
+ : {}),
864
+ };
865
+ }
866
+
867
+ async function maybeAutoFastForwardIdleNode(components: DaemonComponents, args: {
868
+ meshId: string;
869
+ nodeId: string;
870
+ sessionId?: string;
871
+ providerType?: string;
872
+ }): Promise<void> {
873
+ const mesh = getMeshWithCache(components, args.meshId);
874
+ const node = mesh?.nodes?.find((candidate: any) => candidate?.id === args.nodeId || candidate?.nodeId === args.nodeId);
875
+ const workspace = readNonEmptyString(node?.workspace);
876
+ if (!workspace) return;
877
+ if (!existsSync(workspace)) return;
878
+
879
+ const policy = resolveAutoFastForwardPolicy(mesh);
880
+ if (!policy.enabled) return;
881
+ if (nodeHasActiveMeshWork(components, args.meshId, args.nodeId, args.sessionId)) return;
882
+
883
+ const throttleKey = `${args.meshId}:${args.nodeId}`;
884
+ const now = Date.now();
885
+ const lastAttempt = idleAutoFastForwardLastAttempt.get(throttleKey) || 0;
886
+ if (now - lastAttempt < IDLE_AUTO_FAST_FORWARD_THROTTLE_MS) return;
887
+ idleAutoFastForwardLastAttempt.set(throttleKey, now);
888
+
889
+ const submoduleIgnorePaths = Array.isArray(node?.policy?.submoduleIgnorePaths)
890
+ ? node.policy.submoduleIgnorePaths.filter((value: unknown): value is string => typeof value === 'string')
891
+ : undefined;
892
+ try {
893
+ const dryRun = await fastForwardMeshNode({
894
+ meshId: args.meshId,
895
+ nodeId: args.nodeId,
896
+ workspace,
897
+ execute: false,
898
+ dryRun: true,
899
+ updateSubmodules: false,
900
+ submoduleIgnorePaths,
901
+ trigger: 'idle_auto',
902
+ });
903
+ if (!dryRun || dryRun.code !== 'fast_forward_available' || dryRun.allowed !== true) return;
904
+ const behind = Number(dryRun.current?.behind);
905
+ if (policy.maxBehind !== undefined && Number.isFinite(behind) && behind > policy.maxBehind) return;
906
+ if (policy.requireCleanSubmodules) {
907
+ const submodules = Array.isArray(dryRun.current?.submodules) ? dryRun.current.submodules : [];
908
+ if (submodules.some((submodule: any) => submodule?.dirty || submodule?.outOfSync || submodule?.error)) return;
909
+ }
910
+ await fastForwardMeshNode({
911
+ meshId: args.meshId,
912
+ nodeId: args.nodeId,
913
+ workspace,
914
+ execute: true,
915
+ dryRun: false,
916
+ updateSubmodules: false,
917
+ submoduleIgnorePaths,
918
+ trigger: 'idle_auto',
919
+ });
920
+ } catch (e: any) {
921
+ LOG.warn('MeshFastForward', `Idle auto fast-forward check failed for ${args.nodeId}: ${e?.message || e}`);
922
+ }
923
+ }
924
+
925
+ function runIdleMaintenanceThenAssignQueue(components: DaemonComponents, args: {
926
+ meshId: string;
927
+ nodeId: string;
928
+ sessionId: string;
929
+ providerType: string;
930
+ }): void {
931
+ setImmediate(() => {
932
+ maybeAutoFastForwardIdleNode(components, args)
933
+ .finally(() => {
934
+ try {
935
+ tryAssignQueueTask(components, args.meshId, args.nodeId, args.sessionId, args.providerType);
936
+ } catch (e: any) {
937
+ LOG.warn('MeshQueue', `Failed to assign idle queue task after maintenance for ${args.nodeId}: ${e?.message || e}`);
938
+ }
939
+ });
940
+ });
941
+ }
942
+
943
+ // ---------------------------------------------------------------------------
944
+ // Core event injection
945
+ // ---------------------------------------------------------------------------
946
+
947
+ const MESH_COORDINATOR_EVENTS = new Set([
948
+ 'agent:generating_started',
949
+ 'agent:generating_completed',
950
+ 'agent:waiting_approval',
951
+ 'agent:stopped',
952
+ 'agent:ready',
953
+ 'monitor:long_generating',
954
+ 'refine:accepted',
955
+ 'refine:completed',
956
+ 'refine:failed',
957
+ 'worktree_bootstrap_complete',
958
+ 'worktree_bootstrap_failed',
959
+ ]);
960
+
961
+ const EVENT_TO_LEDGER_KIND: Record<string, MeshLedgerKind> = {
962
+ 'agent:generating_completed': 'task_completed',
963
+ 'agent:waiting_approval': 'task_approval_needed',
964
+ 'agent:stopped': 'task_failed',
965
+ 'monitor:long_generating': 'task_stalled',
966
+ };
967
+
968
+ export function isMeshCoordinatorEvent(eventName: unknown): eventName is string {
969
+ return typeof eventName === 'string' && MESH_COORDINATOR_EVENTS.has(eventName);
970
+ }
971
+
972
+ // Terminal events that the coordinator is actively blocked waiting on. When the
973
+ // coordinator CLI session dispatches a task (e.g. mesh_send_task) it stays in
974
+ // `generating` until the result arrives — but a generating coordinator queues
975
+ // incoming send_message calls into its adapter's pendingOutboundQueue, which is
976
+ // only flushed on the coordinator's OWN idle transition. That transition can't
977
+ // happen until it receives this very event → deadlock. We force-inject these so
978
+ // they bypass the busy send-guard and land in the PTY while generating.
979
+ const MESH_FORCE_INJECT_EVENTS = new Set([
980
+ 'agent:generating_completed',
981
+ 'agent:stopped',
982
+ 'agent:waiting_approval',
983
+ 'refine:completed',
984
+ 'refine:failed',
985
+ 'worktree_bootstrap_complete',
986
+ 'worktree_bootstrap_failed',
987
+ ]);
988
+
989
+ function shouldForceInjectMeshEvent(eventName: unknown): boolean {
990
+ return typeof eventName === 'string' && MESH_FORCE_INJECT_EVENTS.has(eventName);
991
+ }
992
+
993
+ function injectMeshSystemMessage(components: DaemonComponents, args: {
994
+ meshId: string;
995
+ sourceInstanceId?: string;
996
+ nodeId?: string;
997
+ nodeLabel: string;
998
+ event: string;
999
+ metadataEvent: Record<string, unknown>;
1000
+ }) {
1001
+ const eventSessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
1002
+ const eventNodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
1003
+
1004
+ const sourceSession = args.sourceInstanceId
1005
+ ? components.instanceManager.getInstance(args.sourceInstanceId)
1006
+ : undefined;
1007
+ const workerCoordinatorDaemonId = readNonEmptyString(
1008
+ (sourceSession?.getState()?.settings as Record<string, unknown>)?.meshCoordinatorDaemonId,
1009
+ );
1010
+ const localDaemonId = readNonEmptyString(loadConfig().machineId);
1011
+
1012
+ // R2: cloud P2P dashboard metadata sync. The cloud daemon used to do this from its own
1013
+ // relay listener; now the single core forwarder invokes the injected hook (no-op on
1014
+ // standalone) so the event path stays single-listener and the local code path is identical
1015
+ // across standalone and cloud.
1016
+ if (components.onMeshCoordinatorEventForwarded) {
1017
+ try {
1018
+ components.onMeshCoordinatorEventForwarded({
1019
+ event: args.event,
1020
+ meshId: args.meshId,
1021
+ nodeId: eventNodeId || undefined,
1022
+ ...args.metadataEvent,
1023
+ });
1024
+ } catch { /* dashboard metadata sync is best-effort */ }
1025
+ }
1026
+
1027
+ const intentionalCleanupStop = shouldSuppressIntentionalCleanupStop({
1028
+ event: args.event,
1029
+ meshId: args.meshId,
1030
+ metadataEvent: args.metadataEvent,
1031
+ sessionId: eventSessionId || undefined,
1032
+ nodeId: eventNodeId || undefined,
1033
+ });
1034
+ if (intentionalCleanupStop) {
1035
+ if (eventSessionId && eventNodeId) {
1036
+ try {
1037
+ MeshRuntimeStore.getInstance().deleteRemoteIdleSession(eventNodeId, eventSessionId);
1038
+ } catch { /* best-effort */ }
1039
+ }
1040
+ LOG.info('MeshEvents', `Suppressed ${args.event} for intentionally cleanup-stopped session ${eventSessionId || '(unknown session)'}`);
1041
+ return { success: true, forwarded: 0, suppressed: true, intentionalCleanupStop: true };
1042
+ }
1043
+
1044
+ if (args.event === 'monitor:long_generating') {
1045
+ const reconciledCompletion = buildLongGeneratingCompletionReconciliation({
1046
+ meshId: args.meshId,
1047
+ nodeId: args.nodeId,
1048
+ nodeLabel: args.nodeLabel,
1049
+ metadataEvent: args.metadataEvent,
1050
+ sourceInstanceId: args.sourceInstanceId,
1051
+ });
1052
+ if (reconciledCompletion?.source === 'long_generating_reconciliation') {
1053
+ LOG.info('MeshEvents', `Reconciled long-generating monitor to completion for session ${eventSessionId || '(unknown session)'}`);
1054
+ return injectMeshSystemMessage(components, {
1055
+ ...args,
1056
+ event: 'agent:generating_completed',
1057
+ metadataEvent: reconciledCompletion,
1058
+ });
1059
+ }
1060
+ if (reconciledCompletion?.source === 'long_generating_terminal_ledger_suppression') {
1061
+ LOG.info('MeshEvents', `Suppressed long-generating monitor because terminal ledger evidence already exists for session ${eventSessionId || '(unknown session)'}`);
1062
+ return {
1063
+ success: true,
1064
+ forwarded: 0,
1065
+ suppressed: true,
1066
+ terminalLedgerEvidence: true,
1067
+ terminalLedgerKind: reconciledCompletion.terminalLedgerKind,
1068
+ };
1069
+ }
1070
+ }
1071
+
1072
+ if (isDuplicateRefineTerminalEvent(args.meshId, args.event, args.metadataEvent)) {
1073
+ LOG.info('MeshEvents', `Suppressed duplicate ${args.event} for refine job ${readRefineJobId({ metadataEvent: args.metadataEvent })}`);
1074
+ return { success: true, forwarded: 0, suppressed: true, duplicateRefineTerminalEvent: true };
1075
+ }
1076
+
1077
+ const eventTimestamp = readEventTimestamp(args.metadataEvent.timestamp);
1078
+ if (args.event === 'agent:waiting_approval' && eventSessionId) {
1079
+ const duplicateApproval = isDuplicateMeshApprovalEvent({
1080
+ meshId: args.meshId,
1081
+ sessionId: eventSessionId,
1082
+ providerType: readNonEmptyString(args.metadataEvent.providerType) || undefined,
1083
+ timestamp: eventTimestamp,
1084
+ modalMessage: readNonEmptyString(args.metadataEvent.modalMessage) || undefined,
1085
+ modalButtons: args.metadataEvent.modalButtons,
1086
+ });
1087
+ if (duplicateApproval) {
1088
+ LOG.info('MeshEvents', `Suppressed duplicate approval event for mesh ${args.meshId} session ${eventSessionId}`);
1089
+ return { success: true, forwarded: 0, suppressed: true, duplicateApproval: true };
1090
+ }
1091
+ }
1092
+ if (args.event === 'agent:generating_completed' && eventSessionId) {
1093
+ const terminal = findRecentTerminalLedgerEvidence({
1094
+ meshId: args.meshId,
1095
+ sessionId: eventSessionId,
1096
+ nodeId: eventNodeId || undefined,
1097
+ });
1098
+ if (terminal?.kind === 'task_completed' && !sessionHasActiveAssignment(args.meshId, eventSessionId)) {
1099
+ const newDispatchAfterTerminal = hasDispatchAfterTerminal(args.meshId, eventSessionId, terminal.id);
1100
+ if (!newDispatchAfterTerminal) {
1101
+ const terminalProviderSessionId = readNonEmptyString(terminal.payload.providerSessionId);
1102
+ const terminalFinalSummary = readNonEmptyString(terminal.payload.finalSummary);
1103
+ const eventProviderSessionId = readNonEmptyString(args.metadataEvent.providerSessionId);
1104
+ const eventFinalSummary = readNonEmptyString(args.metadataEvent.finalSummary);
1105
+ if (
1106
+ (terminalProviderSessionId && terminalProviderSessionId === eventProviderSessionId)
1107
+ || (terminalFinalSummary && terminalFinalSummary === eventFinalSummary)
1108
+ || args.metadataEvent.source === 'long_generating_reconciliation'
1109
+ ) {
1110
+ LOG.info('MeshEvents', `Suppressed duplicate completion with existing terminal ledger evidence for mesh ${args.meshId} session ${eventSessionId}`);
1111
+ return { success: true, forwarded: 0, suppressed: true, duplicateCompletion: true, terminalLedgerEvidence: true };
1112
+ }
1113
+ }
1114
+ }
1115
+ const duplicateCompletion = isDuplicateMeshCompletionEvent({
1116
+ meshId: args.meshId,
1117
+ event: args.event,
1118
+ sessionId: eventSessionId,
1119
+ providerType: readNonEmptyString(args.metadataEvent.providerType) || undefined,
1120
+ providerSessionId: readNonEmptyString(args.metadataEvent.providerSessionId) || undefined,
1121
+ timestamp: eventTimestamp,
1122
+ finalSummary: readNonEmptyString(args.metadataEvent.finalSummary) || undefined,
1123
+ coordinatorDaemonId: workerCoordinatorDaemonId || undefined,
1124
+ taskId: readNonEmptyString(args.metadataEvent.taskId) || undefined,
1125
+ nodeId: eventNodeId || undefined,
1126
+ });
1127
+ if (duplicateCompletion) {
1128
+ LOG.info('MeshEvents', `Suppressed duplicate completion for mesh ${args.meshId} session ${eventSessionId}`);
1129
+ return { success: true, forwarded: 0, suppressed: true, duplicateCompletion: true };
1130
+ }
1131
+ }
1132
+ if (args.event === 'agent:stopped' && eventSessionId) {
1133
+ const duplicateStopped = isDuplicateMeshCompletionEvent({
1134
+ meshId: args.meshId,
1135
+ event: args.event,
1136
+ sessionId: eventSessionId,
1137
+ providerType: readNonEmptyString(args.metadataEvent.providerType) || undefined,
1138
+ providerSessionId: readNonEmptyString(args.metadataEvent.providerSessionId) || undefined,
1139
+ timestamp: eventTimestamp,
1140
+ finalSummary: readNonEmptyString(args.metadataEvent.finalSummary) || undefined,
1141
+ coordinatorDaemonId: workerCoordinatorDaemonId || undefined,
1142
+ taskId: readNonEmptyString(args.metadataEvent.taskId) || undefined,
1143
+ nodeId: eventNodeId || undefined,
1144
+ });
1145
+ if (duplicateStopped) {
1146
+ LOG.info('MeshEvents', `Suppressed duplicate stopped event for mesh ${args.meshId} session ${eventSessionId}`);
1147
+ return { success: true, forwarded: 0, suppressed: true, duplicateStopped: true };
1148
+ }
1149
+ }
1150
+
1151
+ function markSessionTerminal(sessionId: string, outcome: 'completed' | 'failed', occurredAtMs?: number | null): { id?: string } | null {
1152
+ const task = updateSessionTaskStatus(args.meshId, sessionId, outcome, {
1153
+ occurredAt: occurredAtMs != null ? new Date(occurredAtMs).toISOString() : undefined,
1154
+ });
1155
+ updateDirectDispatchStatus(args.meshId, sessionId, outcome);
1156
+ markSessionDeliveriesTerminal(args.meshId, sessionId, outcome);
1157
+ setImmediate(() => cleanupTerminalDirectDispatches());
1158
+ return task ? { id: task.id } : null;
1159
+ }
1160
+
1161
+ let completedTaskForLedger: { id?: string } | null = null;
1162
+ if (args.event === 'agent:generating_completed') {
1163
+ const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
1164
+ const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
1165
+ const providerType = readNonEmptyString(args.metadataEvent.providerType);
1166
+
1167
+ if (sessionId) {
1168
+ completedTaskForLedger = markSessionTerminal(sessionId, 'completed', eventTimestamp);
1169
+ if (nodeId && providerType) {
1170
+ runIdleMaintenanceThenAssignQueue(components, { meshId: args.meshId, nodeId, sessionId, providerType });
1171
+ }
1172
+ // M1-3: wake dependents of the completed task. The maintenance path above
1173
+ // only assigns to the completing session; dependents may be claimable by
1174
+ // other idle sessions, so run a full queue trigger when any are waiting.
1175
+ const completedTaskId = completedTaskForLedger?.id;
1176
+ if (completedTaskId && hasPendingDependents(args.meshId, completedTaskId)) {
1177
+ setImmediate(() => {
1178
+ triggerMeshQueue(components, args.meshId).catch((e: any) => {
1179
+ LOG.warn('MeshQueue', `Dependent wake after task ${completedTaskId} failed: ${e?.message || e}`);
1180
+ });
1181
+ });
1182
+ }
1183
+ }
1184
+ } else if (args.event === 'agent:ready') {
1185
+ const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
1186
+ const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
1187
+ const providerType = readNonEmptyString(args.metadataEvent.providerType);
1188
+ const providerSessionId = readNonEmptyString(args.metadataEvent.providerSessionId) || undefined;
1189
+ const finalSummary = readNonEmptyString(args.metadataEvent.finalSummary) || undefined;
1190
+ const workerResult = readWorkerResultMetadata(args.metadataEvent);
1191
+ const hasCompletionEvidence = !!finalSummary || !!workerResult;
1192
+ if (sessionId && hasCompletionEvidence) {
1193
+ completedTaskForLedger = markSessionTerminal(sessionId, 'completed');
1194
+ if (completedTaskForLedger) {
1195
+ try {
1196
+ appendLedgerEntry(args.meshId, {
1197
+ kind: 'task_completed',
1198
+ nodeId: nodeId || undefined,
1199
+ sessionId,
1200
+ providerType: providerType || undefined,
1201
+ payload: {
1202
+ event: args.event,
1203
+ nodeLabel: args.nodeLabel,
1204
+ taskId: completedTaskForLedger.id,
1205
+ completedViaReady: true,
1206
+ providerSessionId,
1207
+ finalSummary,
1208
+ workerResult,
1209
+ evidence: buildTaskCompletionEvidence({
1210
+ event: 'agent:ready',
1211
+ nodeId,
1212
+ sessionId,
1213
+ providerType: providerType || undefined,
1214
+ providerSessionId,
1215
+ finalSummary,
1216
+ workerResult,
1217
+ }),
1218
+ },
1219
+ });
1220
+ } catch (e: any) {
1221
+ LOG.warn('MeshLedger', `Failed to record task_completed from ready: ${e?.message || e}`);
1222
+ }
1223
+ }
1224
+ }
1225
+
1226
+ if (sessionId && nodeId && providerType) {
1227
+ sweepExpiredRemoteIdleSessions();
1228
+ try {
1229
+ MeshRuntimeStore.getInstance().setRemoteIdleSession(nodeId, sessionId, providerType, Date.now() + REMOTE_IDLE_SESSION_TTL_MS);
1230
+ } catch { /* best-effort */ }
1231
+ setImmediate(() => {
1232
+ maybeAutoFastForwardIdleNode(components, { meshId: args.meshId, nodeId, sessionId, providerType })
1233
+ .finally(() => {
1234
+ try {
1235
+ const assigned = tryAssignQueueTask(components, args.meshId, nodeId, sessionId, providerType);
1236
+ if (assigned) MeshRuntimeStore.getInstance().deleteRemoteIdleSession(nodeId, sessionId);
1237
+ } catch (e: any) {
1238
+ LOG.warn('MeshQueue', `Failed to assign idle queue task after maintenance for ${nodeId}: ${e?.message || e}`);
1239
+ }
1240
+ });
1241
+ });
1242
+ }
1243
+ } else if (args.event === 'agent:generating_started') {
1244
+ const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
1245
+ const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
1246
+ if (sessionId && nodeId) {
1247
+ try {
1248
+ MeshRuntimeStore.getInstance().deleteRemoteIdleSession(nodeId, sessionId);
1249
+ } catch { /* best-effort */ }
1250
+ }
1251
+ if (sessionId) {
1252
+ updateDirectDispatchStatus(args.meshId, sessionId, 'acked');
1253
+ const activeDeliveries = ((): { id: string }[] => {
1254
+ try { return MeshRuntimeStore.getInstance().getActiveSessionDeliveries(args.meshId, sessionId); }
1255
+ catch { return []; }
1256
+ })();
1257
+ for (const d of activeDeliveries) {
1258
+ updateSessionDeliveryStatus(d.id, 'acked');
1259
+ }
1260
+ }
1261
+ } else if (args.event === 'agent:stopped') {
1262
+ const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
1263
+ const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
1264
+ if (sessionId && nodeId) {
1265
+ try {
1266
+ MeshRuntimeStore.getInstance().deleteRemoteIdleSession(nodeId, sessionId);
1267
+ } catch { /* best-effort */ }
1268
+ }
1269
+ if (sessionId) {
1270
+ completedTaskForLedger = markSessionTerminal(sessionId, 'failed');
1271
+ }
1272
+ }
1273
+
1274
+ const ledgerKind = EVENT_TO_LEDGER_KIND[args.event];
1275
+ if (ledgerKind) {
1276
+ try {
1277
+ const ledgerNodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId) || undefined;
1278
+ const ledgerSessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId) || undefined;
1279
+ const ledgerProviderType = readNonEmptyString(args.metadataEvent.providerType) || undefined;
1280
+ const providerSessionId = readNonEmptyString(args.metadataEvent.providerSessionId) || undefined;
1281
+ const finalSummary = readNonEmptyString(args.metadataEvent.finalSummary) || undefined;
1282
+ const workerResult = readWorkerResultMetadata(args.metadataEvent);
1283
+ const completionEvidence = ledgerKind === 'task_completed' && ledgerNodeId && ledgerSessionId
1284
+ ? buildTaskCompletionEvidence({
1285
+ event: 'agent:generating_completed',
1286
+ nodeId: ledgerNodeId,
1287
+ sessionId: ledgerSessionId,
1288
+ providerType: ledgerProviderType,
1289
+ providerSessionId,
1290
+ finalSummary,
1291
+ workerResult,
1292
+ })
1293
+ : undefined;
1294
+ appendLedgerEntry(args.meshId, {
1295
+ kind: ledgerKind,
1296
+ nodeId: ledgerNodeId,
1297
+ sessionId: ledgerSessionId,
1298
+ providerType: ledgerProviderType,
1299
+ payload: {
1300
+ event: args.event,
1301
+ nodeLabel: args.nodeLabel,
1302
+ taskId: completedTaskForLedger?.id || undefined,
1303
+ providerSessionId,
1304
+ finalSummary,
1305
+ workerResult,
1306
+ completionDiagnostic: args.metadataEvent.completionDiagnostic && typeof args.metadataEvent.completionDiagnostic === 'object'
1307
+ ? args.metadataEvent.completionDiagnostic
1308
+ : undefined,
1309
+ evidence: completionEvidence,
1310
+ // B2: evidenceLevel lets coordinator know when completion evidence is insufficient.
1311
+ ...(completionEvidence
1312
+ ? completionEvidence.workerResult.source === 'default'
1313
+ ? { evidenceLevel: 'insufficient', reviewRecommended: true }
1314
+ : { evidenceLevel: 'sufficient' }
1315
+ : {}),
1316
+ },
1317
+ });
1318
+ } catch (e: any) {
1319
+ LOG.warn('MeshLedger', `Failed to record ${ledgerKind}: ${e?.message || e}`);
1320
+ }
1321
+ }
1322
+
1323
+ let recoveryContext: SessionRecoveryContext | null = null;
1324
+ if (args.event === 'agent:stopped') {
1325
+ try {
1326
+ const mesh = getMesh(args.meshId);
1327
+ const maxRetries = mesh?.policy?.maxTaskRetries ?? 1;
1328
+
1329
+ recoveryContext = getSessionRecoveryContext(args.meshId, {
1330
+ sessionId: resolveEventSessionId(args.metadataEvent, args.sourceInstanceId) || undefined,
1331
+ nodeId: readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId) || undefined,
1332
+ maxRetries,
1333
+ });
1334
+ recoveryContext.failedProviderType = readNonEmptyString(args.metadataEvent.providerType) || null;
1335
+
1336
+ if (recoveryContext.retryRecommended && recoveryContext.consecutiveNodeFailures > 0) {
1337
+ appendLedgerEntry(args.meshId, {
1338
+ kind: 'recovery_attempted',
1339
+ nodeId: recoveryContext.failedNodeId || undefined,
1340
+ sessionId: recoveryContext.failedSessionId || undefined,
1341
+ providerType: recoveryContext.failedProviderType || undefined,
1342
+ payload: {
1343
+ consecutiveFailures: recoveryContext.consecutiveNodeFailures,
1344
+ taskAttemptCount: recoveryContext.taskAttemptCount,
1345
+ retryRecommended: recoveryContext.retryRecommended,
1346
+ advice: recoveryContext.advice,
1347
+ },
1348
+ });
1349
+
1350
+ if (recoveryContext.lastTaskMessage && recoveryContext.failedNodeId && recoveryContext.failedProviderType) {
1351
+ const autoNodeId = recoveryContext.failedNodeId;
1352
+ try {
1353
+ const task = enqueueTask(args.meshId, recoveryContext.lastTaskMessage, {
1354
+ targetNodeId: autoNodeId
1355
+ });
1356
+ LOG.info('MeshRecovery', `Auto-requeued failed task: ${task.id} for node ${autoNodeId}`);
1357
+
1358
+ const node = mesh?.nodes.find((n: any) => n.id === autoNodeId);
1359
+ if (node) {
1360
+ components.cliManager.handleCliCommand('launch_cli', {
1361
+ cliType: recoveryContext.failedProviderType,
1362
+ dir: node.workspace,
1363
+ settings: {
1364
+ role: 'worker',
1365
+ meshNodeFor: args.meshId,
1366
+ meshNodeId: node.id,
1367
+ spawnedSessionVisibility: mesh?.policy?.spawnedSessionVisibility || 'hidden',
1368
+ // Coordinator-dispatched recovery relaunch: same auto-approve
1369
+ // policy as the primary worker launch path.
1370
+ autoApprove: resolveDelegatedWorkerAutoApprove(mesh?.policy, node?.policy),
1371
+ launchedByCoordinator: true,
1372
+ }
1373
+ }).catch((e: any) => LOG.error('MeshRecovery', `Failed to auto-relaunch session for ${node.id}: ${e?.message}`));
1374
+ }
1375
+ } catch (e: any) {
1376
+ LOG.warn('MeshRecovery', `Failed to execute auto-recovery: ${e?.message}`);
1377
+ }
1378
+ }
1379
+ }
1380
+
1381
+ LOG.info('MeshRecovery', `Recovery context for ${args.nodeLabel}: ${recoveryContext.advice}`);
1382
+ } catch (e: any) {
1383
+ LOG.warn('MeshRecovery', `Failed to build recovery context: ${e?.message || e}`);
1384
+ }
1385
+ }
1386
+
1387
+ const messageText = buildMeshSystemMessage({
1388
+ event: args.event,
1389
+ nodeLabel: args.nodeLabel,
1390
+ metadataEvent: args.metadataEvent,
1391
+ recoveryContext,
1392
+ });
1393
+ if (!messageText) return { success: false, error: 'unsupported mesh event' };
1394
+
1395
+ const coordinatorInstances = components.instanceManager.getByCategory('cli').filter((inst) => {
1396
+ const instState = inst.getState();
1397
+ if (instState.settings?.meshCoordinatorFor !== args.meshId) return false;
1398
+ if (args.sourceInstanceId && instState.instanceId === args.sourceInstanceId) return false;
1399
+ // canonicalize: the worker stamps the prefixed daemon id (standalone_/daemon_) while
1400
+ // localDaemonId is the raw machineId — a literal !== wrongly excludes the local coordinator.
1401
+ if (workerCoordinatorDaemonId && localDaemonId && !sameDaemonId(workerCoordinatorDaemonId, localDaemonId)) return false;
1402
+ return true;
1403
+ });
1404
+
1405
+ if (coordinatorInstances.length === 0) {
1406
+ // R2: the coordinator is not a live instance on THIS daemon. If it lives on a remote
1407
+ // daemon, forward over the injected transport (dispatchMeshCommand, supplied by cloud as
1408
+ // P2P; absent/no-op on standalone). This replaces cloud's separate
1409
+ // relayRemoteMeshCoordinatorEvent listener — remote delivery is now part of the single
1410
+ // core forwarder path, so local-vs-remote is one code path and standalone == cloud for
1411
+ // the local case. The pending queue remains the fallback when there is no remote target
1412
+ // or the transport send fails (e.g. P2P down), so MCP coordinators can still backfill.
1413
+ const remoteCoordinatorDaemonId = workerCoordinatorDaemonId && localDaemonId && !sameDaemonId(workerCoordinatorDaemonId, localDaemonId)
1414
+ ? workerCoordinatorDaemonId
1415
+ : '';
1416
+ if (remoteCoordinatorDaemonId && components.dispatchMeshCommand) {
1417
+ const forwardPayload: Record<string, unknown> = {
1418
+ event: args.event,
1419
+ meshId: args.meshId,
1420
+ nodeId: args.nodeId || undefined,
1421
+ workspace: readNonEmptyString(args.metadataEvent.workspace),
1422
+ ...args.metadataEvent,
1423
+ ...(recoveryContext ? { recoveryContext } : {}),
1424
+ };
1425
+ components.dispatchMeshCommand(remoteCoordinatorDaemonId, 'mesh_forward_event', forwardPayload)
1426
+ .then(() => {
1427
+ LOG.info('MeshEvents', `Forwarded ${args.event} for mesh ${args.meshId} to remote coordinator daemon ${remoteCoordinatorDaemonId.slice(0, 12)}…`);
1428
+ })
1429
+ .catch((error: any) => {
1430
+ LOG.warn('MeshEvents', `Remote forward of ${args.event} failed (${error?.message || error}); queuing for backfill`);
1431
+ queuePendingMeshCoordinatorEvent({
1432
+ event: args.event,
1433
+ meshId: args.meshId,
1434
+ nodeLabel: args.nodeLabel,
1435
+ nodeId: args.nodeId || undefined,
1436
+ workspace: readNonEmptyString(args.metadataEvent.workspace),
1437
+ metadataEvent: { ...args.metadataEvent, ...(recoveryContext ? { recoveryContext } : {}) },
1438
+ coordinatorMessage: messageText,
1439
+ queuedAt: Date.now(),
1440
+ targetCoordinatorDaemonId: remoteCoordinatorDaemonId,
1441
+ });
1442
+ });
1443
+ return { success: true, forwarded: 0, remoteForwarded: true };
1444
+ }
1445
+ if (queuePendingMeshCoordinatorEvent({
1446
+ event: args.event,
1447
+ meshId: args.meshId,
1448
+ nodeLabel: args.nodeLabel,
1449
+ nodeId: args.nodeId || undefined,
1450
+ workspace: readNonEmptyString(args.metadataEvent.workspace),
1451
+ metadataEvent: {
1452
+ ...args.metadataEvent,
1453
+ ...(recoveryContext ? { recoveryContext } : {}),
1454
+ },
1455
+ coordinatorMessage: messageText,
1456
+ queuedAt: Date.now(),
1457
+ ...(workerCoordinatorDaemonId ? { targetCoordinatorDaemonId: workerCoordinatorDaemonId } : {}),
1458
+ })) {
1459
+ LOG.info('MeshEvents', `Queued ${args.event} for MCP coordinator (mesh ${args.meshId}${workerCoordinatorDaemonId ? `, coordinator daemon ${workerCoordinatorDaemonId}` : ''})`);
1460
+ }
1461
+ return { success: true, forwarded: 0 };
1462
+ }
1463
+
1464
+ // All events — terminal and non-terminal — are queued for MCP coordinator
1465
+ // delivery via the pending-events file/SQLite path. This ensures that MCP
1466
+ // coordinators (which poll via get_pending_mesh_events / mesh_status) always
1467
+ // receive terminal events even when a live CLI coordinator session is present.
1468
+ // Previously, terminal events skipped the queue and were only direct-injected
1469
+ // into live CLI coordinators via send_message, which silently dropped them
1470
+ // when the coordinator was in a generating state.
1471
+ const pendingEvent = {
1472
+ event: args.event,
1473
+ meshId: args.meshId,
1474
+ nodeLabel: args.nodeLabel,
1475
+ nodeId: args.nodeId || undefined,
1476
+ workspace: readNonEmptyString(args.metadataEvent.workspace),
1477
+ metadataEvent: {
1478
+ ...args.metadataEvent,
1479
+ ...(recoveryContext ? { recoveryContext } : {}),
1480
+ },
1481
+ coordinatorMessage: messageText,
1482
+ queuedAt: Date.now(),
1483
+ ...(workerCoordinatorDaemonId ? { targetCoordinatorDaemonId: workerCoordinatorDaemonId } : {}),
1484
+ };
1485
+ if (queuePendingMeshCoordinatorEvent(pendingEvent)) {
1486
+ LOG.info('MeshEvents', `Queued ${args.event} for MCP coordinator (mesh ${args.meshId})`);
1487
+ }
1488
+
1489
+ // R3: the live coordinators below receive this event directly in their PTY. They (or their
1490
+ // MCP client) also poll get_pending_mesh_events with coordinatorDaemonId = this daemon, which
1491
+ // would re-deliver the queued copy → the user saw the same completion twice. Mark the event
1492
+ // direct-delivered to THIS daemon so that coordinator's own drain skips it. The queue entry
1493
+ // stays for every OTHER consumer (idle / MCP-only / remote) that did not get the direct inject.
1494
+ // markMeshCoordinatorEventDirectDelivered canonicalizes the id internally so the raw
1495
+ // machineId here matches the prefixed instanceId (standalone_mach_X) the coordinator drains with.
1496
+ if (localDaemonId) {
1497
+ markMeshCoordinatorEventDirectDelivered(localDaemonId, pendingEvent);
1498
+ }
1499
+
1500
+ const forceInject = shouldForceInjectMeshEvent(args.event);
1501
+ for (const coord of coordinatorInstances) {
1502
+ const coordState = coord.getState();
1503
+ LOG.info('MeshEvents', `Forwarding mesh event to coordinator ${coordState.instanceId}${forceInject ? ' (force)' : ''}`);
1504
+ coord.onEvent('send_message', {
1505
+ input: { text: messageText, textFallback: messageText },
1506
+ ...(forceInject ? { force: true } : {}),
1507
+ });
1508
+ }
1509
+ return { success: true, forwarded: coordinatorInstances.length };
1510
+ }
1511
+
1512
+ export function handleMeshForwardEvent(components: DaemonComponents, payload: Record<string, unknown>) {
1513
+ const eventName = readNonEmptyString(payload.event);
1514
+ if (!isMeshCoordinatorEvent(eventName)) {
1515
+ return { success: false, error: 'unsupported mesh event' };
1516
+ }
1517
+ const meshId = readNonEmptyString(payload.meshId);
1518
+ if (!meshId) return { success: false, error: 'meshId required' };
1519
+
1520
+ const nodeId = readNonEmptyString(payload.nodeId);
1521
+ const workspace = readNonEmptyString(payload.workspace);
1522
+ const nodeLabel = nodeId ? `Node '${nodeId}'` : workspace ? `Agent at ${workspace}` : 'Remote agent';
1523
+ const relayModalMessage = readNonEmptyString(payload.modalMessage);
1524
+ const relayModalButtons = Array.isArray(payload.modalButtons)
1525
+ ? (payload.modalButtons as unknown[]).filter((b): b is string => typeof b === 'string' && b.trim().length > 0)
1526
+ : null;
1527
+
1528
+ return injectMeshSystemMessage(components, {
1529
+ meshId,
1530
+ nodeId,
1531
+ nodeLabel,
1532
+ event: eventName,
1533
+ metadataEvent: {
1534
+ targetSessionId: readNonEmptyString(payload.targetSessionId) || readNonEmptyString(payload.sessionId) || readNonEmptyString(payload.instanceId),
1535
+ providerType: readNonEmptyString(payload.providerType),
1536
+ providerSessionId: readNonEmptyString(payload.providerSessionId),
1537
+ finalSummary: readNonEmptyString(payload.finalSummary) || readNonEmptyString(payload.summary),
1538
+ jobId: readNonEmptyString(payload.jobId),
1539
+ interactionId: readNonEmptyString(payload.interactionId),
1540
+ status: readNonEmptyString(payload.status),
1541
+ targetDaemonId: readNonEmptyString(payload.targetDaemonId),
1542
+ startedAt: readNonEmptyString(payload.startedAt),
1543
+ completedAt: readNonEmptyString(payload.completedAt),
1544
+ retryOfJobId: readNonEmptyString(payload.retryOfJobId),
1545
+ ...(relayModalMessage ? { modalMessage: relayModalMessage } : {}),
1546
+ ...(relayModalButtons && relayModalButtons.length > 0 ? { modalButtons: relayModalButtons } : {}),
1547
+ ...(payload.result && typeof payload.result === 'object' && !Array.isArray(payload.result) ? { result: payload.result } : {}),
1548
+ ...(payload.completionDiagnostic && typeof payload.completionDiagnostic === 'object' && !Array.isArray(payload.completionDiagnostic) ? { completionDiagnostic: payload.completionDiagnostic } : {}),
1549
+ ...(payload.workerResult && typeof payload.workerResult === 'object' && !Array.isArray(payload.workerResult) ? { workerResult: payload.workerResult } : {}),
1550
+ ...(payload.meshWorkerResult && typeof payload.meshWorkerResult === 'object' && !Array.isArray(payload.meshWorkerResult) ? { meshWorkerResult: payload.meshWorkerResult } : {}),
1551
+ ...(payload.structuredResult && typeof payload.structuredResult === 'object' && !Array.isArray(payload.structuredResult) ? { structuredResult: payload.structuredResult } : {}),
1552
+ ...(payload.timestamp !== undefined ? { timestamp: payload.timestamp } : {}),
1553
+ intentional: payload.intentional === true,
1554
+ intentionalStop: payload.intentionalStop === true,
1555
+ operatorCleanup: payload.operatorCleanup === true,
1556
+ reason: readNonEmptyString(payload.reason),
1557
+ stopReason: readNonEmptyString(payload.stopReason),
1558
+ cleanupReason: readNonEmptyString(payload.cleanupReason),
1559
+ source: readNonEmptyString(payload.source),
1560
+ },
1561
+ });
1562
+ }
1563
+
1564
+ export function setupMeshEventForwarding(components: DaemonComponents) {
1565
+ components.instanceManager.onEvent((event) => {
1566
+ // --- Coordinator idle auto-flush ---
1567
+ // When a coordinator session becomes idle, flush any pending coordinator events
1568
+ // that accumulated while it was generating. This runs before the delegate routing
1569
+ // below so that coordinator-own idle transitions are handled first.
1570
+ // Exception: a coordinator that is itself a direct-dispatch target still needs
1571
+ // to go through delegate routing so that the dispatching coordinator receives a
1572
+ // pendingCoordinatorEvents entry for the completion.
1573
+ if (event.event === 'agent:ready' || event.event === 'agent:generating_completed') {
1574
+ const flushInstanceId = readNonEmptyString(event.instanceId);
1575
+ if (flushInstanceId) {
1576
+ const flushSource = components.instanceManager.getInstance(flushInstanceId);
1577
+ if (flushSource && flushSource.category === 'cli') {
1578
+ const flushState = flushSource.getState();
1579
+ const flushSettings = flushState.settings && typeof flushState.settings === 'object' ? flushState.settings as Record<string, unknown> : {};
1580
+ const coordinatorMeshId = readNonEmptyString(flushSettings.meshCoordinatorFor);
1581
+ if (coordinatorMeshId) {
1582
+ const status = readNonEmptyString(flushState.status).toLowerCase();
1583
+ if (status === 'idle') {
1584
+ try {
1585
+ const localDaemonId = readNonEmptyString(loadConfig().machineId) || undefined;
1586
+ const pendingEvents = drainPendingMeshCoordinatorEvents(coordinatorMeshId, localDaemonId);
1587
+ if (pendingEvents.length > 0) {
1588
+ LOG.info('MeshEvents', `Auto-flushing ${pendingEvents.length} pending coordinator event(s) for mesh ${coordinatorMeshId} on coordinator idle`);
1589
+ for (const pending of pendingEvents) {
1590
+ if (!pending.coordinatorMessage) continue;
1591
+ const forcePending = shouldForceInjectMeshEvent(pending.event);
1592
+ flushSource.onEvent('send_message', {
1593
+ input: { text: pending.coordinatorMessage, textFallback: pending.coordinatorMessage },
1594
+ ...(forcePending ? { force: true } : {}),
1595
+ });
1596
+ }
1597
+ }
1598
+ } catch (e: any) {
1599
+ LOG.warn('MeshEvents', `Failed to auto-flush pending coordinator events: ${e?.message || e}`);
1600
+ }
1601
+ }
1602
+ // Skip delegate routing unless this coordinator session is itself
1603
+ // a direct-dispatch target — in that case fall through so the
1604
+ // dispatching coordinator gets a pendingCoordinatorEvents entry.
1605
+ let hasDirectDispatch = false;
1606
+ try {
1607
+ hasDirectDispatch =
1608
+ getActiveDirectDispatches(coordinatorMeshId).some(d => d.sessionId === flushInstanceId)
1609
+ || hasUnterminalDirectDispatchLedgerEntry(coordinatorMeshId, flushInstanceId);
1610
+ } catch { /* best-effort */ }
1611
+ if (!hasDirectDispatch) return;
1612
+ }
1613
+ }
1614
+ }
1615
+ }
1616
+
1617
+ // --- Delegate event routing ---
1618
+ if (!isMeshCoordinatorEvent(event.event)) return;
1619
+
1620
+ const instanceId = readNonEmptyString(event.instanceId);
1621
+ if (!instanceId) return;
1622
+
1623
+ // R1: all session→node→mesh→coordinator interpretation is folded into the single
1624
+ // resolveWorkerDelegateRouting() resolver. No stamp (meshNodeFor / meshNodeId /
1625
+ // meshCoordinatorDaemonId / meshCoordinatorNodeId / launchedByCoordinator) is read
1626
+ // here to make a routing decision — the resolver is the one authority, and the
1627
+ // forwarder consumes its typed result only.
1628
+ const routing = resolveWorkerDelegateRouting(components, instanceId, {
1629
+ getMeshById: (meshId) => getMeshWithCache(components, meshId),
1630
+ getMeshByWorkspace: (workspace) => getCachedMeshByWorkspace(workspace),
1631
+ });
1632
+ if (!routing.isDelegate) {
1633
+ // R4: a worker that presented a valid envelope but resolved to no mesh used to be
1634
+ // dropped silently. Leave a fail-loud diagnostic so the missing completion is
1635
+ // traceable. Benign non-delegate rejections (not_cli / no_workspace / etc.) are
1636
+ // no-ops inside recordUnroutableDelegateEvent.
1637
+ recordUnroutableDelegateEvent(routing, event.event);
1638
+ return;
1639
+ }
1640
+
1641
+ injectMeshSystemMessage(components, {
1642
+ meshId: routing.meshId,
1643
+ sourceInstanceId: instanceId,
1644
+ nodeId: routing.nodeId,
1645
+ nodeLabel: routing.nodeLabel,
1646
+ event: event.event,
1647
+ metadataEvent: event,
1648
+ });
1649
+ });
1650
+ }