@adhdev/daemon-core 0.9.82-rc.447 → 0.9.82-rc.449

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
@@ -409,10 +409,10 @@ function readInjected(value) {
409
409
  }
410
410
  function getDaemonBuildInfo() {
411
411
  if (cached) return cached;
412
- const commit = readInjected(true ? "fb4b6fd9ffb70781692aceb7eea162dd92606fad" : void 0) ?? "unknown";
413
- const commitShort = readInjected(true ? "fb4b6fd9" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
414
- const version = readInjected(true ? "0.9.82-rc.447" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
415
- const builtAt = readInjected(true ? "2026-07-01T16:13:26.252Z" : void 0);
412
+ const commit = readInjected(true ? "fe0e4d2aa03aea2793c2379e5ffc89abef5143d6" : void 0) ?? "unknown";
413
+ const commitShort = readInjected(true ? "fe0e4d2a" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
414
+ const version = readInjected(true ? "0.9.82-rc.449" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
415
+ const builtAt = readInjected(true ? "2026-07-03T01:58:07.610Z" : void 0);
416
416
  cached = builtAt ? { commit, commitShort, version, builtAt } : { commit, commitShort, version };
417
417
  return cached;
418
418
  }
@@ -486,8 +486,8 @@ function validateChangeImpactConfig(raw, source = "inline") {
486
486
  }
487
487
  return { valid: errors.length === 0, errors, config: errors.length === 0 ? config : void 0 };
488
488
  }
489
- function parseConfigText(path43, text) {
490
- if (/\.json$/i.test(path43)) return JSON.parse(text);
489
+ function parseConfigText(path44, text) {
490
+ if (/\.json$/i.test(path44)) return JSON.parse(text);
491
491
  return yaml.load(text);
492
492
  }
493
493
  function loadChangeImpactConfig(repoRoot) {
@@ -1104,14 +1104,14 @@ async function deriveSubmoduleGitlinkStatuses(repo, options) {
1104
1104
  const lastCheckedAt = Date.now();
1105
1105
  const headOidByPath = /* @__PURE__ */ new Map();
1106
1106
  const entries = await Promise.all(
1107
- paths.filter((path43) => !ignoreSet.has(path43)).map(async (path43) => {
1108
- const repoPath = repo.repoRoot + "/" + path43;
1109
- const expected = await readGitlinkExpectedSha(repo, path43, options);
1107
+ paths.filter((path44) => !ignoreSet.has(path44)).map(async (path44) => {
1108
+ const repoPath = repo.repoRoot + "/" + path44;
1109
+ const expected = await readGitlinkExpectedSha(repo, path44, options);
1110
1110
  const actual = await readSubmoduleHeadSha(repo, repoPath, options);
1111
- if (actual) headOidByPath.set(path43, actual);
1111
+ if (actual) headOidByPath.set(path44, actual);
1112
1112
  const outOfSync = actual === null ? true : expected !== null && expected !== actual;
1113
1113
  return {
1114
- path: path43,
1114
+ path: path44,
1115
1115
  // Prefer the recorded gitlink SHA (matches the legacy column); fall back
1116
1116
  // to the checked-out SHA so the field is never empty when both are known.
1117
1117
  commit: expected ?? actual ?? "",
@@ -2557,12 +2557,12 @@ function readGitSubmodules(value, parentRepoRoot) {
2557
2557
  if (!Array.isArray(value)) return void 0;
2558
2558
  const submodules = value.map((entry) => {
2559
2559
  const submodule = readRecord(entry);
2560
- const path43 = readString2(submodule.path);
2560
+ const path44 = readString2(submodule.path);
2561
2561
  const commit = readString2(submodule.commit);
2562
- const repoPath = readString2(submodule.repoPath, submodule.repo_root) ?? joinRepoPath(parentRepoRoot, path43);
2563
- if (!path43 || !commit) return null;
2562
+ const repoPath = readString2(submodule.repoPath, submodule.repo_root) ?? joinRepoPath(parentRepoRoot, path44);
2563
+ if (!path44 || !commit) return null;
2564
2564
  const result = {
2565
- path: path43,
2565
+ path: path44,
2566
2566
  commit,
2567
2567
  dirty: readBoolean(submodule.dirty) ?? false,
2568
2568
  outOfSync: readBoolean(submodule.outOfSync, submodule.out_of_sync) ?? false,
@@ -2887,10 +2887,10 @@ function getMeshConfigPath() {
2887
2887
  return (0, import_path3.join)(getConfigDir(), "meshes.json");
2888
2888
  }
2889
2889
  function loadMeshConfig() {
2890
- const path43 = getMeshConfigPath();
2891
- if (!(0, import_fs3.existsSync)(path43)) return { meshes: [] };
2890
+ const path44 = getMeshConfigPath();
2891
+ if (!(0, import_fs3.existsSync)(path44)) return { meshes: [] };
2892
2892
  try {
2893
- const raw = JSON.parse((0, import_fs3.readFileSync)(path43, "utf-8"));
2893
+ const raw = JSON.parse((0, import_fs3.readFileSync)(path44, "utf-8"));
2894
2894
  if (!raw || !Array.isArray(raw.meshes)) return { meshes: [] };
2895
2895
  const config = raw;
2896
2896
  const migrated = migrateLoadedMeshConfig(config);
@@ -2939,16 +2939,16 @@ function normalizeCapabilityTags(value) {
2939
2939
  return tags.length ? tags : void 0;
2940
2940
  }
2941
2941
  function saveMeshConfig(config) {
2942
- const path43 = getMeshConfigPath();
2943
- (0, import_fs3.writeFileSync)(path43, JSON.stringify(config, null, 2), { encoding: "utf-8", mode: 384 });
2942
+ const path44 = getMeshConfigPath();
2943
+ (0, import_fs3.writeFileSync)(path44, JSON.stringify(config, null, 2), { encoding: "utf-8", mode: 384 });
2944
2944
  }
2945
2945
  function normalizeRepoIdentity(remoteUrl) {
2946
2946
  let identity = remoteUrl.trim();
2947
2947
  if (identity.startsWith("http://") || identity.startsWith("https://")) {
2948
2948
  try {
2949
2949
  const url = new URL(identity);
2950
- const path43 = url.pathname.replace(/^\//, "").replace(/\.git$/, "");
2951
- return `${url.hostname}/${path43}`;
2950
+ const path44 = url.pathname.replace(/^\//, "").replace(/\.git$/, "");
2951
+ return `${url.hostname}/${path44}`;
2952
2952
  } catch {
2953
2953
  }
2954
2954
  }
@@ -4187,10 +4187,10 @@ function rotateArchiveFile(meshId, archivePath) {
4187
4187
  }
4188
4188
  }
4189
4189
  function readArchivedCounts(meshId) {
4190
- const path43 = getArchivedCountsPath(meshId);
4191
- if (!(0, import_fs4.existsSync)(path43)) return { taskCompleted: 0, taskFailed: 0, taskStalled: 0, recoveryAttempted: 0, totalArchived: 0, lastArchivedAt: "" };
4190
+ const path44 = getArchivedCountsPath(meshId);
4191
+ if (!(0, import_fs4.existsSync)(path44)) return { taskCompleted: 0, taskFailed: 0, taskStalled: 0, recoveryAttempted: 0, totalArchived: 0, lastArchivedAt: "" };
4192
4192
  try {
4193
- return JSON.parse((0, import_fs4.readFileSync)(path43, "utf-8"));
4193
+ return JSON.parse((0, import_fs4.readFileSync)(path44, "utf-8"));
4194
4194
  } catch {
4195
4195
  return { taskCompleted: 0, taskFailed: 0, taskStalled: 0, recoveryAttempted: 0, totalArchived: 0, lastArchivedAt: "" };
4196
4196
  }
@@ -5400,11 +5400,11 @@ function readNodeReporter(node, key2) {
5400
5400
  function buildMeshNodeCapabilityTags(node, providerType) {
5401
5401
  const provider = typeof providerType === "string" && providerType.trim() ? providerType.trim() : firstProviderPriority(node?.policy);
5402
5402
  const worktreeBranch = typeof node?.worktreeBranch === "string" && node.worktreeBranch.trim() ? node.worktreeBranch.trim() : null;
5403
- const os30 = readNodeOverride(node, "platform") ?? readNodeReporter(node, "platform") ?? process.platform;
5403
+ const os31 = readNodeOverride(node, "platform") ?? readNodeReporter(node, "platform") ?? process.platform;
5404
5404
  const arch2 = readNodeOverride(node, "arch") ?? readNodeReporter(node, "arch") ?? process.arch;
5405
5405
  return normalizeMeshCapabilityTags([
5406
5406
  ...Array.isArray(node?.capabilities) ? node.capabilities : [],
5407
- `os=${os30}`,
5407
+ `os=${os31}`,
5408
5408
  `arch=${arch2}`,
5409
5409
  ...provider ? [`provider=${provider}`] : [],
5410
5410
  // Worktree nodes automatically expose a "worktree=<branch>" tag so that
@@ -6298,10 +6298,10 @@ var init_mesh_runtime_store = __esm({
6298
6298
  this.migratedMeshIds.add(meshId);
6299
6299
  const count = this.db.prepare("SELECT COUNT(*) AS count FROM mesh_queue WHERE mesh_id = ?").get(meshId);
6300
6300
  if (count.count > 0) return;
6301
- const path43 = legacyQueuePath(meshId);
6302
- if (!(0, import_fs5.existsSync)(path43)) return;
6301
+ const path44 = legacyQueuePath(meshId);
6302
+ if (!(0, import_fs5.existsSync)(path44)) return;
6303
6303
  try {
6304
- const entries = JSON.parse((0, import_fs5.readFileSync)(path43, "utf-8"));
6304
+ const entries = JSON.parse((0, import_fs5.readFileSync)(path44, "utf-8"));
6305
6305
  if (!Array.isArray(entries)) return;
6306
6306
  const insert = this.db.prepare(`
6307
6307
  INSERT OR REPLACE INTO mesh_queue (
@@ -8125,8 +8125,8 @@ function resolveMeshCoordinatorSetup(options) {
8125
8125
  }
8126
8126
  const serverName = mcpConfig.serverName?.trim() || DEFAULT_SERVER_NAME;
8127
8127
  if (mcpConfig.mode === "auto_import") {
8128
- const path43 = mcpConfig.path?.trim();
8129
- if (!path43) {
8128
+ const path44 = mcpConfig.path?.trim();
8129
+ if (!path44) {
8130
8130
  return { kind: "unsupported", reason: "Provider auto-import MCP config is missing a config path" };
8131
8131
  }
8132
8132
  const mcpServer = resolveAdhdevMcpServerLaunch({
@@ -8146,7 +8146,7 @@ function resolveMeshCoordinatorSetup(options) {
8146
8146
  return {
8147
8147
  kind: "auto_import",
8148
8148
  serverName,
8149
- configPath: resolveMcpConfigPath(path43, workspace),
8149
+ configPath: resolveMcpConfigPath(path44, workspace),
8150
8150
  configFormat: mcpConfig.format,
8151
8151
  mcpServer
8152
8152
  };
@@ -8347,8 +8347,8 @@ function stripCoordinatorWrapperFile(filePath) {
8347
8347
  const remaining = (existing.slice(0, openIdx) + existing.slice(closeIdx + CLOSE.length)).replace(/^\s*\n+/, "").replace(/\n+\s*$/, "");
8348
8348
  if (!remaining.trim()) {
8349
8349
  try {
8350
- const fs38 = require("fs");
8351
- fs38.unlinkSync(filePath);
8350
+ const fs39 = require("fs");
8351
+ fs39.unlinkSync(filePath);
8352
8352
  } catch {
8353
8353
  }
8354
8354
  } else {
@@ -8450,10 +8450,10 @@ function getRegistryPath() {
8450
8450
  return (0, import_path6.join)(getDaemonDataDir(), "mesh-coordinators.json");
8451
8451
  }
8452
8452
  function loadMeshCoordinatorRegistry() {
8453
- const path43 = getRegistryPath();
8454
- if (!(0, import_fs6.existsSync)(path43)) return;
8453
+ const path44 = getRegistryPath();
8454
+ if (!(0, import_fs6.existsSync)(path44)) return;
8455
8455
  try {
8456
- const raw = JSON.parse((0, import_fs6.readFileSync)(path43, "utf-8"));
8456
+ const raw = JSON.parse((0, import_fs6.readFileSync)(path44, "utf-8"));
8457
8457
  if (!Array.isArray(raw)) return;
8458
8458
  _registry.clear();
8459
8459
  for (const entry of raw) {
@@ -8624,8 +8624,8 @@ function validateMeshRefineConfig(config, source = "inline") {
8624
8624
  if (rejectedCommands.length) errors.push("one or more validation commands are invalid");
8625
8625
  return { valid: errors.length === 0, errors, bootstrapCommands, commands, rejectedCommands, bootstrapMode, deprecationWarnings };
8626
8626
  }
8627
- function parseConfigText2(path43, text) {
8628
- if (/\.json$/i.test(path43)) return JSON.parse(text);
8627
+ function parseConfigText2(path44, text) {
8628
+ if (/\.json$/i.test(path44)) return JSON.parse(text);
8629
8629
  return yaml2.load(text);
8630
8630
  }
8631
8631
  function loadMeshRefineConfig(mesh, workspace) {
@@ -8952,8 +8952,8 @@ function isCleanIgnoringSubmoduleGitlinks(porcelain, submodulePaths) {
8952
8952
  const lines = porcelain.split(/\r?\n/).filter((line) => line.length > 0);
8953
8953
  for (const line of lines) {
8954
8954
  const status = line.slice(0, 2);
8955
- const path43 = line.slice(3).trim().replace(/\\/g, "/").replace(/\/+$/, "");
8956
- const isGitlinkPointerMove = (status === " M" || status === "M ") && submodulePaths.has(path43);
8955
+ const path44 = line.slice(3).trim().replace(/\\/g, "/").replace(/\/+$/, "");
8956
+ const isGitlinkPointerMove = (status === " M" || status === "M ") && submodulePaths.has(path44);
8957
8957
  if (!isGitlinkPointerMove) return false;
8958
8958
  }
8959
8959
  return true;
@@ -8984,8 +8984,8 @@ function isWorktreeBootstrapStaleRunning(node, nowMs = Date.now()) {
8984
8984
  return false;
8985
8985
  }
8986
8986
  }
8987
- function parseConfigText3(path43, text) {
8988
- if (/\.json$/i.test(path43)) return JSON.parse(text);
8987
+ function parseConfigText3(path44, text) {
8988
+ if (/\.json$/i.test(path44)) return JSON.parse(text);
8989
8989
  return yaml3.load(text);
8990
8990
  }
8991
8991
  function truncateOutput(value) {
@@ -9130,16 +9130,16 @@ async function runMeshWorktreeBootstrap(mesh, workspace) {
9130
9130
  const startedAt = Date.now();
9131
9131
  state.lastCommand = command.displayCommand;
9132
9132
  const resolvedCommand = resolveWin32Executable(command.command);
9133
- const spawn4 = buildWin32ExecFileSpawn(resolvedCommand, command.args);
9133
+ const spawn5 = buildWin32ExecFileSpawn(resolvedCommand, command.args);
9134
9134
  try {
9135
- const result = await execFileAsync4(spawn4.file, spawn4.args, {
9135
+ const result = await execFileAsync4(spawn5.file, spawn5.args, {
9136
9136
  cwd,
9137
9137
  encoding: "utf8",
9138
9138
  timeout: command.timeoutMs || DEFAULT_TIMEOUT_MS2,
9139
9139
  maxBuffer: command.outputLimitBytes || DEFAULT_OUTPUT_LIMIT_BYTES,
9140
9140
  env: { ...process.env, CI: process.env.CI || "1", ...command.env || {} },
9141
9141
  windowsHide: true,
9142
- ...spawn4.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
9142
+ ...spawn5.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
9143
9143
  });
9144
9144
  state.commandsRun?.push({
9145
9145
  command: command.command,
@@ -9262,8 +9262,8 @@ __export(mesh_json_config_exports, {
9262
9262
  function isRecord3(value) {
9263
9263
  return !!value && typeof value === "object" && !Array.isArray(value);
9264
9264
  }
9265
- function parseConfigText4(path43, text) {
9266
- if (/\.json$/i.test(path43)) return JSON.parse(text);
9265
+ function parseConfigText4(path44, text) {
9266
+ if (/\.json$/i.test(path44)) return JSON.parse(text);
9267
9267
  return yaml4.load(text);
9268
9268
  }
9269
9269
  function normalizeOperatingNote(value) {
@@ -11069,10 +11069,10 @@ function readPendingMeshCoordinatorEventsFromDisk(meshId, coordinatorDaemonId) {
11069
11069
  const primaryDaemonId = daemonIds[0];
11070
11070
  const paths = primaryDaemonId ? [getPendingEventsPath(meshId, primaryDaemonId), getPendingEventsPath(meshId)] : [getPendingEventsPath(meshId)];
11071
11071
  const events = [];
11072
- for (const path43 of paths) {
11073
- if (!(0, import_fs11.existsSync)(path43)) continue;
11072
+ for (const path44 of paths) {
11073
+ if (!(0, import_fs11.existsSync)(path44)) continue;
11074
11074
  try {
11075
- const raw = (0, import_fs11.readFileSync)(path43, "utf-8");
11075
+ const raw = (0, import_fs11.readFileSync)(path44, "utf-8");
11076
11076
  const parsed = raw.split("\n").filter(Boolean).flatMap((line) => {
11077
11077
  try {
11078
11078
  return [JSON.parse(line)];
@@ -11080,7 +11080,7 @@ function readPendingMeshCoordinatorEventsFromDisk(meshId, coordinatorDaemonId) {
11080
11080
  return [];
11081
11081
  }
11082
11082
  });
11083
- const filtered = primaryDaemonId && path43 === getPendingEventsPath(meshId) ? parsed.filter((e) => !e.targetCoordinatorDaemonId || daemonIds.includes(e.targetCoordinatorDaemonId)) : parsed;
11083
+ const filtered = primaryDaemonId && path44 === getPendingEventsPath(meshId) ? parsed.filter((e) => !e.targetCoordinatorDaemonId || daemonIds.includes(e.targetCoordinatorDaemonId)) : parsed;
11084
11084
  events.push(...filtered);
11085
11085
  } catch {
11086
11086
  }
@@ -11145,11 +11145,11 @@ function reconcilePendingMeshCoordinatorEvents(meshId, events) {
11145
11145
  const reconciled = terminalJobIds.size === 0 ? events : events.filter((event) => !(event.event === "refine:accepted" && terminalJobIds.has(readRefineJobId2(event))));
11146
11146
  return backfilled.length === 0 ? reconciled : [...reconciled, ...backfilled];
11147
11147
  }
11148
- function trimPendingEventsIfNeeded(path43) {
11148
+ function trimPendingEventsIfNeeded(path44) {
11149
11149
  try {
11150
- if (!(0, import_fs11.existsSync)(path43)) return;
11151
- if ((0, import_fs11.statSync)(path43).size <= MAX_PENDING_EVENTS_BYTES) return;
11152
- const lines = (0, import_fs11.readFileSync)(path43, "utf-8").split("\n").filter(Boolean);
11150
+ if (!(0, import_fs11.existsSync)(path44)) return;
11151
+ if ((0, import_fs11.statSync)(path44).size <= MAX_PENDING_EVENTS_BYTES) return;
11152
+ const lines = (0, import_fs11.readFileSync)(path44, "utf-8").split("\n").filter(Boolean);
11153
11153
  if (lines.length <= MAX_PENDING_EVENTS_KEEP) return;
11154
11154
  const dropped = lines.slice(0, lines.length - MAX_PENDING_EVENTS_KEEP);
11155
11155
  for (const line of dropped) {
@@ -11182,7 +11182,7 @@ function trimPendingEventsIfNeeded(path43) {
11182
11182
  LOG.warn("MeshEvents", `Failed to ledger-record trim-dropped ${event.event} for mesh ${event.meshId}: ${e?.message || e}`);
11183
11183
  }
11184
11184
  }
11185
- (0, import_fs11.writeFileSync)(path43, lines.slice(-MAX_PENDING_EVENTS_KEEP).join("\n") + "\n", "utf-8");
11185
+ (0, import_fs11.writeFileSync)(path44, lines.slice(-MAX_PENDING_EVENTS_KEEP).join("\n") + "\n", "utf-8");
11186
11186
  } catch {
11187
11187
  }
11188
11188
  }
@@ -11212,9 +11212,9 @@ function queuePendingMeshCoordinatorEvent(event) {
11212
11212
  } catch {
11213
11213
  }
11214
11214
  try {
11215
- const path43 = getPendingEventsPath(event.meshId, event.targetCoordinatorDaemonId);
11216
- trimPendingEventsIfNeeded(path43);
11217
- (0, import_fs11.appendFileSync)(path43, JSON.stringify(event) + "\n", "utf-8");
11215
+ const path44 = getPendingEventsPath(event.meshId, event.targetCoordinatorDaemonId);
11216
+ trimPendingEventsIfNeeded(path44);
11217
+ (0, import_fs11.appendFileSync)(path44, JSON.stringify(event) + "\n", "utf-8");
11218
11218
  } catch (e) {
11219
11219
  if (!sqliteOk) throw e;
11220
11220
  LOG.warn("MeshEvents", `JSONL append failed for mesh ${event.meshId}; SQLite holds the event: ${e?.message || e}`);
@@ -11225,10 +11225,10 @@ function queuePendingMeshCoordinatorEvent(event) {
11225
11225
  return false;
11226
11226
  }
11227
11227
  }
11228
- function atomicDrainFile(path43) {
11229
- const tmpPath = `${path43}.draining`;
11228
+ function atomicDrainFile(path44) {
11229
+ const tmpPath = `${path44}.draining`;
11230
11230
  try {
11231
- (0, import_fs11.renameSync)(path43, tmpPath);
11231
+ (0, import_fs11.renameSync)(path44, tmpPath);
11232
11232
  } catch {
11233
11233
  return null;
11234
11234
  }
@@ -11247,10 +11247,10 @@ function atomicDrainFile(path43) {
11247
11247
  return null;
11248
11248
  }
11249
11249
  }
11250
- function selectiveDrainFile(path43, predicate) {
11251
- const tmpPath = `${path43}.draining`;
11250
+ function selectiveDrainFile(path44, predicate) {
11251
+ const tmpPath = `${path44}.draining`;
11252
11252
  try {
11253
- (0, import_fs11.renameSync)(path43, tmpPath);
11253
+ (0, import_fs11.renameSync)(path44, tmpPath);
11254
11254
  } catch {
11255
11255
  return [];
11256
11256
  }
@@ -11282,12 +11282,12 @@ function selectiveDrainFile(path43, predicate) {
11282
11282
  }
11283
11283
  try {
11284
11284
  if (keptLines.length > 0) {
11285
- (0, import_fs11.writeFileSync)(path43, keptLines.join("\n") + "\n", "utf-8");
11285
+ (0, import_fs11.writeFileSync)(path44, keptLines.join("\n") + "\n", "utf-8");
11286
11286
  }
11287
11287
  (0, import_fs11.unlinkSync)(tmpPath);
11288
11288
  } catch {
11289
11289
  try {
11290
- if ((0, import_fs11.existsSync)(tmpPath) && !(0, import_fs11.existsSync)(path43)) (0, import_fs11.renameSync)(tmpPath, path43);
11290
+ if ((0, import_fs11.existsSync)(tmpPath) && !(0, import_fs11.existsSync)(path44)) (0, import_fs11.renameSync)(tmpPath, path44);
11291
11291
  } catch {
11292
11292
  }
11293
11293
  return [];
@@ -11322,16 +11322,16 @@ function drainPendingMeshCoordinatorEvents(meshId, coordinatorDaemonId, opts) {
11322
11322
  LOG.warn("MeshEvents", `SQLite pending-event drain failed for mesh ${meshId}; JSONL fallback only: ${e?.message || e}`);
11323
11323
  }
11324
11324
  const paths = primaryDaemonId ? [getPendingEventsPath(meshId, primaryDaemonId), getPendingEventsPath(meshId)] : [getPendingEventsPath(meshId)];
11325
- for (const path43 of paths) {
11326
- const isSharedFile = !!primaryDaemonId && path43 === getPendingEventsPath(meshId);
11325
+ for (const path44 of paths) {
11326
+ const isSharedFile = !!primaryDaemonId && path44 === getPendingEventsPath(meshId);
11327
11327
  const targets = (e) => !isSharedFile || !e.targetCoordinatorDaemonId || daemonIds.includes(e.targetCoordinatorDaemonId);
11328
11328
  if (onlyEvents) {
11329
- for (const event of selectiveDrainFile(path43, (e) => targets(e) && matchesFilter(e.event))) {
11329
+ for (const event of selectiveDrainFile(path44, (e) => targets(e) && matchesFilter(e.event))) {
11330
11330
  pushUnique(event);
11331
11331
  }
11332
11332
  continue;
11333
11333
  }
11334
- const content = atomicDrainFile(path43);
11334
+ const content = atomicDrainFile(path44);
11335
11335
  if (!content) continue;
11336
11336
  const parsed = content.split("\n").filter(Boolean).flatMap((line) => {
11337
11337
  try {
@@ -11367,9 +11367,9 @@ function retractPendingDispatchBlockedEvent(meshId, taskId, coordinatorDaemonId)
11367
11367
  const daemonIds = normalizeCoordinatorDaemonIds(coordinatorDaemonId);
11368
11368
  const primaryDaemonId = daemonIds[0];
11369
11369
  const paths = primaryDaemonId ? [getPendingEventsPath(meshId, primaryDaemonId), getPendingEventsPath(meshId)] : [getPendingEventsPath(meshId)];
11370
- for (const path43 of paths) {
11370
+ for (const path44 of paths) {
11371
11371
  try {
11372
- removed += selectiveDrainFile(path43, matchesTask).length;
11372
+ removed += selectiveDrainFile(path44, matchesTask).length;
11373
11373
  } catch {
11374
11374
  }
11375
11375
  }
@@ -11410,9 +11410,9 @@ function clearPendingMeshCoordinatorEvents(meshId, coordinatorDaemonId) {
11410
11410
  } catch {
11411
11411
  }
11412
11412
  const paths = coordinatorDaemonId ? [getPendingEventsPath(meshId, coordinatorDaemonId), getPendingEventsPath(meshId)] : [getPendingEventsPath(meshId)];
11413
- for (const path43 of paths) {
11414
- if ((0, import_fs11.existsSync)(path43)) try {
11415
- (0, import_fs11.unlinkSync)(path43);
11413
+ for (const path44 of paths) {
11414
+ if ((0, import_fs11.existsSync)(path44)) try {
11415
+ (0, import_fs11.unlinkSync)(path44);
11416
11416
  } catch {
11417
11417
  }
11418
11418
  }
@@ -11884,9 +11884,9 @@ function findBinary(name) {
11884
11884
  for (const ext of exes) {
11885
11885
  const fullPath = path11.join(p, trimmed + ext);
11886
11886
  try {
11887
- const fs38 = require("fs");
11888
- if (fs38.existsSync(fullPath)) {
11889
- const stat2 = fs38.statSync(fullPath);
11887
+ const fs39 = require("fs");
11888
+ if (fs39.existsSync(fullPath)) {
11889
+ const stat2 = fs39.statSync(fullPath);
11890
11890
  if (stat2.isFile() && (isWin || stat2.mode & 73)) {
11891
11891
  return fullPath;
11892
11892
  }
@@ -11900,12 +11900,12 @@ function findBinary(name) {
11900
11900
  function isScriptBinary(binaryPath) {
11901
11901
  if (!path11.isAbsolute(binaryPath)) return false;
11902
11902
  try {
11903
- const fs38 = require("fs");
11904
- const resolved = fs38.realpathSync(binaryPath);
11903
+ const fs39 = require("fs");
11904
+ const resolved = fs39.realpathSync(binaryPath);
11905
11905
  const head = Buffer.alloc(8);
11906
- const fd = fs38.openSync(resolved, "r");
11907
- fs38.readSync(fd, head, 0, 8, 0);
11908
- fs38.closeSync(fd);
11906
+ const fd = fs39.openSync(resolved, "r");
11907
+ fs39.readSync(fd, head, 0, 8, 0);
11908
+ fs39.closeSync(fd);
11909
11909
  let i = 0;
11910
11910
  if (head[0] === 239 && head[1] === 187 && head[2] === 191) i = 3;
11911
11911
  return head[i] === 35 && head[i + 1] === 33;
@@ -11916,12 +11916,12 @@ function isScriptBinary(binaryPath) {
11916
11916
  function looksLikeMachOOrElf(filePath) {
11917
11917
  if (!path11.isAbsolute(filePath)) return false;
11918
11918
  try {
11919
- const fs38 = require("fs");
11920
- const resolved = fs38.realpathSync(filePath);
11919
+ const fs39 = require("fs");
11920
+ const resolved = fs39.realpathSync(filePath);
11921
11921
  const buf = Buffer.alloc(8);
11922
- const fd = fs38.openSync(resolved, "r");
11923
- fs38.readSync(fd, buf, 0, 8, 0);
11924
- fs38.closeSync(fd);
11922
+ const fd = fs39.openSync(resolved, "r");
11923
+ fs39.readSync(fd, buf, 0, 8, 0);
11924
+ fs39.closeSync(fd);
11925
11925
  let i = 0;
11926
11926
  if (buf[0] === 239 && buf[1] === 187 && buf[2] === 191) i = 3;
11927
11927
  const b = buf.subarray(i);
@@ -12208,19 +12208,19 @@ async function resolveDetectionPath(command, whichCmd) {
12208
12208
  return null;
12209
12209
  }
12210
12210
  function execAsync(cmd, timeoutMs = 5e3) {
12211
- return new Promise((resolve24) => {
12211
+ return new Promise((resolve25) => {
12212
12212
  const child = (0, import_child_process2.exec)(cmd, {
12213
12213
  encoding: "utf-8",
12214
12214
  timeout: timeoutMs,
12215
12215
  ...process.platform === "win32" ? { windowsHide: true } : {}
12216
12216
  }, (err, stdout) => {
12217
12217
  if (err || !stdout?.trim()) {
12218
- resolve24(null);
12218
+ resolve25(null);
12219
12219
  } else {
12220
- resolve24(stdout.trim());
12220
+ resolve25(stdout.trim());
12221
12221
  }
12222
12222
  });
12223
- child.on("error", () => resolve24(null));
12223
+ child.on("error", () => resolve25(null));
12224
12224
  });
12225
12225
  }
12226
12226
  async function detectCLIs(providerLoader, options) {
@@ -12346,7 +12346,7 @@ var init_mesh_event_trace = __esm({
12346
12346
  // src/mesh/mesh-warmup-deadline.ts
12347
12347
  function awaitWithWarmupDeadline(work, opts) {
12348
12348
  const pollMs = Math.max(1, Math.min(opts.pollIntervalMs ?? 200, opts.connectTimeoutMs));
12349
- return new Promise((resolve24, reject) => {
12349
+ return new Promise((resolve25, reject) => {
12350
12350
  let done = false;
12351
12351
  let poll;
12352
12352
  let responseTimer;
@@ -12396,7 +12396,7 @@ function awaitWithWarmupDeadline(work, opts) {
12396
12396
  if (typeof poll.unref === "function") poll.unref();
12397
12397
  }
12398
12398
  work.then(
12399
- (val) => settle(() => resolve24(val)),
12399
+ (val) => settle(() => resolve25(val)),
12400
12400
  (err) => settle(() => reject(err))
12401
12401
  );
12402
12402
  });
@@ -12499,7 +12499,7 @@ async function waitForLocalSessionReady(components, sessionId) {
12499
12499
  const deadline = Date.now() + LOCAL_LAUNCH_READY_TIMEOUT_MS;
12500
12500
  while (Date.now() < deadline) {
12501
12501
  if (adapter.isReady() || adapter.currentStatus === "idle") return;
12502
- await new Promise((resolve24) => setTimeout(resolve24, LOCAL_LAUNCH_READY_POLL_MS));
12502
+ await new Promise((resolve25) => setTimeout(resolve25, LOCAL_LAUNCH_READY_POLL_MS));
12503
12503
  }
12504
12504
  LOG.warn("MeshQueue", `Auto-launched session ${sessionId} not interactive after ${LOCAL_LAUNCH_READY_TIMEOUT_MS}ms; dispatching anyway (adapter queue-until-ready will buffer)`);
12505
12505
  }
@@ -18930,7 +18930,7 @@ function getCliValidator() {
18930
18930
  return _cliValidator;
18931
18931
  }
18932
18932
  function formatIssue(err) {
18933
- const path43 = err.instancePath || "";
18933
+ const path44 = err.instancePath || "";
18934
18934
  const params = err.params;
18935
18935
  let message = err.message || "validation failed";
18936
18936
  let allowed;
@@ -18948,7 +18948,7 @@ function formatIssue(err) {
18948
18948
  } else if (err.keyword === "type") {
18949
18949
  message = `must be ${params.type}`;
18950
18950
  }
18951
- return { path: path43, keyword: err.keyword, message, ...allowed !== void 0 ? { allowed } : {} };
18951
+ return { path: path44, keyword: err.keyword, message, ...allowed !== void 0 ? { allowed } : {} };
18952
18952
  }
18953
18953
  function validateCliProviderManifest(manifest) {
18954
18954
  const validator = getCliValidator();
@@ -19244,40 +19244,40 @@ function validateFsmSpec(raw) {
19244
19244
  }
19245
19245
  return errs;
19246
19246
  }
19247
- function validateCondition(c, sectionIds, path43) {
19247
+ function validateCondition(c, sectionIds, path44) {
19248
19248
  const errs = [];
19249
19249
  const w = c;
19250
19250
  if ("all" in w) {
19251
- w.all.forEach((x, i) => errs.push(...validateCondition(x, sectionIds, `${path43}.all[${i}]`)));
19251
+ w.all.forEach((x, i) => errs.push(...validateCondition(x, sectionIds, `${path44}.all[${i}]`)));
19252
19252
  return errs;
19253
19253
  }
19254
19254
  if ("any" in w) {
19255
- w.any.forEach((x, i) => errs.push(...validateCondition(x, sectionIds, `${path43}.any[${i}]`)));
19255
+ w.any.forEach((x, i) => errs.push(...validateCondition(x, sectionIds, `${path44}.any[${i}]`)));
19256
19256
  return errs;
19257
19257
  }
19258
19258
  if ("not" in w) {
19259
- errs.push(...validateCondition(w.not, sectionIds, `${path43}.not`));
19259
+ errs.push(...validateCondition(w.not, sectionIds, `${path44}.not`));
19260
19260
  return errs;
19261
19261
  }
19262
19262
  if ("matches" in w) {
19263
- if (w.section && !sectionIds.has(w.section)) errs.push(`${path43}.section "${w.section}" unknown`);
19263
+ if (w.section && !sectionIds.has(w.section)) errs.push(`${path44}.section "${w.section}" unknown`);
19264
19264
  try {
19265
19265
  new RegExp(w.matches, w.flags ?? "i");
19266
19266
  } catch (e) {
19267
- errs.push(`${path43}.matches invalid regex: ${e.message}`);
19267
+ errs.push(`${path44}.matches invalid regex: ${e.message}`);
19268
19268
  }
19269
19269
  return errs;
19270
19270
  }
19271
19271
  if ("cursor_above" in w && "changed" in w) return errs;
19272
19272
  if ("elapsed_ms" in w) {
19273
- if (typeof w.elapsed_ms !== "number") errs.push(`${path43}.elapsed_ms must be a number`);
19273
+ if (typeof w.elapsed_ms !== "number") errs.push(`${path44}.elapsed_ms must be a number`);
19274
19274
  return errs;
19275
19275
  }
19276
19276
  if ("stable_ms" in w) {
19277
- if (typeof w.stable_ms !== "number") errs.push(`${path43}.stable_ms must be a number`);
19277
+ if (typeof w.stable_ms !== "number") errs.push(`${path44}.stable_ms must be a number`);
19278
19278
  return errs;
19279
19279
  }
19280
- errs.push(`${path43} is not a recognized condition`);
19280
+ errs.push(`${path44} is not a recognized condition`);
19281
19281
  return errs;
19282
19282
  }
19283
19283
  var fs10;
@@ -19772,8 +19772,8 @@ var init_pty_transport = __esm({
19772
19772
  let cwd = options.cwd;
19773
19773
  if (cwd) {
19774
19774
  try {
19775
- const fs38 = require("fs");
19776
- const stat2 = fs38.statSync(cwd);
19775
+ const fs39 = require("fs");
19776
+ const stat2 = fs39.statSync(cwd);
19777
19777
  if (!stat2.isDirectory()) cwd = os14.homedir();
19778
19778
  } catch {
19779
19779
  cwd = os14.homedir();
@@ -22321,7 +22321,7 @@ ${lastSnapshot}`;
22321
22321
  `[${this.cliType}] Waiting for interactive prompt: status=${status} stableMs=${stableMs} recentOutputMs=${recentlyOutput} screen=${JSON.stringify(summarizeCliTraceText(screenText, 220)).slice(0, 260)}`
22322
22322
  );
22323
22323
  }
22324
- await new Promise((resolve24) => setTimeout(resolve24, 50));
22324
+ await new Promise((resolve25) => setTimeout(resolve25, 50));
22325
22325
  }
22326
22326
  const finalScreenText = this.terminalScreen.getText() || "";
22327
22327
  LOG.warn(
@@ -22616,7 +22616,7 @@ ${lastSnapshot}`;
22616
22616
  if (!this.ptyProcess) throw new Error(`${this.cliName} is not running`);
22617
22617
  await this.ptyProcess.write(chunks[i]);
22618
22618
  if (i + 1 < chunks.length) {
22619
- await new Promise((resolve24) => setTimeout(resolve24, WIN32_PTY_WRITE_CHUNK_GAP_MS));
22619
+ await new Promise((resolve25) => setTimeout(resolve25, WIN32_PTY_WRITE_CHUNK_GAP_MS));
22620
22620
  }
22621
22621
  }
22622
22622
  }
@@ -22784,7 +22784,7 @@ ${lastSnapshot}`;
22784
22784
  this.onStatusChange?.();
22785
22785
  }
22786
22786
  async waitForForceSubmitSettle() {
22787
- await new Promise((resolve24) => setTimeout(resolve24, FORCE_SUBMIT_SETTLE_MS));
22787
+ await new Promise((resolve25) => setTimeout(resolve25, FORCE_SUBMIT_SETTLE_MS));
22788
22788
  }
22789
22789
  enqueuePendingOutboundMessage(text, reason, meshTaskId) {
22790
22790
  const content = String(text || "");
@@ -22863,7 +22863,7 @@ ${lastSnapshot}`;
22863
22863
  const deadline = Date.now() + 1e4;
22864
22864
  while (this.startupParseGate && Date.now() < deadline) {
22865
22865
  this.resolveStartupState("send_wait");
22866
- await new Promise((resolve24) => setTimeout(resolve24, 50));
22866
+ await new Promise((resolve25) => setTimeout(resolve25, 50));
22867
22867
  }
22868
22868
  }
22869
22869
  const parsedStatusBeforeSend = !allowInputDuringGeneration ? (() => {
@@ -22956,13 +22956,13 @@ ${lastSnapshot}`;
22956
22956
  isFirstTurn: !this.firstTurnSent
22957
22957
  };
22958
22958
  this.engine.responseSettleIgnoreUntil = Date.now() + submitDelayMs + this.timeouts.outputSettle + 250;
22959
- await new Promise((resolve24, reject) => {
22959
+ await new Promise((resolve25, reject) => {
22960
22960
  let resolved = false;
22961
22961
  const completion = {
22962
22962
  resolveOnce: () => {
22963
22963
  if (resolved) return;
22964
22964
  resolved = true;
22965
- resolve24();
22965
+ resolve25();
22966
22966
  },
22967
22967
  rejectOnce: (error) => {
22968
22968
  if (resolved) return;
@@ -23150,17 +23150,17 @@ ${lastSnapshot}`;
23150
23150
  }
23151
23151
  }
23152
23152
  waitForStopped(timeoutMs) {
23153
- return new Promise((resolve24) => {
23153
+ return new Promise((resolve25) => {
23154
23154
  const startedAt = Date.now();
23155
23155
  const timer = setInterval(() => {
23156
23156
  if (!this.ptyProcess || this.engine.currentStatus === "stopped") {
23157
23157
  clearInterval(timer);
23158
- resolve24(true);
23158
+ resolve25(true);
23159
23159
  return;
23160
23160
  }
23161
23161
  if (Date.now() - startedAt >= timeoutMs) {
23162
23162
  clearInterval(timer);
23163
- resolve24(false);
23163
+ resolve25(false);
23164
23164
  }
23165
23165
  }, 100);
23166
23166
  });
@@ -24020,6 +24020,7 @@ __export(index_exports, {
24020
24020
  createGitSnapshotStore: () => createGitSnapshotStore,
24021
24021
  createGitWorkspaceMonitor: () => createGitWorkspaceMonitor,
24022
24022
  createInteractionId: () => createInteractionId,
24023
+ createManagedSessionHost: () => createManagedSessionHost,
24023
24024
  createMesh: () => createMesh,
24024
24025
  createNativeHistoryDispatcher: () => createNativeHistoryDispatcher,
24025
24026
  createSessionDelivery: () => createSessionDelivery,
@@ -25868,17 +25869,17 @@ function checkPathExists(paths) {
25868
25869
  return null;
25869
25870
  }
25870
25871
  async function detectIDEs(providerLoader) {
25871
- const os30 = (0, import_os2.platform)();
25872
+ const os31 = (0, import_os2.platform)();
25872
25873
  const results = [];
25873
25874
  for (const def of getMergedDefinitions()) {
25874
25875
  const cliPath = findCliCommand(providerLoader?.getIdeCliCommand(def.id, def.cli) || def.cli);
25875
- const appPath = checkPathExists(providerLoader?.getIdePathCandidates(def.id, def.paths[os30] || []) || []);
25876
+ const appPath = checkPathExists(providerLoader?.getIdePathCandidates(def.id, def.paths[os31] || []) || []);
25876
25877
  let resolvedCli = cliPath;
25877
- if (!resolvedCli && appPath && os30 === "darwin") {
25878
+ if (!resolvedCli && appPath && os31 === "darwin") {
25878
25879
  const bundledCli = `${appPath}/Contents/Resources/app/bin/${def.cli}`;
25879
25880
  if ((0, import_fs15.existsSync)(bundledCli)) resolvedCli = bundledCli;
25880
25881
  }
25881
- if (!resolvedCli && appPath && os30 === "win32") {
25882
+ if (!resolvedCli && appPath && os31 === "win32") {
25882
25883
  const { dirname: dirname17 } = await import("path");
25883
25884
  const appDir = dirname17(appPath);
25884
25885
  const candidates = [
@@ -25895,7 +25896,7 @@ async function detectIDEs(providerLoader) {
25895
25896
  }
25896
25897
  }
25897
25898
  }
25898
- const installed = os30 === "darwin" ? !!(resolvedCli || appPath) : !!resolvedCli;
25899
+ const installed = os31 === "darwin" ? !!(resolvedCli || appPath) : !!resolvedCli;
25899
25900
  const version = null;
25900
25901
  results.push({
25901
25902
  id: def.id,
@@ -26154,7 +26155,7 @@ var DaemonCdpManager = class {
26154
26155
  * Returns multiple entries if multiple IDE windows are open on same port
26155
26156
  */
26156
26157
  static listAllTargets(port) {
26157
- return new Promise((resolve24) => {
26158
+ return new Promise((resolve25) => {
26158
26159
  const req = http.get(`http://127.0.0.1:${port}/json`, (res) => {
26159
26160
  let data = "";
26160
26161
  res.on("data", (chunk) => data += chunk.toString());
@@ -26170,16 +26171,16 @@ var DaemonCdpManager = class {
26170
26171
  (t) => !isNonMain(t.title || "") && t.url?.includes("workbench.html") && !t.url?.includes("agent")
26171
26172
  );
26172
26173
  const fallbackPages = pages.filter((t) => !isNonMain(t.title || ""));
26173
- resolve24(mainPages.length > 0 ? mainPages : fallbackPages);
26174
+ resolve25(mainPages.length > 0 ? mainPages : fallbackPages);
26174
26175
  } catch {
26175
- resolve24([]);
26176
+ resolve25([]);
26176
26177
  }
26177
26178
  });
26178
26179
  });
26179
- req.on("error", () => resolve24([]));
26180
+ req.on("error", () => resolve25([]));
26180
26181
  req.setTimeout(2e3, () => {
26181
26182
  req.destroy();
26182
- resolve24([]);
26183
+ resolve25([]);
26183
26184
  });
26184
26185
  });
26185
26186
  }
@@ -26219,7 +26220,7 @@ var DaemonCdpManager = class {
26219
26220
  }
26220
26221
  }
26221
26222
  findTargetOnPort(port) {
26222
- return new Promise((resolve24) => {
26223
+ return new Promise((resolve25) => {
26223
26224
  const req = http.get(`http://127.0.0.1:${port}/json`, (res) => {
26224
26225
  let data = "";
26225
26226
  res.on("data", (chunk) => data += chunk.toString());
@@ -26230,7 +26231,7 @@ var DaemonCdpManager = class {
26230
26231
  (t) => (t.type === "page" || t.type === "browser" || t.type === "Page") && t.webSocketDebuggerUrl
26231
26232
  );
26232
26233
  if (pages.length === 0) {
26233
- resolve24(targets.find((t) => t.webSocketDebuggerUrl) || null);
26234
+ resolve25(targets.find((t) => t.webSocketDebuggerUrl) || null);
26234
26235
  return;
26235
26236
  }
26236
26237
  const titleFilteredPages = pages.filter((t) => !this.isNonMainTitle(t.title || ""));
@@ -26249,25 +26250,25 @@ var DaemonCdpManager = class {
26249
26250
  this._targetId = selected.target.id;
26250
26251
  }
26251
26252
  this._pageTitle = selected.target.title || "";
26252
- resolve24(selected.target);
26253
+ resolve25(selected.target);
26253
26254
  return;
26254
26255
  }
26255
26256
  if (previousTargetId) {
26256
26257
  this.log(`[CDP] Target ${previousTargetId} not found in page list`);
26257
- resolve24(null);
26258
+ resolve25(null);
26258
26259
  return;
26259
26260
  }
26260
26261
  this._pageTitle = list[0]?.title || "";
26261
- resolve24(list[0]);
26262
+ resolve25(list[0]);
26262
26263
  } catch {
26263
- resolve24(null);
26264
+ resolve25(null);
26264
26265
  }
26265
26266
  });
26266
26267
  });
26267
- req.on("error", () => resolve24(null));
26268
+ req.on("error", () => resolve25(null));
26268
26269
  req.setTimeout(2e3, () => {
26269
26270
  req.destroy();
26270
- resolve24(null);
26271
+ resolve25(null);
26271
26272
  });
26272
26273
  });
26273
26274
  }
@@ -26278,7 +26279,7 @@ var DaemonCdpManager = class {
26278
26279
  this.extensionProviders = providers;
26279
26280
  }
26280
26281
  connectToTarget(wsUrl) {
26281
- return new Promise((resolve24) => {
26282
+ return new Promise((resolve25) => {
26282
26283
  this.ws = new import_ws.default(wsUrl);
26283
26284
  this.ws.on("open", async () => {
26284
26285
  this._connected = true;
@@ -26288,17 +26289,17 @@ var DaemonCdpManager = class {
26288
26289
  }
26289
26290
  this.connectBrowserWs().catch(() => {
26290
26291
  });
26291
- resolve24(true);
26292
+ resolve25(true);
26292
26293
  });
26293
26294
  this.ws.on("message", (data) => {
26294
26295
  try {
26295
26296
  const msg = JSON.parse(data.toString());
26296
26297
  if (msg.id && this.pending.has(msg.id)) {
26297
- const { resolve: resolve25, reject } = this.pending.get(msg.id);
26298
+ const { resolve: resolve26, reject } = this.pending.get(msg.id);
26298
26299
  this.pending.delete(msg.id);
26299
26300
  this.failureCount = 0;
26300
26301
  if (msg.error) reject(new Error(msg.error.message));
26301
- else resolve25(msg.result);
26302
+ else resolve26(msg.result);
26302
26303
  } else if (msg.method === "Runtime.executionContextCreated") {
26303
26304
  this.contexts.add(msg.params.context.id);
26304
26305
  } else if (msg.method === "Runtime.executionContextDestroyed") {
@@ -26321,7 +26322,7 @@ var DaemonCdpManager = class {
26321
26322
  this.ws.on("error", (err) => {
26322
26323
  this.log(`[CDP] WebSocket error: ${err.message}`);
26323
26324
  this._connected = false;
26324
- resolve24(false);
26325
+ resolve25(false);
26325
26326
  });
26326
26327
  });
26327
26328
  }
@@ -26335,7 +26336,7 @@ var DaemonCdpManager = class {
26335
26336
  return;
26336
26337
  }
26337
26338
  this.log(`[CDP] Connecting browser WS for target discovery...`);
26338
- await new Promise((resolve24, reject) => {
26339
+ await new Promise((resolve25, reject) => {
26339
26340
  this.browserWs = new import_ws.default(browserWsUrl);
26340
26341
  this.browserWs.on("open", async () => {
26341
26342
  this._browserConnected = true;
@@ -26345,16 +26346,16 @@ var DaemonCdpManager = class {
26345
26346
  } catch (e) {
26346
26347
  this.log(`[CDP] setDiscoverTargets failed: ${e.message}`);
26347
26348
  }
26348
- resolve24();
26349
+ resolve25();
26349
26350
  });
26350
26351
  this.browserWs.on("message", (data) => {
26351
26352
  try {
26352
26353
  const msg = JSON.parse(data.toString());
26353
26354
  if (msg.id && this.browserPending.has(msg.id)) {
26354
- const { resolve: resolve25, reject: reject2 } = this.browserPending.get(msg.id);
26355
+ const { resolve: resolve26, reject: reject2 } = this.browserPending.get(msg.id);
26355
26356
  this.browserPending.delete(msg.id);
26356
26357
  if (msg.error) reject2(new Error(msg.error.message));
26357
- else resolve25(msg.result);
26358
+ else resolve26(msg.result);
26358
26359
  }
26359
26360
  } catch {
26360
26361
  }
@@ -26374,31 +26375,31 @@ var DaemonCdpManager = class {
26374
26375
  }
26375
26376
  }
26376
26377
  getBrowserWsUrl() {
26377
- return new Promise((resolve24) => {
26378
+ return new Promise((resolve25) => {
26378
26379
  const req = http.get(`http://127.0.0.1:${this.port}/json/version`, (res) => {
26379
26380
  let data = "";
26380
26381
  res.on("data", (chunk) => data += chunk.toString());
26381
26382
  res.on("end", () => {
26382
26383
  try {
26383
26384
  const info = JSON.parse(data);
26384
- resolve24(info.webSocketDebuggerUrl || null);
26385
+ resolve25(info.webSocketDebuggerUrl || null);
26385
26386
  } catch {
26386
- resolve24(null);
26387
+ resolve25(null);
26387
26388
  }
26388
26389
  });
26389
26390
  });
26390
- req.on("error", () => resolve24(null));
26391
+ req.on("error", () => resolve25(null));
26391
26392
  req.setTimeout(3e3, () => {
26392
26393
  req.destroy();
26393
- resolve24(null);
26394
+ resolve25(null);
26394
26395
  });
26395
26396
  });
26396
26397
  }
26397
26398
  sendBrowser(method, params = {}, timeoutMs = 15e3) {
26398
- return new Promise((resolve24, reject) => {
26399
+ return new Promise((resolve25, reject) => {
26399
26400
  if (!this.browserWs || !this._browserConnected) return reject(new Error("Browser WS not connected"));
26400
26401
  const id = this.browserMsgId++;
26401
- this.browserPending.set(id, { resolve: resolve24, reject });
26402
+ this.browserPending.set(id, { resolve: resolve25, reject });
26402
26403
  this.browserWs.send(JSON.stringify({ id, method, params }));
26403
26404
  setTimeout(() => {
26404
26405
  if (this.browserPending.has(id)) {
@@ -26438,11 +26439,11 @@ var DaemonCdpManager = class {
26438
26439
  }
26439
26440
  // ─── CDP Protocol ────────────────────────────────────────
26440
26441
  sendInternal(method, params = {}, timeoutMs = 15e3) {
26441
- return new Promise((resolve24, reject) => {
26442
+ return new Promise((resolve25, reject) => {
26442
26443
  if (!this.ws || !this._connected) return reject(new Error("CDP not connected"));
26443
26444
  if (this.ws.readyState !== import_ws.default.OPEN) return reject(new Error("WebSocket not open"));
26444
26445
  const id = this.msgId++;
26445
- this.pending.set(id, { resolve: resolve24, reject });
26446
+ this.pending.set(id, { resolve: resolve25, reject });
26446
26447
  this.ws.send(JSON.stringify({ id, method, params }));
26447
26448
  setTimeout(() => {
26448
26449
  if (this.pending.has(id)) {
@@ -26691,7 +26692,7 @@ var DaemonCdpManager = class {
26691
26692
  const browserWs = this.browserWs;
26692
26693
  let msgId = this.browserMsgId;
26693
26694
  const sendWs = (method, params = {}, sessionId) => {
26694
- return new Promise((resolve24, reject) => {
26695
+ return new Promise((resolve25, reject) => {
26695
26696
  const mid = msgId++;
26696
26697
  this.browserMsgId = msgId;
26697
26698
  const handler = (raw) => {
@@ -26700,7 +26701,7 @@ var DaemonCdpManager = class {
26700
26701
  if (msg.id === mid) {
26701
26702
  browserWs.removeListener("message", handler);
26702
26703
  if (msg.error) reject(new Error(msg.error.message || JSON.stringify(msg.error)));
26703
- else resolve24(msg.result);
26704
+ else resolve25(msg.result);
26704
26705
  }
26705
26706
  } catch {
26706
26707
  }
@@ -26901,14 +26902,14 @@ var DaemonCdpManager = class {
26901
26902
  if (!ws || ws.readyState !== import_ws.default.OPEN) {
26902
26903
  throw new Error("CDP not connected");
26903
26904
  }
26904
- return new Promise((resolve24, reject) => {
26905
+ return new Promise((resolve25, reject) => {
26905
26906
  const id = getNextId();
26906
26907
  pendingMap.set(id, {
26907
26908
  resolve: (result) => {
26908
26909
  if (result?.result?.subtype === "error") {
26909
26910
  reject(new Error(result.result.description));
26910
26911
  } else {
26911
- resolve24(result?.result?.value);
26912
+ resolve25(result?.result?.value);
26912
26913
  }
26913
26914
  },
26914
26915
  reject
@@ -26940,10 +26941,10 @@ var DaemonCdpManager = class {
26940
26941
  throw new Error("CDP not connected");
26941
26942
  }
26942
26943
  const sendViaSession = (method, params = {}) => {
26943
- return new Promise((resolve24, reject) => {
26944
+ return new Promise((resolve25, reject) => {
26944
26945
  const pendingMap = this._browserConnected ? this.browserPending : this.pending;
26945
26946
  const id = this._browserConnected ? this.browserMsgId++ : this.msgId++;
26946
- pendingMap.set(id, { resolve: resolve24, reject });
26947
+ pendingMap.set(id, { resolve: resolve25, reject });
26947
26948
  ws.send(JSON.stringify({ id, sessionId, method, params }));
26948
26949
  setTimeout(() => {
26949
26950
  if (pendingMap.has(id)) {
@@ -33173,7 +33174,7 @@ function getSendChatInputEnvelope(args) {
33173
33174
  return normalizeInputEnvelope(args?.input ? { input: args.input } : args);
33174
33175
  }
33175
33176
  function sleep(ms) {
33176
- return new Promise((resolve24) => setTimeout(resolve24, ms));
33177
+ return new Promise((resolve25) => setTimeout(resolve25, ms));
33177
33178
  }
33178
33179
  async function waitOnceForFreshHermesCliStart(adapter, log) {
33179
33180
  if (adapter.cliType !== "hermes-cli") return;
@@ -33228,7 +33229,7 @@ function getStateLastSignature(state) {
33228
33229
  async function getStableExtensionBaseline(h) {
33229
33230
  const first = await readExtensionChatState(h);
33230
33231
  if (getStateMessageCount(first) > 0 || getStateLastSignature(first)) return first;
33231
- await new Promise((resolve24) => setTimeout(resolve24, 150));
33232
+ await new Promise((resolve25) => setTimeout(resolve25, 150));
33232
33233
  const second = await readExtensionChatState(h);
33233
33234
  return getStateMessageCount(second) >= getStateMessageCount(first) ? second : first;
33234
33235
  }
@@ -33236,7 +33237,7 @@ async function verifyExtensionSendObserved(h, before) {
33236
33237
  const beforeCount = getStateMessageCount(before);
33237
33238
  const beforeSignature = getStateLastSignature(before);
33238
33239
  for (let attempt = 0; attempt < 12; attempt += 1) {
33239
- await new Promise((resolve24) => setTimeout(resolve24, 250));
33240
+ await new Promise((resolve25) => setTimeout(resolve25, 250));
33240
33241
  const state = await readExtensionChatState(h);
33241
33242
  if (state?.status === "waiting_approval") return true;
33242
33243
  const afterCount = getStateMessageCount(state);
@@ -34638,7 +34639,7 @@ async function executeProviderScript(h, args, scriptName) {
34638
34639
  const enterCount = cliCommand.enterCount || 1;
34639
34640
  await adapter.writeRaw(cliCommand.text + "\r");
34640
34641
  for (let i = 1; i < enterCount; i += 1) {
34641
- await new Promise((resolve24) => setTimeout(resolve24, 50));
34642
+ await new Promise((resolve25) => setTimeout(resolve25, 50));
34642
34643
  await adapter.writeRaw("\r");
34643
34644
  }
34644
34645
  }
@@ -35415,9 +35416,9 @@ var DaemonCommandHandler = class {
35415
35416
  * point at a sibling git checkout.
35416
35417
  */
35417
35418
  getUpstreamInstallRoot() {
35418
- const os30 = require("os");
35419
- const path43 = require("path");
35420
- return path43.join(os30.homedir(), ".adhdev", "providers", ".upstream");
35419
+ const os31 = require("os");
35420
+ const path44 = require("path");
35421
+ return path44.join(os31.homedir(), ".adhdev", "providers", ".upstream");
35421
35422
  }
35422
35423
  /**
35423
35424
  * Download a single provider manifest from the registry and write it to
@@ -35441,11 +35442,11 @@ var DaemonCommandHandler = class {
35441
35442
  return { success: false, error: "invalid type" };
35442
35443
  }
35443
35444
  const https = require("https");
35444
- const fs38 = require("fs");
35445
- const path43 = require("path");
35445
+ const fs39 = require("fs");
35446
+ const path44 = require("path");
35446
35447
  const REGISTRY = "https://api.adhf.dev/api/v1/registry";
35447
35448
  function fetchText(url, timeoutMs) {
35448
- return new Promise((resolve24, reject) => {
35449
+ return new Promise((resolve25, reject) => {
35449
35450
  const req = https.get(url, { headers: { "User-Agent": "adhdev-daemon", "Accept": "application/json" }, timeout: timeoutMs }, (res) => {
35450
35451
  if (res.statusCode !== 200) {
35451
35452
  reject(new Error(`HTTP ${res.statusCode}`));
@@ -35453,7 +35454,7 @@ var DaemonCommandHandler = class {
35453
35454
  }
35454
35455
  const chunks = [];
35455
35456
  res.on("data", (c) => chunks.push(c));
35456
- res.on("end", () => resolve24(Buffer.concat(chunks).toString("utf-8")));
35457
+ res.on("end", () => resolve25(Buffer.concat(chunks).toString("utf-8")));
35457
35458
  });
35458
35459
  req.on("error", reject);
35459
35460
  req.on("timeout", () => {
@@ -35479,12 +35480,12 @@ var DaemonCommandHandler = class {
35479
35480
  return { success: false, error: `checksum mismatch: expected ${meta.checksum}, got ${actualChecksum}` };
35480
35481
  }
35481
35482
  const installRoot = this.getUpstreamInstallRoot();
35482
- const installRootResolved = path43.resolve(installRoot);
35483
- const targetDir = path43.resolve(path43.join(installRoot, category, type));
35484
- if (!targetDir.startsWith(installRootResolved + path43.sep)) {
35483
+ const installRootResolved = path44.resolve(installRoot);
35484
+ const targetDir = path44.resolve(path44.join(installRoot, category, type));
35485
+ if (!targetDir.startsWith(installRootResolved + path44.sep)) {
35485
35486
  return { success: false, error: "install path escaped upstream root" };
35486
35487
  }
35487
- fs38.mkdirSync(targetDir, { recursive: true });
35488
+ fs39.mkdirSync(targetDir, { recursive: true });
35488
35489
  let manifestProbe = {};
35489
35490
  try {
35490
35491
  manifestProbe = JSON.parse(manifestBody);
@@ -35508,8 +35509,8 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35508
35509
  }
35509
35510
  }
35510
35511
  const targetFile = isV1 ? "provider.v1.json" : "provider.json";
35511
- const targetPath = path43.join(targetDir, targetFile);
35512
- fs38.writeFileSync(targetPath, manifestBody, "utf-8");
35512
+ const targetPath = path44.join(targetDir, targetFile);
35513
+ fs39.writeFileSync(targetPath, manifestBody, "utf-8");
35513
35514
  const manifestJson = JSON.parse(manifestBody);
35514
35515
  const scriptFetch = await this.fetchProviderSources(
35515
35516
  manifestJson,
@@ -35579,10 +35580,10 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35579
35580
  const repo = source.repo;
35580
35581
  const ref = source.ref;
35581
35582
  const https = require("https");
35582
- const fs38 = require("fs");
35583
- const path43 = require("path");
35583
+ const fs39 = require("fs");
35584
+ const path44 = require("path");
35584
35585
  function fetchJson(url, timeoutMs) {
35585
- return new Promise((resolve24, reject) => {
35586
+ return new Promise((resolve25, reject) => {
35586
35587
  const req = https.get(url, {
35587
35588
  headers: { "User-Agent": "adhdev-daemon", "Accept": "application/vnd.github+json" },
35588
35589
  timeout: timeoutMs
@@ -35595,7 +35596,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35595
35596
  res.on("data", (c) => chunks.push(c));
35596
35597
  res.on("end", () => {
35597
35598
  try {
35598
- resolve24(JSON.parse(Buffer.concat(chunks).toString("utf-8")));
35599
+ resolve25(JSON.parse(Buffer.concat(chunks).toString("utf-8")));
35599
35600
  } catch (e) {
35600
35601
  reject(e);
35601
35602
  }
@@ -35609,14 +35610,14 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35609
35610
  });
35610
35611
  }
35611
35612
  function fetchBinary(url, timeoutMs) {
35612
- return new Promise((resolve24, reject) => {
35613
+ return new Promise((resolve25, reject) => {
35613
35614
  const req = https.get(url, {
35614
35615
  headers: { "User-Agent": "adhdev-daemon" },
35615
35616
  timeout: timeoutMs
35616
35617
  }, (res) => {
35617
35618
  if (res.statusCode === 301 || res.statusCode === 302) {
35618
35619
  if (res.headers.location) {
35619
- return fetchBinary(res.headers.location, timeoutMs).then(resolve24, reject);
35620
+ return fetchBinary(res.headers.location, timeoutMs).then(resolve25, reject);
35620
35621
  }
35621
35622
  }
35622
35623
  if (res.statusCode !== 200) {
@@ -35625,7 +35626,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35625
35626
  }
35626
35627
  const chunks = [];
35627
35628
  res.on("data", (c) => chunks.push(c));
35628
- res.on("end", () => resolve24(Buffer.concat(chunks)));
35629
+ res.on("end", () => resolve25(Buffer.concat(chunks)));
35629
35630
  });
35630
35631
  req.on("error", reject);
35631
35632
  req.on("timeout", () => {
@@ -35636,9 +35637,9 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35636
35637
  }
35637
35638
  let fetchedCount = 0;
35638
35639
  const sharedDirRel = `${category}/_shared`;
35639
- const sharedTargetDir = path43.resolve(path43.join(targetDir, "../_shared"));
35640
- const installRootResolved = path43.resolve(path43.join(targetDir, "../.."));
35641
- if (sharedTargetDir.startsWith(installRootResolved + path43.sep)) {
35640
+ const sharedTargetDir = path44.resolve(path44.join(targetDir, "../_shared"));
35641
+ const installRootResolved = path44.resolve(path44.join(targetDir, "../.."));
35642
+ if (sharedTargetDir.startsWith(installRootResolved + path44.sep)) {
35642
35643
  const sharedStack = [sharedDirRel];
35643
35644
  while (sharedStack.length) {
35644
35645
  const relDir = sharedStack.pop();
@@ -35661,10 +35662,10 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35661
35662
  try {
35662
35663
  const body = await fetchBinary(entry.download_url, 3e4);
35663
35664
  const relInside = entry.path.startsWith(sharedDirRel + "/") ? entry.path.slice(sharedDirRel.length + 1) : entry.path;
35664
- const outPath = path43.resolve(path43.join(sharedTargetDir, relInside));
35665
- if (!outPath.startsWith(path43.resolve(sharedTargetDir) + path43.sep)) continue;
35666
- fs38.mkdirSync(path43.dirname(outPath), { recursive: true });
35667
- fs38.writeFileSync(outPath, body);
35665
+ const outPath = path44.resolve(path44.join(sharedTargetDir, relInside));
35666
+ if (!outPath.startsWith(path44.resolve(sharedTargetDir) + path44.sep)) continue;
35667
+ fs39.mkdirSync(path44.dirname(outPath), { recursive: true });
35668
+ fs39.writeFileSync(outPath, body);
35668
35669
  fetchedCount++;
35669
35670
  } catch (e) {
35670
35671
  errors.push(`fetch shared ${entry.path}: ${e?.message ?? e}`);
@@ -35697,13 +35698,13 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35697
35698
  try {
35698
35699
  const body = await fetchBinary(entry.download_url, 3e4);
35699
35700
  const relInsideProvider = entry.path.startsWith(subdir + "/") ? entry.path.slice(subdir.length + 1) : entry.path;
35700
- const outPath = path43.resolve(path43.join(targetDir, relInsideProvider));
35701
- if (!outPath.startsWith(path43.resolve(targetDir) + path43.sep)) {
35701
+ const outPath = path44.resolve(path44.join(targetDir, relInsideProvider));
35702
+ if (!outPath.startsWith(path44.resolve(targetDir) + path44.sep)) {
35702
35703
  errors.push(`refusing to write outside targetDir: ${entry.path}`);
35703
35704
  continue;
35704
35705
  }
35705
- fs38.mkdirSync(path43.dirname(outPath), { recursive: true });
35706
- fs38.writeFileSync(outPath, body);
35706
+ fs39.mkdirSync(path44.dirname(outPath), { recursive: true });
35707
+ fs39.writeFileSync(outPath, body);
35707
35708
  fetchedCount++;
35708
35709
  } catch (e) {
35709
35710
  errors.push(`fetch ${entry.path}: ${e?.message ?? e}`);
@@ -35731,19 +35732,19 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35731
35732
  if (!["cli", "ide", "extension", "acp"].includes(category)) {
35732
35733
  return { success: false, error: `unknown category: ${category}` };
35733
35734
  }
35734
- const fs38 = require("fs");
35735
- const path43 = require("path");
35735
+ const fs39 = require("fs");
35736
+ const path44 = require("path");
35736
35737
  try {
35737
35738
  const installRoot = this.getUpstreamInstallRoot();
35738
- const installRootResolved = path43.resolve(installRoot);
35739
- const targetDir = path43.resolve(path43.join(installRoot, category, type));
35740
- if (!targetDir.startsWith(installRootResolved + path43.sep)) {
35739
+ const installRootResolved = path44.resolve(installRoot);
35740
+ const targetDir = path44.resolve(path44.join(installRoot, category, type));
35741
+ if (!targetDir.startsWith(installRootResolved + path44.sep)) {
35741
35742
  return { success: false, error: "refusing to delete outside upstream root" };
35742
35743
  }
35743
- if (!fs38.existsSync(targetDir)) {
35744
+ if (!fs39.existsSync(targetDir)) {
35744
35745
  return { success: false, error: "not installed" };
35745
35746
  }
35746
- fs38.rmSync(targetDir, { recursive: true, force: true });
35747
+ fs39.rmSync(targetDir, { recursive: true, force: true });
35747
35748
  if (this._ctx.providerLoader) {
35748
35749
  this._ctx.providerLoader.reload();
35749
35750
  this._ctx.providerLoader.registerToDetector();
@@ -35759,28 +35760,28 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35759
35760
  * the UI and by the update checker.
35760
35761
  */
35761
35762
  handleListInstalledProviders(_args) {
35762
- const fs38 = require("fs");
35763
- const path43 = require("path");
35763
+ const fs39 = require("fs");
35764
+ const path44 = require("path");
35764
35765
  const installRoot = this.getUpstreamInstallRoot();
35765
- if (!fs38.existsSync(installRoot)) return { success: true, providers: [] };
35766
+ if (!fs39.existsSync(installRoot)) return { success: true, providers: [] };
35766
35767
  const CATEGORIES = ["cli", "ide", "extension", "acp"];
35767
35768
  const items = [];
35768
35769
  for (const category of CATEGORIES) {
35769
- const categoryDir = path43.join(installRoot, category);
35770
- if (!fs38.existsSync(categoryDir)) continue;
35770
+ const categoryDir = path44.join(installRoot, category);
35771
+ if (!fs39.existsSync(categoryDir)) continue;
35771
35772
  let entries;
35772
35773
  try {
35773
- entries = fs38.readdirSync(categoryDir);
35774
+ entries = fs39.readdirSync(categoryDir);
35774
35775
  } catch {
35775
35776
  continue;
35776
35777
  }
35777
35778
  for (const type of entries) {
35778
- const v1Path = path43.join(categoryDir, type, "provider.v1.json");
35779
- const v0Path = path43.join(categoryDir, type, "provider.json");
35780
- const manifestPath = fs38.existsSync(v1Path) ? v1Path : fs38.existsSync(v0Path) ? v0Path : null;
35779
+ const v1Path = path44.join(categoryDir, type, "provider.v1.json");
35780
+ const v0Path = path44.join(categoryDir, type, "provider.json");
35781
+ const manifestPath = fs39.existsSync(v1Path) ? v1Path : fs39.existsSync(v0Path) ? v0Path : null;
35781
35782
  if (!manifestPath) continue;
35782
35783
  try {
35783
- const m = JSON.parse(fs38.readFileSync(manifestPath, "utf-8"));
35784
+ const m = JSON.parse(fs39.readFileSync(manifestPath, "utf-8"));
35784
35785
  items.push({
35785
35786
  type,
35786
35787
  category,
@@ -35807,7 +35808,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35807
35808
  const https = require("https");
35808
35809
  const REGISTRY = "https://api.adhf.dev/api/v1/registry";
35809
35810
  function fetchJson(url) {
35810
- return new Promise((resolve24, reject) => {
35811
+ return new Promise((resolve25, reject) => {
35811
35812
  const req = https.get(url, { headers: { "User-Agent": "adhdev-daemon", "Accept": "application/json" }, timeout: 1e4 }, (res) => {
35812
35813
  if (res.statusCode !== 200) {
35813
35814
  reject(new Error(`HTTP ${res.statusCode}`));
@@ -35817,7 +35818,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35817
35818
  res.on("data", (c) => chunks.push(c));
35818
35819
  res.on("end", () => {
35819
35820
  try {
35820
- resolve24(JSON.parse(Buffer.concat(chunks).toString("utf-8")));
35821
+ resolve25(JSON.parse(Buffer.concat(chunks).toString("utf-8")));
35821
35822
  } catch (e) {
35822
35823
  reject(e);
35823
35824
  }
@@ -35891,8 +35892,8 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35891
35892
  if (!/^@[a-z0-9_-]+$/i.test(requestedName)) {
35892
35893
  return { success: false, error: "name must match @[a-z0-9_-]+" };
35893
35894
  }
35894
- const fs38 = require("fs");
35895
- const path43 = require("path");
35895
+ const fs39 = require("fs");
35896
+ const path44 = require("path");
35896
35897
  const { spawnSync: spawnSync2 } = require("child_process");
35897
35898
  const file = ext.loadExternalSources();
35898
35899
  if (file.sources.some((s2) => s2.name === requestedName)) {
@@ -35901,9 +35902,9 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35901
35902
  if (file.sources.some((s2) => s2.url === url && s2.ref === ref)) {
35902
35903
  return { success: false, error: `source url+ref already registered (use a different name to track another ref)` };
35903
35904
  }
35904
- const sourceDir = path43.join(ext.externalRoot(), requestedName);
35905
- if (!fs38.existsSync(ext.externalRoot())) fs38.mkdirSync(ext.externalRoot(), { recursive: true });
35906
- if (fs38.existsSync(sourceDir)) {
35905
+ const sourceDir = path44.join(ext.externalRoot(), requestedName);
35906
+ if (!fs39.existsSync(ext.externalRoot())) fs39.mkdirSync(ext.externalRoot(), { recursive: true });
35907
+ if (fs39.existsSync(sourceDir)) {
35907
35908
  return { success: false, error: `directory already exists: ${sourceDir} (rename or remove first)` };
35908
35909
  }
35909
35910
  const clone = spawnSync2("git", ["clone", "--depth=1", "--branch", ref, "--", url, sourceDir], {
@@ -35913,7 +35914,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35913
35914
  });
35914
35915
  if (clone.status !== 0) {
35915
35916
  try {
35916
- fs38.rmSync(sourceDir, { recursive: true, force: true });
35917
+ fs39.rmSync(sourceDir, { recursive: true, force: true });
35917
35918
  } catch {
35918
35919
  }
35919
35920
  return { success: false, error: `git clone failed: ${(clone.stderr || clone.stdout || "").trim() || "unknown error"}` };
@@ -35957,15 +35958,15 @@ ${formatManifestValidationIssues2(validation.issues)}`,
35957
35958
  const name = typeof args?.name === "string" ? args.name.trim() : "";
35958
35959
  if (!name) return { success: false, error: "name is required" };
35959
35960
  const ext = (init_external_sources(), __toCommonJS(external_sources_exports));
35960
- const fs38 = require("fs");
35961
- const path43 = require("path");
35961
+ const fs39 = require("fs");
35962
+ const path44 = require("path");
35962
35963
  const file = ext.loadExternalSources();
35963
35964
  const match = file.sources.find((s2) => s2.name === name);
35964
35965
  if (!match) return { success: false, error: `source "${name}" not registered` };
35965
- const sourceDir = path43.join(ext.externalRoot(), name);
35966
- if (fs38.existsSync(sourceDir)) {
35966
+ const sourceDir = path44.join(ext.externalRoot(), name);
35967
+ if (fs39.existsSync(sourceDir)) {
35967
35968
  try {
35968
- fs38.rmSync(sourceDir, { recursive: true, force: true });
35969
+ fs39.rmSync(sourceDir, { recursive: true, force: true });
35969
35970
  } catch (e) {
35970
35971
  return { success: false, error: `failed to delete ${sourceDir}: ${e?.message || e}` };
35971
35972
  }
@@ -36055,7 +36056,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
36055
36056
  try {
36056
36057
  const http3 = await import("http");
36057
36058
  const postData = JSON.stringify(body);
36058
- const result = await new Promise((resolve24, reject) => {
36059
+ const result = await new Promise((resolve25, reject) => {
36059
36060
  const req = http3.request({
36060
36061
  hostname: "127.0.0.1",
36061
36062
  port: 19280,
@@ -36067,9 +36068,9 @@ ${formatManifestValidationIssues2(validation.issues)}`,
36067
36068
  res.on("data", (chunk) => data += chunk);
36068
36069
  res.on("end", () => {
36069
36070
  try {
36070
- resolve24(JSON.parse(data));
36071
+ resolve25(JSON.parse(data));
36071
36072
  } catch {
36072
- resolve24({ raw: data });
36073
+ resolve25({ raw: data });
36073
36074
  }
36074
36075
  });
36075
36076
  });
@@ -36087,15 +36088,15 @@ ${formatManifestValidationIssues2(validation.issues)}`,
36087
36088
  if (!providerType) return { success: false, error: "providerType required" };
36088
36089
  try {
36089
36090
  const http3 = await import("http");
36090
- const result = await new Promise((resolve24, reject) => {
36091
+ const result = await new Promise((resolve25, reject) => {
36091
36092
  http3.get(`http://127.0.0.1:19280/api/providers/${providerType}/${endpoint}`, (res) => {
36092
36093
  let data = "";
36093
36094
  res.on("data", (chunk) => data += chunk);
36094
36095
  res.on("end", () => {
36095
36096
  try {
36096
- resolve24(JSON.parse(data));
36097
+ resolve25(JSON.parse(data));
36097
36098
  } catch {
36098
- resolve24({ raw: data });
36099
+ resolve25({ raw: data });
36099
36100
  }
36100
36101
  });
36101
36102
  }).on("error", reject);
@@ -36109,7 +36110,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
36109
36110
  try {
36110
36111
  const http3 = await import("http");
36111
36112
  const postData = JSON.stringify(args || {});
36112
- const result = await new Promise((resolve24, reject) => {
36113
+ const result = await new Promise((resolve25, reject) => {
36113
36114
  const req = http3.request({
36114
36115
  hostname: "127.0.0.1",
36115
36116
  port: 19280,
@@ -36121,9 +36122,9 @@ ${formatManifestValidationIssues2(validation.issues)}`,
36121
36122
  res.on("data", (chunk) => data += chunk);
36122
36123
  res.on("end", () => {
36123
36124
  try {
36124
- resolve24(JSON.parse(data));
36125
+ resolve25(JSON.parse(data));
36125
36126
  } catch {
36126
- resolve24({ raw: data });
36127
+ resolve25({ raw: data });
36127
36128
  }
36128
36129
  });
36129
36130
  });
@@ -36748,24 +36749,24 @@ var statusMetaHandlers = {
36748
36749
  // src/commands/low-family/coordinator-prompt.ts
36749
36750
  var coordinatorPromptHandlers = {
36750
36751
  list_coordinator_prompts: async (_ctx, _args) => {
36751
- const fs38 = await import("fs");
36752
- const path43 = await import("path");
36753
- const os30 = await import("os");
36754
- const dir = path43.join(os30.homedir(), ".adhdev", "coordinator-prompts");
36752
+ const fs39 = await import("fs");
36753
+ const path44 = await import("path");
36754
+ const os31 = await import("os");
36755
+ const dir = path44.join(os31.homedir(), ".adhdev", "coordinator-prompts");
36755
36756
  const entries = {};
36756
36757
  try {
36757
- if (fs38.existsSync(dir)) {
36758
- for (const name of fs38.readdirSync(dir)) {
36758
+ if (fs39.existsSync(dir)) {
36759
+ for (const name of fs39.readdirSync(dir)) {
36759
36760
  const matchOverride = name.match(/^([a-zA-Z0-9_.-]+)\.md$/);
36760
36761
  const matchAppend = name.match(/^([a-zA-Z0-9_.-]+)\.append\.md$/);
36761
36762
  const m = matchAppend || matchOverride;
36762
36763
  if (!m) continue;
36763
36764
  const isAppend = !!matchAppend;
36764
36765
  const key2 = m[1];
36765
- const full = path43.join(dir, name);
36766
+ const full = path44.join(dir, name);
36766
36767
  let content = "";
36767
36768
  try {
36768
- content = fs38.readFileSync(full, "utf8");
36769
+ content = fs39.readFileSync(full, "utf8");
36769
36770
  } catch {
36770
36771
  }
36771
36772
  if (!entries[key2]) entries[key2] = { override: "", append: "" };
@@ -36779,24 +36780,24 @@ var coordinatorPromptHandlers = {
36779
36780
  return { success: true, dir, entries };
36780
36781
  },
36781
36782
  write_coordinator_prompt: async (_ctx, args) => {
36782
- const fs38 = await import("fs");
36783
- const path43 = await import("path");
36784
- const os30 = await import("os");
36783
+ const fs39 = await import("fs");
36784
+ const path44 = await import("path");
36785
+ const os31 = await import("os");
36785
36786
  const key2 = typeof args?.key === "string" ? args.key.trim() : "";
36786
36787
  const kind = args?.kind === "append" ? "append" : "override";
36787
36788
  const content = typeof args?.content === "string" ? args.content : "";
36788
36789
  if (!key2 || !/^[a-zA-Z0-9_.-]+$/.test(key2)) {
36789
36790
  return { success: false, error: "key must match [a-zA-Z0-9_.-]+" };
36790
36791
  }
36791
- const dir = path43.join(os30.homedir(), ".adhdev", "coordinator-prompts");
36792
+ const dir = path44.join(os31.homedir(), ".adhdev", "coordinator-prompts");
36792
36793
  const filename = kind === "append" ? `${key2}.append.md` : `${key2}.md`;
36793
- const full = path43.join(dir, filename);
36794
+ const full = path44.join(dir, filename);
36794
36795
  try {
36795
- fs38.mkdirSync(dir, { recursive: true });
36796
+ fs39.mkdirSync(dir, { recursive: true });
36796
36797
  if (content.trim()) {
36797
- fs38.writeFileSync(full, content, { encoding: "utf8", mode: 384 });
36798
- } else if (fs38.existsSync(full)) {
36799
- fs38.unlinkSync(full);
36798
+ fs39.writeFileSync(full, content, { encoding: "utf8", mode: 384 });
36799
+ } else if (fs39.existsSync(full)) {
36800
+ fs39.unlinkSync(full);
36800
36801
  }
36801
36802
  return { success: true, path: full, kind, key: key2 };
36802
36803
  } catch (error) {
@@ -37113,7 +37114,7 @@ async function waitForPidExit(pid, timeoutMs) {
37113
37114
  while (Date.now() - start < timeoutMs) {
37114
37115
  try {
37115
37116
  process.kill(pid, 0);
37116
- await new Promise((resolve24) => setTimeout(resolve24, 250));
37117
+ await new Promise((resolve25) => setTimeout(resolve25, 250));
37117
37118
  } catch {
37118
37119
  return;
37119
37120
  }
@@ -37339,7 +37340,7 @@ async function runDaemonUpgradeHelper(payload) {
37339
37340
  appendUpgradeLog(`Install attempt ${attempt} hit a file lock (${error?.code || "lock"}); clearing holders + staging and retrying after backoff`);
37340
37341
  await stopForeignNativeAddonHolders(installCommand.surface.packageRoot, { parentPid: payload.parentPid });
37341
37342
  cleanupStaleGlobalInstallDirs(payload.packageName, installCommand.surface);
37342
- await new Promise((resolve24) => setTimeout(resolve24, attempt * 1500));
37343
+ await new Promise((resolve25) => setTimeout(resolve25, attempt * 1500));
37343
37344
  continue;
37344
37345
  }
37345
37346
  if (isRetriableInstallLockError(error)) {
@@ -37367,7 +37368,7 @@ async function runDaemonUpgradeHelper(payload) {
37367
37368
  appendUpgradeLog(installOutput.trim());
37368
37369
  }
37369
37370
  if (process.platform === "win32") {
37370
- await new Promise((resolve24) => setTimeout(resolve24, 500));
37371
+ await new Promise((resolve25) => setTimeout(resolve25, 500));
37371
37372
  cleanupStaleGlobalInstallDirs(payload.packageName, installCommand.surface);
37372
37373
  appendUpgradeLog("Post-install staging cleanup complete");
37373
37374
  }
@@ -38005,6 +38006,16 @@ var TerminalAdapter = class {
38005
38006
  this.recordEvent("input", capPreview(escapeControl(text)), text.length);
38006
38007
  this.pty?.write(text);
38007
38008
  }
38009
+ /** Forward runtime metadata (meshNodeId, workspaceLabel, lifecycle, …) to
38010
+ * the underlying transport so it reaches the session registry. The spec
38011
+ * path previously dropped everything but providerSessionId here, which
38012
+ * left autoLaunch's meshNodeId stamp unbound on the record (see
38013
+ * SESSION-ACCUMULATION-LEAK). No-op when the transport does not support
38014
+ * metadata updates (e.g. plain node-pty). */
38015
+ updateMeta(meta, replace = false) {
38016
+ if (!this.pty || typeof this.pty.updateMeta !== "function") return;
38017
+ this.pty.updateMeta(meta, replace);
38018
+ }
38008
38019
  /** Debug-only: most-recent PTY input/output/resize/cursor events, oldest
38009
38020
  * first. Pure observation — never consulted by the FSM. */
38010
38021
  getEventTimeline(limit = MAX_PTY_EVENTS) {
@@ -38304,6 +38315,13 @@ var FsmDriver = class {
38304
38315
  return;
38305
38316
  }
38306
38317
  }
38318
+ /** Forward runtime metadata to the terminal transport so mesh binding
38319
+ * fields (meshNodeId / meshNodeFor / workspaceLabel / lifecycle) reach
38320
+ * the session registry. Not a DashboardCommand — this is a control-plane
38321
+ * update, not user input. */
38322
+ updateMeta(meta, replace = false) {
38323
+ this.adapter.updateMeta(meta, replace);
38324
+ }
38307
38325
  snapshot() {
38308
38326
  return this.adapter.snapshot();
38309
38327
  }
@@ -40015,7 +40033,7 @@ function stripAnsi3(text) {
40015
40033
  return String(text || "").replace(/\x1B\][^\x07]*(?:\x07|\x1B\\)/g, "").replace(/\x1B[P^_X][\s\S]*?(?:\x07|\x1B\\)/g, "").replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, "");
40016
40034
  }
40017
40035
  function delay(ms) {
40018
- return new Promise((resolve24) => setTimeout(resolve24, ms));
40036
+ return new Promise((resolve25) => setTimeout(resolve25, ms));
40019
40037
  }
40020
40038
  var SpecCliAdapter = class _SpecCliAdapter {
40021
40039
  cliType;
@@ -40214,7 +40232,7 @@ var SpecCliAdapter = class _SpecCliAdapter {
40214
40232
  const steps = buildClaudeInteractiveTuiAnswerSteps(prompt, response);
40215
40233
  for (const step of steps) {
40216
40234
  this.driver.dispatch({ kind: "pty_write", data: step });
40217
- await new Promise((resolve24) => setTimeout(resolve24, 180));
40235
+ await new Promise((resolve25) => setTimeout(resolve25, 180));
40218
40236
  }
40219
40237
  } else {
40220
40238
  this.driver.dispatch({ kind: "pty_write", data: `${buildClaudeInteractiveToolResult(response)}
@@ -40508,9 +40526,14 @@ var SpecCliAdapter = class _SpecCliAdapter {
40508
40526
  };
40509
40527
  }
40510
40528
  updateRuntimeMeta(meta) {
40511
- if (meta && typeof meta.providerSessionId === "string") {
40529
+ if (!meta) return;
40530
+ if (typeof meta.providerSessionId === "string") {
40512
40531
  this.providerSessionId = meta.providerSessionId;
40513
40532
  }
40533
+ try {
40534
+ this.driver.updateMeta(meta);
40535
+ } catch {
40536
+ }
40514
40537
  }
40515
40538
  refreshProviderDefinition() {
40516
40539
  }
@@ -40765,7 +40788,7 @@ var SpecCliAdapter = class _SpecCliAdapter {
40765
40788
  let screenText = this.driver.snapshot();
40766
40789
  const deadline = Date.now() + _SpecCliAdapter.CLAUDE_TUI_PAGE_SETTLE_TIMEOUT_MS;
40767
40790
  while (!detectClaudeTuiMultiSelect(screenText) && Date.now() < deadline) {
40768
- await new Promise((resolve24) => setTimeout(resolve24, _SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
40791
+ await new Promise((resolve25) => setTimeout(resolve25, _SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
40769
40792
  screenText = this.driver.snapshot();
40770
40793
  }
40771
40794
  return screenText;
@@ -40774,12 +40797,12 @@ var SpecCliAdapter = class _SpecCliAdapter {
40774
40797
  const pages = [{ screenText: firstScreen, header: headers[0] }];
40775
40798
  for (let index = 1; index < headers.length; index += 1) {
40776
40799
  this.driver.dispatch({ kind: "pty_write", data: " " });
40777
- await new Promise((resolve24) => setTimeout(resolve24, _SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
40800
+ await new Promise((resolve25) => setTimeout(resolve25, _SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
40778
40801
  pages.push({ screenText: await this.snapshotSettledClaudeTuiPage(), header: headers[index] });
40779
40802
  }
40780
40803
  for (let index = headers.length - 1; index > 0; index -= 1) {
40781
40804
  this.driver.dispatch({ kind: "pty_write", data: "\x1B[Z" });
40782
- await new Promise((resolve24) => setTimeout(resolve24, _SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
40805
+ await new Promise((resolve25) => setTimeout(resolve25, _SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
40783
40806
  const reread = await this.snapshotSettledClaudeTuiPage();
40784
40807
  const landed = pages[index - 1];
40785
40808
  if (landed && !detectClaudeTuiMultiSelect(landed.screenText) && detectClaudeTuiMultiSelect(reread)) {
@@ -41134,7 +41157,7 @@ async function waitForCliAdapterReady(adapter, options) {
41134
41157
  if (status === "stopped") {
41135
41158
  throw new Error("CLI runtime stopped before it became ready");
41136
41159
  }
41137
- await new Promise((resolve24) => setTimeout(resolve24, pollMs));
41160
+ await new Promise((resolve25) => setTimeout(resolve25, pollMs));
41138
41161
  }
41139
41162
  throw new Error(`CLI runtime did not become ready within ${timeoutMs}ms`);
41140
41163
  }
@@ -41883,7 +41906,7 @@ var CliProviderInstance = class _CliProviderInstance {
41883
41906
  const enterCount = cliCommand.enterCount || 1;
41884
41907
  await this.adapter.writeRaw(cliCommand.text + "\r");
41885
41908
  for (let i = 1; i < enterCount; i += 1) {
41886
- await new Promise((resolve24) => setTimeout(resolve24, 50));
41909
+ await new Promise((resolve25) => setTimeout(resolve25, 50));
41887
41910
  await this.adapter.writeRaw("\r");
41888
41911
  }
41889
41912
  }
@@ -43957,13 +43980,13 @@ var AcpProviderInstance = class {
43957
43980
  }
43958
43981
  this.currentStatus = "waiting_approval";
43959
43982
  this.detectStatusTransition();
43960
- const approved = await new Promise((resolve24) => {
43961
- this.permissionResolvers.push(resolve24);
43983
+ const approved = await new Promise((resolve25) => {
43984
+ this.permissionResolvers.push(resolve25);
43962
43985
  setTimeout(() => {
43963
- const idx = this.permissionResolvers.indexOf(resolve24);
43986
+ const idx = this.permissionResolvers.indexOf(resolve25);
43964
43987
  if (idx >= 0) {
43965
43988
  this.permissionResolvers.splice(idx, 1);
43966
- resolve24(false);
43989
+ resolve25(false);
43967
43990
  }
43968
43991
  }, 3e5);
43969
43992
  });
@@ -44699,7 +44722,7 @@ async function waitForZeroMessageStartingLaunch(adapter) {
44699
44722
  } catch {
44700
44723
  return false;
44701
44724
  }
44702
- await new Promise((resolve24) => setTimeout(resolve24, ZERO_MESSAGE_STARTING_SEND_WAIT_MS));
44725
+ await new Promise((resolve25) => setTimeout(resolve25, ZERO_MESSAGE_STARTING_SEND_WAIT_MS));
44703
44726
  try {
44704
44727
  return hasZeroMessageStartingLaunch(adapter);
44705
44728
  } catch {
@@ -44946,14 +44969,15 @@ var DaemonCliManager = class {
44946
44969
  console.error(colorize("red", ` \u2717 Failed to save recent activity: ${e}`));
44947
44970
  }
44948
44971
  }
44949
- getTransportFactory(runtimeId, providerType, workspace, cliArgs, providerSessionId, attachExisting = false) {
44972
+ getTransportFactory(runtimeId, providerType, workspace, cliArgs, providerSessionId, attachExisting = false, initialMeta) {
44950
44973
  return this.deps.createPtyTransportFactory?.({
44951
44974
  runtimeId,
44952
44975
  providerType,
44953
44976
  workspace,
44954
44977
  cliArgs,
44955
44978
  providerSessionId,
44956
- attachExisting
44979
+ attachExisting,
44980
+ ...initialMeta && Object.keys(initialMeta).length ? { initialMeta } : {}
44957
44981
  }) || void 0;
44958
44982
  }
44959
44983
  createAdapter(cliType, workingDir, cliArgs, runtimeId, providerSessionId, attachExisting = false, extraEnv) {
@@ -45009,13 +45033,25 @@ var DaemonCliManager = class {
45009
45033
  const instanceManager = this.deps.getInstanceManager();
45010
45034
  const sessionRegistry = this.deps.getSessionRegistry?.() || null;
45011
45035
  if (!instanceManager) throw new Error("InstanceManager not available");
45036
+ const launchMeshNodeId = typeof settings?.meshNodeId === "string" ? settings.meshNodeId.trim() : "";
45037
+ const launchMeshNodeFor = typeof settings?.meshNodeFor === "string" ? settings.meshNodeFor.trim() : "";
45038
+ const launchAutoLaunchedForQueueTaskId = typeof settings?.autoLaunchedForQueueTaskId === "string" ? settings.autoLaunchedForQueueTaskId.trim() : "";
45039
+ const launchRecordMeta = {
45040
+ ...launchMeshNodeId ? { meshNodeId: launchMeshNodeId } : {},
45041
+ ...launchMeshNodeFor ? { meshNodeFor: launchMeshNodeFor } : {},
45042
+ ...settings?.launchedByCoordinator === true ? { launchedByCoordinator: true } : {},
45043
+ ...launchAutoLaunchedForQueueTaskId ? { autoLaunchedForQueueTaskId: launchAutoLaunchedForQueueTaskId } : {}
45044
+ };
45012
45045
  const transportFactory = this.getTransportFactory(
45013
45046
  key2,
45014
45047
  normalizedType,
45015
45048
  resolvedDir,
45016
45049
  cliArgs,
45017
45050
  options?.providerSessionId,
45018
- attachExisting
45051
+ attachExisting,
45052
+ // Only seed at create time for fresh launches — an attach restores an
45053
+ // existing record whose meta is already stamped; re-seeding could clobber.
45054
+ attachExisting ? void 0 : launchRecordMeta
45019
45055
  );
45020
45056
  const cliInstance = new CliProviderInstance(provider, resolvedDir, cliArgs, key2, transportFactory, options);
45021
45057
  try {
@@ -45052,17 +45088,9 @@ var DaemonCliManager = class {
45052
45088
  throw new Error(`Failed to start ${provider.displayName || provider.name || cliType}: ${spawnErr?.message}`);
45053
45089
  }
45054
45090
  this.adapters.set(key2, cliInstance.getAdapter());
45055
- const launchMeshNodeId = typeof settings?.meshNodeId === "string" ? settings.meshNodeId.trim() : "";
45056
- const launchMeshNodeFor = typeof settings?.meshNodeFor === "string" ? settings.meshNodeFor.trim() : "";
45057
- const launchAutoLaunchedForQueueTaskId = typeof settings?.autoLaunchedForQueueTaskId === "string" ? settings.autoLaunchedForQueueTaskId.trim() : "";
45058
- if (launchMeshNodeId || launchMeshNodeFor || launchAutoLaunchedForQueueTaskId) {
45091
+ if (Object.keys(launchRecordMeta).length) {
45059
45092
  try {
45060
- cliInstance.getAdapter().updateRuntimeMeta?.({
45061
- ...launchMeshNodeId ? { meshNodeId: launchMeshNodeId } : {},
45062
- ...launchMeshNodeFor ? { meshNodeFor: launchMeshNodeFor } : {},
45063
- ...settings?.launchedByCoordinator === true ? { launchedByCoordinator: true } : {},
45064
- ...launchAutoLaunchedForQueueTaskId ? { autoLaunchedForQueueTaskId: launchAutoLaunchedForQueueTaskId } : {}
45065
- });
45093
+ cliInstance.getAdapter().updateRuntimeMeta?.({ ...launchRecordMeta });
45066
45094
  } catch {
45067
45095
  }
45068
45096
  }
@@ -46040,9 +46068,9 @@ function validateProviderDefinition(raw) {
46040
46068
  const typedProvider = provider;
46041
46069
  const controls = Array.isArray(provider.controls) ? provider.controls : [];
46042
46070
  if (category === "cli" || category === "acp") {
46043
- const spawn4 = provider.spawn;
46044
- const command = spawn4 && typeof spawn4 === "object" ? spawn4.command : void 0;
46045
- if (!spawn4 || typeof spawn4 !== "object") {
46071
+ const spawn5 = provider.spawn;
46072
+ const command = spawn5 && typeof spawn5 === "object" ? spawn5.command : void 0;
46073
+ if (!spawn5 || typeof spawn5 !== "object") {
46046
46074
  errors.push(`${String(category).toUpperCase()}/CLI providers must have spawn config`);
46047
46075
  } else if (typeof command !== "string" || !command.trim()) {
46048
46076
  errors.push("spawn.command is required");
@@ -48563,25 +48591,25 @@ var ProviderLoader = class _ProviderLoader {
48563
48591
  }
48564
48592
  if (providerDir) {
48565
48593
  try {
48566
- const fs38 = require("fs");
48567
- const path43 = require("path");
48594
+ const fs39 = require("fs");
48595
+ const path44 = require("path");
48568
48596
  const candidates = [];
48569
48597
  if (Array.isArray(base.compatibility)) {
48570
48598
  for (const entry of base.compatibility) {
48571
48599
  if (typeof entry?.spec !== "string") continue;
48572
48600
  const matches = !entry.ideVersion || currentVersion && this.matchesVersion(currentVersion, entry.ideVersion) || !currentVersion;
48573
- if (matches) candidates.push(path43.join(providerDir, entry.spec));
48601
+ if (matches) candidates.push(path44.join(providerDir, entry.spec));
48574
48602
  }
48575
48603
  }
48576
- candidates.push(path43.join(providerDir, "specs", "default.json"));
48577
- candidates.push(path43.join(providerDir, "spec.json"));
48578
- const specPath = candidates.find((p) => fs38.existsSync(p));
48604
+ candidates.push(path44.join(providerDir, "specs", "default.json"));
48605
+ candidates.push(path44.join(providerDir, "spec.json"));
48606
+ const specPath = candidates.find((p) => fs39.existsSync(p));
48579
48607
  if (specPath) {
48580
48608
  resolved._resolvedSpecPath = specPath;
48581
48609
  let specControls;
48582
48610
  let nh;
48583
48611
  try {
48584
- const rawSpec = JSON.parse(fs38.readFileSync(specPath, "utf8"));
48612
+ const rawSpec = JSON.parse(fs39.readFileSync(specPath, "utf8"));
48585
48613
  specControls = rawSpec.control_bar;
48586
48614
  nh = rawSpec.native_history;
48587
48615
  } catch {
@@ -48612,10 +48640,10 @@ var ProviderLoader = class _ProviderLoader {
48612
48640
  format = `spec-${nh.source.kind}`;
48613
48641
  reader = (input) => executeNativeHistory(nh, input);
48614
48642
  } else if (nh.override_path) {
48615
- const overrideFile = path43.resolve(providerDir, nh.override_path);
48616
- if (fs38.existsSync(overrideFile)) {
48643
+ const overrideFile = path44.resolve(providerDir, nh.override_path);
48644
+ if (fs39.existsSync(overrideFile)) {
48617
48645
  try {
48618
- registerProviderScriptRootSafely(path43.dirname(path43.dirname(providerDir)));
48646
+ registerProviderScriptRootSafely(path44.dirname(path44.dirname(providerDir)));
48619
48647
  delete require.cache[require.resolve(overrideFile)];
48620
48648
  const mod = require(overrideFile);
48621
48649
  const fn = typeof mod === "function" ? mod : mod && typeof mod.default === "function" ? mod.default : null;
@@ -48789,7 +48817,7 @@ var ProviderLoader = class _ProviderLoader {
48789
48817
  }
48790
48818
  try {
48791
48819
  const listUrl = `${_ProviderLoader.REGISTRY_BASE_URL}/providers`;
48792
- const listBody = await new Promise((resolve24, reject) => {
48820
+ const listBody = await new Promise((resolve25, reject) => {
48793
48821
  const req = https.get(listUrl, { headers: { "User-Agent": "adhdev-daemon", "Accept": "application/json" }, timeout: 1e4 }, (res) => {
48794
48822
  if (res.statusCode !== 200) {
48795
48823
  reject(new Error(`registry list HTTP ${res.statusCode}`));
@@ -48797,7 +48825,7 @@ var ProviderLoader = class _ProviderLoader {
48797
48825
  }
48798
48826
  const chunks = [];
48799
48827
  res.on("data", (c) => chunks.push(c));
48800
- res.on("end", () => resolve24(Buffer.concat(chunks).toString("utf-8")));
48828
+ res.on("end", () => resolve25(Buffer.concat(chunks).toString("utf-8")));
48801
48829
  });
48802
48830
  req.on("error", reject);
48803
48831
  req.on("timeout", () => {
@@ -48813,7 +48841,7 @@ var ProviderLoader = class _ProviderLoader {
48813
48841
  const cacheKey = `${category}/${type}`;
48814
48842
  if (cachedChecksums[cacheKey] === checksum) continue;
48815
48843
  const dlUrl = `${_ProviderLoader.REGISTRY_BASE_URL}/providers/${type}/${version}/download`;
48816
- const manifestBody = await new Promise((resolve24, reject) => {
48844
+ const manifestBody = await new Promise((resolve25, reject) => {
48817
48845
  const req = https.get(dlUrl, { headers: { "User-Agent": "adhdev-daemon", "Accept": "application/json" }, timeout: 3e4 }, (res) => {
48818
48846
  if (res.statusCode !== 200) {
48819
48847
  reject(new Error(`registry download HTTP ${res.statusCode} for ${type}@${version}`));
@@ -48821,7 +48849,7 @@ var ProviderLoader = class _ProviderLoader {
48821
48849
  }
48822
48850
  const chunks = [];
48823
48851
  res.on("data", (c) => chunks.push(c));
48824
- res.on("end", () => resolve24(Buffer.concat(chunks).toString("utf-8")));
48852
+ res.on("end", () => resolve25(Buffer.concat(chunks).toString("utf-8")));
48825
48853
  });
48826
48854
  req.on("error", reject);
48827
48855
  req.on("timeout", () => {
@@ -48880,7 +48908,7 @@ var ProviderLoader = class _ProviderLoader {
48880
48908
  return { updated: false };
48881
48909
  }
48882
48910
  try {
48883
- const etag = await new Promise((resolve24, reject) => {
48911
+ const etag = await new Promise((resolve25, reject) => {
48884
48912
  const options = {
48885
48913
  method: "HEAD",
48886
48914
  hostname: "github.com",
@@ -48898,7 +48926,7 @@ var ProviderLoader = class _ProviderLoader {
48898
48926
  headers: { "User-Agent": "adhdev-launcher" },
48899
48927
  timeout: 1e4
48900
48928
  }, (res2) => {
48901
- resolve24(res2.headers.etag || res2.headers["last-modified"] || "");
48929
+ resolve25(res2.headers.etag || res2.headers["last-modified"] || "");
48902
48930
  });
48903
48931
  req2.on("error", reject);
48904
48932
  req2.on("timeout", () => {
@@ -48907,7 +48935,7 @@ var ProviderLoader = class _ProviderLoader {
48907
48935
  });
48908
48936
  req2.end();
48909
48937
  } else {
48910
- resolve24(res.headers.etag || res.headers["last-modified"] || "");
48938
+ resolve25(res.headers.etag || res.headers["last-modified"] || "");
48911
48939
  }
48912
48940
  });
48913
48941
  req.on("error", reject);
@@ -48971,7 +48999,7 @@ var ProviderLoader = class _ProviderLoader {
48971
48999
  downloadFile(url, destPath) {
48972
49000
  const https = require("https");
48973
49001
  const http3 = require("http");
48974
- return new Promise((resolve24, reject) => {
49002
+ return new Promise((resolve25, reject) => {
48975
49003
  const doRequest = (reqUrl, redirectCount = 0) => {
48976
49004
  if (redirectCount > 5) {
48977
49005
  reject(new Error("Too many redirects"));
@@ -48991,7 +49019,7 @@ var ProviderLoader = class _ProviderLoader {
48991
49019
  res.pipe(ws);
48992
49020
  ws.on("finish", () => {
48993
49021
  ws.close();
48994
- resolve24();
49022
+ resolve25();
48995
49023
  });
48996
49024
  ws.on("error", reject);
48997
49025
  });
@@ -49547,10 +49575,10 @@ function findMacAppProcessPids(psOutput, appPaths) {
49547
49575
 
49548
49576
  // src/launch.ts
49549
49577
  async function execQuiet(command, options = {}) {
49550
- return new Promise((resolve24) => {
49578
+ return new Promise((resolve25) => {
49551
49579
  (0, import_child_process9.exec)(command, options, (error, stdout) => {
49552
- if (error) return resolve24("");
49553
- resolve24(stdout.toString());
49580
+ if (error) return resolve25("");
49581
+ resolve25(stdout.toString());
49554
49582
  });
49555
49583
  });
49556
49584
  }
@@ -49631,17 +49659,17 @@ async function findFreePort(ports) {
49631
49659
  throw new Error("No free port found");
49632
49660
  }
49633
49661
  function checkPortFree(port) {
49634
- return new Promise((resolve24) => {
49662
+ return new Promise((resolve25) => {
49635
49663
  const server = net.createServer();
49636
49664
  server.unref();
49637
- server.on("error", () => resolve24(false));
49665
+ server.on("error", () => resolve25(false));
49638
49666
  server.listen(port, "127.0.0.1", () => {
49639
- server.close(() => resolve24(true));
49667
+ server.close(() => resolve25(true));
49640
49668
  });
49641
49669
  });
49642
49670
  }
49643
49671
  async function isCdpActive(port) {
49644
- return new Promise((resolve24) => {
49672
+ return new Promise((resolve25) => {
49645
49673
  const req = require("http").get(`http://127.0.0.1:${port}/json/version`, {
49646
49674
  timeout: 2e3
49647
49675
  }, (res) => {
@@ -49650,16 +49678,16 @@ async function isCdpActive(port) {
49650
49678
  res.on("end", () => {
49651
49679
  try {
49652
49680
  const info = JSON.parse(data);
49653
- resolve24(!!info["WebKit-Version"] || !!info["Browser"]);
49681
+ resolve25(!!info["WebKit-Version"] || !!info["Browser"]);
49654
49682
  } catch {
49655
- resolve24(false);
49683
+ resolve25(false);
49656
49684
  }
49657
49685
  });
49658
49686
  });
49659
- req.on("error", () => resolve24(false));
49687
+ req.on("error", () => resolve25(false));
49660
49688
  req.on("timeout", () => {
49661
49689
  req.destroy();
49662
- resolve24(false);
49690
+ resolve25(false);
49663
49691
  });
49664
49692
  });
49665
49693
  }
@@ -49795,7 +49823,7 @@ async function detectCurrentWorkspace(ideId) {
49795
49823
  }
49796
49824
  } else if (plat === "win32") {
49797
49825
  try {
49798
- const fs38 = require("fs");
49826
+ const fs39 = require("fs");
49799
49827
  const appNameMap = getMacAppIdentifiers();
49800
49828
  const appName = appNameMap[ideId];
49801
49829
  if (appName) {
@@ -49804,8 +49832,8 @@ async function detectCurrentWorkspace(ideId) {
49804
49832
  appName,
49805
49833
  "storage.json"
49806
49834
  );
49807
- if (fs38.existsSync(storagePath)) {
49808
- const data = JSON.parse(fs38.readFileSync(storagePath, "utf-8"));
49835
+ if (fs39.existsSync(storagePath)) {
49836
+ const data = JSON.parse(fs39.readFileSync(storagePath, "utf-8"));
49809
49837
  const workspaces = data?.openedPathsList?.workspaces3 || data?.openedPathsList?.entries || [];
49810
49838
  if (workspaces.length > 0) {
49811
49839
  const recent = workspaces[0];
@@ -50283,12 +50311,12 @@ var meshCrudHandlers = {
50283
50311
  normalizeRepoMeshDeclarativeConfig: normalizeRepoMeshDeclarativeConfig2,
50284
50312
  MESH_JSON_CONFIG_LOCATIONS: MESH_JSON_CONFIG_LOCATIONS2
50285
50313
  } = await Promise.resolve().then(() => (init_mesh_json_config(), mesh_json_config_exports));
50286
- const { mkdirSync: mkdirSync21, writeFileSync: writeFileSync24 } = await import("fs");
50287
- const { dirname: dirname17, join: join49 } = await import("path");
50314
+ const { mkdirSync: mkdirSync22, writeFileSync: writeFileSync24 } = await import("fs");
50315
+ const { dirname: dirname17, join: join50 } = await import("path");
50288
50316
  const scaffold = buildMeshJsonConfigScaffold2(mesh);
50289
50317
  const scaffoldJson = serializeMeshJsonConfigScaffold2(scaffold);
50290
50318
  const relativePath = MESH_JSON_CONFIG_LOCATIONS2[0];
50291
- const absolutePath = join49(workspace, relativePath);
50319
+ const absolutePath = join50(workspace, relativePath);
50292
50320
  const validation = normalizeRepoMeshDeclarativeConfig2(scaffold);
50293
50321
  if (!validation.valid) {
50294
50322
  return { success: false, meshId, error: `invalid mesh.json scaffold: ${validation.errors.join("; ")}` };
@@ -50324,7 +50352,7 @@ var meshCrudHandlers = {
50324
50352
  note: "Dry-run: nothing written. Re-run with write=true to persist to the repo (commit target). meshes.json is untouched."
50325
50353
  };
50326
50354
  }
50327
- mkdirSync21(dirname17(absolutePath), { recursive: true });
50355
+ mkdirSync22(dirname17(absolutePath), { recursive: true });
50328
50356
  writeFileSync24(absolutePath, `${scaffoldJson}
50329
50357
  `, "utf-8");
50330
50358
  return {
@@ -50532,6 +50560,8 @@ var meshCrudHandlers = {
50532
50560
  const sessionIds = Array.isArray(args?.sessionIds) ? args.sessionIds.map((id) => typeof id === "string" ? id.trim() : "").filter(Boolean) : void 0;
50533
50561
  const source = args?.source === "magi_session_cleanup" ? "magi_session_cleanup" : "mesh_cleanup_sessions";
50534
50562
  const requireAutoLaunchedForTaskIds = args?.requireAutoLaunchedForTaskIds && typeof args.requireAutoLaunchedForTaskIds === "object" && !Array.isArray(args.requireAutoLaunchedForTaskIds) ? args.requireAutoLaunchedForTaskIds : void 0;
50563
+ const reclaimOrphans = args?.reclaimOrphans === true;
50564
+ const liveMeshNodeIds = Array.isArray(mesh?.nodes) ? mesh.nodes.map((n) => normalizeMeshNodeId(n)).filter(Boolean) : [];
50535
50565
  const result = await ctx.cleanupMeshSessions({
50536
50566
  meshId,
50537
50567
  nodeId,
@@ -50540,7 +50570,9 @@ var meshCrudHandlers = {
50540
50570
  sessionIds,
50541
50571
  dryRun: args?.dryRun === true,
50542
50572
  source,
50543
- requireAutoLaunchedForTaskIds
50573
+ requireAutoLaunchedForTaskIds,
50574
+ reclaimOrphans,
50575
+ liveMeshNodeIds
50544
50576
  });
50545
50577
  return result;
50546
50578
  } catch (e) {
@@ -50888,7 +50920,7 @@ var meshCrudHandlers = {
50888
50920
  const setupPromise = finishWorktreeSetup();
50889
50921
  const setupResult = await Promise.race([
50890
50922
  setupPromise.then((value) => ({ completed: true, value })),
50891
- new Promise((resolve24) => setTimeout(() => resolve24({ completed: false }), setupWaitMs))
50923
+ new Promise((resolve25) => setTimeout(() => resolve25({ completed: false }), setupWaitMs))
50892
50924
  ]);
50893
50925
  const emitBootstrapEvent = (eventStatus2, bootstrapState2, startedAtMs, extraPayload) => {
50894
50926
  try {
@@ -52125,7 +52157,7 @@ ${ptyResult.output.slice(-2e3)}`);
52125
52157
  workspace
52126
52158
  };
52127
52159
  }
52128
- const { existsSync: existsSync53, readFileSync: readFileSync41, writeFileSync: writeFileSync24, copyFileSync: copyFileSync4, mkdirSync: mkdirSync21 } = await import("fs");
52160
+ const { existsSync: existsSync54, readFileSync: readFileSync42, writeFileSync: writeFileSync24, copyFileSync: copyFileSync4, mkdirSync: mkdirSync22 } = await import("fs");
52129
52161
  const { dirname: dirname17 } = await import("path");
52130
52162
  const mcpConfigPath = coordinatorSetup.configPath;
52131
52163
  const hermesManualFallback = cliType === "hermes-cli" && configFormat === "hermes_config_yaml" ? createHermesManualMeshCoordinatorSetup(meshId, workspace) : null;
@@ -52161,21 +52193,21 @@ ${ptyResult.output.slice(-2e3)}`);
52161
52193
  };
52162
52194
  }
52163
52195
  try {
52164
- mkdirSync21(dirname17(mcpConfigPath), { recursive: true });
52196
+ mkdirSync22(dirname17(mcpConfigPath), { recursive: true });
52165
52197
  } catch (error) {
52166
52198
  const message = `Could not prepare MCP config path for automatic setup: ${error?.message || error}`;
52167
52199
  LOG.error("MeshCoordinator", message);
52168
52200
  if (hermesManualFallback) return returnManualFallback(message);
52169
52201
  return { success: false, code: "mesh_coordinator_config_write_failed", error: message, meshId, cliType, workspace };
52170
52202
  }
52171
- const hadExistingMcpConfig = existsSync53(mcpConfigPath);
52203
+ const hadExistingMcpConfig = existsSync54(mcpConfigPath);
52172
52204
  let existingMcpConfig = hermesBaseConfig?.config || {};
52173
52205
  if (hermesBaseConfig) {
52174
52206
  copyHermesCoordinatorCredentialFiles(hermesBaseConfig.sourceHome, dirname17(mcpConfigPath));
52175
52207
  }
52176
52208
  if (hadExistingMcpConfig) {
52177
52209
  try {
52178
- const parsedExistingMcpConfig = parseMeshCoordinatorMcpConfig(readFileSync41(mcpConfigPath, "utf-8"), configFormat);
52210
+ const parsedExistingMcpConfig = parseMeshCoordinatorMcpConfig(readFileSync42(mcpConfigPath, "utf-8"), configFormat);
52179
52211
  const existingCoordinatorConfig = hermesManualFallback ? stripHermesCoordinatorTempModelProviderOverrides(parsedExistingMcpConfig) : parsedExistingMcpConfig;
52180
52212
  existingMcpConfig = { ...existingMcpConfig, ...existingCoordinatorConfig };
52181
52213
  copyFileSync4(mcpConfigPath, mcpConfigPath + ".backup");
@@ -52319,10 +52351,10 @@ function runGit2(repoRoot, args) {
52319
52351
  }
52320
52352
  }
52321
52353
  function readRecord6(repoRoot) {
52322
- const path43 = (0, import_node_path2.resolve)(repoRoot, PREVIEW_DEPLOY_RECORD);
52323
- if (!(0, import_node_fs4.existsSync)(path43)) return null;
52354
+ const path44 = (0, import_node_path2.resolve)(repoRoot, PREVIEW_DEPLOY_RECORD);
52355
+ if (!(0, import_node_fs4.existsSync)(path44)) return null;
52324
52356
  try {
52325
- const parsed = JSON.parse((0, import_node_fs4.readFileSync)(path43, "utf8"));
52357
+ const parsed = JSON.parse((0, import_node_fs4.readFileSync)(path44, "utf8"));
52326
52358
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
52327
52359
  } catch {
52328
52360
  return null;
@@ -52877,7 +52909,7 @@ var meshStatusHandlers = {
52877
52909
  const { deriveMeshReviewInboxItems: deriveMeshReviewInboxItems2 } = await Promise.resolve().then(() => (init_mesh_review_inbox(), mesh_review_inbox_exports));
52878
52910
  const { readLedgerEntries: readLedgerEntries2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
52879
52911
  const { getGitDiffSummary: getGitDiffSummary2 } = await Promise.resolve().then(() => (init_git_diff(), git_diff_exports));
52880
- const { existsSync: existsSync53 } = await import("fs");
52912
+ const { existsSync: existsSync54 } = await import("fs");
52881
52913
  const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
52882
52914
  const mesh = meshRecord?.mesh;
52883
52915
  if (!mesh) return { success: false, error: "Mesh not found" };
@@ -52896,7 +52928,7 @@ var meshStatusHandlers = {
52896
52928
  const derivation = deriveMeshReviewInboxItems2({ nodes: nodeStatuses, ledgerEntries });
52897
52929
  for (const item of derivation.items) {
52898
52930
  const workspace = item.workspace;
52899
- if (!workspace || !existsSync53(workspace)) continue;
52931
+ if (!workspace || !existsSync54(workspace)) continue;
52900
52932
  const baseRef = item.defaultBranch ? `origin/${item.defaultBranch}` : "origin/main";
52901
52933
  try {
52902
52934
  const diffResult = await getGitDiffSummary2(workspace, { baseRef, maxFiles: 100 });
@@ -53104,9 +53136,9 @@ init_resolve_executable();
53104
53136
  var execFileAsync3 = (0, import_node_util4.promisify)(import_node_child_process5.execFile);
53105
53137
  var GIT = process.platform === "win32" ? resolveWin32Executable("git") : "git";
53106
53138
  var MAX_CHANGED_FILES2 = 500;
53107
- function topLevel(path43) {
53108
- const slash = path43.indexOf("/");
53109
- return slash === -1 ? path43 : path43.slice(0, slash);
53139
+ function topLevel(path44) {
53140
+ const slash = path44.indexOf("/");
53141
+ return slash === -1 ? path44 : path44.slice(0, slash);
53110
53142
  }
53111
53143
  async function analyzeMeshRefineNodeChangeArea(args) {
53112
53144
  const { nodeId, workspace, branch, baseRef, branchRef, diffCwd, submodulePaths } = args;
@@ -54164,7 +54196,7 @@ async function probeRemoteMeshGitStatusWithRetry(args) {
54164
54196
  const connection = args.getConnection?.(args.daemonId);
54165
54197
  if (args.getConnection && readMeshConnectionState(connection) !== "connected") break;
54166
54198
  if (connection) args.onConnection?.(connection);
54167
- await new Promise((resolve24) => setTimeout(resolve24, 250 * 2 ** (attempt - 1)));
54199
+ await new Promise((resolve25) => setTimeout(resolve25, 250 * 2 ** (attempt - 1)));
54168
54200
  }
54169
54201
  try {
54170
54202
  const remoteGit = await probeRemoteMeshGitStatus({
@@ -54541,18 +54573,18 @@ function resolveRefineryAutoPublishSubmoduleMainCommits(mesh, workspace) {
54541
54573
  return { enabled: false };
54542
54574
  }
54543
54575
  async function computeGitPatchId(cwd, fromRef, toRef, excludePaths = []) {
54544
- const { execFileSync: execFileSync9 } = await import("child_process");
54576
+ const { execFileSync: execFileSync10 } = await import("child_process");
54545
54577
  const diffArgs = ["diff", "--patch", "--full-index", fromRef, toRef];
54546
54578
  if (excludePaths.length > 0) {
54547
- diffArgs.push("--", ".", ...excludePaths.map((path43) => `:(exclude)${path43}`));
54579
+ diffArgs.push("--", ".", ...excludePaths.map((path44) => `:(exclude)${path44}`));
54548
54580
  }
54549
- const diff = execFileSync9(GIT2, diffArgs, {
54581
+ const diff = execFileSync10(GIT2, diffArgs, {
54550
54582
  cwd,
54551
54583
  encoding: "utf8",
54552
54584
  maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
54553
54585
  });
54554
54586
  if (!diff.trim()) return "";
54555
- const patchId = execFileSync9(GIT2, ["patch-id", "--stable"], {
54587
+ const patchId = execFileSync10(GIT2, ["patch-id", "--stable"], {
54556
54588
  cwd,
54557
54589
  input: diff,
54558
54590
  encoding: "utf8",
@@ -54563,8 +54595,8 @@ async function computeGitPatchId(cwd, fromRef, toRef, excludePaths = []) {
54563
54595
  async function runMeshRefinePatchEquivalenceGate(repoRoot, baseHead, branchHead) {
54564
54596
  const startedAt = Date.now();
54565
54597
  try {
54566
- const { execFileSync: execFileSync9 } = await import("child_process");
54567
- const git = (args) => execFileSync9(GIT2, args, {
54598
+ const { execFileSync: execFileSync10 } = await import("child_process");
54599
+ const git = (args) => execFileSync10(GIT2, args, {
54568
54600
  cwd: repoRoot,
54569
54601
  encoding: "utf8",
54570
54602
  maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
@@ -54655,8 +54687,8 @@ ${e?.stderr || ""}`
54655
54687
  async function checkWorktreeChangesPatchEquivalentInRef(repoRoot, ref, worktreeHead) {
54656
54688
  const startedAt = Date.now();
54657
54689
  try {
54658
- const { execFileSync: execFileSync9 } = await import("child_process");
54659
- const git = (gitArgs) => execFileSync9(GIT2, gitArgs, {
54690
+ const { execFileSync: execFileSync10 } = await import("child_process");
54691
+ const git = (gitArgs) => execFileSync10(GIT2, gitArgs, {
54660
54692
  cwd: repoRoot,
54661
54693
  encoding: "utf8",
54662
54694
  maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
@@ -54719,8 +54751,8 @@ ${mergeTreeErr?.stderr || ""}`;
54719
54751
  async function runMeshRefineEffectiveDiffGate(repoRoot, baseHead, branchHead) {
54720
54752
  const startedAt = Date.now();
54721
54753
  try {
54722
- const { execFileSync: execFileSync9 } = await import("child_process");
54723
- const git = (args, opts) => execFileSync9(GIT2, args, {
54754
+ const { execFileSync: execFileSync10 } = await import("child_process");
54755
+ const git = (args, opts) => execFileSync10(GIT2, args, {
54724
54756
  cwd: opts?.cwd || repoRoot,
54725
54757
  encoding: "utf8",
54726
54758
  maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
@@ -54745,9 +54777,9 @@ async function runMeshRefineEffectiveDiffGate(repoRoot, baseHead, branchHead) {
54745
54777
  if (!trimmed) continue;
54746
54778
  if (trimmed.startsWith("+")) {
54747
54779
  const parts = trimmed.slice(1).trim().split(/\s+/);
54748
- const path43 = parts[1] || parts[0] || "(unknown)";
54780
+ const path44 = parts[1] || parts[0] || "(unknown)";
54749
54781
  submoduleHints.push({
54750
- path: path43,
54782
+ path: path44,
54751
54783
  reason: "submodule checked-out commit differs from the committed gitlink (pointer bump not committed on the root branch)"
54752
54784
  });
54753
54785
  }
@@ -54777,10 +54809,10 @@ async function runMeshRefineEffectiveDiffGate(repoRoot, baseHead, branchHead) {
54777
54809
  }
54778
54810
  function buildPatchEquivalenceSubmoduleConflictHint(repoRoot, baseHead, branchHead, output) {
54779
54811
  if (!/(submodule|160000)/i.test(output) || !/(conflict|failed to merge)/i.test(output)) return void 0;
54780
- const conflicts = readChangedGitlinkPaths(repoRoot, baseHead, branchHead).map((path43) => ({
54781
- path: path43,
54782
- baseCommit: readTreeObject(repoRoot, baseHead, path43),
54783
- branchCommit: readTreeObject(repoRoot, branchHead, path43)
54812
+ const conflicts = readChangedGitlinkPaths(repoRoot, baseHead, branchHead).map((path44) => ({
54813
+ path: path44,
54814
+ baseCommit: readTreeObject(repoRoot, baseHead, path44),
54815
+ branchCommit: readTreeObject(repoRoot, branchHead, path44)
54784
54816
  }));
54785
54817
  if (conflicts.length === 0) return void 0;
54786
54818
  return {
@@ -54806,11 +54838,11 @@ function readChangedGitlinkPaths(repoRoot, fromRef, toRef) {
54806
54838
  if (!line.trim()) continue;
54807
54839
  const metaAndPath = line.split(" ");
54808
54840
  const meta = metaAndPath[0] || "";
54809
- const path43 = metaAndPath[metaAndPath.length - 1]?.trim();
54810
- if (!path43) continue;
54841
+ const path44 = metaAndPath[metaAndPath.length - 1]?.trim();
54842
+ if (!path44) continue;
54811
54843
  const parts = meta.split(/\s+/);
54812
54844
  if (parts[0]?.includes("160000") || parts[1]?.includes("160000")) {
54813
- paths.add(path43);
54845
+ paths.add(path44);
54814
54846
  }
54815
54847
  }
54816
54848
  return [...paths].sort();
@@ -54818,9 +54850,9 @@ function readChangedGitlinkPaths(repoRoot, fromRef, toRef) {
54818
54850
  return [];
54819
54851
  }
54820
54852
  }
54821
- function readTreeObject(repoRoot, ref, path43) {
54853
+ function readTreeObject(repoRoot, ref, path44) {
54822
54854
  try {
54823
- const output = (0, import_node_child_process6.execFileSync)(GIT2, ["ls-tree", ref, "--", path43], {
54855
+ const output = (0, import_node_child_process6.execFileSync)(GIT2, ["ls-tree", ref, "--", path44], {
54824
54856
  cwd: repoRoot,
54825
54857
  encoding: "utf8",
54826
54858
  maxBuffer: 1024 * 1024
@@ -54865,12 +54897,12 @@ function readChangedPathKinds(repoRoot, fromRef, toRef) {
54865
54897
  if (!line.trim()) continue;
54866
54898
  const metaAndPath = line.split(" ");
54867
54899
  const meta = metaAndPath[0] || "";
54868
- const path43 = metaAndPath[metaAndPath.length - 1]?.trim();
54869
- if (!path43 || seen.has(path43)) continue;
54870
- seen.add(path43);
54900
+ const path44 = metaAndPath[metaAndPath.length - 1]?.trim();
54901
+ if (!path44 || seen.has(path44)) continue;
54902
+ seen.add(path44);
54871
54903
  const parts = meta.split(/\s+/);
54872
54904
  const isGitlink = !!(parts[0]?.includes("160000") || parts[1]?.includes("160000"));
54873
- result.push({ path: path43, isGitlink });
54905
+ result.push({ path: path44, isGitlink });
54874
54906
  }
54875
54907
  return result;
54876
54908
  } catch {
@@ -54878,20 +54910,20 @@ function readChangedPathKinds(repoRoot, fromRef, toRef) {
54878
54910
  }
54879
54911
  }
54880
54912
  function collectFastForwardGitlinkPaths(repoRoot, baseHead, branchHead) {
54881
- return readChangedGitlinkPaths(repoRoot, baseHead, branchHead).filter((path43) => {
54882
- const baseCommit = readTreeObject(repoRoot, baseHead, path43);
54883
- const branchCommit = readTreeObject(repoRoot, branchHead, path43);
54913
+ return readChangedGitlinkPaths(repoRoot, baseHead, branchHead).filter((path44) => {
54914
+ const baseCommit = readTreeObject(repoRoot, baseHead, path44);
54915
+ const branchCommit = readTreeObject(repoRoot, branchHead, path44);
54884
54916
  if (!baseCommit || !branchCommit) return false;
54885
- return isSubmoduleFastForward((0, import_path14.resolve)(repoRoot, path43), baseCommit, branchCommit);
54917
+ return isSubmoduleFastForward((0, import_path14.resolve)(repoRoot, path44), baseCommit, branchCommit);
54886
54918
  });
54887
54919
  }
54888
54920
  function evaluateGitlinkTrivialFastForward(repoRoot, baseHead, branchHead) {
54889
- const changedGitlinks = readChangedGitlinkPaths(repoRoot, baseHead, branchHead).map((path43) => {
54890
- const baseCommit = readTreeObject(repoRoot, baseHead, path43);
54891
- const branchCommit = readTreeObject(repoRoot, branchHead, path43);
54892
- const submoduleRepoPath = (0, import_path14.resolve)(repoRoot, path43);
54921
+ const changedGitlinks = readChangedGitlinkPaths(repoRoot, baseHead, branchHead).map((path44) => {
54922
+ const baseCommit = readTreeObject(repoRoot, baseHead, path44);
54923
+ const branchCommit = readTreeObject(repoRoot, branchHead, path44);
54924
+ const submoduleRepoPath = (0, import_path14.resolve)(repoRoot, path44);
54893
54925
  const fastForward = !!baseCommit && !!branchCommit && isSubmoduleFastForward(submoduleRepoPath, baseCommit, branchCommit);
54894
- return { path: path43, baseCommit, branchCommit, fastForward };
54926
+ return { path: path44, baseCommit, branchCommit, fastForward };
54895
54927
  });
54896
54928
  if (changedGitlinks.length === 0) {
54897
54929
  return { trivial: false, reason: "no_changed_gitlinks", gitlinks: changedGitlinks };
@@ -54942,7 +54974,7 @@ function buildTreeWithGitlinksEqualized(repoRoot, commitish, paths, placeholderC
54942
54974
  maxBuffer: 1024 * 1024
54943
54975
  }).trim();
54944
54976
  if (!tree) return void 0;
54945
- const updates = paths.map((path43) => `160000 commit ${placeholderCommit} ${path43}`).join("\n");
54977
+ const updates = paths.map((path44) => `160000 commit ${placeholderCommit} ${path44}`).join("\n");
54946
54978
  if (!updates) return tree;
54947
54979
  const tmpIndex = (0, import_path14.join)(resolveGitDir(repoRoot), `adhdev-refine-eq-${commitish.slice(0, 12)}.index`);
54948
54980
  const env = { ...process.env, GIT_INDEX_FILE: tmpIndex };
@@ -55045,7 +55077,7 @@ function synthesizeTrivialFastForwardMergeTree(repoRoot, baseHead, branchHead, g
55045
55077
  }
55046
55078
  async function alignRefinerySubmodulesAfterMerge(repoRoot, previousBaseHead, currentHead, options = {}) {
55047
55079
  const startedAt = Date.now();
55048
- const changedGitlinkPaths = readChangedGitlinkPaths(repoRoot, previousBaseHead, currentHead).filter((path43) => !(options.submoduleIgnorePaths || []).includes(path43));
55080
+ const changedGitlinkPaths = readChangedGitlinkPaths(repoRoot, previousBaseHead, currentHead).filter((path44) => !(options.submoduleIgnorePaths || []).includes(path44));
55049
55081
  const preStatus = await getGitRepoStatus(repoRoot, {
55050
55082
  includeSubmodules: true,
55051
55083
  submoduleIgnorePaths: options.submoduleIgnorePaths,
@@ -55092,7 +55124,7 @@ async function alignRefinerySubmodulesAfterMerge(repoRoot, previousBaseHead, cur
55092
55124
  changedGitlinkPaths,
55093
55125
  outOfSyncPaths,
55094
55126
  updatedPaths: updatePaths,
55095
- verifiedPaths: updatePaths.filter((path43) => !remaining.some((submodule) => submodule.path === path43)),
55127
+ verifiedPaths: updatePaths.filter((path44) => !remaining.some((submodule) => submodule.path === path44)),
55096
55128
  durationMs: Date.now() - startedAt,
55097
55129
  command: `git ${commandArgs.join(" ")}`,
55098
55130
  stdout: truncateValidationOutput(result.stdout),
@@ -55418,15 +55450,15 @@ async function runMeshRefineValidationGate(mesh, workspace, opts) {
55418
55450
  const cwd = candidate.cwd ? (0, import_path14.resolve)(workspace, candidate.cwd) : workspace;
55419
55451
  const timeout = candidate.timeoutMs || REFINE_VALIDATION_TIMEOUT_MS;
55420
55452
  const resolvedCommand = resolveWin32Executable(candidate.command);
55421
- const spawn4 = buildWin32ExecFileSpawn(resolvedCommand, candidate.args);
55453
+ const spawn5 = buildWin32ExecFileSpawn(resolvedCommand, candidate.args);
55422
55454
  try {
55423
- const result = await execFileAsync4(spawn4.file, spawn4.args, {
55455
+ const result = await execFileAsync4(spawn5.file, spawn5.args, {
55424
55456
  cwd,
55425
55457
  encoding: "utf8",
55426
55458
  timeout,
55427
55459
  maxBuffer: candidate.outputLimitBytes || REFINE_VALIDATION_OUTPUT_LIMIT_BYTES,
55428
55460
  env: { ...process.env, CI: process.env.CI || "1", ...candidate.env || {} },
55429
- ...spawn4.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
55461
+ ...spawn5.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
55430
55462
  });
55431
55463
  summary.bootstrapCommandsRun.push(commandRecord(candidate, cwd, startedAt, result, true, { exitCode: 0 }));
55432
55464
  } catch (error) {
@@ -55464,15 +55496,15 @@ async function runMeshRefineValidationGate(mesh, workspace, opts) {
55464
55496
  return summary;
55465
55497
  }
55466
55498
  const resolvedCommand = resolveWin32Executable(candidate.command);
55467
- const spawn4 = buildWin32ExecFileSpawn(resolvedCommand, candidate.args);
55499
+ const spawn5 = buildWin32ExecFileSpawn(resolvedCommand, candidate.args);
55468
55500
  try {
55469
- const result = await execFileAsync4(spawn4.file, spawn4.args, {
55501
+ const result = await execFileAsync4(spawn5.file, spawn5.args, {
55470
55502
  cwd,
55471
55503
  encoding: "utf8",
55472
55504
  timeout,
55473
55505
  maxBuffer: candidate.outputLimitBytes || REFINE_VALIDATION_OUTPUT_LIMIT_BYTES,
55474
55506
  env: { ...process.env, CI: process.env.CI || "1", ...candidate.env || {} },
55475
- ...spawn4.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
55507
+ ...spawn5.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
55476
55508
  });
55477
55509
  summary.commandsRun.push(commandRecord(candidate, cwd, startedAt, result, true, { exitCode: 0 }));
55478
55510
  } catch (error) {
@@ -56181,7 +56213,7 @@ var DaemonCommandRouter = class {
56181
56213
  */
56182
56214
  async bestEffortRemoveWorktreeDir(dir) {
56183
56215
  if (!dir || !fs32.existsSync(dir)) return { removed: true, residue: false };
56184
- const sleep3 = (ms) => new Promise((resolve24) => setTimeout(resolve24, ms));
56216
+ const sleep3 = (ms) => new Promise((resolve25) => setTimeout(resolve25, ms));
56185
56217
  const ABSORB = /* @__PURE__ */ new Set(["EINVAL", "EPERM", "EBUSY", "ENOTEMPTY", "EACCES", "EMFILE", "ENFILE"]);
56186
56218
  let lastErr;
56187
56219
  for (let attempt = 0; attempt < 4; attempt++) {
@@ -56625,6 +56657,13 @@ var DaemonCommandRouter = class {
56625
56657
  }
56626
56658
  if (!this.deps.sessionHostControl) return { success: false, error: "Session host control unavailable" };
56627
56659
  const requestedSessionIds = Array.isArray(args.sessionIds) ? new Set(args.sessionIds.map((id) => typeof id === "string" ? id.trim() : "").filter(Boolean)) : void 0;
56660
+ const reclaimOrphans = args.reclaimOrphans === true;
56661
+ const liveMeshNodeIds = Array.isArray(args.liveMeshNodeIds) ? args.liveMeshNodeIds.map((id) => typeof id === "string" ? id.trim() : "").filter(Boolean) : [];
56662
+ const isNodeStillLive = (candidateNodeId) => {
56663
+ if (!candidateNodeId) return false;
56664
+ return liveMeshNodeIds.some((liveId) => liveId === candidateNodeId || meshNodeIdMatches({ id: liveId }, candidateNodeId) || daemonIdsEquivalent(liveId, candidateNodeId));
56665
+ };
56666
+ const reclaimedOrphanSessionIds = [];
56628
56667
  const sessions = await this.deps.sessionHostControl.listSessions();
56629
56668
  const matched = sessions.filter((record) => this.sessionMatchesMeshNode(record, args.node, args.nodeId, requestedSessionIds));
56630
56669
  const hasExplicitSessionIds = !!requestedSessionIds?.size;
@@ -56693,7 +56732,8 @@ var DaemonCommandRouter = class {
56693
56732
  const matchedByWorkspaceOnly = !recordNodeId;
56694
56733
  const isWorktreeNodeRemoval = cleanupSource === "mesh_remove_node" && args.node?.isLocalWorktree === true;
56695
56734
  const cleanWorkspaceOnlyForWorktree = isWorktreeNodeRemoval && matchedByWorkspaceOnly;
56696
- if (!hasExplicitSessionIds && liveRuntime && !delegateBoundToThisNode && !cleanWorkspaceOnlyForWorktree) {
56735
+ const reclaimableOrphan = reclaimOrphans && liveRuntime && !delegateBoundToThisNode && (matchedByWorkspaceOnly || !isNodeStillLive(recordNodeId));
56736
+ if (!hasExplicitSessionIds && liveRuntime && !delegateBoundToThisNode && !cleanWorkspaceOnlyForWorktree && !reclaimableOrphan) {
56697
56737
  skippedSessionIds.push(sessionId);
56698
56738
  skippedLiveSessionIds.push(sessionId);
56699
56739
  const reason = recordNodeId && recordNodeId !== args.nodeId ? `live_delegate_bound_to_other_node:${recordNodeId}` : matchedByWorkspaceOnly ? "live_session_matched_by_workspace_only_no_node_binding" : "live_session_not_bound_to_this_node";
@@ -56703,6 +56743,10 @@ var DaemonCommandRouter = class {
56703
56743
  if (cleanWorkspaceOnlyForWorktree && !delegateBoundToThisNode) {
56704
56744
  actedLiveDelegateSessionIds.push(sessionId);
56705
56745
  }
56746
+ if (reclaimableOrphan && !cleanWorkspaceOnlyForWorktree && !delegateBoundToThisNode) {
56747
+ reclaimedOrphanSessionIds.push(sessionId);
56748
+ actedLiveDelegateSessionIds.push(sessionId);
56749
+ }
56706
56750
  if (!hasExplicitSessionIds && liveRuntime && delegateBoundToThisNode && args.mode === "delete_stopped") {
56707
56751
  skippedSessionIds.push(sessionId);
56708
56752
  skippedLiveSessionIds.push(sessionId);
@@ -56775,6 +56819,7 @@ var DaemonCommandRouter = class {
56775
56819
  skippedCoordinatorSessionIds,
56776
56820
  ...skippedMarkerMismatchSessionIds.length ? { skippedMarkerMismatchSessionIds } : {},
56777
56821
  ...actedLiveDelegateSessionIds.length ? { actedLiveDelegateSessionIds } : {},
56822
+ ...reclaimedOrphanSessionIds.length ? { reclaimedOrphanSessionIds } : {},
56778
56823
  ...skippedLiveSessionReasons.length ? { skippedLiveSessionReasons } : {},
56779
56824
  ...deleteUnsupported ? {
56780
56825
  deleteUnsupported: true,
@@ -58939,7 +58984,7 @@ var ProviderStreamAdapter = class {
58939
58984
  const beforeCount = this.messageCount(before);
58940
58985
  const beforeSignature = this.lastMessageSignature(before);
58941
58986
  for (let attempt = 0; attempt < 12; attempt += 1) {
58942
- await new Promise((resolve24) => setTimeout(resolve24, 250));
58987
+ await new Promise((resolve25) => setTimeout(resolve25, 250));
58943
58988
  let state;
58944
58989
  try {
58945
58990
  state = await this.readChat(evaluate);
@@ -58961,7 +59006,7 @@ var ProviderStreamAdapter = class {
58961
59006
  if (this.messageCount(first) > 0 || this.lastMessageSignature(first)) {
58962
59007
  return first;
58963
59008
  }
58964
- await new Promise((resolve24) => setTimeout(resolve24, 150));
59009
+ await new Promise((resolve25) => setTimeout(resolve25, 150));
58965
59010
  const second = await this.readChat(evaluate);
58966
59011
  return this.messageCount(second) >= this.messageCount(first) ? second : first;
58967
59012
  }
@@ -59112,7 +59157,7 @@ var ProviderStreamAdapter = class {
59112
59157
  if (typeof data.error === "string" && data.error.trim()) return false;
59113
59158
  }
59114
59159
  for (let attempt = 0; attempt < 6; attempt += 1) {
59115
- await new Promise((resolve24) => setTimeout(resolve24, 250));
59160
+ await new Promise((resolve25) => setTimeout(resolve25, 250));
59116
59161
  const state = await this.readChat(evaluate);
59117
59162
  const title = this.getStateTitle(state);
59118
59163
  if (this.titlesMatch(title, sessionId)) return true;
@@ -60104,13 +60149,13 @@ var VersionArchive = class {
60104
60149
  }
60105
60150
  };
60106
60151
  async function runCommand(cmd, timeout = 1e4) {
60107
- return new Promise((resolve24) => {
60152
+ return new Promise((resolve25) => {
60108
60153
  (0, import_child_process10.exec)(cmd, {
60109
60154
  encoding: "utf-8",
60110
60155
  timeout
60111
60156
  }, (error, stdout) => {
60112
- if (error) return resolve24(null);
60113
- resolve24(stdout.trim());
60157
+ if (error) return resolve25(null);
60158
+ resolve25(stdout.trim());
60114
60159
  });
60115
60160
  });
60116
60161
  }
@@ -61810,7 +61855,7 @@ function getCliTargetBundle(ctx, type, instanceId) {
61810
61855
  return { target, instance, adapter };
61811
61856
  }
61812
61857
  function sleep2(ms) {
61813
- return new Promise((resolve24) => setTimeout(resolve24, ms));
61858
+ return new Promise((resolve25) => setTimeout(resolve25, ms));
61814
61859
  }
61815
61860
  async function waitForCliReady(ctx, type, instanceId, timeoutMs) {
61816
61861
  const startedAt = Date.now();
@@ -62786,8 +62831,8 @@ async function handleAutoImplement(ctx, type, req, res) {
62786
62831
  fs36.writeFileSync(promptFile, prompt, "utf-8");
62787
62832
  ctx.log(`Auto-implement prompt written to ${promptFile} (${prompt.length} chars)`);
62788
62833
  const agentProvider = ctx.providerLoader.resolve(agent) || ctx.providerLoader.getMeta(agent);
62789
- const spawn4 = agentProvider?.spawn;
62790
- if (!spawn4?.command) {
62834
+ const spawn5 = agentProvider?.spawn;
62835
+ if (!spawn5?.command) {
62791
62836
  try {
62792
62837
  fs36.unlinkSync(promptFile);
62793
62838
  } catch {
@@ -62797,22 +62842,22 @@ async function handleAutoImplement(ctx, type, req, res) {
62797
62842
  }
62798
62843
  const agentCategory = agentProvider?.category;
62799
62844
  if (agentCategory === "acp") {
62800
- sendAutoImplSSE(ctx, { event: "progress", data: { function: "_init", status: "spawning", message: `Spawning ACP agent: ${spawn4.command} ${(spawn4.args || []).join(" ")}` } });
62845
+ sendAutoImplSSE(ctx, { event: "progress", data: { function: "_init", status: "spawning", message: `Spawning ACP agent: ${spawn5.command} ${(spawn5.args || []).join(" ")}` } });
62801
62846
  ctx.autoImplStatus.running = true;
62802
62847
  ctx.autoImplStatus.type = type;
62803
62848
  const { ClientSideConnection: ClientSideConnection2, ndJsonStream: ndJsonStream2, PROTOCOL_VERSION: PROTOCOL_VERSION2 } = await import("@agentclientprotocol/sdk");
62804
62849
  const { Readable: Readable2, Writable: Writable2 } = await import("stream");
62805
62850
  const { spawn: spawnFn2 } = await import("child_process");
62806
- const acpArgs = [...spawn4.args || []];
62851
+ const acpArgs = [...spawn5.args || []];
62807
62852
  if (model) {
62808
62853
  acpArgs.push("--model", model);
62809
62854
  ctx.log(`Auto-implement ACP using model: ${model}`);
62810
62855
  }
62811
- const child2 = spawnFn2(spawn4.command, acpArgs, {
62856
+ const child2 = spawnFn2(spawn5.command, acpArgs, {
62812
62857
  cwd: providerDir,
62813
62858
  stdio: ["pipe", "pipe", "pipe"],
62814
- shell: spawn4.shell ?? false,
62815
- env: { ...process.env, ...spawn4.env || {} }
62859
+ shell: spawn5.shell ?? false,
62860
+ env: { ...process.env, ...spawn5.env || {} }
62816
62861
  });
62817
62862
  ctx.autoImplProcess = child2;
62818
62863
  child2.stderr?.on("data", (d) => {
@@ -62922,7 +62967,7 @@ async function handleAutoImplement(ctx, type, req, res) {
62922
62967
  ctx.json(res, 202, {
62923
62968
  started: true,
62924
62969
  type,
62925
- agent: spawn4.command,
62970
+ agent: spawn5.command,
62926
62971
  functions,
62927
62972
  providerDir,
62928
62973
  message: "ACP Auto-implement started. Connect to SSE for progress.",
@@ -62930,10 +62975,10 @@ async function handleAutoImplement(ctx, type, req, res) {
62930
62975
  });
62931
62976
  return;
62932
62977
  }
62933
- const command = spawn4.command;
62934
- const autoImpl = spawn4.autoImpl;
62978
+ const command = spawn5.command;
62979
+ const autoImpl = spawn5.autoImpl;
62935
62980
  const interactiveFlags = ["--yolo", "--interactive", "-i"];
62936
- const baseArgs = [...spawn4.args || []].filter((a) => !interactiveFlags.includes(a));
62981
+ const baseArgs = [...spawn5.args || []].filter((a) => !interactiveFlags.includes(a));
62937
62982
  let shellCmd;
62938
62983
  const isWin = os29.platform() === "win32";
62939
62984
  const escapeArg = (a) => isWin ? `"${a.replace(/"/g, '""')}"` : `'${a.replace(/'/g, "'\\''")}'`;
@@ -62980,7 +63025,7 @@ async function handleAutoImplement(ctx, type, req, res) {
62980
63025
  cols: import_session_host_core8.DEFAULT_SESSION_HOST_COLS,
62981
63026
  rows: import_session_host_core8.DEFAULT_SESSION_HOST_ROWS,
62982
63027
  cwd: providerDir,
62983
- env: { ...process.env, ...spawn4.env || {} }
63028
+ env: { ...process.env, ...spawn5.env || {} }
62984
63029
  });
62985
63030
  isPty = true;
62986
63031
  } catch (err) {
@@ -62992,7 +63037,7 @@ async function handleAutoImplement(ctx, type, req, res) {
62992
63037
  stdio: ["pipe", "pipe", "pipe"],
62993
63038
  env: {
62994
63039
  ...process.env,
62995
- ...spawn4.env || {}
63040
+ ...spawn5.env || {}
62996
63041
  }
62997
63042
  });
62998
63043
  child.on("error", (err2) => {
@@ -64034,8 +64079,8 @@ var DevServer = class _DevServer {
64034
64079
  }
64035
64080
  getEndpointList() {
64036
64081
  return this.routes.map((r) => {
64037
- const path43 = typeof r.pattern === "string" ? r.pattern : r.pattern.source.replace(/\\\//g, "/").replace(/\(\[.*?\]\+\)/g, ":type").replace(/[\^$]/g, "");
64038
- return `${r.method.padEnd(5)} ${path43}`;
64082
+ const path44 = typeof r.pattern === "string" ? r.pattern : r.pattern.source.replace(/\\\//g, "/").replace(/\(\[.*?\]\+\)/g, ":type").replace(/[\^$]/g, "");
64083
+ return `${r.method.padEnd(5)} ${path44}`;
64039
64084
  });
64040
64085
  }
64041
64086
  async start(port = DEV_SERVER_PORT) {
@@ -64066,15 +64111,15 @@ var DevServer = class _DevServer {
64066
64111
  this.json(res, 500, { error: e.message });
64067
64112
  }
64068
64113
  });
64069
- return new Promise((resolve24, reject) => {
64114
+ return new Promise((resolve25, reject) => {
64070
64115
  this.server.listen(port, "127.0.0.1", () => {
64071
64116
  this.log(`Dev server listening on http://127.0.0.1:${port}`);
64072
- resolve24();
64117
+ resolve25();
64073
64118
  });
64074
64119
  this.server.on("error", (e) => {
64075
64120
  if (e.code === "EADDRINUSE") {
64076
64121
  this.log(`Port ${port} in use, skipping dev server`);
64077
- resolve24();
64122
+ resolve25();
64078
64123
  } else {
64079
64124
  reject(e);
64080
64125
  }
@@ -64135,16 +64180,16 @@ var DevServer = class _DevServer {
64135
64180
  this.json(res, 404, { error: `Provider not found: ${type}` });
64136
64181
  return;
64137
64182
  }
64138
- const spawn4 = provider.spawn;
64139
- if (!spawn4) {
64183
+ const spawn5 = provider.spawn;
64184
+ if (!spawn5) {
64140
64185
  this.json(res, 400, { error: `Provider ${type} has no spawn config` });
64141
64186
  return;
64142
64187
  }
64143
64188
  const { spawn: spawnFn } = await import("child_process");
64144
64189
  const start = Date.now();
64145
64190
  try {
64146
- const child = spawnFn(spawn4.command, [...spawn4.args || []], {
64147
- shell: spawn4.shell ?? false,
64191
+ const child = spawnFn(spawn5.command, [...spawn5.args || []], {
64192
+ shell: spawn5.shell ?? false,
64148
64193
  timeout: 5e3,
64149
64194
  stdio: ["pipe", "pipe", "pipe"]
64150
64195
  });
@@ -64156,27 +64201,27 @@ var DevServer = class _DevServer {
64156
64201
  child.stderr?.on("data", (d) => {
64157
64202
  stderr += d.toString().slice(0, 2e3);
64158
64203
  });
64159
- await new Promise((resolve24) => {
64204
+ await new Promise((resolve25) => {
64160
64205
  const timer = setTimeout(() => {
64161
64206
  child.kill();
64162
- resolve24();
64207
+ resolve25();
64163
64208
  }, 3e3);
64164
64209
  child.on("exit", () => {
64165
64210
  clearTimeout(timer);
64166
- resolve24();
64211
+ resolve25();
64167
64212
  });
64168
64213
  child.stdout?.once("data", () => {
64169
64214
  setTimeout(() => {
64170
64215
  child.kill();
64171
64216
  clearTimeout(timer);
64172
- resolve24();
64217
+ resolve25();
64173
64218
  }, 500);
64174
64219
  });
64175
64220
  });
64176
64221
  const elapsed = Date.now() - start;
64177
64222
  this.json(res, 200, {
64178
64223
  success: true,
64179
- command: `${spawn4.command} ${(spawn4.args || []).join(" ")}`,
64224
+ command: `${spawn5.command} ${(spawn5.args || []).join(" ")}`,
64180
64225
  elapsed,
64181
64226
  stdout: stdout.trim(),
64182
64227
  stderr: stderr.trim(),
@@ -64186,7 +64231,7 @@ var DevServer = class _DevServer {
64186
64231
  const elapsed = Date.now() - start;
64187
64232
  this.json(res, 200, {
64188
64233
  success: false,
64189
- command: `${spawn4.command} ${(spawn4.args || []).join(" ")}`,
64234
+ command: `${spawn5.command} ${(spawn5.args || []).join(" ")}`,
64190
64235
  elapsed,
64191
64236
  error: e.message
64192
64237
  });
@@ -64649,20 +64694,20 @@ var DevServer = class _DevServer {
64649
64694
  this.json(res, 404, { error: `Provider not found: ${type}` });
64650
64695
  return;
64651
64696
  }
64652
- const spawn4 = provider.spawn;
64653
- if (!spawn4) {
64697
+ const spawn5 = provider.spawn;
64698
+ if (!spawn5) {
64654
64699
  this.json(res, 400, { error: `Provider ${type} has no spawn config` });
64655
64700
  return;
64656
64701
  }
64657
64702
  const { spawn: spawnFn } = await import("child_process");
64658
64703
  const start = Date.now();
64659
64704
  try {
64660
- const args = [...spawn4.args || [], message];
64661
- const child = spawnFn(spawn4.command, args, {
64662
- shell: spawn4.shell ?? false,
64705
+ const args = [...spawn5.args || [], message];
64706
+ const child = spawnFn(spawn5.command, args, {
64707
+ shell: spawn5.shell ?? false,
64663
64708
  timeout,
64664
64709
  stdio: ["pipe", "pipe", "pipe"],
64665
- env: { ...process.env, ...spawn4.env || {} }
64710
+ env: { ...process.env, ...spawn5.env || {} }
64666
64711
  });
64667
64712
  let stdout = "";
64668
64713
  let stderr = "";
@@ -64672,14 +64717,14 @@ var DevServer = class _DevServer {
64672
64717
  child.stderr?.on("data", (d) => {
64673
64718
  stderr += d.toString();
64674
64719
  });
64675
- await new Promise((resolve24) => {
64720
+ await new Promise((resolve25) => {
64676
64721
  const timer = setTimeout(() => {
64677
64722
  child.kill();
64678
- resolve24();
64723
+ resolve25();
64679
64724
  }, timeout);
64680
64725
  child.on("exit", () => {
64681
64726
  clearTimeout(timer);
64682
- resolve24();
64727
+ resolve25();
64683
64728
  });
64684
64729
  });
64685
64730
  const elapsed = Date.now() - start;
@@ -64878,14 +64923,14 @@ data: ${JSON.stringify(msg.data)}
64878
64923
  res.end(JSON.stringify(data, null, 2));
64879
64924
  }
64880
64925
  async readBody(req) {
64881
- return new Promise((resolve24) => {
64926
+ return new Promise((resolve25) => {
64882
64927
  let body = "";
64883
64928
  req.on("data", (chunk) => body += chunk);
64884
64929
  req.on("end", () => {
64885
64930
  try {
64886
- resolve24(JSON.parse(body));
64931
+ resolve25(JSON.parse(body));
64887
64932
  } catch {
64888
- resolve24({});
64933
+ resolve25({});
64889
64934
  }
64890
64935
  });
64891
64936
  });
@@ -65620,7 +65665,7 @@ async function waitForReady(endpoint, timeoutMs = STARTUP_TIMEOUT_MS, requiredRe
65620
65665
  const deadline = Date.now() + timeoutMs;
65621
65666
  while (Date.now() < deadline) {
65622
65667
  if (await canConnect(endpoint, requiredRequestTypes)) return;
65623
- await new Promise((resolve24) => setTimeout(resolve24, STARTUP_POLL_MS));
65668
+ await new Promise((resolve25) => setTimeout(resolve25, STARTUP_POLL_MS));
65624
65669
  }
65625
65670
  throw new Error(`Session host did not become ready within ${timeoutMs}ms`);
65626
65671
  }
@@ -65661,6 +65706,148 @@ async function listHostedCliRuntimes(endpoint) {
65661
65706
  }
65662
65707
  }
65663
65708
 
65709
+ // src/session-host/managed-host.ts
65710
+ var import_child_process11 = require("child_process");
65711
+ var fs38 = __toESM(require("fs"));
65712
+ var os30 = __toESM(require("os"));
65713
+ var path43 = __toESM(require("path"));
65714
+ var import_session_host_core12 = require("@adhdev/session-host-core");
65715
+ init_runtime_defaults();
65716
+ function createManagedSessionHost(options) {
65717
+ const appName = options.appName;
65718
+ const timeoutMs = options.timeoutMs ?? DEFAULT_SESSION_HOST_READY_TIMEOUT_MS;
65719
+ const endpoint = (0, import_session_host_core12.getDefaultSessionHostEndpoint)(appName);
65720
+ const isManagedPid = options.isManagedPid ?? (() => true);
65721
+ function buildEnv(baseEnv) {
65722
+ const env = (0, import_session_host_core12.sanitizeSpawnEnv)(baseEnv);
65723
+ env.ADHDEV_SESSION_HOST_NAME = appName;
65724
+ return env;
65725
+ }
65726
+ function resolveEntry() {
65727
+ const packagedCandidates = [
65728
+ path43.resolve(__dirname, "../vendor/session-host-daemon/index.js"),
65729
+ path43.resolve(__dirname, "../../vendor/session-host-daemon/index.js")
65730
+ ];
65731
+ for (const candidate of packagedCandidates) {
65732
+ if (fs38.existsSync(candidate)) {
65733
+ return candidate;
65734
+ }
65735
+ }
65736
+ return require.resolve("@adhdev/session-host-daemon");
65737
+ }
65738
+ function getPidFile() {
65739
+ return path43.join(os30.homedir(), ".adhdev", `${appName}-session-host.pid`);
65740
+ }
65741
+ function getPid() {
65742
+ try {
65743
+ const pidFile = getPidFile();
65744
+ if (!fs38.existsSync(pidFile)) return null;
65745
+ const pid = Number.parseInt(fs38.readFileSync(pidFile, "utf8").trim(), 10);
65746
+ return Number.isFinite(pid) ? pid : null;
65747
+ } catch {
65748
+ return null;
65749
+ }
65750
+ }
65751
+ function killPid2(pid) {
65752
+ try {
65753
+ if (process.platform === "win32") {
65754
+ const spawnOpts = { stdio: "ignore" };
65755
+ if (options.killWindowsHide) spawnOpts.windowsHide = true;
65756
+ (0, import_child_process11.execFileSync)("taskkill", ["/PID", String(pid), "/T", "/F"], spawnOpts);
65757
+ } else {
65758
+ process.kill(pid, "SIGTERM");
65759
+ }
65760
+ return true;
65761
+ } catch {
65762
+ return false;
65763
+ }
65764
+ }
65765
+ function spawnHost() {
65766
+ const entry = resolveEntry();
65767
+ let stdio = "ignore";
65768
+ let logFd = null;
65769
+ if (options.spawnStdio === "logfile") {
65770
+ const logDir = path43.join(os30.homedir(), ".adhdev", "logs");
65771
+ fs38.mkdirSync(logDir, { recursive: true });
65772
+ logFd = fs38.openSync(path43.join(logDir, "session-host.log"), "a");
65773
+ stdio = ["ignore", logFd, logFd];
65774
+ }
65775
+ const child = (0, import_child_process11.spawn)(process.execPath, [entry], {
65776
+ detached: true,
65777
+ stdio,
65778
+ windowsHide: true,
65779
+ env: buildEnv(process.env)
65780
+ });
65781
+ child.unref();
65782
+ if (logFd !== null) {
65783
+ try {
65784
+ fs38.closeSync(logFd);
65785
+ } catch {
65786
+ }
65787
+ }
65788
+ }
65789
+ function stopManagedSessionHostProcess() {
65790
+ let stopped = false;
65791
+ const pidFile = getPidFile();
65792
+ try {
65793
+ if (fs38.existsSync(pidFile)) {
65794
+ const pid = Number.parseInt(fs38.readFileSync(pidFile, "utf8").trim(), 10);
65795
+ if (Number.isFinite(pid) && pid !== process.pid && isManagedPid(pid)) {
65796
+ stopped = killPid2(pid) || stopped;
65797
+ }
65798
+ }
65799
+ } catch {
65800
+ } finally {
65801
+ try {
65802
+ fs38.unlinkSync(pidFile);
65803
+ } catch {
65804
+ }
65805
+ }
65806
+ if (options.extraStop) {
65807
+ stopped = options.extraStop(endpoint) || stopped;
65808
+ }
65809
+ return stopped;
65810
+ }
65811
+ async function ensureReady() {
65812
+ options.beforeEnsureReady?.();
65813
+ try {
65814
+ return await ensureSessionHostReady({
65815
+ appName,
65816
+ spawnHost,
65817
+ timeoutMs,
65818
+ requiredRequestTypes: options.requiredRequestTypes
65819
+ });
65820
+ } catch (error) {
65821
+ stopManagedSessionHostProcess();
65822
+ return ensureSessionHostReady({
65823
+ appName,
65824
+ spawnHost,
65825
+ timeoutMs,
65826
+ requiredRequestTypes: options.requiredRequestTypes
65827
+ }).catch((retryError) => {
65828
+ const initialMessage = error instanceof Error ? error.message : String(error);
65829
+ const retryMessage = retryError instanceof Error ? retryError.message : String(retryError);
65830
+ throw new Error(`Session host failed to start after retry (${initialMessage}; retry: ${retryMessage})`);
65831
+ });
65832
+ }
65833
+ }
65834
+ return {
65835
+ appName,
65836
+ endpoint,
65837
+ getPidFile,
65838
+ getPid,
65839
+ buildEnv,
65840
+ resolveEntry,
65841
+ killPid: killPid2,
65842
+ spawnHost,
65843
+ stopManagedSessionHostProcess,
65844
+ ensureReady,
65845
+ getStatusPaths() {
65846
+ return { pidFile: getPidFile(), endpoint };
65847
+ }
65848
+ };
65849
+ }
65850
+
65664
65851
  // src/session-host/startup-restore-policy.js
65665
65852
  function shouldAutoRestoreHostedSessionsOnStartup(env = process.env) {
65666
65853
  const raw = typeof env.ADHDEV_RESTORE_HOSTED_SESSIONS_ON_STARTUP === "string" ? env.ADHDEV_RESTORE_HOSTED_SESSIONS_ON_STARTUP.trim().toLowerCase() : "";
@@ -65670,7 +65857,7 @@ function shouldAutoRestoreHostedSessionsOnStartup(env = process.env) {
65670
65857
  }
65671
65858
 
65672
65859
  // src/installer.ts
65673
- var import_child_process11 = require("child_process");
65860
+ var import_child_process12 = require("child_process");
65674
65861
  var import_util3 = require("util");
65675
65862
  var EXTENSION_CATALOG = [
65676
65863
  // AI Agent extensions
@@ -65758,7 +65945,7 @@ var EXTENSION_CATALOG = [
65758
65945
  apiKeyName: "OpenAI/Anthropic API key"
65759
65946
  }
65760
65947
  ];
65761
- var execAsync4 = (0, import_util3.promisify)(import_child_process11.exec);
65948
+ var execAsync4 = (0, import_util3.promisify)(import_child_process12.exec);
65762
65949
  async function isExtensionInstalled(ide, marketplaceId) {
65763
65950
  if (!ide.cliCommand) return false;
65764
65951
  try {
@@ -65798,12 +65985,12 @@ async function installExtension(ide, extension) {
65798
65985
  const res = await fetch(extension.vsixUrl);
65799
65986
  if (res.ok) {
65800
65987
  const buffer = Buffer.from(await res.arrayBuffer());
65801
- const fs38 = await import("fs");
65802
- fs38.writeFileSync(vsixPath, buffer);
65803
- return new Promise((resolve24) => {
65988
+ const fs39 = await import("fs");
65989
+ fs39.writeFileSync(vsixPath, buffer);
65990
+ return new Promise((resolve25) => {
65804
65991
  const cmd = `"${ide.cliCommand}" --install-extension "${vsixPath}" --force`;
65805
- (0, import_child_process11.exec)(cmd, { timeout: 6e4 }, (error, _stdout, stderr) => {
65806
- resolve24({
65992
+ (0, import_child_process12.exec)(cmd, { timeout: 6e4 }, (error, _stdout, stderr) => {
65993
+ resolve25({
65807
65994
  extensionId: extension.id,
65808
65995
  marketplaceId: extension.marketplaceId,
65809
65996
  success: !error,
@@ -65816,11 +66003,11 @@ async function installExtension(ide, extension) {
65816
66003
  } catch (e) {
65817
66004
  }
65818
66005
  }
65819
- return new Promise((resolve24) => {
66006
+ return new Promise((resolve25) => {
65820
66007
  const cmd = `"${ide.cliCommand}" --install-extension ${extension.marketplaceId} --force`;
65821
- (0, import_child_process11.exec)(cmd, { timeout: 6e4 }, (error, stdout, stderr) => {
66008
+ (0, import_child_process12.exec)(cmd, { timeout: 6e4 }, (error, stdout, stderr) => {
65822
66009
  if (error) {
65823
- resolve24({
66010
+ resolve25({
65824
66011
  extensionId: extension.id,
65825
66012
  marketplaceId: extension.marketplaceId,
65826
66013
  success: false,
@@ -65828,7 +66015,7 @@ async function installExtension(ide, extension) {
65828
66015
  error: stderr || error.message
65829
66016
  });
65830
66017
  } else {
65831
- resolve24({
66018
+ resolve25({
65832
66019
  extensionId: extension.id,
65833
66020
  marketplaceId: extension.marketplaceId,
65834
66021
  success: true,
@@ -65855,7 +66042,7 @@ function launchIDE(ide, workspacePath) {
65855
66042
  if (!ide.cliCommand) return false;
65856
66043
  try {
65857
66044
  const args = workspacePath ? `"${workspacePath}"` : "";
65858
- (0, import_child_process11.exec)(`"${ide.cliCommand}" ${args}`, { timeout: 1e4 });
66045
+ (0, import_child_process12.exec)(`"${ide.cliCommand}" ${args}`, { timeout: 1e4 });
65859
66046
  return true;
65860
66047
  } catch {
65861
66048
  return false;
@@ -66317,7 +66504,7 @@ async function startLocalIpcServer(opts) {
66317
66504
  }));
66318
66505
  }
66319
66506
  }
66320
- await new Promise((resolve24, reject) => {
66507
+ await new Promise((resolve25, reject) => {
66321
66508
  const onError = (error) => {
66322
66509
  httpServer?.off("listening", onListening);
66323
66510
  reject(error);
@@ -66325,7 +66512,7 @@ async function startLocalIpcServer(opts) {
66325
66512
  const onListening = () => {
66326
66513
  httpServer?.off("error", onError);
66327
66514
  listening = true;
66328
- resolve24();
66515
+ resolve25();
66329
66516
  };
66330
66517
  httpServer.once("error", onError);
66331
66518
  httpServer.once("listening", onListening);
@@ -66352,12 +66539,12 @@ async function startLocalIpcServer(opts) {
66352
66539
  }
66353
66540
  }
66354
66541
  clients.clear();
66355
- await new Promise((resolve24) => {
66542
+ await new Promise((resolve25) => {
66356
66543
  if (!httpServer) {
66357
- resolve24();
66544
+ resolve25();
66358
66545
  return;
66359
66546
  }
66360
- httpServer.close(() => resolve24());
66547
+ httpServer.close(() => resolve25());
66361
66548
  });
66362
66549
  httpServer = null;
66363
66550
  wss = null;
@@ -66609,6 +66796,7 @@ var V1_CONTRACT_VERSION = "1.0.0";
66609
66796
  createGitSnapshotStore,
66610
66797
  createGitWorkspaceMonitor,
66611
66798
  createInteractionId,
66799
+ createManagedSessionHost,
66612
66800
  createMesh,
66613
66801
  createNativeHistoryDispatcher,
66614
66802
  createSessionDelivery,