@adhdev/daemon-core 0.9.82-rc.256 → 0.9.82-rc.258

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.
package/dist/index.mjs CHANGED
@@ -3176,6 +3176,21 @@ var init_mesh_runtime_store = __esm({
3176
3176
  expires_at INTEGER NOT NULL
3177
3177
  );
3178
3178
 
3179
+ -- R3: idempotent coordinator inbox. When a terminal/force-inject event is
3180
+ -- direct-injected into a LIVE local CLI coordinator (coord.onEvent('send_message')),
3181
+ -- we record (coordinator_daemon_id, fingerprint) here. That same coordinator also
3182
+ -- polls get_pending_mesh_events, which would re-deliver the queued copy of the very
3183
+ -- event it just received in its PTY \u2192 user sees the completion twice. The drain for
3184
+ -- a coordinator daemon filters out events already direct-delivered to it, giving
3185
+ -- exactly-once-per-coordinator while keeping the queue for other consumers (idle /
3186
+ -- MCP-only / remote) that did NOT receive the direct inject.
3187
+ CREATE TABLE IF NOT EXISTS mesh_direct_delivered_events (
3188
+ coordinator_daemon_id TEXT NOT NULL,
3189
+ fingerprint TEXT NOT NULL,
3190
+ expires_at INTEGER NOT NULL,
3191
+ PRIMARY KEY (coordinator_daemon_id, fingerprint)
3192
+ );
3193
+
3179
3194
  CREATE TABLE IF NOT EXISTS mesh_direct_dispatches (
3180
3195
  task_id TEXT PRIMARY KEY,
3181
3196
  mesh_id TEXT NOT NULL,
@@ -3331,6 +3346,25 @@ var init_mesh_runtime_store = __esm({
3331
3346
  sweepExpiredFingerprints() {
3332
3347
  this.db.prepare("DELETE FROM mesh_completion_fingerprints WHERE expires_at <= ?").run(Date.now());
3333
3348
  }
3349
+ // R3: record that an event (by pending-event fingerprint) was direct-injected into a live
3350
+ // coordinator on the given daemon, so that coordinator's own drain skips the queued copy.
3351
+ recordDirectDelivered(coordinatorDaemonId, fingerprint, ttlMs) {
3352
+ if (!coordinatorDaemonId || !fingerprint) return;
3353
+ this.db.prepare(
3354
+ "INSERT OR REPLACE INTO mesh_direct_delivered_events (coordinator_daemon_id, fingerprint, expires_at) VALUES (?, ?, ?)"
3355
+ ).run(coordinatorDaemonId, fingerprint, Date.now() + ttlMs);
3356
+ this.maybeCheckpointWal();
3357
+ }
3358
+ wasDirectDelivered(coordinatorDaemonId, fingerprint) {
3359
+ if (!coordinatorDaemonId || !fingerprint) return false;
3360
+ const row = this.db.prepare(
3361
+ "SELECT 1 FROM mesh_direct_delivered_events WHERE coordinator_daemon_id = ? AND fingerprint = ? AND expires_at > ?"
3362
+ ).get(coordinatorDaemonId, fingerprint, Date.now());
3363
+ return row !== void 0;
3364
+ }
3365
+ sweepExpiredDirectDelivered() {
3366
+ this.db.prepare("DELETE FROM mesh_direct_delivered_events WHERE expires_at <= ?").run(Date.now());
3367
+ }
3334
3368
  maybeCheckpointWal() {
3335
3369
  if (++this.walWriteCounter < _MeshRuntimeStore.WAL_CHECK_INTERVAL) return;
3336
3370
  this.walWriteCounter = 0;
@@ -5609,6 +5643,16 @@ function readNonEmptyString2(value) {
5609
5643
  function readRecord3(value) {
5610
5644
  return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
5611
5645
  }
5646
+ function canonicalDaemonId(value) {
5647
+ const id = readNonEmptyString2(value);
5648
+ if (!id) return "";
5649
+ return id.replace(/^(?:daemon|standalone)_/, "");
5650
+ }
5651
+ function sameDaemonId(a, b) {
5652
+ const ca = canonicalDaemonId(a);
5653
+ const cb = canonicalDaemonId(b);
5654
+ return ca !== "" && ca === cb;
5655
+ }
5612
5656
  function resolveEventSessionId(event, fallback) {
5613
5657
  return readNonEmptyString2(event.targetSessionId) || readNonEmptyString2(event.sessionId) || readNonEmptyString2(event.instanceId) || readNonEmptyString2(fallback);
5614
5658
  }
@@ -5795,6 +5839,29 @@ function buildPendingEventFingerprint(event) {
5795
5839
  timestamp || ""
5796
5840
  ].join("::");
5797
5841
  }
5842
+ function markMeshCoordinatorEventDirectDelivered(coordinatorDaemonId, event) {
5843
+ const canonical = canonicalDaemonId(coordinatorDaemonId);
5844
+ if (!canonical) return;
5845
+ const fingerprint = buildPendingEventFingerprint(event);
5846
+ if (!fingerprint.trim()) return;
5847
+ try {
5848
+ const store = MeshRuntimeStore.getInstance();
5849
+ store.recordDirectDelivered(canonical, fingerprint, DIRECT_DELIVERED_TTL_MS);
5850
+ store.sweepExpiredDirectDelivered();
5851
+ } catch {
5852
+ }
5853
+ }
5854
+ function wasDirectDeliveredToCoordinator(coordinatorDaemonId, event) {
5855
+ const canonical = canonicalDaemonId(coordinatorDaemonId);
5856
+ if (!canonical) return false;
5857
+ const fingerprint = buildPendingEventFingerprint(event);
5858
+ if (!fingerprint.trim()) return false;
5859
+ try {
5860
+ return MeshRuntimeStore.getInstance().wasDirectDelivered(canonical, fingerprint);
5861
+ } catch {
5862
+ return false;
5863
+ }
5864
+ }
5798
5865
  function hasPendingCoordinatorEventDuplicate(event) {
5799
5866
  const fingerprint = buildPendingEventFingerprint(event);
5800
5867
  if (!fingerprint.trim()) return false;
@@ -5993,7 +6060,9 @@ function drainPendingMeshCoordinatorEvents(meshId, coordinatorDaemonId) {
5993
6060
  for (const event of filtered) pushUnique(event);
5994
6061
  }
5995
6062
  if (merged.length === 0) return [];
5996
- return reconcilePendingMeshCoordinatorEvents(meshId, merged);
6063
+ const deliverable = coordinatorDaemonId ? merged.filter((event) => !wasDirectDeliveredToCoordinator(coordinatorDaemonId, event)) : merged;
6064
+ if (deliverable.length === 0) return [];
6065
+ return reconcilePendingMeshCoordinatorEvents(meshId, deliverable);
5997
6066
  }
5998
6067
  function getPendingMeshCoordinatorEvents(meshId, coordinatorDaemonId) {
5999
6068
  if (!meshId) return [];
@@ -6020,7 +6089,8 @@ function getPendingMeshCoordinatorEvents(meshId, coordinatorDaemonId) {
6020
6089
  for (const event of readPendingMeshCoordinatorEventsFromDisk(meshId, coordinatorDaemonId)) {
6021
6090
  pushUnique(event);
6022
6091
  }
6023
- return reconcilePendingMeshCoordinatorEvents(meshId, merged);
6092
+ const deliverable = coordinatorDaemonId ? merged.filter((event) => !wasDirectDeliveredToCoordinator(coordinatorDaemonId, event)) : merged;
6093
+ return reconcilePendingMeshCoordinatorEvents(meshId, deliverable);
6024
6094
  }
6025
6095
  function clearPendingMeshCoordinatorEvents(meshId, coordinatorDaemonId) {
6026
6096
  if (!meshId) return;
@@ -6036,7 +6106,7 @@ function clearPendingMeshCoordinatorEvents(meshId, coordinatorDaemonId) {
6036
6106
  }
6037
6107
  }
6038
6108
  }
6039
- var REFINE_TERMINAL_EVENTS, MAX_PENDING_EVENTS_BYTES, MAX_PENDING_EVENTS_KEEP;
6109
+ var REFINE_TERMINAL_EVENTS, DIRECT_DELIVERED_TTL_MS, MAX_PENDING_EVENTS_BYTES, MAX_PENDING_EVENTS_KEEP;
6040
6110
  var init_mesh_events_pending = __esm({
6041
6111
  "src/mesh/mesh-events-pending.ts"() {
6042
6112
  "use strict";
@@ -6045,6 +6115,7 @@ var init_mesh_events_pending = __esm({
6045
6115
  init_mesh_runtime_store();
6046
6116
  init_mesh_events_utils();
6047
6117
  REFINE_TERMINAL_EVENTS = /* @__PURE__ */ new Set(["refine:completed", "refine:failed"]);
6118
+ DIRECT_DELIVERED_TTL_MS = 10 * 60 * 1e3;
6048
6119
  MAX_PENDING_EVENTS_BYTES = 100 * 1024;
6049
6120
  MAX_PENDING_EVENTS_KEEP = 50;
6050
6121
  }
@@ -6580,6 +6651,140 @@ var init_cli_detector = __esm({
6580
6651
  }
6581
6652
  });
6582
6653
 
6654
+ // src/mesh/mesh-routing.ts
6655
+ function readSettings(state) {
6656
+ return state?.settings && typeof state.settings === "object" ? state.settings : {};
6657
+ }
6658
+ function resolveWorkerDelegateRouting(components, instanceId, deps) {
6659
+ const sessionId = readNonEmptyString2(instanceId);
6660
+ let workspace = "";
6661
+ let coordinatorDaemonId = "";
6662
+ const reject = (rejectionReason) => ({
6663
+ isDelegate: false,
6664
+ meshId: "",
6665
+ nodeId: "",
6666
+ nodeLabel: "",
6667
+ coordinatorDaemonId,
6668
+ workspace,
6669
+ sessionId,
6670
+ rejectionReason
6671
+ });
6672
+ const sourceInstance = components.instanceManager.getInstance(instanceId);
6673
+ if (!sourceInstance || sourceInstance.category !== "cli") return reject("not_cli");
6674
+ const state = sourceInstance.getState();
6675
+ workspace = readNonEmptyString2(state.workspace);
6676
+ if (!workspace) return reject("no_workspace");
6677
+ const settings = readSettings(state);
6678
+ coordinatorDaemonId = readNonEmptyString2(settings.meshCoordinatorDaemonId);
6679
+ const coordinatorMeshId = readNonEmptyString2(settings.meshCoordinatorFor);
6680
+ let meshIdFromDirectDispatch = "";
6681
+ if (coordinatorMeshId) {
6682
+ let hasActiveDispatch = false;
6683
+ try {
6684
+ hasActiveDispatch = getActiveDirectDispatches(coordinatorMeshId).some((d) => d.sessionId === instanceId) || hasUnterminalDirectDispatchLedgerEntry(coordinatorMeshId, instanceId);
6685
+ } catch {
6686
+ }
6687
+ if (!hasActiveDispatch) return reject("coordinator_not_dispatch_target");
6688
+ meshIdFromDirectDispatch = coordinatorMeshId;
6689
+ }
6690
+ const meshIdFromRuntime = readNonEmptyString2(settings.meshNodeFor) || meshIdFromDirectDispatch;
6691
+ const hasWorkerEnvelope = Boolean(
6692
+ meshIdFromRuntime || settings.launchedByCoordinator || coordinatorDaemonId || readNonEmptyString2(settings.meshCoordinatorNodeId)
6693
+ );
6694
+ if (!hasWorkerEnvelope) return reject("no_worker_envelope");
6695
+ const mesh = meshIdFromRuntime ? deps.getMeshById(meshIdFromRuntime) : deps.getMeshByWorkspace(workspace);
6696
+ const meshId = meshIdFromRuntime || readNonEmptyString2(mesh?.id);
6697
+ if (!meshId) return reject("mesh_unresolved");
6698
+ const targetNode = mesh?.nodes?.find((n) => n.workspace === workspace);
6699
+ const runtimeNodeId = readNonEmptyString2(settings.meshNodeId);
6700
+ const nodeId = readNonEmptyString2(targetNode?.id) || runtimeNodeId;
6701
+ const nodeLabel = targetNode ? `Node '${targetNode.id}'` : runtimeNodeId ? `Node '${runtimeNodeId}'` : `Agent at ${workspace}`;
6702
+ return {
6703
+ isDelegate: true,
6704
+ meshId,
6705
+ nodeId,
6706
+ nodeLabel,
6707
+ coordinatorDaemonId,
6708
+ workspace,
6709
+ sessionId
6710
+ };
6711
+ }
6712
+ function isUnroutableDelegateRejection(routing) {
6713
+ return !routing.isDelegate && routing.rejectionReason === "mesh_unresolved";
6714
+ }
6715
+ function recordUnroutableDelegateEvent(routing, eventName) {
6716
+ if (!isUnroutableDelegateRejection(routing)) return false;
6717
+ const dedupKey = `${routing.sessionId}::${eventName}::${routing.workspace}`;
6718
+ const now = Date.now();
6719
+ const last = recentUnroutableDiagnostics.get(dedupKey);
6720
+ if (last !== void 0 && now - last < UNROUTABLE_DIAGNOSTIC_DEDUP_MS) return false;
6721
+ recentUnroutableDiagnostics.set(dedupKey, now);
6722
+ if (recentUnroutableDiagnostics.size > 256) {
6723
+ for (const [key, ts2] of recentUnroutableDiagnostics) {
6724
+ if (now - ts2 >= UNROUTABLE_DIAGNOSTIC_DEDUP_MS) recentUnroutableDiagnostics.delete(key);
6725
+ }
6726
+ }
6727
+ try {
6728
+ appendLedgerEntry(UNROUTABLE_DIAGNOSTIC_STREAM, {
6729
+ kind: "delivery_unroutable",
6730
+ sessionId: routing.sessionId || void 0,
6731
+ payload: {
6732
+ event: eventName,
6733
+ reason: routing.rejectionReason,
6734
+ workspace: routing.workspace || void 0,
6735
+ coordinatorDaemonId: routing.coordinatorDaemonId || void 0,
6736
+ detail: "Worker envelope was present but no mesh could be resolved; the event could not be routed to a coordinator."
6737
+ }
6738
+ });
6739
+ LOG.warn("MeshEvents", `delivery_unroutable: ${eventName} from session ${routing.sessionId || "(unknown)"} at ${routing.workspace || "(no workspace)"} \u2014 envelope present but mesh unresolved`);
6740
+ return true;
6741
+ } catch (e) {
6742
+ LOG.warn("MeshEvents", `Failed to record delivery_unroutable diagnostic: ${e?.message || e}`);
6743
+ return false;
6744
+ }
6745
+ }
6746
+ function getRecentUnroutableDeliveries(opts) {
6747
+ const sinceMs = opts?.sinceMs ?? 60 * 60 * 1e3;
6748
+ const limit = opts?.limit ?? 20;
6749
+ let entries;
6750
+ try {
6751
+ entries = readLedgerEntries(UNROUTABLE_DIAGNOSTIC_STREAM, { kind: ["delivery_unroutable"], tail: 200 });
6752
+ } catch {
6753
+ return [];
6754
+ }
6755
+ const cutoff = Date.now() - sinceMs;
6756
+ const out = [];
6757
+ for (let i = entries.length - 1; i >= 0; i--) {
6758
+ const entry = entries[i];
6759
+ const ts2 = new Date(entry.timestamp).getTime();
6760
+ if (!Number.isNaN(ts2) && ts2 < cutoff) continue;
6761
+ const payload = entry.payload && typeof entry.payload === "object" ? entry.payload : {};
6762
+ out.push({
6763
+ timestamp: entry.timestamp,
6764
+ event: readNonEmptyString2(payload.event),
6765
+ sessionId: readNonEmptyString2(entry.sessionId) || readNonEmptyString2(payload.sessionId) || void 0,
6766
+ workspace: readNonEmptyString2(payload.workspace) || void 0,
6767
+ coordinatorDaemonId: readNonEmptyString2(payload.coordinatorDaemonId) || void 0
6768
+ });
6769
+ if (out.length >= limit) break;
6770
+ }
6771
+ return out;
6772
+ }
6773
+ var UNROUTABLE_DIAGNOSTIC_STREAM, UNROUTABLE_DIAGNOSTIC_DEDUP_MS, recentUnroutableDiagnostics;
6774
+ var init_mesh_routing = __esm({
6775
+ "src/mesh/mesh-routing.ts"() {
6776
+ "use strict";
6777
+ init_mesh_work_queue();
6778
+ init_mesh_events_stale();
6779
+ init_mesh_ledger();
6780
+ init_logger();
6781
+ init_mesh_events_utils();
6782
+ UNROUTABLE_DIAGNOSTIC_STREAM = "__unroutable__";
6783
+ UNROUTABLE_DIAGNOSTIC_DEDUP_MS = 60 * 1e3;
6784
+ recentUnroutableDiagnostics = /* @__PURE__ */ new Map();
6785
+ }
6786
+ });
6787
+
6583
6788
  // src/mesh/mesh-events-coordinator.ts
6584
6789
  import { existsSync as existsSync14 } from "fs";
6585
6790
  function getCachedMeshByWorkspace(workspace) {
@@ -6593,6 +6798,9 @@ function getCachedMeshByWorkspace(workspace) {
6593
6798
  function __resetIdleAutoFastForwardForTests() {
6594
6799
  idleAutoFastForwardLastAttempt.clear();
6595
6800
  }
6801
+ function __resetMeshWorkspaceCacheForTests() {
6802
+ meshByWorkspaceCache.clear();
6803
+ }
6596
6804
  function sweepExpiredRemoteIdleSessions() {
6597
6805
  try {
6598
6806
  MeshRuntimeStore.getInstance().pruneExpiredRemoteIdleSessions();
@@ -7259,6 +7467,17 @@ function injectMeshSystemMessage(components, args) {
7259
7467
  sourceSession?.getState()?.settings?.meshCoordinatorDaemonId
7260
7468
  );
7261
7469
  const localDaemonId = readNonEmptyString2(loadConfig().machineId);
7470
+ if (components.onMeshCoordinatorEventForwarded) {
7471
+ try {
7472
+ components.onMeshCoordinatorEventForwarded({
7473
+ event: args.event,
7474
+ meshId: args.meshId,
7475
+ nodeId: eventNodeId || void 0,
7476
+ ...args.metadataEvent
7477
+ });
7478
+ } catch {
7479
+ }
7480
+ }
7262
7481
  const intentionalCleanupStop = shouldSuppressIntentionalCleanupStop({
7263
7482
  event: args.event,
7264
7483
  meshId: args.meshId,
@@ -7603,10 +7822,38 @@ function injectMeshSystemMessage(components, args) {
7603
7822
  const instState = inst.getState();
7604
7823
  if (instState.settings?.meshCoordinatorFor !== args.meshId) return false;
7605
7824
  if (args.sourceInstanceId && instState.instanceId === args.sourceInstanceId) return false;
7606
- if (workerCoordinatorDaemonId && localDaemonId && workerCoordinatorDaemonId !== localDaemonId) return false;
7825
+ if (workerCoordinatorDaemonId && localDaemonId && !sameDaemonId(workerCoordinatorDaemonId, localDaemonId)) return false;
7607
7826
  return true;
7608
7827
  });
7609
7828
  if (coordinatorInstances.length === 0) {
7829
+ const remoteCoordinatorDaemonId = workerCoordinatorDaemonId && localDaemonId && !sameDaemonId(workerCoordinatorDaemonId, localDaemonId) ? workerCoordinatorDaemonId : "";
7830
+ if (remoteCoordinatorDaemonId && components.dispatchMeshCommand) {
7831
+ const forwardPayload = {
7832
+ event: args.event,
7833
+ meshId: args.meshId,
7834
+ nodeId: args.nodeId || void 0,
7835
+ workspace: readNonEmptyString2(args.metadataEvent.workspace),
7836
+ ...args.metadataEvent,
7837
+ ...recoveryContext ? { recoveryContext } : {}
7838
+ };
7839
+ components.dispatchMeshCommand(remoteCoordinatorDaemonId, "mesh_forward_event", forwardPayload).then(() => {
7840
+ LOG.info("MeshEvents", `Forwarded ${args.event} for mesh ${args.meshId} to remote coordinator daemon ${remoteCoordinatorDaemonId.slice(0, 12)}\u2026`);
7841
+ }).catch((error) => {
7842
+ LOG.warn("MeshEvents", `Remote forward of ${args.event} failed (${error?.message || error}); queuing for backfill`);
7843
+ queuePendingMeshCoordinatorEvent({
7844
+ event: args.event,
7845
+ meshId: args.meshId,
7846
+ nodeLabel: args.nodeLabel,
7847
+ nodeId: args.nodeId || void 0,
7848
+ workspace: readNonEmptyString2(args.metadataEvent.workspace),
7849
+ metadataEvent: { ...args.metadataEvent, ...recoveryContext ? { recoveryContext } : {} },
7850
+ coordinatorMessage: messageText,
7851
+ queuedAt: Date.now(),
7852
+ targetCoordinatorDaemonId: remoteCoordinatorDaemonId
7853
+ });
7854
+ });
7855
+ return { success: true, forwarded: 0, remoteForwarded: true };
7856
+ }
7610
7857
  if (queuePendingMeshCoordinatorEvent({
7611
7858
  event: args.event,
7612
7859
  meshId: args.meshId,
@@ -7625,7 +7872,7 @@ function injectMeshSystemMessage(components, args) {
7625
7872
  }
7626
7873
  return { success: true, forwarded: 0 };
7627
7874
  }
7628
- if (queuePendingMeshCoordinatorEvent({
7875
+ const pendingEvent = {
7629
7876
  event: args.event,
7630
7877
  meshId: args.meshId,
7631
7878
  nodeLabel: args.nodeLabel,
@@ -7638,9 +7885,13 @@ function injectMeshSystemMessage(components, args) {
7638
7885
  coordinatorMessage: messageText,
7639
7886
  queuedAt: Date.now(),
7640
7887
  ...workerCoordinatorDaemonId ? { targetCoordinatorDaemonId: workerCoordinatorDaemonId } : {}
7641
- })) {
7888
+ };
7889
+ if (queuePendingMeshCoordinatorEvent(pendingEvent)) {
7642
7890
  LOG.info("MeshEvents", `Queued ${args.event} for MCP coordinator (mesh ${args.meshId})`);
7643
7891
  }
7892
+ if (localDaemonId) {
7893
+ markMeshCoordinatorEventDirectDelivered(localDaemonId, pendingEvent);
7894
+ }
7644
7895
  const forceInject = shouldForceInjectMeshEvent(args.event);
7645
7896
  for (const coord of coordinatorInstances) {
7646
7897
  const coordState = coord.getState();
@@ -7708,15 +7959,15 @@ function setupMeshEventForwarding(components) {
7708
7959
  if (flushSource && flushSource.category === "cli") {
7709
7960
  const flushState = flushSource.getState();
7710
7961
  const flushSettings = flushState.settings && typeof flushState.settings === "object" ? flushState.settings : {};
7711
- const coordinatorMeshId2 = readNonEmptyString2(flushSettings.meshCoordinatorFor);
7712
- if (coordinatorMeshId2) {
7962
+ const coordinatorMeshId = readNonEmptyString2(flushSettings.meshCoordinatorFor);
7963
+ if (coordinatorMeshId) {
7713
7964
  const status = readNonEmptyString2(flushState.status).toLowerCase();
7714
7965
  if (status === "idle") {
7715
7966
  try {
7716
7967
  const localDaemonId = readNonEmptyString2(loadConfig().machineId) || void 0;
7717
- const pendingEvents = drainPendingMeshCoordinatorEvents(coordinatorMeshId2, localDaemonId);
7968
+ const pendingEvents = drainPendingMeshCoordinatorEvents(coordinatorMeshId, localDaemonId);
7718
7969
  if (pendingEvents.length > 0) {
7719
- LOG.info("MeshEvents", `Auto-flushing ${pendingEvents.length} pending coordinator event(s) for mesh ${coordinatorMeshId2} on coordinator idle`);
7970
+ LOG.info("MeshEvents", `Auto-flushing ${pendingEvents.length} pending coordinator event(s) for mesh ${coordinatorMeshId} on coordinator idle`);
7720
7971
  for (const pending of pendingEvents) {
7721
7972
  if (!pending.coordinatorMessage) continue;
7722
7973
  const forcePending = shouldForceInjectMeshEvent(pending.event);
@@ -7732,7 +7983,7 @@ function setupMeshEventForwarding(components) {
7732
7983
  }
7733
7984
  let hasDirectDispatch = false;
7734
7985
  try {
7735
- hasDirectDispatch = getActiveDirectDispatches(coordinatorMeshId2).some((d) => d.sessionId === flushInstanceId) || hasUnterminalDirectDispatchLedgerEntry(coordinatorMeshId2, flushInstanceId);
7986
+ hasDirectDispatch = getActiveDirectDispatches(coordinatorMeshId).some((d) => d.sessionId === flushInstanceId) || hasUnterminalDirectDispatchLedgerEntry(coordinatorMeshId, flushInstanceId);
7736
7987
  } catch {
7737
7988
  }
7738
7989
  if (!hasDirectDispatch) return;
@@ -7743,37 +7994,19 @@ function setupMeshEventForwarding(components) {
7743
7994
  if (!isMeshCoordinatorEvent(event.event)) return;
7744
7995
  const instanceId = readNonEmptyString2(event.instanceId);
7745
7996
  if (!instanceId) return;
7746
- const sourceInstance = components.instanceManager.getInstance(instanceId);
7747
- if (!sourceInstance || sourceInstance.category !== "cli") return;
7748
- const state = sourceInstance.getState();
7749
- const workspace = readNonEmptyString2(state.workspace);
7750
- if (!workspace) return;
7751
- const settings = state.settings && typeof state.settings === "object" ? state.settings : {};
7752
- const coordinatorMeshId = readNonEmptyString2(settings.meshCoordinatorFor);
7753
- let meshIdFromDirectDispatch = "";
7754
- if (coordinatorMeshId) {
7755
- try {
7756
- const hasActiveDispatch = getActiveDirectDispatches(coordinatorMeshId).some((d) => d.sessionId === instanceId) || hasUnterminalDirectDispatchLedgerEntry(coordinatorMeshId, instanceId);
7757
- if (hasActiveDispatch) meshIdFromDirectDispatch = coordinatorMeshId;
7758
- } catch {
7759
- }
7760
- if (!meshIdFromDirectDispatch) return;
7761
- }
7762
- const meshIdFromRuntime = readNonEmptyString2(settings.meshNodeFor) || meshIdFromDirectDispatch;
7763
- const isMeshDelegate = Boolean(meshIdFromRuntime || settings.launchedByCoordinator);
7764
- if (!isMeshDelegate) return;
7765
- const mesh = meshIdFromRuntime ? getMeshWithCache(components, meshIdFromRuntime) : getCachedMeshByWorkspace(workspace);
7766
- const meshId = meshIdFromRuntime || readNonEmptyString2(mesh?.id);
7767
- if (!meshId) return;
7768
- const targetNode = mesh?.nodes?.find((n) => n.workspace === workspace);
7769
- const runtimeNodeId = readNonEmptyString2(settings.meshNodeId);
7770
- const resolvedNodeId = targetNode?.id || runtimeNodeId;
7771
- const nodeLabel = targetNode ? `Node '${targetNode.id}'` : runtimeNodeId ? `Node '${runtimeNodeId}'` : `Agent at ${workspace}`;
7997
+ const routing = resolveWorkerDelegateRouting(components, instanceId, {
7998
+ getMeshById: (meshId) => getMeshWithCache(components, meshId),
7999
+ getMeshByWorkspace: (workspace) => getCachedMeshByWorkspace(workspace)
8000
+ });
8001
+ if (!routing.isDelegate) {
8002
+ recordUnroutableDelegateEvent(routing, event.event);
8003
+ return;
8004
+ }
7772
8005
  injectMeshSystemMessage(components, {
7773
- meshId,
8006
+ meshId: routing.meshId,
7774
8007
  sourceInstanceId: instanceId,
7775
- nodeId: resolvedNodeId,
7776
- nodeLabel,
8008
+ nodeId: routing.nodeId,
8009
+ nodeLabel: routing.nodeLabel,
7777
8010
  event: event.event,
7778
8011
  metadataEvent: event
7779
8012
  });
@@ -7793,6 +8026,7 @@ var init_mesh_events_coordinator = __esm({
7793
8026
  init_mesh_delivery_policy();
7794
8027
  init_mesh_runtime_store();
7795
8028
  init_mesh_events_pending();
8029
+ init_mesh_routing();
7796
8030
  init_mesh_events_stale();
7797
8031
  init_mesh_events_utils();
7798
8032
  REMOTE_IDLE_SESSION_TTL_MS = 5 * 60 * 1e3;
@@ -7840,11 +8074,13 @@ var init_mesh_events_coordinator = __esm({
7840
8074
  var mesh_events_exports = {};
7841
8075
  __export(mesh_events_exports, {
7842
8076
  __resetIdleAutoFastForwardForTests: () => __resetIdleAutoFastForwardForTests,
8077
+ __resetMeshWorkspaceCacheForTests: () => __resetMeshWorkspaceCacheForTests,
7843
8078
  clearPendingMeshCoordinatorEvents: () => clearPendingMeshCoordinatorEvents,
7844
8079
  drainPendingMeshCoordinatorEvents: () => drainPendingMeshCoordinatorEvents,
7845
8080
  getPendingMeshCoordinatorEvents: () => getPendingMeshCoordinatorEvents,
7846
8081
  handleMeshForwardEvent: () => handleMeshForwardEvent,
7847
8082
  isMeshCoordinatorEvent: () => isMeshCoordinatorEvent,
8083
+ markMeshCoordinatorEventDirectDelivered: () => markMeshCoordinatorEventDirectDelivered,
7848
8084
  queuePendingMeshCoordinatorEvent: () => queuePendingMeshCoordinatorEvent,
7849
8085
  reconcileDirectDispatchCompletionFromTranscript: () => reconcileDirectDispatchCompletionFromTranscript,
7850
8086
  setupMeshEventForwarding: () => setupMeshEventForwarding,
@@ -38032,6 +38268,7 @@ init_logger();
38032
38268
  import * as yaml3 from "js-yaml";
38033
38269
  init_mesh_coordinator();
38034
38270
  init_mesh_events();
38271
+ init_mesh_routing();
38035
38272
  init_mesh_host_ownership();
38036
38273
  init_mesh_fast_forward();
38037
38274
 
@@ -44798,6 +45035,7 @@ ${ptyResult.output.slice(-2e3)}`);
44798
45035
  }
44799
45036
  const callerCoordinatorDaemonId = typeof args?.coordinatorDaemonId === "string" && args.coordinatorDaemonId.trim() ? args.coordinatorDaemonId.trim() : this.deps.statusInstanceId || void 0;
44800
45037
  const pendingCoordinatorEvents = getPendingMeshCoordinatorEvents(meshId, callerCoordinatorDaemonId);
45038
+ const unroutableDeliveries = getRecentUnroutableDeliveries();
44801
45039
  const previewFreshness = (() => {
44802
45040
  const localRepoRoot = nodeStatuses.map((node) => readStringValue(node?.git?.repoRoot, node?.repoRoot, node?.workspace)).find((candidate) => !!candidate && fs23.existsSync(candidate));
44803
45041
  return localRepoRoot ? buildPreviewFreshness(localRepoRoot) : void 0;
@@ -44853,6 +45091,7 @@ ${ptyResult.output.slice(-2e3)}`);
44853
45091
  ...asyncRefineJobs.length > 0 ? { asyncRefineJobs } : {},
44854
45092
  ...historicalSessions ? { historicalSessions } : {},
44855
45093
  ...pendingCoordinatorEvents.length > 0 ? { pendingCoordinatorEvents } : {},
45094
+ ...unroutableDeliveries.length > 0 ? { unroutableDeliveries } : {},
44856
45095
  activeRefineJobs: Array.from(this.runningRefineJobs.values()).filter((job) => job.meshId === meshId).map((job) => ({
44857
45096
  jobId: job.jobId,
44858
45097
  nodeId: job.targetNodeId,
@@ -44862,9 +45101,13 @@ ${ptyResult.output.slice(-2e3)}`);
44862
45101
  targetCoordinatorDaemonId: job.targetCoordinatorDaemonId
44863
45102
  }))
44864
45103
  };
44865
- const { pendingCoordinatorEvents: _pendingCoordinatorEvents, ...cacheableStatusResult } = statusResult;
45104
+ const { pendingCoordinatorEvents: _pendingCoordinatorEvents, unroutableDeliveries: _unroutableDeliveries, ...cacheableStatusResult } = statusResult;
44866
45105
  const rememberedStatus = this.rememberAggregateMeshStatus(meshId, cacheableStatusResult, refreshReason);
44867
- const returnedStatus = pendingCoordinatorEvents.length > 0 ? { ...rememberedStatus, pendingCoordinatorEvents } : rememberedStatus;
45106
+ const returnedStatus = {
45107
+ ...rememberedStatus,
45108
+ ...pendingCoordinatorEvents.length > 0 ? { pendingCoordinatorEvents } : {},
45109
+ ...unroutableDeliveries.length > 0 ? { unroutableDeliveries } : {}
45110
+ };
44868
45111
  logRepoMeshStatusDebug("return_live", {
44869
45112
  meshId,
44870
45113
  command: "mesh_status",
@@ -53193,7 +53436,8 @@ async function initDaemonComponents(config) {
53193
53436
  sessionRegistry,
53194
53437
  detectedIdes: detectedIdesRef,
53195
53438
  refreshProviderAvailability,
53196
- dispatchMeshCommand: config.dispatchMeshCommand
53439
+ dispatchMeshCommand: config.dispatchMeshCommand,
53440
+ onMeshCoordinatorEventForwarded: config.onMeshCoordinatorEventForwarded
53197
53441
  };
53198
53442
  setupMeshEventForwarding(components);
53199
53443
  setImmediate(() => void router.resumePendingRefineJobsOnStartup());