@adhdev/daemon-standalone 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.js CHANGED
@@ -32926,6 +32926,21 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
32926
32926
  expires_at INTEGER NOT NULL
32927
32927
  );
32928
32928
 
32929
+ -- R3: idempotent coordinator inbox. When a terminal/force-inject event is
32930
+ -- direct-injected into a LIVE local CLI coordinator (coord.onEvent('send_message')),
32931
+ -- we record (coordinator_daemon_id, fingerprint) here. That same coordinator also
32932
+ -- polls get_pending_mesh_events, which would re-deliver the queued copy of the very
32933
+ -- event it just received in its PTY \u2192 user sees the completion twice. The drain for
32934
+ -- a coordinator daemon filters out events already direct-delivered to it, giving
32935
+ -- exactly-once-per-coordinator while keeping the queue for other consumers (idle /
32936
+ -- MCP-only / remote) that did NOT receive the direct inject.
32937
+ CREATE TABLE IF NOT EXISTS mesh_direct_delivered_events (
32938
+ coordinator_daemon_id TEXT NOT NULL,
32939
+ fingerprint TEXT NOT NULL,
32940
+ expires_at INTEGER NOT NULL,
32941
+ PRIMARY KEY (coordinator_daemon_id, fingerprint)
32942
+ );
32943
+
32929
32944
  CREATE TABLE IF NOT EXISTS mesh_direct_dispatches (
32930
32945
  task_id TEXT PRIMARY KEY,
32931
32946
  mesh_id TEXT NOT NULL,
@@ -33081,6 +33096,25 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
33081
33096
  sweepExpiredFingerprints() {
33082
33097
  this.db.prepare("DELETE FROM mesh_completion_fingerprints WHERE expires_at <= ?").run(Date.now());
33083
33098
  }
33099
+ // R3: record that an event (by pending-event fingerprint) was direct-injected into a live
33100
+ // coordinator on the given daemon, so that coordinator's own drain skips the queued copy.
33101
+ recordDirectDelivered(coordinatorDaemonId, fingerprint, ttlMs) {
33102
+ if (!coordinatorDaemonId || !fingerprint) return;
33103
+ this.db.prepare(
33104
+ "INSERT OR REPLACE INTO mesh_direct_delivered_events (coordinator_daemon_id, fingerprint, expires_at) VALUES (?, ?, ?)"
33105
+ ).run(coordinatorDaemonId, fingerprint, Date.now() + ttlMs);
33106
+ this.maybeCheckpointWal();
33107
+ }
33108
+ wasDirectDelivered(coordinatorDaemonId, fingerprint) {
33109
+ if (!coordinatorDaemonId || !fingerprint) return false;
33110
+ const row = this.db.prepare(
33111
+ "SELECT 1 FROM mesh_direct_delivered_events WHERE coordinator_daemon_id = ? AND fingerprint = ? AND expires_at > ?"
33112
+ ).get(coordinatorDaemonId, fingerprint, Date.now());
33113
+ return row !== void 0;
33114
+ }
33115
+ sweepExpiredDirectDelivered() {
33116
+ this.db.prepare("DELETE FROM mesh_direct_delivered_events WHERE expires_at <= ?").run(Date.now());
33117
+ }
33084
33118
  maybeCheckpointWal() {
33085
33119
  if (++this.walWriteCounter < _MeshRuntimeStore.WAL_CHECK_INTERVAL) return;
33086
33120
  this.walWriteCounter = 0;
@@ -35373,6 +35407,16 @@ ${rendered}`, "utf-8");
35373
35407
  function readRecord3(value) {
35374
35408
  return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
35375
35409
  }
35410
+ function canonicalDaemonId(value) {
35411
+ const id = readNonEmptyString2(value);
35412
+ if (!id) return "";
35413
+ return id.replace(/^(?:daemon|standalone)_/, "");
35414
+ }
35415
+ function sameDaemonId(a, b) {
35416
+ const ca = canonicalDaemonId(a);
35417
+ const cb = canonicalDaemonId(b);
35418
+ return ca !== "" && ca === cb;
35419
+ }
35376
35420
  function resolveEventSessionId(event, fallback) {
35377
35421
  return readNonEmptyString2(event.targetSessionId) || readNonEmptyString2(event.sessionId) || readNonEmptyString2(event.instanceId) || readNonEmptyString2(fallback);
35378
35422
  }
@@ -35554,6 +35598,29 @@ Next step: ${nextStep}`;
35554
35598
  timestamp || ""
35555
35599
  ].join("::");
35556
35600
  }
