@adhdev/daemon-core 0.9.82-rc.357 → 0.9.82-rc.359

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.
@@ -40,6 +40,34 @@ export declare function buildPinnedGlobalInstallCommand(options: {
40
40
  export declare function getNpmExecOptions(platform?: NodeJS.Platform): NpmExecOptions;
41
41
  export declare function execNpmCommandSync(args: string[], options?: ExecFileSyncOptions, surface?: Pick<CurrentGlobalInstallSurface, 'npmExecutable' | 'npmArgsPrefix' | 'execOptions'>): Buffer | string;
42
42
  export declare function stopSessionHostProcesses(appName: string): Promise<void>;
43
+ /**
44
+ * Enumerate processes that have a locked native addon (conpty.node /
45
+ * ghostty-vt.dll) of *this* install memory-mapped.
46
+ *
47
+ * `stopSessionHostProcesses()` only knows the single managed session-host pid, so
48
+ * any *foreign* holder — e.g. an orphaned `pty_*probe*.cjs` left in `%TEMP%` — is
49
+ * invisible to it and keeps the addon locked through every install retry, dooming
50
+ * the upgrade with EBUSY. This scans by the module's full path so we only ever
51
+ * target a holder of the exact `packageRoot` being replaced (never an unrelated
52
+ * install's copy). Windows-only — these locks don't exist on POSIX.
53
+ */
54
+ export declare function listForeignNativeAddonHolders(packageRoot: string | null | undefined): Array<{
55
+ pid: number;
56
+ commandLine: string | null;
57
+ }>;
58
+ /**
59
+ * Terminate every foreign process holding this install's native addon mapped,
60
+ * then wait for each to actually exit so the mapping is released before npm
61
+ * copies the file into its staging dir. Returns what it found/killed so the
62
+ * caller can surface an actionable recovery message on failure.
63
+ */
64
+ export declare function stopForeignNativeAddonHolders(packageRoot: string | null | undefined, options?: {
65
+ parentPid?: number;
66
+ }): Promise<Array<{
67
+ pid: number;
68
+ commandLine: string | null;
69
+ killed: boolean;
70
+ }>>;
43
71
  /**
44
72
  * Best-effort removal of a leftover npm staging entry.
45
73
  *
package/dist/index.js CHANGED
@@ -316,10 +316,10 @@ function readInjected(value) {
316
316
  }
317
317
  function getDaemonBuildInfo() {
318
318
  if (cached) return cached;
319
- const commit = readInjected(true ? "37b9d1d9e10336707dbc0861a96d5bcc55cc015e" : void 0) ?? "unknown";
320
- const commitShort = readInjected(true ? "37b9d1d9" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
321
- const version = readInjected(true ? "0.9.82-rc.357" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
322
- const builtAt = readInjected(true ? "2026-06-23T00:25:21.599Z" : void 0);
319
+ const commit = readInjected(true ? "56a1f2a986ab2c2bb7888189d9b027d6067f2317" : void 0) ?? "unknown";
320
+ const commitShort = readInjected(true ? "56a1f2a9" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
321
+ const version = readInjected(true ? "0.9.82-rc.359" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
322
+ const builtAt = readInjected(true ? "2026-06-23T05:03:11.133Z" : void 0);
323
323
  cached = builtAt ? { commit, commitShort, version, builtAt } : { commit, commitShort, version };
324
324
  return cached;
325
325
  }
@@ -13015,9 +13015,7 @@ function isLocalAutoLaunchNode(node) {
13015
13015
  const machineId = readNonEmptyString2(node?.machineId);
13016
13016
  const appConfig = loadConfig();
13017
13017
  const localMachineId = readNonEmptyString2(appConfig.machineId) || readNonEmptyString2(appConfig.registeredMachineId);
13018
- const cloudDaemonId = localMachineId ? `daemon_${localMachineId}` : "";
13019
- const standaloneDaemonId = localMachineId ? `standalone_${localMachineId}` : "";
13020
- const daemonMatchesLocal = !daemonId || daemonId === cloudDaemonId || daemonId === standaloneDaemonId;
13018
+ const daemonMatchesLocal = !daemonId || daemonIdsEquivalent(daemonId, localMachineId);
13021
13019
  const machineMatchesLocal = !machineId || !!localMachineId && machineId === localMachineId;
13022
13020
  if (node?.isLocalWorktree === true) {
13023
13021
  return daemonMatchesLocal && machineMatchesLocal;
@@ -13751,7 +13749,7 @@ function injectMeshSystemMessage(components, args) {
13751
13749
  occurredAt: occurredAtMs != null ? new Date(occurredAtMs).toISOString() : void 0,
13752
13750
  taskId: eventTaskId
13753
13751
  });
13754
- const leaveDirectDispatchActive = !task && opts?.tentativeIfDirect === true;
13752
+ const leaveDirectDispatchActive = !task && opts?.tentativeIfDirect === true || !eventTaskId && !sessionHasActiveAssignment(args.meshId, sessionId);
13755
13753
  if (!leaveDirectDispatchActive) {
13756
13754
  updateDirectDispatchStatus(args.meshId, sessionId, outcome, eventTaskId);
13757
13755
  }
@@ -13850,7 +13848,9 @@ function injectMeshSystemMessage(components, args) {
13850
13848
  }
13851
13849
  if (sessionId) {
13852
13850
  const startedTaskId = readNonEmptyString2(args.metadataEvent.taskId) || void 0;
13853
- updateDirectDispatchStatus(args.meshId, sessionId, "acked", startedTaskId);
13851
+ if (startedTaskId || sessionHasActiveAssignment(args.meshId, sessionId)) {
13852
+ updateDirectDispatchStatus(args.meshId, sessionId, "acked", startedTaskId);
13853
+ }
13854
13854
  const activeDeliveries = (() => {
13855
13855
  try {
13856
13856
  return MeshRuntimeStore.getInstance().getActiveSessionDeliveries(args.meshId, sessionId);
@@ -13951,7 +13951,7 @@ function injectMeshSystemMessage(components, args) {
13951
13951
  targetNodeId: autoNodeId
13952
13952
  });
13953
13953
  LOG.info("MeshRecovery", `Auto-requeued failed task: ${task.id} for node ${autoNodeId}`);
13954
- const node = mesh?.nodes.find((n) => n.id === autoNodeId);
13954
+ const node = mesh?.nodes.find((n) => meshNodeIdMatches(n, autoNodeId));
13955
13955
  if (node) {
13956
13956
  components.cliManager.handleCliCommand("launch_cli", {
13957
13957
  cliType: recoveryContext.failedProviderType,
@@ -14681,7 +14681,7 @@ async function pullRemoteNodeQueues(components, mesh, localDaemonId, candidateDa
14681
14681
  for (const node of mesh.nodes) {
14682
14682
  const nodeDaemonId = readNonEmptyString2(node.daemonId);
14683
14683
  if (!nodeDaemonId) continue;
14684
- if (localDaemonId && nodeDaemonId === localDaemonId) continue;
14684
+ if (daemonIdsEquivalent(nodeDaemonId, localDaemonId)) continue;
14685
14685
  if (candidateDaemonIds.includes(nodeDaemonId)) continue;
14686
14686
  for (const pendingEventArgs of pulls) {
14687
14687
  let events;
@@ -14738,7 +14738,7 @@ async function reconcileUnterminatedDirectDispatches(components, mesh, selfIds,
14738
14738
  if (!sessionId || !nodeId || !taskId) continue;
14739
14739
  const node = nodeById.get(nodeId);
14740
14740
  const nodeDaemonId = readNonEmptyString2(node?.daemonId);
14741
- const isLocalNode = !nodeDaemonId || selfIds.includes(nodeDaemonId) || localDaemonId !== void 0 && nodeDaemonId === localDaemonId || !!components.instanceManager.getInstance(sessionId);
14741
+ const isLocalNode = !nodeDaemonId || selfIds.includes(nodeDaemonId) || daemonIdsEquivalent(nodeDaemonId, localDaemonId) || !!components.instanceManager.getInstance(sessionId);
14742
14742
  const providerType = readNonEmptyString2(dispatch.providerType);
14743
14743
  const readArgs = {
14744
14744
  sessionId,
@@ -14813,7 +14813,7 @@ async function collectLiveNodesWithSessions(components, mesh, selfIds, localDaem
14813
14813
  const dispatchMeshCommand = components.dispatchMeshCommand;
14814
14814
  return Promise.all(mesh.nodes.map(async (node) => {
14815
14815
  const nodeDaemonId = readNonEmptyString2(node.daemonId);
14816
- const isLocalNode = !nodeDaemonId || selfIds.includes(nodeDaemonId) || localDaemonId !== void 0 && nodeDaemonId === localDaemonId;
14816
+ const isLocalNode = !nodeDaemonId || selfIds.includes(nodeDaemonId) || daemonIdsEquivalent(nodeDaemonId, localDaemonId);
14817
14817
  let statusResult;
14818
14818
  try {
14819
14819
  if (isLocalNode) {
@@ -19540,6 +19540,7 @@ __export(evaluator_exports, {
19540
19540
  evaluateCondition: () => evaluateCondition,
19541
19541
  extractButtonsFromRule: () => extractButtonsFromRule,
19542
19542
  extractTitle: () => extractTitle,
19543
+ lastContiguousNumberedBlock: () => lastContiguousNumberedBlock,
19543
19544
  resolveSections: () => resolveSections,
19544
19545
  sectionText: () => sectionText
19545
19546
  });
@@ -19780,7 +19781,6 @@ function extractButtonsFromRule(rule, hay) {
19780
19781
  label += " " + next.trim();
19781
19782
  j += 1;
19782
19783
  }
19783
- if (buttons.some((b) => b.index === idx)) continue;
19784
19784
  const key = keyTemplate.replace(/\{index\}/g, String(idx));
19785
19785
  buttons.push({ index: idx, label, key, current });
19786
19786
  i = j - 1;
@@ -19792,13 +19792,22 @@ function extractButtonsFromRule(rule, hay) {
19792
19792
  const idx = Number(m[1]);
19793
19793
  const label = String(m[2] ?? "").trim();
19794
19794
  if (!Number.isFinite(idx) || idx <= 0 || !label) continue;
19795
- if (buttons.some((b) => b.index === idx)) continue;
19796
19795
  const key = keyTemplate.replace(/\{index\}/g, String(idx));
19797
19796
  buttons.push({ index: idx, label, key, current: hasCursorMarker(m[0]) });
19798
19797
  }
19799
19798
  }
19800
- buttons.sort((a, b) => a.index - b.index);
19801
- return buttons;
19799
+ const block2 = lastContiguousNumberedBlock(buttons);
19800
+ block2.sort((a, b) => a.index - b.index);
19801
+ return block2;
19802
+ }
19803
+ function lastContiguousNumberedBlock(entries) {
19804
+ if (entries.length <= 1) return entries.slice();
19805
+ let start = entries.length - 1;
19806
+ for (let i = entries.length - 1; i > 0; i -= 1) {
19807
+ if (entries[i - 1].index === entries[i].index - 1) start = i - 1;
19808
+ else break;
19809
+ }
19810
+ return entries.slice(start);
19802
19811
  }
19803
19812
  function hasCursorMarker(text) {
19804
19813
  return /^\s*[❯›>]/.test(text);
@@ -34216,6 +34225,9 @@ function collectStableSizes(when, sizes) {
34216
34225
  }
34217
34226
  }
34218
34227
 
34228
+ // src/providers/spec/cli-adapter.ts
34229
+ init_evaluator();
34230
+
34219
34231
  // src/providers/spec/native-history-executor.ts
34220
34232
  var fs13 = __toESM(require("fs"));
34221
34233
  var os18 = __toESM(require("os"));
@@ -35430,21 +35442,19 @@ var SpecCliAdapter = class _SpecCliAdapter {
35430
35442
  const ec = action.extract_choices;
35431
35443
  if (!ec?.pattern) return [];
35432
35444
  const text = this.readScreenSectionText(ec.section);
35433
- const out = [];
35434
- const seen = /* @__PURE__ */ new Set();
35445
+ const all = [];
35435
35446
  for (const rawLine of text.split("\n")) {
35436
35447
  const line = rawLine.replace(/\r$/, "");
35437
35448
  const m = new RegExp(ec.pattern, ec.flags ?? "").exec(line);
35438
35449
  if (!m) continue;
35439
35450
  const idx = Number(m[1]);
35440
- if (!Number.isFinite(idx) || seen.has(idx)) continue;
35451
+ if (!Number.isFinite(idx) || idx <= 0) continue;
35441
35452
  const label = (m[2] ?? "").replace(/\s+/g, " ").trim();
35442
35453
  if (!label) continue;
35443
35454
  const current = /^\s*[❯›>]/.test(line) || /[✔✓●]\s*$/.test(label);
35444
- seen.add(idx);
35445
- out.push({ index: idx, label, current });
35455
+ all.push({ index: idx, label, current });
35446
35456
  }
35447
- return out;
35457
+ return lastContiguousNumberedBlock(all);
35448
35458
  }
35449
35459
  /** Live text of a named screen section (or the whole screen when no
35450
35460
  * section is named), resolved from the driver's current sections. */
@@ -44860,6 +44870,7 @@ function buildInstallEnvWithNodeOnPath(baseEnv = process.env) {
44860
44870
  const pathKey = Object.keys(env).find((k) => k.toLowerCase() === "path") || "PATH";
44861
44871
  const current = env[pathKey] || "";
44862
44872
  env[pathKey] = current ? `${nodeBinDir};${current}` : nodeBinDir;
44873
+ env.ADHDEV_BOOTSTRAP = "1";
44863
44874
  return env;
44864
44875
  }
44865
44876
  function getNpmExecOptions(platform10 = process.platform) {
@@ -44969,6 +44980,94 @@ async function stopSessionHostProcesses(appName) {
44969
44980
  await waitForPidExit(killedPid, 15e3);
44970
44981
  }
44971
44982
  }
44983
+ var LOCKED_NATIVE_ADDON_BASENAMES = ["conpty.node", "ghostty-vt.dll"];
44984
+ function listForeignNativeAddonHolders(packageRoot) {
44985
+ if (process.platform !== "win32" || !packageRoot) return [];
44986
+ const rootLower = packageRoot.replace(/\//g, "\\").replace(/'/g, "''").toLowerCase();
44987
+ const endsWithChecks = LOCKED_NATIVE_ADDON_BASENAMES.map((name) => `$lf.EndsWith('${name}')`).join(" -or ");
44988
+ const script = [
44989
+ `$root = '${rootLower}'`,
44990
+ `Get-Process node -ErrorAction SilentlyContinue | ForEach-Object {`,
44991
+ ` $p = $_`,
44992
+ ` try {`,
44993
+ ` foreach ($m in $p.Modules) {`,
44994
+ ` $fn = $m.FileName`,
44995
+ ` if ($fn) {`,
44996
+ ` $lf = $fn.ToLower()`,
44997
+ ` if ($lf.StartsWith($root) -and (${endsWithChecks})) { $p.Id; break }`,
44998
+ ` }`,
44999
+ ` }`,
45000
+ ` } catch {}`,
45001
+ `}`
45002
+ ].join("\n");
45003
+ let out = "";
45004
+ try {
45005
+ out = String((0, import_child_process8.execFileSync)("powershell.exe", [
45006
+ "-NoProfile",
45007
+ "-NonInteractive",
45008
+ "-ExecutionPolicy",
45009
+ "Bypass",
45010
+ "-Command",
45011
+ script
45012
+ ], { encoding: "utf8", timeout: 8e3, stdio: ["ignore", "pipe", "ignore"], windowsHide: true })).trim();
45013
+ } catch {
45014
+ return [];
45015
+ }
45016
+ const selfPid = process.pid;
45017
+ const seen = /* @__PURE__ */ new Set();
45018
+ const holders = [];
45019
+ for (const line of out.split(/\r?\n/)) {
45020
+ const pid = Number.parseInt(line.trim(), 10);
45021
+ if (!Number.isFinite(pid) || pid <= 0 || pid === selfPid || seen.has(pid)) continue;
45022
+ seen.add(pid);
45023
+ holders.push({ pid, commandLine: getProcessCommandLine(pid) });
45024
+ }
45025
+ return holders;
45026
+ }
45027
+ async function stopForeignNativeAddonHolders(packageRoot, options = {}) {
45028
+ if (process.platform !== "win32" || !packageRoot) return [];
45029
+ const parentPid = Number.isFinite(options.parentPid) ? Number(options.parentPid) : -1;
45030
+ const holders = listForeignNativeAddonHolders(packageRoot);
45031
+ const results = [];
45032
+ for (const holder of holders) {
45033
+ if (holder.pid === parentPid) continue;
45034
+ appendUpgradeLog(
45035
+ `Foreign native-addon holder found: pid ${holder.pid}${holder.commandLine ? ` \u2014 ${holder.commandLine}` : ""}`
45036
+ );
45037
+ const killed = killPid(holder.pid);
45038
+ if (killed) {
45039
+ await waitForPidExit(holder.pid, 15e3);
45040
+ appendUpgradeLog(`Terminated foreign native-addon holder pid ${holder.pid}`);
45041
+ } else {
45042
+ appendUpgradeLog(`Failed to terminate foreign native-addon holder pid ${holder.pid}`);
45043
+ }
45044
+ results.push({ ...holder, killed });
45045
+ }
45046
+ return results;
45047
+ }
45048
+ function getUpgradeFailureNoticePath() {
45049
+ const home = os27.homedir();
45050
+ const dir = path36.join(home, ".adhdev");
45051
+ try {
45052
+ fs25.mkdirSync(dir, { recursive: true });
45053
+ } catch {
45054
+ }
45055
+ return path36.join(dir, "daemon-upgrade-last-error.txt");
45056
+ }
45057
+ function buildManualRecoveryCommand(installCommand) {
45058
+ return [installCommand.command, ...installCommand.args].map((part) => /\s/.test(part) ? `"${part}"` : part).join(" ");
45059
+ }
45060
+ function emitUpgradeFailureNotice(lines) {
45061
+ const body = lines.join("\n");
45062
+ appendUpgradeLog(`Upgrade blocked \u2014 user action required:
45063
+ ${body}`);
45064
+ try {
45065
+ fs25.writeFileSync(getUpgradeFailureNoticePath(), `[${(/* @__PURE__ */ new Date()).toISOString()}]
45066
+ ${body}
45067
+ `, "utf8");
45068
+ } catch {
45069
+ }
45070
+ }
44972
45071
  function isRetriableInstallLockError(error) {
44973
45072
  const code = error?.code;
44974
45073
  if (code === "EBUSY" || code === "EPERM") return true;
@@ -45055,6 +45154,7 @@ async function runDaemonUpgradeHelper(payload) {
45055
45154
  }
45056
45155
  await stopSessionHostProcesses(sessionHostAppName);
45057
45156
  removeDaemonPidFile();
45157
+ await stopForeignNativeAddonHolders(installCommand.surface.packageRoot, { parentPid: payload.parentPid });
45058
45158
  cleanupStaleGlobalInstallDirs(payload.packageName, installCommand.surface);
45059
45159
  const spec = `${payload.packageName}@${payload.targetVersion || "latest"}`;
45060
45160
  appendUpgradeLog(`Installing ${spec}`);
@@ -45076,11 +45176,30 @@ async function runDaemonUpgradeHelper(payload) {
45076
45176
  break;
45077
45177
  } catch (error) {
45078
45178
  if (attempt < maxInstallAttempts && isRetriableInstallLockError(error)) {
45079
- appendUpgradeLog(`Install attempt ${attempt} hit a file lock (${error?.code || "lock"}); cleaning staging and retrying after backoff`);
45179
+ appendUpgradeLog(`Install attempt ${attempt} hit a file lock (${error?.code || "lock"}); clearing holders + staging and retrying after backoff`);
45180
+ await stopForeignNativeAddonHolders(installCommand.surface.packageRoot, { parentPid: payload.parentPid });
45080
45181
  cleanupStaleGlobalInstallDirs(payload.packageName, installCommand.surface);
45081
45182
  await new Promise((resolve24) => setTimeout(resolve24, attempt * 1500));
45082
45183
  continue;
45083
45184
  }
45185
+ if (isRetriableInstallLockError(error)) {
45186
+ const blockers = listForeignNativeAddonHolders(installCommand.surface.packageRoot);
45187
+ const notice = [
45188
+ `adhdev ${spec} could not be installed: a file lock (${error?.code || "EBUSY/EPERM"}) is blocking the native addon.`
45189
+ ];
45190
+ if (blockers.length > 0) {
45191
+ notice.push("Processes still holding the lock:");
45192
+ for (const b of blockers) {
45193
+ notice.push(` pid ${b.pid}${b.commandLine ? ` \u2014 ${b.commandLine}` : ""}`);
45194
+ }
45195
+ notice.push("To recover, stop them and reinstall:");
45196
+ notice.push(` Stop-Process -Id ${blockers.map((b) => b.pid).join(",")} -Force`);
45197
+ } else {
45198
+ notice.push("To recover, reinstall manually:");
45199
+ }
45200
+ notice.push(` ${buildManualRecoveryCommand(installCommand)}`);
45201
+ emitUpgradeFailureNotice(notice);
45202
+ }
45084
45203
  throw error;
45085
45204
  }
45086
45205
  }
@@ -47747,7 +47866,7 @@ var DaemonCommandRouter = class {
47747
47866
  return sanitizedInlineMesh;
47748
47867
  }
47749
47868
  async getMeshForCommand(meshId, inlineMesh, options) {
47750
- const preferInline = options?.preferInline === true;
47869
+ const preferInline = options?.preferInline !== false;
47751
47870
  if (preferInline) {
47752
47871
  const cached4 = this.getCachedInlineMesh(meshId);
47753
47872
  if (cached4) {
@@ -52106,7 +52225,7 @@ ${ptyResult.output.slice(-2e3)}`);
52106
52225
  workspace
52107
52226
  };
52108
52227
  }
52109
- const { existsSync: existsSync46, readFileSync: readFileSync37, writeFileSync: writeFileSync23, copyFileSync: copyFileSync4, mkdirSync: mkdirSync21 } = await import("fs");
52228
+ const { existsSync: existsSync46, readFileSync: readFileSync37, writeFileSync: writeFileSync24, copyFileSync: copyFileSync4, mkdirSync: mkdirSync21 } = await import("fs");
52110
52229
  const { dirname: dirname17 } = await import("path");
52111
52230
  const mcpConfigPath = coordinatorSetup.configPath;
52112
52231
  const hermesManualFallback = cliType === "hermes-cli" && configFormat === "hermes_config_yaml" ? createHermesManualMeshCoordinatorSetup(meshId, workspace) : null;
@@ -52179,7 +52298,7 @@ ${ptyResult.output.slice(-2e3)}`);
52179
52298
  }
52180
52299
  };
52181
52300
  try {
52182
- writeFileSync23(mcpConfigPath, serializeMeshCoordinatorMcpConfig(mcpConfig, configFormat), "utf-8");
52301
+ writeFileSync24(mcpConfigPath, serializeMeshCoordinatorMcpConfig(mcpConfig, configFormat), "utf-8");
52183
52302
  } catch (error) {
52184
52303
  const message = `Could not write MCP config for automatic setup: ${error?.message || error}`;
52185
52304
  LOG.error("MeshCoordinator", message);