@adhdev/daemon-standalone 0.9.77-rc.3 → 0.9.77-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/public/index.html CHANGED
@@ -7,7 +7,7 @@
7
7
  <meta name="description" content="ADHDev self-hosted dashboard for controlling AI agents" />
8
8
  <link rel="icon" href="/otter-logo.png" />
9
9
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet" />
10
- <script type="module" crossorigin src="/assets/index-6WEc6L46.js"></script>
10
+ <script type="module" crossorigin src="/assets/index-CWWeDAva.js"></script>
11
11
  <link rel="modulepreload" crossorigin href="/assets/vendor-CLec0455.js">
12
12
  <link rel="stylesheet" crossorigin href="/assets/index-DftJ2WZr.css">
13
13
  </head>
@@ -26256,22 +26256,47 @@ function formatCompletionMetadata(event) {
26256
26256
  ].filter(Boolean);
26257
26257
  return parts.length > 0 ? ` (${parts.join("; ")})` : "";
26258
26258
  }
26259
+ function getMeshWithCache(components, meshId) {
26260
+ const localMesh = getMesh(meshId);
26261
+ if (localMesh) return localMesh;
26262
+ return components.router?.getCachedInlineMesh(meshId);
26263
+ }
26259
26264
  function tryAssignQueueTask(components, meshId, nodeId, sessionId, providerType) {
26260
26265
  const task = claimNextTask(meshId, nodeId, sessionId);
26261
- if (!task) return false;
26266
+ if (!task) {
26267
+ return false;
26268
+ }
26262
26269
  LOG.info("MeshQueue", `Node ${nodeId} (${sessionId}) pulled task ${task.id}`);
26270
+ const mesh = getMeshWithCache(components, meshId);
26271
+ const node = mesh?.nodes.find((n) => n.id === nodeId);
26272
+ if (node?.daemonId && components.dispatchMeshCommand) {
26273
+ const isLocalNode = components.cliManager.adapters.has(sessionId);
26274
+ if (!isLocalNode) {
26275
+ components.dispatchMeshCommand(node.daemonId, "agent_command", {
26276
+ targetSessionId: sessionId,
26277
+ cliType: providerType,
26278
+ action: "send_chat",
26279
+ message: task.message
26280
+ }).catch((e) => {
26281
+ LOG.error("MeshQueue", `Failed to dispatch task via P2P to remote node ${nodeId}: ${e?.message}`);
26282
+ updateTaskStatus(meshId, task.id, "failed");
26283
+ });
26284
+ return true;
26285
+ }
26286
+ }
26263
26287
  components.cliManager.handleCliCommand("agent_command", {
26264
26288
  targetSessionId: sessionId,
26265
26289
  cliType: providerType,
26266
26290
  action: "send_chat",
26267
- input: task.message
26291
+ message: task.message
26268
26292
  }).catch((e) => {
26269
- LOG.error("MeshQueue", `Failed to dispatch task to node ${nodeId}: ${e?.message}`);
26293
+ LOG.error("MeshQueue", `Failed to dispatch task locally to node ${nodeId}: ${e?.message}`);
26294
+ updateTaskStatus(meshId, task.id, "failed");
26270
26295
  });
26271
26296
  return true;
26272
26297
  }
26273
26298
  function triggerMeshQueue(components, meshId) {
26274
- const mesh = getMesh(meshId);
26299
+ const mesh = getMeshWithCache(components, meshId);
26275
26300
  if (!mesh) return;
26276
26301
  const cliInstances = components.instanceManager.getByCategory("cli");
26277
26302
  for (const inst of cliInstances) {
@@ -26288,6 +26313,15 @@ function triggerMeshQueue(components, meshId) {
26288
26313
  tryAssignQueueTask(components, meshId, nodeId, sessionId, providerType);
26289
26314
  }
26290
26315
  }
26316
+ for (const [key, idle] of remoteIdleSessions.entries()) {
26317
+ const node = mesh.nodes.find((n) => n.id === idle.nodeId);
26318
+ if (node) {
26319
+ const assigned = tryAssignQueueTask(components, meshId, idle.nodeId, idle.sessionId, idle.providerType);
26320
+ if (assigned) {
26321
+ remoteIdleSessions.delete(key);
26322
+ }
26323
+ }
26324
+ }
26291
26325
  }