35601
+ function markMeshCoordinatorEventDirectDelivered(coordinatorDaemonId, event) {
35602
+ const canonical = canonicalDaemonId(coordinatorDaemonId);
35603
+ if (!canonical) return;
35604
+ const fingerprint = buildPendingEventFingerprint(event);
35605
+ if (!fingerprint.trim()) return;
35606
+ try {
35607
+ const store = MeshRuntimeStore.getInstance();
35608
+ store.recordDirectDelivered(canonical, fingerprint, DIRECT_DELIVERED_TTL_MS);
35609
+ store.sweepExpiredDirectDelivered();
35610
+ } catch {
35611
+ }
35612
+ }
35613
+ function wasDirectDeliveredToCoordinator(coordinatorDaemonId, event) {
35614
+ const canonical = canonicalDaemonId(coordinatorDaemonId);
35615
+ if (!canonical) return false;
35616
+ const fingerprint = buildPendingEventFingerprint(event);
35617
+ if (!fingerprint.trim()) return false;
35618
+ try {
35619
+ return MeshRuntimeStore.getInstance().wasDirectDelivered(canonical, fingerprint);
35620
+ } catch {
35621
+ return false;
35622
+ }
35623
+ }
35557
35624
  function hasPendingCoordinatorEventDuplicate(event) {
35558
35625
  const fingerprint = buildPendingEventFingerprint(event);
35559
35626
  if (!fingerprint.trim()) return false;
@@ -35752,7 +35819,9 @@ Next step: ${nextStep}`;
35752
35819
  for (const event of filtered) pushUnique(event);
35753
35820
  }
35754
35821
  if (merged.length === 0) return [];
35755
- return reconcilePendingMeshCoordinatorEvents(meshId, merged);
35822
+ const deliverable = coordinatorDaemonId ? merged.filter((event) => !wasDirectDeliveredToCoordinator(coordinatorDaemonId, event)) : merged;
35823
+ if (deliverable.length === 0) return [];
35824
+ return reconcilePendingMeshCoordinatorEvents(meshId, deliverable);
35756
35825
  }
35757
35826
  function getPendingMeshCoordinatorEvents(meshId, coordinatorDaemonId) {
35758
35827
  if (!meshId) return [];
@@ -35779,7 +35848,8 @@ Next step: ${nextStep}`;
35779
35848
  for (const event of readPendingMeshCoordinatorEventsFromDisk(meshId, coordinatorDaemonId)) {
35780
35849
  pushUnique(event);
35781
35850
  }
35782
- return reconcilePendingMeshCoordinatorEvents(meshId, merged);
35851
+ const deliverable = coordinatorDaemonId ? merged.filter((event) => !wasDirectDeliveredToCoordinator(coordinatorDaemonId, event)) : merged;
35852
+ return reconcilePendingMeshCoordinatorEvents(meshId, deliverable);
35783
35853
  }
35784
35854
  function clearPendingMeshCoordinatorEvents(meshId, coordinatorDaemonId) {
35785
35855
  if (!meshId) return;
@@ -35799,6 +35869,7 @@ Next step: ${nextStep}`;
35799
35869
  var import_path8;
35800
35870
  var import_crypto7;
35801
35871
  var REFINE_TERMINAL_EVENTS;
35872
+ var DIRECT_DELIVERED_TTL_MS;
35802
35873
  var MAX_PENDING_EVENTS_BYTES;
35803
35874
  var MAX_PENDING_EVENTS_KEEP;
35804
35875
  var init_mesh_events_pending = __esm2({
@@ -35812,6 +35883,7 @@ Next step: ${nextStep}`;
35812
35883
  init_mesh_runtime_store();
35813
35884
  init_mesh_events_utils();
35814
35885
  REFINE_TERMINAL_EVENTS = /* @__PURE__ */ new Set(["refine:completed", "refine:failed"]);
35886
+ DIRECT_DELIVERED_TTL_MS = 10 * 60 * 1e3;
35815
35887
  MAX_PENDING_EVENTS_BYTES = 100 * 1024;
35816
35888
  MAX_PENDING_EVENTS_KEEP = 50;
35817
35889
  }
