@adhdev/daemon-standalone 0.9.82-rc.273 → 0.9.82-rc.275

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
@@ -29983,10 +29983,10 @@ var require_dist3 = __commonJS({
29983
29983
  }
29984
29984
  function getDaemonBuildInfo() {
29985
29985
  if (cached2) return cached2;
29986
- const commit = readInjected(true ? "e4a64afbd050fa5167c383b1fc6f9df5f8e48ba2" : void 0) ?? "unknown";
29987
- const commitShort = readInjected(true ? "e4a64afb" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
29988
- const version2 = readInjected(true ? "0.9.82-rc.273" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
29989
- const builtAt = readInjected(true ? "2026-06-15T05:37:35.385Z" : void 0);
29986
+ const commit = readInjected(true ? "080b607ef221e44126942d9d52eaf547b4e92550" : void 0) ?? "unknown";
29987
+ const commitShort = readInjected(true ? "080b607e" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
29988
+ const version2 = readInjected(true ? "0.9.82-rc.275" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
29989
+ const builtAt = readInjected(true ? "2026-06-15T08:25:07.224Z" : void 0);
29990
29990
  cached2 = builtAt ? { commit, commitShort, version: version2, builtAt } : { commit, commitShort, version: version2 };
29991
29991
  return cached2;
29992
29992
  }
@@ -34007,12 +34007,33 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
34007
34007
  this.maybeCheckpointWal();
34008
34008
  return result.changes > 0;
34009
34009
  }
34010
- drainPendingEvents(meshId, coordinatorDaemonId) {
34010
+ /**
34011
+ * Drain undrained pending events for a mesh, atomically marking them drained.
34012
+ * When `opts.onlyEvents` is supplied, ONLY rows whose `event` is in that set are
34013
+ * drained — the rest stay queued (drained=0) for a later drain. This is how the
34014
+ * reconcile loop force-drains terminal/force-inject events into a *generating*
34015
+ * coordinator while leaving non-force progress events for the coordinator's next
34016
+ * idle transition. Filtering happens inside the same transaction as the
34017
+ * drained=1 marking, so force-drain + a concurrent full drain can never both
34018
+ * consume the same row.
34019
+ */
34020
+ drainPendingEvents(meshId, coordinatorDaemonId, opts) {
34011
34021
  return this.transaction(() => {
34012
- const whereClause = coordinatorDaemonId ? `WHERE mesh_id = ? AND drained = 0 AND (coordinator_daemon_id IS NULL OR coordinator_daemon_id = ?)` : `WHERE mesh_id = ? AND drained = 0`;
34013
- const params = coordinatorDaemonId ? [meshId, coordinatorDaemonId] : [meshId];
34022
+ const onlyEvents = opts?.onlyEvents;
34023
+ if (onlyEvents && onlyEvents.size === 0) return [];
34024
+ const eventList = onlyEvents ? [...onlyEvents] : [];
34025
+ const clauses = ["mesh_id = ?", "drained = 0"];
34026
+ const params = [meshId];
34027
+ if (coordinatorDaemonId) {
34028
+ clauses.push("(coordinator_daemon_id IS NULL OR coordinator_daemon_id = ?)");
34029
+ params.push(coordinatorDaemonId);
34030
+ }
34031
+ if (eventList.length > 0) {
34032
+ clauses.push(`event IN (${eventList.map(() => "?").join(",")})`);
34033
+ params.push(...eventList);
34034
+ }
34014
34035
  const rows = this.db.prepare(
34015
- `SELECT id, event, payload FROM mesh_pending_events ${whereClause} ORDER BY queued_at ASC LIMIT 100`
34036
+ `SELECT id, event, payload FROM mesh_pending_events WHERE ${clauses.join(" AND ")} ORDER BY queued_at ASC LIMIT 100`
34016
34037
  ).all(...params);
34017
34038
  if (rows.length === 0) return [];
34018
34039
  const ids = rows.map((r) => r.id);
@@ -35927,16 +35948,6 @@ ${rendered}`, "utf-8");
35927
35948
  function readRecord3(value) {
35928
35949
  return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
35929
35950
  }
35930
- function canonicalDaemonId(value) {
35931
- const id = readNonEmptyString2(value);
35932
- if (!id) return "";
35933
- return id.replace(/^(?:daemon|standalone)_/, "");
35934
- }
35935
- function sameDaemonId(a, b) {
35936
- const ca = canonicalDaemonId(a);
35937
- const cb = canonicalDaemonId(b);
35938
- return ca !== "" && ca === cb;
35939
- }
35940
35951
  function buildMeshWorkerRelayStamp(currentSettings, meshContext) {
35941
35952
  if (!meshContext) return void 0;
35942
35953
  const settings = currentSettings && typeof currentSettings === "object" ? currentSettings : {};
@@ -36135,29 +36146,6 @@ Next step: ${nextStep}`;
36135
36146
  timestamp || ""
36136
36147
  ].join("::");
36137
36148
  }
36138
- function markMeshCoordinatorEventDirectDelivered(coordinatorDaemonId, event) {
36139
- const canonical = canonicalDaemonId(coordinatorDaemonId);
36140
- if (!canonical) return;
36141
- const fingerprint = buildPendingEventFingerprint(event);
36142
- if (!fingerprint.trim()) return;
36143
- try {
36144
- const store = MeshRuntimeStore.getInstance();
36145
- store.recordDirectDelivered(canonical, fingerprint, DIRECT_DELIVERED_TTL_MS);
36146
- store.sweepExpiredDirectDelivered();
36147
- } catch {
36148
- }
36149
- }
36150
- function wasDirectDeliveredToCoordinator(coordinatorDaemonId, event) {
36151
- const canonical = canonicalDaemonId(coordinatorDaemonId);
36152
- if (!canonical) return false;
36153
- const fingerprint = buildPendingEventFingerprint(event);
36154
- if (!fingerprint.trim()) return false;
36155
- try {
36156
- return MeshRuntimeStore.getInstance().wasDirectDelivered(canonical, fingerprint);
36157
- } catch {
36158
- return false;
36159
- }
36160
- }
36161
36149
  function hasPendingCoordinatorEventDuplicate(event) {
36162
36150
  const fingerprint = buildPendingEventFingerprint(event);
36163
36151
  if (!fingerprint.trim()) return false;
@@ -36319,8 +36307,57 @@ Next step: ${nextStep}`;
36319
36307
  return null;
36320
36308
  }
36321
36309
  }
36322
- function drainPendingMeshCoordinatorEvents(meshId, coordinatorDaemonId) {
36310
+ function selectiveDrainFile(path39, predicate) {
36311
+ const tmpPath = `${path39}.draining`;
36312
+ try {
36313
+ (0, import_fs8.renameSync)(path39, tmpPath);
36314
+ } catch {
36315
+ return [];
36316
+ }
36317
+ let content;
36318
+ try {
36319
+ content = (0, import_fs8.readFileSync)(tmpPath, "utf-8");
36320
+ } catch {
36321
+ try {
36322
+ (0, import_fs8.unlinkSync)(tmpPath);
36323
+ } catch {
36324
+ }
36325
+ return [];
36326
+ }
36327
+ const consumed = [];
36328
+ const keptLines = [];
36329
+ for (const line of content.split("\n")) {
36330
+ if (!line) continue;
36331
+ let parsed;
36332
+ try {
36333
+ parsed = JSON.parse(line);
36334
+ } catch {
36335
+ parsed = void 0;
36336
+ }
36337
+ if (parsed && predicate(parsed)) {
36338
+ consumed.push(parsed);
36339
+ } else {
36340
+ keptLines.push(line);
36341
+ }
36342
+ }
36343
+ try {
36344
+ if (keptLines.length > 0) {
36345
+ (0, import_fs8.writeFileSync)(path39, keptLines.join("\n") + "\n", "utf-8");
36346
+ }
36347
+ (0, import_fs8.unlinkSync)(tmpPath);
36348
+ } catch {
36349
+ try {
36350
+ if ((0, import_fs8.existsSync)(tmpPath) && !(0, import_fs8.existsSync)(path39)) (0, import_fs8.renameSync)(tmpPath, path39);
36351
+ } catch {
36352
+ }
36353
+ return [];
36354
+ }
36355
+ return consumed;
36356
+ }
36357
+ function drainPendingMeshCoordinatorEvents(meshId, coordinatorDaemonId, opts) {
36323
36358
  if (!meshId) return [];
36359
+ const onlyEvents = opts?.onlyEvents;
36360
+ const matchesFilter = (eventName) => !onlyEvents || onlyEvents.has(eventName);
36324
36361
  const merged = [];
36325
36362
  const seenFingerprints = /* @__PURE__ */ new Set();
36326
36363
  const pushUnique = (event) => {
@@ -36334,7 +36371,7 @@ Next step: ${nextStep}`;
36334
36371
  try {
36335
36372
  const store = MeshRuntimeStore.getInstance();
36336
36373
  if (store.pendingEventCount(meshId) > 0) {
36337
- for (const row of store.drainPendingEvents(meshId, coordinatorDaemonId)) {
36374
+ for (const row of store.drainPendingEvents(meshId, coordinatorDaemonId, onlyEvents ? { onlyEvents } : void 0)) {
36338
36375
  const event = row.payload;
36339
36376
  if (event) pushUnique(event);
36340
36377
  }
@@ -36343,6 +36380,14 @@ Next step: ${nextStep}`;
36343
36380
  }
36344
36381
  const paths = coordinatorDaemonId ? [getPendingEventsPath(meshId, coordinatorDaemonId), getPendingEventsPath(meshId)] : [getPendingEventsPath(meshId)];
36345
36382
  for (const path39 of paths) {
36383
+ const isSharedFile = coordinatorDaemonId && path39 === getPendingEventsPath(meshId);
36384
+ const targets = (e) => !isSharedFile || !e.targetCoordinatorDaemonId || e.targetCoordinatorDaemonId === coordinatorDaemonId;
36385
+ if (onlyEvents) {
36386
+ for (const event of selectiveDrainFile(path39, (e) => targets(e) && matchesFilter(e.event))) {
36387
+ pushUnique(event);
36388
+ }
36389
+ continue;
36390
+ }
36346
36391
  const content = atomicDrainFile(path39);
36347
36392
  if (!content) continue;
36348
36393
  const parsed = content.split("\n").filter(Boolean).flatMap((line) => {
@@ -36352,13 +36397,11 @@ Next step: ${nextStep}`;
36352
36397
  return [];
36353
36398
  }
36354
36399
  });
36355
- const filtered = coordinatorDaemonId && path39 === getPendingEventsPath(meshId) ? parsed.filter((e) => !e.targetCoordinatorDaemonId || e.targetCoordinatorDaemonId === coordinatorDaemonId) : parsed;
36400
+ const filtered = isSharedFile ? parsed.filter(targets) : parsed;
36356
36401
  for (const event of filtered) pushUnique(event);
36357
36402
  }
36358
36403
  if (merged.length === 0) return [];
36359
- const deliverable = coordinatorDaemonId ? merged.filter((event) => !wasDirectDeliveredToCoordinator(coordinatorDaemonId, event)) : merged;
36360
- if (deliverable.length === 0) return [];
36361
- return reconcilePendingMeshCoordinatorEvents(meshId, deliverable);
36404
+ return reconcilePendingMeshCoordinatorEvents(meshId, merged);
36362
36405
  }
36363
36406
  function getPendingMeshCoordinatorEvents(meshId, coordinatorDaemonId) {
36364
36407
  if (!meshId) return [];
@@ -36385,8 +36428,7 @@ Next step: ${nextStep}`;
36385
36428
  for (const event of readPendingMeshCoordinatorEventsFromDisk(meshId, coordinatorDaemonId)) {
36386
36429
  pushUnique(event);
36387
36430
  }
36388
- const deliverable = coordinatorDaemonId ? merged.filter((event) => !wasDirectDeliveredToCoordinator(coordinatorDaemonId, event)) : merged;
36389
- return reconcilePendingMeshCoordinatorEvents(meshId, deliverable);
36431
+ return reconcilePendingMeshCoordinatorEvents(meshId, merged);
36390
36432
  }
36391
36433
  function clearPendingMeshCoordinatorEvents(meshId, coordinatorDaemonId) {
36392
36434
  if (!meshId) return;
@@ -36406,7 +36448,6 @@ Next step: ${nextStep}`;
36406
36448
  var import_path8;
36407
36449
  var import_crypto7;
36408
36450
  var REFINE_TERMINAL_EVENTS;
36409
- var DIRECT_DELIVERED_TTL_MS;
36410
36451
  var MAX_PENDING_EVENTS_BYTES;
36411
36452
  var MAX_PENDING_EVENTS_KEEP;
36412
36453
  var init_mesh_events_pending = __esm2({
@@ -36420,7 +36461,6 @@ Next step: ${nextStep}`;
36420
36461
  init_mesh_runtime_store();
36421
36462
  init_mesh_events_utils();
36422
36463
  REFINE_TERMINAL_EVENTS = /* @__PURE__ */ new Set(["refine:completed", "refine:failed"]);
36423
- DIRECT_DELIVERED_TTL_MS = 10 * 60 * 1e3;
36424
36464
  MAX_PENDING_EVENTS_BYTES = 100 * 1024;
36425
36465
  MAX_PENDING_EVENTS_KEEP = 50;
36426
36466
  }
@@ -37780,7 +37820,6 @@ Next step: ${nextStep}`;
37780
37820
  const workerCoordinatorDaemonId = readNonEmptyString2(
37781
37821
  sourceSession?.getState()?.settings?.meshCoordinatorDaemonId
37782
37822
  );
37783
- const localDaemonId = readNonEmptyString2(loadConfig2().machineId);
37784
37823
  if (components.onMeshCoordinatorEventForwarded) {
37785
37824
  try {
37786
37825
  components.onMeshCoordinatorEventForwarded({
@@ -38135,60 +38174,6 @@ Next step: ${nextStep}`;
38135
38174
  recoveryContext
38136
38175
  });
38137
38176
  if (!messageText) return { success: false, error: "unsupported mesh event" };
38138
- const coordinatorInstances = components.instanceManager.getByCategory("cli").filter((inst) => {
38139
- const instState = inst.getState();
38140
- if (instState.settings?.meshCoordinatorFor !== args.meshId) return false;
38141
- if (args.sourceInstanceId && instState.instanceId === args.sourceInstanceId) return false;
38142
- if (workerCoordinatorDaemonId && localDaemonId && !sameDaemonId(workerCoordinatorDaemonId, localDaemonId)) return false;
38143
- return true;
38144
- });
38145
- if (coordinatorInstances.length === 0) {
38146
- const remoteCoordinatorDaemonId = workerCoordinatorDaemonId && localDaemonId && !sameDaemonId(workerCoordinatorDaemonId, localDaemonId) ? workerCoordinatorDaemonId : "";
38147
- if (remoteCoordinatorDaemonId && components.dispatchMeshCommand) {
38148
- const forwardPayload = {
38149
- event: args.event,
38150
- meshId: args.meshId,
38151
- nodeId: args.nodeId || void 0,
38152
- workspace: readNonEmptyString2(args.metadataEvent.workspace),
38153
- ...args.metadataEvent,
38154
- ...recoveryContext ? { recoveryContext } : {}
38155
- };
38156
- components.dispatchMeshCommand(remoteCoordinatorDaemonId, "mesh_forward_event", forwardPayload).then(() => {
38157
- LOG2.info("MeshEvents", `Forwarded ${args.event} for mesh ${args.meshId} to remote coordinator daemon ${remoteCoordinatorDaemonId.slice(0, 12)}\u2026`);
38158
- }).catch((error48) => {
38159
- LOG2.warn("MeshEvents", `Remote forward of ${args.event} failed (${error48?.message || error48}); queuing for backfill`);
38160
- queuePendingMeshCoordinatorEvent({
38161
- event: args.event,
38162
- meshId: args.meshId,
38163
- nodeLabel: args.nodeLabel,
38164
- nodeId: args.nodeId || void 0,
38165
- workspace: readNonEmptyString2(args.metadataEvent.workspace),
38166
- metadataEvent: { ...args.metadataEvent, ...recoveryContext ? { recoveryContext } : {} },
38167
- coordinatorMessage: messageText,
38168
- queuedAt: Date.now(),
38169
- targetCoordinatorDaemonId: remoteCoordinatorDaemonId
38170
- });
38171
- });
38172
- return { success: true, forwarded: 0, remoteForwarded: true };
38173
- }
38174
- if (queuePendingMeshCoordinatorEvent({
38175
- event: args.event,
38176
- meshId: args.meshId,
38177
- nodeLabel: args.nodeLabel,
38178
- nodeId: args.nodeId || void 0,
38179
- workspace: readNonEmptyString2(args.metadataEvent.workspace),
38180
- metadataEvent: {
38181
- ...args.metadataEvent,
38182
- ...recoveryContext ? { recoveryContext } : {}
38183
- },
38184
- coordinatorMessage: messageText,
38185
- queuedAt: Date.now(),
38186
- ...workerCoordinatorDaemonId ? { targetCoordinatorDaemonId: workerCoordinatorDaemonId } : {}
38187
- })) {
38188
- LOG2.info("MeshEvents", `Queued ${args.event} for MCP coordinator (mesh ${args.meshId}${workerCoordinatorDaemonId ? `, coordinator daemon ${workerCoordinatorDaemonId}` : ""})`);
38189
- }
38190
- return { success: true, forwarded: 0 };
38191
- }
38192
38177
  const pendingEvent = {
38193
38178
  event: args.event,
38194
38179
  meshId: args.meshId,
@@ -38204,21 +38189,9 @@ Next step: ${nextStep}`;
38204
38189
  ...workerCoordinatorDaemonId ? { targetCoordinatorDaemonId: workerCoordinatorDaemonId } : {}
38205
38190
  };
38206
38191
  if (queuePendingMeshCoordinatorEvent(pendingEvent)) {
38207
- LOG2.info("MeshEvents", `Queued ${args.event} for MCP coordinator (mesh ${args.meshId})`);
38208
- }
38209
- if (localDaemonId) {
38210
- markMeshCoordinatorEventDirectDelivered(localDaemonId, pendingEvent);
38211
- }
38212
- const forceInject = shouldForceInjectMeshEvent(args.event);
38213
- for (const coord of coordinatorInstances) {
38214
- const coordState = coord.getState();
38215
- LOG2.info("MeshEvents", `Forwarding mesh event to coordinator ${coordState.instanceId}${forceInject ? " (force)" : ""}`);
38216
- coord.onEvent("send_message", {
38217
- input: { text: messageText, textFallback: messageText },
38218
- ...forceInject ? { force: true } : {}
38219
- });
38192
+ LOG2.info("MeshEvents", `Queued ${args.event} for coordinator (mesh ${args.meshId}${workerCoordinatorDaemonId ? `, coordinator daemon ${workerCoordinatorDaemonId}` : ""})`);
38220
38193
  }
38221
- return { success: true, forwarded: coordinatorInstances.length };
38194
+ return { success: true, forwarded: 0 };
38222
38195
  }
38223
38196
  function handleMeshForwardEvent(components, payload) {
38224
38197
  const eventName = readNonEmptyString2(payload.event);
@@ -38401,6 +38374,174 @@ Next step: ${nextStep}`;
38401
38374
  ]);
38402
38375
  }
38403
38376
  });
38377
+ function resolveReconcileIntervalMs() {
38378
+ const raw = readNonEmptyString2(process.env.MESH_RECONCILE_INTERVAL_MS);
38379
+ if (raw) {
38380
+ const parsed = Number.parseInt(raw, 10);
38381
+ if (Number.isFinite(parsed) && parsed >= 1e3 && parsed <= 6e4) return parsed;
38382
+ }
38383
+ return DEFAULT_RECONCILE_INTERVAL_MS;
38384
+ }
38385
+ function findLiveCoordinators(components) {
38386
+ const out = [];
38387
+ for (const inst of components.instanceManager.getByCategory("cli")) {
38388
+ const state = inst.getState();
38389
+ const settings = state.settings && typeof state.settings === "object" ? state.settings : {};
38390
+ const meshId = readNonEmptyString2(settings.meshCoordinatorFor);
38391
+ if (!meshId) continue;
38392
+ const status = readNonEmptyString2(state.status).toLowerCase();
38393
+ out.push({ meshId, instance: inst, idle: status === "idle" });
38394
+ }
38395
+ return out;
38396
+ }
38397
+ function injectPendingIntoCoordinator(coordinator, pending) {
38398
+ if (!coordinator || !pending.coordinatorMessage) return;
38399
+ const force = shouldForceInjectMeshEvent(pending.event);
38400
+ coordinator.onEvent("send_message", {
38401
+ input: { text: pending.coordinatorMessage, textFallback: pending.coordinatorMessage },
38402
+ ...force ? { force: true } : {}
38403
+ });
38404
+ }
38405
+ async function runMeshReconcileTick(components) {
38406
+ const coordinators = findLiveCoordinators(components);
38407
+ if (coordinators.length === 0) {
38408
+ return;
38409
+ }
38410
+ const byMesh = /* @__PURE__ */ new Map();
38411
+ for (const c of coordinators) {
38412
+ const list = byMesh.get(c.meshId);
38413
+ if (list) list.push(c);
38414
+ else byMesh.set(c.meshId, [c]);
38415
+ }
38416
+ const localDaemonId = readNonEmptyString2(loadConfig2().machineId) || void 0;
38417
+ const dispatchMeshCommand = components.dispatchMeshCommand;
38418
+ const store = (() => {
38419
+ try {
38420
+ return MeshRuntimeStore.getInstance();
38421
+ } catch {
38422
+ return void 0;
38423
+ }
38424
+ })();
38425
+ for (const [meshId, meshCoordinators] of byMesh) {
38426
+ if (dispatchMeshCommand) {
38427
+ try {
38428
+ await pullRemoteNodeQueues(components, meshId, localDaemonId);
38429
+ } catch (e) {
38430
+ LOG2.warn("MeshReconcile", `Remote node pull failed for mesh ${meshId}: ${e?.message || e}`);
38431
+ }
38432
+ }
38433
+ const idleCoordinators = meshCoordinators.filter((c) => c.idle);
38434
+ const generatingCoordinators = meshCoordinators.filter((c) => !c.idle);
38435
+ const targetCoordinators = idleCoordinators.length > 0 ? idleCoordinators : generatingCoordinators;
38436
+ const forceOnly = idleCoordinators.length === 0;
38437
+ if (store) {
38438
+ try {
38439
+ if (store.pendingEventCount(meshId) === 0) continue;
38440
+ } catch {
38441
+ }
38442
+ }
38443
+ let pendingEvents = [];
38444
+ try {
38445
+ pendingEvents = drainPendingMeshCoordinatorEvents(
38446
+ meshId,
38447
+ localDaemonId,
38448
+ forceOnly ? { onlyEvents: MESH_FORCE_INJECT_EVENTS } : void 0
38449
+ );
38450
+ } catch (e) {
38451
+ LOG2.warn("MeshReconcile", `Drain failed for mesh ${meshId}: ${e?.message || e}`);
38452
+ continue;
38453
+ }
38454
+ if (pendingEvents.length === 0) continue;
38455
+ const mode = forceOnly ? "force-drain \u2192 generating" : "inject \u2192 idle";
38456
+ LOG2.info("MeshReconcile", `Reconcile ${mode}: ${pendingEvents.length} pending event(s) \u2192 ${targetCoordinators.length} coordinator(s) for mesh ${meshId}`);
38457
+ for (const pending of pendingEvents) {
38458
+ for (const c of targetCoordinators) {
38459
+ injectPendingIntoCoordinator(c.instance, pending);
38460
+ }
38461
+ }
38462
+ }
38463
+ }
38464
+ async function pullRemoteNodeQueues(components, meshId, localDaemonId) {
38465
+ const dispatchMeshCommand = components.dispatchMeshCommand;
38466
+ if (!dispatchMeshCommand) return;
38467
+ const mesh = listMeshes().find((m) => m.id === meshId);
38468
+ if (!mesh) return;
38469
+ const pendingEventArgs = {
38470
+ meshId,
38471
+ ...localDaemonId ? { coordinatorDaemonId: localDaemonId } : {}
38472
+ };
38473
+ for (const node of mesh.nodes) {
38474
+ const nodeDaemonId = readNonEmptyString2(node.daemonId);
38475
+ if (!nodeDaemonId) continue;
38476
+ if (localDaemonId && nodeDaemonId === localDaemonId) continue;
38477
+ let events;
38478
+ try {
38479
+ events = await dispatchMeshCommand(nodeDaemonId, "get_pending_mesh_events", pendingEventArgs);
38480
+ } catch {
38481
+ continue;
38482
+ }
38483
+ const list = extractPendingEvents(events).filter((e) => readNonEmptyString2(e?.meshId) === meshId);
38484
+ for (const event of list) {
38485
+ const payload = buildForwardPayloadFromPending(event);
38486
+ if (!payload.event || !payload.meshId) continue;
38487
+ try {
38488
+ handleMeshForwardEvent(components, payload);
38489
+ } catch {
38490
+ }
38491
+ }
38492
+ }
38493
+ }
38494
+ function extractPendingEvents(raw) {
38495
+ if (Array.isArray(raw)) return raw;
38496
+ if (raw && typeof raw === "object") {
38497
+ const events = raw.events;
38498
+ if (Array.isArray(events)) return events;
38499
+ }
38500
+ return [];
38501
+ }
38502
+ function buildForwardPayloadFromPending(event) {
38503
+ const metadata = event?.metadataEvent && typeof event.metadataEvent === "object" ? event.metadataEvent : {};
38504
+ return {
38505
+ event: readNonEmptyString2(event?.event),
38506
+ meshId: readNonEmptyString2(event?.meshId),
38507
+ nodeId: readNonEmptyString2(event?.nodeId) || readNonEmptyString2(metadata.meshNodeId),
38508
+ workspace: readNonEmptyString2(event?.workspace) || readNonEmptyString2(metadata.workspace),
38509
+ ...metadata
38510
+ };
38511
+ }
38512
+ function setupMeshReconcileLoop(components) {
38513
+ const intervalMs = resolveReconcileIntervalMs();
38514
+ let running = false;
38515
+ const timer = setInterval(() => {
38516
+ if (running) return;
38517
+ running = true;
38518
+ void runMeshReconcileTick(components).catch((e) => LOG2.warn("MeshReconcile", `Reconcile tick error: ${e?.message || e}`)).finally(() => {
38519
+ running = false;
38520
+ });
38521
+ }, intervalMs);
38522
+ if (typeof timer.unref === "function") timer.unref();
38523
+ LOG2.info("MeshReconcile", `Mesh reconcile loop started (interval ${intervalMs}ms)`);
38524
+ return {
38525
+ stop() {
38526
+ clearInterval(timer);
38527
+ LOG2.info("MeshReconcile", "Mesh reconcile loop stopped");
38528
+ }
38529
+ };
38530
+ }
38531
+ var DEFAULT_RECONCILE_INTERVAL_MS;
38532
+ var init_mesh_reconcile_loop = __esm2({
38533
+ "src/mesh/mesh-reconcile-loop.ts"() {
38534
+ "use strict";
38535
+ init_config();
38536
+ init_mesh_config();
38537
+ init_logger();
38538
+ init_mesh_events_pending();
38539
+ init_mesh_runtime_store();
38540
+ init_mesh_events_coordinator();
38541
+ init_mesh_events_utils();
38542
+ DEFAULT_RECONCILE_INTERVAL_MS = 4e3;
38543
+ }
38544
+ });
38404
38545
  var mesh_events_exports = {};
38405
38546
  __export2(mesh_events_exports, {
38406
38547
  __resetIdleAutoFastForwardForTests: () => __resetIdleAutoFastForwardForTests,
@@ -38410,10 +38551,11 @@ Next step: ${nextStep}`;
38410
38551
  getPendingMeshCoordinatorEvents: () => getPendingMeshCoordinatorEvents,
38411
38552
  handleMeshForwardEvent: () => handleMeshForwardEvent,
38412
38553
  isMeshCoordinatorEvent: () => isMeshCoordinatorEvent,
38413
- markMeshCoordinatorEventDirectDelivered: () => markMeshCoordinatorEventDirectDelivered,
38414
38554
  queuePendingMeshCoordinatorEvent: () => queuePendingMeshCoordinatorEvent,
38415
38555
  reconcileDirectDispatchCompletionFromTranscript: () => reconcileDirectDispatchCompletionFromTranscript,
38556
+ runMeshReconcileTick: () => runMeshReconcileTick,
38416
38557
  setupMeshEventForwarding: () => setupMeshEventForwarding,
38558
+ setupMeshReconcileLoop: () => setupMeshReconcileLoop,
38417
38559
  triggerMeshQueue: () => triggerMeshQueue,
38418
38560
  tryAssignQueueTask: () => tryAssignQueueTask
38419
38561
  });
@@ -38422,6 +38564,7 @@ Next step: ${nextStep}`;
38422
38564
  "use strict";
38423
38565
  init_mesh_events_pending();
38424
38566
  init_mesh_events_stale();
38567
+ init_mesh_reconcile_loop();
38425
38568
  init_mesh_events_coordinator();
38426
38569
  }
38427
38570
  });
@@ -84922,6 +85065,7 @@ data: ${JSON.stringify(msg.data)}
84922
85065
  init_logger();
84923
85066
  init_config();
84924
85067
  init_mesh_events();
85068
+ init_mesh_reconcile_loop();
84925
85069
  var _hardened = false;
84926
85070
  var HARDENED_PROTOS = [
84927
85071
  { name: "Object", proto: Object.prototype },
@@ -85119,6 +85263,7 @@ data: ${JSON.stringify(msg.data)}
85119
85263
  onMeshCoordinatorEventForwarded: config2.onMeshCoordinatorEventForwarded
85120
85264
  };
85121
85265
  setupMeshEventForwarding(components);
85266
+ components.meshReconcileLoop = setupMeshReconcileLoop(components);
85122
85267
  setImmediate(() => void router.resumePendingRefineJobsOnStartup());
85123
85268
  return components;
85124
85269
  }
@@ -85144,10 +85289,15 @@ data: ${JSON.stringify(msg.data)}
85144
85289
  agentStreamManager,
85145
85290
  cliManager,
85146
85291
  instanceManager,
85147
- cdpManagers
85292
+ cdpManagers,
85293
+ meshReconcileLoop
85148
85294
  } = components;
85149
85295
  poller.stop();
85150
85296
  cdpInitializer.stop();
85297
+ try {
85298
+ meshReconcileLoop?.stop();
85299
+ } catch {
85300
+ }
85151
85301
  try {
85152
85302
  if (agentStreamManager) {
85153
85303
  await agentStreamManager.dispose(cdpManagers);