@adhdev/daemon-core 0.9.77-rc.2 → 0.9.77-rc.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1311,13 +1311,15 @@ function formatCompletionMetadata(event) {
1311
1311
  }
1312
1312
  function tryAssignQueueTask(components, meshId, nodeId, sessionId, providerType) {
1313
1313
  const task = claimNextTask(meshId, nodeId, sessionId);
1314
- if (!task) return false;
1314
+ if (!task) {
1315
+ return false;
1316
+ }
1315
1317
  LOG.info("MeshQueue", `Node ${nodeId} (${sessionId}) pulled task ${task.id}`);
1316
1318
  components.cliManager.handleCliCommand("agent_command", {
1317
1319
  targetSessionId: sessionId,
1318
1320
  cliType: providerType,
1319
1321
  action: "send_chat",
1320
- input: task.message
1322
+ message: task.message
1321
1323
  }).catch((e) => {
1322
1324
  LOG.error("MeshQueue", `Failed to dispatch task to node ${nodeId}: ${e?.message}`);
1323
1325
  });
@@ -1389,7 +1391,7 @@ Do NOT retry on this node. Consider reassigning to a different node or asking th
1389
1391
  function injectMeshSystemMessage(components, args) {
1390
1392
  if (args.event === "agent:generating_completed") {
1391
1393
  const sessionId = readNonEmptyString(args.metadataEvent.targetSessionId);
1392
- const nodeId = readNonEmptyString(args.metadataEvent.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
1394
+ const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
1393
1395
  const providerType = readNonEmptyString(args.metadataEvent.providerType);
1394
1396
  if (sessionId) {
1395
1397
  updateSessionTaskStatus(args.meshId, sessionId, "completed");
@@ -1399,6 +1401,15 @@ function injectMeshSystemMessage(components, args) {
1399
1401
  }, 500);
1400
1402
  }
1401
1403
  }
1404
+ } else if (args.event === "agent:ready") {
1405
+ const sessionId = readNonEmptyString(args.metadataEvent.targetSessionId);
1406
+ const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
1407
+ const providerType = readNonEmptyString(args.metadataEvent.providerType);
1408
+ if (sessionId && nodeId && providerType) {
1409
+ setTimeout(() => {
1410
+ tryAssignQueueTask(components, args.meshId, nodeId, sessionId, providerType);
1411
+ }, 500);
1412
+ }
1402
1413
  } else if (args.event === "agent:stopped") {
1403
1414
  const sessionId = readNonEmptyString(args.metadataEvent.targetSessionId);
1404
1415
  if (sessionId) {
@@ -1410,7 +1421,7 @@ function injectMeshSystemMessage(components, args) {
1410
1421
  try {
1411
1422
  appendLedgerEntry(args.meshId, {
1412
1423
  kind: ledgerKind,
1413
- nodeId: readNonEmptyString(args.metadataEvent.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId) || void 0,
1424
+ nodeId: readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId) || void 0,
1414
1425
  sessionId: readNonEmptyString(args.metadataEvent.targetSessionId) || void 0,
1415
1426
  providerType: readNonEmptyString(args.metadataEvent.providerType) || void 0,
1416
1427
  payload: {
@@ -1430,7 +1441,7 @@ function injectMeshSystemMessage(components, args) {
1430
1441
  const maxRetries = mesh?.policy?.maxTaskRetries ?? 1;
1431
1442
  recoveryContext = getSessionRecoveryContext(args.meshId, {
1432
1443
  sessionId: readNonEmptyString(args.metadataEvent.targetSessionId) || void 0,
1433
- nodeId: readNonEmptyString(args.metadataEvent.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId) || void 0,
1444
+ nodeId: readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId) || void 0,
1434
1445
  maxRetries
1435
1446
  });
1436
1447
  recoveryContext.failedProviderType = readNonEmptyString(args.metadataEvent.providerType) || null;
@@ -1525,6 +1536,7 @@ function handleMeshForwardEvent(components, payload) {
1525
1536
  const nodeLabel = nodeId ? `Node '${nodeId}'` : workspace ? `Agent at ${workspace}` : "Remote agent";
1526
1537
  return injectMeshSystemMessage(components, {
1527
1538
  meshId,
1539
+ nodeId,
1528
1540
  nodeLabel,
1529
1541
  event: eventName,
1530
1542
  metadataEvent: {
@@ -1554,10 +1566,12 @@ function setupMeshEventForwarding(components) {
1554
1566
  if (!meshId) return;
1555
1567
  const targetNode = mesh?.nodes?.find((n) => n.workspace === workspace);
1556
1568
  const runtimeNodeId = readNonEmptyString(settings.meshNodeId);
1569
+ const resolvedNodeId = targetNode?.id || runtimeNodeId;
1557
1570
  const nodeLabel = targetNode ? `Node '${targetNode.id}'` : runtimeNodeId ? `Node '${runtimeNodeId}'` : `Agent at ${workspace}`;
1558
1571
  injectMeshSystemMessage(components, {
1559
1572
  meshId,
1560
1573
  sourceInstanceId: instanceId,
1574
+ nodeId: resolvedNodeId,
1561
1575
  nodeLabel,
1562
1576
  event: event.event,
1563
1577
  metadataEvent: event
@@ -1578,6 +1592,7 @@ var init_mesh_events = __esm({
1578
1592
  "agent:generating_completed",
1579
1593
  "agent:waiting_approval",
1580
1594
  "agent:stopped",
1595
+ "agent:ready",
1581
1596
  "monitor:long_generating"
1582
1597
  ]);
1583
1598
  EVENT_TO_LEDGER_KIND = {
@@ -2695,6 +2710,8 @@ var init_provider_cli_adapter = __esm({
2695
2710
  statusHistory = [];
2696
2711
  // ─── CLI Scripts (script-based parsing) ───
2697
2712
  cliScripts;
2713
+ /** Per-session opaque state object created by cliScripts.createState(), reset on stop. */
2714
+ scriptState = null;
2698
2715
  runtimeSettings = {};
2699
2716
  /** Full accumulated rendered PTY transcript for parser/readback use */
2700
2717
  accumulatedBuffer = "";
@@ -2876,6 +2893,7 @@ ${lastSnapshot}`;
2876
2893
  this.cliScripts = scripts;
2877
2894
  this.parsedStatusCache = null;
2878
2895
  this.parseErrorMessage = null;
2896
+ this.scriptState = typeof scripts.createState === "function" ? scripts.createState() : null;
2879
2897
  const scriptNames = listCliScriptNames(scripts);
2880
2898
  LOG.info("CLI", `[${this.cliType}] CLI scripts injected: [${scriptNames.join(", ")}]`);
2881
2899
  }
@@ -2993,6 +3011,7 @@ ${lastSnapshot}`;
2993
3011
  this.ready = false;
2994
3012
  this.startupParseGate = false;
2995
3013
  this.spawnAt = 0;
3014
+ this.scriptState = null;
2996
3015
  this.onStatusChange?.();
2997
3016
  });
2998
3017
  this.spawnAt = Date.now();
@@ -3766,7 +3785,7 @@ ${lastSnapshot}`;
3766
3785
  scope: this.currentTurnScope,
3767
3786
  runtimeSettings: this.runtimeSettings
3768
3787
  });
3769
- const session = this.cliScripts.parseSession({ ...input, tail, tailScreen: buildCliScreenSnapshot(tail) });
3788
+ const session = this.cliScripts.parseSession(this.scriptState, { ...input, tail, tailScreen: buildCliScreenSnapshot(tail) });
3770
3789
  this.parseErrorMessage = null;
3771
3790
  return session && typeof session === "object" ? session : null;
3772
3791
  } catch (e) {
@@ -3780,7 +3799,7 @@ ${lastSnapshot}`;
3780
3799
  if (!this.cliScripts?.detectStatus) return null;
3781
3800
  try {
3782
3801
  const screenText = this.terminalScreen.getText();
3783
- const status = this.cliScripts.detectStatus({
3802
+ const status = this.cliScripts.detectStatus(this.scriptState, {
3784
3803
  tail: text.slice(-500),
3785
3804
  screenText,
3786
3805
  rawBuffer: this.accumulatedRawBuffer,
@@ -3799,7 +3818,7 @@ ${lastSnapshot}`;
3799
3818
  try {
3800
3819
  const screenText = this.terminalScreen.getText();
3801
3820
  const buffer = screenText || this.accumulatedBuffer;
3802
- return this.cliScripts.parseApproval({
3821
+ return this.cliScripts.parseApproval(this.scriptState, {
3803
3822
  buffer,
3804
3823
  screenText,
3805
3824
  rawBuffer: this.accumulatedRawBuffer,
@@ -3907,7 +3926,7 @@ ${lastSnapshot}`;
3907
3926
  scope: this.currentTurnScope,
3908
3927
  runtimeSettings: this.runtimeSettings
3909
3928
  });
3910
- return await Promise.resolve(fn({
3929
+ return await Promise.resolve(fn(this.scriptState, {
3911
3930
  ...input,
3912
3931
  args: args && typeof args === "object" ? { ...args } : {}
3913
3932
  }));
@@ -14983,11 +15002,13 @@ async function handleOpenPanel(h, args) {
14983
15002
  async function handlePtyInput(h, args) {
14984
15003
  const { cliType, data, targetSessionId } = args || {};
14985
15004
  if (!data) return { success: false, error: "data required" };
15005
+ const cleanData = typeof data === "string" ? data.replace(/\x1b\[[?>][0-9;]*c/g, "") : data;
15006
+ if (!cleanData) return { success: true };
14986
15007
  const adapter = h.getCliAdapter(targetSessionId || cliType);
14987
15008
  if (!adapter || typeof adapter.writeRaw !== "function") {
14988
15009
  return { success: false, error: `CLI adapter not found: ${targetSessionId || cliType || "unknown"}` };
14989
15010
  }
14990
- await adapter.writeRaw(data);
15011
+ await adapter.writeRaw(cleanData);
14991
15012
  return { success: true };
14992
15013
  }
14993
15014
  function handlePtyResize(_h, args) {
@@ -16617,6 +16638,8 @@ var CliProviderInstance = class {
16617
16638
  this.completedDebounceTimer = null;
16618
16639
  }, 3e3);
16619
16640
  }
16641
+ } else if (newStatus === "idle" && this.lastStatus === "starting") {
16642
+ this.pushEvent({ event: "agent:ready", chatTitle, timestamp: now });
16620
16643
  } else if (newStatus === "stopped") {
16621
16644
  if (this.generatingDebounceTimer) {
16622
16645
  clearTimeout(this.generatingDebounceTimer);
@@ -18365,9 +18388,6 @@ function buildCoordinatorDelegatedCliLaunchOptions(input) {
18365
18388
  const cliType = String(input.cliType || "").trim();
18366
18389
  const cliArgs = Array.isArray(input.cliArgs) ? [...input.cliArgs] : [];
18367
18390
  const env = { ...input.env || {}, ...COORDINATOR_DELEGATED_ENV_UNSETS };
18368
- if (cliType === "hermes-cli" && !hasCliArg(cliArgs, "--ignore-user-config")) {
18369
- cliArgs.unshift("--ignore-user-config");
18370
- }
18371
18391
  if (cliType === "claude-cli" && !hasCliArg(cliArgs, "--mcp-config")) {
18372
18392
  cliArgs.unshift("--mcp-config", ensureEmptyDelegatedMcpConfig(input.workspace));
18373
18393
  }
@@ -21702,6 +21722,22 @@ function resolveMeshCoordinatorSetup(options) {
21702
21722
  if (!instructions || !template?.trim()) {
21703
21723
  return { kind: "unsupported", reason: "Provider manual MCP setup is missing instructions or template" };
21704
21724
  }
21725
+ const renderedTemplate = renderMeshCoordinatorTemplate(template, {
21726
+ meshId,
21727
+ workspace,
21728
+ serverName,
21729
+ adhdevMcpCommand: options.adhdevMcpCommand || DEFAULT_ADHDEV_MCP_COMMAND
21730
+ });
21731
+ const isCliCommand = !renderedTemplate.trim().includes("\n") && !renderedTemplate.trim().startsWith("{");
21732
+ if (isCliCommand) {
21733
+ return {
21734
+ kind: "cli_command",
21735
+ serverName,
21736
+ command: renderedTemplate.trim(),
21737
+ requiresRestart: mcpConfig.requiresRestart === true,
21738
+ instructions
21739
+ };
21740
+ }
21705
21741
  return {
21706
21742
  kind: "manual",
21707
21743
  serverName,
@@ -21709,12 +21745,7 @@ function resolveMeshCoordinatorSetup(options) {
21709
21745
  configPathCommand: mcpConfig.configPathCommand,
21710
21746
  requiresRestart: mcpConfig.requiresRestart === true,
21711
21747
  instructions,
21712
- template: renderMeshCoordinatorTemplate(template, {
21713
- meshId,
21714
- workspace,
21715
- serverName,
21716
- adhdevMcpCommand: options.adhdevMcpCommand || DEFAULT_ADHDEV_MCP_COMMAND
21717
- })
21748
+ template: renderedTemplate
21718
21749
  };
21719
21750
  }
21720
21751
  return {
@@ -23896,6 +23927,93 @@ var DaemonCommandRouter = class {
23896
23927
  meshCoordinatorSetup: coordinatorSetup
23897
23928
  };
23898
23929
  }
23930
+ if (coordinatorSetup.kind === "cli_command") {
23931
+ let cliCmdSystemPrompt = "";
23932
+ try {
23933
+ cliCmdSystemPrompt = buildCoordinatorSystemPrompt2({ mesh, coordinatorCliType: cliType });
23934
+ } catch (error) {
23935
+ const message = error?.message || String(error);
23936
+ LOG.error("MeshCoordinator", `Failed to build coordinator prompt: ${message}`);
23937
+ return {
23938
+ success: false,
23939
+ code: "mesh_coordinator_prompt_failed",
23940
+ error: `Failed to build Repo Mesh coordinator prompt: ${message}`,
23941
+ meshId,
23942
+ cliType,
23943
+ workspace
23944
+ };
23945
+ }
23946
+ try {
23947
+ const { execFileSync: execCmdSync } = await import("child_process");
23948
+ const cmdParts = coordinatorSetup.command.trim().split(/\s+/);
23949
+ const [regCmd, ...regArgs] = cmdParts;
23950
+ LOG.info("MeshCoordinator", `Running MCP registration: ${coordinatorSetup.command}`);
23951
+ execCmdSync(regCmd, regArgs, { stdio: "pipe", timeout: 15e3 });
23952
+ } catch (error) {
23953
+ LOG.warn("MeshCoordinator", `MCP registration command failed (may be pre-registered): ${error?.message || error}`);
23954
+ }
23955
+ const cliCmdArgs = [];
23956
+ const cliCmdEnv = {};
23957
+ if (cliCmdSystemPrompt) {
23958
+ if (cliType === "codex-cli") {
23959
+ cliCmdArgs.push("-c", `developer_instructions=${JSON.stringify(cliCmdSystemPrompt)}`);
23960
+ } else if (cliType === "gemini-cli") {
23961
+ try {
23962
+ const { writeFileSync: wfs, existsSync: efs, readFileSync: rfs } = await import("fs");
23963
+ const geminiMdPath = `${workspace}/GEMINI.md`;
23964
+ const marker = "<!-- adhdev-mesh-coordinator-prompt -->";
23965
+ const markerEnd = "<!-- /adhdev-mesh-coordinator-prompt -->";
23966
+ const block = `${marker}
23967
+ ${cliCmdSystemPrompt}
23968
+ ${markerEnd}`;
23969
+ if (efs(geminiMdPath)) {
23970
+ const existing = rfs(geminiMdPath, "utf-8");
23971
+ const replaced = existing.replace(
23972
+ new RegExp(`${marker}[\\s\\S]*?${markerEnd}`, "g"),
23973
+ block
23974
+ );
23975
+ wfs(geminiMdPath, replaced.includes(marker) ? replaced : `${existing}
23976
+
23977
+ ${block}`);
23978
+ } else {
23979
+ wfs(geminiMdPath, block);
23980
+ }
23981
+ LOG.info("MeshCoordinator", `Wrote coordinator prompt to ${workspace}/GEMINI.md`);
23982
+ } catch (e) {
23983
+ LOG.warn("MeshCoordinator", `Could not write GEMINI.md: ${e?.message || e}`);
23984
+ }
23985
+ }
23986
+ }
23987
+ const cliCmdLaunch = await this.deps.cliManager.handleCliCommand("launch_cli", {
23988
+ cliType,
23989
+ dir: workspace,
23990
+ cliArgs: cliCmdArgs.length > 0 ? cliCmdArgs : void 0,
23991
+ env: Object.keys(cliCmdEnv).length > 0 ? cliCmdEnv : void 0,
23992
+ settings: { meshCoordinatorFor: meshId }
23993
+ });
23994
+ if (!cliCmdLaunch?.success) {
23995
+ return { success: false, error: cliCmdLaunch?.error || "Failed to launch CLI session" };
23996
+ }
23997
+ LOG.info("MeshCoordinator", `Launched ${cliType} coordinator (cli_command) for mesh ${meshId}`);
23998
+ try {
23999
+ const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
24000
+ appendLedgerEntry2(meshId, {
24001
+ kind: "coordinator_started",
24002
+ sessionId: cliCmdLaunch.sessionId || cliCmdLaunch.id,
24003
+ providerType: cliType,
24004
+ payload: { workspace }
24005
+ });
24006
+ } catch {
24007
+ }
24008
+ return {
24009
+ success: true,
24010
+ meshId,
24011
+ cliType,
24012
+ workspace,
24013
+ sessionId: cliCmdLaunch.sessionId || cliCmdLaunch.id,
24014
+ mcpRegistered: true
24015
+ };
24016
+ }
23899
24017
  const configFormat = coordinatorSetup.configFormat;
23900
24018
  if (configFormat !== "claude_mcp_json" && configFormat !== "hermes_config_yaml") {
23901
24019
  return {