@@ -36347,6 +36419,140 @@ Next step: ${nextStep}`;
36347
36419
  import_fs9 = require("fs");
36348
36420
  }
36349
36421
  });
36422
+ function readSettings(state) {
36423
+ return state?.settings && typeof state.settings === "object" ? state.settings : {};
36424
+ }
36425
+ function resolveWorkerDelegateRouting(components, instanceId, deps) {
36426
+ const sessionId = readNonEmptyString2(instanceId);
36427
+ let workspace = "";
36428
+ let coordinatorDaemonId = "";
36429
+ const reject = (rejectionReason) => ({
36430
+ isDelegate: false,
36431
+ meshId: "",
36432
+ nodeId: "",
36433
+ nodeLabel: "",
36434
+ coordinatorDaemonId,
36435
+ workspace,
36436
+ sessionId,
36437
+ rejectionReason
36438
+ });
36439
+ const sourceInstance = components.instanceManager.getInstance(instanceId);
36440
+ if (!sourceInstance || sourceInstance.category !== "cli") return reject("not_cli");
36441
+ const state = sourceInstance.getState();
36442
+ workspace = readNonEmptyString2(state.workspace);
36443
+ if (!workspace) return reject("no_workspace");
36444
+ const settings = readSettings(state);
36445
+ coordinatorDaemonId = readNonEmptyString2(settings.meshCoordinatorDaemonId);
36446
+ const coordinatorMeshId = readNonEmptyString2(settings.meshCoordinatorFor);
36447
+ let meshIdFromDirectDispatch = "";
36448
+ if (coordinatorMeshId) {
36449
+ let hasActiveDispatch = false;
36450
+ try {
36451
+ hasActiveDispatch = getActiveDirectDispatches(coordinatorMeshId).some((d) => d.sessionId === instanceId) || hasUnterminalDirectDispatchLedgerEntry(coordinatorMeshId, instanceId);
36452
+ } catch {
36453
+ }
36454
+ if (!hasActiveDispatch) return reject("coordinator_not_dispatch_target");
36455
+ meshIdFromDirectDispatch = coordinatorMeshId;
36456
+ }
36457
+ const meshIdFromRuntime = readNonEmptyString2(settings.meshNodeFor) || meshIdFromDirectDispatch;
36458
+ const hasWorkerEnvelope = Boolean(
36459
+ meshIdFromRuntime || settings.launchedByCoordinator || coordinatorDaemonId || readNonEmptyString2(settings.meshCoordinatorNodeId)
36460
+ );
36461
+ if (!hasWorkerEnvelope) return reject("no_worker_envelope");
36462
+ const mesh = meshIdFromRuntime ? deps.getMeshById(meshIdFromRuntime) : deps.getMeshByWorkspace(workspace);
36463
+ const meshId = meshIdFromRuntime || readNonEmptyString2(mesh?.id);
36464
+ if (!meshId) return reject("mesh_unresolved");
36465
+ const targetNode = mesh?.nodes?.find((n) => n.workspace === workspace);
36466
+ const runtimeNodeId = readNonEmptyString2(settings.meshNodeId);
36467
+ const nodeId = readNonEmptyString2(targetNode?.id) || runtimeNodeId;
36468
+ const nodeLabel = targetNode ? `Node '${targetNode.id}'` : runtimeNodeId ? `Node '${runtimeNodeId}'` : `Agent at ${workspace}`;
36469
+ return {
36470
+ isDelegate: true,
36471
+ meshId,
36472
+ nodeId,
36473
+ nodeLabel,
36474
+ coordinatorDaemonId,
36475
+ workspace,
36476
+ sessionId
36477
+ };
36478
+ }
36479
+ function isUnroutableDelegateRejection(routing) {
36480
+ return !routing.isDelegate && routing.rejectionReason === "mesh_unresolved";
36481
+ }
36482
+ function recordUnroutableDelegateEvent(routing, eventName) {
36483
+ if (!isUnroutableDelegateRejection(routing)) return false;
36484
+ const dedupKey = `${routing.sessionId}::${eventName}::${routing.workspace}`;
36485
+ const now = Date.now();
36486
+ const last = recentUnroutableDiagnostics.get(dedupKey);
36487
+ if (last !== void 0 && now - last < UNROUTABLE_DIAGNOSTIC_DEDUP_MS) return false;
36488
+ recentUnroutableDiagnostics.set(dedupKey, now);
36489
+ if (recentUnroutableDiagnostics.size > 256) {
36490
+ for (const [key, ts2] of recentUnroutableDiagnostics) {
36491
+ if (now - ts2 >= UNROUTABLE_DIAGNOSTIC_DEDUP_MS) recentUnroutableDiagnostics.delete(key);
36492
+ }
36493
+ }
36494
+ try {
36495
+ appendLedgerEntry(UNROUTABLE_DIAGNOSTIC_STREAM, {
36496
+ kind: "delivery_unroutable",
36497
+ sessionId: routing.sessionId || void 0,
36498
+ payload: {
36499
+ event: eventName,
36500
+ reason: routing.rejectionReason,
36501
+ workspace: routing.workspace || void 0,
36502
+ coordinatorDaemonId: routing.coordinatorDaemonId || void 0,
36503
+ detail: "Worker envelope was present but no mesh could be resolved; the event could not be routed to a coordinator."
36504
+ }
36505
+ });
36506
+ LOG2.warn("MeshEvents", `delivery_unroutable: ${eventName} from session ${routing.sessionId || "(unknown)"} at ${routing.workspace || "(no workspace)"} \u2014 envelope present but mesh unresolved`);
36507
+ return true;
36508
+ } catch (e) {
36509
+ LOG2.warn("MeshEvents", `Failed to record delivery_unroutable diagnostic: ${e?.message || e}`);
36510
+ return false;
36511
+ }
36512
+ }
36513
+ function getRecentUnroutableDeliveries(opts) {
36514
+ const sinceMs = opts?.sinceMs ?? 60 * 60 * 1e3;
36515
+ const limit = opts?.limit ?? 20;
36516
+ let entries;
36517
+ try {
36518
+ entries = readLedgerEntries(UNROUTABLE_DIAGNOSTIC_STREAM, { kind: ["delivery_unroutable"], tail: 200 });
36519
+ } catch {
36520
+ return [];
36521
+ }
36522
+ const cutoff = Date.now() - sinceMs;
36523
+ const out = [];
36524
+ for (let i = entries.length - 1; i >= 0; i--) {
36525
+ const entry = entries[i];
36526
+ const ts2 = new Date(entry.timestamp).getTime();
36527
+ if (!Number.isNaN(ts2) && ts2 < cutoff) continue;
36528
+ const payload = entry.payload && typeof entry.payload === "object" ? entry.payload : {};
36529
+ out.push({
36530
+ timestamp: entry.timestamp,
36531
+ event: readNonEmptyString2(payload.event),
36532
+ sessionId: readNonEmptyString2(entry.sessionId) || readNonEmptyString2(payload.sessionId) || void 0,
36533
+ workspace: readNonEmptyString2(payload.workspace) || void 0,
36534
+ coordinatorDaemonId: readNonEmptyString2(payload.coordinatorDaemonId) || void 0
36535
+ });
36536
+ if (out.length >= limit) break;
36537
+ }
36538
+ return out;
36539
+ }
36540
+ var UNROUTABLE_DIAGNOSTIC_STREAM;
36541
+ var UNROUTABLE_DIAGNOSTIC_DEDUP_MS;
36542
+ var recentUnroutableDiagnostics;
36543
+ var init_mesh_routing = __esm2({
36544
+ "src/mesh/mesh-routing.ts"() {
36545
+ "use strict";
36546
+ init_mesh_work_queue();
36547
+ init_mesh_events_stale();
36548
+ init_mesh_ledger();
36549
+ init_logger();
36550
+ init_mesh_events_utils();
36551
+ UNROUTABLE_DIAGNOSTIC_STREAM = "__unroutable__";
36552
+ UNROUTABLE_DIAGNOSTIC_DEDUP_MS = 60 * 1e3;
36553
+ recentUnroutableDiagnostics = /* @__PURE__ */ new Map();
36554
+ }
36555
+ });
36350
36556
  function getCachedMeshByWorkspace(workspace) {
36351
36557
  const now = Date.now();
36352
36558
  const cached2 = meshByWorkspaceCache.get(workspace);
@@ -36358,6 +36564,9 @@ Next step: ${nextStep}`;
36358
36564
  function __resetIdleAutoFastForwardForTests() {
36359
36565
  idleAutoFastForwardLastAttempt.clear();
36360
36566
  }
