@adhdev/daemon-core 0.9.82-rc.464 → 0.9.82-rc.465

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 ? "260f54788520ce6f51b44fa097d6d3ee337fe79d" : void 0) ?? "unknown";
413
- const commitShort = readInjected(true ? "260f5478" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
414
- const version = readInjected(true ? "0.9.82-rc.464" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
415
- const builtAt = readInjected(true ? "2026-07-05T05:20:43.844Z" : void 0);
412
+ const commit = readInjected(true ? "1fb9559b573b07e5386c80329057766b4822dddb" : void 0) ?? "unknown";
413
+ const commitShort = readInjected(true ? "1fb9559b" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
414
+ const version = readInjected(true ? "0.9.82-rc.465" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
415
+ const builtAt = readInjected(true ? "2026-07-05T07:20:34.545Z" : 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(path44, text) {
490
- if (/\.json$/i.test(path44)) return JSON.parse(text);
489
+ function parseConfigText(path45, text) {
490
+ if (/\.json$/i.test(path45)) 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((path44) => !ignoreSet.has(path44)).map(async (path44) => {
1108
- const repoPath = repo.repoRoot + "/" + path44;
1109
- const expected = await readGitlinkExpectedSha(repo, path44, options);
1107
+ paths.filter((path45) => !ignoreSet.has(path45)).map(async (path45) => {
1108
+ const repoPath = repo.repoRoot + "/" + path45;
1109
+ const expected = await readGitlinkExpectedSha(repo, path45, options);
1110
1110
  const actual = await readSubmoduleHeadSha(repo, repoPath, options);
1111
- if (actual) headOidByPath.set(path44, actual);
1111
+ if (actual) headOidByPath.set(path45, actual);
1112
1112
  const outOfSync = actual === null ? true : expected !== null && expected !== actual;
1113
1113
  return {
1114
- path: path44,
1114
+ path: path45,
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 ?? "",
@@ -2559,12 +2559,12 @@ function readGitSubmodules(value, parentRepoRoot) {
2559
2559
  if (!Array.isArray(value)) return void 0;
2560
2560
  const submodules = value.map((entry) => {
2561
2561
  const submodule = readRecord(entry);
2562
- const path44 = readString2(submodule.path);
2562
+ const path45 = readString2(submodule.path);
2563
2563
  const commit = readString2(submodule.commit);
2564
- const repoPath = readString2(submodule.repoPath, submodule.repo_root) ?? joinRepoPath(parentRepoRoot, path44);
2565
- if (!path44 || !commit) return null;
2564
+ const repoPath = readString2(submodule.repoPath, submodule.repo_root) ?? joinRepoPath(parentRepoRoot, path45);
2565
+ if (!path45 || !commit) return null;
2566
2566
  const result = {
2567
- path: path44,
2567
+ path: path45,
2568
2568
  commit,
2569
2569
  dirty: readBoolean(submodule.dirty) ?? false,
2570
2570
  outOfSync: readBoolean(submodule.outOfSync, submodule.out_of_sync) ?? false,
@@ -2895,10 +2895,10 @@ function getMeshConfigPath() {
2895
2895
  return (0, import_path3.join)(getConfigDir(), "meshes.json");
2896
2896
  }
2897
2897
  function loadMeshConfig() {
2898
- const path44 = getMeshConfigPath();
2899
- if (!(0, import_fs3.existsSync)(path44)) return { meshes: [] };
2898
+ const path45 = getMeshConfigPath();
2899
+ if (!(0, import_fs3.existsSync)(path45)) return { meshes: [] };
2900
2900
  try {
2901
- const raw = JSON.parse((0, import_fs3.readFileSync)(path44, "utf-8"));
2901
+ const raw = JSON.parse((0, import_fs3.readFileSync)(path45, "utf-8"));
2902
2902
  if (!raw || !Array.isArray(raw.meshes)) return { meshes: [] };
2903
2903
  const config = raw;
2904
2904
  const migrated = migrateLoadedMeshConfig(config);
@@ -2947,16 +2947,16 @@ function normalizeCapabilityTags(value) {
2947
2947
  return tags.length ? tags : void 0;
2948
2948
  }
2949
2949
  function saveMeshConfig(config) {
2950
- const path44 = getMeshConfigPath();
2951
- (0, import_fs3.writeFileSync)(path44, JSON.stringify(config, null, 2), { encoding: "utf-8", mode: 384 });
2950
+ const path45 = getMeshConfigPath();
2951
+ (0, import_fs3.writeFileSync)(path45, JSON.stringify(config, null, 2), { encoding: "utf-8", mode: 384 });
2952
2952
  }
2953
2953
  function normalizeRepoIdentity(remoteUrl) {
2954
2954
  let identity = remoteUrl.trim();
2955
2955
  if (identity.startsWith("http://") || identity.startsWith("https://")) {
2956
2956
  try {
2957
2957
  const url = new URL(identity);
2958
- const path44 = url.pathname.replace(/^\//, "").replace(/\.git$/, "");
2959
- return `${url.hostname}/${path44}`;
2958
+ const path45 = url.pathname.replace(/^\//, "").replace(/\.git$/, "");
2959
+ return `${url.hostname}/${path45}`;
2960
2960
  } catch {
2961
2961
  }
2962
2962
  }
@@ -4203,59 +4203,59 @@ function isMeshEventScope(value) {
4203
4203
  function isNonEmptyString(value) {
4204
4204
  return typeof value === "string" && value.length > 0;
4205
4205
  }
4206
- function assertCoordinatorIdentity(raw, path44) {
4206
+ function assertCoordinatorIdentity(raw, path45) {
4207
4207
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
4208
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, path44, "must be an object");
4208
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, path45, "must be an object");
4209
4209
  }
4210
4210
  const obj = raw;
4211
4211
  if (!isNonEmptyString(obj.daemonId)) {
4212
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.daemonId`, "must be a non-empty string");
4212
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.daemonId`, "must be a non-empty string");
4213
4213
  }
4214
4214
  if (!isNonEmptyString(obj.coordinatorRunId)) {
4215
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.coordinatorRunId`, "must be a non-empty string");
4215
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.coordinatorRunId`, "must be a non-empty string");
4216
4216
  }
4217
4217
  const sessionId = obj.sessionId;
4218
4218
  if (sessionId !== void 0 && !isNonEmptyString(sessionId)) {
4219
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.sessionId`, "must be a non-empty string when provided");
4219
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.sessionId`, "must be a non-empty string when provided");
4220
4220
  }
4221
4221
  return sessionId !== void 0 ? { daemonId: obj.daemonId, coordinatorRunId: obj.coordinatorRunId, sessionId } : { daemonId: obj.daemonId, coordinatorRunId: obj.coordinatorRunId };
4222
4222
  }
4223
- function assertPendingMeshCoordinatorEventV2(raw, path44 = "$") {
4223
+ function assertPendingMeshCoordinatorEventV2(raw, path45 = "$") {
4224
4224
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
4225
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, path44, "must be an object");
4225
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, path45, "must be an object");
4226
4226
  }
4227
4227
  const obj = raw;
4228
4228
  if (!isSupportedMeshProtocolVersion(obj.protocolVersion)) {
4229
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.protocolVersion`, `must be one of ${SUPPORTED_MESH_PROTOCOL_VERSIONS.join(", ")}`);
4229
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.protocolVersion`, `must be one of ${SUPPORTED_MESH_PROTOCOL_VERSIONS.join(", ")}`);
4230
4230
  }
4231
4231
  if (!isNonEmptyString(obj.eventId)) {
4232
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.eventId`, "must be a non-empty string");
4232
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.eventId`, "must be a non-empty string");
4233
4233
  }
4234
4234
  if (!isMeshEventScope(obj.scope)) {
4235
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.scope`, `must be one of ${MESH_EVENT_SCOPES.join(", ")}`);
4235
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.scope`, `must be one of ${MESH_EVENT_SCOPES.join(", ")}`);
4236
4236
  }
4237
4237
  if (!isNonEmptyString(obj.event)) {
4238
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.event`, "must be a non-empty string");
4238
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.event`, "must be a non-empty string");
4239
4239
  }
4240
4240
  if (!isNonEmptyString(obj.meshId)) {
4241
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.meshId`, "must be a non-empty string");
4241
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.meshId`, "must be a non-empty string");
4242
4242
  }
4243
- const dispatchedBy = assertCoordinatorIdentity(obj.dispatchedBy, `${path44}.dispatchedBy`);
4243
+ const dispatchedBy = assertCoordinatorIdentity(obj.dispatchedBy, `${path45}.dispatchedBy`);
4244
4244
  if (obj.scope === "unicast") {
4245
4245
  if (!obj.intendedFor) {
4246
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.intendedFor`, "unicast scope requires intendedFor");
4246
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.intendedFor`, "unicast scope requires intendedFor");
4247
4247
  }
4248
4248
  } else if (obj.intendedFor !== void 0) {
4249
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.intendedFor`, "only unicast scope may set intendedFor");
4249
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.intendedFor`, "only unicast scope may set intendedFor");
4250
4250
  }
4251
- const intendedFor = obj.intendedFor ? assertCoordinatorIdentity(obj.intendedFor, `${path44}.intendedFor`) : void 0;
4251
+ const intendedFor = obj.intendedFor ? assertCoordinatorIdentity(obj.intendedFor, `${path45}.intendedFor`) : void 0;
4252
4252
  const metadata = obj.metadataEvent && typeof obj.metadataEvent === "object" && !Array.isArray(obj.metadataEvent) ? obj.metadataEvent : null;
4253
4253
  if (!metadata) {
4254
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.metadataEvent`, "must be an object");
4254
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.metadataEvent`, "must be an object");
4255
4255
  }
4256
4256
  const queuedAt = typeof obj.queuedAt === "number" && Number.isFinite(obj.queuedAt) ? obj.queuedAt : null;
4257
4257
  if (queuedAt === null) {
4258
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.queuedAt`, "must be a finite number");
4258
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.queuedAt`, "must be a finite number");
4259
4259
  }
4260
4260
  return {
4261
4261
  event: obj.event,
@@ -4418,10 +4418,10 @@ function rotateArchiveFile(meshId, archivePath) {
4418
4418
  }
4419
4419
  }
4420
4420
  function readArchivedCounts(meshId) {
4421
- const path44 = getArchivedCountsPath(meshId);
4422
- if (!(0, import_fs4.existsSync)(path44)) return { taskCompleted: 0, taskFailed: 0, taskStalled: 0, recoveryAttempted: 0, totalArchived: 0, lastArchivedAt: "" };
4421
+ const path45 = getArchivedCountsPath(meshId);
4422
+ if (!(0, import_fs4.existsSync)(path45)) return { taskCompleted: 0, taskFailed: 0, taskStalled: 0, recoveryAttempted: 0, totalArchived: 0, lastArchivedAt: "" };
4423
4423
  try {
4424
- return JSON.parse((0, import_fs4.readFileSync)(path44, "utf-8"));
4424
+ return JSON.parse((0, import_fs4.readFileSync)(path45, "utf-8"));
4425
4425
  } catch {
4426
4426
  return { taskCompleted: 0, taskFailed: 0, taskStalled: 0, recoveryAttempted: 0, totalArchived: 0, lastArchivedAt: "" };
4427
4427
  }
@@ -5643,11 +5643,11 @@ function readNodeReporter(node, key2) {
5643
5643
  function buildMeshNodeCapabilityTags(node, providerType) {
5644
5644
  const provider = typeof providerType === "string" && providerType.trim() ? providerType.trim() : firstProviderPriority(node?.policy);
5645
5645
  const worktreeBranch = typeof node?.worktreeBranch === "string" && node.worktreeBranch.trim() ? node.worktreeBranch.trim() : null;
5646
- const os31 = readNodeOverride(node, "platform") ?? readNodeReporter(node, "platform") ?? process.platform;
5646
+ const os32 = readNodeOverride(node, "platform") ?? readNodeReporter(node, "platform") ?? process.platform;
5647
5647
  const arch2 = readNodeOverride(node, "arch") ?? readNodeReporter(node, "arch") ?? process.arch;
5648
5648
  return normalizeMeshCapabilityTags([
5649
5649
  ...Array.isArray(node?.capabilities) ? node.capabilities : [],
5650
- `os=${os31}`,
5650
+ `os=${os32}`,
5651
5651
  `arch=${arch2}`,
5652
5652
  ...provider ? [`provider=${provider}`] : [],
5653
5653
  // Worktree nodes automatically expose a "worktree=<branch>" tag so that
@@ -6601,10 +6601,10 @@ var init_mesh_runtime_store = __esm({
6601
6601
  this.migratedMeshIds.add(meshId);
6602
6602
  const count = this.db.prepare("SELECT COUNT(*) AS count FROM mesh_queue WHERE mesh_id = ?").get(meshId);
6603
6603
  if (count.count > 0) return;
6604
- const path44 = legacyQueuePath(meshId);
6605
- if (!(0, import_fs5.existsSync)(path44)) return;
6604
+ const path45 = legacyQueuePath(meshId);
6605
+ if (!(0, import_fs5.existsSync)(path45)) return;
6606
6606
  try {
6607
- const entries = JSON.parse((0, import_fs5.readFileSync)(path44, "utf-8"));
6607
+ const entries = JSON.parse((0, import_fs5.readFileSync)(path45, "utf-8"));
6608
6608
  if (!Array.isArray(entries)) return;
6609
6609
  const insert = this.db.prepare(`
6610
6610
  INSERT OR REPLACE INTO mesh_queue (
@@ -8513,8 +8513,8 @@ function resolveMeshCoordinatorSetup(options) {
8513
8513
  }
8514
8514
  const serverName = mcpConfig.serverName?.trim() || DEFAULT_SERVER_NAME;
8515
8515
  if (mcpConfig.mode === "auto_import") {
8516
- const path44 = mcpConfig.path?.trim();
8517
- if (!path44) {
8516
+ const path45 = mcpConfig.path?.trim();
8517
+ if (!path45) {
8518
8518
  return { kind: "unsupported", reason: "Provider auto-import MCP config is missing a config path" };
8519
8519
  }
8520
8520
  const mcpServer = resolveAdhdevMcpServerLaunch({
@@ -8534,7 +8534,7 @@ function resolveMeshCoordinatorSetup(options) {
8534
8534
  return {
8535
8535
  kind: "auto_import",
8536
8536
  serverName,
8537
- configPath: resolveMcpConfigPath(path44, workspace),
8537
+ configPath: resolveMcpConfigPath(path45, workspace),
8538
8538
  configFormat: mcpConfig.format,
8539
8539
  mcpServer
8540
8540
  };
@@ -8735,8 +8735,8 @@ function stripCoordinatorWrapperFile(filePath) {
8735
8735
  const remaining = (existing.slice(0, openIdx) + existing.slice(closeIdx + CLOSE.length)).replace(/^\s*\n+/, "").replace(/\n+\s*$/, "");
8736
8736
  if (!remaining.trim()) {
8737
8737
  try {
8738
- const fs40 = require("fs");
8739
- fs40.unlinkSync(filePath);
8738
+ const fs41 = require("fs");
8739
+ fs41.unlinkSync(filePath);
8740
8740
  } catch {
8741
8741
  }
8742
8742
  } else {
@@ -8838,10 +8838,10 @@ function getRegistryPath() {
8838
8838
  return (0, import_path6.join)(getDaemonDataDir(), "mesh-coordinators.json");
8839
8839
  }
8840
8840
  function loadMeshCoordinatorRegistry() {
8841
- const path44 = getRegistryPath();
8842
- if (!(0, import_fs6.existsSync)(path44)) return;
8841
+ const path45 = getRegistryPath();
8842
+ if (!(0, import_fs6.existsSync)(path45)) return;
8843
8843
  try {
8844
- const raw = JSON.parse((0, import_fs6.readFileSync)(path44, "utf-8"));
8844
+ const raw = JSON.parse((0, import_fs6.readFileSync)(path45, "utf-8"));
8845
8845
  if (!Array.isArray(raw)) return;
8846
8846
  _registry.clear();
8847
8847
  for (const entry of raw) {
@@ -9012,8 +9012,8 @@ function validateMeshRefineConfig(config, source = "inline") {
9012
9012
  if (rejectedCommands.length) errors.push("one or more validation commands are invalid");
9013
9013
  return { valid: errors.length === 0, errors, bootstrapCommands, commands, rejectedCommands, bootstrapMode, deprecationWarnings };
9014
9014
  }
9015
- function parseConfigText2(path44, text) {
9016
- if (/\.json$/i.test(path44)) return JSON.parse(text);
9015
+ function parseConfigText2(path45, text) {
9016
+ if (/\.json$/i.test(path45)) return JSON.parse(text);
9017
9017
  return yaml2.load(text);
9018
9018
  }
9019
9019
  function loadMeshRefineConfig(mesh, workspace) {
@@ -9420,8 +9420,8 @@ function isCleanIgnoringSubmoduleGitlinks(porcelain, submodulePaths) {
9420
9420
  const lines = porcelain.split(/\r?\n/).filter((line) => line.length > 0);
9421
9421
  for (const line of lines) {
9422
9422
  const status = line.slice(0, 2);
9423
- const path44 = line.slice(3).trim().replace(/\\/g, "/").replace(/\/+$/, "");
9424
- const isGitlinkPointerMove = (status === " M" || status === "M ") && submodulePaths.has(path44);
9423
+ const path45 = line.slice(3).trim().replace(/\\/g, "/").replace(/\/+$/, "");
9424
+ const isGitlinkPointerMove = (status === " M" || status === "M ") && submodulePaths.has(path45);
9425
9425
  if (!isGitlinkPointerMove) return false;
9426
9426
  }
9427
9427
  return true;
@@ -9456,8 +9456,8 @@ function shouldDeferDispatchForBootstrap(node, nowMs = Date.now()) {
9456
9456
  if (node?.worktreeBootstrap?.status !== "running") return false;
9457
9457
  return !isWorktreeBootstrapStaleRunning(node, nowMs);
9458
9458
  }
9459
- function parseConfigText3(path44, text) {
9460
- if (/\.json$/i.test(path44)) return JSON.parse(text);
9459
+ function parseConfigText3(path45, text) {
9460
+ if (/\.json$/i.test(path45)) return JSON.parse(text);
9461
9461
  return yaml3.load(text);
9462
9462
  }
9463
9463
  function truncateOutput(value) {
@@ -9735,8 +9735,8 @@ __export(mesh_json_config_exports, {
9735
9735
  function isRecord3(value) {
9736
9736
  return !!value && typeof value === "object" && !Array.isArray(value);
9737
9737
  }
9738
- function parseConfigText4(path44, text) {
9739
- if (/\.json$/i.test(path44)) return JSON.parse(text);
9738
+ function parseConfigText4(path45, text) {
9739
+ if (/\.json$/i.test(path45)) return JSON.parse(text);
9740
9740
  return yaml4.load(text);
9741
9741
  }
9742
9742
  function normalizeOperatingNote(value) {
@@ -11692,10 +11692,10 @@ function readPendingMeshCoordinatorEventsFromDisk(meshId, coordinatorDaemonId) {
11692
11692
  const primaryDaemonId = daemonIds[0];
11693
11693
  const paths = primaryDaemonId ? [getPendingEventsPath(meshId, primaryDaemonId), getPendingEventsPath(meshId)] : [getPendingEventsPath(meshId)];
11694
11694
  const events = [];
11695
- for (const path44 of paths) {
11696
- if (!(0, import_fs11.existsSync)(path44)) continue;
11695
+ for (const path45 of paths) {
11696
+ if (!(0, import_fs11.existsSync)(path45)) continue;
11697
11697
  try {
11698
- const raw = (0, import_fs11.readFileSync)(path44, "utf-8");
11698
+ const raw = (0, import_fs11.readFileSync)(path45, "utf-8");
11699
11699
  const parsed = raw.split("\n").filter(Boolean).flatMap((line) => {
11700
11700
  try {
11701
11701
  return [JSON.parse(line)];
@@ -11703,7 +11703,7 @@ function readPendingMeshCoordinatorEventsFromDisk(meshId, coordinatorDaemonId) {
11703
11703
  return [];
11704
11704
  }
11705
11705
  });
11706
- const filtered = primaryDaemonId && path44 === getPendingEventsPath(meshId) ? parsed.filter((e) => !e.targetCoordinatorDaemonId || daemonIds.includes(e.targetCoordinatorDaemonId)) : parsed;
11706
+ const filtered = primaryDaemonId && path45 === getPendingEventsPath(meshId) ? parsed.filter((e) => !e.targetCoordinatorDaemonId || daemonIds.includes(e.targetCoordinatorDaemonId)) : parsed;
11707
11707
  events.push(...filtered);
11708
11708
  } catch {
11709
11709
  }
@@ -11768,11 +11768,11 @@ function reconcilePendingMeshCoordinatorEvents(meshId, events) {
11768
11768
  const reconciled = terminalJobIds.size === 0 ? events : events.filter((event) => !(event.event === "refine:accepted" && terminalJobIds.has(readRefineJobId2(event))));
11769
11769
  return backfilled.length === 0 ? reconciled : [...reconciled, ...backfilled];
11770
11770
  }
11771
- function trimPendingEventsIfNeeded(path44) {
11771
+ function trimPendingEventsIfNeeded(path45) {
11772
11772
  try {
11773
- if (!(0, import_fs11.existsSync)(path44)) return;
11774
- if ((0, import_fs11.statSync)(path44).size <= MAX_PENDING_EVENTS_BYTES) return;
11775
- const lines = (0, import_fs11.readFileSync)(path44, "utf-8").split("\n").filter(Boolean);
11773
+ if (!(0, import_fs11.existsSync)(path45)) return;
11774
+ if ((0, import_fs11.statSync)(path45).size <= MAX_PENDING_EVENTS_BYTES) return;
11775
+ const lines = (0, import_fs11.readFileSync)(path45, "utf-8").split("\n").filter(Boolean);
11776
11776
  if (lines.length <= MAX_PENDING_EVENTS_KEEP) return;
11777
11777
  const dropped = lines.slice(0, lines.length - MAX_PENDING_EVENTS_KEEP);
11778
11778
  for (const line of dropped) {
@@ -11805,7 +11805,7 @@ function trimPendingEventsIfNeeded(path44) {
11805
11805
  LOG.warn("MeshEvents", `Failed to ledger-record trim-dropped ${event.event} for mesh ${event.meshId}: ${e?.message || e}`);
11806
11806
  }
11807
11807
  }
11808
- (0, import_fs11.writeFileSync)(path44, lines.slice(-MAX_PENDING_EVENTS_KEEP).join("\n") + "\n", "utf-8");
11808
+ (0, import_fs11.writeFileSync)(path45, lines.slice(-MAX_PENDING_EVENTS_KEEP).join("\n") + "\n", "utf-8");
11809
11809
  } catch {
11810
11810
  }
11811
11811
  }
@@ -11813,18 +11813,24 @@ function stampPendingEventV2(event, hint) {
11813
11813
  if (event.protocolVersion === MESH_PROTOCOL_VERSION_V2 && readNonEmptyString2(event.eventId)) {
11814
11814
  return event;
11815
11815
  }
11816
- const dispatchedBy = hint?.dispatchedBy ?? coordinatorIdentityFromEmitFields({
11816
+ const coordinatorIdentity = hint?.dispatchedBy ?? coordinatorIdentityFromEmitFields({
11817
11817
  daemonId: event.targetCoordinatorDaemonId,
11818
11818
  coordinatorRunId: hint?.coordinatorRunId,
11819
11819
  sessionId: event.targetCoordinatorSessionId
11820
11820
  });
11821
- const intendedFor = hint?.intendedFor ?? dispatchedBy;
11821
+ const selfFallback = !coordinatorIdentity;
11822
+ const dispatchedBy = coordinatorIdentity ?? coordinatorIdentityFromEmitFields({
11823
+ daemonId: readNonEmptyString2(loadConfig().machineId)
11824
+ });
11825
+ const intendedFor = hint?.intendedFor ?? (selfFallback ? void 0 : coordinatorIdentity);
11822
11826
  const stamp = buildPendingEventEmitStamp({
11823
11827
  eventName: event.event,
11824
11828
  eventId: (0, import_crypto8.randomUUID)(),
11825
11829
  dispatchedBy,
11826
11830
  intendedFor,
11827
- scope: hint?.scope
11831
+ // Force broadcast for the self-fallback so a unicast-defaulting terminal
11832
+ // event isn't addressed to this daemon alone; an explicit hint still wins.
11833
+ scope: hint?.scope ?? (selfFallback ? "broadcast" : void 0)
11828
11834
  });
11829
11835
  if (!stamp) return event;
11830
11836
  return {
@@ -11868,6 +11874,9 @@ function readV2EnvelopeFromWire(payload) {
11868
11874
  }
11869
11875
  function queuePendingMeshCoordinatorEvent(rawEvent, hint) {
11870
11876
  const event = stampPendingEventV2(rawEvent, hint);
11877
+ return persistPendingMeshCoordinatorEvent(event);
11878
+ }
11879
+ function persistPendingMeshCoordinatorEvent(event) {
11871
11880
  try {
11872
11881
  if (hasPendingRefineTerminalEventDuplicate(event)) {
11873
11882
  LOG.info("MeshEvents", `Suppressed duplicate pending ${event.event} for refine job ${readRefineJobId2(event)}`);
@@ -11902,9 +11911,9 @@ function queuePendingMeshCoordinatorEvent(rawEvent, hint) {
11902
11911
  } catch {
11903
11912
  }
11904
11913
  try {
11905
- const path44 = getPendingEventsPath(event.meshId, event.targetCoordinatorDaemonId);
11906
- trimPendingEventsIfNeeded(path44);
11907
- (0, import_fs11.appendFileSync)(path44, JSON.stringify(event) + "\n", "utf-8");
11914
+ const path45 = getPendingEventsPath(event.meshId, event.targetCoordinatorDaemonId);
11915
+ trimPendingEventsIfNeeded(path45);
11916
+ (0, import_fs11.appendFileSync)(path45, JSON.stringify(event) + "\n", "utf-8");
11908
11917
  } catch (e) {
11909
11918
  if (!sqliteOk) throw e;
11910
11919
  LOG.warn("MeshEvents", `JSONL append failed for mesh ${event.meshId}; SQLite holds the event: ${e?.message || e}`);
@@ -11915,10 +11924,10 @@ function queuePendingMeshCoordinatorEvent(rawEvent, hint) {
11915
11924
  return false;
11916
11925
  }
11917
11926
  }
11918
- function atomicDrainFile(path44) {
11919
- const tmpPath = `${path44}.draining`;
11927
+ function atomicDrainFile(path45) {
11928
+ const tmpPath = `${path45}.draining`;
11920
11929
  try {
11921
- (0, import_fs11.renameSync)(path44, tmpPath);
11930
+ (0, import_fs11.renameSync)(path45, tmpPath);
11922
11931
  } catch {
11923
11932
  return null;
11924
11933
  }
@@ -11937,10 +11946,10 @@ function atomicDrainFile(path44) {
11937
11946
  return null;
11938
11947
  }
11939
11948
  }
11940
- function selectiveDrainFile(path44, predicate) {
11941
- const tmpPath = `${path44}.draining`;
11949
+ function selectiveDrainFile(path45, predicate) {
11950
+ const tmpPath = `${path45}.draining`;
11942
11951
  try {
11943
- (0, import_fs11.renameSync)(path44, tmpPath);
11952
+ (0, import_fs11.renameSync)(path45, tmpPath);
11944
11953
  } catch {
11945
11954
  return [];
11946
11955
  }
@@ -11972,12 +11981,12 @@ function selectiveDrainFile(path44, predicate) {
11972
11981
  }
11973
11982
  try {
11974
11983
  if (keptLines.length > 0) {
11975
- (0, import_fs11.writeFileSync)(path44, keptLines.join("\n") + "\n", "utf-8");
11984
+ (0, import_fs11.writeFileSync)(path45, keptLines.join("\n") + "\n", "utf-8");
11976
11985
  }
11977
11986
  (0, import_fs11.unlinkSync)(tmpPath);
11978
11987
  } catch {
11979
11988
  try {
11980
- if ((0, import_fs11.existsSync)(tmpPath) && !(0, import_fs11.existsSync)(path44)) (0, import_fs11.renameSync)(tmpPath, path44);
11989
+ if ((0, import_fs11.existsSync)(tmpPath) && !(0, import_fs11.existsSync)(path45)) (0, import_fs11.renameSync)(tmpPath, path45);
11981
11990
  } catch {
11982
11991
  }
11983
11992
  return [];
@@ -12018,16 +12027,16 @@ function drainPendingMeshCoordinatorEvents(meshId, coordinatorDaemonId, opts) {
12018
12027
  LOG.warn("MeshEvents", `SQLite pending-event drain failed for mesh ${meshId}; JSONL fallback only: ${e?.message || e}`);
12019
12028
  }
12020
12029
  const paths = primaryDaemonId ? [getPendingEventsPath(meshId, primaryDaemonId), getPendingEventsPath(meshId)] : [getPendingEventsPath(meshId)];
12021
- for (const path44 of paths) {
12022
- const isSharedFile = !!primaryDaemonId && path44 === getPendingEventsPath(meshId);
12030
+ for (const path45 of paths) {
12031
+ const isSharedFile = !!primaryDaemonId && path45 === getPendingEventsPath(meshId);
12023
12032
  const targets = (e) => !isSharedFile || !e.targetCoordinatorDaemonId || daemonIds.includes(e.targetCoordinatorDaemonId);
12024
12033
  if (onlyEvents) {
12025
- for (const event of selectiveDrainFile(path44, (e) => targets(e) && matchesFilter(e.event))) {
12034
+ for (const event of selectiveDrainFile(path45, (e) => targets(e) && matchesFilter(e.event))) {
12026
12035
  pushUnique(event);
12027
12036
  }
12028
12037
  continue;
12029
12038
  }
12030
- const content = atomicDrainFile(path44);
12039
+ const content = atomicDrainFile(path45);
12031
12040
  if (!content) continue;
12032
12041
  const parsed = content.split("\n").filter(Boolean).flatMap((line) => {
12033
12042
  try {
@@ -12068,9 +12077,9 @@ function retractPendingDispatchBlockedEvent(meshId, taskId, coordinatorDaemonId)
12068
12077
  const daemonIds = normalizeCoordinatorDaemonIds(coordinatorDaemonId);
12069
12078
  const primaryDaemonId = daemonIds[0];
12070
12079
  const paths = primaryDaemonId ? [getPendingEventsPath(meshId, primaryDaemonId), getPendingEventsPath(meshId)] : [getPendingEventsPath(meshId)];
12071
- for (const path44 of paths) {
12080
+ for (const path45 of paths) {
12072
12081
  try {
12073
- removed += selectiveDrainFile(path44, matchesTask).length;
12082
+ removed += selectiveDrainFile(path45, matchesTask).length;
12074
12083
  } catch {
12075
12084
  }
12076
12085
  }
@@ -12122,9 +12131,9 @@ function clearPendingMeshCoordinatorEvents(meshId, coordinatorDaemonId) {
12122
12131
  } catch {
12123
12132
  }
12124
12133
  const paths = coordinatorDaemonId ? [getPendingEventsPath(meshId, coordinatorDaemonId), getPendingEventsPath(meshId)] : [getPendingEventsPath(meshId)];
12125
- for (const path44 of paths) {
12126
- if ((0, import_fs11.existsSync)(path44)) try {
12127
- (0, import_fs11.unlinkSync)(path44);
12134
+ for (const path45 of paths) {
12135
+ if ((0, import_fs11.existsSync)(path45)) try {
12136
+ (0, import_fs11.unlinkSync)(path45);
12128
12137
  } catch {
12129
12138
  }
12130
12139
  }
@@ -12137,6 +12146,7 @@ var init_mesh_events_pending = __esm({
12137
12146
  import_path10 = require("path");
12138
12147
  import_crypto8 = require("crypto");
12139
12148
  init_logger();
12149
+ init_config();
12140
12150
  init_mesh_ledger();
12141
12151
  init_mesh_runtime_store();
12142
12152
  init_mesh_events_utils();
@@ -12804,9 +12814,9 @@ function findBinary(name) {
12804
12814
  for (const ext of exes) {
12805
12815
  const fullPath = path11.join(p, trimmed + ext);
12806
12816
  try {
12807
- const fs40 = require("fs");
12808
- if (fs40.existsSync(fullPath)) {
12809
- const stat2 = fs40.statSync(fullPath);
12817
+ const fs41 = require("fs");
12818
+ if (fs41.existsSync(fullPath)) {
12819
+ const stat2 = fs41.statSync(fullPath);
12810
12820
  if (stat2.isFile() && (isWin || stat2.mode & 73)) {
12811
12821
  return fullPath;
12812
12822
  }
@@ -12820,12 +12830,12 @@ function findBinary(name) {
12820
12830
  function isScriptBinary(binaryPath) {
12821
12831
  if (!path11.isAbsolute(binaryPath)) return false;
12822
12832
  try {
12823
- const fs40 = require("fs");
12824
- const resolved = fs40.realpathSync(binaryPath);
12833
+ const fs41 = require("fs");
12834
+ const resolved = fs41.realpathSync(binaryPath);
12825
12835
  const head = Buffer.alloc(8);
12826
- const fd = fs40.openSync(resolved, "r");
12827
- fs40.readSync(fd, head, 0, 8, 0);
12828
- fs40.closeSync(fd);
12836
+ const fd = fs41.openSync(resolved, "r");
12837
+ fs41.readSync(fd, head, 0, 8, 0);
12838
+ fs41.closeSync(fd);
12829
12839
  let i = 0;
12830
12840
  if (head[0] === 239 && head[1] === 187 && head[2] === 191) i = 3;
12831
12841
  return head[i] === 35 && head[i + 1] === 33;
@@ -12836,12 +12846,12 @@ function isScriptBinary(binaryPath) {
12836
12846
  function looksLikeMachOOrElf(filePath) {
12837
12847
  if (!path11.isAbsolute(filePath)) return false;
12838
12848
  try {
12839
- const fs40 = require("fs");
12840
- const resolved = fs40.realpathSync(filePath);
12849
+ const fs41 = require("fs");
12850
+ const resolved = fs41.realpathSync(filePath);
12841
12851
  const buf = Buffer.alloc(8);
12842
- const fd = fs40.openSync(resolved, "r");
12843
- fs40.readSync(fd, buf, 0, 8, 0);
12844
- fs40.closeSync(fd);
12852
+ const fd = fs41.openSync(resolved, "r");
12853
+ fs41.readSync(fd, buf, 0, 8, 0);
12854
+ fs41.closeSync(fd);
12845
12855
  let i = 0;
12846
12856
  if (buf[0] === 239 && buf[1] === 187 && buf[2] === 191) i = 3;
12847
12857
  const b = buf.subarray(i);
@@ -18336,40 +18346,48 @@ var init_mesh_events_coordinator = __esm({
18336
18346
  }
18337
18347
  });
18338
18348
 
18339
- // src/mesh/mesh-reconcile-loop.ts
18340
- function resolveAutoPruneMinAgeMs() {
18341
- const raw = readNonEmptyString2(process.env.MESH_AUTO_PRUNE_MIN_AGE_MS);
18342
- if (raw) {
18343
- const parsed = Number.parseInt(raw, 10);
18344
- if (Number.isFinite(parsed) && parsed >= 60 * 6e4 && parsed <= 30 * 24 * 60 * 6e4) return parsed;
18345
- }
18346
- return DEFAULT_AUTO_PRUNE_MIN_AGE_MS;
18349
+ // src/mesh/mesh-reconcile-identity.ts
18350
+ function resolveCoordinatorDaemonIds(components) {
18351
+ const statusInstanceId = readNonEmptyString2(components.statusInstanceId);
18352
+ const machineId = readNonEmptyString2(loadConfig().machineId);
18353
+ return expandDaemonIdForms([statusInstanceId, machineId]);
18347
18354
  }
18348
- function resolvePendingHeldDrainEscalateMs() {
18349
- return resolveTunedReconcileMs("MESH_PENDING_HELD_DRAIN_ESCALATE_MS", DEFAULT_PENDING_HELD_DRAIN_ESCALATE_MS, 4e3, 5 * 6e4);
18355
+ function daemonHostsMesh(mesh, daemonIds) {
18356
+ const host = mesh.meshHost;
18357
+ if (!host) return true;
18358
+ if (host.role && host.role !== "host") return false;
18359
+ const hostDaemonId = readNonEmptyString2(host.hostDaemonId);
18360
+ if (!hostDaemonId) return true;
18361
+ return daemonIdListIncludes(daemonIds, hostDaemonId);
18350
18362
  }
18351
- function resolveReconcileIntervalMs() {
18352
- const raw = readNonEmptyString2(process.env.MESH_RECONCILE_INTERVAL_MS);
18353
- if (raw) {
18354
- const parsed = Number.parseInt(raw, 10);
18355
- if (Number.isFinite(parsed) && parsed >= 1e3 && parsed <= 6e4) return parsed;
18356
- }
18357
- return DEFAULT_RECONCILE_INTERVAL_MS;
18363
+ function daemonIdListIncludes(ids, id) {
18364
+ if (!id) return false;
18365
+ return ids.some((candidate) => candidate === id || daemonIdsEquivalent(candidate, id));
18358
18366
  }
18359
- function resolveTunedReconcileMs(envName, def, min, max) {
18360
- const raw = readNonEmptyString2(process.env[envName]);
18361
- if (raw) {
18362
- const parsed = Number.parseInt(raw, 10);
18363
- if (Number.isFinite(parsed) && parsed >= min && parsed <= max) return parsed;
18367
+ function resolveCoordinatorSelfIds(mesh, drainDaemonIds) {
18368
+ const ids = new Set(drainDaemonIds);
18369
+ for (const node of mesh.nodes) {
18370
+ const nodeDaemonId = readNonEmptyString2(node.daemonId);
18371
+ const nodeMachineId = readNonEmptyString2(node.machineId);
18372
+ const isSelf = nodeDaemonId && daemonIdListIncludes(drainDaemonIds, nodeDaemonId) || nodeMachineId && daemonIdListIncludes(drainDaemonIds, nodeMachineId);
18373
+ if (!isSelf) continue;
18374
+ if (nodeDaemonId) ids.add(nodeDaemonId);
18375
+ if (nodeMachineId) ids.add(nodeMachineId);
18364
18376
  }
18365
- return def;
18366
- }
18367
- function resolveAckedDeathDeadlineMs() {
18368
- return resolveTunedReconcileMs("MESH_INFLIGHT_ACKED_DEATH_DEADLINE_MS", 8 * 6e4, 0, 60 * 6e4);
18369
- }
18370
- function resolveAckedTranscriptFastTrackGraceMs() {
18371
- return resolveTunedReconcileMs("MESH_INFLIGHT_ACKED_TRANSCRIPT_FASTTRACK_GRACE_MS", 4e4, 0, 5 * 6e4);
18377
+ const hostDaemonId = readNonEmptyString2(mesh.meshHost?.hostDaemonId);
18378
+ if (hostDaemonId && daemonIdListIncludes([...ids], hostDaemonId)) ids.add(hostDaemonId);
18379
+ return [...ids];
18372
18380
  }
18381
+ var init_mesh_reconcile_identity = __esm({
18382
+ "src/mesh/mesh-reconcile-identity.ts"() {
18383
+ "use strict";
18384
+ init_config();
18385
+ init_dist();
18386
+ init_mesh_events_utils();
18387
+ }
18388
+ });
18389
+
18390
+ // src/mesh/mesh-reconcile-v2-backstop.ts
18373
18391
  function getMeshV2BackstopCounters() {
18374
18392
  return { ...meshV2BackstopCounters };
18375
18393
  }
@@ -18385,6 +18403,37 @@ function recordBackstopFire(kind, detail) {
18385
18403
  LOG.warn("MeshReconcileV2", `v2 ENFORCE last-resort backstop fired (${kind}): ${detail}. Under a healthy v2 completion contract this should be 0 \u2014 a worker's real terminal emit was lost/late.`);
18386
18404
  }
18387
18405
  }
18406
+ var meshV2BackstopCounters;
18407
+ var init_mesh_reconcile_v2_backstop = __esm({
18408
+ "src/mesh/mesh-reconcile-v2-backstop.ts"() {
18409
+ "use strict";
18410
+ init_logger();
18411
+ meshV2BackstopCounters = {
18412
+ /** PHASE-4 transcript synthesis actually reconciled a missing completion. */
18413
+ phase4SynthesisFired: 0,
18414
+ /** Acked-hold transcript fast-track promoted a synth ahead of the death deadline. */
18415
+ ackedHoldFastTrackFired: 0,
18416
+ /** Acked-hold death-deadline backstop released a held synth (the 8-min net). */
18417
+ ackedHoldDeathDeadlineFired: 0
18418
+ };
18419
+ }
18420
+ });
18421
+
18422
+ // src/mesh/mesh-reconcile-acked-hold.ts
18423
+ function resolveTunedReconcileMs(envName, def, min, max) {
18424
+ const raw = readNonEmptyString2(process.env[envName]);
18425
+ if (raw) {
18426
+ const parsed = Number.parseInt(raw, 10);
18427
+ if (Number.isFinite(parsed) && parsed >= min && parsed <= max) return parsed;
18428
+ }
18429
+ return def;
18430
+ }
18431
+ function resolveAckedDeathDeadlineMs() {
18432
+ return resolveTunedReconcileMs("MESH_INFLIGHT_ACKED_DEATH_DEADLINE_MS", 8 * 6e4, 0, 60 * 6e4);
18433
+ }
18434
+ function resolveAckedTranscriptFastTrackGraceMs() {
18435
+ return resolveTunedReconcileMs("MESH_INFLIGHT_ACKED_TRANSCRIPT_FASTTRACK_GRACE_MS", 4e4, 0, 5 * 6e4);
18436
+ }
18388
18437
  function inFlightSynthKey(meshId, taskId) {
18389
18438
  return `${meshId}::${taskId}`;
18390
18439
  }
@@ -18467,36 +18516,54 @@ function rehydrateAckedHoldsForMesh(meshId) {
18467
18516
  LOG.info("MeshReconcile", `Rehydrated ${rows.length} persisted acked-hold row(s) for mesh ${meshId} after (re)start`);
18468
18517
  }
18469
18518
  }
18470
- function resolveCoordinatorDaemonIds(components) {
18471
- const statusInstanceId = readNonEmptyString2(components.statusInstanceId);
18472
- const machineId = readNonEmptyString2(loadConfig().machineId);
18473
- return expandDaemonIdForms([statusInstanceId, machineId]);
18519
+ function collectHeldSynthKeysForMesh(meshId) {
18520
+ const heldKeys = /* @__PURE__ */ new Set();
18521
+ for (const key2 of inFlightAckedHoldState.keys()) {
18522
+ if (key2.startsWith(`${meshId}::`)) heldKeys.add(key2);
18523
+ }
18524
+ const store = holdStore();
18525
+ if (store) {
18526
+ try {
18527
+ for (const row of store.listInflightHoldsByMesh(meshId)) {
18528
+ heldKeys.add(inFlightSynthKey(meshId, row.taskId));
18529
+ }
18530
+ } catch {
18531
+ }
18532
+ }
18533
+ return heldKeys;
18474
18534
  }
18475
- function daemonHostsMesh(mesh, daemonIds) {
18476
- const host = mesh.meshHost;
18477
- if (!host) return true;
18478
- if (host.role && host.role !== "host") return false;
18479
- const hostDaemonId = readNonEmptyString2(host.hostDaemonId);
18480
- if (!hostDaemonId) return true;
18481
- return daemonIdListIncludes(daemonIds, hostDaemonId);
18535
+ var ACKED_DEATH_CONSECUTIVE_READ_FAILURES, inFlightAckedHoldState, rehydratedHoldMeshes;
18536
+ var init_mesh_reconcile_acked_hold = __esm({
18537
+ "src/mesh/mesh-reconcile-acked-hold.ts"() {
18538
+ "use strict";
18539
+ init_logger();
18540
+ init_mesh_runtime_store();
18541
+ init_mesh_events_utils();
18542
+ ACKED_DEATH_CONSECUTIVE_READ_FAILURES = 3;
18543
+ inFlightAckedHoldState = /* @__PURE__ */ new Map();
18544
+ rehydratedHoldMeshes = /* @__PURE__ */ new Set();
18545
+ }
18546
+ });
18547
+
18548
+ // src/mesh/mesh-reconcile-loop.ts
18549
+ function resolveAutoPruneMinAgeMs() {
18550
+ const raw = readNonEmptyString2(process.env.MESH_AUTO_PRUNE_MIN_AGE_MS);
18551
+ if (raw) {
18552
+ const parsed = Number.parseInt(raw, 10);
18553
+ if (Number.isFinite(parsed) && parsed >= 60 * 6e4 && parsed <= 30 * 24 * 60 * 6e4) return parsed;
18554
+ }
18555
+ return DEFAULT_AUTO_PRUNE_MIN_AGE_MS;
18482
18556
  }
18483
- function daemonIdListIncludes(ids, id) {
18484
- if (!id) return false;
18485
- return ids.some((candidate) => candidate === id || daemonIdsEquivalent(candidate, id));
18557
+ function resolvePendingHeldDrainEscalateMs() {
18558
+ return resolveTunedReconcileMs("MESH_PENDING_HELD_DRAIN_ESCALATE_MS", DEFAULT_PENDING_HELD_DRAIN_ESCALATE_MS, 4e3, 5 * 6e4);
18486
18559
  }
18487
- function resolveCoordinatorSelfIds(mesh, drainDaemonIds) {
18488
- const ids = new Set(drainDaemonIds);
18489
- for (const node of mesh.nodes) {
18490
- const nodeDaemonId = readNonEmptyString2(node.daemonId);
18491
- const nodeMachineId = readNonEmptyString2(node.machineId);
18492
- const isSelf = nodeDaemonId && daemonIdListIncludes(drainDaemonIds, nodeDaemonId) || nodeMachineId && daemonIdListIncludes(drainDaemonIds, nodeMachineId);
18493
- if (!isSelf) continue;
18494
- if (nodeDaemonId) ids.add(nodeDaemonId);
18495
- if (nodeMachineId) ids.add(nodeMachineId);
18560
+ function resolveReconcileIntervalMs() {
18561
+ const raw = readNonEmptyString2(process.env.MESH_RECONCILE_INTERVAL_MS);
18562
+ if (raw) {
18563
+ const parsed = Number.parseInt(raw, 10);
18564
+ if (Number.isFinite(parsed) && parsed >= 1e3 && parsed <= 6e4) return parsed;
18496
18565
  }
18497
- const hostDaemonId = readNonEmptyString2(mesh.meshHost?.hostDaemonId);
18498
- if (hostDaemonId && daemonIdListIncludes([...ids], hostDaemonId)) ids.add(hostDaemonId);
18499
- return [...ids];
18566
+ return DEFAULT_RECONCILE_INTERVAL_MS;
18500
18567
  }
18501
18568
  function findLiveCoordinators(components) {
18502
18569
  const out = [];
@@ -19262,19 +19329,7 @@ async function reconcileUnterminatedDirectDispatches(components, mesh, selfIds,
19262
19329
  const activeTaskKeys = new Set(
19263
19330
  dispatches.map((d) => readNonEmptyString2(d.taskId)).filter(Boolean).map((taskId) => inFlightSynthKey(mesh.id, taskId))
19264
19331
  );
19265
- const heldKeys = /* @__PURE__ */ new Set();
19266
- for (const key2 of inFlightAckedHoldState.keys()) {
19267
- if (key2.startsWith(`${mesh.id}::`)) heldKeys.add(key2);
19268
- }
19269
- const store = holdStore();
19270
- if (store) {
19271
- try {
19272
- for (const row of store.listInflightHoldsByMesh(mesh.id)) {
19273
- heldKeys.add(inFlightSynthKey(mesh.id, row.taskId));
19274
- }
19275
- } catch {
19276
- }
19277
- }
19332
+ const heldKeys = collectHeldSynthKeysForMesh(mesh.id);
19278
19333
  for (const key2 of heldKeys) {
19279
19334
  if (!activeTaskKeys.has(key2)) deleteHoldState(key2, mesh.id);
19280
19335
  }
@@ -19550,7 +19605,7 @@ function setupMeshReconcileLoop(components) {
19550
19605
  }
19551
19606
  };
19552
19607
  }
19553
- var DEFAULT_RECONCILE_INTERVAL_MS, DEFAULT_AUTO_PRUNE_MIN_AGE_MS, DEFAULT_PENDING_HELD_DRAIN_ESCALATE_MS, ACKED_DEATH_CONSECUTIVE_READ_FAILURES, inFlightAckedHoldState, rehydratedHoldMeshes, meshV2BackstopCounters, coordinatorModalParkState, heldEventLedgerRecorded, ASSIGNED_STRANDED_DEADLINE_MS, DELIVERED_NO_TURN_DEADLINE_MS, RECLAIM_UNKNOWN_GRACE_TICKS, deliveredNoTurnUnknownStreak, STRICT_SESSION_MATCH_TTL_MS, unresolvedForwardRejectionCounts, MAX_FORWARD_REJECTIONS;
19608
+ var DEFAULT_RECONCILE_INTERVAL_MS, DEFAULT_AUTO_PRUNE_MIN_AGE_MS, DEFAULT_PENDING_HELD_DRAIN_ESCALATE_MS, coordinatorModalParkState, heldEventLedgerRecorded, ASSIGNED_STRANDED_DEADLINE_MS, DELIVERED_NO_TURN_DEADLINE_MS, RECLAIM_UNKNOWN_GRACE_TICKS, deliveredNoTurnUnknownStreak, STRICT_SESSION_MATCH_TTL_MS, unresolvedForwardRejectionCounts, MAX_FORWARD_REJECTIONS;
19554
19609
  var init_mesh_reconcile_loop = __esm({
19555
19610
  "src/mesh/mesh-reconcile-loop.ts"() {
19556
19611
  "use strict";
@@ -19572,20 +19627,14 @@ var init_mesh_reconcile_loop = __esm({
19572
19627
  init_mesh_active_work();
19573
19628
  init_mesh_events_stale();
19574
19629
  init_chat_message_normalization();
19630
+ init_mesh_reconcile_identity();
19631
+ init_mesh_reconcile_v2_backstop();
19632
+ init_mesh_reconcile_acked_hold();
19633
+ init_mesh_reconcile_v2_backstop();
19634
+ init_mesh_reconcile_acked_hold();
19575
19635
  DEFAULT_RECONCILE_INTERVAL_MS = 4e3;
19576
19636
  DEFAULT_AUTO_PRUNE_MIN_AGE_MS = 24 * 60 * 6e4;
19577
19637
  DEFAULT_PENDING_HELD_DRAIN_ESCALATE_MS = 12e3;
19578
- ACKED_DEATH_CONSECUTIVE_READ_FAILURES = 3;
19579
- inFlightAckedHoldState = /* @__PURE__ */ new Map();
19580
- rehydratedHoldMeshes = /* @__PURE__ */ new Set();
19581
- meshV2BackstopCounters = {
19582
- /** PHASE-4 transcript synthesis actually reconciled a missing completion. */
19583
- phase4SynthesisFired: 0,
19584
- /** Acked-hold transcript fast-track promoted a synth ahead of the death deadline. */
19585
- ackedHoldFastTrackFired: 0,
19586
- /** Acked-hold death-deadline backstop released a held synth (the 8-min net). */
19587
- ackedHoldDeathDeadlineFired: 0
19588
- };
19589
19638
  coordinatorModalParkState = /* @__PURE__ */ new Map();
19590
19639
  heldEventLedgerRecorded = /* @__PURE__ */ new Set();
19591
19640
  ASSIGNED_STRANDED_DEADLINE_MS = 5 * 6e4;
@@ -20280,7 +20329,7 @@ function getCliValidator() {
20280
20329
  return _cliValidator;
20281
20330
  }
20282
20331
  function formatIssue(err) {
20283
- const path44 = err.instancePath || "";
20332
+ const path45 = err.instancePath || "";
20284
20333
  const params = err.params;
20285
20334
  let message = err.message || "validation failed";
20286
20335
  let allowed;
@@ -20298,7 +20347,7 @@ function formatIssue(err) {
20298
20347
  } else if (err.keyword === "type") {
20299
20348
  message = `must be ${params.type}`;
20300
20349
  }
20301
- return { path: path44, keyword: err.keyword, message, ...allowed !== void 0 ? { allowed } : {} };
20350
+ return { path: path45, keyword: err.keyword, message, ...allowed !== void 0 ? { allowed } : {} };
20302
20351
  }
20303
20352
  function validateCliProviderManifest(manifest) {
20304
20353
  const validator = getCliValidator();
@@ -20594,49 +20643,49 @@ function validateFsmSpec(raw) {
20594
20643
  }
20595
20644
  return errs;
20596
20645
  }
20597
- function validateCondition(c, sectionIds, path44) {
20646
+ function validateCondition(c, sectionIds, path45) {
20598
20647
  const errs = [];
20599
20648
  const w = c;
20600
20649
  if ("all" in w) {
20601
- w.all.forEach((x, i) => errs.push(...validateCondition(x, sectionIds, `${path44}.all[${i}]`)));
20650
+ w.all.forEach((x, i) => errs.push(...validateCondition(x, sectionIds, `${path45}.all[${i}]`)));
20602
20651
  return errs;
20603
20652
  }
20604
20653
  if ("any" in w) {
20605
- w.any.forEach((x, i) => errs.push(...validateCondition(x, sectionIds, `${path44}.any[${i}]`)));
20654
+ w.any.forEach((x, i) => errs.push(...validateCondition(x, sectionIds, `${path45}.any[${i}]`)));
20606
20655
  return errs;
20607
20656
  }
20608
20657
  if ("not" in w) {
20609
- errs.push(...validateCondition(w.not, sectionIds, `${path44}.not`));
20658
+ errs.push(...validateCondition(w.not, sectionIds, `${path45}.not`));
20610
20659
  return errs;
20611
20660
  }
20612
20661
  if ("matches" in w) {
20613
- if (w.section && !sectionIds.has(w.section)) errs.push(`${path44}.section "${w.section}" unknown`);
20662
+ if (w.section && !sectionIds.has(w.section)) errs.push(`${path45}.section "${w.section}" unknown`);
20614
20663
  try {
20615
20664
  new RegExp(w.matches, w.flags ?? "i");
20616
20665
  } catch (e) {
20617
- errs.push(`${path44}.matches invalid regex: ${e.message}`);
20666
+ errs.push(`${path45}.matches invalid regex: ${e.message}`);
20618
20667
  }
20619
20668
  return errs;
20620
20669
  }
20621
20670
  if ("cursor_above" in w && "changed" in w) return errs;
20622
20671
  if ("elapsed_ms" in w) {
20623
- if (typeof w.elapsed_ms !== "number") errs.push(`${path44}.elapsed_ms must be a number`);
20672
+ if (typeof w.elapsed_ms !== "number") errs.push(`${path45}.elapsed_ms must be a number`);
20624
20673
  return errs;
20625
20674
  }
20626
20675
  if ("stable_ms" in w) {
20627
- if (typeof w.stable_ms !== "number") errs.push(`${path44}.stable_ms must be a number`);
20628
- if (w.section && !sectionIds.has(w.section)) errs.push(`${path44}.section "${w.section}" unknown`);
20676
+ if (typeof w.stable_ms !== "number") errs.push(`${path45}.stable_ms must be a number`);
20677
+ if (w.section && !sectionIds.has(w.section)) errs.push(`${path45}.section "${w.section}" unknown`);
20629
20678
  if (w.ignore_lines !== void 0) {
20630
- if (typeof w.ignore_lines !== "string") errs.push(`${path44}.ignore_lines must be a string`);
20679
+ if (typeof w.ignore_lines !== "string") errs.push(`${path45}.ignore_lines must be a string`);
20631
20680
  else try {
20632
20681
  new RegExp(w.ignore_lines, "m");
20633
20682
  } catch (e) {
20634
- errs.push(`${path44}.ignore_lines invalid regex: ${e.message}`);
20683
+ errs.push(`${path45}.ignore_lines invalid regex: ${e.message}`);
20635
20684
  }
20636
20685
  }
20637
20686
  return errs;
20638
20687
  }
20639
- errs.push(`${path44} is not a recognized condition`);
20688
+ errs.push(`${path45} is not a recognized condition`);
20640
20689
  return errs;
20641
20690
  }
20642
20691
  var fs10;
@@ -21135,8 +21184,8 @@ var init_pty_transport = __esm({
21135
21184
  let cwd = options.cwd;
21136
21185
  if (cwd) {
21137
21186
  try {
21138
- const fs40 = require("fs");
21139
- const stat2 = fs40.statSync(cwd);
21187
+ const fs41 = require("fs");
21188
+ const stat2 = fs41.statSync(cwd);
21140
21189
  if (!stat2.isDirectory()) cwd = os14.homedir();
21141
21190
  } catch {
21142
21191
  cwd = os14.homedir();
@@ -25069,7 +25118,7 @@ function _getRegisteredRoots() {
25069
25118
  }
25070
25119
  function canonicalize(p) {
25071
25120
  try {
25072
- const resolved = path34.resolve(p);
25121
+ const resolved = path35.resolve(p);
25073
25122
  try {
25074
25123
  return nodeFs.realpathSync.native ? nodeFs.realpathSync.native(resolved) : nodeFs.realpathSync(resolved);
25075
25124
  } catch {
@@ -25089,7 +25138,7 @@ function isCallerInsideGatedRoot(callerFilename) {
25089
25138
  }
25090
25139
  for (const root of _gatedRoots) {
25091
25140
  if (normalized === root.rootPath) return root;
25092
- if (normalized.startsWith(root.rootPath + path34.sep)) return root;
25141
+ if (normalized.startsWith(root.rootPath + path35.sep)) return root;
25093
25142
  }
25094
25143
  return null;
25095
25144
  }
@@ -25108,16 +25157,16 @@ function ensureInstalled() {
25108
25157
  };
25109
25158
  }
25110
25159
  function gatedRequire(request, parent, isMain, gated, originalLoad) {
25111
- if (request.startsWith("./") || request.startsWith("../") || path34.isAbsolute(request)) {
25160
+ if (request.startsWith("./") || request.startsWith("../") || path35.isAbsolute(request)) {
25112
25161
  let resolved;
25113
25162
  try {
25114
- const callerRequire = parent?.filename ? (0, import_node_module2.createRequire)(parent.filename) : (0, import_node_module2.createRequire)(path34.join(gated.rootPath, "__entry__.js"));
25163
+ const callerRequire = parent?.filename ? (0, import_node_module2.createRequire)(parent.filename) : (0, import_node_module2.createRequire)(path35.join(gated.rootPath, "__entry__.js"));
25115
25164
  resolved = callerRequire.resolve(request);
25116
25165
  } catch {
25117
25166
  return originalLoad.call(this, request, parent, isMain);
25118
25167
  }
25119
25168
  const resolvedCanon = canonicalize(resolved) || resolved;
25120
- if (!(resolvedCanon === gated.rootPath || resolvedCanon.startsWith(gated.rootPath + path34.sep))) {
25169
+ if (!(resolvedCanon === gated.rootPath || resolvedCanon.startsWith(gated.rootPath + path35.sep))) {
25121
25170
  denyRequire(request, parent, `relative path escapes provider root (resolved to ${resolvedCanon})`);
25122
25171
  }
25123
25172
  return originalLoad.call(this, request, parent, isMain);
@@ -25141,11 +25190,11 @@ function denyRequire(request, parent, reason) {
25141
25190
  err.callerFilename = caller;
25142
25191
  throw err;
25143
25192
  }
25144
- var path34, import_node_module2, nodeFs, nodeChildProcess, SAFE_STDLIB, SHIMMED_STDLIB, ALL_GATED_STDLIB, FS_READ_ONLY_MEMBERS, FS_PROMISES_READ_ONLY_MEMBERS, FS_SHIM, CHILD_PROCESS_SHIM, DANGEROUS_PROCESS_METHODS, _processGloballyHardened, _originalProcessMethods, PROCESS_SHIM, _gatedRoots, _installed, PROVIDER_REQUIRE_POLICY;
25193
+ var path35, import_node_module2, nodeFs, nodeChildProcess, SAFE_STDLIB, SHIMMED_STDLIB, ALL_GATED_STDLIB, FS_READ_ONLY_MEMBERS, FS_PROMISES_READ_ONLY_MEMBERS, FS_SHIM, CHILD_PROCESS_SHIM, DANGEROUS_PROCESS_METHODS, _processGloballyHardened, _originalProcessMethods, PROCESS_SHIM, _gatedRoots, _installed, PROVIDER_REQUIRE_POLICY;
25145
25194
  var init_require_whitelist = __esm({
25146
25195
  "src/providers/sdk/v1/sandbox/require-whitelist.ts"() {
25147
25196
  "use strict";
25148
- path34 = __toESM(require("path"));
25197
+ path35 = __toESM(require("path"));
25149
25198
  import_node_module2 = require("module");
25150
25199
  nodeFs = __toESM(require("fs"));
25151
25200
  nodeChildProcess = __toESM(require("child_process"));
@@ -27249,17 +27298,17 @@ function checkPathExists(paths) {
27249
27298
  return null;
27250
27299
  }
27251
27300
  async function detectIDEs(providerLoader) {
27252
- const os31 = (0, import_os2.platform)();
27301
+ const os32 = (0, import_os2.platform)();
27253
27302
  const results = [];
27254
27303
  for (const def of getMergedDefinitions()) {
27255
27304
  const cliPath = findCliCommand(providerLoader?.getIdeCliCommand(def.id, def.cli) || def.cli);
27256
- const appPath = checkPathExists(providerLoader?.getIdePathCandidates(def.id, def.paths[os31] || []) || []);
27305
+ const appPath = checkPathExists(providerLoader?.getIdePathCandidates(def.id, def.paths[os32] || []) || []);
27257
27306
  let resolvedCli = cliPath;
27258
- if (!resolvedCli && appPath && os31 === "darwin") {
27307
+ if (!resolvedCli && appPath && os32 === "darwin") {
27259
27308
  const bundledCli = `${appPath}/Contents/Resources/app/bin/${def.cli}`;
27260
27309
  if ((0, import_fs15.existsSync)(bundledCli)) resolvedCli = bundledCli;
27261
27310
  }
27262
- if (!resolvedCli && appPath && os31 === "win32") {
27311
+ if (!resolvedCli && appPath && os32 === "win32") {
27263
27312
  const { dirname: dirname17 } = await import("path");
27264
27313
  const appDir = dirname17(appPath);
27265
27314
  const candidates = [
@@ -27276,7 +27325,7 @@ async function detectIDEs(providerLoader) {
27276
27325
  }
27277
27326
  }
27278
27327
  }
27279
- const installed = os31 === "darwin" ? !!(resolvedCli || appPath) : !!resolvedCli;
27328
+ const installed = os32 === "darwin" ? !!(resolvedCli || appPath) : !!resolvedCli;
27280
27329
  const version = null;
27281
27330
  results.push({
27282
27331
  id: def.id,
@@ -36699,9 +36748,9 @@ var DaemonCommandHandler = class {
36699
36748
  * point at a sibling git checkout.
36700
36749
  */
36701
36750
  getUpstreamInstallRoot() {
36702
- const os31 = require("os");
36703
- const path44 = require("path");
36704
- return path44.join(os31.homedir(), ".adhdev", "providers", ".upstream");
36751
+ const os32 = require("os");
36752
+ const path45 = require("path");
36753
+ return path45.join(os32.homedir(), ".adhdev", "providers", ".upstream");
36705
36754
  }
36706
36755
  /**
36707
36756
  * Download a single provider manifest from the registry and write it to
@@ -36725,8 +36774,8 @@ var DaemonCommandHandler = class {
36725
36774
  return { success: false, error: "invalid type" };
36726
36775
  }
36727
36776
  const https = require("https");
36728
- const fs40 = require("fs");
36729
- const path44 = require("path");
36777
+ const fs41 = require("fs");
36778
+ const path45 = require("path");
36730
36779
  const REGISTRY = resolveRegistryBaseUrl(loadConfig().registryUrl);
36731
36780
  function fetchText(url, timeoutMs) {
36732
36781
  return new Promise((resolve25, reject) => {
@@ -36763,12 +36812,12 @@ var DaemonCommandHandler = class {
36763
36812
  return { success: false, error: `checksum mismatch: expected ${meta.checksum}, got ${actualChecksum}` };
36764
36813
  }
36765
36814
  const installRoot = this.getUpstreamInstallRoot();
36766
- const installRootResolved = path44.resolve(installRoot);
36767
- const targetDir = path44.resolve(path44.join(installRoot, category, type));
36768
- if (!targetDir.startsWith(installRootResolved + path44.sep)) {
36815
+ const installRootResolved = path45.resolve(installRoot);
36816
+ const targetDir = path45.resolve(path45.join(installRoot, category, type));
36817
+ if (!targetDir.startsWith(installRootResolved + path45.sep)) {
36769
36818
  return { success: false, error: "install path escaped upstream root" };
36770
36819
  }
36771
- fs40.mkdirSync(targetDir, { recursive: true });
36820
+ fs41.mkdirSync(targetDir, { recursive: true });
36772
36821
  let manifestProbe = {};
36773
36822
  try {
36774
36823
  manifestProbe = JSON.parse(manifestBody);
@@ -36792,8 +36841,8 @@ ${formatManifestValidationIssues2(validation.issues)}`,
36792
36841
  }
36793
36842
  }
36794
36843
  const targetFile = isV1 ? "provider.v1.json" : "provider.json";
36795
- const targetPath = path44.join(targetDir, targetFile);
36796
- fs40.writeFileSync(targetPath, manifestBody, "utf-8");
36844
+ const targetPath = path45.join(targetDir, targetFile);
36845
+ fs41.writeFileSync(targetPath, manifestBody, "utf-8");
36797
36846
  const manifestJson = JSON.parse(manifestBody);
36798
36847
  const scriptFetch = await this.fetchProviderSources(
36799
36848
  manifestJson,
@@ -36863,8 +36912,8 @@ ${formatManifestValidationIssues2(validation.issues)}`,
36863
36912
  const repo = source.repo;
36864
36913
  const ref = source.ref;
36865
36914
  const https = require("https");
36866
- const fs40 = require("fs");
36867
- const path44 = require("path");
36915
+ const fs41 = require("fs");
36916
+ const path45 = require("path");
36868
36917
  function fetchJson(url, timeoutMs) {
36869
36918
  return new Promise((resolve25, reject) => {
36870
36919
  const req = https.get(url, {
@@ -36920,9 +36969,9 @@ ${formatManifestValidationIssues2(validation.issues)}`,
36920
36969
  }
36921
36970
  let fetchedCount = 0;
36922
36971
  const sharedDirRel = `${category}/_shared`;
36923
- const sharedTargetDir = path44.resolve(path44.join(targetDir, "../_shared"));
36924
- const installRootResolved = path44.resolve(path44.join(targetDir, "../.."));
36925
- if (sharedTargetDir.startsWith(installRootResolved + path44.sep)) {
36972
+ const sharedTargetDir = path45.resolve(path45.join(targetDir, "../_shared"));
36973
+ const installRootResolved = path45.resolve(path45.join(targetDir, "../.."));
36974
+ if (sharedTargetDir.startsWith(installRootResolved + path45.sep)) {
36926
36975
  const sharedStack = [sharedDirRel];
36927
36976
  while (sharedStack.length) {
36928
36977
  const relDir = sharedStack.pop();
@@ -36945,10 +36994,10 @@ ${formatManifestValidationIssues2(validation.issues)}`,
36945
36994
  try {
36946
36995
  const body = await fetchBinary(entry.download_url, 3e4);
36947
36996
  const relInside = entry.path.startsWith(sharedDirRel + "/") ? entry.path.slice(sharedDirRel.length + 1) : entry.path;
36948
- const outPath = path44.resolve(path44.join(sharedTargetDir, relInside));
36949
- if (!outPath.startsWith(path44.resolve(sharedTargetDir) + path44.sep)) continue;
36950
- fs40.mkdirSync(path44.dirname(outPath), { recursive: true });
36951
- fs40.writeFileSync(outPath, body);
36997
+ const outPath = path45.resolve(path45.join(sharedTargetDir, relInside));
36998
+ if (!outPath.startsWith(path45.resolve(sharedTargetDir) + path45.sep)) continue;
36999
+ fs41.mkdirSync(path45.dirname(outPath), { recursive: true });
37000
+ fs41.writeFileSync(outPath, body);
36952
37001
  fetchedCount++;
36953
37002
  } catch (e) {
36954
37003
  errors.push(`fetch shared ${entry.path}: ${e?.message ?? e}`);
@@ -36981,13 +37030,13 @@ ${formatManifestValidationIssues2(validation.issues)}`,
36981
37030
  try {
36982
37031
  const body = await fetchBinary(entry.download_url, 3e4);
36983
37032
  const relInsideProvider = entry.path.startsWith(subdir + "/") ? entry.path.slice(subdir.length + 1) : entry.path;
36984
- const outPath = path44.resolve(path44.join(targetDir, relInsideProvider));
36985
- if (!outPath.startsWith(path44.resolve(targetDir) + path44.sep)) {
37033
+ const outPath = path45.resolve(path45.join(targetDir, relInsideProvider));
37034
+ if (!outPath.startsWith(path45.resolve(targetDir) + path45.sep)) {
36986
37035
  errors.push(`refusing to write outside targetDir: ${entry.path}`);
36987
37036
  continue;
36988
37037
  }
36989
- fs40.mkdirSync(path44.dirname(outPath), { recursive: true });
36990
- fs40.writeFileSync(outPath, body);
37038
+ fs41.mkdirSync(path45.dirname(outPath), { recursive: true });
37039
+ fs41.writeFileSync(outPath, body);
36991
37040
  fetchedCount++;
36992
37041
  } catch (e) {
36993
37042
  errors.push(`fetch ${entry.path}: ${e?.message ?? e}`);
@@ -37015,19 +37064,19 @@ ${formatManifestValidationIssues2(validation.issues)}`,
37015
37064
  if (!["cli", "ide", "extension", "acp"].includes(category)) {
37016
37065
  return { success: false, error: `unknown category: ${category}` };
37017
37066
  }
37018
- const fs40 = require("fs");
37019
- const path44 = require("path");
37067
+ const fs41 = require("fs");
37068
+ const path45 = require("path");
37020
37069
  try {
37021
37070
  const installRoot = this.getUpstreamInstallRoot();
37022
- const installRootResolved = path44.resolve(installRoot);
37023
- const targetDir = path44.resolve(path44.join(installRoot, category, type));
37024
- if (!targetDir.startsWith(installRootResolved + path44.sep)) {
37071
+ const installRootResolved = path45.resolve(installRoot);
37072
+ const targetDir = path45.resolve(path45.join(installRoot, category, type));
37073
+ if (!targetDir.startsWith(installRootResolved + path45.sep)) {
37025
37074
  return { success: false, error: "refusing to delete outside upstream root" };
37026
37075
  }
37027
- if (!fs40.existsSync(targetDir)) {
37076
+ if (!fs41.existsSync(targetDir)) {
37028
37077
  return { success: false, error: "not installed" };
37029
37078
  }
37030
- fs40.rmSync(targetDir, { recursive: true, force: true });
37079
+ fs41.rmSync(targetDir, { recursive: true, force: true });
37031
37080
  if (this._ctx.providerLoader) {
37032
37081
  this._ctx.providerLoader.reload();
37033
37082
  this._ctx.providerLoader.registerToDetector();
@@ -37043,28 +37092,28 @@ ${formatManifestValidationIssues2(validation.issues)}`,
37043
37092
  * the UI and by the update checker.
37044
37093
  */
37045
37094
  handleListInstalledProviders(_args) {
37046
- const fs40 = require("fs");
37047
- const path44 = require("path");
37095
+ const fs41 = require("fs");
37096
+ const path45 = require("path");
37048
37097
  const installRoot = this.getUpstreamInstallRoot();
37049
- if (!fs40.existsSync(installRoot)) return { success: true, providers: [] };
37098
+ if (!fs41.existsSync(installRoot)) return { success: true, providers: [] };
37050
37099
  const CATEGORIES = ["cli", "ide", "extension", "acp"];
37051
37100
  const items = [];
37052
37101
  for (const category of CATEGORIES) {
37053
- const categoryDir = path44.join(installRoot, category);
37054
- if (!fs40.existsSync(categoryDir)) continue;
37102
+ const categoryDir = path45.join(installRoot, category);
37103
+ if (!fs41.existsSync(categoryDir)) continue;
37055
37104
  let entries;
37056
37105
  try {
37057
- entries = fs40.readdirSync(categoryDir);
37106
+ entries = fs41.readdirSync(categoryDir);
37058
37107
  } catch {
37059
37108
  continue;
37060
37109
  }
37061
37110
  for (const type of entries) {
37062
- const v1Path = path44.join(categoryDir, type, "provider.v1.json");
37063
- const v0Path = path44.join(categoryDir, type, "provider.json");
37064
- const manifestPath = fs40.existsSync(v1Path) ? v1Path : fs40.existsSync(v0Path) ? v0Path : null;
37111
+ const v1Path = path45.join(categoryDir, type, "provider.v1.json");
37112
+ const v0Path = path45.join(categoryDir, type, "provider.json");
37113
+ const manifestPath = fs41.existsSync(v1Path) ? v1Path : fs41.existsSync(v0Path) ? v0Path : null;
37065
37114
  if (!manifestPath) continue;
37066
37115
  try {
37067
- const m = JSON.parse(fs40.readFileSync(manifestPath, "utf-8"));
37116
+ const m = JSON.parse(fs41.readFileSync(manifestPath, "utf-8"));
37068
37117
  items.push({
37069
37118
  type,
37070
37119
  category,
@@ -37175,8 +37224,8 @@ ${formatManifestValidationIssues2(validation.issues)}`,
37175
37224
  if (!/^@[a-z0-9_-]+$/i.test(requestedName)) {
37176
37225
  return { success: false, error: "name must match @[a-z0-9_-]+" };
37177
37226
  }
37178
- const fs40 = require("fs");
37179
- const path44 = require("path");
37227
+ const fs41 = require("fs");
37228
+ const path45 = require("path");
37180
37229
  const { spawnSync: spawnSync2 } = require("child_process");
37181
37230
  const file = ext.loadExternalSources();
37182
37231
  if (file.sources.some((s2) => s2.name === requestedName)) {
@@ -37185,9 +37234,9 @@ ${formatManifestValidationIssues2(validation.issues)}`,
37185
37234
  if (file.sources.some((s2) => s2.url === url && s2.ref === ref)) {
37186
37235
  return { success: false, error: `source url+ref already registered (use a different name to track another ref)` };
37187
37236
  }
37188
- const sourceDir = path44.join(ext.externalRoot(), requestedName);
37189
- if (!fs40.existsSync(ext.externalRoot())) fs40.mkdirSync(ext.externalRoot(), { recursive: true });
37190
- if (fs40.existsSync(sourceDir)) {
37237
+ const sourceDir = path45.join(ext.externalRoot(), requestedName);
37238
+ if (!fs41.existsSync(ext.externalRoot())) fs41.mkdirSync(ext.externalRoot(), { recursive: true });
37239
+ if (fs41.existsSync(sourceDir)) {
37191
37240
  return { success: false, error: `directory already exists: ${sourceDir} (rename or remove first)` };
37192
37241
  }
37193
37242
  const clone = spawnSync2("git", ["clone", "--depth=1", "--branch", ref, "--", url, sourceDir], {
@@ -37197,7 +37246,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
37197
37246
  });
37198
37247
  if (clone.status !== 0) {
37199
37248
  try {
37200
- fs40.rmSync(sourceDir, { recursive: true, force: true });
37249
+ fs41.rmSync(sourceDir, { recursive: true, force: true });
37201
37250
  } catch {
37202
37251
  }
37203
37252
  return { success: false, error: `git clone failed: ${(clone.stderr || clone.stdout || "").trim() || "unknown error"}` };
@@ -37241,15 +37290,15 @@ ${formatManifestValidationIssues2(validation.issues)}`,
37241
37290
  const name = typeof args?.name === "string" ? args.name.trim() : "";
37242
37291
  if (!name) return { success: false, error: "name is required" };
37243
37292
  const ext = (init_external_sources(), __toCommonJS(external_sources_exports));
37244
- const fs40 = require("fs");
37245
- const path44 = require("path");
37293
+ const fs41 = require("fs");
37294
+ const path45 = require("path");
37246
37295
  const file = ext.loadExternalSources();
37247
37296
  const match = file.sources.find((s2) => s2.name === name);
37248
37297
  if (!match) return { success: false, error: `source "${name}" not registered` };
37249
- const sourceDir = path44.join(ext.externalRoot(), name);
37250
- if (fs40.existsSync(sourceDir)) {
37298
+ const sourceDir = path45.join(ext.externalRoot(), name);
37299
+ if (fs41.existsSync(sourceDir)) {
37251
37300
  try {
37252
- fs40.rmSync(sourceDir, { recursive: true, force: true });
37301
+ fs41.rmSync(sourceDir, { recursive: true, force: true });
37253
37302
  } catch (e) {
37254
37303
  return { success: false, error: `failed to delete ${sourceDir}: ${e?.message || e}` };
37255
37304
  }
@@ -38034,24 +38083,24 @@ var statusMetaHandlers = {
38034
38083
  // src/commands/low-family/coordinator-prompt.ts
38035
38084
  var coordinatorPromptHandlers = {
38036
38085
  list_coordinator_prompts: async (_ctx, _args) => {
38037
- const fs40 = await import("fs");
38038
- const path44 = await import("path");
38039
- const os31 = await import("os");
38040
- const dir = path44.join(os31.homedir(), ".adhdev", "coordinator-prompts");
38086
+ const fs41 = await import("fs");
38087
+ const path45 = await import("path");
38088
+ const os32 = await import("os");
38089
+ const dir = path45.join(os32.homedir(), ".adhdev", "coordinator-prompts");
38041
38090
  const entries = {};
38042
38091
  try {
38043
- if (fs40.existsSync(dir)) {
38044
- for (const name of fs40.readdirSync(dir)) {
38092
+ if (fs41.existsSync(dir)) {
38093
+ for (const name of fs41.readdirSync(dir)) {
38045
38094
  const matchOverride = name.match(/^([a-zA-Z0-9_.-]+)\.md$/);
38046
38095
  const matchAppend = name.match(/^([a-zA-Z0-9_.-]+)\.append\.md$/);
38047
38096
  const m = matchAppend || matchOverride;
38048
38097
  if (!m) continue;
38049
38098
  const isAppend = !!matchAppend;
38050
38099
  const key2 = m[1];
38051
- const full = path44.join(dir, name);
38100
+ const full = path45.join(dir, name);
38052
38101
  let content = "";
38053
38102
  try {
38054
- content = fs40.readFileSync(full, "utf8");
38103
+ content = fs41.readFileSync(full, "utf8");
38055
38104
  } catch {
38056
38105
  }
38057
38106
  if (!entries[key2]) entries[key2] = { override: "", append: "" };
@@ -38065,24 +38114,24 @@ var coordinatorPromptHandlers = {
38065
38114
  return { success: true, dir, entries };
38066
38115
  },
38067
38116
  write_coordinator_prompt: async (_ctx, args) => {
38068
- const fs40 = await import("fs");
38069
- const path44 = await import("path");
38070
- const os31 = await import("os");
38117
+ const fs41 = await import("fs");
38118
+ const path45 = await import("path");
38119
+ const os32 = await import("os");
38071
38120
  const key2 = typeof args?.key === "string" ? args.key.trim() : "";
38072
38121
  const kind = args?.kind === "append" ? "append" : "override";
38073
38122
  const content = typeof args?.content === "string" ? args.content : "";
38074
38123
  if (!key2 || !/^[a-zA-Z0-9_.-]+$/.test(key2)) {
38075
38124
  return { success: false, error: "key must match [a-zA-Z0-9_.-]+" };
38076
38125
  }
38077
- const dir = path44.join(os31.homedir(), ".adhdev", "coordinator-prompts");
38126
+ const dir = path45.join(os32.homedir(), ".adhdev", "coordinator-prompts");
38078
38127
  const filename = kind === "append" ? `${key2}.append.md` : `${key2}.md`;
38079
- const full = path44.join(dir, filename);
38128
+ const full = path45.join(dir, filename);
38080
38129
  try {
38081
- fs40.mkdirSync(dir, { recursive: true });
38130
+ fs41.mkdirSync(dir, { recursive: true });
38082
38131
  if (content.trim()) {
38083
- fs40.writeFileSync(full, content, { encoding: "utf8", mode: 384 });
38084
- } else if (fs40.existsSync(full)) {
38085
- fs40.unlinkSync(full);
38132
+ fs41.writeFileSync(full, content, { encoding: "utf8", mode: 384 });
38133
+ } else if (fs41.existsSync(full)) {
38134
+ fs41.unlinkSync(full);
38086
38135
  }
38087
38136
  return { success: true, path: full, kind, key: key2 };
38088
38137
  } catch (error) {
@@ -39165,9 +39214,9 @@ var lowFamilyRegistry = new Map(
39165
39214
  init_dist();
39166
39215
 
39167
39216
  // src/commands/cli-manager.ts
39168
- var os21 = __toESM(require("os"));
39169
- var path28 = __toESM(require("path"));
39170
- var crypto5 = __toESM(require("crypto"));
39217
+ var os22 = __toESM(require("os"));
39218
+ var path29 = __toESM(require("path"));
39219
+ var crypto6 = __toESM(require("crypto"));
39171
39220
  var import_fs16 = require("fs");
39172
39221
  var import_child_process8 = require("child_process");
39173
39222
  var import_chalk = __toESM(require("chalk"));
@@ -39182,11 +39231,9 @@ init_coordinator_registry();
39182
39231
  init_summary_metadata();
39183
39232
 
39184
39233
  // src/providers/cli-provider-instance.ts
39185
- var os20 = __toESM(require("os"));
39186
- var path26 = __toESM(require("path"));
39187
- var crypto4 = __toESM(require("crypto"));
39188
- var fs19 = __toESM(require("fs"));
39189
- var import_node_module = require("module");
39234
+ var os21 = __toESM(require("os"));
39235
+ var crypto5 = __toESM(require("crypto"));
39236
+ var fs20 = __toESM(require("fs"));
39190
39237
  init_contracts2();
39191
39238
  init_provider_input_support();
39192
39239
  init_hash();
@@ -42392,28 +42439,11 @@ function workingDirBasename(p) {
42392
42439
  return (p || "").split(/[\\/]/).filter(Boolean).pop() || "session";
42393
42440
  }
42394
42441
 
42395
- // src/providers/cli-provider-instance.ts
42396
- var STATUS_HYDRATION_TAIL_LIMIT = 200;
42397
- function isIdleStatus(value) {
42398
- const status = typeof value === "string" ? value.trim().toLowerCase() : "";
42399
- return !status || status === "idle" || status === "ready";
42400
- }
42401
- function getMessageTime(message) {
42402
- if (!message || typeof message !== "object") return 0;
42403
- const record = message;
42404
- const value = Number(record.receivedAt ?? record.timestamp ?? 0);
42405
- return Number.isFinite(value) ? value : 0;
42406
- }
42407
- var COMPLETED_FINALIZATION_RETRY_MS = 1e3;
42408
- var COMPLETED_FINALIZATION_MAX_WAIT_MS = 3e4;
42409
- var NATIVE_HISTORY_MESH_IDLE_SETTLE_MS = 4e3;
42410
- var USER_INPUT_ACK_DEDUP_WINDOW_MS = 6e4;
42411
- var STARTUP_GRACE_IDLE_COLLAPSE_WINDOW_MS = 12e3;
42412
- var TERMINAL_MESH_EVENTS = /* @__PURE__ */ new Set([
42413
- "agent:generating_completed",
42414
- "agent:stopped",
42415
- "agent:ready"
42416
- ]);
42442
+ // src/providers/cli-provider-input-prompt.ts
42443
+ var os20 = __toESM(require("os"));
42444
+ var path26 = __toESM(require("path"));
42445
+ var crypto4 = __toESM(require("crypto"));
42446
+ var fs19 = __toESM(require("fs"));
42417
42447
  var IMAGE_MIME_EXTENSIONS = {
42418
42448
  "image/png": ".png",
42419
42449
  "image/jpeg": ".jpg",
@@ -42477,19 +42507,6 @@ function cleanupStaleMaterializedImages(dir) {
42477
42507
  } catch {
42478
42508
  }
42479
42509
  }
42480
- function hasNonEmptyCliModalButtons(activeModal) {
42481
- const buttons = activeModal?.buttons;
42482
- return Array.isArray(buttons) && buttons.some((button) => String(button || "").trim().length > 0);
42483
- }
42484
- function isCliGeneratingLikeStatus(status) {
42485
- return status === "generating" || status === "streaming" || status === "no_progress" || status === "long_generating" || status === "starting";
42486
- }
42487
- function computeTurnAnchoredDurationMs(engineTurnStartedAt, generatingStartedAt, now) {
42488
- const engineStart = typeof engineTurnStartedAt === "number" && Number.isFinite(engineTurnStartedAt) ? engineTurnStartedAt : 0;
42489
- if (engineStart > 0) return { durationMs: now - engineStart, anchor: "turn-start" };
42490
- if (generatingStartedAt > 0) return { durationMs: now - generatingStartedAt, anchor: "generatingStartedAt" };
42491
- return { durationMs: 0, anchor: "none" };
42492
- }
42493
42510
  function buildCliStructuredInputPrompt(input, options = {}) {
42494
42511
  const promptParts = [];
42495
42512
  const imageRefs = [];
@@ -42527,6 +42544,9 @@ function buildCliStructuredInputPrompt(input, options = {}) {
42527
42544
  ].filter((value, index, values) => value.trim().length > 0 && values.indexOf(value) === index);
42528
42545
  return ordered.join("\n");
42529
42546
  }
42547
+
42548
+ // src/providers/cli-provider-history-dedup.ts
42549
+ init_contracts2();
42530
42550
  function normalizePersistableCliHistoryContent(content) {
42531
42551
  return flattenContent(content).replace(/\s+/g, " ").trim();
42532
42552
  }
@@ -42558,10 +42578,37 @@ function buildIncrementalHistoryAppendMessages(previousMessages, currentMessages
42558
42578
  if (sharedPrefixLength === previousMessages.length) return currentMessages.slice(sharedPrefixLength);
42559
42579
  return currentMessages;
42560
42580
  }
42581
+
42582
+ // src/providers/cli-provider-status-helpers.ts
42583
+ var path27 = __toESM(require("path"));
42584
+ var import_node_module = require("module");
42585
+ function isIdleStatus(value) {
42586
+ const status = typeof value === "string" ? value.trim().toLowerCase() : "";
42587
+ return !status || status === "idle" || status === "ready";
42588
+ }
42589
+ function getMessageTime(message) {
42590
+ if (!message || typeof message !== "object") return 0;
42591
+ const record = message;
42592
+ const value = Number(record.receivedAt ?? record.timestamp ?? 0);
42593
+ return Number.isFinite(value) ? value : 0;
42594
+ }
42595
+ function hasNonEmptyCliModalButtons(activeModal) {
42596
+ const buttons = activeModal?.buttons;
42597
+ return Array.isArray(buttons) && buttons.some((button) => String(button || "").trim().length > 0);
42598
+ }
42599
+ function isCliGeneratingLikeStatus(status) {
42600
+ return status === "generating" || status === "streaming" || status === "no_progress" || status === "long_generating" || status === "starting";
42601
+ }
42602
+ function computeTurnAnchoredDurationMs(engineTurnStartedAt, generatingStartedAt, now) {
42603
+ const engineStart = typeof engineTurnStartedAt === "number" && Number.isFinite(engineTurnStartedAt) ? engineTurnStartedAt : 0;
42604
+ if (engineStart > 0) return { durationMs: now - engineStart, anchor: "turn-start" };
42605
+ if (generatingStartedAt > 0) return { durationMs: now - generatingStartedAt, anchor: "generatingStartedAt" };
42606
+ return { durationMs: 0, anchor: "none" };
42607
+ }
42561
42608
  var CachedDatabaseSync = null;
42562
42609
  function getDatabaseSync() {
42563
42610
  if (CachedDatabaseSync) return CachedDatabaseSync;
42564
- const requireFn = typeof require === "function" ? require : (0, import_node_module.createRequire)(path26.join(process.cwd(), "__adhdev_sqlite_loader__.js"));
42611
+ const requireFn = typeof require === "function" ? require : (0, import_node_module.createRequire)(path27.join(process.cwd(), "__adhdev_sqlite_loader__.js"));
42565
42612
  const sqliteModule = requireFn(`node:${"sqlite"}`);
42566
42613
  CachedDatabaseSync = sqliteModule.DatabaseSync;
42567
42614
  if (!CachedDatabaseSync) {
@@ -42603,13 +42650,26 @@ async function waitForCliAdapterReady(adapter, options) {
42603
42650
  }
42604
42651
  throw new Error(`CLI runtime did not become ready within ${timeoutMs}ms`);
42605
42652
  }
42653
+
42654
+ // src/providers/cli-provider-instance.ts
42655
+ var STATUS_HYDRATION_TAIL_LIMIT = 200;
42656
+ var COMPLETED_FINALIZATION_RETRY_MS = 1e3;
42657
+ var COMPLETED_FINALIZATION_MAX_WAIT_MS = 3e4;
42658
+ var NATIVE_HISTORY_MESH_IDLE_SETTLE_MS = 4e3;
42659
+ var USER_INPUT_ACK_DEDUP_WINDOW_MS = 6e4;
42660
+ var STARTUP_GRACE_IDLE_COLLAPSE_WINDOW_MS = 12e3;
42661
+ var TERMINAL_MESH_EVENTS = /* @__PURE__ */ new Set([
42662
+ "agent:generating_completed",
42663
+ "agent:stopped",
42664
+ "agent:ready"
42665
+ ]);
42606
42666
  var CliProviderInstance = class _CliProviderInstance {
42607
42667
  constructor(provider, workingDir, cliArgs = [], instanceId, transportFactory, options) {
42608
42668
  this.provider = provider;
42609
42669
  this.workingDir = workingDir;
42610
42670
  this.cliArgs = cliArgs;
42611
42671
  this.type = provider.type;
42612
- this.instanceId = instanceId || crypto4.randomUUID();
42672
+ this.instanceId = instanceId || crypto5.randomUUID();
42613
42673
  this.presentationMode = "chat";
42614
42674
  this.providerSessionId = options?.providerSessionId;
42615
42675
  this.launchMode = options?.launchMode || "new";
@@ -42835,10 +42895,10 @@ var CliProviderInstance = class _CliProviderInstance {
42835
42895
  * Replaces the previously duplicated probeOpenCode/Codex/Goose functions.
42836
42896
  */
42837
42897
  probeSessionIdFromConfig(probe) {
42838
- const resolvedDbPath = probe.dbPath.replace(/^~/, os20.homedir());
42898
+ const resolvedDbPath = probe.dbPath.replace(/^~/, os21.homedir());
42839
42899
  const now = Date.now();
42840
42900
  if (this.cachedSqliteDbMissingUntil > now) return null;
42841
- if (!fs19.existsSync(resolvedDbPath)) {
42901
+ if (!fs20.existsSync(resolvedDbPath)) {
42842
42902
  this.cachedSqliteDbMissingUntil = now + 1e4;
42843
42903
  return null;
42844
42904
  }
@@ -43434,7 +43494,7 @@ var CliProviderInstance = class _CliProviderInstance {
43434
43494
  if (!isNativeSourceCanonicalHistory(this.provider.nativeHistory)) return null;
43435
43495
  if (this.lastExternalCompletionProbe?.sourcePath) {
43436
43496
  try {
43437
- fs19.statSync(this.lastExternalCompletionProbe.sourcePath);
43497
+ fs20.statSync(this.lastExternalCompletionProbe.sourcePath);
43438
43498
  } catch {
43439
43499
  }
43440
43500
  }
@@ -44967,7 +45027,7 @@ ${effect.notification.body || ""}`.trim();
44967
45027
  };
44968
45028
  addDir(this.workingDir);
44969
45029
  try {
44970
- addDir(fs19.realpathSync.native(this.workingDir));
45030
+ addDir(fs20.realpathSync.native(this.workingDir));
44971
45031
  } catch {
44972
45032
  }
44973
45033
  return Array.from(dirs);
@@ -45004,7 +45064,7 @@ ${effect.notification.body || ""}`.trim();
45004
45064
  };
45005
45065
 
45006
45066
  // src/providers/acp-provider-instance.ts
45007
- var path27 = __toESM(require("path"));
45067
+ var path28 = __toESM(require("path"));
45008
45068
  var import_stream = require("stream");
45009
45069
  var import_child_process7 = require("child_process");
45010
45070
  var import_sdk = require("@agentclientprotocol/sdk");
@@ -45794,7 +45854,7 @@ var AcpProviderInstance = class {
45794
45854
  return b.uri ? {
45795
45855
  type: "resource_link",
45796
45856
  uri: b.uri,
45797
- name: path27.basename(b.uri),
45857
+ name: path28.basename(b.uri),
45798
45858
  mimeType: b.mimeType,
45799
45859
  ...b.transcript ? { description: b.transcript } : {}
45800
45860
  } : { type: "text", text: b.transcript || `[Video attachment: ${b.mimeType}]` };
@@ -46266,11 +46326,11 @@ function shouldRestoreHostedRuntime(record, managerTag) {
46266
46326
  // src/commands/cli-manager.ts
46267
46327
  function isExplicitCommand(command) {
46268
46328
  const trimmed = command.trim();
46269
- return path28.isAbsolute(trimmed) || trimmed.includes("/") || trimmed.includes("\\") || trimmed.startsWith("~");
46329
+ return path29.isAbsolute(trimmed) || trimmed.includes("/") || trimmed.includes("\\") || trimmed.startsWith("~");
46270
46330
  }
46271
46331
  function expandExecutable(command) {
46272
46332
  const trimmed = command.trim();
46273
- return trimmed.startsWith("~") ? path28.join(os21.homedir(), trimmed.slice(1)) : trimmed;
46333
+ return trimmed.startsWith("~") ? path29.join(os22.homedir(), trimmed.slice(1)) : trimmed;
46274
46334
  }
46275
46335
  function commandExists(command) {
46276
46336
  const trimmed = command.trim();
@@ -46415,10 +46475,10 @@ function hasConfigOverride(args, key2) {
46415
46475
  return false;
46416
46476
  }
46417
46477
  function ensureEmptyDelegatedMcpConfig(workspace) {
46418
- const baseDir = path28.join(os21.tmpdir(), "adhdev-delegated-agent-empty-mcp");
46478
+ const baseDir = path29.join(os22.tmpdir(), "adhdev-delegated-agent-empty-mcp");
46419
46479
  (0, import_fs16.mkdirSync)(baseDir, { recursive: true });
46420
- const workspaceHash = shortHash(path28.resolve(workspace || os21.tmpdir()));
46421
- const filePath = path28.join(baseDir, `${workspaceHash}.json`);
46480
+ const workspaceHash = shortHash(path29.resolve(workspace || os22.tmpdir()));
46481
+ const filePath = path29.join(baseDir, `${workspaceHash}.json`);
46422
46482
  (0, import_fs16.writeFileSync)(filePath, JSON.stringify({ mcpServers: {} }, null, 2), "utf-8");
46423
46483
  return filePath;
46424
46484
  }
@@ -46572,7 +46632,7 @@ function resolveCliSessionBinding(provider, normalizedType, cliArgs, requestedRe
46572
46632
  if (!supportsExplicitSessionStart(resume)) {
46573
46633
  return { cliArgs: baseArgs, launchMode: "new" };
46574
46634
  }
46575
- const providerSessionId = crypto5.randomUUID();
46635
+ const providerSessionId = crypto6.randomUUID();
46576
46636
  const newSessionArgs = expandResumeArgs(resume.newSessionArgs, providerSessionId);
46577
46637
  return {
46578
46638
  cliArgs: [...baseArgs || [], ...newSessionArgs || []],
@@ -46756,7 +46816,7 @@ var DaemonCliManager = class {
46756
46816
  async startSession(cliType, workingDir, cliArgs, initialModel, options) {
46757
46817
  const trimmed = (workingDir || "").trim();
46758
46818
  if (!trimmed) throw new Error("working directory required");
46759
- const resolvedDir = trimmed.startsWith("~") ? trimmed.replace(/^~/, os21.homedir()) : path28.resolve(trimmed);
46819
+ const resolvedDir = trimmed.startsWith("~") ? trimmed.replace(/^~/, os22.homedir()) : path29.resolve(trimmed);
46760
46820
  const normalizedType = this.providerLoader.resolveAlias(cliType);
46761
46821
  const rawProvider = this.providerLoader.getByAlias(cliType);
46762
46822
  const provider = rawProvider ? this.providerLoader.resolve(normalizedType) || rawProvider : void 0;
@@ -46767,7 +46827,7 @@ var DaemonCliManager = class {
46767
46827
  Enable and detect this provider from the Machine Providers page before starting a runtime.`
46768
46828
  );
46769
46829
  }
46770
- const key2 = crypto5.randomUUID();
46830
+ const key2 = crypto6.randomUUID();
46771
46831
  {
46772
46832
  const coordinatorMeshId = options?.settingsOverride?.meshCoordinatorFor;
46773
46833
  if (typeof coordinatorMeshId === "string" && coordinatorMeshId.trim()) {
@@ -47608,13 +47668,13 @@ var cliAgentHandlers = {
47608
47668
  // src/launch.ts
47609
47669
  var import_child_process9 = require("child_process");
47610
47670
  var net = __toESM(require("net"));
47611
- var os26 = __toESM(require("os"));
47612
- var path36 = __toESM(require("path"));
47671
+ var os27 = __toESM(require("os"));
47672
+ var path37 = __toESM(require("path"));
47613
47673
 
47614
47674
  // src/providers/provider-loader.ts
47615
- var fs25 = __toESM(require("fs"));
47616
- var path35 = __toESM(require("path"));
47617
- var os25 = __toESM(require("os"));
47675
+ var fs26 = __toESM(require("fs"));
47676
+ var path36 = __toESM(require("path"));
47677
+ var os26 = __toESM(require("os"));
47618
47678
  var chokidar = __toESM(require("chokidar"));
47619
47679
  init_hash();
47620
47680
  init_logger();
@@ -48006,13 +48066,13 @@ function validateControl(control, errors) {
48006
48066
  init_external_sources();
48007
48067
 
48008
48068
  // src/providers/native-history/dispatcher.ts
48009
- var fs24 = __toESM(require("fs"));
48010
- var os24 = __toESM(require("os"));
48011
- var path33 = __toESM(require("path"));
48069
+ var fs25 = __toESM(require("fs"));
48070
+ var os25 = __toESM(require("os"));
48071
+ var path34 = __toESM(require("path"));
48012
48072
 
48013
48073
  // src/providers/native-history/claude-cli-transcript.ts
48014
- var fs20 = __toESM(require("fs"));
48015
- var path29 = __toESM(require("path"));
48074
+ var fs21 = __toESM(require("fs"));
48075
+ var path30 = __toESM(require("path"));
48016
48076
  function extractTimestampValue(value) {
48017
48077
  if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;
48018
48078
  if (typeof value === "string") {
@@ -48025,7 +48085,7 @@ function extractTimestampValue(value) {
48025
48085
  }
48026
48086
  function statMtimeMs(filePath) {
48027
48087
  try {
48028
- return fs20.statSync(filePath).mtimeMs;
48088
+ return fs21.statSync(filePath).mtimeMs;
48029
48089
  } catch {
48030
48090
  return 0;
48031
48091
  }
@@ -48095,7 +48155,7 @@ function extractUserContentParts(content) {
48095
48155
  function parseTranscriptFile(filePath, sessionId, workspaceFallback) {
48096
48156
  let raw;
48097
48157
  try {
48098
- raw = fs20.readFileSync(filePath, "utf-8");
48158
+ raw = fs21.readFileSync(filePath, "utf-8");
48099
48159
  } catch {
48100
48160
  return [];
48101
48161
  }
@@ -48168,10 +48228,10 @@ function parseTranscriptFile(filePath, sessionId, workspaceFallback) {
48168
48228
  return records;
48169
48229
  }
48170
48230
  function readSession(sessionPath) {
48171
- if (!sessionPath || !path29.isAbsolute(sessionPath)) return null;
48172
- const basename14 = path29.basename(sessionPath, ".jsonl");
48231
+ if (!sessionPath || !path30.isAbsolute(sessionPath)) return null;
48232
+ const basename14 = path30.basename(sessionPath, ".jsonl");
48173
48233
  if (!isSafeSessionId(basename14)) return null;
48174
- if (!fs20.existsSync(sessionPath)) return null;
48234
+ if (!fs21.existsSync(sessionPath)) return null;
48175
48235
  const sourceMtimeMs = statMtimeMs(sessionPath);
48176
48236
  const messages = parseTranscriptFile(sessionPath, basename14);
48177
48237
  if (messages.length === 0) return null;
@@ -48189,8 +48249,8 @@ function readSession(sessionPath) {
48189
48249
  }
48190
48250
 
48191
48251
  // src/providers/native-history/codex-cli-transcript.ts
48192
- var fs21 = __toESM(require("fs"));
48193
- var path30 = __toESM(require("path"));
48252
+ var fs22 = __toESM(require("fs"));
48253
+ var path31 = __toESM(require("path"));
48194
48254
  function extractTimestampValue2(value) {
48195
48255
  if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;
48196
48256
  if (typeof value === "string") {
@@ -48203,7 +48263,7 @@ function extractTimestampValue2(value) {
48203
48263
  }
48204
48264
  function statMtimeMs2(filePath) {
48205
48265
  try {
48206
- return fs21.statSync(filePath).mtimeMs;
48266
+ return fs22.statSync(filePath).mtimeMs;
48207
48267
  } catch {
48208
48268
  return 0;
48209
48269
  }
@@ -48300,7 +48360,7 @@ function pushAssistantStandardMessage(records, sessionId, receivedAt, content, w
48300
48360
  }
48301
48361
  function readSessionMeta(filePath) {
48302
48362
  try {
48303
- const firstLine = fs21.readFileSync(filePath, "utf-8").split("\n").find(Boolean);
48363
+ const firstLine = fs22.readFileSync(filePath, "utf-8").split("\n").find(Boolean);
48304
48364
  if (!firstLine) return null;
48305
48365
  const parsed = JSON.parse(firstLine);
48306
48366
  if (String(parsed.type ?? "") !== "session_meta") return null;
@@ -48312,7 +48372,7 @@ function readSessionMeta(filePath) {
48312
48372
  function parseSessionFile(filePath, sessionId, workspaceFallback) {
48313
48373
  let raw;
48314
48374
  try {
48315
- raw = fs21.readFileSync(filePath, "utf-8");
48375
+ raw = fs22.readFileSync(filePath, "utf-8");
48316
48376
  } catch {
48317
48377
  return [];
48318
48378
  }
@@ -48427,11 +48487,11 @@ function parseSessionFile(filePath, sessionId, workspaceFallback) {
48427
48487
  return records;
48428
48488
  }
48429
48489
  function readSession2(sessionPath) {
48430
- if (!sessionPath || !path30.isAbsolute(sessionPath)) return null;
48431
- if (!fs21.existsSync(sessionPath)) return null;
48490
+ if (!sessionPath || !path31.isAbsolute(sessionPath)) return null;
48491
+ if (!fs22.existsSync(sessionPath)) return null;
48432
48492
  const meta = readSessionMeta(sessionPath);
48433
48493
  const metaId = String(meta?.id ?? "").trim();
48434
- const basename14 = path30.basename(sessionPath, ".jsonl");
48494
+ const basename14 = path31.basename(sessionPath, ".jsonl");
48435
48495
  const uuidMatch = basename14.match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i);
48436
48496
  const filenameUuid2 = uuidMatch ? uuidMatch[1] : "";
48437
48497
  if (metaId && filenameUuid2 && metaId !== filenameUuid2) return null;
@@ -48455,9 +48515,9 @@ function readSession2(sessionPath) {
48455
48515
  }
48456
48516
 
48457
48517
  // src/providers/native-history/antigravity-cli-transcript.ts
48458
- var fs22 = __toESM(require("fs"));
48459
- var path31 = __toESM(require("path"));
48460
- var os22 = __toESM(require("os"));
48518
+ var fs23 = __toESM(require("fs"));
48519
+ var path32 = __toESM(require("path"));
48520
+ var os23 = __toESM(require("os"));
48461
48521
  init_load_better_sqlite3();
48462
48522
  init_logger();
48463
48523
  function extractTimestampValue3(value) {
@@ -48472,7 +48532,7 @@ function extractTimestampValue3(value) {
48472
48532
  }
48473
48533
  function statMtimeMs3(filePath) {
48474
48534
  try {
48475
- return fs22.statSync(filePath).mtimeMs;
48535
+ return fs23.statSync(filePath).mtimeMs;
48476
48536
  } catch {
48477
48537
  return 0;
48478
48538
  }
@@ -48481,13 +48541,13 @@ function isUuidLike(value) {
48481
48541
  return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
48482
48542
  }
48483
48543
  function antigravityRoot() {
48484
- return path31.join(os22.homedir(), ".gemini", "antigravity-cli");
48544
+ return path32.join(os23.homedir(), ".gemini", "antigravity-cli");
48485
48545
  }
48486
48546
  function historyJsonlPath() {
48487
- return path31.join(antigravityRoot(), "history.jsonl");
48547
+ return path32.join(antigravityRoot(), "history.jsonl");
48488
48548
  }
48489
48549
  function brainRoot() {
48490
- return path31.join(antigravityRoot(), "brain");
48550
+ return path32.join(antigravityRoot(), "brain");
48491
48551
  }
48492
48552
  function extractUserRequestContent(content) {
48493
48553
  const raw = content.trim();
@@ -48503,7 +48563,7 @@ function antigravityRowKind(rowType) {
48503
48563
  function parseBrainTranscript(filePath, sessionId, workspace) {
48504
48564
  let raw;
48505
48565
  try {
48506
- raw = fs22.readFileSync(filePath, "utf-8");
48566
+ raw = fs23.readFileSync(filePath, "utf-8");
48507
48567
  } catch {
48508
48568
  return null;
48509
48569
  }
@@ -48563,7 +48623,7 @@ function readHistoryRows() {
48563
48623
  const sourcePath = historyJsonlPath();
48564
48624
  let lines = [];
48565
48625
  try {
48566
- lines = fs22.readFileSync(sourcePath, "utf-8").split("\n").filter(Boolean);
48626
+ lines = fs23.readFileSync(sourcePath, "utf-8").split("\n").filter(Boolean);
48567
48627
  } catch {
48568
48628
  return [];
48569
48629
  }
@@ -48611,7 +48671,7 @@ function extractStringsFromBuffer(buf) {
48611
48671
  function parsePbFile(filePath, sessionId) {
48612
48672
  let buf;
48613
48673
  try {
48614
- buf = fs22.readFileSync(filePath);
48674
+ buf = fs23.readFileSync(filePath);
48615
48675
  } catch {
48616
48676
  return null;
48617
48677
  }
@@ -48781,7 +48841,7 @@ function parseConversationDb(filePath, sessionId, workspace) {
48781
48841
  } catch (err) {
48782
48842
  LOG.warn(
48783
48843
  "NativeHistory",
48784
- `antigravity .db reader could not load better-sqlite3 for ${path31.basename(filePath)}: ${err instanceof Error ? err.message : String(err)} (native binding unavailable \u2014 assistant answers in this .db will not surface)`
48844
+ `antigravity .db reader could not load better-sqlite3 for ${path32.basename(filePath)}: ${err instanceof Error ? err.message : String(err)} (native binding unavailable \u2014 assistant answers in this .db will not surface)`
48785
48845
  );
48786
48846
  return null;
48787
48847
  }
@@ -48811,13 +48871,13 @@ function parseConversationDb(filePath, sessionId, workspace) {
48811
48871
  }
48812
48872
  LOG.warn(
48813
48873
  "NativeHistory",
48814
- `antigravity .db ${path31.basename(filePath)} stayed locked (SQLITE_BUSY) after ${AGY_DB_MAX_ATTEMPTS} attempts: ${err instanceof Error ? err.message : String(err)} (WAL write/checkpoint lock contention \u2014 assistant answers may transiently not surface this read)`
48874
+ `antigravity .db ${path32.basename(filePath)} stayed locked (SQLITE_BUSY) after ${AGY_DB_MAX_ATTEMPTS} attempts: ${err instanceof Error ? err.message : String(err)} (WAL write/checkpoint lock contention \u2014 assistant answers may transiently not surface this read)`
48815
48875
  );
48816
48876
  return null;
48817
48877
  }
48818
48878
  LOG.debug(
48819
48879
  "NativeHistory",
48820
- `antigravity .db ${path31.basename(filePath)} not readable: ${err instanceof Error ? err.message : String(err)}`
48880
+ `antigravity .db ${path32.basename(filePath)} not readable: ${err instanceof Error ? err.message : String(err)}`
48821
48881
  );
48822
48882
  return null;
48823
48883
  } finally {
@@ -48844,12 +48904,12 @@ function parseConversationDb(filePath, sessionId, workspace) {
48844
48904
  content = recovered;
48845
48905
  LOG.debug(
48846
48906
  "NativeHistory",
48847
- `antigravity .db ${path31.basename(filePath)} step ${row.idx} (type ${row.step_type}): user prompt absent at field 19; recovered ${content.length} chars via printable-run fallback \u2014 possible step_payload schema drift`
48907
+ `antigravity .db ${path32.basename(filePath)} step ${row.idx} (type ${row.step_type}): user prompt absent at field 19; recovered ${content.length} chars via printable-run fallback \u2014 possible step_payload schema drift`
48848
48908
  );
48849
48909
  } else {
48850
48910
  LOG.debug(
48851
48911
  "NativeHistory",
48852
- `antigravity .db ${path31.basename(filePath)} step ${row.idx} (type ${row.step_type}) dropped: no user prompt text (payload ${payload.length}B, top-level fields [${topLevelFieldNumbers(payload).join(",")}])`
48912
+ `antigravity .db ${path32.basename(filePath)} step ${row.idx} (type ${row.step_type}) dropped: no user prompt text (payload ${payload.length}B, top-level fields [${topLevelFieldNumbers(payload).join(",")}])`
48853
48913
  );
48854
48914
  continue;
48855
48915
  }
@@ -48874,12 +48934,12 @@ function parseConversationDb(filePath, sessionId, workspace) {
48874
48934
  content = recovered;
48875
48935
  LOG.debug(
48876
48936
  "NativeHistory",
48877
- `antigravity .db ${path31.basename(filePath)} step ${row.idx} (type ${row.step_type}): answer absent at field 20; recovered ${content.length} chars via printable-run fallback \u2014 possible step_payload schema drift`
48937
+ `antigravity .db ${path32.basename(filePath)} step ${row.idx} (type ${row.step_type}): answer absent at field 20; recovered ${content.length} chars via printable-run fallback \u2014 possible step_payload schema drift`
48878
48938
  );
48879
48939
  } else {
48880
48940
  LOG.debug(
48881
48941
  "NativeHistory",
48882
- `antigravity .db ${path31.basename(filePath)} step ${row.idx} (type ${row.step_type}) dropped: no answer text (payload ${payload.length}B, top-level fields [${topLevelFieldNumbers(payload).join(",")}], reasoningOnly=${reasoning ? "yes" : "no"})`
48942
+ `antigravity .db ${path32.basename(filePath)} step ${row.idx} (type ${row.step_type}) dropped: no answer text (payload ${payload.length}B, top-level fields [${topLevelFieldNumbers(payload).join(",")}], reasoningOnly=${reasoning ? "yes" : "no"})`
48883
48943
  );
48884
48944
  continue;
48885
48945
  }
@@ -48900,13 +48960,13 @@ function parseConversationDb(filePath, sessionId, workspace) {
48900
48960
  return messages.length > 0 ? messages : null;
48901
48961
  }
48902
48962
  function readSession3(sessionPath, sessionId, workspace) {
48903
- if (!sessionPath || !path31.isAbsolute(sessionPath)) return null;
48904
- if (!fs22.existsSync(sessionPath)) return null;
48963
+ if (!sessionPath || !path32.isAbsolute(sessionPath)) return null;
48964
+ if (!fs23.existsSync(sessionPath)) return null;
48905
48965
  const sourceMtimeMs = statMtimeMs3(sessionPath);
48906
48966
  const brainRootPath = brainRoot();
48907
- if (sessionPath.startsWith(brainRootPath + path31.sep) && sessionPath.endsWith(".jsonl")) {
48967
+ if (sessionPath.startsWith(brainRootPath + path32.sep) && sessionPath.endsWith(".jsonl")) {
48908
48968
  const relative5 = sessionPath.slice(brainRootPath.length + 1);
48909
- const uuidFromPath = relative5.split(path31.sep)[0];
48969
+ const uuidFromPath = relative5.split(path32.sep)[0];
48910
48970
  const resolvedSessionId = sessionId || (isUuidLike(uuidFromPath) ? uuidFromPath : "");
48911
48971
  if (!resolvedSessionId) return null;
48912
48972
  const messages = parseBrainTranscript(sessionPath, resolvedSessionId, workspace);
@@ -48922,7 +48982,7 @@ function readSession3(sessionPath, sessionId, workspace) {
48922
48982
  };
48923
48983
  }
48924
48984
  if (sessionPath.endsWith(".db")) {
48925
- const dbSessionId = sessionId || path31.basename(sessionPath, ".db");
48985
+ const dbSessionId = sessionId || path32.basename(sessionPath, ".db");
48926
48986
  if (!isUuidLike(dbSessionId)) return null;
48927
48987
  const messages = parseConversationDb(sessionPath, dbSessionId, workspace);
48928
48988
  if (!messages || messages.length === 0) return null;
@@ -48937,7 +48997,7 @@ function readSession3(sessionPath, sessionId, workspace) {
48937
48997
  };
48938
48998
  }
48939
48999
  if (sessionPath.endsWith(".pb")) {
48940
- const pbSessionId = sessionId || path31.basename(sessionPath, ".pb");
49000
+ const pbSessionId = sessionId || path32.basename(sessionPath, ".pb");
48941
49001
  if (!isUuidLike(pbSessionId)) return null;
48942
49002
  const messages = parsePbFile(sessionPath, pbSessionId);
48943
49003
  if (!messages || messages.length === 0) return null;
@@ -48951,7 +49011,7 @@ function readSession3(sessionPath, sessionId, workspace) {
48951
49011
  partialReason: "antigravity_cli_pb_raw_text_extraction"
48952
49012
  };
48953
49013
  }
48954
- if (path31.basename(sessionPath) === "history.jsonl") {
49014
+ if (path32.basename(sessionPath) === "history.jsonl") {
48955
49015
  const resolvedSessionId = sessionId || "";
48956
49016
  if (!resolvedSessionId || !isUuidLike(resolvedSessionId)) return null;
48957
49017
  const rows = readHistoryRows().filter((r) => r.conversationId === resolvedSessionId);
@@ -48998,21 +49058,21 @@ function readSession3(sessionPath, sessionId, workspace) {
48998
49058
  }
48999
49059
 
49000
49060
  // src/providers/native-history/hermes-cli-transcript.ts
49001
- var fs23 = __toESM(require("fs"));
49002
- var path32 = __toESM(require("path"));
49003
- var os23 = __toESM(require("os"));
49061
+ var fs24 = __toESM(require("fs"));
49062
+ var path33 = __toESM(require("path"));
49063
+ var os24 = __toESM(require("os"));
49004
49064
  init_load_better_sqlite3();
49005
- var HERMES_STATE_DB = path32.join(os23.homedir(), ".hermes", "state.db");
49006
- var HERMES_LEGACY_SESSIONS_DIR = path32.join(os23.homedir(), ".hermes", "sessions");
49065
+ var HERMES_STATE_DB = path33.join(os24.homedir(), ".hermes", "state.db");
49066
+ var HERMES_LEGACY_SESSIONS_DIR = path33.join(os24.homedir(), ".hermes", "sessions");
49007
49067
  function statMtimeMs4(p) {
49008
49068
  try {
49009
- return Math.floor(fs23.statSync(p).mtimeMs);
49069
+ return Math.floor(fs24.statSync(p).mtimeMs);
49010
49070
  } catch {
49011
49071
  return 0;
49012
49072
  }
49013
49073
  }
49014
49074
  function openDb() {
49015
- if (!fs23.existsSync(HERMES_STATE_DB)) return null;
49075
+ if (!fs24.existsSync(HERMES_STATE_DB)) return null;
49016
49076
  try {
49017
49077
  const Database = loadBetterSqlite3();
49018
49078
  return new Database(HERMES_STATE_DB, { readonly: true, fileMustExist: true });
@@ -49108,10 +49168,10 @@ function readSession4(sessionPath, requestedSessionId) {
49108
49168
  }
49109
49169
  }
49110
49170
  }
49111
- if (!path32.isAbsolute(sessionPath) || !fs23.existsSync(sessionPath)) return null;
49171
+ if (!path33.isAbsolute(sessionPath) || !fs24.existsSync(sessionPath)) return null;
49112
49172
  let raw;
49113
49173
  try {
49114
- raw = JSON.parse(fs23.readFileSync(sessionPath, "utf8"));
49174
+ raw = JSON.parse(fs24.readFileSync(sessionPath, "utf8"));
49115
49175
  } catch {
49116
49176
  return null;
49117
49177
  }
@@ -49134,7 +49194,7 @@ function readSession4(sessionPath, requestedSessionId) {
49134
49194
  });
49135
49195
  }
49136
49196
  if (messages.length === 0) return null;
49137
- const sessionId = typeof raw.session_id === "string" && raw.session_id ? raw.session_id : path32.basename(sessionPath, ".json").replace(/^session_/, "");
49197
+ const sessionId = typeof raw.session_id === "string" && raw.session_id ? raw.session_id : path33.basename(sessionPath, ".json").replace(/^session_/, "");
49138
49198
  return {
49139
49199
  messages,
49140
49200
  providerSessionId: sessionId,
@@ -49164,7 +49224,7 @@ function createNativeHistoryDispatcher(reader) {
49164
49224
  if (!sourcePath) return null;
49165
49225
  if (input.forceRefresh === true || input.args?.forceRefresh === true) {
49166
49226
  try {
49167
- fs24.statSync(sourcePath);
49227
+ fs25.statSync(sourcePath);
49168
49228
  } catch {
49169
49229
  }
49170
49230
  }
@@ -49201,11 +49261,11 @@ function resolveSourcePath(reader, workspace, sessionId, sessionStartedAtMs, ins
49201
49261
  }
49202
49262
  }
49203
49263
  function resolveClaudePath(workspace, sessionId) {
49204
- const dir = path33.join(os24.homedir(), ".claude", "projects", cwdAsDashes(workspace));
49205
- if (!fs24.existsSync(dir)) return null;
49264
+ const dir = path34.join(os25.homedir(), ".claude", "projects", cwdAsDashes(workspace));
49265
+ if (!fs25.existsSync(dir)) return null;
49206
49266
  if (sessionId) {
49207
- const candidate = path33.join(dir, `${sessionId}.jsonl`);
49208
- if (fs24.existsSync(candidate)) return candidate;
49267
+ const candidate = path34.join(dir, `${sessionId}.jsonl`);
49268
+ if (fs25.existsSync(candidate)) return candidate;
49209
49269
  }
49210
49270
  return null;
49211
49271
  }
@@ -49217,7 +49277,7 @@ function resolveCodexPath(workspace, sessionId, sessionStartedAtMs) {
49217
49277
  return findCodexPathByRuntime(root, workspace, sessionStartedAtMs);
49218
49278
  }
49219
49279
  function findCodexPathBySessionId(root, sessionId) {
49220
- if (!fs24.existsSync(root)) return null;
49280
+ if (!fs25.existsSync(root)) return null;
49221
49281
  const needle = sessionId.toLowerCase();
49222
49282
  const matches = [];
49223
49283
  const stack = [root];
@@ -49225,12 +49285,12 @@ function findCodexPathBySessionId(root, sessionId) {
49225
49285
  const current = stack.pop();
49226
49286
  let entries = [];
49227
49287
  try {
49228
- entries = fs24.readdirSync(current, { withFileTypes: true });
49288
+ entries = fs25.readdirSync(current, { withFileTypes: true });
49229
49289
  } catch {
49230
49290
  continue;
49231
49291
  }
49232
49292
  for (const entry of entries) {
49233
- const entryPath = path33.join(current, entry.name);
49293
+ const entryPath = path34.join(current, entry.name);
49234
49294
  if (entry.isDirectory()) {
49235
49295
  stack.push(entryPath);
49236
49296
  continue;
@@ -49245,7 +49305,7 @@ function findCodexPathBySessionId(root, sessionId) {
49245
49305
  return matches[0]?.p ?? null;
49246
49306
  }
49247
49307
  function findCodexPathByRuntime(root, workspace, sessionStartedAtMs) {
49248
- if (!fs24.existsSync(root) || !workspace) return null;
49308
+ if (!fs25.existsSync(root) || !workspace) return null;
49249
49309
  const workspaceResolved = resolveRealPath(workspace);
49250
49310
  const cutoff = Date.now() - RECENT_WINDOW_MS;
49251
49311
  const matches = [];
@@ -49254,12 +49314,12 @@ function findCodexPathByRuntime(root, workspace, sessionStartedAtMs) {
49254
49314
  const current = stack.pop();
49255
49315
  let entries = [];
49256
49316
  try {
49257
- entries = fs24.readdirSync(current, { withFileTypes: true });
49317
+ entries = fs25.readdirSync(current, { withFileTypes: true });
49258
49318
  } catch {
49259
49319
  continue;
49260
49320
  }
49261
49321
  for (const entry of entries) {
49262
- const entryPath = path33.join(current, entry.name);
49322
+ const entryPath = path34.join(current, entry.name);
49263
49323
  if (entry.isDirectory()) {
49264
49324
  stack.push(entryPath);
49265
49325
  continue;
@@ -49279,10 +49339,10 @@ function findCodexPathByRuntime(root, workspace, sessionStartedAtMs) {
49279
49339
  }
49280
49340
  function readCodexSessionMeta(filePath) {
49281
49341
  try {
49282
- const fd = fs24.openSync(filePath, "r");
49342
+ const fd = fs25.openSync(filePath, "r");
49283
49343
  try {
49284
49344
  const buffer = Buffer.alloc(8192);
49285
- const bytes = fs24.readSync(fd, buffer, 0, buffer.length, 0);
49345
+ const bytes = fs25.readSync(fd, buffer, 0, buffer.length, 0);
49286
49346
  if (bytes <= 0) return null;
49287
49347
  const text = buffer.subarray(0, bytes).toString("utf8");
49288
49348
  const firstLine = text.slice(0, text.indexOf("\n") >= 0 ? text.indexOf("\n") : text.length).trim();
@@ -49297,7 +49357,7 @@ function readCodexSessionMeta(filePath) {
49297
49357
  timestampMs: Number.isFinite(timestampMs) ? timestampMs : void 0
49298
49358
  };
49299
49359
  } finally {
49300
- fs24.closeSync(fd);
49360
+ fs25.closeSync(fd);
49301
49361
  }
49302
49362
  } catch {
49303
49363
  return null;
@@ -49305,35 +49365,35 @@ function readCodexSessionMeta(filePath) {
49305
49365
  }
49306
49366
  function resolveRealPath(value) {
49307
49367
  try {
49308
- return fs24.realpathSync(value);
49368
+ return fs25.realpathSync(value);
49309
49369
  } catch {
49310
49370
  return value;
49311
49371
  }
49312
49372
  }
49313
49373
  var AGY_SPAWN_CLAIM_GRACE_MS = 2e3;
49314
49374
  function resolveAntigravityPath(workspace, sessionId, sessionStartedAtMs, instanceId) {
49315
- const agyRoot = path33.join(os24.homedir(), ".gemini", "antigravity-cli");
49375
+ const agyRoot = path34.join(os25.homedir(), ".gemini", "antigravity-cli");
49316
49376
  const owner = antigravityOwnerToken(workspace, sessionStartedAtMs, instanceId);
49317
49377
  if (sessionId && isUuidLikeSessionId2(sessionId)) {
49318
- const dbPath = path33.join(agyRoot, "conversations", `${sessionId}.db`);
49319
- if (fs24.existsSync(dbPath)) {
49378
+ const dbPath = path34.join(agyRoot, "conversations", `${sessionId}.db`);
49379
+ if (fs25.existsSync(dbPath)) {
49320
49380
  if (owner) claimAntigravityConversation(sessionId, owner);
49321
49381
  return dbPath;
49322
49382
  }
49323
49383
  }
49324
- const brainRoot2 = path33.join(agyRoot, "brain");
49325
- if (fs24.existsSync(brainRoot2)) {
49384
+ const brainRoot2 = path34.join(agyRoot, "brain");
49385
+ if (fs25.existsSync(brainRoot2)) {
49326
49386
  const cutoff = spawnAwareCutoff(sessionStartedAtMs);
49327
- const entries = fs24.readdirSync(brainRoot2, { withFileTypes: true }).filter((e) => e.isDirectory() && isUuidLikeSessionId2(e.name)).filter((e) => !isAntigravityConversationClaimedByOther(e.name, owner)).map((e) => ({ uuid: e.name, p: path33.join(brainRoot2, e.name), mtime: safeMtime(path33.join(brainRoot2, e.name)) })).filter((e) => e.mtime >= cutoff).sort((a, b) => b.mtime - a.mtime);
49387
+ const entries = fs25.readdirSync(brainRoot2, { withFileTypes: true }).filter((e) => e.isDirectory() && isUuidLikeSessionId2(e.name)).filter((e) => !isAntigravityConversationClaimedByOther(e.name, owner)).map((e) => ({ uuid: e.name, p: path34.join(brainRoot2, e.name), mtime: safeMtime(path34.join(brainRoot2, e.name)) })).filter((e) => e.mtime >= cutoff).sort((a, b) => b.mtime - a.mtime);
49328
49388
  for (const e of entries) {
49329
- const t = path33.join(e.p, ".system_generated", "logs", "transcript.jsonl");
49330
- if (fs24.existsSync(t) && safeSize(t) > 0) {
49389
+ const t = path34.join(e.p, ".system_generated", "logs", "transcript.jsonl");
49390
+ if (fs25.existsSync(t) && safeSize(t) > 0) {
49331
49391
  if (owner) claimAntigravityConversation(e.uuid, owner);
49332
49392
  return t;
49333
49393
  }
49334
49394
  }
49335
49395
  }
49336
- const convRoot = path33.join(agyRoot, "conversations");
49396
+ const convRoot = path34.join(agyRoot, "conversations");
49337
49397
  const picked = pickUnboundConversationDb(convRoot, sessionStartedAtMs, owner);
49338
49398
  if (picked) {
49339
49399
  if (owner) claimAntigravityConversation(picked.uuid, owner);
@@ -49344,7 +49404,7 @@ function resolveAntigravityPath(workspace, sessionId, sessionStartedAtMs, instan
49344
49404
  function pickUnboundConversationDb(convRoot, sessionFloorMs, owner) {
49345
49405
  let entries = [];
49346
49406
  try {
49347
- entries = fs24.readdirSync(convRoot, { withFileTypes: true });
49407
+ entries = fs25.readdirSync(convRoot, { withFileTypes: true });
49348
49408
  } catch {
49349
49409
  return null;
49350
49410
  }
@@ -49356,7 +49416,7 @@ function pickUnboundConversationDb(convRoot, sessionFloorMs, owner) {
49356
49416
  if (!match || !isUuidLikeSessionId2(match[1])) continue;
49357
49417
  const uuid = match[1];
49358
49418
  if (isAntigravityConversationClaimedByOther(uuid, owner)) continue;
49359
- const p = path33.join(convRoot, entry.name);
49419
+ const p = path34.join(convRoot, entry.name);
49360
49420
  const mtime = safeMtime(p);
49361
49421
  if (mtime < recencyCutoff) continue;
49362
49422
  candidates.push({ path: p, uuid, mtime, birth: safeBirthtime(p) });
@@ -49380,10 +49440,10 @@ function spawnAwareCutoff(sessionStartedAtMs) {
49380
49440
  function resolveHermesPath(workspace, sessionId) {
49381
49441
  void workspace;
49382
49442
  void sessionId;
49383
- const dbPath = path33.join(os24.homedir(), ".hermes", "state.db");
49384
- if (fs24.existsSync(dbPath)) return dbPath;
49385
- const dir = path33.join(os24.homedir(), ".hermes", "sessions");
49386
- if (!fs24.existsSync(dir)) return null;
49443
+ const dbPath = path34.join(os25.homedir(), ".hermes", "state.db");
49444
+ if (fs25.existsSync(dbPath)) return dbPath;
49445
+ const dir = path34.join(os25.homedir(), ".hermes", "sessions");
49446
+ if (!fs25.existsSync(dir)) return null;
49387
49447
  return newestRecentFile2(dir, /^session_.*\.json$/);
49388
49448
  }
49389
49449
  function readByReader(reader, sourcePath, sessionId, workspace, requestedProviderSid) {
@@ -49408,7 +49468,7 @@ function cwdAsDashes(cwd) {
49408
49468
  return cwd.replace(/\//g, "-");
49409
49469
  }
49410
49470
  function codexSessionsRoot() {
49411
- return path33.join(os24.homedir(), ".codex", "sessions");
49471
+ return path34.join(os25.homedir(), ".codex", "sessions");
49412
49472
  }
49413
49473
  function isUuidLikeSessionId2(sessionId) {
49414
49474
  return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sessionId);
@@ -49420,7 +49480,7 @@ var RECENT_WINDOW_MS = 5 * 60 * 1e3;
49420
49480
  function newestRecentFile2(dir, pattern) {
49421
49481
  try {
49422
49482
  const cutoff = Date.now() - RECENT_WINDOW_MS;
49423
- const entries = fs24.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile() && pattern.test(e.name)).map((e) => ({ p: path33.join(dir, e.name), mtime: safeMtime(path33.join(dir, e.name)) })).filter((e) => e.mtime >= cutoff).sort((a, b) => b.mtime - a.mtime);
49483
+ const entries = fs25.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile() && pattern.test(e.name)).map((e) => ({ p: path34.join(dir, e.name), mtime: safeMtime(path34.join(dir, e.name)) })).filter((e) => e.mtime >= cutoff).sort((a, b) => b.mtime - a.mtime);
49424
49484
  return entries[0]?.p ?? null;
49425
49485
  } catch {
49426
49486
  return null;
@@ -49428,14 +49488,14 @@ function newestRecentFile2(dir, pattern) {
49428
49488
  }
49429
49489
  function safeMtime(p) {
49430
49490
  try {
49431
- return Math.floor(fs24.statSync(p).mtimeMs);
49491
+ return Math.floor(fs25.statSync(p).mtimeMs);
49432
49492
  } catch {
49433
49493
  return 0;
49434
49494
  }
49435
49495
  }
49436
49496
  function safeBirthtime(p) {
49437
49497
  try {
49438
- const st = fs24.statSync(p);
49498
+ const st = fs25.statSync(p);
49439
49499
  const birth = Math.floor(st.birthtimeMs);
49440
49500
  return birth > 0 ? birth : Math.floor(st.mtimeMs);
49441
49501
  } catch {
@@ -49444,7 +49504,7 @@ function safeBirthtime(p) {
49444
49504
  }
49445
49505
  function safeSize(p) {
49446
49506
  try {
49447
- return fs24.statSync(p).size;
49507
+ return fs25.statSync(p).size;
49448
49508
  } catch {
49449
49509
  return 0;
49450
49510
  }
@@ -49538,9 +49598,9 @@ var ProviderLoader = class _ProviderLoader {
49538
49598
  static siblingStderrLogged = /* @__PURE__ */ new Set();
49539
49599
  static looksLikeProviderRoot(candidate) {
49540
49600
  try {
49541
- if (!fs25.existsSync(candidate) || !fs25.statSync(candidate).isDirectory()) return false;
49601
+ if (!fs26.existsSync(candidate) || !fs26.statSync(candidate).isDirectory()) return false;
49542
49602
  return ["ide", "extension", "cli", "acp"].some(
49543
- (category) => fs25.existsSync(path35.join(candidate, category))
49603
+ (category) => fs26.existsSync(path36.join(candidate, category))
49544
49604
  );
49545
49605
  } catch {
49546
49606
  return false;
@@ -49548,20 +49608,20 @@ var ProviderLoader = class _ProviderLoader {
49548
49608
  }
49549
49609
  static hasProviderRootMarker(candidate) {
49550
49610
  try {
49551
- return fs25.existsSync(path35.join(candidate, _ProviderLoader.SIBLING_MARKER_FILE));
49611
+ return fs26.existsSync(path36.join(candidate, _ProviderLoader.SIBLING_MARKER_FILE));
49552
49612
  } catch {
49553
49613
  return false;
49554
49614
  }
49555
49615
  }
49556
49616
  detectDefaultUserDir() {
49557
- const fallback = path35.join(os25.homedir(), ".adhdev", "providers");
49617
+ const fallback = path36.join(os26.homedir(), ".adhdev", "providers");
49558
49618
  const envOptIn = process.env[_ProviderLoader.SIBLING_ENV_VAR] === "1";
49559
49619
  const visited = /* @__PURE__ */ new Set();
49560
49620
  for (const start of this.probeStarts) {
49561
- let current = path35.resolve(start);
49621
+ let current = path36.resolve(start);
49562
49622
  while (!visited.has(current)) {
49563
49623
  visited.add(current);
49564
- const siblingCandidate = path35.join(path35.dirname(current), _ProviderLoader.REPO_PROVIDER_DIRNAME);
49624
+ const siblingCandidate = path36.join(path36.dirname(current), _ProviderLoader.REPO_PROVIDER_DIRNAME);
49565
49625
  if (_ProviderLoader.looksLikeProviderRoot(siblingCandidate)) {
49566
49626
  const hasMarker = _ProviderLoader.hasProviderRootMarker(siblingCandidate);
49567
49627
  if (envOptIn || hasMarker) {
@@ -49583,7 +49643,7 @@ var ProviderLoader = class _ProviderLoader {
49583
49643
  return { path: siblingCandidate, source };
49584
49644
  }
49585
49645
  }
49586
- const parent = path35.dirname(current);
49646
+ const parent = path36.dirname(current);
49587
49647
  if (parent === current) break;
49588
49648
  current = parent;
49589
49649
  }
@@ -49595,11 +49655,11 @@ var ProviderLoader = class _ProviderLoader {
49595
49655
  this.probeStarts = options?.probeStarts ?? [process.cwd(), __dirname];
49596
49656
  this.registryBaseUrl = resolveRegistryBaseUrl(options?.registryUrl);
49597
49657
  this.providerTarballUrl = resolveProviderTarballUrl(options?.providerTarballUrl);
49598
- this.defaultProvidersDir = path35.join(os25.homedir(), ".adhdev", "providers");
49658
+ this.defaultProvidersDir = path36.join(os26.homedir(), ".adhdev", "providers");
49599
49659
  const detected = this.detectDefaultUserDir();
49600
49660
  this.userDir = detected.path;
49601
49661
  this.userDirSource = detected.source;
49602
- this.upstreamDir = path35.join(this.defaultProvidersDir, ".upstream");
49662
+ this.upstreamDir = path36.join(this.defaultProvidersDir, ".upstream");
49603
49663
  this.disableUpstream = false;
49604
49664
  this.applySourceConfig({
49605
49665
  userDir: options?.userDir,
@@ -49610,15 +49670,15 @@ var ProviderLoader = class _ProviderLoader {
49610
49670
  }
49611
49671
  migrateMarketplaceDirToExternal() {
49612
49672
  try {
49613
- const home = os25.homedir();
49614
- const oldDir = path35.join(home, ".adhdev", "marketplace");
49615
- const newDir = path35.join(home, ".adhdev", "external");
49616
- if (!fs25.existsSync(oldDir)) return;
49617
- if (fs25.existsSync(newDir)) {
49673
+ const home = os26.homedir();
49674
+ const oldDir = path36.join(home, ".adhdev", "marketplace");
49675
+ const newDir = path36.join(home, ".adhdev", "external");
49676
+ if (!fs26.existsSync(oldDir)) return;
49677
+ if (fs26.existsSync(newDir)) {
49618
49678
  this.log(`Migration skipped: both ~/.adhdev/marketplace and ~/.adhdev/external exist (marketplace dir is now inert and can be removed manually).`);
49619
49679
  return;
49620
49680
  }
49621
- fs25.renameSync(oldDir, newDir);
49681
+ fs26.renameSync(oldDir, newDir);
49622
49682
  this.log(`Migrated ~/.adhdev/marketplace \u2192 ~/.adhdev/external (one-time rename after provider source-layer cleanup).`);
49623
49683
  } catch (e) {
49624
49684
  this.log(`Marketplace\u2192external migration failed: ${e?.message || e}`);
@@ -49648,7 +49708,7 @@ var ProviderLoader = class _ProviderLoader {
49648
49708
  * Highest-priority editable overrides come first.
49649
49709
  */
49650
49710
  getProviderRoots() {
49651
- const externalDir = path35.join(os25.homedir(), ".adhdev", "external");
49711
+ const externalDir = path36.join(os26.homedir(), ".adhdev", "external");
49652
49712
  return [this.userDir, externalDir, this.upstreamDir];
49653
49713
  }
49654
49714
  getSourceConfig() {
@@ -49676,7 +49736,7 @@ var ProviderLoader = class _ProviderLoader {
49676
49736
  this.userDir = detected.path;
49677
49737
  this.userDirSource = detected.source;
49678
49738
  }
49679
- this.upstreamDir = path35.join(this.defaultProvidersDir, ".upstream");
49739
+ this.upstreamDir = path36.join(this.defaultProvidersDir, ".upstream");
49680
49740
  this.disableUpstream = this.sourceMode === "no-upstream";
49681
49741
  if (this.explicitProviderDir) {
49682
49742
  this.log(`Config 'providerDir' applied: ${this.userDir}`);
@@ -49690,7 +49750,7 @@ var ProviderLoader = class _ProviderLoader {
49690
49750
  * Canonical provider directory shape for a given root.
49691
49751
  */
49692
49752
  getProviderDir(root, category, type) {
49693
- return path35.join(root, category, type);
49753
+ return path36.join(root, category, type);
49694
49754
  }
49695
49755
  /**
49696
49756
  * Canonical user override directory for a provider.
@@ -49717,7 +49777,7 @@ var ProviderLoader = class _ProviderLoader {
49717
49777
  resolveProviderFile(type, ...segments) {
49718
49778
  const dir = this.findProviderDirInternal(type);
49719
49779
  if (!dir) return null;
49720
- return path35.join(dir, ...segments);
49780
+ return path36.join(dir, ...segments);
49721
49781
  }
49722
49782
  /**
49723
49783
  * Load all providers (3-tier priority)
@@ -49733,7 +49793,7 @@ var ProviderLoader = class _ProviderLoader {
49733
49793
  this.providers.clear();
49734
49794
  this.providerAvailability.clear();
49735
49795
  let upstreamCount = 0;
49736
- if (!this.disableUpstream && fs25.existsSync(this.upstreamDir)) {
49796
+ if (!this.disableUpstream && fs26.existsSync(this.upstreamDir)) {
49737
49797
  upstreamCount = this.loadDir(this.upstreamDir);
49738
49798
  if (upstreamCount > 0) {
49739
49799
  this.log(`Loaded ${upstreamCount} upstream providers (auto-updated)`);
@@ -49741,11 +49801,11 @@ var ProviderLoader = class _ProviderLoader {
49741
49801
  } else if (this.disableUpstream) {
49742
49802
  this.log("Upstream loading disabled (sourceMode=no-upstream)");
49743
49803
  }
49744
- const externalDir = path35.join(os25.homedir(), ".adhdev", "external");
49745
- if (fs25.existsSync(externalDir)) {
49804
+ const externalDir = path36.join(os26.homedir(), ".adhdev", "external");
49805
+ if (fs26.existsSync(externalDir)) {
49746
49806
  const rootEntries = (() => {
49747
49807
  try {
49748
- return fs25.readdirSync(externalDir, { withFileTypes: true });
49808
+ return fs26.readdirSync(externalDir, { withFileTypes: true });
49749
49809
  } catch {
49750
49810
  return [];
49751
49811
  }
@@ -49763,7 +49823,7 @@ var ProviderLoader = class _ProviderLoader {
49763
49823
  const ambiguousTypes = [];
49764
49824
  for (const sourceEntry of rootEntries) {
49765
49825
  if (!sourceEntry.isDirectory()) continue;
49766
- const sourceDir = path35.join(externalDir, sourceEntry.name);
49826
+ const sourceDir = path36.join(externalDir, sourceEntry.name);
49767
49827
  const sourceLoaded = this.loadDir(sourceDir);
49768
49828
  if (sourceLoaded > 0) {
49769
49829
  totalLoaded += sourceLoaded;
@@ -49779,7 +49839,7 @@ var ProviderLoader = class _ProviderLoader {
49779
49839
  ambiguousTypes.push({ type, chosen: resolved.source ?? "?", candidates: resolved.candidates });
49780
49840
  }
49781
49841
  if (resolved.source && resolved.source !== "?") {
49782
- const sourceDir = path35.join(externalDir, resolved.source);
49842
+ const sourceDir = path36.join(externalDir, resolved.source);
49783
49843
  const reloadCount = this.loadDir(sourceDir);
49784
49844
  if (reloadCount === 0) {
49785
49845
  this.log(`Active source "${resolved.source}" no longer provides ${type}`);
@@ -49794,7 +49854,7 @@ var ProviderLoader = class _ProviderLoader {
49794
49854
  }
49795
49855
  }
49796
49856
  }
49797
- if (fs25.existsSync(this.userDir)) {
49857
+ if (fs26.existsSync(this.userDir)) {
49798
49858
  const userCount = this.loadDir(this.userDir, [".upstream"]);
49799
49859
  if (userCount > 0) {
49800
49860
  this.log(`Loaded ${userCount} user custom providers (never auto-updated)`);
@@ -49809,10 +49869,10 @@ var ProviderLoader = class _ProviderLoader {
49809
49869
  * Check if upstream directory exists and has providers.
49810
49870
  */
49811
49871
  hasUpstream() {
49812
- if (!fs25.existsSync(this.upstreamDir)) return false;
49872
+ if (!fs26.existsSync(this.upstreamDir)) return false;
49813
49873
  try {
49814
- return fs25.readdirSync(this.upstreamDir).some(
49815
- (d) => fs25.statSync(path35.join(this.upstreamDir, d)).isDirectory()
49874
+ return fs26.readdirSync(this.upstreamDir).some(
49875
+ (d) => fs26.statSync(path36.join(this.upstreamDir, d)).isDirectory()
49816
49876
  );
49817
49877
  } catch {
49818
49878
  return false;
@@ -50310,8 +50370,8 @@ var ProviderLoader = class _ProviderLoader {
50310
50370
  resolved._resolvedScriptDir = entry.scriptDir;
50311
50371
  resolved._resolvedScriptsSource = `compatibility:${entry.ideVersion}`;
50312
50372
  if (providerDir) {
50313
- const fullDir = path35.join(providerDir, entry.scriptDir);
50314
- resolved._resolvedScriptsPath = fs25.existsSync(path35.join(fullDir, "scripts.js")) ? path35.join(fullDir, "scripts.js") : fullDir;
50373
+ const fullDir = path36.join(providerDir, entry.scriptDir);
50374
+ resolved._resolvedScriptsPath = fs26.existsSync(path36.join(fullDir, "scripts.js")) ? path36.join(fullDir, "scripts.js") : fullDir;
50315
50375
  }
50316
50376
  matched = true;
50317
50377
  }
@@ -50329,8 +50389,8 @@ var ProviderLoader = class _ProviderLoader {
50329
50389
  resolved._resolvedScriptDir = base.defaultScriptDir;
50330
50390
  resolved._resolvedScriptsSource = "defaultScriptDir:version_miss";
50331
50391
  if (providerDir) {
50332
- const fullDir = path35.join(providerDir, base.defaultScriptDir);
50333
- resolved._resolvedScriptsPath = fs25.existsSync(path35.join(fullDir, "scripts.js")) ? path35.join(fullDir, "scripts.js") : fullDir;
50392
+ const fullDir = path36.join(providerDir, base.defaultScriptDir);
50393
+ resolved._resolvedScriptsPath = fs26.existsSync(path36.join(fullDir, "scripts.js")) ? path36.join(fullDir, "scripts.js") : fullDir;
50334
50394
  }
50335
50395
  }
50336
50396
  resolved._versionWarning = `Version ${currentVersion} not in compatibility matrix. Using default scripts.`;
@@ -50347,8 +50407,8 @@ var ProviderLoader = class _ProviderLoader {
50347
50407
  resolved._resolvedScriptDir = dirOverride;
50348
50408
  resolved._resolvedScriptsSource = `versions:${range}`;
50349
50409
  if (providerDir) {
50350
- const fullDir = path35.join(providerDir, dirOverride);
50351
- resolved._resolvedScriptsPath = fs25.existsSync(path35.join(fullDir, "scripts.js")) ? path35.join(fullDir, "scripts.js") : fullDir;
50410
+ const fullDir = path36.join(providerDir, dirOverride);
50411
+ resolved._resolvedScriptsPath = fs26.existsSync(path36.join(fullDir, "scripts.js")) ? path36.join(fullDir, "scripts.js") : fullDir;
50352
50412
  }
50353
50413
  }
50354
50414
  } else if (override.scripts) {
@@ -50364,8 +50424,8 @@ var ProviderLoader = class _ProviderLoader {
50364
50424
  resolved._resolvedScriptDir = base.defaultScriptDir;
50365
50425
  resolved._resolvedScriptsSource = "defaultScriptDir:no_version";
50366
50426
  if (providerDir) {
50367
- const fullDir = path35.join(providerDir, base.defaultScriptDir);
50368
- resolved._resolvedScriptsPath = fs25.existsSync(path35.join(fullDir, "scripts.js")) ? path35.join(fullDir, "scripts.js") : fullDir;
50427
+ const fullDir = path36.join(providerDir, base.defaultScriptDir);
50428
+ resolved._resolvedScriptsPath = fs26.existsSync(path36.join(fullDir, "scripts.js")) ? path36.join(fullDir, "scripts.js") : fullDir;
50369
50429
  }
50370
50430
  }
50371
50431
  }
@@ -50382,13 +50442,13 @@ var ProviderLoader = class _ProviderLoader {
50382
50442
  if (providerDir2) {
50383
50443
  for (const [scriptName, override] of Object.entries(base.overrides)) {
50384
50444
  if (!override || typeof override.path !== "string") continue;
50385
- const fullPath = path35.join(providerDir2, override.path);
50386
- if (!fs25.existsSync(fullPath)) {
50445
+ const fullPath = path36.join(providerDir2, override.path);
50446
+ if (!fs26.existsSync(fullPath)) {
50387
50447
  this.log(` [overrides] ${base.type}: ${scriptName} path not found: ${fullPath}`);
50388
50448
  continue;
50389
50449
  }
50390
50450
  try {
50391
- registerProviderScriptRootSafely(path35.dirname(path35.dirname(providerDir2)));
50451
+ registerProviderScriptRootSafely(path36.dirname(path36.dirname(providerDir2)));
50392
50452
  delete require.cache[require.resolve(fullPath)];
50393
50453
  const fn = require(fullPath);
50394
50454
  const target = typeof fn === "function" ? fn : fn && fn[scriptName];
@@ -50413,25 +50473,25 @@ var ProviderLoader = class _ProviderLoader {
50413
50473
  }
50414
50474
  if (providerDir) {
50415
50475
  try {
50416
- const fs40 = require("fs");
50417
- const path44 = require("path");
50476
+ const fs41 = require("fs");
50477
+ const path45 = require("path");
50418
50478
  const candidates = [];
50419
50479
  if (Array.isArray(base.compatibility)) {
50420
50480
  for (const entry of base.compatibility) {
50421
50481
  if (typeof entry?.spec !== "string") continue;
50422
50482
  const matches = !entry.ideVersion || currentVersion && this.matchesVersion(currentVersion, entry.ideVersion) || !currentVersion;
50423
- if (matches) candidates.push(path44.join(providerDir, entry.spec));
50483
+ if (matches) candidates.push(path45.join(providerDir, entry.spec));
50424
50484
  }
50425
50485
  }
50426
- candidates.push(path44.join(providerDir, "specs", "default.json"));
50427
- candidates.push(path44.join(providerDir, "spec.json"));
50428
- const specPath = candidates.find((p) => fs40.existsSync(p));
50486
+ candidates.push(path45.join(providerDir, "specs", "default.json"));
50487
+ candidates.push(path45.join(providerDir, "spec.json"));
50488
+ const specPath = candidates.find((p) => fs41.existsSync(p));
50429
50489
  if (specPath) {
50430
50490
  resolved._resolvedSpecPath = specPath;
50431
50491
  let specControls;
50432
50492
  let nh;
50433
50493
  try {
50434
- const rawSpec = JSON.parse(fs40.readFileSync(specPath, "utf8"));
50494
+ const rawSpec = JSON.parse(fs41.readFileSync(specPath, "utf8"));
50435
50495
  specControls = rawSpec.control_bar;
50436
50496
  nh = rawSpec.native_history;
50437
50497
  } catch {
@@ -50462,10 +50522,10 @@ var ProviderLoader = class _ProviderLoader {
50462
50522
  format = `spec-${nh.source.kind}`;
50463
50523
  reader = (input) => executeNativeHistory(nh, input);
50464
50524
  } else if (nh.override_path) {
50465
- const overrideFile = path44.resolve(providerDir, nh.override_path);
50466
- if (fs40.existsSync(overrideFile)) {
50525
+ const overrideFile = path45.resolve(providerDir, nh.override_path);
50526
+ if (fs41.existsSync(overrideFile)) {
50467
50527
  try {
50468
- registerProviderScriptRootSafely(path44.dirname(path44.dirname(providerDir)));
50528
+ registerProviderScriptRootSafely(path45.dirname(path45.dirname(providerDir)));
50469
50529
  delete require.cache[require.resolve(overrideFile)];
50470
50530
  const mod = require(overrideFile);
50471
50531
  const fn = typeof mod === "function" ? mod : mod && typeof mod.default === "function" ? mod.default : null;
@@ -50508,16 +50568,16 @@ var ProviderLoader = class _ProviderLoader {
50508
50568
  this.debugLog(`[loadScriptsFromDir] ${type}: providerDir not found`);
50509
50569
  return null;
50510
50570
  }
50511
- const dir = path35.join(providerDir, scriptDir);
50512
- if (!fs25.existsSync(dir)) {
50571
+ const dir = path36.join(providerDir, scriptDir);
50572
+ if (!fs26.existsSync(dir)) {
50513
50573
  this.debugLog(`[loadScriptsFromDir] ${type}: dir not found: ${dir}`);
50514
50574
  return null;
50515
50575
  }
50516
- registerProviderScriptRootSafely(path35.dirname(path35.dirname(providerDir)));
50576
+ registerProviderScriptRootSafely(path36.dirname(path36.dirname(providerDir)));
50517
50577
  const cached3 = this.scriptsCache.get(dir);
50518
50578
  if (cached3) return cached3;
50519
- const scriptsJs = path35.join(dir, "scripts.js");
50520
- if (fs25.existsSync(scriptsJs)) {
50579
+ const scriptsJs = path36.join(dir, "scripts.js");
50580
+ if (fs26.existsSync(scriptsJs)) {
50521
50581
  try {
50522
50582
  delete require.cache[require.resolve(scriptsJs)];
50523
50583
  const loaded = require(scriptsJs);
@@ -50538,9 +50598,9 @@ var ProviderLoader = class _ProviderLoader {
50538
50598
  watch() {
50539
50599
  this.stopWatch();
50540
50600
  const watchDir = (dir) => {
50541
- if (!fs25.existsSync(dir)) {
50601
+ if (!fs26.existsSync(dir)) {
50542
50602
  try {
50543
- fs25.mkdirSync(dir, { recursive: true });
50603
+ fs26.mkdirSync(dir, { recursive: true });
50544
50604
  } catch {
50545
50605
  return;
50546
50606
  }
@@ -50561,7 +50621,7 @@ var ProviderLoader = class _ProviderLoader {
50561
50621
  if (filePath.endsWith(".js") || filePath.endsWith(".json")) {
50562
50622
  if (reloadTimer) clearTimeout(reloadTimer);
50563
50623
  reloadTimer = setTimeout(() => {
50564
- this.log(`File changed: ${path35.basename(filePath)}, reloading...`);
50624
+ this.log(`File changed: ${path36.basename(filePath)}, reloading...`);
50565
50625
  this.reload();
50566
50626
  }, 300);
50567
50627
  }
@@ -50629,11 +50689,11 @@ var ProviderLoader = class _ProviderLoader {
50629
50689
  }
50630
50690
  this.log(`Registry sync starting (${this.registryBaseUrl})...`);
50631
50691
  const https = require("https");
50632
- const regMetaPath = path35.join(this.upstreamDir, _ProviderLoader.REGISTRY_META_FILE);
50692
+ const regMetaPath = path36.join(this.upstreamDir, _ProviderLoader.REGISTRY_META_FILE);
50633
50693
  let cachedChecksums = {};
50634
50694
  try {
50635
- if (fs25.existsSync(regMetaPath)) {
50636
- cachedChecksums = JSON.parse(fs25.readFileSync(regMetaPath, "utf-8")).checksums ?? {};
50695
+ if (fs26.existsSync(regMetaPath)) {
50696
+ cachedChecksums = JSON.parse(fs26.readFileSync(regMetaPath, "utf-8")).checksums ?? {};
50637
50697
  }
50638
50698
  } catch {
50639
50699
  }
@@ -50684,15 +50744,15 @@ var ProviderLoader = class _ProviderLoader {
50684
50744
  this.log(`\u26A0 Registry checksum mismatch for ${type}@${version} \u2014 skipping`);
50685
50745
  continue;
50686
50746
  }
50687
- const providerDir = path35.join(this.upstreamDir, category, type);
50688
- fs25.mkdirSync(providerDir, { recursive: true });
50689
- fs25.writeFileSync(path35.join(providerDir, "provider.json"), manifestBody, "utf-8");
50747
+ const providerDir = path36.join(this.upstreamDir, category, type);
50748
+ fs26.mkdirSync(providerDir, { recursive: true });
50749
+ fs26.writeFileSync(path36.join(providerDir, "provider.json"), manifestBody, "utf-8");
50690
50750
  cachedChecksums[cacheKey] = checksum;
50691
50751
  updatedCount++;
50692
50752
  this.log(`\u2713 Registry updated: ${category}/${type}@${version}`);
50693
50753
  }
50694
- fs25.mkdirSync(this.upstreamDir, { recursive: true });
50695
- fs25.writeFileSync(regMetaPath, JSON.stringify({
50754
+ fs26.mkdirSync(this.upstreamDir, { recursive: true });
50755
+ fs26.writeFileSync(regMetaPath, JSON.stringify({
50696
50756
  checksums: cachedChecksums,
50697
50757
  syncedAt: (/* @__PURE__ */ new Date()).toISOString(),
50698
50758
  providerCount: list.providers.length
@@ -50713,12 +50773,12 @@ var ProviderLoader = class _ProviderLoader {
50713
50773
  const { exec: exec7 } = require("child_process");
50714
50774
  const { promisify: promisify8 } = require("util");
50715
50775
  const execAsync5 = promisify8(exec7);
50716
- const metaPath = path35.join(this.upstreamDir, _ProviderLoader.META_FILE);
50776
+ const metaPath = path36.join(this.upstreamDir, _ProviderLoader.META_FILE);
50717
50777
  let prevEtag = "";
50718
50778
  let prevTimestamp = 0;
50719
50779
  try {
50720
- if (fs25.existsSync(metaPath)) {
50721
- const meta = JSON.parse(fs25.readFileSync(metaPath, "utf-8"));
50780
+ if (fs26.existsSync(metaPath)) {
50781
+ const meta = JSON.parse(fs26.readFileSync(metaPath, "utf-8"));
50722
50782
  prevEtag = meta.etag || "";
50723
50783
  prevTimestamp = meta.timestamp || 0;
50724
50784
  }
@@ -50774,39 +50834,39 @@ var ProviderLoader = class _ProviderLoader {
50774
50834
  return { updated: false };
50775
50835
  }
50776
50836
  this.log("Downloading latest providers from GitHub...");
50777
- const tmpTar = path35.join(os25.tmpdir(), `adhdev-providers-${Date.now()}.tar.gz`);
50778
- const tmpExtract = path35.join(os25.tmpdir(), `adhdev-providers-extract-${Date.now()}`);
50837
+ const tmpTar = path36.join(os26.tmpdir(), `adhdev-providers-${Date.now()}.tar.gz`);
50838
+ const tmpExtract = path36.join(os26.tmpdir(), `adhdev-providers-extract-${Date.now()}`);
50779
50839
  await this.downloadFile(tarballTarget.url, tmpTar);
50780
- fs25.mkdirSync(tmpExtract, { recursive: true });
50840
+ fs26.mkdirSync(tmpExtract, { recursive: true });
50781
50841
  await execAsync5(`tar -xzf "${tmpTar}" -C "${tmpExtract}"`, { timeout: 3e4 });
50782
- const extracted = fs25.readdirSync(tmpExtract);
50842
+ const extracted = fs26.readdirSync(tmpExtract);
50783
50843
  const rootDir = extracted.find(
50784
- (d) => fs25.statSync(path35.join(tmpExtract, d)).isDirectory() && d.startsWith("adhdev-providers")
50844
+ (d) => fs26.statSync(path36.join(tmpExtract, d)).isDirectory() && d.startsWith("adhdev-providers")
50785
50845
  );
50786
50846
  if (!rootDir) throw new Error("Unexpected tarball structure");
50787
- const sourceDir = path35.join(tmpExtract, rootDir);
50847
+ const sourceDir = path36.join(tmpExtract, rootDir);
50788
50848
  const backupDir = this.upstreamDir + ".bak";
50789
- if (fs25.existsSync(this.upstreamDir)) {
50790
- if (fs25.existsSync(backupDir)) fs25.rmSync(backupDir, { recursive: true, force: true });
50791
- fs25.renameSync(this.upstreamDir, backupDir);
50849
+ if (fs26.existsSync(this.upstreamDir)) {
50850
+ if (fs26.existsSync(backupDir)) fs26.rmSync(backupDir, { recursive: true, force: true });
50851
+ fs26.renameSync(this.upstreamDir, backupDir);
50792
50852
  }
50793
50853
  try {
50794
50854
  this.copyDirRecursive(sourceDir, this.upstreamDir);
50795
50855
  this.writeMeta(metaPath, etag || `ts-${Date.now()}`, Date.now());
50796
- if (fs25.existsSync(backupDir)) fs25.rmSync(backupDir, { recursive: true, force: true });
50856
+ if (fs26.existsSync(backupDir)) fs26.rmSync(backupDir, { recursive: true, force: true });
50797
50857
  } catch (e) {
50798
- if (fs25.existsSync(backupDir)) {
50799
- if (fs25.existsSync(this.upstreamDir)) fs25.rmSync(this.upstreamDir, { recursive: true, force: true });
50800
- fs25.renameSync(backupDir, this.upstreamDir);
50858
+ if (fs26.existsSync(backupDir)) {
50859
+ if (fs26.existsSync(this.upstreamDir)) fs26.rmSync(this.upstreamDir, { recursive: true, force: true });
50860
+ fs26.renameSync(backupDir, this.upstreamDir);
50801
50861
  }
50802
50862
  throw e;
50803
50863
  }
50804
50864
  try {
50805
- fs25.rmSync(tmpTar, { force: true });
50865
+ fs26.rmSync(tmpTar, { force: true });
50806
50866
  } catch {
50807
50867
  }
50808
50868
  try {
50809
- fs25.rmSync(tmpExtract, { recursive: true, force: true });
50869
+ fs26.rmSync(tmpExtract, { recursive: true, force: true });
50810
50870
  } catch {
50811
50871
  }
50812
50872
  const upstreamCount = this.countProviders(this.upstreamDir);
@@ -50838,7 +50898,7 @@ var ProviderLoader = class _ProviderLoader {
50838
50898
  reject(new Error(`HTTP ${res.statusCode}`));
50839
50899
  return;
50840
50900
  }
50841
- const ws = fs25.createWriteStream(destPath);
50901
+ const ws = fs26.createWriteStream(destPath);
50842
50902
  res.pipe(ws);
50843
50903
  ws.on("finish", () => {
50844
50904
  ws.close();
@@ -50857,22 +50917,22 @@ var ProviderLoader = class _ProviderLoader {
50857
50917
  }
50858
50918
  /** Recursive directory copy */
50859
50919
  copyDirRecursive(src, dest) {
50860
- fs25.mkdirSync(dest, { recursive: true });
50861
- for (const entry of fs25.readdirSync(src, { withFileTypes: true })) {
50862
- const srcPath = path35.join(src, entry.name);
50863
- const destPath = path35.join(dest, entry.name);
50920
+ fs26.mkdirSync(dest, { recursive: true });
50921
+ for (const entry of fs26.readdirSync(src, { withFileTypes: true })) {
50922
+ const srcPath = path36.join(src, entry.name);
50923
+ const destPath = path36.join(dest, entry.name);
50864
50924
  if (entry.isDirectory()) {
50865
50925
  this.copyDirRecursive(srcPath, destPath);
50866
50926
  } else {
50867
- fs25.copyFileSync(srcPath, destPath);
50927
+ fs26.copyFileSync(srcPath, destPath);
50868
50928
  }
50869
50929
  }
50870
50930
  }
50871
50931
  /** .meta.json save */
50872
50932
  writeMeta(metaPath, etag, timestamp) {
50873
50933
  try {
50874
- fs25.mkdirSync(path35.dirname(metaPath), { recursive: true });
50875
- fs25.writeFileSync(metaPath, JSON.stringify({
50934
+ fs26.mkdirSync(path36.dirname(metaPath), { recursive: true });
50935
+ fs26.writeFileSync(metaPath, JSON.stringify({
50876
50936
  etag,
50877
50937
  timestamp,
50878
50938
  lastCheck: new Date(timestamp).toISOString(),
@@ -50883,15 +50943,15 @@ var ProviderLoader = class _ProviderLoader {
50883
50943
  }
50884
50944
  /** Count provider files (provider.v1.json or provider.json — at most one per dir). */
50885
50945
  countProviders(dir) {
50886
- if (!fs25.existsSync(dir)) return 0;
50946
+ if (!fs26.existsSync(dir)) return 0;
50887
50947
  let count = 0;
50888
50948
  const scan = (d) => {
50889
50949
  try {
50890
- const entries = fs25.readdirSync(d, { withFileTypes: true });
50950
+ const entries = fs26.readdirSync(d, { withFileTypes: true });
50891
50951
  const hasManifest = entries.some((e) => e.name === "provider.v1.json" || e.name === "provider.json");
50892
50952
  if (hasManifest) count++;
50893
50953
  for (const entry of entries) {
50894
- if (entry.isDirectory()) scan(path35.join(d, entry.name));
50954
+ if (entry.isDirectory()) scan(path36.join(d, entry.name));
50895
50955
  }
50896
50956
  } catch {
50897
50957
  }
@@ -51117,13 +51177,13 @@ var ProviderLoader = class _ProviderLoader {
51117
51177
  if (!provider) return null;
51118
51178
  const cat = provider.category;
51119
51179
  const searchRoots = this.getProviderRoots();
51120
- const hasManifest = (dir) => fs25.existsSync(path35.join(dir, "provider.v1.json")) || fs25.existsSync(path35.join(dir, "provider.json"));
51180
+ const hasManifest = (dir) => fs26.existsSync(path36.join(dir, "provider.v1.json")) || fs26.existsSync(path36.join(dir, "provider.json"));
51121
51181
  const readManifestType = (dir) => {
51122
51182
  for (const file of ["provider.v1.json", "provider.json"]) {
51123
- const p = path35.join(dir, file);
51124
- if (!fs25.existsSync(p)) continue;
51183
+ const p = path36.join(dir, file);
51184
+ if (!fs26.existsSync(p)) continue;
51125
51185
  try {
51126
- const data = JSON.parse(fs25.readFileSync(p, "utf-8"));
51186
+ const data = JSON.parse(fs26.readFileSync(p, "utf-8"));
51127
51187
  if (typeof data?.type === "string") return data.type;
51128
51188
  } catch {
51129
51189
  }
@@ -51131,15 +51191,15 @@ var ProviderLoader = class _ProviderLoader {
51131
51191
  return null;
51132
51192
  };
51133
51193
  for (const root of searchRoots) {
51134
- if (!fs25.existsSync(root)) continue;
51194
+ if (!fs26.existsSync(root)) continue;
51135
51195
  const candidate = this.getProviderDir(root, cat, type);
51136
51196
  if (hasManifest(candidate)) return candidate;
51137
- const catDir = path35.join(root, cat);
51138
- if (fs25.existsSync(catDir)) {
51197
+ const catDir = path36.join(root, cat);
51198
+ if (fs26.existsSync(catDir)) {
51139
51199
  try {
51140
- for (const entry of fs25.readdirSync(catDir, { withFileTypes: true })) {
51200
+ for (const entry of fs26.readdirSync(catDir, { withFileTypes: true })) {
51141
51201
  if (!entry.isDirectory()) continue;
51142
- const entryDir = path35.join(catDir, entry.name);
51202
+ const entryDir = path36.join(catDir, entry.name);
51143
51203
  const manifestType = readManifestType(entryDir);
51144
51204
  if (manifestType === type) return entryDir;
51145
51205
  }
@@ -51155,8 +51215,8 @@ var ProviderLoader = class _ProviderLoader {
51155
51215
  * (template substitution is NOT applied here — scripts.js handles that)
51156
51216
  */
51157
51217
  buildScriptWrappersFromDir(dir) {
51158
- const scriptsJs = path35.join(dir, "scripts.js");
51159
- if (fs25.existsSync(scriptsJs)) {
51218
+ const scriptsJs = path36.join(dir, "scripts.js");
51219
+ if (fs26.existsSync(scriptsJs)) {
51160
51220
  try {
51161
51221
  delete require.cache[require.resolve(scriptsJs)];
51162
51222
  return require(scriptsJs);
@@ -51166,13 +51226,13 @@ var ProviderLoader = class _ProviderLoader {
51166
51226
  const toCamel = (name) => name.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
51167
51227
  const result = {};
51168
51228
  try {
51169
- for (const file of fs25.readdirSync(dir)) {
51229
+ for (const file of fs26.readdirSync(dir)) {
51170
51230
  if (!file.endsWith(".js")) continue;
51171
51231
  const scriptName = toCamel(file.replace(".js", ""));
51172
- const filePath = path35.join(dir, file);
51232
+ const filePath = path36.join(dir, file);
51173
51233
  result[scriptName] = (...args) => {
51174
51234
  try {
51175
- let content = fs25.readFileSync(filePath, "utf-8");
51235
+ let content = fs26.readFileSync(filePath, "utf-8");
51176
51236
  if (args[0] && typeof args[0] === "object") {
51177
51237
  for (const [key2, val] of Object.entries(args[0])) {
51178
51238
  let v = val;
@@ -51218,12 +51278,12 @@ var ProviderLoader = class _ProviderLoader {
51218
51278
  * Structure: dir/category/agent-name/provider.{json,js}
51219
51279
  */
51220
51280
  loadDir(dir, excludeDirs) {
51221
- if (!fs25.existsSync(dir)) return 0;
51281
+ if (!fs26.existsSync(dir)) return 0;
51222
51282
  let count = 0;
51223
51283
  const scan = (d) => {
51224
51284
  let entries;
51225
51285
  try {
51226
- entries = fs25.readdirSync(d, { withFileTypes: true });
51286
+ entries = fs26.readdirSync(d, { withFileTypes: true });
51227
51287
  } catch {
51228
51288
  return;
51229
51289
  }
@@ -51231,9 +51291,9 @@ var ProviderLoader = class _ProviderLoader {
51231
51291
  const hasJson = entries.some((e) => e.name === "provider.json");
51232
51292
  if (hasV1 || hasJson) {
51233
51293
  const manifestFile = hasV1 ? "provider.v1.json" : "provider.json";
51234
- const jsonPath = path35.join(d, manifestFile);
51294
+ const jsonPath = path36.join(d, manifestFile);
51235
51295
  try {
51236
- const raw = fs25.readFileSync(jsonPath, "utf-8");
51296
+ const raw = fs26.readFileSync(jsonPath, "utf-8");
51237
51297
  const mod = JSON.parse(raw);
51238
51298
  if (hasV1 && mod?.category === "cli") {
51239
51299
  try {
@@ -51271,10 +51331,10 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
51271
51331
  this.log(`\u26A0 Invalid provider at ${jsonPath}: ${validation.errors.join("; ")}`);
51272
51332
  } else {
51273
51333
  const hasCompatibility = Array.isArray(normalizedProvider.compatibility);
51274
- const scriptsPath = path35.join(d, "scripts.js");
51275
- if (!hasCompatibility && fs25.existsSync(scriptsPath)) {
51334
+ const scriptsPath = path36.join(d, "scripts.js");
51335
+ if (!hasCompatibility && fs26.existsSync(scriptsPath)) {
51276
51336
  try {
51277
- registerProviderScriptRootSafely(path35.dirname(path35.dirname(d)));
51337
+ registerProviderScriptRootSafely(path36.dirname(path36.dirname(d)));
51278
51338
  delete require.cache[require.resolve(scriptsPath)];
51279
51339
  const scripts = require(scriptsPath);
51280
51340
  normalizedProvider.scripts = scripts;
@@ -51282,7 +51342,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
51282
51342
  this.log(`\u26A0 Failed to load scripts: ${scriptsPath}: ${e.message}`);
51283
51343
  }
51284
51344
  }
51285
- const externalDirAbs = path35.join(os25.homedir(), ".adhdev", "external");
51345
+ const externalDirAbs = path36.join(os26.homedir(), ".adhdev", "external");
51286
51346
  const layer = d.startsWith(externalDirAbs) ? "external" : d.startsWith(this.userDir) && !d.includes(".upstream") ? "user" : "upstream";
51287
51347
  try {
51288
51348
  const { inspectManifestShape: inspectManifestShape2, classifyTrust: classifyTrust2 } = (init_provider_trust(), __toCommonJS(provider_trust_exports));
@@ -51292,8 +51352,8 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
51292
51352
  normalizedProvider._sourceTrust = trust;
51293
51353
  normalizedProvider._manifestShape = shape;
51294
51354
  if (layer === "external") {
51295
- const rel = path35.relative(externalDirAbs, d);
51296
- const firstSeg = rel.split(path35.sep)[0];
51355
+ const rel = path36.relative(externalDirAbs, d);
51356
+ const firstSeg = rel.split(path36.sep)[0];
51297
51357
  if (firstSeg && firstSeg !== "..") normalizedProvider._sourceName = firstSeg;
51298
51358
  }
51299
51359
  } catch {
@@ -51317,7 +51377,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
51317
51377
  if (entry.name.startsWith("_") || entry.name.startsWith(".")) continue;
51318
51378
  if (d === dir && entry.name === "examples") continue;
51319
51379
  if (excludeDirs && d === dir && excludeDirs.includes(entry.name)) continue;
51320
- scan(path35.join(d, entry.name));
51380
+ scan(path36.join(d, entry.name));
51321
51381
  }
51322
51382
  }
51323
51383
  };
@@ -51515,7 +51575,7 @@ async function isCdpActive(port) {
51515
51575
  });
51516
51576
  }
51517
51577
  async function killIdeProcess(ideId) {
51518
- const plat = os26.platform();
51578
+ const plat = os27.platform();
51519
51579
  const appName = getMacAppIdentifiers()[ideId];
51520
51580
  const winProcesses = getWinProcessNames()[ideId];
51521
51581
  try {
@@ -51576,7 +51636,7 @@ async function killIdeProcess(ideId) {
51576
51636
  }
51577
51637
  }
51578
51638
  async function isIdeRunning(ideId) {
51579
- const plat = os26.platform();
51639
+ const plat = os27.platform();
51580
51640
  try {
51581
51641
  if (plat === "darwin") {
51582
51642
  const appName = getMacAppIdentifiers()[ideId];
@@ -51631,7 +51691,7 @@ async function isIdeRunning(ideId) {
51631
51691
  }
51632
51692
  }
51633
51693
  async function detectCurrentWorkspace(ideId) {
51634
- const plat = os26.platform();
51694
+ const plat = os27.platform();
51635
51695
  if (plat === "darwin") {
51636
51696
  try {
51637
51697
  const appName = getMacAppIdentifiers()[ideId];
@@ -51646,17 +51706,17 @@ async function detectCurrentWorkspace(ideId) {
51646
51706
  }
51647
51707
  } else if (plat === "win32") {
51648
51708
  try {
51649
- const fs40 = require("fs");
51709
+ const fs41 = require("fs");
51650
51710
  const appNameMap = getMacAppIdentifiers();
51651
51711
  const appName = appNameMap[ideId];
51652
51712
  if (appName) {
51653
- const storagePath = path36.join(
51654
- process.env.APPDATA || path36.join(os26.homedir(), "AppData", "Roaming"),
51713
+ const storagePath = path37.join(
51714
+ process.env.APPDATA || path37.join(os27.homedir(), "AppData", "Roaming"),
51655
51715
  appName,
51656
51716
  "storage.json"
51657
51717
  );
51658
- if (fs40.existsSync(storagePath)) {
51659
- const data = JSON.parse(fs40.readFileSync(storagePath, "utf-8"));
51718
+ if (fs41.existsSync(storagePath)) {
51719
+ const data = JSON.parse(fs41.readFileSync(storagePath, "utf-8"));
51660
51720
  const workspaces = data?.openedPathsList?.workspaces3 || data?.openedPathsList?.entries || [];
51661
51721
  if (workspaces.length > 0) {
51662
51722
  const recent = workspaces[0];
@@ -51673,7 +51733,7 @@ async function detectCurrentWorkspace(ideId) {
51673
51733
  return void 0;
51674
51734
  }
51675
51735
  async function launchWithCdp(options = {}) {
51676
- const platform10 = os26.platform();
51736
+ const platform10 = os27.platform();
51677
51737
  let targetIde;
51678
51738
  const ides = await detectIDEs(getProviderLoader());
51679
51739
  if (options.ideId) {
@@ -52176,11 +52236,11 @@ var meshCrudHandlers = {
52176
52236
  MESH_JSON_CONFIG_LOCATIONS: MESH_JSON_CONFIG_LOCATIONS2
52177
52237
  } = await Promise.resolve().then(() => (init_mesh_json_config(), mesh_json_config_exports));
52178
52238
  const { mkdirSync: mkdirSync22, writeFileSync: writeFileSync24 } = await import("fs");
52179
- const { dirname: dirname17, join: join50 } = await import("path");
52239
+ const { dirname: dirname17, join: join51 } = await import("path");
52180
52240
  const scaffold = buildMeshJsonConfigScaffold2(mesh);
52181
52241
  const scaffoldJson = serializeMeshJsonConfigScaffold2(scaffold);
52182
52242
  const relativePath = MESH_JSON_CONFIG_LOCATIONS2[0];
52183
- const absolutePath = join50(workspace, relativePath);
52243
+ const absolutePath = join51(workspace, relativePath);
52184
52244
  const validation = normalizeRepoMeshDeclarativeConfig2(scaffold);
52185
52245
  if (!validation.valid) {
52186
52246
  return { success: false, meshId, error: `invalid mesh.json scaffold: ${validation.errors.join("; ")}` };
@@ -53633,7 +53693,7 @@ var meshEventsHandlers = {
53633
53693
 
53634
53694
  // src/commands/high-family/mesh-coordinator-launch.ts
53635
53695
  var import_path13 = require("path");
53636
- var fs26 = __toESM(require("fs"));
53696
+ var fs27 = __toESM(require("fs"));
53637
53697
  init_logger();
53638
53698
  init_mesh_host_ownership();
53639
53699
  init_coordinator_registry();
@@ -53868,15 +53928,15 @@ ${ptyResult.output.slice(-2e3)}`);
53868
53928
  }
53869
53929
  if (cliType === "codex-cli") {
53870
53930
  const repoMcpConfigPath = (0, import_path13.join)(workspace, ".mcp.json");
53871
- if (fs26.existsSync(repoMcpConfigPath)) {
53931
+ if (fs27.existsSync(repoMcpConfigPath)) {
53872
53932
  try {
53873
53933
  const repoMcpConfig = parseMeshCoordinatorMcpConfig(
53874
- fs26.readFileSync(repoMcpConfigPath, "utf-8"),
53934
+ fs27.readFileSync(repoMcpConfigPath, "utf-8"),
53875
53935
  "claude_mcp_json"
53876
53936
  );
53877
53937
  const existingServers2 = repoMcpConfig.mcpServers;
53878
53938
  if (existingServers2 && typeof existingServers2 === "object" && !Array.isArray(existingServers2) && existingServers2[coordinatorSetup.serverName]) {
53879
- fs26.writeFileSync(repoMcpConfigPath, serializeMeshCoordinatorMcpConfig({
53939
+ fs27.writeFileSync(repoMcpConfigPath, serializeMeshCoordinatorMcpConfig({
53880
53940
  ...repoMcpConfig,
53881
53941
  mcpServers: {
53882
53942
  ...existingServers2,
@@ -54159,7 +54219,7 @@ ${ptyResult.output.slice(-2e3)}`);
54159
54219
  };
54160
54220
 
54161
54221
  // src/commands/high-family/mesh-status.ts
54162
- var fs27 = __toESM(require("fs"));
54222
+ var fs28 = __toESM(require("fs"));
54163
54223
  var import_os3 = require("os");
54164
54224
  init_config();
54165
54225
  init_git_status();
@@ -54206,10 +54266,10 @@ function runGit2(repoRoot, args) {
54206
54266
  }
54207
54267
  }
54208
54268
  function readRecord6(repoRoot) {
54209
- const path44 = (0, import_node_path2.resolve)(repoRoot, PREVIEW_DEPLOY_RECORD);
54210
- if (!(0, import_node_fs4.existsSync)(path44)) return null;
54269
+ const path45 = (0, import_node_path2.resolve)(repoRoot, PREVIEW_DEPLOY_RECORD);
54270
+ if (!(0, import_node_fs4.existsSync)(path45)) return null;
54211
54271
  try {
54212
- const parsed = JSON.parse((0, import_node_fs4.readFileSync)(path44, "utf8"));
54272
+ const parsed = JSON.parse((0, import_node_fs4.readFileSync)(path45, "utf8"));
54213
54273
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
54214
54274
  } catch {
54215
54275
  return null;
@@ -54520,7 +54580,7 @@ var meshStatusHandlers = {
54520
54580
  }
54521
54581
  }
54522
54582
  if (workspace) {
54523
- if (!fs27.existsSync(workspace)) {
54583
+ if (!fs28.existsSync(workspace)) {
54524
54584
  const inlineTransitGit = buildInlineMeshTransitGitStatus(node);
54525
54585
  let remoteProbeApplied = false;
54526
54586
  if (inlineTransitGit) {
@@ -54650,7 +54710,7 @@ var meshStatusHandlers = {
54650
54710
  backstop: { ...getMeshV2BackstopCounters() }
54651
54711
  };
54652
54712
  const previewFreshness = (() => {
54653
- const localRepoRoot = nodeStatuses.map((node) => readStringValue(node?.git?.repoRoot, node?.repoRoot, node?.workspace)).find((candidate) => !!candidate && fs27.existsSync(candidate));
54713
+ const localRepoRoot = nodeStatuses.map((node) => readStringValue(node?.git?.repoRoot, node?.repoRoot, node?.workspace)).find((candidate) => !!candidate && fs28.existsSync(candidate));
54654
54714
  return localRepoRoot ? buildPreviewFreshness(localRepoRoot) : void 0;
54655
54715
  })();
54656
54716
  const asyncRefineJobs = buildMeshAsyncRefineJobs({
@@ -54850,15 +54910,15 @@ init_dist();
54850
54910
  init_logger();
54851
54911
 
54852
54912
  // src/logging/command-log.ts
54853
- var fs28 = __toESM(require("fs"));
54854
- var path37 = __toESM(require("path"));
54855
- var os27 = __toESM(require("os"));
54856
- var ADHDEV_HOME2 = process.env.ADHDEV_CONFIG_DIR && process.env.ADHDEV_CONFIG_DIR.trim() ? process.env.ADHDEV_CONFIG_DIR.trim() : path37.join(os27.homedir(), ".adhdev");
54857
- var LOG_DIR2 = path37.join(ADHDEV_HOME2, "logs");
54913
+ var fs29 = __toESM(require("fs"));
54914
+ var path38 = __toESM(require("path"));
54915
+ var os28 = __toESM(require("os"));
54916
+ var ADHDEV_HOME2 = process.env.ADHDEV_CONFIG_DIR && process.env.ADHDEV_CONFIG_DIR.trim() ? process.env.ADHDEV_CONFIG_DIR.trim() : path38.join(os28.homedir(), ".adhdev");
54917
+ var LOG_DIR2 = path38.join(ADHDEV_HOME2, "logs");
54858
54918
  var MAX_FILE_SIZE = 5 * 1024 * 1024;
54859
54919
  var MAX_DAYS = 7;
54860
54920
  try {
54861
- fs28.mkdirSync(LOG_DIR2, { recursive: true });
54921
+ fs29.mkdirSync(LOG_DIR2, { recursive: true });
54862
54922
  } catch {
54863
54923
  }
54864
54924
  var SENSITIVE_KEYS = /* @__PURE__ */ new Set([
@@ -54892,19 +54952,19 @@ function getDateStr2() {
54892
54952
  return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
54893
54953
  }
54894
54954
  var currentDate2 = getDateStr2();
54895
- var currentFile = path37.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
54955
+ var currentFile = path38.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
54896
54956
  var writeCount2 = 0;
54897
54957
  function checkRotation() {
54898
54958
  const today = getDateStr2();
54899
54959
  if (today !== currentDate2) {
54900
54960
  currentDate2 = today;
54901
- currentFile = path37.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
54961
+ currentFile = path38.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
54902
54962
  cleanOldFiles();
54903
54963
  }
54904
54964
  }
54905
54965
  function cleanOldFiles() {
54906
54966
  try {
54907
- const files = fs28.readdirSync(LOG_DIR2).filter((f) => f.startsWith("commands-") && f.endsWith(".jsonl"));
54967
+ const files = fs29.readdirSync(LOG_DIR2).filter((f) => f.startsWith("commands-") && f.endsWith(".jsonl"));
54908
54968
  const cutoff = /* @__PURE__ */ new Date();
54909
54969
  cutoff.setDate(cutoff.getDate() - MAX_DAYS);
54910
54970
  const cutoffStr = cutoff.toISOString().slice(0, 10);
@@ -54912,7 +54972,7 @@ function cleanOldFiles() {
54912
54972
  const dateMatch = file.match(/commands-(\d{4}-\d{2}-\d{2})/);
54913
54973
  if (dateMatch && dateMatch[1] < cutoffStr) {
54914
54974
  try {
54915
- fs28.unlinkSync(path37.join(LOG_DIR2, file));
54975
+ fs29.unlinkSync(path38.join(LOG_DIR2, file));
54916
54976
  } catch {
54917
54977
  }
54918
54978
  }
@@ -54922,14 +54982,14 @@ function cleanOldFiles() {
54922
54982
  }
54923
54983
  function checkSize() {
54924
54984
  try {
54925
- const stat2 = fs28.statSync(currentFile);
54985
+ const stat2 = fs29.statSync(currentFile);
54926
54986
  if (stat2.size > MAX_FILE_SIZE) {
54927
54987
  const backup = currentFile.replace(".jsonl", ".1.jsonl");
54928
54988
  try {
54929
- fs28.unlinkSync(backup);
54989
+ fs29.unlinkSync(backup);
54930
54990
  } catch {
54931
54991
  }
54932
- fs28.renameSync(currentFile, backup);
54992
+ fs29.renameSync(currentFile, backup);
54933
54993
  }
54934
54994
  } catch {
54935
54995
  }
@@ -54962,14 +55022,14 @@ function logCommand(entry) {
54962
55022
  ...entry.error ? { err: entry.error } : {},
54963
55023
  ...entry.durationMs !== void 0 ? { ms: entry.durationMs } : {}
54964
55024
  });
54965
- fs28.appendFileSync(currentFile, line + "\n");
55025
+ fs29.appendFileSync(currentFile, line + "\n");
54966
55026
  } catch {
54967
55027
  }
54968
55028
  }
54969
55029
  function getRecentCommands(count = 50) {
54970
55030
  try {
54971
- if (!fs28.existsSync(currentFile)) return [];
54972
- const content = fs28.readFileSync(currentFile, "utf-8");
55031
+ if (!fs29.existsSync(currentFile)) return [];
55032
+ const content = fs29.readFileSync(currentFile, "utf-8");
54973
55033
  const lines = content.trim().split("\n").filter(Boolean);
54974
55034
  return lines.slice(-count).map((line) => {
54975
55035
  try {
@@ -54997,7 +55057,7 @@ cleanOldFiles();
54997
55057
  // src/commands/router.ts
54998
55058
  init_debug_trace();
54999
55059
  init_mesh_host_ownership();
55000
- var fs33 = __toESM(require("fs"));
55060
+ var fs34 = __toESM(require("fs"));
55001
55061
 
55002
55062
  // src/mesh/mesh-node-identity.ts
55003
55063
  init_cli_detector();
@@ -55005,7 +55065,7 @@ init_git_status();
55005
55065
  init_dist();
55006
55066
  init_logger();
55007
55067
  init_mesh_warmup_deadline();
55008
- var fs29 = __toESM(require("fs"));
55068
+ var fs30 = __toESM(require("fs"));
55009
55069
  init_runtime_defaults();
55010
55070
  function readProviderPriorityFromPolicy(policy) {
55011
55071
  const record = policy && typeof policy === "object" && !Array.isArray(policy) ? policy : {};
@@ -55392,7 +55452,7 @@ function isDeadLocalWorktreeNode(node) {
55392
55452
  if (node?.isLocalWorktree !== true) return false;
55393
55453
  const workspace = readStringValue(node?.workspace);
55394
55454
  if (!workspace) return false;
55395
- return !fs29.existsSync(workspace);
55455
+ return !fs30.existsSync(workspace);
55396
55456
  }
55397
55457
  function foldMeshNodeIdentityToCanonical(node) {
55398
55458
  if (!node || typeof node !== "object" || Array.isArray(node)) return node;
@@ -55640,7 +55700,7 @@ function summarizeInlineMeshBranchConvergence(nodes) {
55640
55700
  const followUps = nodes.filter((node) => {
55641
55701
  if (readObjectRecord(node.branchConvergence).needsConvergence !== true) return false;
55642
55702
  const workspace = typeof node.workspace === "string" ? node.workspace : "";
55643
- if (workspace && !fs29.existsSync(workspace)) return false;
55703
+ if (workspace && !fs30.existsSync(workspace)) return false;
55644
55704
  return true;
55645
55705
  }).map((node) => {
55646
55706
  const convergence = readObjectRecord(node.branchConvergence);
@@ -56070,7 +56130,7 @@ async function hydrateInlineMeshDirectTruth(args) {
56070
56130
  if (!workspace) {
56071
56131
  return !isSelfNode && daemonId ? { kind: "unavailable", nodeId } : { kind: "skip" };
56072
56132
  }
56073
- if (fs29.existsSync(workspace)) {
56133
+ if (fs30.existsSync(workspace)) {
56074
56134
  try {
56075
56135
  const runLocalProbe = () => getGitRepoStatus(workspace, { timeoutMs: 1e4, refreshUpstream: true });
56076
56136
  const localGit = args.probeCache ? await args.probeCache.probeLocal(workspace, runLocalProbe) : await runLocalProbe();
@@ -56217,7 +56277,7 @@ function readLiveMeshNodeWorkspace(args) {
56217
56277
  }
56218
56278
  function collectLiveMeshSessionRecords(args) {
56219
56279
  const nodeWorkspace = readStringValue(args.node?.workspace);
56220
- const nodeIsMissingLocalWorktree = args.node?.isLocalWorktree === true && !!nodeWorkspace && !fs29.existsSync(nodeWorkspace);
56280
+ const nodeIsMissingLocalWorktree = args.node?.isLocalWorktree === true && !!nodeWorkspace && !fs30.existsSync(nodeWorkspace);
56221
56281
  const matches = args.liveSessionRecords.filter((record) => {
56222
56282
  const recordNodeId = readStringValue(record?.meta?.meshNodeId);
56223
56283
  if (recordNodeId && !daemonIdsEquivalent(recordNodeId, args.nodeId)) return false;
@@ -56244,7 +56304,7 @@ function buildHistoricalMeshSessions(args) {
56244
56304
  const workspace = readStringValue(node?.workspace);
56245
56305
  if (nodeId) liveNodeIds.add(nodeId);
56246
56306
  if (workspace) liveWorkspaces.add(workspace);
56247
- if (nodeId && node?.isLocalWorktree === true && workspace && !fs29.existsSync(workspace)) {
56307
+ if (nodeId && node?.isLocalWorktree === true && workspace && !fs30.existsSync(workspace)) {
56248
56308
  missingLocalWorktreeNodeIds.add(nodeId);
56249
56309
  }
56250
56310
  }
@@ -56340,9 +56400,9 @@ init_resolve_executable();
56340
56400
  var execFileAsync3 = (0, import_node_util4.promisify)(import_node_child_process5.execFile);
56341
56401
  var GIT = process.platform === "win32" ? resolveWin32Executable("git") : "git";
56342
56402
  var MAX_CHANGED_FILES2 = 500;
56343
- function topLevel(path44) {
56344
- const slash = path44.indexOf("/");
56345
- return slash === -1 ? path44 : path44.slice(0, slash);
56403
+ function topLevel(path45) {
56404
+ const slash = path45.indexOf("/");
56405
+ return slash === -1 ? path45 : path45.slice(0, slash);
56346
56406
  }
56347
56407
  async function analyzeMeshRefineNodeChangeArea(args) {
56348
56408
  const { nodeId, workspace, branch, baseRef, branchRef, diffCwd, submodulePaths } = args;
@@ -56430,7 +56490,7 @@ init_git_status();
56430
56490
  init_refine_config();
56431
56491
  init_worktree_bootstrap_config();
56432
56492
  var import_path14 = require("path");
56433
- var fs30 = __toESM(require("fs"));
56493
+ var fs31 = __toESM(require("fs"));
56434
56494
  var import_node_child_process6 = require("child_process");
56435
56495
  init_resolve_executable();
56436
56496
  var GIT2 = process.platform === "win32" ? resolveWin32Executable("git") : "git";
@@ -56490,7 +56550,7 @@ async function computeGitPatchId(cwd, fromRef, toRef, excludePaths = []) {
56490
56550
  const { execFileSync: execFileSync10 } = await import("child_process");
56491
56551
  const diffArgs = ["diff", "--patch", "--full-index", fromRef, toRef];
56492
56552
  if (excludePaths.length > 0) {
56493
- diffArgs.push("--", ".", ...excludePaths.map((path44) => `:(exclude)${path44}`));
56553
+ diffArgs.push("--", ".", ...excludePaths.map((path45) => `:(exclude)${path45}`));
56494
56554
  }
56495
56555
  const diff = execFileSync10(GIT2, diffArgs, {
56496
56556
  cwd,
@@ -56691,9 +56751,9 @@ async function runMeshRefineEffectiveDiffGate(repoRoot, baseHead, branchHead) {
56691
56751
  if (!trimmed) continue;
56692
56752
  if (trimmed.startsWith("+")) {
56693
56753
  const parts = trimmed.slice(1).trim().split(/\s+/);
56694
- const path44 = parts[1] || parts[0] || "(unknown)";
56754
+ const path45 = parts[1] || parts[0] || "(unknown)";
56695
56755
  submoduleHints.push({
56696
- path: path44,
56756
+ path: path45,
56697
56757
  reason: "submodule checked-out commit differs from the committed gitlink (pointer bump not committed on the root branch)"
56698
56758
  });
56699
56759
  }
@@ -56723,10 +56783,10 @@ async function runMeshRefineEffectiveDiffGate(repoRoot, baseHead, branchHead) {
56723
56783
  }
56724
56784
  function buildPatchEquivalenceSubmoduleConflictHint(repoRoot, baseHead, branchHead, output) {
56725
56785
  if (!/(submodule|160000)/i.test(output) || !/(conflict|failed to merge)/i.test(output)) return void 0;
56726
- const conflicts = readChangedGitlinkPaths(repoRoot, baseHead, branchHead).map((path44) => ({
56727
- path: path44,
56728
- baseCommit: readTreeObject(repoRoot, baseHead, path44),
56729
- branchCommit: readTreeObject(repoRoot, branchHead, path44)
56786
+ const conflicts = readChangedGitlinkPaths(repoRoot, baseHead, branchHead).map((path45) => ({
56787
+ path: path45,
56788
+ baseCommit: readTreeObject(repoRoot, baseHead, path45),
56789
+ branchCommit: readTreeObject(repoRoot, branchHead, path45)
56730
56790
  }));
56731
56791
  if (conflicts.length === 0) return void 0;
56732
56792
  return {
@@ -56752,11 +56812,11 @@ function readChangedGitlinkPaths(repoRoot, fromRef, toRef) {
56752
56812
  if (!line.trim()) continue;
56753
56813
  const metaAndPath = line.split(" ");
56754
56814
  const meta = metaAndPath[0] || "";
56755
- const path44 = metaAndPath[metaAndPath.length - 1]?.trim();
56756
- if (!path44) continue;
56815
+ const path45 = metaAndPath[metaAndPath.length - 1]?.trim();
56816
+ if (!path45) continue;
56757
56817
  const parts = meta.split(/\s+/);
56758
56818
  if (parts[0]?.includes("160000") || parts[1]?.includes("160000")) {
56759
- paths.add(path44);
56819
+ paths.add(path45);
56760
56820
  }
56761
56821
  }
56762
56822
  return [...paths].sort();
@@ -56764,9 +56824,9 @@ function readChangedGitlinkPaths(repoRoot, fromRef, toRef) {
56764
56824
  return [];
56765
56825
  }
56766
56826
  }
56767
- function readTreeObject(repoRoot, ref, path44) {
56827
+ function readTreeObject(repoRoot, ref, path45) {
56768
56828
  try {
56769
- const output = (0, import_node_child_process6.execFileSync)(GIT2, ["ls-tree", ref, "--", path44], {
56829
+ const output = (0, import_node_child_process6.execFileSync)(GIT2, ["ls-tree", ref, "--", path45], {
56770
56830
  cwd: repoRoot,
56771
56831
  encoding: "utf8",
56772
56832
  maxBuffer: 1024 * 1024
@@ -56789,7 +56849,7 @@ function isSubmoduleFastForward(submoduleRepoPath, baseCommit, branchCommit) {
56789
56849
  if (!baseCommit || !branchCommit) return false;
56790
56850
  if (baseCommit === branchCommit) return true;
56791
56851
  try {
56792
- if (!fs30.existsSync(submoduleRepoPath)) return false;
56852
+ if (!fs31.existsSync(submoduleRepoPath)) return false;
56793
56853
  (0, import_node_child_process6.execFileSync)(GIT2, ["cat-file", "-e", `${baseCommit}^{commit}`], { cwd: submoduleRepoPath, stdio: "ignore" });
56794
56854
  (0, import_node_child_process6.execFileSync)(GIT2, ["cat-file", "-e", `${branchCommit}^{commit}`], { cwd: submoduleRepoPath, stdio: "ignore" });
56795
56855
  (0, import_node_child_process6.execFileSync)(GIT2, ["merge-base", "--is-ancestor", baseCommit, branchCommit], { cwd: submoduleRepoPath, stdio: "ignore" });
@@ -56811,12 +56871,12 @@ function readChangedPathKinds(repoRoot, fromRef, toRef) {
56811
56871
  if (!line.trim()) continue;
56812
56872
  const metaAndPath = line.split(" ");
56813
56873
  const meta = metaAndPath[0] || "";
56814
- const path44 = metaAndPath[metaAndPath.length - 1]?.trim();
56815
- if (!path44 || seen.has(path44)) continue;
56816
- seen.add(path44);
56874
+ const path45 = metaAndPath[metaAndPath.length - 1]?.trim();
56875
+ if (!path45 || seen.has(path45)) continue;
56876
+ seen.add(path45);
56817
56877
  const parts = meta.split(/\s+/);
56818
56878
  const isGitlink = !!(parts[0]?.includes("160000") || parts[1]?.includes("160000"));
56819
- result.push({ path: path44, isGitlink });
56879
+ result.push({ path: path45, isGitlink });
56820
56880
  }
56821
56881
  return result;
56822
56882
  } catch {
@@ -56824,20 +56884,20 @@ function readChangedPathKinds(repoRoot, fromRef, toRef) {
56824
56884
  }
56825
56885
  }
56826
56886
  function collectFastForwardGitlinkPaths(repoRoot, baseHead, branchHead) {
56827
- return readChangedGitlinkPaths(repoRoot, baseHead, branchHead).filter((path44) => {
56828
- const baseCommit = readTreeObject(repoRoot, baseHead, path44);
56829
- const branchCommit = readTreeObject(repoRoot, branchHead, path44);
56887
+ return readChangedGitlinkPaths(repoRoot, baseHead, branchHead).filter((path45) => {
56888
+ const baseCommit = readTreeObject(repoRoot, baseHead, path45);
56889
+ const branchCommit = readTreeObject(repoRoot, branchHead, path45);
56830
56890
  if (!baseCommit || !branchCommit) return false;
56831
- return isSubmoduleFastForward((0, import_path14.resolve)(repoRoot, path44), baseCommit, branchCommit);
56891
+ return isSubmoduleFastForward((0, import_path14.resolve)(repoRoot, path45), baseCommit, branchCommit);
56832
56892
  });
56833
56893
  }
56834
56894
  function evaluateGitlinkTrivialFastForward(repoRoot, baseHead, branchHead) {
56835
- const changedGitlinks = readChangedGitlinkPaths(repoRoot, baseHead, branchHead).map((path44) => {
56836
- const baseCommit = readTreeObject(repoRoot, baseHead, path44);
56837
- const branchCommit = readTreeObject(repoRoot, branchHead, path44);
56838
- const submoduleRepoPath = (0, import_path14.resolve)(repoRoot, path44);
56895
+ const changedGitlinks = readChangedGitlinkPaths(repoRoot, baseHead, branchHead).map((path45) => {
56896
+ const baseCommit = readTreeObject(repoRoot, baseHead, path45);
56897
+ const branchCommit = readTreeObject(repoRoot, branchHead, path45);
56898
+ const submoduleRepoPath = (0, import_path14.resolve)(repoRoot, path45);
56839
56899
  const fastForward = !!baseCommit && !!branchCommit && isSubmoduleFastForward(submoduleRepoPath, baseCommit, branchCommit);
56840
- return { path: path44, baseCommit, branchCommit, fastForward };
56900
+ return { path: path45, baseCommit, branchCommit, fastForward };
56841
56901
  });
56842
56902
  if (changedGitlinks.length === 0) {
56843
56903
  return { trivial: false, reason: "no_changed_gitlinks", gitlinks: changedGitlinks };
@@ -56888,7 +56948,7 @@ function buildTreeWithGitlinksEqualized(repoRoot, commitish, paths, placeholderC
56888
56948
  maxBuffer: 1024 * 1024
56889
56949
  }).trim();
56890
56950
  if (!tree) return void 0;
56891
- const updates = paths.map((path44) => `160000 commit ${placeholderCommit} ${path44}`).join("\n");
56951
+ const updates = paths.map((path45) => `160000 commit ${placeholderCommit} ${path45}`).join("\n");
56892
56952
  if (!updates) return tree;
56893
56953
  const tmpIndex = (0, import_path14.join)(resolveGitDir(repoRoot), `adhdev-refine-eq-${commitish.slice(0, 12)}.index`);
56894
56954
  const env = { ...process.env, GIT_INDEX_FILE: tmpIndex };
@@ -56906,7 +56966,7 @@ function buildTreeWithGitlinksEqualized(repoRoot, commitish, paths, placeholderC
56906
56966
  return newTree || void 0;
56907
56967
  } finally {
56908
56968
  try {
56909
- fs30.rmSync(tmpIndex, { force: true });
56969
+ fs31.rmSync(tmpIndex, { force: true });
56910
56970
  } catch {
56911
56971
  }
56912
56972
  }
@@ -56981,7 +57041,7 @@ function synthesizeTrivialFastForwardMergeTree(repoRoot, baseHead, branchHead, g
56981
57041
  return newTree || void 0;
56982
57042
  } finally {
56983
57043
  try {
56984
- fs30.rmSync(tmpIndex, { force: true });
57044
+ fs31.rmSync(tmpIndex, { force: true });
56985
57045
  } catch {
56986
57046
  }
56987
57047
  }
@@ -56991,7 +57051,7 @@ function synthesizeTrivialFastForwardMergeTree(repoRoot, baseHead, branchHead, g
56991
57051
  }
56992
57052
  async function alignRefinerySubmodulesAfterMerge(repoRoot, previousBaseHead, currentHead, options = {}) {
56993
57053
  const startedAt = Date.now();
56994
- const changedGitlinkPaths = readChangedGitlinkPaths(repoRoot, previousBaseHead, currentHead).filter((path44) => !(options.submoduleIgnorePaths || []).includes(path44));
57054
+ const changedGitlinkPaths = readChangedGitlinkPaths(repoRoot, previousBaseHead, currentHead).filter((path45) => !(options.submoduleIgnorePaths || []).includes(path45));
56995
57055
  const preStatus = await getGitRepoStatus(repoRoot, {
56996
57056
  includeSubmodules: true,
56997
57057
  submoduleIgnorePaths: options.submoduleIgnorePaths,
@@ -57038,7 +57098,7 @@ async function alignRefinerySubmodulesAfterMerge(repoRoot, previousBaseHead, cur
57038
57098
  changedGitlinkPaths,
57039
57099
  outOfSyncPaths,
57040
57100
  updatedPaths: updatePaths,
57041
- verifiedPaths: updatePaths.filter((path44) => !remaining.some((submodule) => submodule.path === path44)),
57101
+ verifiedPaths: updatePaths.filter((path45) => !remaining.some((submodule) => submodule.path === path45)),
57042
57102
  durationMs: Date.now() - startedAt,
57043
57103
  command: `git ${commandArgs.join(" ")}`,
57044
57104
  stdout: truncateValidationOutput(result.stdout),
@@ -57093,7 +57153,7 @@ async function runMeshRefineSubmoduleReachabilityGate(repoRoot, mergedTree, opti
57093
57153
  return { stdout: String(stdout || ""), stderr: String(stderr || ""), refspec };
57094
57154
  };
57095
57155
  const importCommitFromWorktreeSubmodule = async (submodulePath, worktreeSubmodulePath, commit) => {
57096
- if (!fs30.existsSync(worktreeSubmodulePath)) return false;
57156
+ if (!fs31.existsSync(worktreeSubmodulePath)) return false;
57097
57157
  try {
57098
57158
  await runGit3(worktreeSubmodulePath, ["cat-file", "-e", `${commit}^{commit}`]);
57099
57159
  } catch {
@@ -57117,7 +57177,7 @@ async function runMeshRefineSubmoduleReachabilityGate(repoRoot, mergedTree, opti
57117
57177
  };
57118
57178
  let submoduleDefaultBranch = "main";
57119
57179
  try {
57120
- if (!fs30.existsSync(submodulePath)) {
57180
+ if (!fs31.existsSync(submodulePath)) {
57121
57181
  entry.error = `Submodule checkout missing at ${gitlink.path}`;
57122
57182
  entry.publishRequired = true;
57123
57183
  if (options.allowAutoPublishSubmoduleMainCommits === true) {
@@ -57359,9 +57419,9 @@ async function runMeshRefineValidationGate(mesh, workspace, opts) {
57359
57419
  return ["npm", "pnpm", "yarn", "bun"].includes(command) && candidate.args.some((arg) => arg === "run" || arg === "test" || arg === "exec");
57360
57420
  };
57361
57421
  const dependenciesLikelyMissing = (cwd) => {
57362
- if (!fs30.existsSync((0, import_path14.join)(cwd, "package.json"))) return false;
57363
- if (fs30.existsSync((0, import_path14.join)(cwd, "node_modules"))) return false;
57364
- return ["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "bun.lock"].some((lock) => fs30.existsSync((0, import_path14.join)(cwd, lock)));
57422
+ if (!fs31.existsSync((0, import_path14.join)(cwd, "package.json"))) return false;
57423
+ if (fs31.existsSync((0, import_path14.join)(cwd, "node_modules"))) return false;
57424
+ return ["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "bun.lock"].some((lock) => fs31.existsSync((0, import_path14.join)(cwd, lock)));
57365
57425
  };
57366
57426
  if (runLegacyBootstrapCommands) {
57367
57427
  summary.bootstrap = { stage: "legacy" };
@@ -58775,7 +58835,7 @@ async function startMeshRefineJob(self, meshId, nodeId, args) {
58775
58835
  }
58776
58836
 
58777
58837
  // src/commands/router-worktree-cleanup.ts
58778
- var fs31 = __toESM(require("fs"));
58838
+ var fs32 = __toESM(require("fs"));
58779
58839
  var import_path15 = require("path");
58780
58840
  init_logger();
58781
58841
  init_dist();
@@ -58790,14 +58850,14 @@ function sessionMatchesMeshNode(self, record, node, nodeId, sessionIds) {
58790
58850
  return false;
58791
58851
  }
58792
58852
  async function bestEffortRemoveWorktreeDir(self, dir) {
58793
- if (!dir || !fs31.existsSync(dir)) return { removed: true, residue: false };
58853
+ if (!dir || !fs32.existsSync(dir)) return { removed: true, residue: false };
58794
58854
  const sleep3 = (ms) => new Promise((resolve25) => setTimeout(resolve25, ms));
58795
58855
  const ABSORB = /* @__PURE__ */ new Set(["EINVAL", "EPERM", "EBUSY", "ENOTEMPTY", "EACCES", "EMFILE", "ENFILE"]);
58796
58856
  let lastErr;
58797
58857
  for (let attempt = 0; attempt < 4; attempt++) {
58798
58858
  try {
58799
- fs31.rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
58800
- if (!fs31.existsSync(dir)) return { removed: true, residue: false };
58859
+ fs32.rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
58860
+ if (!fs32.existsSync(dir)) return { removed: true, residue: false };
58801
58861
  lastErr = new Error("directory still present after rmSync");
58802
58862
  } catch (e) {
58803
58863
  lastErr = e;
@@ -58808,7 +58868,7 @@ async function bestEffortRemoveWorktreeDir(self, dir) {
58808
58868
  }
58809
58869
  await sleep3(150 * (attempt + 1));
58810
58870
  }
58811
- return fs31.existsSync(dir) ? { removed: false, residue: true, error: String(lastErr?.message || lastErr || "unknown rm error") } : { removed: true, residue: false };
58871
+ return fs32.existsSync(dir) ? { removed: false, residue: true, error: String(lastErr?.message || lastErr || "unknown rm error") } : { removed: true, residue: false };
58812
58872
  }
58813
58873
  async function precheckLocalWorktreeRemovable(self, args) {
58814
58874
  const sessionPreservedNote = " The delegated session was left running (not stopped) \u2014 resolve the issue and retry mesh_remove_node.";
@@ -58821,10 +58881,10 @@ async function precheckLocalWorktreeRemovable(self, args) {
58821
58881
  recoveryHint: "Inspect the mesh node record before removing it, or remove stale metadata manually only after confirming no managed worktree remains." + sessionPreservedNote
58822
58882
  };
58823
58883
  }
58824
- if (!fs31.existsSync(workspace)) return { ok: true };
58884
+ if (!fs32.existsSync(workspace)) return { ok: true };
58825
58885
  const sourceNode = args.node?.clonedFromNodeId ? args.mesh?.nodes?.find((n) => meshNodeIdMatches(n, args.node.clonedFromNodeId)) : args.mesh?.nodes?.find((n) => !n.isLocalWorktree);
58826
58886
  const repoRoot = typeof sourceNode?.repoRoot === "string" && sourceNode.repoRoot.trim() ? sourceNode.repoRoot.trim() : typeof sourceNode?.workspace === "string" && sourceNode.workspace.trim() ? sourceNode.workspace.trim() : "";
58827
- if (!repoRoot || !fs31.existsSync(repoRoot)) {
58887
+ if (!repoRoot || !fs32.existsSync(repoRoot)) {
58828
58888
  return {
58829
58889
  ok: false,
58830
58890
  code: "mesh_worktree_cleanup_missing_source_repo",
@@ -58844,7 +58904,7 @@ async function precheckLocalWorktreeRemovable(self, args) {
58844
58904
  const normalizePath = (value) => {
58845
58905
  const resolved = (0, import_path15.resolve)(value);
58846
58906
  try {
58847
- return fs31.realpathSync(resolved);
58907
+ return fs32.realpathSync(resolved);
58848
58908
  } catch {
58849
58909
  return resolved;
58850
58910
  }
@@ -58906,13 +58966,13 @@ async function cleanupLocalWorktreeNode(self, args) {
58906
58966
  recoveryHint: "Inspect the mesh node record before removing it, or remove stale metadata manually only after confirming no managed worktree remains."
58907
58967
  };
58908
58968
  }
58909
- const worktreeExists = fs31.existsSync(workspace);
58969
+ const worktreeExists = fs32.existsSync(workspace);
58910
58970
  const sourceNode = args.node?.clonedFromNodeId ? args.mesh?.nodes?.find((n) => meshNodeIdMatches(n, args.node.clonedFromNodeId)) : args.mesh?.nodes?.find((n) => !n.isLocalWorktree);
58911
58971
  const repoRoot = typeof sourceNode?.repoRoot === "string" && sourceNode.repoRoot.trim() ? sourceNode.repoRoot.trim() : typeof sourceNode?.workspace === "string" && sourceNode.workspace.trim() ? sourceNode.workspace.trim() : "";
58912
58972
  if (!worktreeExists) {
58913
58973
  return { success: true, skipped: true, removedPath: workspace, repoRoot: repoRoot || void 0, reason: "worktree_path_missing" };
58914
58974
  }
58915
- if (!repoRoot || !fs31.existsSync(repoRoot)) {
58975
+ if (!repoRoot || !fs32.existsSync(repoRoot)) {
58916
58976
  return {
58917
58977
  success: false,
58918
58978
  code: "mesh_worktree_cleanup_missing_source_repo",
@@ -58932,7 +58992,7 @@ async function cleanupLocalWorktreeNode(self, args) {
58932
58992
  const normalizePath = (value) => {
58933
58993
  const resolved = (0, import_path15.resolve)(value);
58934
58994
  try {
58935
- return fs31.realpathSync(resolved);
58995
+ return fs32.realpathSync(resolved);
58936
58996
  } catch {
58937
58997
  return resolved;
58938
58998
  }
@@ -59566,7 +59626,7 @@ init_logger();
59566
59626
  var yaml5 = __toESM(require("js-yaml"));
59567
59627
  var import_os4 = require("os");
59568
59628
  var import_path16 = require("path");
59569
- var fs32 = __toESM(require("fs"));
59629
+ var fs33 = __toESM(require("fs"));
59570
59630
  function loadYamlModule() {
59571
59631
  return yaml5;
59572
59632
  }
@@ -59590,9 +59650,9 @@ function resolveHermesUserHome() {
59590
59650
  function loadHermesCoordinatorBaseConfig(targetConfigPath) {
59591
59651
  const sourceHome = resolveHermesUserHome();
59592
59652
  const sourceConfigPath = (0, import_path16.join)(sourceHome, "config.yaml");
59593
- if (!fs32.existsSync(sourceConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
59653
+ if (!fs33.existsSync(sourceConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
59594
59654
  if ((0, import_path16.resolve)(sourceConfigPath) === (0, import_path16.resolve)(targetConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
59595
- const parsed = parseMeshCoordinatorMcpConfig(fs32.readFileSync(sourceConfigPath, "utf-8"), "hermes_config_yaml");
59655
+ const parsed = parseMeshCoordinatorMcpConfig(fs33.readFileSync(sourceConfigPath, "utf-8"), "hermes_config_yaml");
59596
59656
  const { mcp_servers: _mcpServers, ...baseConfig } = parsed;
59597
59657
  return { config: baseConfig, sourceHome, sourceConfigPath };
59598
59658
  }
@@ -59629,9 +59689,9 @@ function copyHermesCoordinatorCredentialFiles(sourceHome, targetHome) {
59629
59689
  for (const fileName of [".env", "auth.json"]) {
59630
59690
  const sourcePath = (0, import_path16.join)(sourceHome, fileName);
59631
59691
  const targetPath = (0, import_path16.join)(targetHome, fileName);
59632
- if (!fs32.existsSync(sourcePath)) continue;
59692
+ if (!fs33.existsSync(sourcePath)) continue;
59633
59693
  try {
59634
- fs32.copyFileSync(sourcePath, targetPath);
59694
+ fs33.copyFileSync(sourcePath, targetPath);
59635
59695
  } catch (error) {
59636
59696
  LOG.warn("MeshCoordinator", `Could not copy Hermes ${fileName} into isolated coordinator home: ${error?.message || error}`);
59637
59697
  }
@@ -60023,7 +60083,7 @@ var DaemonCommandRouter = class {
60023
60083
  const nodeId = readInlineMeshNodeId(node);
60024
60084
  if (!nodeId || !tombstones.has(nodeId)) return true;
60025
60085
  const workspace = readStringValue(node?.workspace);
60026
- if (workspace && fs33.existsSync(workspace)) {
60086
+ if (workspace && fs34.existsSync(workspace)) {
60027
60087
  tombstones.delete(nodeId);
60028
60088
  return true;
60029
60089
  }
@@ -61942,12 +62002,12 @@ init_io_contracts();
61942
62002
  init_chat_message_normalization();
61943
62003
 
61944
62004
  // src/providers/version-archive.ts
61945
- var fs34 = __toESM(require("fs"));
61946
- var path38 = __toESM(require("path"));
61947
- var os28 = __toESM(require("os"));
62005
+ var fs35 = __toESM(require("fs"));
62006
+ var path39 = __toESM(require("path"));
62007
+ var os29 = __toESM(require("os"));
61948
62008
  var import_os5 = require("os");
61949
62009
  var import_child_process10 = require("child_process");
61950
- var ARCHIVE_PATH = path38.join(os28.homedir(), ".adhdev", "version-history.json");
62010
+ var ARCHIVE_PATH = path39.join(os29.homedir(), ".adhdev", "version-history.json");
61951
62011
  var MAX_ENTRIES_PER_PROVIDER = 20;
61952
62012
  var VersionArchive = class {
61953
62013
  history = {};
@@ -61956,8 +62016,8 @@ var VersionArchive = class {
61956
62016
  }
61957
62017
  load() {
61958
62018
  try {
61959
- if (fs34.existsSync(ARCHIVE_PATH)) {
61960
- this.history = JSON.parse(fs34.readFileSync(ARCHIVE_PATH, "utf-8"));
62019
+ if (fs35.existsSync(ARCHIVE_PATH)) {
62020
+ this.history = JSON.parse(fs35.readFileSync(ARCHIVE_PATH, "utf-8"));
61961
62021
  }
61962
62022
  } catch {
61963
62023
  this.history = {};
@@ -61994,8 +62054,8 @@ var VersionArchive = class {
61994
62054
  }
61995
62055
  save() {
61996
62056
  try {
61997
- fs34.mkdirSync(path38.dirname(ARCHIVE_PATH), { recursive: true });
61998
- fs34.writeFileSync(ARCHIVE_PATH, JSON.stringify(this.history, null, 2));
62057
+ fs35.mkdirSync(path39.dirname(ARCHIVE_PATH), { recursive: true });
62058
+ fs35.writeFileSync(ARCHIVE_PATH, JSON.stringify(this.history, null, 2));
61999
62059
  } catch {
62000
62060
  }
62001
62061
  }
@@ -62018,10 +62078,10 @@ function findBinary2(name) {
62018
62078
  for (const p of paths) {
62019
62079
  if (!p) continue;
62020
62080
  for (const ext of exes) {
62021
- const fullPath = path38.join(p, name + ext);
62081
+ const fullPath = path39.join(p, name + ext);
62022
62082
  try {
62023
- if (fs34.existsSync(fullPath)) {
62024
- const stat2 = fs34.statSync(fullPath);
62083
+ if (fs35.existsSync(fullPath)) {
62084
+ const stat2 = fs35.statSync(fullPath);
62025
62085
  if (stat2.isFile() && (isWin || stat2.mode & 73)) {
62026
62086
  return fullPath;
62027
62087
  }
@@ -62066,19 +62126,19 @@ async function getVersion(binary, versionCommand) {
62066
62126
  function checkPathExists2(paths) {
62067
62127
  for (const p of paths) {
62068
62128
  if (p.includes("*")) {
62069
- const home = os28.homedir();
62070
- const resolved = p.replace(/\*/g, home.split(path38.sep).pop() || "");
62071
- if (fs34.existsSync(resolved)) return resolved;
62129
+ const home = os29.homedir();
62130
+ const resolved = p.replace(/\*/g, home.split(path39.sep).pop() || "");
62131
+ if (fs35.existsSync(resolved)) return resolved;
62072
62132
  } else {
62073
- if (fs34.existsSync(p)) return p;
62133
+ if (fs35.existsSync(p)) return p;
62074
62134
  }
62075
62135
  }
62076
62136
  return null;
62077
62137
  }
62078
62138
  async function getMacAppVersion(appPath) {
62079
62139
  if ((0, import_os5.platform)() !== "darwin" || !appPath.endsWith(".app")) return null;
62080
- const plistPath = path38.join(appPath, "Contents", "Info.plist");
62081
- if (!fs34.existsSync(plistPath)) return null;
62140
+ const plistPath = path39.join(appPath, "Contents", "Info.plist");
62141
+ if (!fs35.existsSync(plistPath)) return null;
62082
62142
  const raw = await runCommand(`/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "${plistPath}"`);
62083
62143
  return raw || null;
62084
62144
  }
@@ -62104,8 +62164,8 @@ async function detectAllVersions(loader, archive) {
62104
62164
  const cliBin = provider.cli ? findBinary2(provider.cli) : null;
62105
62165
  let resolvedBin = cliBin;
62106
62166
  if (!resolvedBin && appPath && currentOs === "darwin") {
62107
- const bundled = path38.join(appPath, "Contents", "Resources", "app", "bin", provider.cli || "");
62108
- if (provider.cli && fs34.existsSync(bundled)) resolvedBin = bundled;
62167
+ const bundled = path39.join(appPath, "Contents", "Resources", "app", "bin", provider.cli || "");
62168
+ if (provider.cli && fs35.existsSync(bundled)) resolvedBin = bundled;
62109
62169
  }
62110
62170
  info.installed = !!(appPath || resolvedBin);
62111
62171
  info.path = appPath || null;
@@ -62153,8 +62213,8 @@ async function detectAllVersions(loader, archive) {
62153
62213
 
62154
62214
  // src/daemon/dev-server.ts
62155
62215
  var http2 = __toESM(require("http"));
62156
- var fs38 = __toESM(require("fs"));
62157
- var path42 = __toESM(require("path"));
62216
+ var fs39 = __toESM(require("fs"));
62217
+ var path43 = __toESM(require("path"));
62158
62218
  init_config();
62159
62219
 
62160
62220
  // src/daemon/scaffold-template.ts
@@ -62505,8 +62565,8 @@ init_logger();
62505
62565
  init_builders();
62506
62566
 
62507
62567
  // src/daemon/dev-cdp-handlers.ts
62508
- var fs35 = __toESM(require("fs"));
62509
- var path39 = __toESM(require("path"));
62568
+ var fs36 = __toESM(require("fs"));
62569
+ var path40 = __toESM(require("path"));
62510
62570
  init_logger();
62511
62571
  async function handleCdpEvaluate(ctx, req, res) {
62512
62572
  const body = await ctx.readBody(req);
@@ -62685,18 +62745,18 @@ async function handleScriptHints(ctx, type, _req, res) {
62685
62745
  return;
62686
62746
  }
62687
62747
  let scriptsPath = "";
62688
- const directScripts = path39.join(dir, "scripts.js");
62689
- if (fs35.existsSync(directScripts)) {
62748
+ const directScripts = path40.join(dir, "scripts.js");
62749
+ if (fs36.existsSync(directScripts)) {
62690
62750
  scriptsPath = directScripts;
62691
62751
  } else {
62692
- const scriptsDir = path39.join(dir, "scripts");
62693
- if (fs35.existsSync(scriptsDir)) {
62694
- const versions = fs35.readdirSync(scriptsDir).filter((d) => {
62695
- return fs35.statSync(path39.join(scriptsDir, d)).isDirectory();
62752
+ const scriptsDir = path40.join(dir, "scripts");
62753
+ if (fs36.existsSync(scriptsDir)) {
62754
+ const versions = fs36.readdirSync(scriptsDir).filter((d) => {
62755
+ return fs36.statSync(path40.join(scriptsDir, d)).isDirectory();
62696
62756
  }).sort().reverse();
62697
62757
  for (const ver of versions) {
62698
- const p = path39.join(scriptsDir, ver, "scripts.js");
62699
- if (fs35.existsSync(p)) {
62758
+ const p = path40.join(scriptsDir, ver, "scripts.js");
62759
+ if (fs36.existsSync(p)) {
62700
62760
  scriptsPath = p;
62701
62761
  break;
62702
62762
  }
@@ -62708,7 +62768,7 @@ async function handleScriptHints(ctx, type, _req, res) {
62708
62768
  return;
62709
62769
  }
62710
62770
  try {
62711
- const source = fs35.readFileSync(scriptsPath, "utf-8");
62771
+ const source = fs36.readFileSync(scriptsPath, "utf-8");
62712
62772
  const hints = {};
62713
62773
  const funcRegex = /module\.exports\.(\w+)\s*=\s*function\s+\w+\s*\(params\)/g;
62714
62774
  let match;
@@ -63523,8 +63583,8 @@ async function handleDomContext(ctx, type, req, res) {
63523
63583
  }
63524
63584
 
63525
63585
  // src/daemon/dev-cli-debug.ts
63526
- var fs36 = __toESM(require("fs"));
63527
- var path40 = __toESM(require("path"));
63586
+ var fs37 = __toESM(require("fs"));
63587
+ var path41 = __toESM(require("path"));
63528
63588
  function slugifyFixtureName(value) {
63529
63589
  const normalized = String(value || "").trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
63530
63590
  return normalized || `fixture-${Date.now()}`;
@@ -63534,15 +63594,15 @@ function getCliFixtureDir(ctx, type) {
63534
63594
  if (!providerDir) {
63535
63595
  throw new Error(`Provider directory not found for '${type}'`);
63536
63596
  }
63537
- return path40.join(providerDir, "fixtures");
63597
+ return path41.join(providerDir, "fixtures");
63538
63598
  }
63539
63599
  function readCliFixture(ctx, type, name) {
63540
63600
  const fixtureDir = getCliFixtureDir(ctx, type);
63541
- const filePath = path40.join(fixtureDir, `${name}.json`);
63542
- if (!fs36.existsSync(filePath)) {
63601
+ const filePath = path41.join(fixtureDir, `${name}.json`);
63602
+ if (!fs37.existsSync(filePath)) {
63543
63603
  throw new Error(`Fixture not found: ${filePath}`);
63544
63604
  }
63545
- return JSON.parse(fs36.readFileSync(filePath, "utf-8"));
63605
+ return JSON.parse(fs37.readFileSync(filePath, "utf-8"));
63546
63606
  }
63547
63607
  function getExerciseTranscriptText(result) {
63548
63608
  const parts = [];
@@ -64287,7 +64347,7 @@ async function handleCliFixtureCapture(ctx, req, res) {
64287
64347
  return;
64288
64348
  }
64289
64349
  const fixtureDir = getCliFixtureDir(ctx, type);
64290
- fs36.mkdirSync(fixtureDir, { recursive: true });
64350
+ fs37.mkdirSync(fixtureDir, { recursive: true });
64291
64351
  const name = slugifyFixtureName(String(body?.name || `${type}-${Date.now()}`));
64292
64352
  const result = await runCliExerciseInternal(ctx, { ...request, type });
64293
64353
  const fixture = {
@@ -64314,8 +64374,8 @@ async function handleCliFixtureCapture(ctx, req, res) {
64314
64374
  },
64315
64375
  notes: typeof body?.notes === "string" ? body.notes : void 0
64316
64376
  };
64317
- const filePath = path40.join(fixtureDir, `${name}.json`);
64318
- fs36.writeFileSync(filePath, JSON.stringify(fixture, null, 2));
64377
+ const filePath = path41.join(fixtureDir, `${name}.json`);
64378
+ fs37.writeFileSync(filePath, JSON.stringify(fixture, null, 2));
64319
64379
  ctx.json(res, 200, {
64320
64380
  saved: true,
64321
64381
  name,
@@ -64333,14 +64393,14 @@ async function handleCliFixtureCapture(ctx, req, res) {
64333
64393
  async function handleCliFixtureList(ctx, type, _req, res) {
64334
64394
  try {
64335
64395
  const fixtureDir = getCliFixtureDir(ctx, type);
64336
- if (!fs36.existsSync(fixtureDir)) {
64396
+ if (!fs37.existsSync(fixtureDir)) {
64337
64397
  ctx.json(res, 200, { fixtures: [], count: 0 });
64338
64398
  return;
64339
64399
  }
64340
- const fixtures = fs36.readdirSync(fixtureDir).filter((file) => file.endsWith(".json")).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" })).map((file) => {
64341
- const fullPath = path40.join(fixtureDir, file);
64400
+ const fixtures = fs37.readdirSync(fixtureDir).filter((file) => file.endsWith(".json")).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" })).map((file) => {
64401
+ const fullPath = path41.join(fixtureDir, file);
64342
64402
  try {
64343
- const raw = JSON.parse(fs36.readFileSync(fullPath, "utf-8"));
64403
+ const raw = JSON.parse(fs37.readFileSync(fullPath, "utf-8"));
64344
64404
  return {
64345
64405
  name: raw.name || file.replace(/\.json$/i, ""),
64346
64406
  path: fullPath,
@@ -64473,9 +64533,9 @@ async function handleCliRaw(ctx, req, res) {
64473
64533
  }
64474
64534
 
64475
64535
  // src/daemon/dev-auto-implement.ts
64476
- var fs37 = __toESM(require("fs"));
64477
- var path41 = __toESM(require("path"));
64478
- var os29 = __toESM(require("os"));
64536
+ var fs38 = __toESM(require("fs"));
64537
+ var path42 = __toESM(require("path"));
64538
+ var os30 = __toESM(require("os"));
64479
64539
  var import_session_host_core9 = require("@adhdev/session-host-core");
64480
64540
  function getAutoImplPid(ctx) {
64481
64541
  const pid = ctx.autoImplProcess?.pid;
@@ -64522,38 +64582,38 @@ function resolveAutoImplReference(ctx, category, requestedReference, targetType)
64522
64582
  return fallback?.type || null;
64523
64583
  }
64524
64584
  function getLatestScriptVersionDir(scriptsDir) {
64525
- if (!fs37.existsSync(scriptsDir)) return null;
64526
- const versions = fs37.readdirSync(scriptsDir).filter((d) => {
64585
+ if (!fs38.existsSync(scriptsDir)) return null;
64586
+ const versions = fs38.readdirSync(scriptsDir).filter((d) => {
64527
64587
  try {
64528
- return fs37.statSync(path41.join(scriptsDir, d)).isDirectory();
64588
+ return fs38.statSync(path42.join(scriptsDir, d)).isDirectory();
64529
64589
  } catch {
64530
64590
  return false;
64531
64591
  }
64532
64592
  }).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" }));
64533
64593
  if (versions.length === 0) return null;
64534
- return path41.join(scriptsDir, versions[0]);
64594
+ return path42.join(scriptsDir, versions[0]);
64535
64595
  }
64536
64596
  function resolveAutoImplWritableProviderDir(ctx, category, type, requestedDir) {
64537
- const canonicalUserDir = path41.resolve(ctx.providerLoader.getUserProviderDir(category, type));
64538
- const desiredDir = requestedDir ? path41.resolve(requestedDir) : canonicalUserDir;
64539
- const upstreamRoot = path41.resolve(ctx.providerLoader.getUpstreamDir());
64540
- if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path41.sep}`)) {
64597
+ const canonicalUserDir = path42.resolve(ctx.providerLoader.getUserProviderDir(category, type));
64598
+ const desiredDir = requestedDir ? path42.resolve(requestedDir) : canonicalUserDir;
64599
+ const upstreamRoot = path42.resolve(ctx.providerLoader.getUpstreamDir());
64600
+ if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path42.sep}`)) {
64541
64601
  return { dir: null, reason: `Refusing to write into upstream provider directory: ${desiredDir}` };
64542
64602
  }
64543
- if (path41.basename(desiredDir) !== type) {
64603
+ if (path42.basename(desiredDir) !== type) {
64544
64604
  return { dir: null, reason: `Requested writable provider directory must end with '${type}': ${desiredDir}` };
64545
64605
  }
64546
64606
  const sourceDir = ctx.findProviderDir(type);
64547
64607
  if (!sourceDir) {
64548
64608
  return { dir: null, reason: `Provider source directory not found for '${type}'` };
64549
64609
  }
64550
- if (!fs37.existsSync(desiredDir)) {
64551
- fs37.mkdirSync(path41.dirname(desiredDir), { recursive: true });
64552
- fs37.cpSync(sourceDir, desiredDir, { recursive: true });
64610
+ if (!fs38.existsSync(desiredDir)) {
64611
+ fs38.mkdirSync(path42.dirname(desiredDir), { recursive: true });
64612
+ fs38.cpSync(sourceDir, desiredDir, { recursive: true });
64553
64613
  ctx.log(`Auto-implement writable copy created: ${desiredDir}`);
64554
64614
  }
64555
- const providerJson = path41.join(desiredDir, "provider.json");
64556
- if (!fs37.existsSync(providerJson)) {
64615
+ const providerJson = path42.join(desiredDir, "provider.json");
64616
+ if (!fs38.existsSync(providerJson)) {
64557
64617
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
64558
64618
  }
64559
64619
  return { dir: desiredDir };
@@ -64561,15 +64621,15 @@ function resolveAutoImplWritableProviderDir(ctx, category, type, requestedDir) {
64561
64621
  function loadAutoImplReferenceScripts(ctx, referenceType) {
64562
64622
  if (!referenceType) return {};
64563
64623
  const refDir = ctx.findProviderDir(referenceType);
64564
- if (!refDir || !fs37.existsSync(refDir)) return {};
64624
+ if (!refDir || !fs38.existsSync(refDir)) return {};
64565
64625
  const referenceScripts = {};
64566
- const scriptsDir = path41.join(refDir, "scripts");
64626
+ const scriptsDir = path42.join(refDir, "scripts");
64567
64627
  const latestDir = getLatestScriptVersionDir(scriptsDir);
64568
64628
  if (!latestDir) return referenceScripts;
64569
- for (const file of fs37.readdirSync(latestDir)) {
64629
+ for (const file of fs38.readdirSync(latestDir)) {
64570
64630
  if (!file.endsWith(".js")) continue;
64571
64631
  try {
64572
- referenceScripts[file] = fs37.readFileSync(path41.join(latestDir, file), "utf-8");
64632
+ referenceScripts[file] = fs38.readFileSync(path42.join(latestDir, file), "utf-8");
64573
64633
  } catch {
64574
64634
  }
64575
64635
  }
@@ -64677,16 +64737,16 @@ async function handleAutoImplement(ctx, type, req, res) {
64677
64737
  });
64678
64738
  const referenceScripts = loadAutoImplReferenceScripts(ctx, resolvedReference);
64679
64739
  const prompt = buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domContext, referenceScripts, comment, resolvedReference, verification);
64680
- const tmpDir = path41.join(os29.tmpdir(), "adhdev-autoimpl");
64681
- if (!fs37.existsSync(tmpDir)) fs37.mkdirSync(tmpDir, { recursive: true });
64682
- const promptFile = path41.join(tmpDir, `prompt-${type}-${Date.now()}.md`);
64683
- fs37.writeFileSync(promptFile, prompt, "utf-8");
64740
+ const tmpDir = path42.join(os30.tmpdir(), "adhdev-autoimpl");
64741
+ if (!fs38.existsSync(tmpDir)) fs38.mkdirSync(tmpDir, { recursive: true });
64742
+ const promptFile = path42.join(tmpDir, `prompt-${type}-${Date.now()}.md`);
64743
+ fs38.writeFileSync(promptFile, prompt, "utf-8");
64684
64744
  ctx.log(`Auto-implement prompt written to ${promptFile} (${prompt.length} chars)`);
64685
64745
  const agentProvider = ctx.providerLoader.resolve(agent) || ctx.providerLoader.getMeta(agent);
64686
64746
  const spawn5 = agentProvider?.spawn;
64687
64747
  if (!spawn5?.command) {
64688
64748
  try {
64689
- fs37.unlinkSync(promptFile);
64749
+ fs38.unlinkSync(promptFile);
64690
64750
  } catch {
64691
64751
  }
64692
64752
  ctx.json(res, 400, { error: `Agent '${agent}' has no spawn config. Select a CLI provider with a spawn configuration.` });
@@ -64788,7 +64848,7 @@ async function handleAutoImplement(ctx, type, req, res) {
64788
64848
  } catch {
64789
64849
  }
64790
64850
  try {
64791
- fs37.unlinkSync(promptFile);
64851
+ fs38.unlinkSync(promptFile);
64792
64852
  } catch {
64793
64853
  }
64794
64854
  ctx.log(`Auto-implement (ACP) ${success ? "completed" : "failed"}: ${type} (exit: ${code})`);
@@ -64832,7 +64892,7 @@ async function handleAutoImplement(ctx, type, req, res) {
64832
64892
  const interactiveFlags = ["--yolo", "--interactive", "-i"];
64833
64893
  const baseArgs = [...spawn5.args || []].filter((a) => !interactiveFlags.includes(a));
64834
64894
  let shellCmd;
64835
- const isWin = os29.platform() === "win32";
64895
+ const isWin = os30.platform() === "win32";
64836
64896
  const escapeArg = (a) => isWin ? `"${a.replace(/"/g, '""')}"` : `'${a.replace(/'/g, "'\\''")}'`;
64837
64897
  const promptMode = autoImpl?.promptMode ?? "stdin";
64838
64898
  const extraArgs = autoImpl?.extraArgs ?? [];
@@ -64871,7 +64931,7 @@ async function handleAutoImplement(ctx, type, req, res) {
64871
64931
  try {
64872
64932
  const pty = require("node-pty");
64873
64933
  ctx.log(`Auto-implement spawn (PTY): ${shellCmd}`);
64874
- const isWin2 = os29.platform() === "win32";
64934
+ const isWin2 = os30.platform() === "win32";
64875
64935
  child = pty.spawn(isWin2 ? "cmd.exe" : process.env.SHELL || "/bin/zsh", [isWin2 ? "/c" : "-c", shellCmd], {
64876
64936
  name: "xterm-256color",
64877
64937
  cols: import_session_host_core9.DEFAULT_SESSION_HOST_COLS,
@@ -65014,7 +65074,7 @@ async function handleAutoImplement(ctx, type, req, res) {
65014
65074
  }
65015
65075
  });
65016
65076
  try {
65017
- fs37.unlinkSync(promptFile);
65077
+ fs38.unlinkSync(promptFile);
65018
65078
  } catch {
65019
65079
  }
65020
65080
  ctx.log(`Auto-implement ${success ? "completed" : "failed"}: ${type} (exit: ${code})${verificationSummary ? ` verify=${verificationSummary.pass ? "pass" : "fail"}` : ""}`);
@@ -65111,7 +65171,7 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
65111
65171
  setMode: "set_mode.js"
65112
65172
  };
65113
65173
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
65114
- const scriptsDir = path41.join(providerDir, "scripts");
65174
+ const scriptsDir = path42.join(providerDir, "scripts");
65115
65175
  const latestScriptsDir = getLatestScriptVersionDir(scriptsDir);
65116
65176
  if (latestScriptsDir) {
65117
65177
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -65119,10 +65179,10 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
65119
65179
  lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
65120
65180
  lines.push("These are the ONLY files you are allowed to modify. Replace the TODO stubs with working implementations.");
65121
65181
  lines.push("");
65122
- for (const file of fs37.readdirSync(latestScriptsDir)) {
65182
+ for (const file of fs38.readdirSync(latestScriptsDir)) {
65123
65183
  if (file.endsWith(".js") && targetFileNames.has(file)) {
65124
65184
  try {
65125
- const content = fs37.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
65185
+ const content = fs38.readFileSync(path42.join(latestScriptsDir, file), "utf-8");
65126
65186
  lines.push(`### \`${file}\` \u270F\uFE0F EDIT`);
65127
65187
  lines.push("```javascript");
65128
65188
  lines.push(content);
@@ -65132,14 +65192,14 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
65132
65192
  }
65133
65193
  }
65134
65194
  }
65135
- const refFiles = fs37.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
65195
+ const refFiles = fs38.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
65136
65196
  if (refFiles.length > 0) {
65137
65197
  lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
65138
65198
  lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
65139
65199
  lines.push("");
65140
65200
  for (const file of refFiles) {
65141
65201
  try {
65142
- const content = fs37.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
65202
+ const content = fs38.readFileSync(path42.join(latestScriptsDir, file), "utf-8");
65143
65203
  lines.push(`### \`${file}\` \u{1F512}`);
65144
65204
  lines.push("```javascript");
65145
65205
  lines.push(content);
@@ -65180,11 +65240,11 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
65180
65240
  lines.push("");
65181
65241
  }
65182
65242
  }
65183
- const docsDir = path41.join(providerDir, "../../docs");
65243
+ const docsDir = path42.join(providerDir, "../../docs");
65184
65244
  const loadGuide = (name) => {
65185
65245
  try {
65186
- const p = path41.join(docsDir, name);
65187
- if (fs37.existsSync(p)) return fs37.readFileSync(p, "utf-8");
65246
+ const p = path42.join(docsDir, name);
65247
+ if (fs38.existsSync(p)) return fs38.readFileSync(p, "utf-8");
65188
65248
  } catch {
65189
65249
  }
65190
65250
  return null;
@@ -65420,7 +65480,7 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
65420
65480
  parseApproval: "parse_approval.js"
65421
65481
  };
65422
65482
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
65423
- const scriptsDir = path41.join(providerDir, "scripts");
65483
+ const scriptsDir = path42.join(providerDir, "scripts");
65424
65484
  const latestScriptsDir = getLatestScriptVersionDir(scriptsDir);
65425
65485
  if (latestScriptsDir) {
65426
65486
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -65428,11 +65488,11 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
65428
65488
  lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
65429
65489
  lines.push("These are the ONLY files you are allowed to modify. Replace TODO or heuristic-only logic with working PTY-aware implementations.");
65430
65490
  lines.push("");
65431
- for (const file of fs37.readdirSync(latestScriptsDir)) {
65491
+ for (const file of fs38.readdirSync(latestScriptsDir)) {
65432
65492
  if (!file.endsWith(".js")) continue;
65433
65493
  if (!targetFileNames.has(file)) continue;
65434
65494
  try {
65435
- const content = fs37.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
65495
+ const content = fs38.readFileSync(path42.join(latestScriptsDir, file), "utf-8");
65436
65496
  lines.push(`### \`${file}\` \u270F\uFE0F EDIT`);
65437
65497
  lines.push("```javascript");
65438
65498
  lines.push(content);
@@ -65441,14 +65501,14 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
65441
65501
  } catch {
65442
65502
  }
65443
65503
  }
65444
- const refFiles = fs37.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
65504
+ const refFiles = fs38.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
65445
65505
  if (refFiles.length > 0) {
65446
65506
  lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
65447
65507
  lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
65448
65508
  lines.push("");
65449
65509
  for (const file of refFiles) {
65450
65510
  try {
65451
- const content = fs37.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
65511
+ const content = fs38.readFileSync(path42.join(latestScriptsDir, file), "utf-8");
65452
65512
  lines.push(`### \`${file}\` \u{1F512}`);
65453
65513
  lines.push("```javascript");
65454
65514
  lines.push(content);
@@ -65481,11 +65541,11 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
65481
65541
  lines.push("");
65482
65542
  }
65483
65543
  }
65484
- const docsDir = path41.join(providerDir, "../../docs");
65544
+ const docsDir = path42.join(providerDir, "../../docs");
65485
65545
  const loadGuide = (name) => {
65486
65546
  try {
65487
- const p = path41.join(docsDir, name);
65488
- if (fs37.existsSync(p)) return fs37.readFileSync(p, "utf-8");
65547
+ const p = path42.join(docsDir, name);
65548
+ if (fs38.existsSync(p)) return fs38.readFileSync(p, "utf-8");
65489
65549
  } catch {
65490
65550
  }
65491
65551
  return null;
@@ -65931,8 +65991,8 @@ var DevServer = class _DevServer {
65931
65991
  }
65932
65992
  getEndpointList() {
65933
65993
  return this.routes.map((r) => {
65934
- const path44 = typeof r.pattern === "string" ? r.pattern : r.pattern.source.replace(/\\\//g, "/").replace(/\(\[.*?\]\+\)/g, ":type").replace(/[\^$]/g, "");
65935
- return `${r.method.padEnd(5)} ${path44}`;
65994
+ const path45 = typeof r.pattern === "string" ? r.pattern : r.pattern.source.replace(/\\\//g, "/").replace(/\(\[.*?\]\+\)/g, ":type").replace(/[\^$]/g, "");
65995
+ return `${r.method.padEnd(5)} ${path45}`;
65936
65996
  });
65937
65997
  }
65938
65998
  async start(port = DEV_SERVER_PORT) {
@@ -66220,12 +66280,12 @@ var DevServer = class _DevServer {
66220
66280
  // ─── DevConsole SPA ───
66221
66281
  getConsoleDistDir() {
66222
66282
  const candidates = [
66223
- path42.resolve(__dirname, "../../web-devconsole/dist"),
66224
- path42.resolve(__dirname, "../../../web-devconsole/dist"),
66225
- path42.join(process.cwd(), "packages/web-devconsole/dist")
66283
+ path43.resolve(__dirname, "../../web-devconsole/dist"),
66284
+ path43.resolve(__dirname, "../../../web-devconsole/dist"),
66285
+ path43.join(process.cwd(), "packages/web-devconsole/dist")
66226
66286
  ];
66227
66287
  for (const dir of candidates) {
66228
- if (fs38.existsSync(path42.join(dir, "index.html"))) return dir;
66288
+ if (fs39.existsSync(path43.join(dir, "index.html"))) return dir;
66229
66289
  }
66230
66290
  return null;
66231
66291
  }
@@ -66235,9 +66295,9 @@ var DevServer = class _DevServer {
66235
66295
  this.json(res, 500, { error: "DevConsole not found. Run: npm run build -w packages/web-devconsole" });
66236
66296
  return;
66237
66297
  }
66238
- const htmlPath = path42.join(distDir, "index.html");
66298
+ const htmlPath = path43.join(distDir, "index.html");
66239
66299
  try {
66240
- const html = fs38.readFileSync(htmlPath, "utf-8");
66300
+ const html = fs39.readFileSync(htmlPath, "utf-8");
66241
66301
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
66242
66302
  res.end(html);
66243
66303
  } catch (e) {
@@ -66260,15 +66320,15 @@ var DevServer = class _DevServer {
66260
66320
  this.json(res, 404, { error: "Not found" });
66261
66321
  return;
66262
66322
  }
66263
- const safePath = path42.normalize(pathname).replace(/^\.\.\//, "");
66264
- const filePath = path42.join(distDir, safePath);
66323
+ const safePath = path43.normalize(pathname).replace(/^\.\.\//, "");
66324
+ const filePath = path43.join(distDir, safePath);
66265
66325
  if (!filePath.startsWith(distDir)) {
66266
66326
  this.json(res, 403, { error: "Forbidden" });
66267
66327
  return;
66268
66328
  }
66269
66329
  try {
66270
- const content = fs38.readFileSync(filePath);
66271
- const ext = path42.extname(filePath);
66330
+ const content = fs39.readFileSync(filePath);
66331
+ const ext = path43.extname(filePath);
66272
66332
  const contentType = _DevServer.MIME_MAP[ext] || "application/octet-stream";
66273
66333
  res.writeHead(200, { "Content-Type": contentType, "Cache-Control": "public, max-age=31536000, immutable" });
66274
66334
  res.end(content);
@@ -66376,14 +66436,14 @@ var DevServer = class _DevServer {
66376
66436
  const files = [];
66377
66437
  const scan = (d, prefix) => {
66378
66438
  try {
66379
- for (const entry of fs38.readdirSync(d, { withFileTypes: true })) {
66439
+ for (const entry of fs39.readdirSync(d, { withFileTypes: true })) {
66380
66440
  if (entry.name.startsWith(".") || entry.name.endsWith(".bak")) continue;
66381
66441
  const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
66382
66442
  if (entry.isDirectory()) {
66383
66443
  files.push({ path: rel, size: 0, type: "dir" });
66384
- scan(path42.join(d, entry.name), rel);
66444
+ scan(path43.join(d, entry.name), rel);
66385
66445
  } else {
66386
- const stat2 = fs38.statSync(path42.join(d, entry.name));
66446
+ const stat2 = fs39.statSync(path43.join(d, entry.name));
66387
66447
  files.push({ path: rel, size: stat2.size, type: "file" });
66388
66448
  }
66389
66449
  }
@@ -66406,16 +66466,16 @@ var DevServer = class _DevServer {
66406
66466
  this.json(res, 404, { error: `Provider directory not found: ${type}` });
66407
66467
  return;
66408
66468
  }
66409
- const fullPath = path42.resolve(dir, path42.normalize(filePath));
66469
+ const fullPath = path43.resolve(dir, path43.normalize(filePath));
66410
66470
  if (!fullPath.startsWith(dir)) {
66411
66471
  this.json(res, 403, { error: "Forbidden" });
66412
66472
  return;
66413
66473
  }
66414
- if (!fs38.existsSync(fullPath) || fs38.statSync(fullPath).isDirectory()) {
66474
+ if (!fs39.existsSync(fullPath) || fs39.statSync(fullPath).isDirectory()) {
66415
66475
  this.json(res, 404, { error: `File not found: ${filePath}` });
66416
66476
  return;
66417
66477
  }
66418
- const content = fs38.readFileSync(fullPath, "utf-8");
66478
+ const content = fs39.readFileSync(fullPath, "utf-8");
66419
66479
  this.json(res, 200, { type, path: filePath, content, lines: content.split("\n").length });
66420
66480
  }
66421
66481
  /** POST /api/providers/:type/file — write a file { path, content } */
@@ -66431,15 +66491,15 @@ var DevServer = class _DevServer {
66431
66491
  this.json(res, 404, { error: `Provider directory not found: ${type}` });
66432
66492
  return;
66433
66493
  }
66434
- const fullPath = path42.resolve(dir, path42.normalize(filePath));
66494
+ const fullPath = path43.resolve(dir, path43.normalize(filePath));
66435
66495
  if (!fullPath.startsWith(dir)) {
66436
66496
  this.json(res, 403, { error: "Forbidden" });
66437
66497
  return;
66438
66498
  }
66439
66499
  try {
66440
- if (fs38.existsSync(fullPath)) fs38.copyFileSync(fullPath, fullPath + ".bak");
66441
- fs38.mkdirSync(path42.dirname(fullPath), { recursive: true });
66442
- fs38.writeFileSync(fullPath, content, "utf-8");
66500
+ if (fs39.existsSync(fullPath)) fs39.copyFileSync(fullPath, fullPath + ".bak");
66501
+ fs39.mkdirSync(path43.dirname(fullPath), { recursive: true });
66502
+ fs39.writeFileSync(fullPath, content, "utf-8");
66443
66503
  this.log(`File saved: ${fullPath} (${content.length} chars)`);
66444
66504
  this.providerLoader.reload();
66445
66505
  this.json(res, 200, { saved: true, path: filePath, chars: content.length });
@@ -66455,9 +66515,9 @@ var DevServer = class _DevServer {
66455
66515
  return;
66456
66516
  }
66457
66517
  for (const name of ["scripts.js", "provider.json"]) {
66458
- const p = path42.join(dir, name);
66459
- if (fs38.existsSync(p)) {
66460
- const source = fs38.readFileSync(p, "utf-8");
66518
+ const p = path43.join(dir, name);
66519
+ if (fs39.existsSync(p)) {
66520
+ const source = fs39.readFileSync(p, "utf-8");
66461
66521
  this.json(res, 200, { type, path: p, source, lines: source.split("\n").length });
66462
66522
  return;
66463
66523
  }
@@ -66476,11 +66536,11 @@ var DevServer = class _DevServer {
66476
66536
  this.json(res, 404, { error: `Provider not found: ${type}` });
66477
66537
  return;
66478
66538
  }
66479
- const target = fs38.existsSync(path42.join(dir, "scripts.js")) ? "scripts.js" : "provider.json";
66480
- const targetPath = path42.join(dir, target);
66539
+ const target = fs39.existsSync(path43.join(dir, "scripts.js")) ? "scripts.js" : "provider.json";
66540
+ const targetPath = path43.join(dir, target);
66481
66541
  try {
66482
- if (fs38.existsSync(targetPath)) fs38.copyFileSync(targetPath, targetPath + ".bak");
66483
- fs38.writeFileSync(targetPath, source, "utf-8");
66542
+ if (fs39.existsSync(targetPath)) fs39.copyFileSync(targetPath, targetPath + ".bak");
66543
+ fs39.writeFileSync(targetPath, source, "utf-8");
66484
66544
  this.log(`Saved provider: ${targetPath} (${source.length} chars)`);
66485
66545
  this.providerLoader.reload();
66486
66546
  this.json(res, 200, { saved: true, path: targetPath, chars: source.length });
@@ -66624,21 +66684,21 @@ var DevServer = class _DevServer {
66624
66684
  }
66625
66685
  let targetDir;
66626
66686
  targetDir = this.providerLoader.getUserProviderDir(category, type);
66627
- const jsonPath = path42.join(targetDir, "provider.json");
66628
- if (fs38.existsSync(jsonPath)) {
66687
+ const jsonPath = path43.join(targetDir, "provider.json");
66688
+ if (fs39.existsSync(jsonPath)) {
66629
66689
  this.json(res, 409, { error: `Provider already exists at ${targetDir}`, path: targetDir });
66630
66690
  return;
66631
66691
  }
66632
66692
  try {
66633
66693
  const result = generateFiles(type, name, category, { cdpPorts, cli, processName, installPath, binary, extensionId, version, osPaths, processNames });
66634
- fs38.mkdirSync(targetDir, { recursive: true });
66635
- fs38.writeFileSync(jsonPath, result["provider.json"], "utf-8");
66694
+ fs39.mkdirSync(targetDir, { recursive: true });
66695
+ fs39.writeFileSync(jsonPath, result["provider.json"], "utf-8");
66636
66696
  const createdFiles = ["provider.json"];
66637
66697
  if (result.files) {
66638
66698
  for (const [relPath, content] of Object.entries(result.files)) {
66639
- const fullPath = path42.join(targetDir, relPath);
66640
- fs38.mkdirSync(path42.dirname(fullPath), { recursive: true });
66641
- fs38.writeFileSync(fullPath, content, "utf-8");
66699
+ const fullPath = path43.join(targetDir, relPath);
66700
+ fs39.mkdirSync(path43.dirname(fullPath), { recursive: true });
66701
+ fs39.writeFileSync(fullPath, content, "utf-8");
66642
66702
  createdFiles.push(relPath);
66643
66703
  }
66644
66704
  }
@@ -66687,38 +66747,38 @@ var DevServer = class _DevServer {
66687
66747
  }
66688
66748
  // ─── Phase 2: Auto-Implement Backend ───
66689
66749
  getLatestScriptVersionDir(scriptsDir) {
66690
- if (!fs38.existsSync(scriptsDir)) return null;
66691
- const versions = fs38.readdirSync(scriptsDir).filter((d) => {
66750
+ if (!fs39.existsSync(scriptsDir)) return null;
66751
+ const versions = fs39.readdirSync(scriptsDir).filter((d) => {
66692
66752
  try {
66693
- return fs38.statSync(path42.join(scriptsDir, d)).isDirectory();
66753
+ return fs39.statSync(path43.join(scriptsDir, d)).isDirectory();
66694
66754
  } catch {
66695
66755
  return false;
66696
66756
  }
66697
66757
  }).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" }));
66698
66758
  if (versions.length === 0) return null;
66699
- return path42.join(scriptsDir, versions[0]);
66759
+ return path43.join(scriptsDir, versions[0]);
66700
66760
  }
66701
66761
  resolveAutoImplWritableProviderDir(category, type, requestedDir) {
66702
- const canonicalUserDir = path42.resolve(this.providerLoader.getUserProviderDir(category, type));
66703
- const desiredDir = requestedDir ? path42.resolve(requestedDir) : canonicalUserDir;
66704
- const upstreamRoot = path42.resolve(this.providerLoader.getUpstreamDir());
66705
- if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path42.sep}`)) {
66762
+ const canonicalUserDir = path43.resolve(this.providerLoader.getUserProviderDir(category, type));
66763
+ const desiredDir = requestedDir ? path43.resolve(requestedDir) : canonicalUserDir;
66764
+ const upstreamRoot = path43.resolve(this.providerLoader.getUpstreamDir());
66765
+ if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path43.sep}`)) {
66706
66766
  return { dir: null, reason: `Refusing to write into upstream provider directory: ${desiredDir}` };
66707
66767
  }
66708
- if (path42.basename(desiredDir) !== type) {
66768
+ if (path43.basename(desiredDir) !== type) {
66709
66769
  return { dir: null, reason: `Requested writable provider directory must end with '${type}': ${desiredDir}` };
66710
66770
  }
66711
66771
  const sourceDir = this.findProviderDir(type);
66712
66772
  if (!sourceDir) {
66713
66773
  return { dir: null, reason: `Provider source directory not found for '${type}'` };
66714
66774
  }
66715
- if (!fs38.existsSync(desiredDir)) {
66716
- fs38.mkdirSync(path42.dirname(desiredDir), { recursive: true });
66717
- fs38.cpSync(sourceDir, desiredDir, { recursive: true });
66775
+ if (!fs39.existsSync(desiredDir)) {
66776
+ fs39.mkdirSync(path43.dirname(desiredDir), { recursive: true });
66777
+ fs39.cpSync(sourceDir, desiredDir, { recursive: true });
66718
66778
  this.log(`Auto-implement writable copy created: ${desiredDir}`);
66719
66779
  }
66720
- const providerJson = path42.join(desiredDir, "provider.json");
66721
- if (!fs38.existsSync(providerJson)) {
66780
+ const providerJson = path43.join(desiredDir, "provider.json");
66781
+ if (!fs39.existsSync(providerJson)) {
66722
66782
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
66723
66783
  }
66724
66784
  return { dir: desiredDir };
@@ -67560,9 +67620,9 @@ async function listHostedCliRuntimes(endpoint) {
67560
67620
 
67561
67621
  // src/session-host/managed-host.ts
67562
67622
  var import_child_process11 = require("child_process");
67563
- var fs39 = __toESM(require("fs"));
67564
- var os30 = __toESM(require("os"));
67565
- var path43 = __toESM(require("path"));
67623
+ var fs40 = __toESM(require("fs"));
67624
+ var os31 = __toESM(require("os"));
67625
+ var path44 = __toESM(require("path"));
67566
67626
  var import_session_host_core13 = require("@adhdev/session-host-core");
67567
67627
  init_runtime_defaults();
67568
67628
  function createManagedSessionHost(options) {
@@ -67577,24 +67637,24 @@ function createManagedSessionHost(options) {
67577
67637
  }
67578
67638
  function resolveEntry() {
67579
67639
  const packagedCandidates = [
67580
- path43.resolve(__dirname, "../vendor/session-host-daemon/index.js"),
67581
- path43.resolve(__dirname, "../../vendor/session-host-daemon/index.js")
67640
+ path44.resolve(__dirname, "../vendor/session-host-daemon/index.js"),
67641
+ path44.resolve(__dirname, "../../vendor/session-host-daemon/index.js")
67582
67642
  ];
67583
67643
  for (const candidate of packagedCandidates) {
67584
- if (fs39.existsSync(candidate)) {
67644
+ if (fs40.existsSync(candidate)) {
67585
67645
  return candidate;
67586
67646
  }
67587
67647
  }
67588
67648
  return require.resolve("@adhdev/session-host-daemon");
67589
67649
  }
67590
67650
  function getPidFile() {
67591
- return path43.join(os30.homedir(), ".adhdev", `${appName}-session-host.pid`);
67651
+ return path44.join(os31.homedir(), ".adhdev", `${appName}-session-host.pid`);
67592
67652
  }
67593
67653
  function getPid() {
67594
67654
  try {
67595
67655
  const pidFile = getPidFile();
67596
- if (!fs39.existsSync(pidFile)) return null;
67597
- const pid = Number.parseInt(fs39.readFileSync(pidFile, "utf8").trim(), 10);
67656
+ if (!fs40.existsSync(pidFile)) return null;
67657
+ const pid = Number.parseInt(fs40.readFileSync(pidFile, "utf8").trim(), 10);
67598
67658
  return Number.isFinite(pid) ? pid : null;
67599
67659
  } catch {
67600
67660
  return null;
@@ -67619,9 +67679,9 @@ function createManagedSessionHost(options) {
67619
67679
  let stdio = "ignore";
67620
67680
  let logFd = null;
67621
67681
  if (options.spawnStdio === "logfile") {
67622
- const logDir = path43.join(os30.homedir(), ".adhdev", "logs");
67623
- fs39.mkdirSync(logDir, { recursive: true });
67624
- logFd = fs39.openSync(path43.join(logDir, "session-host.log"), "a");
67682
+ const logDir = path44.join(os31.homedir(), ".adhdev", "logs");
67683
+ fs40.mkdirSync(logDir, { recursive: true });
67684
+ logFd = fs40.openSync(path44.join(logDir, "session-host.log"), "a");
67625
67685
  stdio = ["ignore", logFd, logFd];
67626
67686
  }
67627
67687
  const child = (0, import_child_process11.spawn)(process.execPath, [entry], {
@@ -67633,7 +67693,7 @@ function createManagedSessionHost(options) {
67633
67693
  child.unref();
67634
67694
  if (logFd !== null) {
67635
67695
  try {
67636
- fs39.closeSync(logFd);
67696
+ fs40.closeSync(logFd);
67637
67697
  } catch {
67638
67698
  }
67639
67699
  }
@@ -67642,8 +67702,8 @@ function createManagedSessionHost(options) {
67642
67702
  let stopped = false;
67643
67703
  const pidFile = getPidFile();
67644
67704
  try {
67645
- if (fs39.existsSync(pidFile)) {
67646
- const pid = Number.parseInt(fs39.readFileSync(pidFile, "utf8").trim(), 10);
67705
+ if (fs40.existsSync(pidFile)) {
67706
+ const pid = Number.parseInt(fs40.readFileSync(pidFile, "utf8").trim(), 10);
67647
67707
  if (Number.isFinite(pid) && pid !== process.pid && isManagedPid(pid)) {
67648
67708
  stopped = killPid2(pid) || stopped;
67649
67709
  }
@@ -67651,7 +67711,7 @@ function createManagedSessionHost(options) {
67651
67711
  } catch {
67652
67712
  } finally {
67653
67713
  try {
67654
- fs39.unlinkSync(pidFile);
67714
+ fs40.unlinkSync(pidFile);
67655
67715
  } catch {
67656
67716
  }
67657
67717
  }
@@ -67837,8 +67897,8 @@ async function installExtension(ide, extension) {
67837
67897
  const res = await fetch(extension.vsixUrl);
67838
67898
  if (res.ok) {
67839
67899
  const buffer = Buffer.from(await res.arrayBuffer());
67840
- const fs40 = await import("fs");
67841
- fs40.writeFileSync(vsixPath, buffer);
67900
+ const fs41 = await import("fs");
67901
+ fs41.writeFileSync(vsixPath, buffer);
67842
67902
  return new Promise((resolve25) => {
67843
67903
  const cmd = `"${ide.cliCommand}" --install-extension "${vsixPath}" --force`;
67844
67904
  (0, import_child_process12.exec)(cmd, { timeout: 6e4 }, (error, _stdout, stderr) => {