@adhdev/daemon-core 0.9.82-rc.3 → 0.9.82-rc.30

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
@@ -1360,6 +1360,36 @@ function getQueuePath(meshId) {
1360
1360
  const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, "_");
1361
1361
  return (0, import_path4.join)(getLedgerDir(), `${safe}.queue.json`);
1362
1362
  }
1363
+ function getLockPath(meshId) {
1364
+ const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, "_");
1365
+ return (0, import_path4.join)(getLedgerDir(), `${safe}.queue.lock`);
1366
+ }
1367
+ function withQueueLock(meshId, fn) {
1368
+ const lockPath = getLockPath(meshId);
1369
+ let fd = -1;
1370
+ for (let i = 0; i < 10; i++) {
1371
+ try {
1372
+ fd = (0, import_fs4.openSync)(lockPath, "wx");
1373
+ break;
1374
+ } catch {
1375
+ const deadline = Date.now() + 30;
1376
+ while (Date.now() < deadline) {
1377
+ }
1378
+ }
1379
+ }
1380
+ try {
1381
+ return fn();
1382
+ } finally {
1383
+ if (fd !== -1) try {
1384
+ (0, import_fs4.closeSync)(fd);
1385
+ } catch {
1386
+ }
1387
+ try {
1388
+ (0, import_fs4.unlinkSync)(lockPath);
1389
+ } catch {
1390
+ }
1391
+ }
1392
+ }
1363
1393
  function readQueue(meshId) {
1364
1394
  const path28 = getQueuePath(meshId);
1365
1395
  if (!(0, import_fs4.existsSync)(path28)) return [];
@@ -1375,20 +1405,22 @@ function writeQueue(meshId, queue) {
1375
1405
  (0, import_fs4.writeFileSync)(path28, JSON.stringify(queue, null, 2), "utf-8");
1376
1406
  }
1377
1407
  function enqueueTask(meshId, message, opts) {
1378
- const queue = readQueue(meshId);
1379
- const entry = {
1380
- id: (0, import_crypto5.randomUUID)(),
1381
- meshId,
1382
- message,
1383
- status: "pending",
1384
- targetNodeId: opts?.targetNodeId,
1385
- targetSessionId: opts?.targetSessionId,
1386
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1387
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1388
- };
1389
- queue.push(entry);
1390
- writeQueue(meshId, queue);
1391
- return entry;
1408
+ return withQueueLock(meshId, () => {
1409
+ const queue = readQueue(meshId);
1410
+ const entry = {
1411
+ id: (0, import_crypto5.randomUUID)(),
1412
+ meshId,
1413
+ message,
1414
+ status: "pending",
1415
+ targetNodeId: opts?.targetNodeId,
1416
+ targetSessionId: opts?.targetSessionId,
1417
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1418
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1419
+ };
1420
+ queue.push(entry);
1421
+ writeQueue(meshId, queue);
1422
+ return entry;
1423
+ });
1392
1424
  }
1393
1425
  function getQueue(meshId, opts) {
1394
1426
  let queue = readQueue(meshId);
@@ -1399,100 +1431,111 @@ function getQueue(meshId, opts) {
1399
1431
  return queue;
1400
1432
  }
1401
1433
  function claimNextTask(meshId, nodeId, sessionId) {
1402
- const queue = readQueue(meshId);
1403
- const hasActiveAssignment = queue.some((q) => q.status === "assigned" && (q.assignedSessionId === sessionId || q.assignedNodeId === nodeId));
1404
- if (hasActiveAssignment) return null;
1405
- let targetIdx = queue.findIndex((q) => q.status === "pending" && q.targetSessionId === sessionId);
1406
- if (targetIdx === -1) {
1407
- targetIdx = queue.findIndex((q) => q.status === "pending" && q.targetNodeId === nodeId && !q.targetSessionId);
1408
- }
1409
- if (targetIdx === -1) {
1410
- targetIdx = queue.findIndex((q) => q.status === "pending" && !q.targetNodeId && !q.targetSessionId);
1411
- }
1412
- if (targetIdx === -1) return null;
1413
- const entry = queue[targetIdx];
1414
- entry.status = "assigned";
1415
- entry.assignedNodeId = nodeId;
1416
- entry.assignedSessionId = sessionId;
1417
- entry.dispatchTimestamp = (/* @__PURE__ */ new Date()).toISOString();
1418
- entry.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1419
- writeQueue(meshId, queue);
1420
- return entry;
1434
+ return withQueueLock(meshId, () => {
1435
+ const queue = readQueue(meshId);
1436
+ const hasActiveAssignment = queue.some((q) => q.status === "assigned" && (q.assignedSessionId === sessionId || q.assignedNodeId === nodeId));
1437
+ if (hasActiveAssignment) return null;
1438
+ let targetIdx = queue.findIndex((q) => q.status === "pending" && q.targetSessionId === sessionId);
1439
+ if (targetIdx === -1) {
1440
+ targetIdx = queue.findIndex((q) => q.status === "pending" && q.targetNodeId === nodeId && !q.targetSessionId);
1441
+ }
1442
+ if (targetIdx === -1) {
1443
+ targetIdx = queue.findIndex((q) => q.status === "pending" && !q.targetNodeId && !q.targetSessionId);
1444
+ }
1445
+ if (targetIdx === -1) return null;
1446
+ const entry = queue[targetIdx];
1447
+ entry.status = "assigned";
1448
+ entry.assignedNodeId = nodeId;
1449
+ entry.assignedSessionId = sessionId;
1450
+ entry.dispatchTimestamp = (/* @__PURE__ */ new Date()).toISOString();
1451
+ entry.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1452
+ writeQueue(meshId, queue);
1453
+ return entry;
1454
+ });
1421
1455
  }
1422
1456
  function updateTaskStatus(meshId, taskId, status) {
1423
- const queue = readQueue(meshId);
1424
- const idx = queue.findIndex((q) => q.id === taskId);
1425
- if (idx === -1) return null;
1426
- queue[idx].status = status;
1427
- queue[idx].updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1428
- writeQueue(meshId, queue);
1429
- return queue[idx];
1457
+ return withQueueLock(meshId, () => {
1458
+ const queue = readQueue(meshId);
1459
+ const idx = queue.findIndex((q) => q.id === taskId);
1460
+ if (idx === -1) return null;
1461
+ queue[idx].status = status;
1462
+ queue[idx].updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1463
+ writeQueue(meshId, queue);
1464
+ return queue[idx];
1465
+ });
1430
1466
  }
1431
1467
  function recordTaskAutoLaunch(meshId, taskId, autoLaunch) {
1432
- const queue = readQueue(meshId);
1433
- const idx = queue.findIndex((q) => q.id === taskId);
1434
- if (idx === -1) return null;
1435
- const now = (/* @__PURE__ */ new Date()).toISOString();
1436
- queue[idx].autoLaunch = {
1437
- ...autoLaunch,
1438
- updatedAt: now
1439
- };
1440
- queue[idx].updatedAt = now;
1441
- writeQueue(meshId, queue);
1442
- return queue[idx];
1468
+ return withQueueLock(meshId, () => {
1469
+ const queue = readQueue(meshId);
1470
+ const idx = queue.findIndex((q) => q.id === taskId);
1471
+ if (idx === -1) return null;
1472
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1473
+ queue[idx].autoLaunch = { ...autoLaunch, updatedAt: now };
1474
+ queue[idx].updatedAt = now;
1475
+ writeQueue(meshId, queue);
1476
+ return queue[idx];
1477
+ });
1443
1478
  }
1444
1479
  function cancelTask(meshId, taskId, opts) {
1445
- const queue = readQueue(meshId);
1446
- const idx = queue.findIndex((q) => q.id === taskId);
1447
- if (idx === -1) return null;
1448
- const now = (/* @__PURE__ */ new Date()).toISOString();
1449
- queue[idx].status = "cancelled";
1450
- queue[idx].updatedAt = now;
1451
- queue[idx].cancelledAt = now;
1452
- if (opts?.reason) queue[idx].cancelReason = opts.reason;
1453
- writeQueue(meshId, queue);
1454
- return queue[idx];
1480
+ return withQueueLock(meshId, () => {
1481
+ const queue = readQueue(meshId);
1482
+ const idx = queue.findIndex((q) => q.id === taskId);
1483
+ if (idx === -1) return null;
1484
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1485
+ queue[idx].status = "cancelled";
1486
+ queue[idx].updatedAt = now;
1487
+ queue[idx].cancelledAt = now;
1488
+ if (opts?.reason) queue[idx].cancelReason = opts.reason;
1489
+ writeQueue(meshId, queue);
1490
+ return queue[idx];
1491
+ });
1455
1492
  }
1456
1493
  function requeueTask(meshId, taskId, opts) {
1457
- const queue = readQueue(meshId);
1458
- const idx = queue.findIndex((q) => q.id === taskId);
1459
- if (idx === -1) return null;
1460
- const entry = queue[idx];
1461
- const now = (/* @__PURE__ */ new Date()).toISOString();
1462
- entry.status = "pending";
1463
- delete entry.assignedNodeId;
1464
- delete entry.assignedSessionId;
1465
- delete entry.cancelledAt;
1466
- delete entry.cancelReason;
1467
- if (opts?.clearTargetNode) delete entry.targetNodeId;
1468
- if (typeof opts?.targetNodeId === "string") entry.targetNodeId = opts.targetNodeId;
1469
- if (opts?.clearTargetSession !== false) delete entry.targetSessionId;
1470
- if (typeof opts?.targetSessionId === "string") entry.targetSessionId = opts.targetSessionId;
1471
- entry.updatedAt = now;
1472
- entry.requeuedAt = now;
1473
- entry.requeueCount = (entry.requeueCount || 0) + 1;
1474
- if (opts?.reason) entry.requeueReason = opts.reason;
1475
- writeQueue(meshId, queue);
1476
- return entry;
1477
- }
1478
- function updateSessionTaskStatus(meshId, sessionId, status) {
1479
- const queue = readQueue(meshId);
1480
- let bestIdx = -1;
1481
- let bestTime = 0;
1482
- for (let i = queue.length - 1; i >= 0; i--) {
1483
- if (queue[i].assignedSessionId === sessionId && queue[i].status === "assigned") {
1494
+ return withQueueLock(meshId, () => {
1495
+ const queue = readQueue(meshId);
1496
+ const idx = queue.findIndex((q) => q.id === taskId);
1497
+ if (idx === -1) return null;
1498
+ const entry = queue[idx];
1499
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1500
+ entry.status = "pending";
1501
+ delete entry.assignedNodeId;
1502
+ delete entry.assignedSessionId;
1503
+ delete entry.cancelledAt;
1504
+ delete entry.cancelReason;
1505
+ if (opts?.clearTargetNode) delete entry.targetNodeId;
1506
+ if (typeof opts?.targetNodeId === "string") entry.targetNodeId = opts.targetNodeId;
1507
+ if (opts?.clearTargetSession !== false) delete entry.targetSessionId;
1508
+ if (typeof opts?.targetSessionId === "string") entry.targetSessionId = opts.targetSessionId;
1509
+ entry.updatedAt = now;
1510
+ entry.requeuedAt = now;
1511
+ entry.requeueCount = (entry.requeueCount || 0) + 1;
1512
+ if (opts?.reason) entry.requeueReason = opts.reason;
1513
+ writeQueue(meshId, queue);
1514
+ return entry;
1515
+ });
1516
+ }
1517
+ function updateSessionTaskStatus(meshId, sessionId, status, opts) {
1518
+ return withQueueLock(meshId, () => {
1519
+ const queue = readQueue(meshId);
1520
+ const occurredAtTime = opts?.occurredAt ? new Date(opts.occurredAt).getTime() : Number.NaN;
1521
+ const hasOccurredAt = Number.isFinite(occurredAtTime);
1522
+ let bestIdx = -1;
1523
+ let bestTime = 0;
1524
+ for (let i = queue.length - 1; i >= 0; i--) {
1525
+ if (queue[i].assignedSessionId !== sessionId || queue[i].status !== "assigned") continue;
1484
1526
  const time = new Date(queue[i].dispatchTimestamp || queue[i].updatedAt).getTime();
1527
+ if (hasOccurredAt && Number.isFinite(time) && time > occurredAtTime) continue;
1485
1528
  if (time > bestTime) {
1486
1529
  bestTime = time;
1487
1530
  bestIdx = i;
1488
1531
  }
1489
1532
  }
1490
- }
1491
- if (bestIdx === -1) return null;
1492
- queue[bestIdx].status = status;
1493
- queue[bestIdx].updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1494
- writeQueue(meshId, queue);
1495
- return queue[bestIdx];
1533
+ if (bestIdx === -1) return null;
1534
+ queue[bestIdx].status = status;
1535
+ queue[bestIdx].updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1536
+ writeQueue(meshId, queue);
1537
+ return queue[bestIdx];
1538
+ });
1496
1539
  }
1497
1540
  function getMeshQueueStats(meshId) {
1498
1541
  const queue = readQueue(meshId);
@@ -1896,18 +1939,75 @@ __export(mesh_events_exports, {
1896
1939
  drainPendingMeshCoordinatorEvents: () => drainPendingMeshCoordinatorEvents,
1897
1940
  getPendingMeshCoordinatorEvents: () => getPendingMeshCoordinatorEvents,
1898
1941
  handleMeshForwardEvent: () => handleMeshForwardEvent,
1942
+ queuePendingMeshCoordinatorEvent: () => queuePendingMeshCoordinatorEvent,
1899
1943
  setupMeshEventForwarding: () => setupMeshEventForwarding,
1900
1944
  triggerMeshQueue: () => triggerMeshQueue,
1901
1945
  tryAssignQueueTask: () => tryAssignQueueTask
1902
1946
  });
1903
- function drainPendingMeshCoordinatorEvents() {
1904
- return pendingMeshCoordinatorEvents.splice(0);
1947
+ function sweepExpiredRemoteIdleSessions() {
1948
+ const now = Date.now();
1949
+ for (const [key, session] of remoteIdleSessions) {
1950
+ if (session.expiresAt <= now) remoteIdleSessions.delete(key);
1951
+ }
1905
1952
  }
1906
- function getPendingMeshCoordinatorEvents() {
1907
- return pendingMeshCoordinatorEvents.slice();
1953
+ function getPendingEventsPath(meshId) {
1954
+ const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, "_");
1955
+ return (0, import_path5.join)(getLedgerDir(), `${safe}.pending-events.jsonl`);
1908
1956
  }
1909
- function clearPendingMeshCoordinatorEvents() {
1910
- pendingMeshCoordinatorEvents.splice(0);
1957
+ function queuePendingMeshCoordinatorEvent(event) {
1958
+ try {
1959
+ (0, import_fs6.appendFileSync)(getPendingEventsPath(event.meshId), JSON.stringify(event) + "\n", "utf-8");
1960
+ return true;
1961
+ } catch (e) {
1962
+ LOG.warn("MeshEvents", `Failed to persist pending coordinator event: ${e?.message || e}`);
1963
+ return false;
1964
+ }
1965
+ }
1966
+ function drainPendingMeshCoordinatorEvents(meshId) {
1967
+ if (!meshId) return [];
1968
+ const path28 = getPendingEventsPath(meshId);
1969
+ if (!(0, import_fs6.existsSync)(path28)) return [];
1970
+ try {
1971
+ const raw = (0, import_fs6.readFileSync)(path28, "utf-8");
1972
+ try {
1973
+ (0, import_fs6.unlinkSync)(path28);
1974
+ } catch {
1975
+ }
1976
+ return raw.split("\n").filter(Boolean).flatMap((line) => {
1977
+ try {
1978
+ return [JSON.parse(line)];
1979
+ } catch {
1980
+ return [];
1981
+ }
1982
+ });
1983
+ } catch {
1984
+ return [];
1985
+ }
1986
+ }
1987
+ function getPendingMeshCoordinatorEvents(meshId) {
1988
+ if (!meshId) return [];
1989
+ const path28 = getPendingEventsPath(meshId);
1990
+ if (!(0, import_fs6.existsSync)(path28)) return [];
1991
+ try {
1992
+ const raw = (0, import_fs6.readFileSync)(path28, "utf-8");
1993
+ return raw.split("\n").filter(Boolean).flatMap((line) => {
1994
+ try {
1995
+ return [JSON.parse(line)];
1996
+ } catch {
1997
+ return [];
1998
+ }
1999
+ });
2000
+ } catch {
2001
+ return [];
2002
+ }
2003
+ }
2004
+ function clearPendingMeshCoordinatorEvents(meshId) {
2005
+ if (!meshId) return;
2006
+ const path28 = getPendingEventsPath(meshId);
2007
+ if ((0, import_fs6.existsSync)(path28)) try {
2008
+ (0, import_fs6.unlinkSync)(path28);
2009
+ } catch {
2010
+ }
1911
2011
  }
1912
2012
  function readNonEmptyString(value) {
1913
2013
  return typeof value === "string" && value.trim() ? value.trim() : "";
@@ -1953,6 +2053,38 @@ function shouldSuppressIntentionalCleanupStop(args) {
1953
2053
  if (isIntentionalCleanupStopMetadata(args.metadataEvent)) return true;
1954
2054
  return hasRecentIntentionalCleanupStop(args.meshId, args.sessionId, args.nodeId);
1955
2055
  }
2056
+ function readEventTimestamp(value) {
2057
+ if (typeof value === "number" && Number.isFinite(value)) return value;
2058
+ if (typeof value === "string" && value.trim()) {
2059
+ const numeric = Number(value);
2060
+ if (Number.isFinite(numeric)) return numeric;
2061
+ const parsed = Date.parse(value);
2062
+ if (Number.isFinite(parsed)) return parsed;
2063
+ }
2064
+ return null;
2065
+ }
2066
+ function buildMeshCompletionFingerprint(args) {
2067
+ const timestampPart = Number.isFinite(args.timestamp) ? String(args.timestamp) : readNonEmptyString(args.finalSummary).slice(0, 200);
2068
+ return [
2069
+ args.meshId,
2070
+ args.event,
2071
+ args.sessionId,
2072
+ args.providerType || "",
2073
+ args.providerSessionId || "",
2074
+ timestampPart
2075
+ ].join("::");
2076
+ }
2077
+ function isDuplicateMeshCompletionEvent(args) {
2078
+ const fingerprint = buildMeshCompletionFingerprint(args);
2079
+ if (!fingerprint) return false;
2080
+ const now = Date.now();
2081
+ for (const [key, seenAt] of recentCompletionFingerprints.entries()) {
2082
+ if (now - seenAt > RECENT_COMPLETION_FINGERPRINT_TTL_MS) recentCompletionFingerprints.delete(key);
2083
+ }
2084
+ if (recentCompletionFingerprints.has(fingerprint)) return true;
2085
+ recentCompletionFingerprints.set(fingerprint, now);
2086
+ return false;
2087
+ }
1956
2088
  function tryAssignQueueTask(components, meshId, nodeId, sessionId, providerType) {
1957
2089
  const task = claimNextTask(meshId, nodeId, sessionId);
1958
2090
  if (!task) {
@@ -1971,7 +2103,16 @@ function tryAssignQueueTask(components, meshId, nodeId, sessionId, providerType)
1971
2103
  message: task.message
1972
2104
  }).catch((e) => {
1973
2105
  LOG.error("MeshQueue", `Failed to dispatch task via P2P to remote node ${nodeId}: ${e?.message}`);
1974
- updateTaskStatus(meshId, task.id, "failed");
2106
+ updateTaskStatus(meshId, task.id, "pending");
2107
+ try {
2108
+ appendLedgerEntry(meshId, {
2109
+ kind: "dispatch_failed",
2110
+ nodeId,
2111
+ sessionId,
2112
+ payload: { taskId: task.id, error: e?.message, retryable: true }
2113
+ });
2114
+ } catch {
2115
+ }
1975
2116
  });
1976
2117
  return true;
1977
2118
  }
@@ -2305,18 +2446,36 @@ function injectMeshSystemMessage(components, args) {
2305
2446
  LOG.info("MeshEvents", `Suppressed ${args.event} for intentionally cleanup-stopped session ${eventSessionId || "(unknown session)"}`);
2306
2447
  return { success: true, forwarded: 0, suppressed: true, intentionalCleanupStop: true };
2307
2448
  }
2449
+ const eventTimestamp = readEventTimestamp(args.metadataEvent.timestamp);
2450
+ if (args.event === "agent:generating_completed" && eventSessionId) {
2451
+ const duplicateCompletion = isDuplicateMeshCompletionEvent({
2452
+ meshId: args.meshId,
2453
+ event: args.event,
2454
+ sessionId: eventSessionId,
2455
+ providerType: readNonEmptyString(args.metadataEvent.providerType) || void 0,
2456
+ providerSessionId: readNonEmptyString(args.metadataEvent.providerSessionId) || void 0,
2457
+ timestamp: eventTimestamp,
2458
+ finalSummary: readNonEmptyString(args.metadataEvent.finalSummary) || void 0
2459
+ });
2460
+ if (duplicateCompletion) {
2461
+ LOG.info("MeshEvents", `Suppressed duplicate completion for mesh ${args.meshId} session ${eventSessionId}`);
2462
+ return { success: true, forwarded: 0, suppressed: true, duplicateCompletion: true };
2463
+ }
2464
+ }
2308
2465
  let completedTaskForLedger = null;
2309
2466
  if (args.event === "agent:generating_completed") {
2310
2467
  const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
2311
2468
  const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
2312
2469
  const providerType = readNonEmptyString(args.metadataEvent.providerType);
2313
2470
  if (sessionId) {
2314
- const completedTask = updateSessionTaskStatus(args.meshId, sessionId, "completed");
2471
+ const completedTask = updateSessionTaskStatus(args.meshId, sessionId, "completed", {
2472
+ occurredAt: eventTimestamp !== null ? new Date(eventTimestamp).toISOString() : void 0
2473
+ });
2315
2474
  completedTaskForLedger = completedTask ? { id: completedTask.id } : null;
2316
2475
  if (nodeId && providerType) {
2317
- setTimeout(() => {
2476
+ setImmediate(() => {
2318
2477
  tryAssignQueueTask(components, args.meshId, nodeId, sessionId, providerType);
2319
- }, 500);
2478
+ });
2320
2479
  }
2321
2480
  }
2322
2481
  } else if (args.event === "agent:ready") {
@@ -2354,13 +2513,17 @@ function injectMeshSystemMessage(components, args) {
2354
2513
  }
2355
2514
  }
2356
2515
  if (sessionId && nodeId && providerType) {
2357
- remoteIdleSessions.set(`${nodeId}:${sessionId}`, { nodeId, sessionId, providerType });
2358
- setTimeout(() => {
2516
+ sweepExpiredRemoteIdleSessions();
2517
+ remoteIdleSessions.set(`${nodeId}:${sessionId}`, {
2518
+ nodeId,
2519
+ sessionId,
2520
+ providerType,
2521
+ expiresAt: Date.now() + REMOTE_IDLE_SESSION_TTL_MS
2522
+ });
2523
+ setImmediate(() => {
2359
2524
  const assigned = tryAssignQueueTask(components, args.meshId, nodeId, sessionId, providerType);
2360
- if (assigned) {
2361
- remoteIdleSessions.delete(`${nodeId}:${sessionId}`);
2362
- }
2363
- }, 500);
2525
+ if (assigned) remoteIdleSessions.delete(`${nodeId}:${sessionId}`);
2526
+ });
2364
2527
  }
2365
2528
  } else if (args.event === "agent:generating_started") {
2366
2529
  const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
@@ -2471,17 +2634,18 @@ function injectMeshSystemMessage(components, args) {
2471
2634
  return true;
2472
2635
  });
2473
2636
  if (coordinatorInstances.length === 0) {
2474
- if (pendingMeshCoordinatorEvents.length < MAX_PENDING_EVENTS) {
2475
- pendingMeshCoordinatorEvents.push({
2476
- event: args.event,
2477
- meshId: args.meshId,
2478
- nodeLabel: args.nodeLabel,
2479
- metadataEvent: {
2480
- ...args.metadataEvent,
2481
- ...recoveryContext ? { recoveryContext } : {}
2482
- },
2483
- queuedAt: Date.now()
2484
- });
2637
+ if (queuePendingMeshCoordinatorEvent({
2638
+ event: args.event,
2639
+ meshId: args.meshId,
2640
+ nodeLabel: args.nodeLabel,
2641
+ nodeId: args.nodeId || void 0,
2642
+ workspace: readNonEmptyString(args.metadataEvent.workspace),
2643
+ metadataEvent: {
2644
+ ...args.metadataEvent,
2645
+ ...recoveryContext ? { recoveryContext } : {}
2646
+ },
2647
+ queuedAt: Date.now()
2648
+ })) {
2485
2649
  LOG.info("MeshEvents", `Queued ${args.event} for MCP coordinator (mesh ${args.meshId})`);
2486
2650
  }
2487
2651
  return { success: true, forwarded: 0 };
@@ -2520,6 +2684,7 @@ function handleMeshForwardEvent(components, payload) {
2520
2684
  providerType: readNonEmptyString(payload.providerType),
2521
2685
  providerSessionId: readNonEmptyString(payload.providerSessionId),
2522
2686
  finalSummary: readNonEmptyString(payload.finalSummary) || readNonEmptyString(payload.summary),
2687
+ ...payload.timestamp !== void 0 ? { timestamp: payload.timestamp } : {},
2523
2688
  intentional: payload.intentional === true,
2524
2689
  intentionalStop: payload.intentionalStop === true,
2525
2690
  operatorCleanup: payload.operatorCleanup === true,
@@ -2562,19 +2727,20 @@ function setupMeshEventForwarding(components) {
2562
2727
  });
2563
2728
  });
2564
2729
  }
2565
- var remoteIdleSessions, MAX_PENDING_EVENTS, pendingMeshCoordinatorEvents, MESH_COORDINATOR_EVENTS, EVENT_TO_LEDGER_KIND, INTENTIONAL_CLEANUP_STOP_SUPPRESSION_MS, autoLaunchInProgress, autoLaunchCooldownUntil, AUTO_LAUNCH_COOLDOWN_MS;
2730
+ var import_fs6, import_path5, REMOTE_IDLE_SESSION_TTL_MS, remoteIdleSessions, MESH_COORDINATOR_EVENTS, EVENT_TO_LEDGER_KIND, INTENTIONAL_CLEANUP_STOP_SUPPRESSION_MS, RECENT_COMPLETION_FINGERPRINT_TTL_MS, recentCompletionFingerprints, autoLaunchInProgress, autoLaunchCooldownUntil, AUTO_LAUNCH_COOLDOWN_MS;
2566
2731
  var init_mesh_events = __esm({
2567
2732
  "src/mesh/mesh-events.ts"() {
2568
2733
  "use strict";
2734
+ import_fs6 = require("fs");
2735
+ import_path5 = require("path");
2569
2736
  init_config();
2570
2737
  init_mesh_config();
2571
2738
  init_cli_detector();
2572
2739
  init_logger();
2573
2740
  init_mesh_ledger();
2574
2741
  init_mesh_work_queue();
2742
+ REMOTE_IDLE_SESSION_TTL_MS = 5 * 60 * 1e3;
2575
2743
  remoteIdleSessions = /* @__PURE__ */ new Map();
2576
- MAX_PENDING_EVENTS = 50;
2577
- pendingMeshCoordinatorEvents = [];
2578
2744
  MESH_COORDINATOR_EVENTS = /* @__PURE__ */ new Set([
2579
2745
  "agent:generating_started",
2580
2746
  "agent:generating_completed",
@@ -2590,6 +2756,8 @@ var init_mesh_events = __esm({
2590
2756
  "monitor:long_generating": "task_stalled"
2591
2757
  };
2592
2758
  INTENTIONAL_CLEANUP_STOP_SUPPRESSION_MS = 30 * 60 * 1e3;
2759
+ RECENT_COMPLETION_FINGERPRINT_TTL_MS = 10 * 60 * 1e3;
2760
+ recentCompletionFingerprints = /* @__PURE__ */ new Map();
2593
2761
  autoLaunchInProgress = /* @__PURE__ */ new Set();
2594
2762
  autoLaunchCooldownUntil = /* @__PURE__ */ new Map();
2595
2763
  AUTO_LAUNCH_COOLDOWN_MS = 5e3;
@@ -5860,6 +6028,7 @@ __export(index_exports, {
5860
6028
  prepareSessionChatTailUpdate: () => prepareSessionChatTailUpdate,
5861
6029
  prepareSessionModalUpdate: () => prepareSessionModalUpdate,
5862
6030
  probeCdpPort: () => probeCdpPort,
6031
+ queuePendingMeshCoordinatorEvent: () => queuePendingMeshCoordinatorEvent,
5863
6032
  readChatHistory: () => readChatHistory,
5864
6033
  readLedgerEntries: () => readLedgerEntries,
5865
6034
  readLedgerSlice: () => readLedgerSlice,
@@ -5913,8 +6082,14 @@ async function getGitRepoStatus(workspace, options = {}) {
5913
6082
  const includeSubmodules = options.includeSubmodules !== false;
5914
6083
  try {
5915
6084
  const repo = await resolveGitRepository(workspace, options);
5916
- const statusOutput = await runGit(repo, ["status", "--porcelain=v2", "--branch"], options);
5917
- const parsed = parsePorcelainV2Status(statusOutput.stdout);
6085
+ let parsed = await readPorcelainStatus(repo, options);
6086
+ let upstreamProbe = getInitialUpstreamProbe(parsed);
6087
+ if (options.refreshUpstream) {
6088
+ upstreamProbe = await refreshTrackedUpstream(repo, parsed, options);
6089
+ if (upstreamProbe.upstreamStatus === "fresh") {
6090
+ parsed = await readPorcelainStatus(repo, options);
6091
+ }
6092
+ }
5918
6093
  const head = await readHead(repo, options);
5919
6094
  const stashCount = await readStashCount(repo, options);
5920
6095
  let submodules;
@@ -5929,6 +6104,9 @@ async function getGitRepoStatus(workspace, options = {}) {
5929
6104
  headCommit: head.commit,
5930
6105
  headMessage: head.message,
5931
6106
  upstream: parsed.upstream,
6107
+ upstreamStatus: parsed.upstream ? upstreamProbe.upstreamStatus : "no_upstream",
6108
+ upstreamFetchedAt: upstreamProbe.upstreamFetchedAt,
6109
+ upstreamFetchError: upstreamProbe.upstreamFetchError,
5932
6110
  ahead: parsed.ahead,
5933
6111
  behind: parsed.behind,
5934
6112
  staged: parsed.staged,
@@ -5953,6 +6131,60 @@ async function getGitRepoStatus(workspace, options = {}) {
5953
6131
  );
5954
6132
  }
5955
6133
  }
6134
+ async function readPorcelainStatus(repo, options) {
6135
+ const statusOutput = await runGit(repo, ["status", "--porcelain=v2", "--branch"], options);
6136
+ return parsePorcelainV2Status(statusOutput.stdout);
6137
+ }
6138
+ function getInitialUpstreamProbe(parsed) {
6139
+ return {
6140
+ upstreamStatus: parsed.upstream ? "unchecked" : "no_upstream"
6141
+ };
6142
+ }
6143
+ async function refreshTrackedUpstream(repo, parsed, options) {
6144
+ if (!parsed.upstream || !parsed.branch) {
6145
+ return { upstreamStatus: "no_upstream" };
6146
+ }
6147
+ const remoteName = await readBranchRemote(repo, parsed.branch, options) ?? inferRemoteName(parsed.upstream);
6148
+ if (!remoteName) {
6149
+ return {
6150
+ upstreamStatus: "stale",
6151
+ upstreamFetchError: `Unable to resolve remote for upstream '${parsed.upstream}'`
6152
+ };
6153
+ }
6154
+ try {
6155
+ await runGit(repo, ["fetch", "--quiet", "--prune", "--no-tags", remoteName], options);
6156
+ return {
6157
+ upstreamStatus: "fresh",
6158
+ upstreamFetchedAt: Date.now()
6159
+ };
6160
+ } catch (error) {
6161
+ return {
6162
+ upstreamStatus: "stale",
6163
+ upstreamFetchError: formatGitError(error)
6164
+ };
6165
+ }
6166
+ }
6167
+ async function readBranchRemote(repo, branch, options) {
6168
+ try {
6169
+ const result = await runGit(repo, ["config", "--get", `branch.${branch}.remote`], options);
6170
+ return result.stdout.trim() || null;
6171
+ } catch {
6172
+ return null;
6173
+ }
6174
+ }
6175
+ function inferRemoteName(upstream) {
6176
+ const [remoteName] = upstream.split("/");
6177
+ return remoteName?.trim() || null;
6178
+ }
6179
+ function formatGitError(error) {
6180
+ if (error instanceof GitCommandError) {
6181
+ return error.stderr || error.message;
6182
+ }
6183
+ if (error instanceof Error) {
6184
+ return error.message;
6185
+ }
6186
+ return String(error);
6187
+ }
5956
6188
  function parsePorcelainV2Status(output) {
5957
6189
  const parsed = {
5958
6190
  branch: null,
@@ -6047,6 +6279,7 @@ function emptyStatus(workspace, lastCheckedAt, error) {
6047
6279
  headCommit: null,
6048
6280
  headMessage: null,
6049
6281
  upstream: null,
6282
+ upstreamStatus: "unavailable",
6050
6283
  ahead: 0,
6051
6284
  behind: 0,
6052
6285
  staged: 0,
@@ -6327,6 +6560,9 @@ function createGitCompactSummary(status, diffSummary) {
6327
6560
  isGitRepo: status.isGitRepo,
6328
6561
  repoRoot: status.repoRoot,
6329
6562
  branch: status.branch,
6563
+ upstreamStatus: status.upstreamStatus,
6564
+ upstreamFetchedAt: status.upstreamFetchedAt,
6565
+ upstreamFetchError: status.upstreamFetchError,
6330
6566
  dirty: status.staged > 0 || status.modified > 0 || status.untracked > 0 || status.deleted > 0 || status.renamed > 0 || conflictCount > 0 || changedFiles > 0,
6331
6567
  changedFiles,
6332
6568
  ahead: status.ahead,
@@ -6671,7 +6907,7 @@ var defaultSnapshotStore = createGitSnapshotStore({
6671
6907
  });
6672
6908
  function createDefaultGitCommandServices() {
6673
6909
  return {
6674
- getStatus: ({ workspace }) => getGitRepoStatus(workspace),
6910
+ getStatus: ({ workspace, refreshUpstream }) => getGitRepoStatus(workspace, { refreshUpstream }),
6675
6911
  getDiffSummary: ({ workspace }) => getGitDiffSummary(workspace),
6676
6912
  getDiffFile: ({ workspace, path: filePath }) => getGitFileDiff(workspace, filePath),
6677
6913
  createSnapshot: ({ workspace, reason, sessionId, turnId }) => defaultSnapshotStore.create({
@@ -6757,7 +6993,7 @@ async function handleGitCommand(command, args, services = defaultGitCommandServi
6757
6993
  switch (command) {
6758
6994
  case "git_status": {
6759
6995
  if (!services.getStatus) return serviceNotImplemented(command);
6760
- const status = await runService(() => services.getStatus({ workspace }));
6996
+ const status = await runService(() => services.getStatus({ workspace, refreshUpstream: optionalBoolean(args?.refreshUpstream) }));
6761
6997
  return "success" in status ? status : { success: true, status };
6762
6998
  }
6763
6999
  case "git_diff_summary": {
@@ -7795,8 +8031,8 @@ var P2pRelayFailureError = class extends Error {
7795
8031
  };
7796
8032
 
7797
8033
  // src/config/state-store.ts
7798
- var import_fs6 = require("fs");
7799
- var import_path5 = require("path");
8034
+ var import_fs7 = require("fs");
8035
+ var import_path6 = require("path");
7800
8036
  init_config();
7801
8037
  var DEFAULT_STATE = {
7802
8038
  recentActivity: [],
@@ -7810,7 +8046,7 @@ function isPlainObject2(value) {
7810
8046
  return !!value && typeof value === "object" && !Array.isArray(value);
7811
8047
  }
7812
8048
  function getStatePath() {
7813
- return (0, import_path5.join)(getConfigDir(), "state.json");
8049
+ return (0, import_path6.join)(getConfigDir(), "state.json");
7814
8050
  }
7815
8051
  function normalizeState(raw) {
7816
8052
  const parsed = isPlainObject2(raw) ? raw : {};
@@ -7846,11 +8082,11 @@ function normalizeState(raw) {
7846
8082
  }
7847
8083
  function loadState() {
7848
8084
  const statePath = getStatePath();
7849
- if (!(0, import_fs6.existsSync)(statePath)) {
8085
+ if (!(0, import_fs7.existsSync)(statePath)) {
7850
8086
  return { ...DEFAULT_STATE };
7851
8087
  }
7852
8088
  try {
7853
- const raw = (0, import_fs6.readFileSync)(statePath, "utf-8");
8089
+ const raw = (0, import_fs7.readFileSync)(statePath, "utf-8");
7854
8090
  return normalizeState(JSON.parse(raw));
7855
8091
  } catch {
7856
8092
  return { ...DEFAULT_STATE };
@@ -7859,7 +8095,7 @@ function loadState() {
7859
8095
  function saveState(state) {
7860
8096
  const statePath = getStatePath();
7861
8097
  const normalized = normalizeState(state);
7862
- (0, import_fs6.writeFileSync)(statePath, JSON.stringify(normalized, null, 2), { encoding: "utf-8", mode: 384 });
8098
+ (0, import_fs7.writeFileSync)(statePath, JSON.stringify(normalized, null, 2), { encoding: "utf-8", mode: 384 });
7863
8099
  }
7864
8100
  function resetState() {
7865
8101
  saveState({ ...DEFAULT_STATE });
@@ -7867,7 +8103,7 @@ function resetState() {
7867
8103
 
7868
8104
  // src/detection/ide-detector.ts
7869
8105
  var import_child_process2 = require("child_process");
7870
- var import_fs7 = require("fs");
8106
+ var import_fs8 = require("fs");
7871
8107
  var import_os2 = require("os");
7872
8108
  var path10 = __toESM(require("path"));
7873
8109
  var BUILTIN_IDE_DEFINITIONS = [];
@@ -7891,7 +8127,7 @@ function findCliCommand(command) {
7891
8127
  if (path10.isAbsolute(trimmed) || trimmed.includes("/") || trimmed.includes("\\") || trimmed.startsWith("~")) {
7892
8128
  const candidate = trimmed.startsWith("~") ? path10.join((0, import_os2.homedir)(), trimmed.slice(1)) : trimmed;
7893
8129
  const resolved = path10.isAbsolute(candidate) ? candidate : path10.resolve(candidate);
7894
- return (0, import_fs7.existsSync)(resolved) ? resolved : null;
8130
+ return (0, import_fs8.existsSync)(resolved) ? resolved : null;
7895
8131
  }
7896
8132
  try {
7897
8133
  const result = (0, import_child_process2.execSync)(
@@ -7922,9 +8158,9 @@ function checkPathExists(paths) {
7922
8158
  if (normalized.includes("*")) {
7923
8159
  const username = home.split(/[\\/]/).pop() || "";
7924
8160
  const resolved = normalized.replace("*", username);
7925
- if ((0, import_fs7.existsSync)(resolved)) return resolved;
8161
+ if ((0, import_fs8.existsSync)(resolved)) return resolved;
7926
8162
  } else {
7927
- if ((0, import_fs7.existsSync)(normalized)) return normalized;
8163
+ if ((0, import_fs8.existsSync)(normalized)) return normalized;
7928
8164
  }
7929
8165
  }
7930
8166
  return null;
@@ -7938,7 +8174,7 @@ async function detectIDEs(providerLoader) {
7938
8174
  let resolvedCli = cliPath;
7939
8175
  if (!resolvedCli && appPath && os22 === "darwin") {
7940
8176
  const bundledCli = `${appPath}/Contents/Resources/app/bin/${def.cli}`;
7941
- if ((0, import_fs7.existsSync)(bundledCli)) resolvedCli = bundledCli;
8177
+ if ((0, import_fs8.existsSync)(bundledCli)) resolvedCli = bundledCli;
7942
8178
  }
7943
8179
  if (!resolvedCli && appPath && os22 === "win32") {
7944
8180
  const { dirname: dirname9 } = await import("path");
@@ -7951,7 +8187,7 @@ async function detectIDEs(providerLoader) {
7951
8187
  `${appDir}\\\\resources\\\\app\\\\bin\\\\${def.cli}.cmd`
7952
8188
  ];
7953
8189
  for (const c of candidates) {
7954
- if ((0, import_fs7.existsSync)(c)) {
8190
+ if ((0, import_fs8.existsSync)(c)) {
7955
8191
  resolvedCli = c;
7956
8192
  break;
7957
8193
  }
@@ -9843,7 +10079,8 @@ var StatusMonitor = class {
9843
10079
  };
9844
10080
 
9845
10081
  // src/providers/chat-message-normalization.ts
9846
- function extractFinalSummaryFromMessages(messages, maxChars = 500) {
10082
+ var DEFAULT_FINAL_SUMMARY_MAX_CHARS = 4e3;
10083
+ function extractFinalSummaryFromMessages(messages, maxChars = DEFAULT_FINAL_SUMMARY_MAX_CHARS) {
9847
10084
  if (!Array.isArray(messages) || messages.length === 0) return "";
9848
10085
  for (let i = messages.length - 1; i >= 0; i--) {
9849
10086
  const msg = messages[i];
@@ -17103,7 +17340,7 @@ var DaemonCommandHandler = class {
17103
17340
  var os13 = __toESM(require("os"));
17104
17341
  var path18 = __toESM(require("path"));
17105
17342
  var crypto4 = __toESM(require("crypto"));
17106
- var import_fs8 = require("fs");
17343
+ var import_fs9 = require("fs");
17107
17344
  var import_child_process6 = require("child_process");
17108
17345
  var import_chalk = __toESM(require("chalk"));
17109
17346
  init_provider_cli_adapter();
@@ -19575,7 +19812,7 @@ function commandExists(command) {
19575
19812
  const trimmed = command.trim();
19576
19813
  if (!trimmed) return false;
19577
19814
  if (isExplicitCommand(trimmed)) {
19578
- return (0, import_fs8.existsSync)(expandExecutable(trimmed));
19815
+ return (0, import_fs9.existsSync)(expandExecutable(trimmed));
19579
19816
  }
19580
19817
  try {
19581
19818
  (0, import_child_process6.execFileSync)(process.platform === "win32" ? "where" : "which", [trimmed], {
@@ -19604,10 +19841,10 @@ function hasCliArg(args, flag) {
19604
19841
  }
19605
19842
  function ensureEmptyDelegatedMcpConfig(workspace) {
19606
19843
  const baseDir = path18.join(os13.tmpdir(), "adhdev-delegated-agent-empty-mcp");
19607
- (0, import_fs8.mkdirSync)(baseDir, { recursive: true });
19844
+ (0, import_fs9.mkdirSync)(baseDir, { recursive: true });
19608
19845
  const workspaceHash = crypto4.createHash("sha256").update(path18.resolve(workspace || os13.tmpdir())).digest("hex").slice(0, 16);
19609
19846
  const filePath = path18.join(baseDir, `${workspaceHash}.json`);
19610
- (0, import_fs8.writeFileSync)(filePath, JSON.stringify({ mcpServers: {} }, null, 2), "utf-8");
19847
+ (0, import_fs9.writeFileSync)(filePath, JSON.stringify({ mcpServers: {} }, null, 2), "utf-8");
19611
19848
  return filePath;
19612
19849
  }
19613
19850
  function buildCoordinatorDelegatedCliLaunchOptions(input) {
@@ -23786,7 +24023,7 @@ async function maybeRunDaemonUpgradeHelperFromEnv() {
23786
24023
 
23787
24024
  // src/commands/router.ts
23788
24025
  var import_os3 = require("os");
23789
- var import_path6 = require("path");
24026
+ var import_path7 = require("path");
23790
24027
  var fs10 = __toESM(require("fs"));
23791
24028
  var CHANNEL_NPM_TAG = { stable: "latest", preview: "next" };
23792
24029
  var CHANNEL_SERVER_URL = {
@@ -23835,52 +24072,33 @@ function readBooleanValue(...values) {
23835
24072
  }
23836
24073
  return void 0;
23837
24074
  }
23838
- function buildCachedInlineMeshGitStatus(node) {
23839
- const cachedStatus = readObjectRecord(node?.cachedStatus);
23840
- const cachedGit = readObjectRecord(cachedStatus.git);
23841
- if (Object.keys(cachedGit).length) {
23842
- const conflictFiles2 = Array.isArray(cachedGit.conflictFiles) ? cachedGit.conflictFiles.filter((value) => typeof value === "string") : [];
23843
- const conflictCount2 = readNumberValue(cachedGit.conflicts) ?? conflictFiles2.length;
23844
- const hasConflicts2 = readBooleanValue(cachedGit.hasConflicts) ?? conflictCount2 > 0;
23845
- const isGitRepo2 = readBooleanValue(cachedGit.isGitRepo);
23846
- if (isGitRepo2 !== void 0) {
23847
- return {
23848
- workspace: readStringValue(cachedGit.workspace, node?.workspace) || "",
23849
- repoRoot: readStringValue(cachedGit.repoRoot, node?.repoRoot, node?.workspace) || null,
23850
- isGitRepo: isGitRepo2,
23851
- branch: readStringValue(cachedGit.branch) ?? null,
23852
- headCommit: readStringValue(cachedGit.headCommit) ?? null,
23853
- headMessage: readStringValue(cachedGit.headMessage) ?? null,
23854
- upstream: readStringValue(cachedGit.upstream) ?? null,
23855
- ahead: readNumberValue(cachedGit.ahead) ?? 0,
23856
- behind: readNumberValue(cachedGit.behind) ?? 0,
23857
- staged: readNumberValue(cachedGit.staged) ?? 0,
23858
- modified: readNumberValue(cachedGit.modified) ?? 0,
23859
- untracked: readNumberValue(cachedGit.untracked) ?? 0,
23860
- deleted: readNumberValue(cachedGit.deleted) ?? 0,
23861
- renamed: readNumberValue(cachedGit.renamed) ?? 0,
23862
- hasConflicts: hasConflicts2,
23863
- conflictFiles: conflictFiles2,
23864
- stashCount: readNumberValue(cachedGit.stashCount) ?? 0,
23865
- lastCheckedAt: readNumberValue(cachedGit.lastCheckedAt) ?? Date.now()
23866
- };
23867
- }
23868
- }
23869
- const rawGit = readObjectRecord(node?.lastGit ?? node?.last_git);
23870
- const gitResult = readObjectRecord(rawGit.result);
23871
- const directStatus = readObjectRecord(rawGit.status);
23872
- const nestedStatus = readObjectRecord(gitResult.status);
23873
- const rawProbe = readObjectRecord(node?.lastProbe ?? node?.last_probe);
23874
- const probeGit = readObjectRecord(rawProbe.git);
23875
- const probeGitResult = readObjectRecord(probeGit.result);
23876
- const probeDirectStatus = readObjectRecord(probeGit.status);
23877
- const probeNestedStatus = readObjectRecord(probeGitResult.status);
23878
- const status = Object.keys(directStatus).length ? directStatus : Object.keys(nestedStatus).length ? nestedStatus : Object.keys(probeDirectStatus).length ? probeDirectStatus : Object.keys(probeNestedStatus).length ? probeNestedStatus : {};
24075
+ function readGitSubmodules(value) {
24076
+ if (!Array.isArray(value)) return void 0;
24077
+ const submodules = value.map((entry) => {
24078
+ const submodule = readObjectRecord(entry);
24079
+ const path28 = readStringValue(submodule.path);
24080
+ const commit = readStringValue(submodule.commit);
24081
+ const repoPath = readStringValue(submodule.repoPath, submodule.repo_root);
24082
+ if (!path28 || !commit || !repoPath) return null;
24083
+ return {
24084
+ path: path28,
24085
+ commit,
24086
+ repoPath,
24087
+ dirty: readBooleanValue(submodule.dirty) ?? false,
24088
+ outOfSync: readBooleanValue(submodule.outOfSync, submodule.out_of_sync) ?? false,
24089
+ lastCheckedAt: readNumberValue(submodule.lastCheckedAt, submodule.last_checked_at) ?? Date.now(),
24090
+ ...readStringValue(submodule.error) ? { error: readStringValue(submodule.error) } : {}
24091
+ };
24092
+ }).filter((entry) => entry !== null);
24093
+ return submodules.length > 0 ? submodules : void 0;
24094
+ }
24095
+ function normalizeInlineMeshGitStatus(status, node, options) {
23879
24096
  const isGitRepo = readBooleanValue(status.isGitRepo);
23880
24097
  if (!Object.keys(status).length || isGitRepo === void 0) return void 0;
23881
24098
  const conflictFiles = Array.isArray(status.conflictFiles) ? status.conflictFiles.filter((value) => typeof value === "string") : [];
23882
24099
  const conflictCount = readNumberValue(status.conflicts) ?? conflictFiles.length;
23883
24100
  const hasConflicts = readBooleanValue(status.hasConflicts) ?? conflictCount > 0;
24101
+ const submodules = readGitSubmodules(status.submodules);
23884
24102
  return {
23885
24103
  workspace: readStringValue(status.workspace, node?.workspace) || "",
23886
24104
  repoRoot: readStringValue(status.repoRoot, node?.repoRoot, node?.workspace) || null,
@@ -23899,29 +24117,285 @@ function buildCachedInlineMeshGitStatus(node) {
23899
24117
  hasConflicts,
23900
24118
  conflictFiles,
23901
24119
  stashCount: readNumberValue(status.stashCount) ?? 0,
23902
- lastCheckedAt: Date.now()
24120
+ lastCheckedAt: options?.lastCheckedAt ?? readNumberValue(status.lastCheckedAt) ?? Date.now(),
24121
+ ...submodules ? { submodules } : {}
24122
+ };
24123
+ }
24124
+ function buildInlineMeshTransitGitStatus(node) {
24125
+ const rawGit = readObjectRecord(node?.lastGit ?? node?.last_git);
24126
+ const gitResult = readObjectRecord(rawGit.result);
24127
+ const directStatus = readObjectRecord(rawGit.status);
24128
+ const nestedStatus = readObjectRecord(gitResult.status);
24129
+ const rawProbe = readObjectRecord(node?.lastProbe ?? node?.last_probe);
24130
+ const probeGit = readObjectRecord(rawProbe.git);
24131
+ const probeGitResult = readObjectRecord(probeGit.result);
24132
+ const probeDirectStatus = readObjectRecord(probeGit.status);
24133
+ const probeNestedStatus = readObjectRecord(probeGitResult.status);
24134
+ const status = Object.keys(directStatus).length ? directStatus : Object.keys(nestedStatus).length ? nestedStatus : Object.keys(probeDirectStatus).length ? probeDirectStatus : Object.keys(probeNestedStatus).length ? probeNestedStatus : {};
24135
+ return normalizeInlineMeshGitStatus(status, node, { lastCheckedAt: Date.now() });
24136
+ }
24137
+ function buildCachedInlineMeshGitStatus(node) {
24138
+ const liveGit = buildInlineMeshTransitGitStatus(node);
24139
+ if (liveGit) return liveGit;
24140
+ const cachedStatus = readObjectRecord(node?.cachedStatus);
24141
+ const cachedGit = readObjectRecord(cachedStatus.git);
24142
+ if (!Object.keys(cachedGit).length) return void 0;
24143
+ return normalizeInlineMeshGitStatus(cachedGit, node);
24144
+ }
24145
+ function shouldDiscardCachedInlineMeshStatus(node) {
24146
+ const cachedStatus = readObjectRecord(node?.cachedStatus);
24147
+ if (!Object.keys(cachedStatus).length) return false;
24148
+ const cachedGit = readObjectRecord(cachedStatus.git);
24149
+ const workspaceError = readStringValue(cachedStatus.error, node?.error);
24150
+ if (workspaceError && /workspace must be an existing directory/i.test(workspaceError)) return true;
24151
+ const isGitRepo = readBooleanValue(cachedGit.isGitRepo);
24152
+ const branch = readStringValue(cachedGit.branch);
24153
+ const headCommit = readStringValue(cachedGit.headCommit);
24154
+ return isGitRepo === false && !branch && !headCommit;
24155
+ }
24156
+ function stripInlineMeshTransientNodeState(node) {
24157
+ if (!node || typeof node !== "object" || Array.isArray(node)) return node;
24158
+ const {
24159
+ cachedStatus,
24160
+ lastGit: _lastGit,
24161
+ last_git: _lastGitLegacy,
24162
+ lastProbe: _lastProbe,
24163
+ last_probe: _lastProbeLegacy,
24164
+ error: _error,
24165
+ health: _health,
24166
+ machineStatus: _machineStatus,
24167
+ lastSeenAt: _lastSeenAt,
24168
+ last_seen_at: _lastSeenAtLegacy,
24169
+ updatedAt: _updatedAt,
24170
+ updated_at: _updatedAtLegacy,
24171
+ activeSession: _activeSession,
24172
+ active_session: _activeSessionLegacy,
24173
+ activeSessionId: _activeSessionId,
24174
+ active_session_id: _activeSessionIdLegacy,
24175
+ sessionId: _sessionId,
24176
+ session_id: _sessionIdLegacy,
24177
+ providerType: _providerType,
24178
+ provider_type: _providerTypeLegacy,
24179
+ providers: _providers,
24180
+ ...rest
24181
+ } = node;
24182
+ if (cachedStatus && !shouldDiscardCachedInlineMeshStatus(node)) {
24183
+ return { ...rest, cachedStatus };
24184
+ }
24185
+ return rest;
24186
+ }
24187
+ function hasInlineMeshTransientNodeState(node) {
24188
+ if (!node || typeof node !== "object" || Array.isArray(node)) return false;
24189
+ return "cachedStatus" in node || "lastGit" in node || "last_git" in node || "lastProbe" in node || "last_probe" in node || "error" in node || "health" in node || "machineStatus" in node || "lastSeenAt" in node || "last_seen_at" in node || "updatedAt" in node || "updated_at" in node || "activeSession" in node || "active_session" in node || "activeSessionId" in node || "active_session_id" in node || "sessionId" in node || "session_id" in node || "providerType" in node || "provider_type" in node || "providers" in node;
24190
+ }
24191
+ function readInlineMeshNodeId(node) {
24192
+ return readStringValue(node?.id, node?.nodeId) || "";
24193
+ }
24194
+ function sanitizeInlineMesh(inlineMesh) {
24195
+ if (!inlineMesh || typeof inlineMesh !== "object" || Array.isArray(inlineMesh)) return inlineMesh;
24196
+ if (!Array.isArray(inlineMesh.nodes)) return inlineMesh;
24197
+ let changed = false;
24198
+ const nodes = inlineMesh.nodes.map((node) => {
24199
+ if (!hasInlineMeshTransientNodeState(node)) return node;
24200
+ changed = true;
24201
+ return stripInlineMeshTransientNodeState(node);
24202
+ });
24203
+ if (!changed) return inlineMesh;
24204
+ return {
24205
+ ...inlineMesh,
24206
+ nodes
23903
24207
  };
23904
24208
  }
23905
- function applyCachedInlineMeshNodeStatus(status, node) {
24209
+ function reconcileInlineMeshCache(cached, incoming) {
24210
+ if (!cached || typeof cached !== "object" || Array.isArray(cached)) return incoming;
24211
+ if (!incoming || typeof incoming !== "object" || Array.isArray(incoming)) return cached;
24212
+ const cachedNodes = Array.isArray(cached.nodes) ? cached.nodes : [];
24213
+ const incomingNodes = Array.isArray(incoming.nodes) ? incoming.nodes : [];
24214
+ if (!cachedNodes.length || !incomingNodes.length) return { ...cached, ...incoming };
24215
+ const incomingById = /* @__PURE__ */ new Map();
24216
+ for (const node of incomingNodes) {
24217
+ const nodeId = readInlineMeshNodeId(node);
24218
+ if (nodeId) incomingById.set(nodeId, node);
24219
+ }
24220
+ const nodes = cachedNodes.map((cachedNode) => {
24221
+ const nodeId = readInlineMeshNodeId(cachedNode);
24222
+ const incomingNode = nodeId ? incomingById.get(nodeId) : void 0;
24223
+ if (!incomingNode) return cachedNode;
24224
+ if (hasInlineMeshTransientNodeState(incomingNode)) {
24225
+ return { ...cachedNode, ...incomingNode };
24226
+ }
24227
+ return { ...stripInlineMeshTransientNodeState(cachedNode), ...incomingNode };
24228
+ });
24229
+ return {
24230
+ ...cached,
24231
+ ...incoming,
24232
+ nodes
24233
+ };
24234
+ }
24235
+ function hasGitWorktreeChanges(git) {
24236
+ if (!git) return false;
24237
+ return Number(git.staged || 0) + Number(git.modified || 0) + Number(git.untracked || 0) + Number(git.deleted || 0) + Number(git.renamed || 0) > 0;
24238
+ }
24239
+ function getGitSubmoduleDriftState(git) {
24240
+ const submodules = Array.isArray(git?.submodules) ? git.submodules : [];
24241
+ let dirty = false;
24242
+ let outOfSync = false;
24243
+ for (const entry of submodules) {
24244
+ const submodule = readObjectRecord(entry);
24245
+ if (readBooleanValue(submodule.dirty) === true) dirty = true;
24246
+ if (readBooleanValue(submodule.outOfSync) === true || !!readStringValue(submodule.error)) outOfSync = true;
24247
+ }
24248
+ return { dirty, outOfSync };
24249
+ }
24250
+ function deriveMeshNodeHealthFromGit(git) {
24251
+ if (!git || readBooleanValue(git.isGitRepo) === false) return "degraded";
24252
+ const branch = readStringValue(git.branch);
24253
+ if (!branch) return "degraded";
24254
+ const submoduleDrift = getGitSubmoduleDriftState(git);
24255
+ if (submoduleDrift.outOfSync) return "degraded";
24256
+ if (submoduleDrift.dirty || hasGitWorktreeChanges(git)) return "dirty";
24257
+ return "online";
24258
+ }
24259
+ function readCachedInlineMeshActiveSessions(node) {
24260
+ const cachedStatus = readObjectRecord(node?.cachedStatus);
24261
+ const activeSession = readObjectRecord(cachedStatus.activeSession);
24262
+ const fallbackSession = Object.keys(activeSession).length ? activeSession : readObjectRecord(node?.activeSession ?? node?.active_session);
24263
+ const sessionId = readStringValue(fallbackSession.id, fallbackSession.sessionId, fallbackSession.session_id, node?.activeSessionId, node?.active_session_id, node?.sessionId, node?.session_id);
24264
+ return sessionId ? [sessionId] : [];
24265
+ }
24266
+ function readCachedInlineMeshActiveSessionDetails(node) {
24267
+ const cachedStatus = readObjectRecord(node?.cachedStatus);
24268
+ const activeSession = readObjectRecord(cachedStatus.activeSession);
24269
+ const fallbackSession = Object.keys(activeSession).length ? activeSession : readObjectRecord(node?.activeSession ?? node?.active_session);
24270
+ const sessionId = readStringValue(
24271
+ fallbackSession.id,
24272
+ fallbackSession.sessionId,
24273
+ fallbackSession.session_id,
24274
+ node?.activeSessionId,
24275
+ node?.active_session_id,
24276
+ node?.sessionId,
24277
+ node?.session_id
24278
+ );
24279
+ if (!sessionId) return [];
24280
+ return [{
24281
+ sessionId,
24282
+ providerType: readStringValue(
24283
+ fallbackSession.providerType,
24284
+ fallbackSession.provider_type,
24285
+ fallbackSession.cliType,
24286
+ fallbackSession.cli_type,
24287
+ fallbackSession.provider,
24288
+ node?.providerType,
24289
+ node?.provider_type
24290
+ ),
24291
+ state: readStringValue(fallbackSession.status, fallbackSession.state, fallbackSession.lifecycle),
24292
+ lifecycle: readStringValue(fallbackSession.lifecycle),
24293
+ title: readStringValue(fallbackSession.title, fallbackSession.displayName, fallbackSession.display_name) ?? null,
24294
+ workspace: readStringValue(fallbackSession.workspace, node?.workspace) ?? null,
24295
+ lastActivityAt: readStringValue(fallbackSession.lastActivityAt, fallbackSession.last_activity_at) ?? null,
24296
+ recoveryState: readStringValue(fallbackSession.recoveryState, fallbackSession.recovery_state) ?? null,
24297
+ isCached: true
24298
+ }];
24299
+ }
24300
+ function readLiveMeshSessionState(record) {
24301
+ return readStringValue(
24302
+ record?.meta?.sessionStatus,
24303
+ record?.meta?.status,
24304
+ record?.meta?.providerStatus,
24305
+ record?.status,
24306
+ record?.state,
24307
+ record?.lifecycle
24308
+ );
24309
+ }
24310
+ function toIsoTimestamp(value) {
24311
+ if (typeof value === "number" && Number.isFinite(value)) return new Date(value).toISOString();
24312
+ const stringValue = readStringValue(value);
24313
+ return stringValue || null;
24314
+ }
24315
+ function summarizeMeshSessionRecord(record) {
24316
+ return {
24317
+ sessionId: readStringValue(record?.sessionId) || "unknown",
24318
+ providerType: readStringValue(record?.providerType),
24319
+ state: readLiveMeshSessionState(record),
24320
+ lifecycle: readStringValue(record?.lifecycle),
24321
+ surfaceKind: getSessionHostSurfaceKind(record),
24322
+ recoveryState: readStringValue(record?.meta?.runtimeRecoveryState) ?? null,
24323
+ workspace: readStringValue(record?.workspace) ?? null,
24324
+ title: readStringValue(record?.displayName, record?.workspaceLabel) ?? null,
24325
+ lastActivityAt: toIsoTimestamp(record?.updatedAt ?? record?.lastActivityAt ?? record?.last_activity_at),
24326
+ isCached: false
24327
+ };
24328
+ }
24329
+ function liveSessionRecordMatchesMeshNode(record, meshId, nodeId) {
24330
+ const recordNodeId = readStringValue(record?.meta?.meshNodeId);
24331
+ if (!recordNodeId || recordNodeId !== nodeId) return false;
24332
+ const recordMeshId = readStringValue(record?.meta?.meshNodeFor);
24333
+ return !recordMeshId || recordMeshId === meshId;
24334
+ }
24335
+ function liveSessionRecordMatchesMeshWorkspace(record, meshId, workspace) {
24336
+ const recordWorkspace = readStringValue(record?.workspace);
24337
+ if (!recordWorkspace || !workspace || recordWorkspace !== workspace) return false;
24338
+ const recordMeshId = readStringValue(record?.meta?.meshNodeFor);
24339
+ if (recordMeshId) return recordMeshId === meshId;
24340
+ return record?.meta?.launchedByCoordinator === true || !!readStringValue(record?.meta?.meshNodeId);
24341
+ }
24342
+ function readLiveMeshNodeWorkspace(args) {
24343
+ const directNodeWorkspace = args.liveSessionRecords.find((record) => liveSessionRecordMatchesMeshNode(record, args.meshId, args.nodeId) && readStringValue(record?.workspace));
24344
+ if (directNodeWorkspace) {
24345
+ return readStringValue(directNodeWorkspace.workspace) || "";
24346
+ }
24347
+ if (args.allowCoordinatorSession) {
24348
+ const coordinatorWorkspace = args.liveSessionRecords.find((record) => readStringValue(record?.meta?.meshCoordinatorFor) === args.meshId && readStringValue(record?.workspace));
24349
+ if (coordinatorWorkspace) {
24350
+ return readStringValue(coordinatorWorkspace.workspace) || "";
24351
+ }
24352
+ }
24353
+ return "";
24354
+ }
24355
+ function collectLiveMeshSessionRecords(args) {
24356
+ const matches = args.liveSessionRecords.filter((record) => {
24357
+ const nodeWorkspace = readStringValue(args.node?.workspace);
24358
+ if (liveSessionRecordMatchesMeshNode(record, args.meshId, args.nodeId)) return true;
24359
+ return !!nodeWorkspace && liveSessionRecordMatchesMeshWorkspace(record, args.meshId, nodeWorkspace);
24360
+ });
24361
+ if (args.allowCoordinatorSession) {
24362
+ for (const record of args.liveSessionRecords) {
24363
+ if (readStringValue(record?.meta?.meshCoordinatorFor) !== args.meshId) continue;
24364
+ const sessionId = readStringValue(record?.sessionId);
24365
+ if (sessionId && matches.some((entry) => readStringValue(entry?.sessionId) === sessionId)) continue;
24366
+ matches.push(record);
24367
+ }
24368
+ }
24369
+ return matches;
24370
+ }
24371
+ function applyCachedInlineMeshNodeStatus(status, node, options) {
23906
24372
  const cachedStatus = readObjectRecord(node?.cachedStatus);
23907
- const git = buildCachedInlineMeshGitStatus(node);
23908
- const error = readStringValue(cachedStatus.error, node?.error);
23909
- const health = readStringValue(cachedStatus.health, node?.health);
24373
+ const liveGit = buildInlineMeshTransitGitStatus(node);
24374
+ const git = options?.skipGit ? void 0 : liveGit ?? buildCachedInlineMeshGitStatus(node);
24375
+ const error = options?.skipError ? void 0 : liveGit ? void 0 : readStringValue(cachedStatus.error, node?.error);
24376
+ const health = options?.skipHealth ? void 0 : liveGit ? void 0 : readStringValue(cachedStatus.health, node?.health);
23910
24377
  const machineStatus = readStringValue(cachedStatus.machineStatus, node?.machineStatus);
23911
- if (!git && !error && !health) return false;
23912
- if (!machineStatus && !git && !error) return false;
24378
+ const lastSeenAt = toIsoTimestamp(cachedStatus.lastSeenAt ?? cachedStatus.last_seen_at ?? node?.lastSeenAt ?? node?.last_seen_at);
24379
+ const updatedAt = toIsoTimestamp(cachedStatus.updatedAt ?? cachedStatus.updated_at ?? node?.updatedAt ?? node?.updated_at);
24380
+ const activeSessions = readCachedInlineMeshActiveSessions(node);
24381
+ const activeSessionDetails = readCachedInlineMeshActiveSessionDetails(node);
24382
+ if (!git && !error && !health && !machineStatus && !lastSeenAt && !updatedAt && activeSessions.length === 0) return false;
23913
24383
  if (git) status.git = git;
23914
24384
  if (error) status.error = error;
24385
+ if (machineStatus) status.machineStatus = machineStatus;
24386
+ if (lastSeenAt) status.lastSeenAt = lastSeenAt;
24387
+ if (updatedAt) status.updatedAt = updatedAt;
24388
+ if (activeSessions.length > 0) status.activeSessions = activeSessions;
24389
+ if (activeSessionDetails.length > 0) status.activeSessionDetails = activeSessionDetails;
23915
24390
  if (health) {
23916
24391
  status.health = health;
23917
24392
  return true;
23918
24393
  }
23919
24394
  if (git) {
23920
- const dirty = Number(git.staged || 0) + Number(git.modified || 0) + Number(git.untracked || 0) + Number(git.deleted || 0) + Number(git.renamed || 0) > 0;
23921
- status.health = git.isGitRepo === false ? "degraded" : dirty ? "dirty" : "online";
24395
+ status.health = deriveMeshNodeHealthFromGit(git);
23922
24396
  return true;
23923
24397
  }
23924
- return false;
24398
+ return activeSessions.length > 0 || !!machineStatus || !!lastSeenAt || !!updatedAt;
23925
24399
  }
23926
24400
  async function resolveProviderTypeFromPriority(args) {
23927
24401
  if (!args.providerPriority.length) {
@@ -23959,7 +24433,7 @@ function truncateValidationOutput(value) {
23959
24433
  }
23960
24434
  function readPackageScripts(workspace) {
23961
24435
  try {
23962
- const packageJsonPath = (0, import_path6.join)(workspace, "package.json");
24436
+ const packageJsonPath = (0, import_path7.join)(workspace, "package.json");
23963
24437
  const parsed = JSON.parse(fs10.readFileSync(packageJsonPath, "utf-8"));
23964
24438
  return parsed?.scripts && typeof parsed.scripts === "object" && !Array.isArray(parsed.scripts) ? parsed.scripts : {};
23965
24439
  } catch {
@@ -24167,13 +24641,13 @@ function serializeMeshCoordinatorMcpConfig(config, format) {
24167
24641
  }
24168
24642
  function resolveHermesUserHome() {
24169
24643
  const explicitHome = process.env.HERMES_HOME?.trim();
24170
- return explicitHome || (0, import_path6.join)((0, import_os3.homedir)(), ".hermes");
24644
+ return explicitHome || (0, import_path7.join)((0, import_os3.homedir)(), ".hermes");
24171
24645
  }
24172
24646
  function loadHermesCoordinatorBaseConfig(targetConfigPath) {
24173
24647
  const sourceHome = resolveHermesUserHome();
24174
- const sourceConfigPath = (0, import_path6.join)(sourceHome, "config.yaml");
24648
+ const sourceConfigPath = (0, import_path7.join)(sourceHome, "config.yaml");
24175
24649
  if (!fs10.existsSync(sourceConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
24176
- if ((0, import_path6.resolve)(sourceConfigPath) === (0, import_path6.resolve)(targetConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
24650
+ if ((0, import_path7.resolve)(sourceConfigPath) === (0, import_path7.resolve)(targetConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
24177
24651
  const parsed = parseMeshCoordinatorMcpConfig(fs10.readFileSync(sourceConfigPath, "utf-8"), "hermes_config_yaml");
24178
24652
  const { mcp_servers: _mcpServers, ...baseConfig } = parsed;
24179
24653
  return { config: baseConfig, sourceHome, sourceConfigPath };
@@ -24207,10 +24681,10 @@ function stripHermesCoordinatorTempModelProviderOverrides(config) {
24207
24681
  return sanitized;
24208
24682
  }
24209
24683
  function copyHermesCoordinatorCredentialFiles(sourceHome, targetHome) {
24210
- if ((0, import_path6.resolve)(sourceHome) === (0, import_path6.resolve)(targetHome)) return;
24684
+ if ((0, import_path7.resolve)(sourceHome) === (0, import_path7.resolve)(targetHome)) return;
24211
24685
  for (const fileName of [".env", "auth.json"]) {
24212
- const sourcePath = (0, import_path6.join)(sourceHome, fileName);
24213
- const targetPath = (0, import_path6.join)(targetHome, fileName);
24686
+ const sourcePath = (0, import_path7.join)(sourceHome, fileName);
24687
+ const targetPath = (0, import_path7.join)(targetHome, fileName);
24214
24688
  if (!fs10.existsSync(sourcePath)) continue;
24215
24689
  try {
24216
24690
  fs10.copyFileSync(sourcePath, targetPath);
@@ -24319,25 +24793,40 @@ var DaemonCommandRouter = class {
24319
24793
  }
24320
24794
  getCachedInlineMesh(meshId, inlineMesh) {
24321
24795
  if (inlineMesh && typeof inlineMesh === "object") {
24322
- this.inlineMeshCache.set(meshId, inlineMesh);
24323
- return inlineMesh;
24796
+ return this.warmInlineMeshCache(meshId, inlineMesh);
24324
24797
  }
24325
24798
  return this.inlineMeshCache.get(meshId);
24326
24799
  }
24800
+ warmInlineMeshCache(meshId, inlineMesh) {
24801
+ if (!inlineMesh || typeof inlineMesh !== "object") return void 0;
24802
+ const sanitizedInlineMesh = sanitizeInlineMesh(inlineMesh);
24803
+ const cached = this.inlineMeshCache.get(meshId);
24804
+ if (cached) {
24805
+ const merged = reconcileInlineMeshCache(cached, sanitizedInlineMesh);
24806
+ this.inlineMeshCache.set(meshId, merged);
24807
+ return merged;
24808
+ }
24809
+ this.inlineMeshCache.set(meshId, sanitizedInlineMesh);
24810
+ return sanitizedInlineMesh;
24811
+ }
24327
24812
  async getMeshForCommand(meshId, inlineMesh, options) {
24328
24813
  const preferInline = options?.preferInline === true;
24329
24814
  if (preferInline) {
24330
- const cached2 = this.getCachedInlineMesh(meshId, inlineMesh);
24331
- if (cached2) return { mesh: cached2, inline: true };
24815
+ const cached2 = this.getCachedInlineMesh(meshId);
24816
+ if (cached2) return { mesh: cached2, inline: true, source: "inline_cache" };
24817
+ const warmedInline2 = this.warmInlineMeshCache(meshId, inlineMesh);
24818
+ if (warmedInline2) return { mesh: warmedInline2, inline: true, source: "inline_bootstrap" };
24332
24819
  }
24333
24820
  try {
24334
24821
  const { getMesh: getMesh3 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
24335
24822
  const mesh = getMesh3(meshId);
24336
- if (mesh) return { mesh, inline: false };
24823
+ if (mesh) return { mesh, inline: false, source: "local_config" };
24337
24824
  } catch {
24338
24825
  }
24339
- const cached = this.getCachedInlineMesh(meshId, inlineMesh);
24340
- return cached ? { mesh: cached, inline: true } : null;
24826
+ const cached = this.getCachedInlineMesh(meshId);
24827
+ if (cached) return { mesh: cached, inline: true, source: "inline_cache" };
24828
+ const warmedInline = this.warmInlineMeshCache(meshId, inlineMesh);
24829
+ return warmedInline ? { mesh: warmedInline, inline: true, source: "inline_bootstrap" } : null;
24341
24830
  }
24342
24831
  updateInlineMeshNode(meshId, mesh, node) {
24343
24832
  if (!mesh || !Array.isArray(mesh.nodes) || !node?.id) return;
@@ -24402,7 +24891,7 @@ var DaemonCommandRouter = class {
24402
24891
  }
24403
24892
  const { resolveWorktreePath: resolveWorktreePath2, listWorktrees: listWorktrees2, removeWorktree: removeWorktree2 } = await Promise.resolve().then(() => (init_git_worktree(), git_worktree_exports));
24404
24893
  const normalizePath = (value) => {
24405
- const resolved = (0, import_path6.resolve)(value);
24894
+ const resolved = (0, import_path7.resolve)(value);
24406
24895
  try {
24407
24896
  return fs10.realpathSync(resolved);
24408
24897
  } catch {
@@ -24566,6 +25055,7 @@ var DaemonCommandRouter = class {
24566
25055
  const deletedSessionIds = [];
24567
25056
  const skippedSessionIds = [];
24568
25057
  const skippedLiveSessionIds = [];
25058
+ const skippedCoordinatorSessionIds = [];
24569
25059
  const deleteUnsupportedSessionIds = [];
24570
25060
  const recordsRemainSessionIds = [];
24571
25061
  const errors = [];
@@ -24598,6 +25088,12 @@ var DaemonCommandRouter = class {
24598
25088
  const completed = this.isCompletedHostedSession(record);
24599
25089
  const surfaceKind = getSessionHostSurfaceKind(record);
24600
25090
  const liveRuntime = surfaceKind === "live_runtime";
25091
+ const coordinatorSession = readStringValue(record?.meta?.meshCoordinatorFor) === args.meshId;
25092
+ if (!hasExplicitSessionIds && coordinatorSession) {
25093
+ skippedSessionIds.push(sessionId);
25094
+ skippedCoordinatorSessionIds.push(sessionId);
25095
+ continue;
25096
+ }
24601
25097
  if (!hasExplicitSessionIds && liveRuntime) {
24602
25098
  skippedSessionIds.push(sessionId);
24603
25099
  skippedLiveSessionIds.push(sessionId);
@@ -24663,6 +25159,7 @@ var DaemonCommandRouter = class {
24663
25159
  deletedSessionIds,
24664
25160
  skippedSessionIds,
24665
25161
  skippedLiveSessionIds,
25162
+ skippedCoordinatorSessionIds,
24666
25163
  ...deleteUnsupported ? {
24667
25164
  deleteUnsupported: true,
24668
25165
  effectiveCleanup: args.mode === "stop_and_delete" ? "stopped_only_records_remain" : "delete_unsupported_records_remain",
@@ -24795,7 +25292,8 @@ var DaemonCommandRouter = class {
24795
25292
  return handleMeshForwardEvent({ instanceManager: this.deps.instanceManager }, args);
24796
25293
  }
24797
25294
  case "get_pending_mesh_events": {
24798
- const events = drainPendingMeshCoordinatorEvents();
25295
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
25296
+ const events = drainPendingMeshCoordinatorEvents(meshId || void 0);
24799
25297
  return { success: true, events };
24800
25298
  }
24801
25299
  case "launch_cli":
@@ -25324,14 +25822,8 @@ var DaemonCommandRouter = class {
25324
25822
  case "get_mesh": {
25325
25823
  const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
25326
25824
  if (!meshId) return { success: false, error: "meshId required" };
25327
- try {
25328
- const { getMesh: getMesh3 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
25329
- const mesh = getMesh3(meshId);
25330
- if (mesh) return { success: true, mesh };
25331
- } catch {
25332
- }
25333
- const cached = this.inlineMeshCache.get(meshId);
25334
- if (cached) return { success: true, mesh: cached };
25825
+ const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
25826
+ if (meshRecord?.mesh) return { success: true, mesh: meshRecord.mesh };
25335
25827
  return { success: false, error: "Mesh not found" };
25336
25828
  }
25337
25829
  case "create_mesh": {
@@ -25853,7 +26345,14 @@ var DaemonCommandRouter = class {
25853
26345
  cliType
25854
26346
  };
25855
26347
  }
25856
- const workspace = typeof coordinatorNode.workspace === "string" ? coordinatorNode.workspace.trim() : "";
26348
+ const sessionHostRecords = this.deps.sessionHostControl?.listSessions ? await this.deps.sessionHostControl.listSessions().catch(() => []) : [];
26349
+ const liveMeshSessions = partitionSessionHostRecords(Array.isArray(sessionHostRecords) ? sessionHostRecords : []).liveRuntimes;
26350
+ const workspace = readLiveMeshNodeWorkspace({
26351
+ meshId,
26352
+ nodeId: String(coordinatorNode.id || coordinatorNode.nodeId || preferredCoordinatorNodeId || ""),
26353
+ liveSessionRecords: liveMeshSessions,
26354
+ allowCoordinatorSession: true
26355
+ }) || (typeof coordinatorNode.workspace === "string" ? coordinatorNode.workspace.trim() : "");
25857
26356
  if (!workspace) return { success: false, error: "Coordinator node workspace required", meshId, cliType };
25858
26357
  if (!cliType) {
25859
26358
  const resolved = await resolveProviderTypeFromPriority({
@@ -26015,7 +26514,7 @@ ${block}`);
26015
26514
  workspace
26016
26515
  };
26017
26516
  }
26018
- const { existsSync: existsSync25, readFileSync: readFileSync17, writeFileSync: writeFileSync15, copyFileSync: copyFileSync4, mkdirSync: mkdirSync17 } = await import("fs");
26517
+ const { existsSync: existsSync26, readFileSync: readFileSync18, writeFileSync: writeFileSync15, copyFileSync: copyFileSync4, mkdirSync: mkdirSync17 } = await import("fs");
26019
26518
  const { dirname: dirname9 } = await import("path");
26020
26519
  const mcpConfigPath = coordinatorSetup.configPath;
26021
26520
  const hermesManualFallback = cliType === "hermes-cli" && configFormat === "hermes_config_yaml" ? createHermesManualMeshCoordinatorSetup(meshId, workspace) : null;
@@ -26058,14 +26557,14 @@ ${block}`);
26058
26557
  if (hermesManualFallback) return returnManualFallback(message);
26059
26558
  return { success: false, code: "mesh_coordinator_config_write_failed", error: message, meshId, cliType, workspace };
26060
26559
  }
26061
- const hadExistingMcpConfig = existsSync25(mcpConfigPath);
26560
+ const hadExistingMcpConfig = existsSync26(mcpConfigPath);
26062
26561
  let existingMcpConfig = hermesBaseConfig?.config || {};
26063
26562
  if (hermesBaseConfig) {
26064
26563
  copyHermesCoordinatorCredentialFiles(hermesBaseConfig.sourceHome, dirname9(mcpConfigPath));
26065
26564
  }
26066
26565
  if (hadExistingMcpConfig) {
26067
26566
  try {
26068
- const parsedExistingMcpConfig = parseMeshCoordinatorMcpConfig(readFileSync17(mcpConfigPath, "utf-8"), configFormat);
26567
+ const parsedExistingMcpConfig = parseMeshCoordinatorMcpConfig(readFileSync18(mcpConfigPath, "utf-8"), configFormat);
26069
26568
  const existingCoordinatorConfig = hermesManualFallback ? stripHermesCoordinatorTempModelProviderOverrides(parsedExistingMcpConfig) : parsedExistingMcpConfig;
26070
26569
  existingMcpConfig = { ...existingMcpConfig, ...existingCoordinatorConfig };
26071
26570
  copyFileSync4(mcpConfigPath, mcpConfigPath + ".backup");
@@ -26161,92 +26660,157 @@ ${block}`);
26161
26660
  const { readLedgerEntries: readLedgerEntries2, getLedgerSummary: getLedgerSummary2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
26162
26661
  const ledgerEntries = readLedgerEntries2(meshId, { tail: 20 });
26163
26662
  const ledgerSummary = getLedgerSummary2(meshId);
26663
+ const sessionHostRecords = this.deps.sessionHostControl?.listSessions ? await this.deps.sessionHostControl.listSessions().catch(() => []) : [];
26664
+ const liveMeshSessions = partitionSessionHostRecords(Array.isArray(sessionHostRecords) ? sessionHostRecords : []).liveRuntimes;
26665
+ const localMachineId = loadConfig().machineId || "";
26666
+ const selectedCoordinatorNodeId = readStringValue(
26667
+ mesh.coordinator?.preferredNodeId,
26668
+ mesh.nodes?.[0]?.id,
26669
+ mesh.nodes?.[0]?.nodeId
26670
+ );
26671
+ const inlineCoordinatorNodeId = meshRecord?.inline && Array.isArray(mesh.nodes) ? selectedCoordinatorNodeId : void 0;
26672
+ const refreshedAt = (/* @__PURE__ */ new Date()).toISOString();
26164
26673
  const nodeStatuses = [];
26165
- for (const node of mesh.nodes || []) {
26674
+ for (const [nodeIndex, node] of (mesh.nodes || []).entries()) {
26675
+ const nodeId = String(node.id || node.nodeId || "");
26676
+ const daemonId = readStringValue(node.daemonId);
26677
+ const providerPriority = readProviderPriorityFromPolicy(node.policy);
26678
+ const isSelfNode = Boolean(
26679
+ nodeId && inlineCoordinatorNodeId && nodeId === inlineCoordinatorNodeId
26680
+ ) || Boolean(
26681
+ daemonId && (daemonId === localMachineId || daemonId === this.deps.statusInstanceId)
26682
+ ) || Boolean(meshRecord?.inline && nodeIndex === 0);
26166
26683
  const status = {
26167
- nodeId: node.id || node.nodeId,
26684
+ nodeId,
26168
26685
  machineLabel: node.machineLabel || node.id || node.nodeId,
26169
26686
  workspace: node.workspace,
26170
26687
  repoRoot: node.repoRoot,
26171
26688
  isLocalWorktree: node.isLocalWorktree,
26172
26689
  worktreeBranch: node.worktreeBranch,
26173
- daemonId: node.daemonId,
26690
+ daemonId,
26174
26691
  machineId: node.machineId,
26692
+ machineStatus: node.machineStatus,
26175
26693
  health: "unknown",
26176
26694
  providers: node.providers || [],
26177
- activeSessions: []
26695
+ providerPriority,
26696
+ activeSessions: [],
26697
+ activeSessionDetails: [],
26698
+ launchReady: false
26178
26699
  };
26179
- if (node.workspace && typeof node.workspace === "string") {
26180
- if (!fs10.existsSync(node.workspace) && applyCachedInlineMeshNodeStatus(status, node)) {
26181
- nodeStatuses.push(status);
26182
- continue;
26700
+ if (isSelfNode) {
26701
+ status.connection = {
26702
+ perspective: "selected_coordinator",
26703
+ source: "mesh_peer_status",
26704
+ state: "self",
26705
+ transport: "local",
26706
+ reported: true,
26707
+ reason: "Selected coordinator daemon",
26708
+ lastStateChangeAt: refreshedAt
26709
+ };
26710
+ } else if (daemonId) {
26711
+ const connection = this.deps.getMeshPeerConnectionStatus?.(daemonId);
26712
+ status.connection = connection ?? {
26713
+ perspective: "selected_coordinator",
26714
+ source: "not_reported",
26715
+ state: "unknown",
26716
+ transport: "unknown",
26717
+ reported: false,
26718
+ reason: "No live mesh peer telemetry reported by the selected coordinator yet."
26719
+ };
26720
+ } else {
26721
+ status.connection = {
26722
+ perspective: "selected_coordinator",
26723
+ source: "not_reported",
26724
+ state: "unknown",
26725
+ transport: "unknown",
26726
+ reported: false,
26727
+ reason: "Node has no daemon id, so mesh transport cannot be reported from the selected coordinator."
26728
+ };
26729
+ }
26730
+ const matchedLiveSessionRecords = collectLiveMeshSessionRecords({
26731
+ meshId,
26732
+ node,
26733
+ nodeId,
26734
+ liveSessionRecords: liveMeshSessions,
26735
+ allowCoordinatorSession: nodeId === selectedCoordinatorNodeId
26736
+ });
26737
+ const workspace = readLiveMeshNodeWorkspace({
26738
+ meshId,
26739
+ nodeId,
26740
+ liveSessionRecords: matchedLiveSessionRecords,
26741
+ allowCoordinatorSession: nodeId === selectedCoordinatorNodeId
26742
+ }) || (typeof node.workspace === "string" ? node.workspace : "");
26743
+ status.workspace = workspace || node.workspace;
26744
+ if (matchedLiveSessionRecords.length > 0) {
26745
+ const sessionIds = matchedLiveSessionRecords.map((record) => typeof record?.sessionId === "string" ? record.sessionId : "").filter(Boolean);
26746
+ const providerTypes = matchedLiveSessionRecords.map((record) => readStringValue(record?.providerType)).filter(Boolean);
26747
+ status.activeSessions = sessionIds;
26748
+ status.activeSessionDetails = matchedLiveSessionRecords.map(summarizeMeshSessionRecord);
26749
+ if (providerTypes.length > 0) {
26750
+ status.providers = Array.from(/* @__PURE__ */ new Set([...Array.isArray(status.providers) ? status.providers : [], ...providerTypes]));
26183
26751
  }
26184
- try {
26185
- const { execFile: execFile3 } = await import("child_process");
26186
- const { promisify: promisify3 } = await import("util");
26187
- const execFileAsync3 = promisify3(execFile3);
26188
- const runGit2 = async (args2) => {
26189
- const result = await execFileAsync3("git", ["-C", node.workspace, ...args2], {
26190
- encoding: "utf8",
26191
- timeout: 1e4
26192
- });
26193
- return result.stdout.trim();
26194
- };
26195
- const branch = await runGit2(["branch", "--show-current"]).catch(() => "");
26196
- const porc = await runGit2(["status", "--porcelain"]).catch(() => "");
26197
- const headCommit = await runGit2(["rev-parse", "--short", "HEAD"]).catch(() => null);
26198
- const headMessage = await runGit2(["log", "-1", "--format=%s"]).catch(() => null);
26199
- const upstream = await runGit2(["rev-parse", "--abbrev-ref", "@{upstream}"]).catch(() => null);
26200
- const aheadBehind = await runGit2(["rev-list", "--left-right", "--count", "@{upstream}...HEAD"]).catch(() => "");
26201
- const stashCount = await runGit2(["stash", "list"]).catch(() => "");
26202
- let ahead = 0, behind = 0;
26203
- if (aheadBehind) {
26204
- const parts = aheadBehind.split(/\s+/);
26205
- if (parts.length >= 2) {
26206
- behind = parseInt(parts[0], 10) || 0;
26207
- ahead = parseInt(parts[1], 10) || 0;
26752
+ }
26753
+ if (workspace) {
26754
+ if (!fs10.existsSync(workspace)) {
26755
+ let remoteProbeApplied = false;
26756
+ if (!isSelfNode && daemonId && this.deps.dispatchMeshCommand) {
26757
+ try {
26758
+ const remoteResult = await Promise.race([
26759
+ this.deps.dispatchMeshCommand(daemonId, "git_status", { workspace }),
26760
+ new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 8e3))
26761
+ ]);
26762
+ const remoteGit = remoteResult?.status ?? remoteResult?.git ?? remoteResult;
26763
+ if (remoteGit && typeof remoteGit === "object" && typeof remoteGit.isGitRepo === "boolean") {
26764
+ status.git = remoteGit;
26765
+ status.health = remoteGit.isGitRepo ? deriveMeshNodeHealthFromGit(remoteGit) : "degraded";
26766
+ remoteProbeApplied = true;
26767
+ }
26768
+ } catch {
26208
26769
  }
26209
26770
  }
26210
- const dirty = porc.length > 0;
26211
- const lines = porc ? porc.split("\n").filter(Boolean) : [];
26212
- let staged = 0, modified = 0, untracked = 0, deleted = 0, renamed = 0;
26213
- for (const line of lines) {
26214
- const xy = line.slice(0, 2);
26215
- if (xy[0] !== " " && xy[0] !== "?") staged++;
26216
- if (xy[1] === "M") modified++;
26217
- if (xy[1] === "D") deleted++;
26218
- if (xy[0] === "R" || xy[1] === "R") renamed++;
26219
- if (xy === "??") untracked++;
26771
+ if (!remoteProbeApplied) {
26772
+ const connectionState = readStringValue(status.connection?.state);
26773
+ const inlineTransitGit = buildInlineMeshTransitGitStatus(node);
26774
+ const pendingPeerGitProbe = !inlineTransitGit && !isSelfNode && !!daemonId && (readStringValue(status.machineStatus) === "online" || readStringValue(status.health) === "online" || connectionState === "connecting" || connectionState === "connected" || connectionState === "unknown");
26775
+ if (pendingPeerGitProbe) {
26776
+ status.gitProbePending = true;
26777
+ status.health = "unknown";
26778
+ }
26779
+ if (applyCachedInlineMeshNodeStatus(
26780
+ status,
26781
+ node,
26782
+ pendingPeerGitProbe ? { skipGit: true, skipError: true, skipHealth: true } : void 0
26783
+ )) {
26784
+ status.launchReady = !!daemonId && (readStringValue(status.machineStatus) === "online" || isSelfNode);
26785
+ nodeStatuses.push(status);
26786
+ continue;
26787
+ }
26788
+ if (meshRecord?.source === "inline_cache" && !isSelfNode) {
26789
+ status.launchReady = !!daemonId && (readStringValue(status.machineStatus) === "online" || isSelfNode);
26790
+ nodeStatuses.push(status);
26791
+ continue;
26792
+ }
26220
26793
  }
26221
- status.git = {
26222
- workspace: node.workspace,
26223
- repoRoot: node.workspace,
26224
- isGitRepo: true,
26225
- branch: branch || null,
26226
- headCommit,
26227
- headMessage,
26228
- upstream,
26229
- ahead,
26230
- behind,
26231
- staged,
26232
- modified,
26233
- untracked,
26234
- deleted,
26235
- renamed,
26236
- hasConflicts: false,
26237
- conflictFiles: [],
26238
- stashCount: stashCount ? stashCount.split("\n").filter(Boolean).length : 0,
26239
- lastCheckedAt: Date.now()
26240
- };
26241
- status.health = branch ? dirty ? "dirty" : "online" : "degraded";
26242
- } catch {
26243
- if (!applyCachedInlineMeshNodeStatus(status, node)) {
26244
- status.health = "degraded";
26794
+ } else {
26795
+ try {
26796
+ const gitStatus = await getGitRepoStatus(workspace, { timeoutMs: 1e4, refreshUpstream: true });
26797
+ status.git = gitStatus;
26798
+ if (gitStatus.isGitRepo) {
26799
+ status.health = deriveMeshNodeHealthFromGit(gitStatus);
26800
+ } else {
26801
+ status.health = "degraded";
26802
+ if (gitStatus.error && !status.error) status.error = gitStatus.error;
26803
+ }
26804
+ } catch {
26805
+ if (!applyCachedInlineMeshNodeStatus(status, node)) {
26806
+ status.health = "degraded";
26807
+ }
26245
26808
  }
26246
26809
  }
26247
26810
  } else {
26248
26811
  applyCachedInlineMeshNodeStatus(status, node);
26249
26812
  }
26813
+ status.launchReady = !!daemonId && (readStringValue(status.machineStatus) === "online" || isSelfNode);
26250
26814
  nodeStatuses.push(status);
26251
26815
  }
26252
26816
  return {
@@ -26255,6 +26819,12 @@ ${block}`);
26255
26819
  meshName: mesh.name,
26256
26820
  repoIdentity: mesh.repoIdentity,
26257
26821
  defaultBranch: mesh.defaultBranch,
26822
+ refreshedAt: (/* @__PURE__ */ new Date()).toISOString(),
26823
+ sourceOfTruth: {
26824
+ membership: meshRecord?.source === "inline_cache" ? "coordinator_inline_mesh_cache" : meshRecord?.source === "local_config" ? "local_mesh_config" : "inline_bootstrap_snapshot",
26825
+ coordinatorOwnsLiveTruth: meshRecord?.source !== "inline_bootstrap",
26826
+ historicalEvidenceOnly: ["recoveryHints", "ledger.summary", "queue.summary"]
26827
+ },
26258
26828
  nodes: nodeStatuses,
26259
26829
  queue: { tasks: queue, summary: queueSummary },
26260
26830
  ledger: { entries: ledgerEntries, summary: ledgerSummary }
@@ -34184,6 +34754,7 @@ async function initDaemonComponents(config) {
34184
34754
  sessionHostControl: config.sessionHostControl,
34185
34755
  statusInstanceId: config.statusInstanceId,
34186
34756
  statusVersion: config.statusVersion,
34757
+ getMeshPeerConnectionStatus: config.getMeshPeerConnectionStatus,
34187
34758
  getCdpLogFn: config.getCdpLogFn || ((ideType) => LOG.forComponent(`CDP:${ideType}`).asLogFn())
34188
34759
  });
34189
34760
  poller = new AgentStreamPoller({
@@ -34459,6 +35030,7 @@ async function shutdownDaemonComponents(components) {
34459
35030
  prepareSessionChatTailUpdate,
34460
35031
  prepareSessionModalUpdate,
34461
35032
  probeCdpPort,
35033
+ queuePendingMeshCoordinatorEvent,
34462
35034
  readChatHistory,
34463
35035
  readLedgerEntries,
34464
35036
  readLedgerSlice,