36567
+ function __resetMeshWorkspaceCacheForTests() {
36568
+ meshByWorkspaceCache.clear();
36569
+ }
36361
36570
  function sweepExpiredRemoteIdleSessions() {
36362
36571
  try {
36363
36572
  MeshRuntimeStore.getInstance().pruneExpiredRemoteIdleSessions();
@@ -37024,6 +37233,17 @@ Next step: ${nextStep}`;
37024
37233
  sourceSession?.getState()?.settings?.meshCoordinatorDaemonId
37025
37234
  );
37026
37235
  const localDaemonId = readNonEmptyString2(loadConfig2().machineId);
37236
+ if (components.onMeshCoordinatorEventForwarded) {
37237
+ try {
37238
+ components.onMeshCoordinatorEventForwarded({
37239
+ event: args.event,
37240
+ meshId: args.meshId,
37241
+ nodeId: eventNodeId || void 0,
37242
+ ...args.metadataEvent
37243
+ });
37244
+ } catch {
37245
+ }
37246
+ }
37027
37247
  const intentionalCleanupStop = shouldSuppressIntentionalCleanupStop({
37028
37248
  event: args.event,
37029
37249
  meshId: args.meshId,
@@ -37368,10 +37588,38 @@ Next step: ${nextStep}`;
37368
37588
  const instState = inst.getState();
37369
37589
  if (instState.settings?.meshCoordinatorFor !== args.meshId) return false;
37370
37590
  if (args.sourceInstanceId && instState.instanceId === args.sourceInstanceId) return false;
37371
- if (workerCoordinatorDaemonId && localDaemonId && workerCoordinatorDaemonId !== localDaemonId) return false;
37591
+ if (workerCoordinatorDaemonId && localDaemonId && !sameDaemonId(workerCoordinatorDaemonId, localDaemonId)) return false;
37372
37592
  return true;
37373
37593
  });