26292
26326
  function buildMeshSystemMessage(args) {
26293
26327
  const metadata = formatCompletionMetadata(args.metadataEvent);
@@ -26336,7 +26370,7 @@ Do NOT retry on this node. Consider reassigning to a different node or asking th
26336
26370
  function injectMeshSystemMessage(components, args) {
26337
26371
  if (args.event === "agent:generating_completed") {
26338
26372
  const sessionId = readNonEmptyString(args.metadataEvent.targetSessionId);
26339
- const nodeId = readNonEmptyString(args.metadataEvent.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
26373
+ const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
26340
26374
  const providerType = readNonEmptyString(args.metadataEvent.providerType);
26341
26375
  if (sessionId) {
26342
26376
  updateSessionTaskStatus(args.meshId, sessionId, "completed");
@@ -26346,8 +26380,31 @@ function injectMeshSystemMessage(components, args) {
26346
26380
  }, 500);
26347
26381
  }
26348
26382
  }
26383
+ } else if (args.event === "agent:ready") {
26384
+ const sessionId = readNonEmptyString(args.metadataEvent.targetSessionId);
26385
+ const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
26386
+ const providerType = readNonEmptyString(args.metadataEvent.providerType);
26387
+ if (sessionId && nodeId && providerType) {
26388
+ remoteIdleSessions.set(`${nodeId}:${sessionId}`, { nodeId, sessionId, providerType });
26389
+ setTimeout(() => {
26390
+ const assigned = tryAssignQueueTask(components, args.meshId, nodeId, sessionId, providerType);
26391
+ if (assigned) {
26392
+ remoteIdleSessions.delete(`${nodeId}:${sessionId}`);
26393
+ }
26394
+ }, 500);
26395
+ }
26396
+ } else if (args.event === "agent:generating_started") {
26397
+ const sessionId = readNonEmptyString(args.metadataEvent.targetSessionId);
26398
+ const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
26399
+ if (sessionId && nodeId) {
26400
+ remoteIdleSessions.delete(`${nodeId}:${sessionId}`);
26401
+ }
26349
26402
  } else if (args.event === "agent:stopped") {
26350
26403
  const sessionId = readNonEmptyString(args.metadataEvent.targetSessionId);
26404
+ const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
26405
+ if (sessionId && nodeId) {
26406
+ remoteIdleSessions.delete(`${nodeId}:${sessionId}`);
26407
+ }
26351
26408
  if (sessionId) {
26352
26409
  updateSessionTaskStatus(args.meshId, sessionId, "failed");
26353
26410
  }
@@ -26357,7 +26414,7 @@ function injectMeshSystemMessage(components, args) {
26357
26414
  try {
26358
26415
  appendLedgerEntry(args.meshId, {
26359
26416
  kind: ledgerKind,
26360
- nodeId: readNonEmptyString(args.metadataEvent.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId) || void 0,
26417
+ nodeId: readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId) || void 0,
26361
26418
  sessionId: readNonEmptyString(args.metadataEvent.targetSessionId) || void 0,
26362
26419
  providerType: readNonEmptyString(args.metadataEvent.providerType) || void 0,
26363
26420
  payload: {
@@ -26377,7 +26434,7 @@ function injectMeshSystemMessage(components, args) {
26377
26434
  const maxRetries = mesh?.policy?.maxTaskRetries ?? 1;
26378
26435
  recoveryContext = getSessionRecoveryContext(args.meshId, {
26379
26436
  sessionId: readNonEmptyString(args.metadataEvent.targetSessionId) || void 0,
26380
- nodeId: readNonEmptyString(args.metadataEvent.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId) || void 0,
26437
+ nodeId: readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId) || void 0,
26381
26438
  maxRetries
26382
26439
  });
26383
26440
  recoveryContext.failedProviderType = readNonEmptyString(args.metadataEvent.providerType) || null;
@@ -26472,6 +26529,7 @@ function handleMeshForwardEvent(components, payload) {
26472
26529
  const nodeLabel = nodeId ? `Node '${nodeId}'` : workspace ? `Agent at ${workspace}` : "Remote agent";
26473
26530
  return injectMeshSystemMessage(components, {
26474
26531
  meshId,
26532
+ nodeId,
26475
26533
  nodeLabel,
26476
26534
  event: eventName,
26477
26535
  metadataEvent: {
@@ -26496,15 +26554,17 @@ function setupMeshEventForwarding(components) {
26496
26554
  const meshIdFromRuntime = readNonEmptyString(settings.meshNodeFor);
26497
26555
  const isMeshDelegate = Boolean(meshIdFromRuntime || settings.launchedByCoordinator);
26498
26556
  if (!isMeshDelegate) return;
26499
- const mesh = meshIdFromRuntime ? getMesh(meshIdFromRuntime) : getMeshByRepo(workspace);
26557
+ const mesh = meshIdFromRuntime ? getMeshWithCache(components, meshIdFromRuntime) : getMeshByRepo(workspace);
26500
26558
  const meshId = meshIdFromRuntime || readNonEmptyString(mesh?.id);
26501
26559
  if (!meshId) return;
26502
26560
  const targetNode = mesh?.nodes?.find((n) => n.workspace === workspace);
26503
26561
  const runtimeNodeId = readNonEmptyString(settings.meshNodeId);
26562
+ const resolvedNodeId = targetNode?.id || runtimeNodeId;
26504
26563
  const nodeLabel = targetNode ? `Node '${targetNode.id}'` : runtimeNodeId ? `Node '${runtimeNodeId}'` : `Agent at ${workspace}`;
26505
26564
  injectMeshSystemMessage(components, {
26506
26565
  meshId,
26507
26566
  sourceInstanceId: instanceId,
26567
+ nodeId: resolvedNodeId,
26508
26568
  nodeLabel,
26509
26569
  event: event.event,
26510
26570
  metadataEvent: event
@@ -33701,11 +33761,13 @@ async function handleOpenPanel(h, args) {
33701
33761
  async function handlePtyInput(h, args) {
33702
33762
  const { cliType, data, targetSessionId } = args || {};
33703
33763
  if (!data) return { success: false, error: "data required" };
33764
+ const cleanData = typeof data === "string" ? data.replace(/\x1b\[[?>][0-9;]*c/g, "") : data;
33765
+ if (!cleanData) return { success: true };
33704
33766
  const adapter = h.getCliAdapter(targetSessionId || cliType);
33705
33767
  if (!adapter || typeof adapter.writeRaw !== "function") {
33706
33768
  return { success: false, error: `CLI adapter not found: ${targetSessionId || cliType || "unknown"}` };
33707
33769
  }
33708
- await adapter.writeRaw(data);
33770
+ await adapter.writeRaw(cleanData);
33709
33771
  return { success: true };
33710
33772
  }
33711
33773
  function handlePtyResize(_h, args) {
@@ -34532,9 +34594,6 @@ function buildCoordinatorDelegatedCliLaunchOptions(input) {
34532
34594
  const cliType = String(input.cliType || "").trim();
34533
34595
  const cliArgs = Array.isArray(input.cliArgs) ? [...input.cliArgs] : [];
34534
34596
  const env2 = { ...input.env || {}, ...COORDINATOR_DELEGATED_ENV_UNSETS };
34535
- if (cliType === "hermes-cli" && !hasCliArg(cliArgs, "--ignore-user-config")) {
34536
- cliArgs.unshift("--ignore-user-config");
34537
- }
34538
34597
  if (cliType === "claude-cli" && !hasCliArg(cliArgs, "--mcp-config")) {
34539
34598
  cliArgs.unshift("--mcp-config", ensureEmptyDelegatedMcpConfig(input.workspace));
34540
34599
  }
@@ -35567,6 +35626,22 @@ function resolveMeshCoordinatorSetup(options) {
35567
35626
  if (!instructions || !template?.trim()) {
35568
35627
  return { kind: "unsupported", reason: "Provider manual MCP setup is missing instructions or template" };
35569
35628
  }
35629
+ const renderedTemplate = renderMeshCoordinatorTemplate(template, {
35630
+ meshId,
35631
+ workspace,
35632
+ serverName,
35633
+ adhdevMcpCommand: options.adhdevMcpCommand || DEFAULT_ADHDEV_MCP_COMMAND
35634
+ });
35635
+ const isCliCommand = !renderedTemplate.trim().includes("\n") && !renderedTemplate.trim().startsWith("{");
35636
+ if (isCliCommand) {
35637
+ return {
35638
+ kind: "cli_command",
35639
+ serverName,
35640
+ command: renderedTemplate.trim(),
35641
+ requiresRestart: mcpConfig.requiresRestart === true,
35642
+ instructions
35643
+ };
35644
+ }
35570
35645
  return {
35571
35646
  kind: "manual",
35572
35647
  serverName,
@@ -35574,12 +35649,7 @@ function resolveMeshCoordinatorSetup(options) {
35574
35649
  configPathCommand: mcpConfig.configPathCommand,
35575
35650
  requiresRestart: mcpConfig.requiresRestart === true,
35576
35651
  instructions,
35577
- template: renderMeshCoordinatorTemplate(template, {
35578
- meshId,
35579
- workspace,
35580
- serverName,
35581
- adhdevMcpCommand: options.adhdevMcpCommand || DEFAULT_ADHDEV_MCP_COMMAND
35582
- })
35652
+ template: renderedTemplate
35583
35653
  };
35584
35654
  }
35585
35655
  return {
@@ -40855,7 +40925,8 @@ async function initDaemonComponents(config2) {
40855
40925
  cdpManagers,
40856
40926
  sessionRegistry,
40857
40927
  detectedIdes: detectedIdesRef,
40858
- refreshProviderAvailability
40928
+ refreshProviderAvailability,
40929
+ dispatchMeshCommand: config2.dispatchMeshCommand
40859
40930
  };
40860
40931
  setupMeshEventForwarding(components);
40861
40932
  return components;
@@ -40913,7 +40984,7 @@ async function shutdownDaemonComponents(components) {
40913
40984
  }
40914
40985
  cdpManagers.clear();
40915
40986
  }
40916
- var path4, import_promises4, import_fs3, import_child_process, import_util3, import_os2, import_path, import_fs4, import_crypto2, import_fs5, import_path2, import_crypto3, import_fs6, import_path3, import_crypto4, import_events2, import_fs7, import_path4, import_crypto5, fs2, path8, os22, os8, os9, path14, import_child_process2, os10, path15, os11, import_child_process3, import_fs8, import_promises5, path, import_util4, import_promises6, path22, path32, fs, os4, path5, import_crypto6, path6, path7, import_fs9, import_path5, import_child_process4, import_fs10, import_os3, path9, import_child_process5, os32, path10, import_fs11, os42, import_child_process6, http, crypto2, fs3, path11, os5, fs4, os6, path12, import_crypto7, fs5, path13, os7, os13, path18, crypto4, import_fs12, import_child_process7, os12, path16, crypto3, fs6, import_module, path17, import_stream2, import_child_process8, import_child_process9, net2, os15, path20, fs7, path19, os14, fs8, path21, os16, import_child_process10, import_crypto8, import_fs13, import_module2, os17, import_path6, os18, import_child_process11, import_child_process12, fs9, os19, path222, import_os4, import_path7, fs10, fs11, path23, os20, import_child_process13, import_os5, http2, fs15, path27, fs12, path24, fs13, path25, fs14, path26, os21, import_child_process14, __defProp2, __getOwnPropDesc2, __getOwnPropNames2, __hasOwnProp2, __require2, __esm2, __export2, __copyProps2, __toCommonJS2, DEFAULT_MESH_POLICY, init_repo_mesh_types, git_worktree_exports, execFileAsync2, WORKTREE_DIR_NAME, GIT_TIMEOUT_MS, GIT_MAX_BUFFER, init_git_worktree, config_exports, DEFAULT_CONFIG, MACHINE_ID_PREFIX, init_config, mesh_config_exports, SESSION_CLEANUP_MODES, SPAWNED_SESSION_VISIBILITY_MODES, init_mesh_config, coordinator_prompt_exports, TOOLS_SECTION, TOOL_EXPOSURE_PREFLIGHT_SECTION, WORKFLOW_SECTION, init_coordinator_prompt, mesh_ledger_exports, LEDGER_DIR_NAME, MAX_FILE_SIZE_BYTES, RECENT_FAILURE_WINDOW_MS, meshLedgerEvents, init_mesh_ledger, init_mesh_work_queue, LEVEL_NUM, LEVEL_LABEL, currentLevel, LOG_DIR, MAX_LOG_SIZE, MAX_LOG_DAYS, currentDate, currentLogFile, writeCount, RING_BUFFER_SIZE, ringBuffer, origConsoleLog, origConsoleError, origConsoleWarn, LOG, interceptorInstalled, LOG_PATH, init_logger, mesh_events_exports, MAX_PENDING_EVENTS, pendingMeshCoordinatorEvents, MESH_COORDINATOR_EVENTS, EVENT_TO_LEDGER_KIND, init_mesh_events, NORMAL_TRACE_BUFFER_SIZE, DEV_TRACE_BUFFER_SIZE, DEFAULT_CONFIG2, currentConfig, init_debug_config, DEFAULT_BINDING_CANDIDATES, cachedBinding, cachedBindingError, GhosttyVtTerminalBackend, init_ghostty_vt_backend, TerminalCtor, XtermTerminalBackend, init_xterm_backend, DEFAULT_SCROLLBACK, loggedTerminalBackends, TerminalScreen, init_terminal_screen, init_spawn_env, cachedPty, NodePtyRuntimeTransport, NodePtyTransportFactory, init_pty_transport, TerminalTranscriptAccumulator, buildCliSpawnEnv, init_provider_cli_shared, init_provider_cli_parse, init_provider_cli_config, init_provider_cli_runtime, provider_cli_adapter_exports, ProviderCliAdapter, init_provider_cli_adapter, execFileAsync, DEFAULT_TIMEOUT_MS, DEFAULT_MAX_BUFFER, GitCommandError, DEFAULT_MAX_FILES, DEFAULT_MAX_BYTES, summarizeGitStatus, InMemoryGitSnapshotStore, DEFAULT_GIT_WORKSPACE_POLL_INTERVAL_MS, MIN_GIT_WORKSPACE_POLL_INTERVAL_MS, GitWorkspaceMonitor, GIT_COMMAND_NAMES, SNAPSHOT_REASONS, FAILURE_REASONS, defaultSnapshotStore, defaultGitCommandServices, BUSY_STATUSES, TERMINAL_STATUSES, TurnSnapshotTracker, MAX_WORKSPACES, MAX_ACTIVITY, MAX_SAVED_SESSIONS, DEFAULT_STATE, BUILTIN_IDE_DEFINITIONS, registeredIDEs, LIVE_LIFECYCLES, DEFAULT_ACTIVE_CHAT_POLL_STATUSES, DEFAULT_CHAT_TAIL_RECENT_MESSAGE_GRACE_MS, LIVE_RUNTIME_LIFECYCLES, DaemonCdpManager, CdpDomHandlers, DEFAULT_MONITOR_CONFIG, StatusMonitor, BUILTIN_CHAT_MESSAGE_KINDS, CHAT_MESSAGE_VISIBILITIES, CHAT_MESSAGE_TRANSCRIPT_VISIBILITIES, CHAT_MESSAGE_AUDIENCES, CHAT_MESSAGE_SOURCES, CHAT_MESSAGE_ACTIVITY_SOURCES, CHAT_MESSAGE_INTERNAL_SOURCES, KNOWN_CHAT_MESSAGE_KINDS, CHAT_MESSAGE_KIND_ALIASES, EXPLICIT_HIDDEN_VISIBILITIES, EXPLICIT_VISIBLE_VISIBILITIES, HIDDEN_AUDIENCES, ACTIVITY_SOURCE_SET, INTERNAL_SOURCE_SET, HISTORY_DIR, RETAIN_DAYS, SAVED_HISTORY_INDEX_VERSION, SAVED_HISTORY_INDEX_FILE, SAVED_HISTORY_INDEX_LOCK_SUFFIX, SAVED_HISTORY_INDEX_LOCK_WAIT_MS, SAVED_HISTORY_INDEX_LOCK_STALE_MS, SAVED_HISTORY_INDEX_LOCK_POLL_MS, SAVED_HISTORY_ROLLUP_THRESHOLD_BYTES, savedHistorySessionCache, savedHistoryFileSummaryCache, savedHistoryBackgroundRefresh, savedHistoryRollupInFlight, ChatHistoryWriter, IDE_PROVIDER_SESSION_CAPABILITIES_BASE, EXTENSION_PROVIDER_SESSION_CAPABILITIES_BASE, ExtensionProviderInstance, VALID_STATUSES, VALID_ROLES, VALID_BUBBLE_STATES, VALID_TURN_STATUSES, DEFAULT_APPROVAL_POSITIVE_HINTS, IdeProviderInstance, DEFAULT_CDP_SCAN_INTERVAL_MS, DEFAULT_CDP_DISCOVERY_INTERVAL_MS, DEFAULT_STATUS_INITIAL_REPORT_DELAY_MS, DEFAULT_STATUS_SERVER_REPORT_INTERVAL_MS, DEFAULT_STATUS_P2P_REPORT_INTERVAL_MS, MIN_MACHINE_RUNTIME_SUBSCRIPTION_INTERVAL_MS, DEFAULT_MACHINE_RUNTIME_SUBSCRIPTION_INTERVAL_MS, MIN_SESSION_HOST_DIAGNOSTICS_SUBSCRIPTION_INTERVAL_MS, DEFAULT_SESSION_HOST_DIAGNOSTICS_SUBSCRIPTION_INTERVAL_MS, DEFAULT_SESSION_HOST_READY_TIMEOUT_MS, STANDALONE_CDP_SCAN_INTERVAL_MS, DaemonCdpScanner, DaemonCdpInitializer, WORKING_STATUSES, FULL_STATUS_ACTIVE_CHAT_OPTIONS, LIVE_STATUS_ACTIVE_CHAT_OPTIONS, STATUS_MODAL_MESSAGE_LIMIT, STATUS_MODAL_BUTTON_LIMIT, VALID_INPUT_MEDIA_TYPES, VALID_INPUT_STRATEGIES, TEXT_ONLY_MESSAGE_INPUT_SUPPORT, IDE_SESSION_CAPABILITIES, EXTENSION_SESSION_CAPABILITIES, PTY_SESSION_CAPABILITIES, CLI_CHAT_SESSION_CAPABILITIES, ACP_SESSION_CAPABILITIES, globalStore, RECENT_SEND_WINDOW_MS, READ_CHAT_PROVIDER_EVAL_TIMEOUT_MS, HERMES_CLI_STARTING_SEND_SETTLE_MS, recentSendByTarget, DEFAULT_DEBUG_SANITIZE_OPTIONS, SECRET_KEY_PATTERN, KEY_TO_VK, COMMAND_DEBUG_LEVELS, DaemonCommandHandler, IMAGE_MIME_EXTENSIONS, MATERIALIZED_IMAGE_MAX_AGE_MS, MATERIALIZED_IMAGE_CLEANUP_INTERVAL_MS, lastMaterializedImageCleanupAt, CachedDatabaseSync, CliProviderInstance, AcpProviderInstance, chalkModule, chalkApi, COORDINATOR_DELEGATED_ENV_UNSETS, DaemonCliManager, VALID_CAPABILITY_MEDIA_TYPES, VALID_INPUT_STRATEGIES2, KNOWN_PROVIDER_FIELDS, VALUE_CONTROL_TYPES, ProviderLoader, _providerLoader, LOG_DIR2, MAX_FILE_SIZE, MAX_DAYS, SENSITIVE_KEYS, currentDate2, currentFile, writeCount2, SKIP_COMMANDS, DEFAULT_SERVER_NAME, DEFAULT_ADHDEV_MCP_COMMAND, HERMES_CLI_TYPE, HERMES_MCP_CONFIG_PATH, READ_DEBUG_ENABLED, recentReadDebugSignatureBySession, UPGRADE_HELPER_ENV, CHANNEL_NPM_TAG, CHANNEL_SERVER_URL, CHAT_COMMANDS, READ_DEBUG_ENABLED2, DaemonCommandRouter, DaemonStatusReporter, DEFAULT_DAEMON_PORT, DAEMON_WS_PATH, ProviderStreamAdapter, DaemonAgentStreamManager, AgentStreamPoller, ProviderInstanceManager, ARCHIVE_PATH, MAX_ENTRIES_PER_PROVIDER, VersionArchive, DEV_SERVER_PORT, DevServer, SessionHostRuntimeTransport, SessionHostPtyTransportFactory, DEFAULT_SESSION_HOST_APP_NAME, DEFAULT_STANDALONE_SESSION_HOST_APP_NAME, STARTUP_TIMEOUT_MS, STARTUP_POLL_MS, SessionHostCompatibilityError, EXTENSION_CATALOG, SessionRegistry;
40987
+ var path4, import_promises4, import_fs3, import_child_process, import_util3, import_os2, import_path, import_fs4, import_crypto2, import_fs5, import_path2, import_crypto3, import_fs6, import_path3, import_crypto4, import_events2, import_fs7, import_path4, import_crypto5, fs2, path8, os22, os8, os9, path14, import_child_process2, os10, path15, os11, import_child_process3, import_fs8, import_promises5, path, import_util4, import_promises6, path22, path32, fs, os4, path5, import_crypto6, path6, path7, import_fs9, import_path5, import_child_process4, import_fs10, import_os3, path9, import_child_process5, os32, path10, import_fs11, os42, import_child_process6, http, crypto2, fs3, path11, os5, fs4, os6, path12, import_crypto7, fs5, path13, os7, os13, path18, crypto4, import_fs12, import_child_process7, os12, path16, crypto3, fs6, import_module, path17, import_stream2, import_child_process8, import_child_process9, net2, os15, path20, fs7, path19, os14, fs8, path21, os16, import_child_process10, import_crypto8, import_fs13, import_module2, os17, import_path6, os18, import_child_process11, import_child_process12, fs9, os19, path222, import_os4, import_path7, fs10, fs11, path23, os20, import_child_process13, import_os5, http2, fs15, path27, fs12, path24, fs13, path25, fs14, path26, os21, import_child_process14, __defProp2, __getOwnPropDesc2, __getOwnPropNames2, __hasOwnProp2, __require2, __esm2, __export2, __copyProps2, __toCommonJS2, DEFAULT_MESH_POLICY, init_repo_mesh_types, git_worktree_exports, execFileAsync2, WORKTREE_DIR_NAME, GIT_TIMEOUT_MS, GIT_MAX_BUFFER, init_git_worktree, config_exports, DEFAULT_CONFIG, MACHINE_ID_PREFIX, init_config, mesh_config_exports, SESSION_CLEANUP_MODES, SPAWNED_SESSION_VISIBILITY_MODES, init_mesh_config, coordinator_prompt_exports, TOOLS_SECTION, TOOL_EXPOSURE_PREFLIGHT_SECTION, WORKFLOW_SECTION, init_coordinator_prompt, mesh_ledger_exports, LEDGER_DIR_NAME, MAX_FILE_SIZE_BYTES, RECENT_FAILURE_WINDOW_MS, meshLedgerEvents, init_mesh_ledger, init_mesh_work_queue, LEVEL_NUM, LEVEL_LABEL, currentLevel, LOG_DIR, MAX_LOG_SIZE, MAX_LOG_DAYS, currentDate, currentLogFile, writeCount, RING_BUFFER_SIZE, ringBuffer, origConsoleLog, origConsoleError, origConsoleWarn, LOG, interceptorInstalled, LOG_PATH, init_logger, mesh_events_exports, remoteIdleSessions, MAX_PENDING_EVENTS, pendingMeshCoordinatorEvents, MESH_COORDINATOR_EVENTS, EVENT_TO_LEDGER_KIND, init_mesh_events, NORMAL_TRACE_BUFFER_SIZE, DEV_TRACE_BUFFER_SIZE, DEFAULT_CONFIG2, currentConfig, init_debug_config, DEFAULT_BINDING_CANDIDATES, cachedBinding, cachedBindingError, GhosttyVtTerminalBackend, init_ghostty_vt_backend, TerminalCtor, XtermTerminalBackend, init_xterm_backend, DEFAULT_SCROLLBACK, loggedTerminalBackends, TerminalScreen, init_terminal_screen, init_spawn_env, cachedPty, NodePtyRuntimeTransport, NodePtyTransportFactory, init_pty_transport, TerminalTranscriptAccumulator, buildCliSpawnEnv, init_provider_cli_shared, init_provider_cli_parse, init_provider_cli_config, init_provider_cli_runtime, provider_cli_adapter_exports, ProviderCliAdapter, init_provider_cli_adapter, execFileAsync, DEFAULT_TIMEOUT_MS, DEFAULT_MAX_BUFFER, GitCommandError, DEFAULT_MAX_FILES, DEFAULT_MAX_BYTES, summarizeGitStatus, InMemoryGitSnapshotStore, DEFAULT_GIT_WORKSPACE_POLL_INTERVAL_MS, MIN_GIT_WORKSPACE_POLL_INTERVAL_MS, GitWorkspaceMonitor, GIT_COMMAND_NAMES, SNAPSHOT_REASONS, FAILURE_REASONS, defaultSnapshotStore, defaultGitCommandServices, BUSY_STATUSES, TERMINAL_STATUSES, TurnSnapshotTracker, MAX_WORKSPACES, MAX_ACTIVITY, MAX_SAVED_SESSIONS, DEFAULT_STATE, BUILTIN_IDE_DEFINITIONS, registeredIDEs, LIVE_LIFECYCLES, DEFAULT_ACTIVE_CHAT_POLL_STATUSES, DEFAULT_CHAT_TAIL_RECENT_MESSAGE_GRACE_MS, LIVE_RUNTIME_LIFECYCLES, DaemonCdpManager, CdpDomHandlers, DEFAULT_MONITOR_CONFIG, StatusMonitor, BUILTIN_CHAT_MESSAGE_KINDS, CHAT_MESSAGE_VISIBILITIES, CHAT_MESSAGE_TRANSCRIPT_VISIBILITIES, CHAT_MESSAGE_AUDIENCES, CHAT_MESSAGE_SOURCES, CHAT_MESSAGE_ACTIVITY_SOURCES, CHAT_MESSAGE_INTERNAL_SOURCES, KNOWN_CHAT_MESSAGE_KINDS, CHAT_MESSAGE_KIND_ALIASES, EXPLICIT_HIDDEN_VISIBILITIES, EXPLICIT_VISIBLE_VISIBILITIES, HIDDEN_AUDIENCES, ACTIVITY_SOURCE_SET, INTERNAL_SOURCE_SET, HISTORY_DIR, RETAIN_DAYS, SAVED_HISTORY_INDEX_VERSION, SAVED_HISTORY_INDEX_FILE, SAVED_HISTORY_INDEX_LOCK_SUFFIX, SAVED_HISTORY_INDEX_LOCK_WAIT_MS, SAVED_HISTORY_INDEX_LOCK_STALE_MS, SAVED_HISTORY_INDEX_LOCK_POLL_MS, SAVED_HISTORY_ROLLUP_THRESHOLD_BYTES, savedHistorySessionCache, savedHistoryFileSummaryCache, savedHistoryBackgroundRefresh, savedHistoryRollupInFlight, ChatHistoryWriter, IDE_PROVIDER_SESSION_CAPABILITIES_BASE, EXTENSION_PROVIDER_SESSION_CAPABILITIES_BASE, ExtensionProviderInstance, VALID_STATUSES, VALID_ROLES, VALID_BUBBLE_STATES, VALID_TURN_STATUSES, DEFAULT_APPROVAL_POSITIVE_HINTS, IdeProviderInstance, DEFAULT_CDP_SCAN_INTERVAL_MS, DEFAULT_CDP_DISCOVERY_INTERVAL_MS, DEFAULT_STATUS_INITIAL_REPORT_DELAY_MS, DEFAULT_STATUS_SERVER_REPORT_INTERVAL_MS, DEFAULT_STATUS_P2P_REPORT_INTERVAL_MS, MIN_MACHINE_RUNTIME_SUBSCRIPTION_INTERVAL_MS, DEFAULT_MACHINE_RUNTIME_SUBSCRIPTION_INTERVAL_MS, MIN_SESSION_HOST_DIAGNOSTICS_SUBSCRIPTION_INTERVAL_MS, DEFAULT_SESSION_HOST_DIAGNOSTICS_SUBSCRIPTION_INTERVAL_MS, DEFAULT_SESSION_HOST_READY_TIMEOUT_MS, STANDALONE_CDP_SCAN_INTERVAL_MS, DaemonCdpScanner, DaemonCdpInitializer, WORKING_STATUSES, FULL_STATUS_ACTIVE_CHAT_OPTIONS, LIVE_STATUS_ACTIVE_CHAT_OPTIONS, STATUS_MODAL_MESSAGE_LIMIT, STATUS_MODAL_BUTTON_LIMIT, VALID_INPUT_MEDIA_TYPES, VALID_INPUT_STRATEGIES, TEXT_ONLY_MESSAGE_INPUT_SUPPORT, IDE_SESSION_CAPABILITIES, EXTENSION_SESSION_CAPABILITIES, PTY_SESSION_CAPABILITIES, CLI_CHAT_SESSION_CAPABILITIES, ACP_SESSION_CAPABILITIES, globalStore, RECENT_SEND_WINDOW_MS, READ_CHAT_PROVIDER_EVAL_TIMEOUT_MS, HERMES_CLI_STARTING_SEND_SETTLE_MS, recentSendByTarget, DEFAULT_DEBUG_SANITIZE_OPTIONS, SECRET_KEY_PATTERN, KEY_TO_VK, COMMAND_DEBUG_LEVELS, DaemonCommandHandler, IMAGE_MIME_EXTENSIONS, MATERIALIZED_IMAGE_MAX_AGE_MS, MATERIALIZED_IMAGE_CLEANUP_INTERVAL_MS, lastMaterializedImageCleanupAt, CachedDatabaseSync, CliProviderInstance, AcpProviderInstance, chalkModule, chalkApi, COORDINATOR_DELEGATED_ENV_UNSETS, DaemonCliManager, VALID_CAPABILITY_MEDIA_TYPES, VALID_INPUT_STRATEGIES2, KNOWN_PROVIDER_FIELDS, VALUE_CONTROL_TYPES, ProviderLoader, _providerLoader, LOG_DIR2, MAX_FILE_SIZE, MAX_DAYS, SENSITIVE_KEYS, currentDate2, currentFile, writeCount2, SKIP_COMMANDS, DEFAULT_SERVER_NAME, DEFAULT_ADHDEV_MCP_COMMAND, HERMES_CLI_TYPE, HERMES_MCP_CONFIG_PATH, READ_DEBUG_ENABLED, recentReadDebugSignatureBySession, UPGRADE_HELPER_ENV, CHANNEL_NPM_TAG, CHANNEL_SERVER_URL, CHAT_COMMANDS, READ_DEBUG_ENABLED2, DaemonCommandRouter, DaemonStatusReporter, DEFAULT_DAEMON_PORT, DAEMON_WS_PATH, ProviderStreamAdapter, DaemonAgentStreamManager, AgentStreamPoller, ProviderInstanceManager, ARCHIVE_PATH, MAX_ENTRIES_PER_PROVIDER, VersionArchive, DEV_SERVER_PORT, DevServer, SessionHostRuntimeTransport, SessionHostPtyTransportFactory, DEFAULT_SESSION_HOST_APP_NAME, DEFAULT_STANDALONE_SESSION_HOST_APP_NAME, STARTUP_TIMEOUT_MS, STARTUP_POLL_MS, SessionHostCompatibilityError, EXTENSION_CATALOG, SessionRegistry;
40917
40988
  var init_dist2 = __esm({
40918
40989
  "../daemon-core/dist/index.mjs"() {
40919
40990
  "use strict";
@@ -41325,12 +41396,14 @@ Follow these recovery rules:
41325
41396
  init_logger();
41326
41397
  init_mesh_ledger();
41327
41398
  init_mesh_work_queue();
41399
+ remoteIdleSessions = /* @__PURE__ */ new Map();
41328
41400
  MAX_PENDING_EVENTS = 50;
41329
41401
  pendingMeshCoordinatorEvents = [];
41330
41402
  MESH_COORDINATOR_EVENTS = /* @__PURE__ */ new Set([
41331
41403
  "agent:generating_completed",
41332
41404
  "agent:waiting_approval",
41333
41405
  "agent:stopped",
41406
+ "agent:ready",
41334
41407
  "monitor:long_generating"
41335
41408
  ]);
41336
41409
  EVENT_TO_LEDGER_KIND = {
@@ -41865,6 +41938,8 @@ Follow these recovery rules:
41865
41938
  statusHistory = [];
41866
41939
  // ─── CLI Scripts (script-based parsing) ───
41867
41940
  cliScripts;
41941
+ /** Per-session opaque state object created by cliScripts.createState(), reset on stop. */
41942
+ scriptState = null;
41868
41943
  runtimeSettings = {};
41869
41944
  /** Full accumulated rendered PTY transcript for parser/readback use */
41870
41945
  accumulatedBuffer = "";
@@ -42046,6 +42121,7 @@ ${lastSnapshot}`;
42046
42121
  this.cliScripts = scripts;
42047
42122
  this.parsedStatusCache = null;
42048
42123
  this.parseErrorMessage = null;
42124
+ this.scriptState = typeof scripts.createState === "function" ? scripts.createState() : null;
42049
42125
  const scriptNames = listCliScriptNames(scripts);
42050
42126
  LOG.info("CLI", `[${this.cliType}] CLI scripts injected: [${scriptNames.join(", ")}]`);
42051
42127
  }
@@ -42163,6 +42239,7 @@ ${lastSnapshot}`;
42163
42239
  this.ready = false;
42164
42240
  this.startupParseGate = false;
42165
42241
  this.spawnAt = 0;
42242
+ this.scriptState = null;
42166
42243
  this.onStatusChange?.();
42167
42244
  });
42168
42245
  this.spawnAt = Date.now();
@@ -42936,7 +43013,7 @@ ${lastSnapshot}`;
42936
43013
  scope: this.currentTurnScope,
42937
43014
  runtimeSettings: this.runtimeSettings
42938
43015
  });
42939
- const session = this.cliScripts.parseSession({ ...input, tail, tailScreen: buildCliScreenSnapshot(tail) });
43016
+ const session = this.cliScripts.parseSession(this.scriptState, { ...input, tail, tailScreen: buildCliScreenSnapshot(tail) });
42940
43017
  this.parseErrorMessage = null;
42941
43018
  return session && typeof session === "object" ? session : null;
42942
43019
  } catch (e) {
@@ -42950,7 +43027,7 @@ ${lastSnapshot}`;
42950
43027
  if (!this.cliScripts?.detectStatus) return null;
42951
43028
  try {
42952
43029
  const screenText = this.terminalScreen.getText();
42953
- const status = this.cliScripts.detectStatus({
43030
+ const status = this.cliScripts.detectStatus(this.scriptState, {
42954
43031
  tail: text.slice(-500),
42955
43032
  screenText,
42956
43033
  rawBuffer: this.accumulatedRawBuffer,
@@ -42969,7 +43046,7 @@ ${lastSnapshot}`;
42969
43046
  try {
42970
43047
  const screenText = this.terminalScreen.getText();
42971
43048
  const buffer = screenText || this.accumulatedBuffer;
42972
- return this.cliScripts.parseApproval({
43049
+ return this.cliScripts.parseApproval(this.scriptState, {
42973
43050
  buffer,
42974
43051
  screenText,
42975
43052
  rawBuffer: this.accumulatedRawBuffer,
@@ -43077,7 +43154,7 @@ ${lastSnapshot}`;
43077
43154
  scope: this.currentTurnScope,
43078
43155
  runtimeSettings: this.runtimeSettings
43079
43156
  });
43080
- return await Promise.resolve(fn({
43157
+ return await Promise.resolve(fn(this.scriptState, {
43081
43158
  ...input,
43082
43159
  args: args && typeof args === "object" ? { ...args } : {}
43083
43160
  }));
@@ -48296,6 +48373,8 @@ ${effect.notification.body || ""}`.trim();
48296
48373
  this.completedDebounceTimer = null;
48297
48374
  }, 3e3);
48298
48375
  }
48376
+ } else if (newStatus === "idle" && this.lastStatus === "starting") {
48377
+ this.pushEvent({ event: "agent:ready", chatTitle, timestamp: now });
48299
48378
  } else if (newStatus === "stopped") {
48300
48379
  if (this.generatingDebounceTimer) {
48301
48380
  clearTimeout(this.generatingDebounceTimer);
@@ -53342,6 +53421,93 @@ Run 'adhdev doctor' for detailed diagnostics.`
53342
53421
  meshCoordinatorSetup: coordinatorSetup
53343
53422
  };
53344
53423
  }
53424
+ if (coordinatorSetup.kind === "cli_command") {
53425
+ let cliCmdSystemPrompt = "";
53426
+ try {
53427
+ cliCmdSystemPrompt = buildCoordinatorSystemPrompt2({ mesh, coordinatorCliType: cliType });
53428
+ } catch (error48) {
53429
+ const message = error48?.message || String(error48);
53430
+ LOG.error("MeshCoordinator", `Failed to build coordinator prompt: ${message}`);
53431
+ return {
53432
+ success: false,
53433
+ code: "mesh_coordinator_prompt_failed",
53434
+ error: `Failed to build Repo Mesh coordinator prompt: ${message}`,
53435
+ meshId,
53436
+ cliType,
53437
+ workspace
53438
+ };
53439
+ }
53440
+ try {
53441
+ const { execFileSync: execCmdSync } = await import("child_process");
53442
+ const cmdParts = coordinatorSetup.command.trim().split(/\s+/);
53443
+ const [regCmd, ...regArgs] = cmdParts;
53444
+ LOG.info("MeshCoordinator", `Running MCP registration: ${coordinatorSetup.command}`);
53445
+ execCmdSync(regCmd, regArgs, { stdio: "pipe", timeout: 15e3 });
53446
+ } catch (error48) {
53447
+ LOG.warn("MeshCoordinator", `MCP registration command failed (may be pre-registered): ${error48?.message || error48}`);
53448
+ }
53449
+ const cliCmdArgs = [];
53450
+ const cliCmdEnv = {};
53451
+ if (cliCmdSystemPrompt) {
53452
+ if (cliType === "codex-cli") {
53453
+ cliCmdArgs.push("-c", `developer_instructions=${JSON.stringify(cliCmdSystemPrompt)}`);
53454
+ } else if (cliType === "gemini-cli") {
53455
+ try {
53456
+ const { writeFileSync: wfs, existsSync: efs, readFileSync: rfs } = await import("fs");
53457
+ const geminiMdPath = `${workspace}/GEMINI.md`;
53458
+ const marker = "<!-- adhdev-mesh-coordinator-prompt -->";
53459
+ const markerEnd = "<!-- /adhdev-mesh-coordinator-prompt -->";
53460
+ const block = `${marker}
53461
+ ${cliCmdSystemPrompt}
53462
+ ${markerEnd}`;
53463
+ if (efs(geminiMdPath)) {
53464
+ const existing = rfs(geminiMdPath, "utf-8");
53465
+ const replaced = existing.replace(
53466
+ new RegExp(`${marker}[\\s\\S]*?${markerEnd}`, "g"),
53467
+ block
53468
+ );
53469
+ wfs(geminiMdPath, replaced.includes(marker) ? replaced : `${existing}
53470
+
53471
+ ${block}`);
53472
+ } else {
53473
+ wfs(geminiMdPath, block);
53474
+ }
53475
+ LOG.info("MeshCoordinator", `Wrote coordinator prompt to ${workspace}/GEMINI.md`);
53476
+ } catch (e) {
53477
+ LOG.warn("MeshCoordinator", `Could not write GEMINI.md: ${e?.message || e}`);
53478
+ }
53479
+ }
53480
+ }
53481
+ const cliCmdLaunch = await this.deps.cliManager.handleCliCommand("launch_cli", {
53482
+ cliType,
53483
+ dir: workspace,
53484
+ cliArgs: cliCmdArgs.length > 0 ? cliCmdArgs : void 0,
53485
+ env: Object.keys(cliCmdEnv).length > 0 ? cliCmdEnv : void 0,
53486
+ settings: { meshCoordinatorFor: meshId }
53487
+ });
53488
+ if (!cliCmdLaunch?.success) {
53489
+ return { success: false, error: cliCmdLaunch?.error || "Failed to launch CLI session" };
53490
+ }
53491
+ LOG.info("MeshCoordinator", `Launched ${cliType} coordinator (cli_command) for mesh ${meshId}`);
53492
+ try {
53493
+ const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
53494
+ appendLedgerEntry2(meshId, {
53495
+ kind: "coordinator_started",
53496
+ sessionId: cliCmdLaunch.sessionId || cliCmdLaunch.id,
53497
+ providerType: cliType,
53498
+ payload: { workspace }
53499
+ });
53500
+ } catch {
53501
+ }
53502
+ return {
53503
+ success: true,
53504
+ meshId,
53505
+ cliType,
53506
+ workspace,
53507
+ sessionId: cliCmdLaunch.sessionId || cliCmdLaunch.id,
53508
+ mcpRegistered: true
53509
+ };
53510
+ }
53345
53511
  const configFormat = coordinatorSetup.configFormat;
53346
53512
  if (configFormat !== "claude_mcp_json" && configFormat !== "hermes_config_yaml") {
53347
53513
  return {
@@ -57300,12 +57466,60 @@ function extractGitDiff(value) {
57300
57466
  function extractLaunchPayload(value) {
57301
57467
  return findNestedPayload(value, (payload) => Boolean(payload?.sessionId || payload?.id || payload?.runtimeSessionId));
57302
57468
  }
57469
+ async function ipcDispatchToRemoteAgent(ctx, node, args) {
57470
+ const transport = ctx.transport;
57471
+ const daemonId = node.daemonId;
57472
+ let sessionId = args.session_id?.trim() || "";
57473
+ const providerPriorityList = Array.isArray(node.policy?.providerPriority) ? node.policy.providerPriority : [];
57474
+ let resolvedProviderType = args.providerType?.trim() || providerPriorityList[0] || "";
57475
+ if (!sessionId) {
57476
+ try {
57477
+ const relayResult = await transport.meshCommand(daemonId, "get_status_metadata", {});
57478
+ const innerResult = relayResult?.result ?? relayResult;
57479
+ const statusObj = innerResult?.status ?? innerResult;
57480
+ const sessions = Array.isArray(statusObj?.sessions) ? statusObj.sessions : [];
57481
+ const meshSessions = sessions.filter(
57482
+ (s) => s?.settings?.meshNodeFor === ctx.mesh.id || s?.settings?.meshNodeId === node.id || s?.settings?.launchedByCoordinator === true
57483
+ );
57484
+ const targetSession = meshSessions[0] || sessions.find(
57485
+ (s) => !resolvedProviderType || s?.providerType === resolvedProviderType || s?.cliType === resolvedProviderType
57486
+ ) || sessions[0];
57487
+ if (targetSession?.id || targetSession?.sessionId) {
57488
+ sessionId = targetSession.id || targetSession.sessionId;
57489
+ if (!resolvedProviderType) {
57490
+ resolvedProviderType = targetSession.providerType || targetSession.cliType || "";
57491
+ }
57492
+ } else {
57493
+ }
57494
+ } catch (e) {
57495
+ }
57496
+ }
57497
+ if (!resolvedProviderType) {
57498
+ return { success: false, error: `Cannot dispatch to remote node '${node.id}': providerType unknown. Set providerPriority on the node policy or call mesh_launch_session first.` };
57499
+ }
57500
+ try {
57501
+ await transport.meshCommand(daemonId, "agent_command", {
57502
+ ...sessionId ? { targetSessionId: sessionId } : {},
57503
+ agentType: resolvedProviderType,
57504
+ cliType: resolvedProviderType,
57505
+ action: "send_chat",
57506
+ message: args.message
57507
+ });
57508
+ return { success: true, dispatched: true, sessionId: sessionId || resolvedProviderType };
57509
+ } catch (e) {
57510
+ return { success: false, error: `P2P dispatch failed: ${e?.message || String(e)}` };
57511
+ }
57512
+ }
57303
57513
  function resolveCoordinatorNode(ctx) {
57304
57514
  const preferredNodeId = typeof ctx.mesh.coordinator?.preferredNodeId === "string" ? ctx.mesh.coordinator.preferredNodeId.trim() : "";
57305
57515
  if (preferredNodeId) {
57306
57516
  const preferred = ctx.mesh.nodes.find((n) => n.id === preferredNodeId && typeof n.daemonId === "string" && n.daemonId.trim());
57307
57517
  if (preferred) return preferred;
57308
57518
  }
57519
+ if (ctx.localMachineId) {
57520
+ const byMachine = ctx.mesh.nodes.find((n) => n.machineId === ctx.localMachineId);
57521
+ if (byMachine) return byMachine;
57522
+ }
57309
57523
  if (ctx.localDaemonId) {
57310
57524
  return ctx.mesh.nodes.find((n) => n.daemonId === ctx.localDaemonId);
57311
57525
  }
@@ -57395,7 +57609,8 @@ function getNodeLaunchReadiness(node) {
57395
57609
  };
57396
57610
  }
57397
57611
  async function commandForNode(ctx, node, command, args = {}) {
57398
- if (ctx.transport instanceof IpcTransport && node.daemonId && node.daemonId !== ctx.localDaemonId) {
57612
+ const isLocalNode = ctx.localMachineId && node.machineId === ctx.localMachineId || ctx.localDaemonId && node.daemonId === ctx.localDaemonId;
57613
+ if (ctx.transport instanceof IpcTransport && node.daemonId && !isLocalNode) {
57399
57614
  return ctx.transport.meshCommand(node.daemonId, command, args);
57400
57615
  }
57401
57616
  if (isLocalTransport(ctx.transport)) {
@@ -57408,7 +57623,9 @@ var MESH_STATUS_TOOL = {
57408
57623
  description: "Get the current status of all nodes in the repo mesh \u2014 health, git state, active sessions. Use this to decide which node to send work to.",
57409
57624
  inputSchema: {
57410
57625
  type: "object",
57411
- properties: {}
57626
+ properties: {
57627
+ _gemini_compat: { type: "string", description: "Dummy property for Gemini compatibility. Ignore this." }
57628
+ }
57412
57629
  }
57413
57630
  };
57414
57631
  var MESH_LIST_NODES_TOOL = {
@@ -57416,7 +57633,9 @@ var MESH_LIST_NODES_TOOL = {
57416
57633
  description: "List all nodes in the mesh with their capabilities, platform, and workspace paths.",
57417
57634
  inputSchema: {
57418
57635
  type: "object",
57419
- properties: {}
57636
+ properties: {
57637
+ _gemini_compat: { type: "string", description: "Dummy property for Gemini compatibility. Ignore this." }
57638
+ }
57420
57639
  }
57421
57640
  };
57422
57641
  var MESH_ENQUEUE_TASK_TOOL = {
@@ -57720,12 +57939,38 @@ async function meshListNodes(ctx) {
57720
57939
  async function meshEnqueueTask(ctx, args) {
57721
57940
  try {
57722
57941
  const task = enqueueTask(ctx.mesh.id, args.message);
57723
- if (ctx.transport instanceof IpcTransport && ctx.localDaemonId) {
57724
- ctx.transport.meshCommand(ctx.localDaemonId, "trigger_mesh_queue", { meshId: ctx.mesh.id }).catch(() => {
57942
+ if (isLocalTransport(ctx.transport) && !(ctx.transport instanceof IpcTransport)) {
57943
+ ctx.transport.command("trigger_mesh_queue", { meshId: ctx.mesh.id }).catch(() => {
57725
57944
  });
57726
- } else if (isLocalTransport(ctx.transport)) {
57945
+ return JSON.stringify({ success: true, taskId: task.id, status: task.status });
57946
+ }
57947
+ if (ctx.transport instanceof IpcTransport) {
57727
57948
  ctx.transport.command("trigger_mesh_queue", { meshId: ctx.mesh.id }).catch(() => {
57728
57949
  });
57950
+ const dispatchPromises = [];
57951
+ for (const node of ctx.mesh.nodes) {
57952
+ const isLocalNode = ctx.localMachineId && node.machineId === ctx.localMachineId || ctx.localDaemonId && node.daemonId === ctx.localDaemonId;
57953
+ if (isLocalNode || !node.daemonId) continue;
57954
+ dispatchPromises.push(
57955
+ ipcDispatchToRemoteAgent(ctx, node, { message: args.message }).then((result) => {
57956
+ if (result.success) {
57957
+ try {
57958
+ appendLedgerEntry(ctx.mesh.id, {
57959
+ kind: "task_dispatched",
57960
+ nodeId: node.id,
57961
+ sessionId: result.sessionId,
57962
+ payload: { message: args.message, via: "p2p_direct", taskId: task.id }
57963
+ });
57964
+ } catch {
57965
+ }
57966
+ }
57967
+ }).catch(() => {
57968
+ })
57969
+ );
57970
+ }
57971
+ Promise.all(dispatchPromises).catch(() => {
57972
+ });
57973
+ return JSON.stringify({ success: true, taskId: task.id, status: task.status });
57729
57974
  }
57730
57975
  return JSON.stringify({ success: true, taskId: task.id, status: task.status });
57731
57976
  } catch (e) {
@@ -57754,11 +57999,29 @@ async function meshSendTask(ctx, args) {
57754
57999
  });
57755
58000
  return JSON.stringify(res);
57756
58001
  }
57757
- const task = enqueueTask(ctx.mesh.id, args.message, { targetNodeId: args.node_id });
57758
- if (ctx.transport instanceof IpcTransport && node.daemonId && node.daemonId !== ctx.localDaemonId) {
57759
- ctx.transport.meshCommand(node.daemonId, "trigger_mesh_queue", { meshId: ctx.mesh.id }).catch(() => {
58002
+ const isLocalNode = ctx.localMachineId && node.machineId === ctx.localMachineId || ctx.localDaemonId && node.daemonId === ctx.localDaemonId;
58003
+ if (ctx.transport instanceof IpcTransport && node.daemonId && !isLocalNode) {
58004
+ const cached2 = meshSessionProviderMetadata.get(meshSessionCacheKey(args.node_id, args.session_id || ""));
58005
+ const result = await ipcDispatchToRemoteAgent(ctx, node, {
58006
+ session_id: args.session_id,
58007
+ message: args.message,
58008
+ providerType: cached2?.providerType
57760
58009
  });
57761
- } else if (isLocalTransport(ctx.transport)) {
58010
+ if (result.success) {
58011
+ try {
58012
+ appendLedgerEntry(ctx.mesh.id, {
58013
+ kind: "task_dispatched",
58014
+ nodeId: args.node_id,
58015
+ sessionId: result.sessionId,
58016
+ payload: { message: args.message, via: "p2p_direct" }
58017
+ });
58018
+ } catch {
58019
+ }
58020
+ }
58021
+ return JSON.stringify({ ...result, nodeId: args.node_id });
58022
+ }
58023
+ const task = enqueueTask(ctx.mesh.id, args.message, { targetNodeId: args.node_id });
58024
+ if (isLocalTransport(ctx.transport)) {
57762
58025
  ctx.transport.command("trigger_mesh_queue", { meshId: ctx.mesh.id }).catch(() => {
57763
58026
  });
57764
58027
  }
@@ -57902,7 +58165,8 @@ async function meshLaunchSession(ctx, args) {
57902
58165
  });
57903
58166
  } catch {
57904
58167
  }
57905
- if (ctx.transport instanceof IpcTransport && node.daemonId && node.daemonId !== ctx.localDaemonId) {
58168
+ const isLocalNode = ctx.localMachineId && node.machineId === ctx.localMachineId || ctx.localDaemonId && node.daemonId === ctx.localDaemonId;
58169
+ if (ctx.transport instanceof IpcTransport && node.daemonId && !isLocalNode) {
57906
58170
  ctx.transport.meshCommand(node.daemonId, "trigger_mesh_queue", { meshId: ctx.mesh.id }).catch(() => {
57907
58171
  });
57908
58172
  } else if (isLocalTransport(ctx.transport)) {
@@ -59840,6 +60104,15 @@ async function startMcpServer(opts) {
59840
60104
  process.exit(1);
59841
60105
  }
59842
60106
  let localDaemonId;
60107
+ let localMachineId;
60108
+ if (transport instanceof LocalTransport || transport instanceof IpcTransport) {
60109
+ try {
60110
+ const { loadConfig: loadConfig2 } = await Promise.resolve().then(() => (init_dist2(), dist_exports));
60111
+ const cfg = loadConfig2();
60112
+ if (cfg.registeredMachineId) localMachineId = cfg.registeredMachineId;
60113
+ } catch {
60114
+ }
60115
+ }
59843
60116
  if (transport instanceof IpcTransport) {
59844
60117
  try {
59845
60118
  const statusResult = await transport.getStatus();
@@ -59848,7 +60121,7 @@ async function startMcpServer(opts) {
59848
60121
  } catch {
59849
60122
  }
59850
60123
  }
59851
- const meshCtx = { mesh, transport, ...localDaemonId ? { localDaemonId } : {} };
60124
+ const meshCtx = { mesh, transport, ...localDaemonId ? { localDaemonId } : {}, ...localMachineId ? { localMachineId } : {} };
59852
60125
  const coordinatorPrompt = await buildMeshModeCoordinatorPrompt(mesh);
59853
60126
  const server2 = new import_server.Server(
59854
60127
  { name: "adhdev-mcp-server", version: "0.9.76" },