37374
37594
  if (coordinatorInstances.length === 0) {
37595
+ const remoteCoordinatorDaemonId = workerCoordinatorDaemonId && localDaemonId && !sameDaemonId(workerCoordinatorDaemonId, localDaemonId) ? workerCoordinatorDaemonId : "";
37596
+ if (remoteCoordinatorDaemonId && components.dispatchMeshCommand) {
37597
+ const forwardPayload = {
37598
+ event: args.event,
37599
+ meshId: args.meshId,
37600
+ nodeId: args.nodeId || void 0,
37601
+ workspace: readNonEmptyString2(args.metadataEvent.workspace),
37602
+ ...args.metadataEvent,
37603
+ ...recoveryContext ? { recoveryContext } : {}
37604
+ };
37605
+ components.dispatchMeshCommand(remoteCoordinatorDaemonId, "mesh_forward_event", forwardPayload).then(() => {
37606
+ LOG2.info("MeshEvents", `Forwarded ${args.event} for mesh ${args.meshId} to remote coordinator daemon ${remoteCoordinatorDaemonId.slice(0, 12)}\u2026`);
37607
+ }).catch((error48) => {
37608
+ LOG2.warn("MeshEvents", `Remote forward of ${args.event} failed (${error48?.message || error48}); queuing for backfill`);
37609
+ queuePendingMeshCoordinatorEvent({
37610
+ event: args.event,
37611
+ meshId: args.meshId,
37612
+ nodeLabel: args.nodeLabel,
37613
+ nodeId: args.nodeId || void 0,
37614
+ workspace: readNonEmptyString2(args.metadataEvent.workspace),
37615
+ metadataEvent: { ...args.metadataEvent, ...recoveryContext ? { recoveryContext } : {} },
37616
+ coordinatorMessage: messageText,
37617
+ queuedAt: Date.now(),
37618
+ targetCoordinatorDaemonId: remoteCoordinatorDaemonId
37619
+ });
37620
+ });
37621
+ return { success: true, forwarded: 0, remoteForwarded: true };
37622
+ }
37375
37623
  if (queuePendingMeshCoordinatorEvent({
37376
37624
  event: args.event,
37377
37625
  meshId: args.meshId,
@@ -37390,7 +37638,7 @@ Next step: ${nextStep}`;
37390
37638
  }
37391
37639
  return { success: true, forwarded: 0 };
37392
37640
  }
37393
- if (queuePendingMeshCoordinatorEvent({
37641
+ const pendingEvent = {
37394
37642
  event: args.event,
37395
37643
  meshId: args.meshId,
37396
37644
  nodeLabel: args.nodeLabel,
@@ -37403,9 +37651,13 @@ Next step: ${nextStep}`;
37403
37651
  coordinatorMessage: messageText,
37404
37652
  queuedAt: Date.now(),
37405
37653
  ...workerCoordinatorDaemonId ? { targetCoordinatorDaemonId: workerCoordinatorDaemonId } : {}
37406
- })) {
37654
+ };
37655
+ if (queuePendingMeshCoordinatorEvent(pendingEvent)) {
37407
37656
  LOG2.info("MeshEvents", `Queued ${args.event} for MCP coordinator (mesh ${args.meshId})`);
37408
37657
  }
37658
+ if (localDaemonId) {
37659
+ markMeshCoordinatorEventDirectDelivered(localDaemonId, pendingEvent);
37660
+ }
37409
37661
  const forceInject = shouldForceInjectMeshEvent(args.event);
37410
37662
  for (const coord of coordinatorInstances) {
37411
37663
  const coordState = coord.getState();
@@ -37473,15 +37725,15 @@ Next step: ${nextStep}`;
37473
37725
  if (flushSource && flushSource.category === "cli") {
37474
37726
  const flushState = flushSource.getState();
37475
37727
  const flushSettings = flushState.settings && typeof flushState.settings === "object" ? flushState.settings : {};
37476
- const coordinatorMeshId2 = readNonEmptyString2(flushSettings.meshCoordinatorFor);
37477
- if (coordinatorMeshId2) {
37728
+ const coordinatorMeshId = readNonEmptyString2(flushSettings.meshCoordinatorFor);
37729
+ if (coordinatorMeshId) {
37478
37730
  const status = readNonEmptyString2(flushState.status).toLowerCase();
37479
37731
  if (status === "idle") {
37480
37732
  try {
37481
37733
  const localDaemonId = readNonEmptyString2(loadConfig2().machineId) || void 0;
37482
- const pendingEvents = drainPendingMeshCoordinatorEvents(coordinatorMeshId2, localDaemonId);
37734
+ const pendingEvents = drainPendingMeshCoordinatorEvents(coordinatorMeshId, localDaemonId);
37483
37735
  if (pendingEvents.length > 0) {
37484
- LOG2.info("MeshEvents", `Auto-flushing ${pendingEvents.length} pending coordinator event(s) for mesh ${coordinatorMeshId2} on coordinator idle`);
37736
+ LOG2.info("MeshEvents", `Auto-flushing ${pendingEvents.length} pending coordinator event(s) for mesh ${coordinatorMeshId} on coordinator idle`);
37485
37737
  for (const pending of pendingEvents) {
37486
37738
  if (!pending.coordinatorMessage) continue;
37487
37739
  const forcePending = shouldForceInjectMeshEvent(pending.event);
@@ -37497,7 +37749,7 @@ Next step: ${nextStep}`;
37497
37749
  }
37498
37750
  let hasDirectDispatch = false;
37499
37751
  try {
37500
- hasDirectDispatch = getActiveDirectDispatches(coordinatorMeshId2).some((d) => d.sessionId === flushInstanceId) || hasUnterminalDirectDispatchLedgerEntry(coordinatorMeshId2, flushInstanceId);
37752
+ hasDirectDispatch = getActiveDirectDispatches(coordinatorMeshId).some((d) => d.sessionId === flushInstanceId) || hasUnterminalDirectDispatchLedgerEntry(coordinatorMeshId, flushInstanceId);
37501
37753
  } catch {
37502
37754
  }
37503
37755
  if (!hasDirectDispatch) return;
@@ -37508,37 +37760,19 @@ Next step: ${nextStep}`;
37508
37760
  if (!isMeshCoordinatorEvent(event.event)) return;
37509
37761
  const instanceId = readNonEmptyString2(event.instanceId);
37510
37762
  if (!instanceId) return;
37511
- const sourceInstance = components.instanceManager.getInstance(instanceId);
37512
- if (!sourceInstance || sourceInstance.category !== "cli") return;
37513
- const state = sourceInstance.getState();
37514
- const workspace = readNonEmptyString2(state.workspace);
37515
- if (!workspace) return;
37516
- const settings = state.settings && typeof state.settings === "object" ? state.settings : {};
37517
- const coordinatorMeshId = readNonEmptyString2(settings.meshCoordinatorFor);
37518
- let meshIdFromDirectDispatch = "";
37519
- if (coordinatorMeshId) {
37520
- try {
37521
- const hasActiveDispatch = getActiveDirectDispatches(coordinatorMeshId).some((d) => d.sessionId === instanceId) || hasUnterminalDirectDispatchLedgerEntry(coordinatorMeshId, instanceId);
37522
- if (hasActiveDispatch) meshIdFromDirectDispatch = coordinatorMeshId;
37523
- } catch {
37524
- }
37525
- if (!meshIdFromDirectDispatch) return;
37526
- }
37527
- const meshIdFromRuntime = readNonEmptyString2(settings.meshNodeFor) || meshIdFromDirectDispatch;
37528
- const isMeshDelegate = Boolean(meshIdFromRuntime || settings.launchedByCoordinator);
37529
- if (!isMeshDelegate) return;
37530
- const mesh = meshIdFromRuntime ? getMeshWithCache(components, meshIdFromRuntime) : getCachedMeshByWorkspace(workspace);
37531
- const meshId = meshIdFromRuntime || readNonEmptyString2(mesh?.id);
37532
- if (!meshId) return;
37533
- const targetNode = mesh?.nodes?.find((n) => n.workspace === workspace);
37534
- const runtimeNodeId = readNonEmptyString2(settings.meshNodeId);
37535
- const resolvedNodeId = targetNode?.id || runtimeNodeId;
37536
- const nodeLabel = targetNode ? `Node '${targetNode.id}'` : runtimeNodeId ? `Node '${runtimeNodeId}'` : `Agent at ${workspace}`;
37763
+ const routing = resolveWorkerDelegateRouting(components, instanceId, {
37764
+ getMeshById: (meshId) => getMeshWithCache(components, meshId),
37765
+ getMeshByWorkspace: (workspace) => getCachedMeshByWorkspace(workspace)
37766
+ });
37767
+ if (!routing.isDelegate) {
37768
+ recordUnroutableDelegateEvent(routing, event.event);
37769
+ return;
37770
+ }
37537
37771
  injectMeshSystemMessage(components, {
37538
- meshId,
37772
+ meshId: routing.meshId,
37539
37773
  sourceInstanceId: instanceId,
37540
- nodeId: resolvedNodeId,
37541
- nodeLabel,
37774
+ nodeId: routing.nodeId,
37775
+ nodeLabel: routing.nodeLabel,
37542
37776
  event: event.event,
37543
37777
  metadataEvent: event
37544
37778
  });
@@ -37572,6 +37806,7 @@ Next step: ${nextStep}`;
37572
37806
  init_mesh_delivery_policy();
37573
37807
  init_mesh_runtime_store();
37574
37808
  init_mesh_events_pending();
37809
+ init_mesh_routing();
37575
37810
  init_mesh_events_stale();
37576
37811
  init_mesh_events_utils();
37577
37812
  REMOTE_IDLE_SESSION_TTL_MS = 5 * 60 * 1e3;
@@ -37617,11 +37852,13 @@ Next step: ${nextStep}`;
37617
37852
  var mesh_events_exports = {};
37618
37853
  __export2(mesh_events_exports, {
37619
37854
  __resetIdleAutoFastForwardForTests: () => __resetIdleAutoFastForwardForTests,
37855
+ __resetMeshWorkspaceCacheForTests: () => __resetMeshWorkspaceCacheForTests,
37620
37856
  clearPendingMeshCoordinatorEvents: () => clearPendingMeshCoordinatorEvents,
37621
37857
  drainPendingMeshCoordinatorEvents: () => drainPendingMeshCoordinatorEvents,
37622
37858
  getPendingMeshCoordinatorEvents: () => getPendingMeshCoordinatorEvents,
37623
37859
  handleMeshForwardEvent: () => handleMeshForwardEvent,
37624
37860
  isMeshCoordinatorEvent: () => isMeshCoordinatorEvent,
37861
+ markMeshCoordinatorEventDirectDelivered: () => markMeshCoordinatorEventDirectDelivered,
37625
37862
  queuePendingMeshCoordinatorEvent: () => queuePendingMeshCoordinatorEvent,
37626
37863
  reconcileDirectDispatchCompletionFromTranscript: () => reconcileDirectDispatchCompletionFromTranscript,
37627
37864
  setupMeshEventForwarding: () => setupMeshEventForwarding,
@@ -67916,6 +68153,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
67916
68153
  init_logger();
67917
68154
  init_mesh_coordinator();
67918
68155
  init_mesh_events();
68156
+ init_mesh_routing();
67919
68157
  init_mesh_host_ownership();
67920
68158
  init_mesh_fast_forward();
67921
68159
  var import_node_child_process4 = require("child_process");
@@ -74672,6 +74910,7 @@ ${ptyResult.output.slice(-2e3)}`);
74672
74910
  }
74673
74911
  const callerCoordinatorDaemonId = typeof args?.coordinatorDaemonId === "string" && args.coordinatorDaemonId.trim() ? args.coordinatorDaemonId.trim() : this.deps.statusInstanceId || void 0;
74674
74912
  const pendingCoordinatorEvents = getPendingMeshCoordinatorEvents(meshId, callerCoordinatorDaemonId);
74913
+ const unroutableDeliveries = getRecentUnroutableDeliveries();
74675
74914
  const previewFreshness = (() => {
74676
74915
  const localRepoRoot = nodeStatuses.map((node) => readStringValue(node?.git?.repoRoot, node?.repoRoot, node?.workspace)).find((candidate) => !!candidate && fs23.existsSync(candidate));
74677
74916
  return localRepoRoot ? buildPreviewFreshness(localRepoRoot) : void 0;
@@ -74727,6 +74966,7 @@ ${ptyResult.output.slice(-2e3)}`);
74727
74966
  ...asyncRefineJobs.length > 0 ? { asyncRefineJobs } : {},
74728
74967
  ...historicalSessions ? { historicalSessions } : {},
74729
74968
  ...pendingCoordinatorEvents.length > 0 ? { pendingCoordinatorEvents } : {},
74969
+ ...unroutableDeliveries.length > 0 ? { unroutableDeliveries } : {},
74730
74970
  activeRefineJobs: Array.from(this.runningRefineJobs.values()).filter((job) => job.meshId === meshId).map((job) => ({
74731
74971
  jobId: job.jobId,
74732
74972
  nodeId: job.targetNodeId,
@@ -74736,9 +74976,13 @@ ${ptyResult.output.slice(-2e3)}`);
74736
74976
  targetCoordinatorDaemonId: job.targetCoordinatorDaemonId
74737
74977
  }))
74738
74978
  };
74739
- const { pendingCoordinatorEvents: _pendingCoordinatorEvents, ...cacheableStatusResult } = statusResult;
74979
+ const { pendingCoordinatorEvents: _pendingCoordinatorEvents, unroutableDeliveries: _unroutableDeliveries, ...cacheableStatusResult } = statusResult;
74740
74980
  const rememberedStatus = this.rememberAggregateMeshStatus(meshId, cacheableStatusResult, refreshReason);
74741
- const returnedStatus = pendingCoordinatorEvents.length > 0 ? { ...rememberedStatus, pendingCoordinatorEvents } : rememberedStatus;
74981
+ const returnedStatus = {
74982
+ ...rememberedStatus,
74983
+ ...pendingCoordinatorEvents.length > 0 ? { pendingCoordinatorEvents } : {},
74984
+ ...unroutableDeliveries.length > 0 ? { unroutableDeliveries } : {}
74985
+ };
74742
74986
  logRepoMeshStatusDebug("return_live", {
74743
74987
  meshId,
74744
74988
  command: "mesh_status",
@@ -83000,7 +83244,8 @@ data: ${JSON.stringify(msg.data)}
83000
83244
  sessionRegistry,
83001
83245
  detectedIdes: detectedIdesRef,
83002
83246
  refreshProviderAvailability,
83003
- dispatchMeshCommand: config2.dispatchMeshCommand
83247
+ dispatchMeshCommand: config2.dispatchMeshCommand,
83248
+ onMeshCoordinatorEventForwarded: config2.onMeshCoordinatorEventForwarded
83004
83249
  };
83005
83250
  setupMeshEventForwarding(components);
83006
83251
  setImmediate(() => void router.resumePendingRefineJobsOnStartup());