@adhdev/daemon-core 0.9.82-rc.540 → 0.9.82-rc.542

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -414,10 +414,10 @@ function readInjected(value) {
414
414
  }
415
415
  function getDaemonBuildInfo() {
416
416
  if (cached) return cached;
417
- const commit = readInjected(true ? "0674080aa30d25acbfb5c295598d15f686d4cba3" : void 0) ?? "unknown";
418
- const commitShort = readInjected(true ? "0674080a" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
419
- const version = readInjected(true ? "0.9.82-rc.540" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
420
- const builtAt = readInjected(true ? "2026-07-16T01:53:13.412Z" : void 0);
417
+ const commit = readInjected(true ? "eb1fb961d4f22983420fad4c65b982d3ab42b5cf" : void 0) ?? "unknown";
418
+ const commitShort = readInjected(true ? "eb1fb961" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
419
+ const version = readInjected(true ? "0.9.82-rc.542" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
420
+ const builtAt = readInjected(true ? "2026-07-16T06:30:14.678Z" : void 0);
421
421
  cached = builtAt ? { commit, commitShort, version, builtAt } : { commit, commitShort, version };
422
422
  return cached;
423
423
  }
@@ -4070,7 +4070,8 @@ function buildRulesSection(coordinatorCliType) {
4070
4070
  - **Coordinator runtime is not a delegation default.** This coordinator is running as \`${coordinatorCliType}\`, but delegated node sessions must follow the user's requested provider, not the coordinator's own runtime.` : "";
4071
4071
  return `## Rules
4072
4072
 
4073
- - **Route, don't implement.** Delegate all code reading, analysis, and execution to node agents. Never read source files or run commands in the coordinator \u2014 keep context lean.
4073
+ - **Route, don't implement.** Delegate all code reading, analysis, and execution to node agents. Never read source files or run commands in the coordinator \u2014 keep context lean. See also: **Never use local sub-agents** below.
4074
+ - **Never use local sub-agents.** Do NOT spawn your runtime's own sub-agents (e.g. Claude Code's Task/Explore/Agent tools, or any equivalent in-process agent-spawning tool) to read code, investigate, run RCA, or implement. Such sub-agents execute on the coordinator's machine, outside the mesh \u2014 they escape mesh parallelism, the ledger/audit trail, node capability profiles, and worktree isolation, and leave no \`mesh_task_history\` record. ALL code reading, analysis, RCA, and implementation must be delegated to mesh nodes via \`mesh_enqueue_task\` / \`mesh_send_task\` (use \`task_mode: "live_debug_readonly"\` for read-only investigation), or cross-verified via \`mesh_magi_review\` for read-only fan-out. The coordinator's own actions are limited to \`mesh_*\` tool orchestration and synthesizing results.
4074
4075
  - **Front-load task messages.** Include everything the agent needs (files, problem, expected fix) in \`mesh_enqueue_task\` / \`mesh_send_task\`. Append a structured result request at the end: ask the worker to conclude with a JSON block containing \`status\`, \`changedFiles\`, \`gitStatus\`, \`validationResults\`, \`errors\`, \`nextAction\`. The daemon parses this automatically; you can read it from \`mesh_task_history\`.
4075
4076
  - **Reuse idle sessions.** For follow-up, retry, commit/push, or cleanup on the same issue, send only the delta to the existing idle session. Start a fresh session only when: (a) branch/worktree isolation is required, (b) the existing session had a dispatch failure or provider mismatch, (c) the transcript/runtime is contaminated or interrupted, or (d) the user explicitly asks for a different provider/session. Continuation of the same issue in an already-idle session is allowed and preferred \u2014 this rule blocks concurrent unrelated work interleaved into a live (still-generating) session, not sequential same-issue follow-ups.
4076
4077
  - **Worktree affinity.** A worktree is a durable per-branch workspace; keep all of a branch's code_change/fix/review work on its worktree node by targeting \`required_tags: ["worktree=<branch>"]\` or \`target_node_id\`. Get the id/branch from the \`mesh_clone_node\` result or a live \`mesh_status\` \u2014 the Configured Nodes snapshot won't list a worktree cloned after launch. Untargeted same-branch follow-ups drift to the base node. Only \`convergence\` (merge/push) runs on the base, never pinned to the worktree.
@@ -10646,8 +10647,8 @@ function stripCoordinatorWrapperFile(filePath) {
10646
10647
  const remaining = (existing.slice(0, openIdx) + existing.slice(closeIdx + CLOSE.length)).replace(/^\s*\n+/, "").replace(/\n+\s*$/, "");
10647
10648
  if (!remaining.trim()) {
10648
10649
  try {
10649
- const fs42 = __require("fs");
10650
- fs42.unlinkSync(filePath);
10650
+ const fs43 = __require("fs");
10651
+ fs43.unlinkSync(filePath);
10651
10652
  } catch {
10652
10653
  }
10653
10654
  } else {
@@ -12644,9 +12645,9 @@ function findBinary(name) {
12644
12645
  for (const ext of exes) {
12645
12646
  const fullPath = path11.join(p, trimmed + ext);
12646
12647
  try {
12647
- const fs42 = __require("fs");
12648
- if (fs42.existsSync(fullPath)) {
12649
- const stat2 = fs42.statSync(fullPath);
12648
+ const fs43 = __require("fs");
12649
+ if (fs43.existsSync(fullPath)) {
12650
+ const stat2 = fs43.statSync(fullPath);
12650
12651
  if (stat2.isFile() && (isWin || stat2.mode & 73)) {
12651
12652
  return fullPath;
12652
12653
  }
@@ -12660,12 +12661,12 @@ function findBinary(name) {
12660
12661
  function isScriptBinary(binaryPath) {
12661
12662
  if (!path11.isAbsolute(binaryPath)) return false;
12662
12663
  try {
12663
- const fs42 = __require("fs");
12664
- const resolved = fs42.realpathSync(binaryPath);
12664
+ const fs43 = __require("fs");
12665
+ const resolved = fs43.realpathSync(binaryPath);
12665
12666
  const head = Buffer.alloc(8);
12666
- const fd = fs42.openSync(resolved, "r");
12667
- fs42.readSync(fd, head, 0, 8, 0);
12668
- fs42.closeSync(fd);
12667
+ const fd = fs43.openSync(resolved, "r");
12668
+ fs43.readSync(fd, head, 0, 8, 0);
12669
+ fs43.closeSync(fd);
12669
12670
  let i = 0;
12670
12671
  if (head[0] === 239 && head[1] === 187 && head[2] === 191) i = 3;
12671
12672
  return head[i] === 35 && head[i + 1] === 33;
@@ -12676,12 +12677,12 @@ function isScriptBinary(binaryPath) {
12676
12677
  function looksLikeMachOOrElf(filePath) {
12677
12678
  if (!path11.isAbsolute(filePath)) return false;
12678
12679
  try {
12679
- const fs42 = __require("fs");
12680
- const resolved = fs42.realpathSync(filePath);
12680
+ const fs43 = __require("fs");
12681
+ const resolved = fs43.realpathSync(filePath);
12681
12682
  const buf = Buffer.alloc(8);
12682
- const fd = fs42.openSync(resolved, "r");
12683
- fs42.readSync(fd, buf, 0, 8, 0);
12684
- fs42.closeSync(fd);
12683
+ const fd = fs43.openSync(resolved, "r");
12684
+ fs43.readSync(fd, buf, 0, 8, 0);
12685
+ fs43.closeSync(fd);
12685
12686
  let i = 0;
12686
12687
  if (buf[0] === 239 && buf[1] === 187 && buf[2] === 191) i = 3;
12687
12688
  const b = buf.subarray(i);
@@ -12970,19 +12971,19 @@ async function resolveDetectionPath(command, whichCmd) {
12970
12971
  return null;
12971
12972
  }
12972
12973
  function execAsync(cmd, timeoutMs = 5e3) {
12973
- return new Promise((resolve25) => {
12974
+ return new Promise((resolve26) => {
12974
12975
  const child = exec(cmd, {
12975
12976
  encoding: "utf-8",
12976
12977
  timeout: timeoutMs,
12977
12978
  ...process.platform === "win32" ? { windowsHide: true } : {}
12978
12979
  }, (err, stdout) => {
12979
12980
  if (err || !stdout?.trim()) {
12980
- resolve25(null);
12981
+ resolve26(null);
12981
12982
  } else {
12982
- resolve25(stdout.trim());
12983
+ resolve26(stdout.trim());
12983
12984
  }
12984
12985
  });
12985
- child.on("error", () => resolve25(null));
12986
+ child.on("error", () => resolve26(null));
12986
12987
  });
12987
12988
  }
12988
12989
  async function detectCLIs(providerLoader, options) {
@@ -13126,7 +13127,7 @@ var init_runtime_surface = __esm({
13126
13127
  // src/mesh/mesh-warmup-deadline.ts
13127
13128
  function awaitWithWarmupDeadline(work, opts) {
13128
13129
  const pollMs = Math.max(1, Math.min(opts.pollIntervalMs ?? 200, opts.connectTimeoutMs));
13129
- return new Promise((resolve25, reject) => {
13130
+ return new Promise((resolve26, reject) => {
13130
13131
  let done = false;
13131
13132
  let poll;
13132
13133
  let responseTimer;
@@ -13176,7 +13177,7 @@ function awaitWithWarmupDeadline(work, opts) {
13176
13177
  if (typeof poll.unref === "function") poll.unref();
13177
13178
  }
13178
13179
  work.then(
13179
- (val) => settle(() => resolve25(val)),
13180
+ (val) => settle(() => resolve26(val)),
13180
13181
  (err) => settle(() => reject(err))
13181
13182
  );
13182
13183
  });
@@ -14262,7 +14263,7 @@ async function probeRemoteMeshGitStatusWithRetry(args) {
14262
14263
  const connection = args.getConnection?.(args.daemonId);
14263
14264
  if (args.getConnection && readMeshConnectionState(connection) !== "connected") break;
14264
14265
  if (connection) args.onConnection?.(connection);
14265
- await new Promise((resolve25) => setTimeout(resolve25, 250 * 2 ** (attempt - 1)));
14266
+ await new Promise((resolve26) => setTimeout(resolve26, 250 * 2 ** (attempt - 1)));
14266
14267
  }
14267
14268
  try {
14268
14269
  const remoteGit = await probeRemoteMeshGitStatus({
@@ -16046,7 +16047,7 @@ async function waitForLocalSessionReady(components, sessionId) {
16046
16047
  const deadline = Date.now() + LOCAL_LAUNCH_READY_TIMEOUT_MS;
16047
16048
  while (Date.now() < deadline) {
16048
16049
  if (adapter.isReady() || adapter.currentStatus === "idle") return;
16049
- await new Promise((resolve25) => setTimeout(resolve25, LOCAL_LAUNCH_READY_POLL_MS));
16050
+ await new Promise((resolve26) => setTimeout(resolve26, LOCAL_LAUNCH_READY_POLL_MS));
16050
16051
  }
16051
16052
  LOG.warn("MeshQueue", `Auto-launched session ${sessionId} not interactive after ${LOCAL_LAUNCH_READY_TIMEOUT_MS}ms; dispatching anyway (adapter queue-until-ready will buffer)`);
16052
16053
  }
@@ -19530,8 +19531,12 @@ function buildCliSession(state, options) {
19530
19531
  settings: state.settings,
19531
19532
  ...coordinator && { coordinator },
19532
19533
  ...meshQueueStats && { meshQueueStats },
19533
- ...resolveSurfaceHidden(state.settings) && { surfaceHidden: true },
19534
- ...resolveMuted(state.settings) && { muted: true }
19534
+ // Emit these booleans explicitly (including false) so an un-hide/un-mute clears a
19535
+ // previously-true value downstream. Consumers merge with `?? existing` and copy only
19536
+ // `!== undefined` fields, so an absent field on false never overwrote a prior true —
19537
+ // the toggle-off direction silently stuck. See session-entry-merge.ts.
19538
+ surfaceHidden: resolveSurfaceHidden(state.settings),
19539
+ muted: resolveMuted(state.settings)
19535
19540
  };
19536
19541
  }
19537
19542
  function buildAcpSession(state, options) {
@@ -19572,8 +19577,10 @@ function buildAcpSession(state, options) {
19572
19577
  settings: state.settings,
19573
19578
  ...coordinator && { coordinator },
19574
19579
  ...meshQueueStats && { meshQueueStats },
19575
- ...resolveSurfaceHidden(state.settings) && { surfaceHidden: true },
19576
- ...resolveMuted(state.settings) && { muted: true }
19580
+ // Emit explicitly (including false) so un-hide/un-mute clears a prior true downstream —
19581
+ // see buildCliSession above and session-entry-merge.ts.
19582
+ surfaceHidden: resolveSurfaceHidden(state.settings),
19583
+ muted: resolveMuted(state.settings)
19577
19584
  };
19578
19585
  }
19579
19586
  function buildSessionEntries(allStates, cdpManagers, options = {}) {
@@ -23714,7 +23721,7 @@ __export(external_sources_exports, {
23714
23721
  sourcesFilePath: () => sourcesFilePath,
23715
23722
  sourcesProviding: () => sourcesProviding
23716
23723
  });
23717
- import * as fs10 from "fs";
23724
+ import * as fs11 from "fs";
23718
23725
  import * as os12 from "os";
23719
23726
  import * as path19 from "path";
23720
23727
  function adhdevDir() {
@@ -23731,13 +23738,13 @@ function activeFilePath() {
23731
23738
  }
23732
23739
  function ensureAdhdevDir() {
23733
23740
  const d = adhdevDir();
23734
- if (!fs10.existsSync(d)) fs10.mkdirSync(d, { recursive: true });
23741
+ if (!fs11.existsSync(d)) fs11.mkdirSync(d, { recursive: true });
23735
23742
  }
23736
23743
  function loadExternalSources() {
23737
23744
  const p = sourcesFilePath();
23738
- if (!fs10.existsSync(p)) return { schema: 1, sources: [] };
23745
+ if (!fs11.existsSync(p)) return { schema: 1, sources: [] };
23739
23746
  try {
23740
- const raw = JSON.parse(fs10.readFileSync(p, "utf-8"));
23747
+ const raw = JSON.parse(fs11.readFileSync(p, "utf-8"));
23741
23748
  if (!raw || typeof raw !== "object") return { schema: 1, sources: [] };
23742
23749
  const sources = Array.isArray(raw.sources) ? raw.sources.filter(isValidSource) : [];
23743
23750
  return { schema: 1, sources };
@@ -23748,14 +23755,14 @@ function loadExternalSources() {
23748
23755
  function saveExternalSources(file) {
23749
23756
  ensureAdhdevDir();
23750
23757
  const tmp = sourcesFilePath() + ".tmp";
23751
- fs10.writeFileSync(tmp, JSON.stringify(file, null, 2) + "\n", "utf-8");
23752
- fs10.renameSync(tmp, sourcesFilePath());
23758
+ fs11.writeFileSync(tmp, JSON.stringify(file, null, 2) + "\n", "utf-8");
23759
+ fs11.renameSync(tmp, sourcesFilePath());
23753
23760
  }
23754
23761
  function loadProvidersActive() {
23755
23762
  const p = activeFilePath();
23756
- if (!fs10.existsSync(p)) return { schema: 1, active: {} };
23763
+ if (!fs11.existsSync(p)) return { schema: 1, active: {} };
23757
23764
  try {
23758
- const raw = JSON.parse(fs10.readFileSync(p, "utf-8"));
23765
+ const raw = JSON.parse(fs11.readFileSync(p, "utf-8"));
23759
23766
  if (!raw || typeof raw !== "object") return { schema: 1, active: {} };
23760
23767
  const active = raw.active && typeof raw.active === "object" ? raw.active : {};
23761
23768
  return { schema: 1, active };
@@ -23766,8 +23773,8 @@ function loadProvidersActive() {
23766
23773
  function saveProvidersActive(file) {
23767
23774
  ensureAdhdevDir();
23768
23775
  const tmp = activeFilePath() + ".tmp";
23769
- fs10.writeFileSync(tmp, JSON.stringify(file, null, 2) + "\n", "utf-8");
23770
- fs10.renameSync(tmp, activeFilePath());
23776
+ fs11.writeFileSync(tmp, JSON.stringify(file, null, 2) + "\n", "utf-8");
23777
+ fs11.renameSync(tmp, activeFilePath());
23771
23778
  }
23772
23779
  function isValidSource(x) {
23773
23780
  if (!x || typeof x !== "object") return false;
@@ -23783,11 +23790,11 @@ function deriveSourceName(url) {
23783
23790
  }
23784
23791
  function inventoryExternalSources() {
23785
23792
  const root = externalRoot();
23786
- if (!fs10.existsSync(root)) return [];
23793
+ if (!fs11.existsSync(root)) return [];
23787
23794
  const out = [];
23788
23795
  let entries;
23789
23796
  try {
23790
- entries = fs10.readdirSync(root, { withFileTypes: true });
23797
+ entries = fs11.readdirSync(root, { withFileTypes: true });
23791
23798
  } catch {
23792
23799
  return [];
23793
23800
  }
@@ -23798,7 +23805,7 @@ function inventoryExternalSources() {
23798
23805
  const providers = {};
23799
23806
  let categoryEntries;
23800
23807
  try {
23801
- categoryEntries = fs10.readdirSync(sourceDir, { withFileTypes: true });
23808
+ categoryEntries = fs11.readdirSync(sourceDir, { withFileTypes: true });
23802
23809
  } catch {
23803
23810
  continue;
23804
23811
  }
@@ -23808,7 +23815,7 @@ function inventoryExternalSources() {
23808
23815
  const categoryDir = path19.join(sourceDir, category);
23809
23816
  let typeEntries;
23810
23817
  try {
23811
- typeEntries = fs10.readdirSync(categoryDir, { withFileTypes: true });
23818
+ typeEntries = fs11.readdirSync(categoryDir, { withFileTypes: true });
23812
23819
  } catch {
23813
23820
  continue;
23814
23821
  }
@@ -23816,8 +23823,8 @@ function inventoryExternalSources() {
23816
23823
  for (const typeEntry of typeEntries) {
23817
23824
  if (!typeEntry.isDirectory()) continue;
23818
23825
  const typeDir = path19.join(categoryDir, typeEntry.name);
23819
- const hasV1 = fs10.existsSync(path19.join(typeDir, "provider.v1.json"));
23820
- const hasV0 = fs10.existsSync(path19.join(typeDir, "provider.json"));
23826
+ const hasV1 = fs11.existsSync(path19.join(typeDir, "provider.v1.json"));
23827
+ const hasV0 = fs11.existsSync(path19.join(typeDir, "provider.json"));
23821
23828
  if (hasV1 || hasV0) types.push(typeEntry.name);
23822
23829
  }
23823
23830
  if (types.length > 0) providers[category] = types;
@@ -23890,11 +23897,11 @@ __export(fsm_loader_exports, {
23890
23897
  loadFsmSpec: () => loadFsmSpec,
23891
23898
  validateFsmSpec: () => validateFsmSpec
23892
23899
  });
23893
- import * as fs11 from "fs";
23900
+ import * as fs12 from "fs";
23894
23901
  function loadFsmSpec(sourcePath) {
23895
23902
  let raw;
23896
23903
  try {
23897
- raw = JSON.parse(fs11.readFileSync(sourcePath, "utf8"));
23904
+ raw = JSON.parse(fs12.readFileSync(sourcePath, "utf8"));
23898
23905
  } catch (err) {
23899
23906
  return { ok: false, errors: [`Failed to read/parse spec: ${err.message}`], sourcePath };
23900
23907
  }
@@ -24508,8 +24515,8 @@ var init_pty_transport = __esm({
24508
24515
  let cwd = options.cwd;
24509
24516
  if (cwd) {
24510
24517
  try {
24511
- const fs42 = __require("fs");
24512
- const stat2 = fs42.statSync(cwd);
24518
+ const fs43 = __require("fs");
24519
+ const stat2 = fs43.statSync(cwd);
24513
24520
  if (!stat2.isDirectory()) cwd = os14.homedir();
24514
24521
  } catch {
24515
24522
  cwd = os14.homedir();
@@ -25497,7 +25504,7 @@ var init_provider_cli_parse = __esm({
25497
25504
  });
25498
25505
 
25499
25506
  // src/cli-adapters/cli-state-engine.ts
25500
- var SCRIPT_STATUS_DEBOUNCE_MS, MAX_FINISH_RETRIES, FINISH_RETRY_DELAY_MS, MAX_TRACE_ENTRIES, APPROVAL_EXIT_TIMEOUT_MS, IDLE_CONFIRMATION_GRACE_MS, APPROVAL_RESUME_IDLE_DEFER_CAP_MS, CliStateEngine;
25507
+ var SCRIPT_STATUS_DEBOUNCE_MS, MAX_FINISH_RETRIES, FINISH_RETRY_DELAY_MS, MAX_TRACE_ENTRIES, APPROVAL_EXIT_TIMEOUT_MS, IDLE_CONFIRMATION_GRACE_MS, APPROVAL_RESUME_IDLE_DEFER_CAP_MS, SCREEN_QUIET_IDLE_MS, CliStateEngine;
25501
25508
  var init_cli_state_engine = __esm({
25502
25509
  "src/cli-adapters/cli-state-engine.ts"() {
25503
25510
  "use strict";
@@ -25511,6 +25518,7 @@ var init_cli_state_engine = __esm({
25511
25518
  APPROVAL_EXIT_TIMEOUT_MS = 6e4;
25512
25519
  IDLE_CONFIRMATION_GRACE_MS = 2e3;
25513
25520
  APPROVAL_RESUME_IDLE_DEFER_CAP_MS = 18e3;
25521
+ SCREEN_QUIET_IDLE_MS = 5e3;
25514
25522
  CliStateEngine = class {
25515
25523
  constructor(provider, runner, transport, callbacks, timeouts) {
25516
25524
  this.provider = provider;
@@ -26075,6 +26083,10 @@ var init_cli_state_engine = __esm({
26075
26083
  this.idleTimeout = setTimeout(() => {
26076
26084
  if (this.isWaitingForResponse && !this.hasActionableApproval()) {
26077
26085
  if (this.shouldDeferIdleTimeoutFinish()) return;
26086
+ if (!this.hasScreenBeenQuietForIdle(Date.now())) {
26087
+ this.evaluateSettled(this.transport.getSnapshot());
26088
+ return;
26089
+ }
26078
26090
  this.finishResponse();
26079
26091
  }
26080
26092
  }, this.timeouts.generatingIdle);
@@ -26097,6 +26109,10 @@ var init_cli_state_engine = __esm({
26097
26109
  this.idleTimeout = setTimeout(() => {
26098
26110
  if (this.isWaitingForResponse && !this.hasActionableApproval()) {
26099
26111
  if (this.shouldDeferIdleTimeoutFinish()) return;
26112
+ if (!this.hasScreenBeenQuietForIdle(Date.now())) {
26113
+ this.evaluateSettled(this.transport.getSnapshot());
26114
+ return;
26115
+ }
26100
26116
  this.finishResponse();
26101
26117
  }
26102
26118
  }, this.timeouts.generatingIdle);
@@ -26165,6 +26181,10 @@ var init_cli_state_engine = __esm({
26165
26181
  this.idleTimeout = setTimeout(() => {
26166
26182
  if (this.isWaitingForResponse) {
26167
26183
  if (this.shouldDeferIdleTimeoutFinish()) return;
26184
+ if (!this.hasScreenBeenQuietForIdle(Date.now())) {
26185
+ this.evaluateSettled(this.transport.getSnapshot());
26186
+ return;
26187
+ }
26168
26188
  this.finishResponse();
26169
26189
  }
26170
26190
  }, this.timeouts.generatingIdle);
@@ -26250,7 +26270,8 @@ var init_cli_state_engine = __esm({
26250
26270
  const assistantLength = lastParsedAssistant?.content?.length || 0;
26251
26271
  const idleFinishConfirmMs = this.timeouts.idleFinishConfirm;
26252
26272
  const idleQuietThresholdMs = Math.max(idleFinishConfirmMs, this.timeouts.outputSettle);
26253
- const idleReady = !modal && hasAssistantTurn && quietForMs >= idleQuietThresholdMs && screenStableMs >= idleFinishConfirmMs;
26273
+ const screenQuietForIdle = screenStableMs >= SCREEN_QUIET_IDLE_MS;
26274
+ const idleReady = !modal && hasAssistantTurn && quietForMs >= idleQuietThresholdMs && screenStableMs >= idleFinishConfirmMs && screenQuietForIdle;
26254
26275
  const candidate = this.idleFinishCandidate;
26255
26276
  const candidateQuiet = !!candidate && candidate.responseEpoch === this.responseEpoch && candidate.lastOutputAt === snap.lastOutputAt && candidate.lastScreenChangeAt === snap.lastScreenChangeAt && assistantLength >= candidate.assistantLength && now - candidate.armedAt >= idleFinishConfirmMs;
26256
26277
  if (this.shouldDeferIdleForApprovalResume(now)) {
@@ -26285,6 +26306,13 @@ var init_cli_state_engine = __esm({
26285
26306
  return;
26286
26307
  }
26287
26308
  if (this.shouldDeferIdleTimeoutFinish()) return;
26309
+ if (!this.hasScreenBeenQuietForIdle(Date.now())) {
26310
+ if (this.idleTimeout) clearTimeout(this.idleTimeout);
26311
+ this.idleTimeout = setTimeout(() => {
26312
+ if (this.isWaitingForResponse) this.evaluateSettled(this.transport.getSnapshot());
26313
+ }, this.timeouts.idleFinish);
26314
+ return;
26315
+ }
26288
26316
  const parsed = this.runParseSession(this.transport.getSnapshot());
26289
26317
  if (this.shouldDeferFinishForTranscript(parsed)) {
26290
26318
  this.rescheduleTranscriptFinishCheck("transcript_idle_timeout_not_final");
@@ -26295,6 +26323,22 @@ var init_cli_state_engine = __esm({
26295
26323
  }
26296
26324
  }, this.timeouts.idleFinish);
26297
26325
  }
26326
+ /**
26327
+ * FALSE-IDLE (screen-quiet gate): has the visible terminal screen content been
26328
+ * byte-identical for at least SCREEN_QUIET_IDLE_MS continuously?
26329
+ *
26330
+ * `lastScreenChangeAt` is bumped by the adapter every time the normalized screen
26331
+ * snapshot changes (spinner frame, streaming command output, etc.), so
26332
+ * `now - lastScreenChangeAt` is the real screen-diff quiet age. Reads the LIVE
26333
+ * transport snapshot so the deferred idleFinish timeout re-checks current screen
26334
+ * state, not the stale snapshot from when the timer was armed. A never-changed
26335
+ * screen (lastScreenChangeAt === 0) is treated as quiet.
26336
+ */
26337
+ hasScreenBeenQuietForIdle(now) {
26338
+ const lastChange = this.transport.getSnapshot().lastScreenChangeAt;
26339
+ if (!lastChange) return true;
26340
+ return now - lastChange >= SCREEN_QUIET_IDLE_MS;
26341
+ }
26298
26342
  /**
26299
26343
  * FALSE-IDLE (Fix 2): should applyIdle suppress the idle/finish for the current
26300
26344
  * turn because we are inside the post-approval resume grace?
@@ -27374,7 +27418,7 @@ ${lastSnapshot}`;
27374
27418
  `[${this.cliType}] Waiting for interactive prompt: status=${status} stableMs=${stableMs} recentOutputMs=${recentlyOutput} screen=${JSON.stringify(summarizeCliTraceText(screenText, 220)).slice(0, 260)}`
27375
27419
  );
27376
27420
  }
27377
- await new Promise((resolve25) => setTimeout(resolve25, 50));
27421
+ await new Promise((resolve26) => setTimeout(resolve26, 50));
27378
27422
  }
27379
27423
  const finalScreenText = this.terminalScreen.getText() || "";
27380
27424
  LOG.warn(
@@ -27741,7 +27785,7 @@ ${lastSnapshot}`;
27741
27785
  if (!this.ptyProcess) throw new Error(`${this.cliName} is not running`);
27742
27786
  await this.ptyProcess.write(chunks[i]);
27743
27787
  if (i + 1 < chunks.length) {
27744
- await new Promise((resolve25) => setTimeout(resolve25, WIN32_PTY_WRITE_CHUNK_GAP_MS));
27788
+ await new Promise((resolve26) => setTimeout(resolve26, WIN32_PTY_WRITE_CHUNK_GAP_MS));
27745
27789
  }
27746
27790
  }
27747
27791
  }
@@ -27909,7 +27953,7 @@ ${lastSnapshot}`;
27909
27953
  this.onStatusChange?.();
27910
27954
  }
27911
27955
  async waitForForceSubmitSettle() {
27912
- await new Promise((resolve25) => setTimeout(resolve25, FORCE_SUBMIT_SETTLE_MS));
27956
+ await new Promise((resolve26) => setTimeout(resolve26, FORCE_SUBMIT_SETTLE_MS));
27913
27957
  }
27914
27958
  enqueuePendingOutboundMessage(text, reason, meshTaskId) {
27915
27959
  const content = String(text || "");
@@ -27988,7 +28032,7 @@ ${lastSnapshot}`;
27988
28032
  const deadline = Date.now() + 1e4;
27989
28033
  while (this.startupParseGate && Date.now() < deadline) {
27990
28034
  this.resolveStartupState("send_wait");
27991
- await new Promise((resolve25) => setTimeout(resolve25, 50));
28035
+ await new Promise((resolve26) => setTimeout(resolve26, 50));
27992
28036
  }
27993
28037
  }
27994
28038
  const parsedStatusBeforeSend = !allowInputDuringGeneration ? (() => {
@@ -28081,13 +28125,13 @@ ${lastSnapshot}`;
28081
28125
  isFirstTurn: !this.firstTurnSent
28082
28126
  };
28083
28127
  this.engine.responseSettleIgnoreUntil = Date.now() + submitDelayMs + this.timeouts.outputSettle + 250;
28084
- await new Promise((resolve25, reject) => {
28128
+ await new Promise((resolve26, reject) => {
28085
28129
  let resolved = false;
28086
28130
  const completion = {
28087
28131
  resolveOnce: () => {
28088
28132
  if (resolved) return;
28089
28133
  resolved = true;
28090
- resolve25();
28134
+ resolve26();
28091
28135
  },
28092
28136
  rejectOnce: (error) => {
28093
28137
  if (resolved) return;
@@ -28275,17 +28319,17 @@ ${lastSnapshot}`;
28275
28319
  }
28276
28320
  }
28277
28321
  waitForStopped(timeoutMs) {
28278
- return new Promise((resolve25) => {
28322
+ return new Promise((resolve26) => {
28279
28323
  const startedAt = Date.now();
28280
28324
  const timer = setInterval(() => {
28281
28325
  if (!this.ptyProcess || this.engine.currentStatus === "stopped") {
28282
28326
  clearInterval(timer);
28283
- resolve25(true);
28327
+ resolve26(true);
28284
28328
  return;
28285
28329
  }
28286
28330
  if (Date.now() - startedAt >= timeoutMs) {
28287
28331
  clearInterval(timer);
28288
- resolve25(false);
28332
+ resolve26(false);
28289
28333
  }
28290
28334
  }, 100);
28291
28335
  });
@@ -30621,8 +30665,8 @@ async function detectIDEs(providerLoader) {
30621
30665
  if (existsSync21(bundledCli)) resolvedCli = bundledCli;
30622
30666
  }
30623
30667
  if (!resolvedCli && appPath && os32 === "win32") {
30624
- const { dirname: dirname17 } = await import("path");
30625
- const appDir = dirname17(appPath);
30668
+ const { dirname: dirname18 } = await import("path");
30669
+ const appDir = dirname18(appPath);
30626
30670
  const candidates = [
30627
30671
  `${appDir}\\\\bin\\\\${def.cli}.cmd`,
30628
30672
  `${appDir}\\\\bin\\\\${def.cli}`,
@@ -30880,7 +30924,7 @@ var DaemonCdpManager = class {
30880
30924
  * Returns multiple entries if multiple IDE windows are open on same port
30881
30925
  */
30882
30926
  static listAllTargets(port) {
30883
- return new Promise((resolve25) => {
30927
+ return new Promise((resolve26) => {
30884
30928
  const req = http.get(`http://127.0.0.1:${port}/json`, (res) => {
30885
30929
  let data = "";
30886
30930
  res.on("data", (chunk) => data += chunk.toString());
@@ -30896,16 +30940,16 @@ var DaemonCdpManager = class {
30896
30940
  (t) => !isNonMain(t.title || "") && t.url?.includes("workbench.html") && !t.url?.includes("agent")
30897
30941
  );
30898
30942
  const fallbackPages = pages.filter((t) => !isNonMain(t.title || ""));
30899
- resolve25(mainPages.length > 0 ? mainPages : fallbackPages);
30943
+ resolve26(mainPages.length > 0 ? mainPages : fallbackPages);
30900
30944
  } catch {
30901
- resolve25([]);
30945
+ resolve26([]);
30902
30946
  }
30903
30947
  });
30904
30948
  });
30905
- req.on("error", () => resolve25([]));
30949
+ req.on("error", () => resolve26([]));
30906
30950
  req.setTimeout(2e3, () => {
30907
30951
  req.destroy();
30908
- resolve25([]);
30952
+ resolve26([]);
30909
30953
  });
30910
30954
  });
30911
30955
  }
@@ -30945,7 +30989,7 @@ var DaemonCdpManager = class {
30945
30989
  }
30946
30990
  }
30947
30991
  findTargetOnPort(port) {
30948
- return new Promise((resolve25) => {
30992
+ return new Promise((resolve26) => {
30949
30993
  const req = http.get(`http://127.0.0.1:${port}/json`, (res) => {
30950
30994
  let data = "";
30951
30995
  res.on("data", (chunk) => data += chunk.toString());
@@ -30956,7 +31000,7 @@ var DaemonCdpManager = class {
30956
31000
  (t) => (t.type === "page" || t.type === "browser" || t.type === "Page") && t.webSocketDebuggerUrl
30957
31001
  );
30958
31002
  if (pages.length === 0) {
30959
- resolve25(targets.find((t) => t.webSocketDebuggerUrl) || null);
31003
+ resolve26(targets.find((t) => t.webSocketDebuggerUrl) || null);
30960
31004
  return;
30961
31005
  }
30962
31006
  const titleFilteredPages = pages.filter((t) => !this.isNonMainTitle(t.title || ""));
@@ -30975,25 +31019,25 @@ var DaemonCdpManager = class {
30975
31019
  this._targetId = selected.target.id;
30976
31020
  }
30977
31021
  this._pageTitle = selected.target.title || "";
30978
- resolve25(selected.target);
31022
+ resolve26(selected.target);
30979
31023
  return;
30980
31024
  }
30981
31025
  if (previousTargetId) {
30982
31026
  this.log(`[CDP] Target ${previousTargetId} not found in page list`);
30983
- resolve25(null);
31027
+ resolve26(null);
30984
31028
  return;
30985
31029
  }
30986
31030
  this._pageTitle = list[0]?.title || "";
30987
- resolve25(list[0]);
31031
+ resolve26(list[0]);
30988
31032
  } catch {
30989
- resolve25(null);
31033
+ resolve26(null);
30990
31034
  }
30991
31035
  });
30992
31036
  });
30993
- req.on("error", () => resolve25(null));
31037
+ req.on("error", () => resolve26(null));
30994
31038
  req.setTimeout(2e3, () => {
30995
31039
  req.destroy();
30996
- resolve25(null);
31040
+ resolve26(null);
30997
31041
  });
30998
31042
  });
30999
31043
  }
@@ -31004,7 +31048,7 @@ var DaemonCdpManager = class {
31004
31048
  this.extensionProviders = providers;
31005
31049
  }
31006
31050
  connectToTarget(wsUrl) {
31007
- return new Promise((resolve25) => {
31051
+ return new Promise((resolve26) => {
31008
31052
  this.ws = new WebSocket(wsUrl);
31009
31053
  this.ws.on("open", async () => {
31010
31054
  this._connected = true;
@@ -31014,17 +31058,17 @@ var DaemonCdpManager = class {
31014
31058
  }
31015
31059
  this.connectBrowserWs().catch(() => {
31016
31060
  });
31017
- resolve25(true);
31061
+ resolve26(true);
31018
31062
  });
31019
31063
  this.ws.on("message", (data) => {
31020
31064
  try {
31021
31065
  const msg = JSON.parse(data.toString());
31022
31066
  if (msg.id && this.pending.has(msg.id)) {
31023
- const { resolve: resolve26, reject } = this.pending.get(msg.id);
31067
+ const { resolve: resolve27, reject } = this.pending.get(msg.id);
31024
31068
  this.pending.delete(msg.id);
31025
31069
  this.failureCount = 0;
31026
31070
  if (msg.error) reject(new Error(msg.error.message));
31027
- else resolve26(msg.result);
31071
+ else resolve27(msg.result);
31028
31072
  } else if (msg.method === "Runtime.executionContextCreated") {
31029
31073
  this.contexts.add(msg.params.context.id);
31030
31074
  } else if (msg.method === "Runtime.executionContextDestroyed") {
@@ -31047,7 +31091,7 @@ var DaemonCdpManager = class {
31047
31091
  this.ws.on("error", (err) => {
31048
31092
  this.log(`[CDP] WebSocket error: ${err.message}`);
31049
31093
  this._connected = false;
31050
- resolve25(false);
31094
+ resolve26(false);
31051
31095
  });
31052
31096
  });
31053
31097
  }
@@ -31061,7 +31105,7 @@ var DaemonCdpManager = class {
31061
31105
  return;
31062
31106
  }
31063
31107
  this.log(`[CDP] Connecting browser WS for target discovery...`);
31064
- await new Promise((resolve25, reject) => {
31108
+ await new Promise((resolve26, reject) => {
31065
31109
  this.browserWs = new WebSocket(browserWsUrl);
31066
31110
  this.browserWs.on("open", async () => {
31067
31111
  this._browserConnected = true;
@@ -31071,16 +31115,16 @@ var DaemonCdpManager = class {
31071
31115
  } catch (e) {
31072
31116
  this.log(`[CDP] setDiscoverTargets failed: ${e.message}`);
31073
31117
  }
31074
- resolve25();
31118
+ resolve26();
31075
31119
  });
31076
31120
  this.browserWs.on("message", (data) => {
31077
31121
  try {
31078
31122
  const msg = JSON.parse(data.toString());
31079
31123
  if (msg.id && this.browserPending.has(msg.id)) {
31080
- const { resolve: resolve26, reject: reject2 } = this.browserPending.get(msg.id);
31124
+ const { resolve: resolve27, reject: reject2 } = this.browserPending.get(msg.id);
31081
31125
  this.browserPending.delete(msg.id);
31082
31126
  if (msg.error) reject2(new Error(msg.error.message));
31083
- else resolve26(msg.result);
31127
+ else resolve27(msg.result);
31084
31128
  }
31085
31129
  } catch {
31086
31130
  }
@@ -31100,31 +31144,31 @@ var DaemonCdpManager = class {
31100
31144
  }
31101
31145
  }
31102
31146
  getBrowserWsUrl() {
31103
- return new Promise((resolve25) => {
31147
+ return new Promise((resolve26) => {
31104
31148
  const req = http.get(`http://127.0.0.1:${this.port}/json/version`, (res) => {
31105
31149
  let data = "";
31106
31150
  res.on("data", (chunk) => data += chunk.toString());
31107
31151
  res.on("end", () => {
31108
31152
  try {
31109
31153
  const info = JSON.parse(data);
31110
- resolve25(info.webSocketDebuggerUrl || null);
31154
+ resolve26(info.webSocketDebuggerUrl || null);
31111
31155
  } catch {
31112
- resolve25(null);
31156
+ resolve26(null);
31113
31157
  }
31114
31158
  });
31115
31159
  });
31116
- req.on("error", () => resolve25(null));
31160
+ req.on("error", () => resolve26(null));
31117
31161
  req.setTimeout(3e3, () => {
31118
31162
  req.destroy();
31119
- resolve25(null);
31163
+ resolve26(null);
31120
31164
  });
31121
31165
  });
31122
31166
  }
31123
31167
  sendBrowser(method, params = {}, timeoutMs = 15e3) {
31124
- return new Promise((resolve25, reject) => {
31168
+ return new Promise((resolve26, reject) => {
31125
31169
  if (!this.browserWs || !this._browserConnected) return reject(new Error("Browser WS not connected"));
31126
31170
  const id = this.browserMsgId++;
31127
- this.browserPending.set(id, { resolve: resolve25, reject });
31171
+ this.browserPending.set(id, { resolve: resolve26, reject });
31128
31172
  this.browserWs.send(JSON.stringify({ id, method, params }));
31129
31173
  setTimeout(() => {
31130
31174
  if (this.browserPending.has(id)) {
@@ -31164,11 +31208,11 @@ var DaemonCdpManager = class {
31164
31208
  }
31165
31209
  // ─── CDP Protocol ────────────────────────────────────────
31166
31210
  sendInternal(method, params = {}, timeoutMs = 15e3) {
31167
- return new Promise((resolve25, reject) => {
31211
+ return new Promise((resolve26, reject) => {
31168
31212
  if (!this.ws || !this._connected) return reject(new Error("CDP not connected"));
31169
31213
  if (this.ws.readyState !== WebSocket.OPEN) return reject(new Error("WebSocket not open"));
31170
31214
  const id = this.msgId++;
31171
- this.pending.set(id, { resolve: resolve25, reject });
31215
+ this.pending.set(id, { resolve: resolve26, reject });
31172
31216
  this.ws.send(JSON.stringify({ id, method, params }));
31173
31217
  setTimeout(() => {
31174
31218
  if (this.pending.has(id)) {
@@ -31417,7 +31461,7 @@ var DaemonCdpManager = class {
31417
31461
  const browserWs = this.browserWs;
31418
31462
  let msgId = this.browserMsgId;
31419
31463
  const sendWs = (method, params = {}, sessionId) => {
31420
- return new Promise((resolve25, reject) => {
31464
+ return new Promise((resolve26, reject) => {
31421
31465
  const mid = msgId++;
31422
31466
  this.browserMsgId = msgId;
31423
31467
  const handler = (raw) => {
@@ -31426,7 +31470,7 @@ var DaemonCdpManager = class {
31426
31470
  if (msg.id === mid) {
31427
31471
  browserWs.removeListener("message", handler);
31428
31472
  if (msg.error) reject(new Error(msg.error.message || JSON.stringify(msg.error)));
31429
- else resolve25(msg.result);
31473
+ else resolve26(msg.result);
31430
31474
  }
31431
31475
  } catch {
31432
31476
  }
@@ -31627,14 +31671,14 @@ var DaemonCdpManager = class {
31627
31671
  if (!ws || ws.readyState !== WebSocket.OPEN) {
31628
31672
  throw new Error("CDP not connected");
31629
31673
  }
31630
- return new Promise((resolve25, reject) => {
31674
+ return new Promise((resolve26, reject) => {
31631
31675
  const id = getNextId();
31632
31676
  pendingMap.set(id, {
31633
31677
  resolve: (result) => {
31634
31678
  if (result?.result?.subtype === "error") {
31635
31679
  reject(new Error(result.result.description));
31636
31680
  } else {
31637
- resolve25(result?.result?.value);
31681
+ resolve26(result?.result?.value);
31638
31682
  }
31639
31683
  },
31640
31684
  reject
@@ -31666,10 +31710,10 @@ var DaemonCdpManager = class {
31666
31710
  throw new Error("CDP not connected");
31667
31711
  }
31668
31712
  const sendViaSession = (method, params = {}) => {
31669
- return new Promise((resolve25, reject) => {
31713
+ return new Promise((resolve26, reject) => {
31670
31714
  const pendingMap = this._browserConnected ? this.browserPending : this.pending;
31671
31715
  const id = this._browserConnected ? this.browserMsgId++ : this.msgId++;
31672
- pendingMap.set(id, { resolve: resolve25, reject });
31716
+ pendingMap.set(id, { resolve: resolve26, reject });
31673
31717
  ws.send(JSON.stringify({ id, sessionId, method, params }));
31674
31718
  setTimeout(() => {
31675
31719
  if (pendingMap.has(id)) {
@@ -35584,13 +35628,14 @@ function resolveTargetSessionActualWorkspace(h, targetSessionId) {
35584
35628
  // src/commands/chat-commands-debug-bundle.ts
35585
35629
  init_logger();
35586
35630
  init_debug_trace();
35587
- import * as fs8 from "fs";
35631
+ import * as fs9 from "fs";
35588
35632
  import * as os10 from "os";
35589
35633
  import * as path17 from "path";
35590
35634
  import { randomUUID as randomUUID11 } from "crypto";
35591
35635
 
35592
35636
  // src/commands/chat-commands-read.ts
35593
35637
  init_contracts2();
35638
+ import * as fs8 from "fs";
35594
35639
  import * as path16 from "path";
35595
35640
  init_state_store();
35596
35641
  init_coordinator_registry();
@@ -36543,7 +36588,16 @@ function readExactRuntimeMirrorMessages(args) {
36543
36588
  function normalizeComparableWorkspace(value) {
36544
36589
  const text = typeof value === "string" ? value.trim() : "";
36545
36590
  if (!text) return "";
36546
- return path16.resolve(text);
36591
+ const lexical = path16.resolve(text);
36592
+ try {
36593
+ return fs8.realpathSync.native(lexical);
36594
+ } catch {
36595
+ try {
36596
+ return fs8.realpathSync(lexical);
36597
+ } catch {
36598
+ return lexical;
36599
+ }
36600
+ }
36547
36601
  }
36548
36602
  function isCurrentRuntimePtySafelyAttributed(args) {
36549
36603
  if (args.adapter.cliType !== "codex-cli") return false;
@@ -37861,11 +37915,11 @@ function buildChatDebugBundleSummary(bundle) {
37861
37915
  function storeChatDebugBundleOnDaemon(bundle, targetSessionId) {
37862
37916
  const bundleId = createChatDebugBundleId(targetSessionId);
37863
37917
  const dir = getChatDebugBundleDir();
37864
- fs8.mkdirSync(dir, { recursive: true });
37918
+ fs9.mkdirSync(dir, { recursive: true });
37865
37919
  const savedPath = path17.join(dir, `${bundleId}.json`);
37866
37920
  const json = `${JSON.stringify(bundle, null, 2)}
37867
37921
  `;
37868
- fs8.writeFileSync(savedPath, json, { encoding: "utf8", mode: 384 });
37922
+ fs9.writeFileSync(savedPath, json, { encoding: "utf8", mode: 384 });
37869
37923
  return { bundleId, savedPath, sizeBytes: Buffer.byteLength(json, "utf8") };
37870
37924
  }
37871
37925
  function isDaemonFileDebugDelivery(args) {
@@ -38026,7 +38080,7 @@ function getSendChatInputEnvelope(args) {
38026
38080
  return normalizeInputEnvelope(args?.input ? { input: args.input } : args);
38027
38081
  }
38028
38082
  function sleep(ms) {
38029
- return new Promise((resolve25) => setTimeout(resolve25, ms));
38083
+ return new Promise((resolve26) => setTimeout(resolve26, ms));
38030
38084
  }
38031
38085
  async function waitOnceForFreshHermesCliStart(adapter, log) {
38032
38086
  if (adapter.cliType !== "hermes-cli") return;
@@ -38081,7 +38135,7 @@ function getStateLastSignature(state) {
38081
38135
  async function getStableExtensionBaseline(h) {
38082
38136
  const first = await readExtensionChatState(h);
38083
38137
  if (getStateMessageCount(first) > 0 || getStateLastSignature(first)) return first;
38084
- await new Promise((resolve25) => setTimeout(resolve25, 150));
38138
+ await new Promise((resolve26) => setTimeout(resolve26, 150));
38085
38139
  const second = await readExtensionChatState(h);
38086
38140
  return getStateMessageCount(second) >= getStateMessageCount(first) ? second : first;
38087
38141
  }
@@ -38089,7 +38143,7 @@ async function verifyExtensionSendObserved(h, before) {
38089
38143
  const beforeCount = getStateMessageCount(before);
38090
38144
  const beforeSignature = getStateLastSignature(before);
38091
38145
  for (let attempt = 0; attempt < 12; attempt += 1) {
38092
- await new Promise((resolve25) => setTimeout(resolve25, 250));
38146
+ await new Promise((resolve26) => setTimeout(resolve26, 250));
38093
38147
  const state = await readExtensionChatState(h);
38094
38148
  if (state?.status === "waiting_approval") return true;
38095
38149
  const afterCount = getStateMessageCount(state);
@@ -38806,7 +38860,7 @@ async function handleResolveAction(h, args) {
38806
38860
  }
38807
38861
 
38808
38862
  // src/commands/cdp-commands.ts
38809
- import * as fs9 from "fs";
38863
+ import * as fs10 from "fs";
38810
38864
  import * as path18 from "path";
38811
38865
  import * as os11 from "os";
38812
38866
  var KEY_TO_VK = {
@@ -39079,7 +39133,7 @@ function resolveSafePath(requestedPath) {
39079
39133
  return path18.resolve(inputPath);
39080
39134
  }
39081
39135
  function listDirectoryEntriesSafe(dirPath) {
39082
- const entries = fs9.readdirSync(dirPath, { withFileTypes: true });
39136
+ const entries = fs10.readdirSync(dirPath, { withFileTypes: true });
39083
39137
  const files = [];
39084
39138
  for (const entry of entries) {
39085
39139
  const entryPath = path18.join(dirPath, entry.name);
@@ -39091,14 +39145,14 @@ function listDirectoryEntriesSafe(dirPath) {
39091
39145
  if (entry.isFile()) {
39092
39146
  let size;
39093
39147
  try {
39094
- size = fs9.statSync(entryPath).size;
39148
+ size = fs10.statSync(entryPath).size;
39095
39149
  } catch {
39096
39150
  size = void 0;
39097
39151
  }
39098
39152
  files.push({ name: entry.name, type: "file", size });
39099
39153
  continue;
39100
39154
  }
39101
- const stat2 = fs9.statSync(entryPath);
39155
+ const stat2 = fs10.statSync(entryPath);
39102
39156
  files.push({
39103
39157
  name: entry.name,
39104
39158
  type: stat2.isDirectory() ? "directory" : "file",
@@ -39116,7 +39170,7 @@ function listWindowsDriveEntries(excludePath) {
39116
39170
  const letter = String.fromCharCode(code);
39117
39171
  const root = `${letter}:\\`;
39118
39172
  try {
39119
- if (!fs9.existsSync(root)) continue;
39173
+ if (!fs10.existsSync(root)) continue;
39120
39174
  if (excluded && root.toLowerCase() === excluded) continue;
39121
39175
  drives.push({ name: `${letter}:`, type: "directory", path: root });
39122
39176
  } catch {
@@ -39127,7 +39181,7 @@ function listWindowsDriveEntries(excludePath) {
39127
39181
  async function handleFileRead(h, args) {
39128
39182
  try {
39129
39183
  const filePath = resolveSafePath(args?.path);
39130
- const content = fs9.readFileSync(filePath, "utf-8");
39184
+ const content = fs10.readFileSync(filePath, "utf-8");
39131
39185
  return { success: true, content, path: filePath };
39132
39186
  } catch (e) {
39133
39187
  return { success: false, error: e.message };
@@ -39136,8 +39190,8 @@ async function handleFileRead(h, args) {
39136
39190
  async function handleFileWrite(h, args) {
39137
39191
  try {
39138
39192
  const filePath = resolveSafePath(args?.path);
39139
- fs9.mkdirSync(path18.dirname(filePath), { recursive: true });
39140
- fs9.writeFileSync(filePath, args?.content || "", "utf-8");
39193
+ fs10.mkdirSync(path18.dirname(filePath), { recursive: true });
39194
+ fs10.writeFileSync(filePath, args?.content || "", "utf-8");
39141
39195
  return { success: true, path: filePath };
39142
39196
  } catch (e) {
39143
39197
  return { success: false, error: e.message };
@@ -39491,7 +39545,7 @@ async function executeProviderScript(h, args, scriptName) {
39491
39545
  const enterCount = cliCommand.enterCount || 1;
39492
39546
  await adapter.writeRaw(cliCommand.text + "\r");
39493
39547
  for (let i = 1; i < enterCount; i += 1) {
39494
- await new Promise((resolve25) => setTimeout(resolve25, 50));
39548
+ await new Promise((resolve26) => setTimeout(resolve26, 50));
39495
39549
  await adapter.writeRaw("\r");
39496
39550
  }
39497
39551
  }
@@ -40295,11 +40349,11 @@ var DaemonCommandHandler = class {
40295
40349
  return { success: false, error: "invalid type" };
40296
40350
  }
40297
40351
  const https = __require("https");
40298
- const fs42 = __require("fs");
40352
+ const fs43 = __require("fs");
40299
40353
  const path45 = __require("path");
40300
40354
  const REGISTRY = resolveRegistryBaseUrl(loadConfig().registryUrl);
40301
40355
  function fetchText(url, timeoutMs) {
40302
- return new Promise((resolve25, reject) => {
40356
+ return new Promise((resolve26, reject) => {
40303
40357
  const req = https.get(url, { headers: { "User-Agent": "adhdev-daemon", "Accept": "application/json" }, timeout: timeoutMs }, (res) => {
40304
40358
  if (res.statusCode !== 200) {
40305
40359
  reject(new Error(`HTTP ${res.statusCode}`));
@@ -40307,7 +40361,7 @@ var DaemonCommandHandler = class {
40307
40361
  }
40308
40362
  const chunks = [];
40309
40363
  res.on("data", (c) => chunks.push(c));
40310
- res.on("end", () => resolve25(Buffer.concat(chunks).toString("utf-8")));
40364
+ res.on("end", () => resolve26(Buffer.concat(chunks).toString("utf-8")));
40311
40365
  });
40312
40366
  req.on("error", reject);
40313
40367
  req.on("timeout", () => {
@@ -40338,7 +40392,7 @@ var DaemonCommandHandler = class {
40338
40392
  if (!targetDir.startsWith(installRootResolved + path45.sep)) {
40339
40393
  return { success: false, error: "install path escaped upstream root" };
40340
40394
  }
40341
- fs42.mkdirSync(targetDir, { recursive: true });
40395
+ fs43.mkdirSync(targetDir, { recursive: true });
40342
40396
  let manifestProbe = {};
40343
40397
  try {
40344
40398
  manifestProbe = JSON.parse(manifestBody);
@@ -40363,7 +40417,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
40363
40417
  }
40364
40418
  const targetFile = isV1 ? "provider.v1.json" : "provider.json";
40365
40419
  const targetPath = path45.join(targetDir, targetFile);
40366
- fs42.writeFileSync(targetPath, manifestBody, "utf-8");
40420
+ fs43.writeFileSync(targetPath, manifestBody, "utf-8");
40367
40421
  const manifestJson = JSON.parse(manifestBody);
40368
40422
  const scriptFetch = await this.fetchProviderSources(
40369
40423
  manifestJson,
@@ -40433,10 +40487,10 @@ ${formatManifestValidationIssues2(validation.issues)}`,
40433
40487
  const repo = source.repo;
40434
40488
  const ref = source.ref;
40435
40489
  const https = __require("https");
40436
- const fs42 = __require("fs");
40490
+ const fs43 = __require("fs");
40437
40491
  const path45 = __require("path");
40438
40492
  function fetchJson(url, timeoutMs) {
40439
- return new Promise((resolve25, reject) => {
40493
+ return new Promise((resolve26, reject) => {
40440
40494
  const req = https.get(url, {
40441
40495
  headers: { "User-Agent": "adhdev-daemon", "Accept": "application/vnd.github+json" },
40442
40496
  timeout: timeoutMs
@@ -40449,7 +40503,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
40449
40503
  res.on("data", (c) => chunks.push(c));
40450
40504
  res.on("end", () => {
40451
40505
  try {
40452
- resolve25(JSON.parse(Buffer.concat(chunks).toString("utf-8")));
40506
+ resolve26(JSON.parse(Buffer.concat(chunks).toString("utf-8")));
40453
40507
  } catch (e) {
40454
40508
  reject(e);
40455
40509
  }
@@ -40463,14 +40517,14 @@ ${formatManifestValidationIssues2(validation.issues)}`,
40463
40517
  });
40464
40518
  }
40465
40519
  function fetchBinary(url, timeoutMs) {
40466
- return new Promise((resolve25, reject) => {
40520
+ return new Promise((resolve26, reject) => {
40467
40521
  const req = https.get(url, {
40468
40522
  headers: { "User-Agent": "adhdev-daemon" },
40469
40523
  timeout: timeoutMs
40470
40524
  }, (res) => {
40471
40525
  if (res.statusCode === 301 || res.statusCode === 302) {
40472
40526
  if (res.headers.location) {
40473
- return fetchBinary(res.headers.location, timeoutMs).then(resolve25, reject);
40527
+ return fetchBinary(res.headers.location, timeoutMs).then(resolve26, reject);
40474
40528
  }
40475
40529
  }
40476
40530
  if (res.statusCode !== 200) {
@@ -40479,7 +40533,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
40479
40533
  }
40480
40534
  const chunks = [];
40481
40535
  res.on("data", (c) => chunks.push(c));
40482
- res.on("end", () => resolve25(Buffer.concat(chunks)));
40536
+ res.on("end", () => resolve26(Buffer.concat(chunks)));
40483
40537
  });
40484
40538
  req.on("error", reject);
40485
40539
  req.on("timeout", () => {
@@ -40517,8 +40571,8 @@ ${formatManifestValidationIssues2(validation.issues)}`,
40517
40571
  const relInside = entry.path.startsWith(sharedDirRel + "/") ? entry.path.slice(sharedDirRel.length + 1) : entry.path;
40518
40572
  const outPath = path45.resolve(path45.join(sharedTargetDir, relInside));
40519
40573
  if (!outPath.startsWith(path45.resolve(sharedTargetDir) + path45.sep)) continue;
40520
- fs42.mkdirSync(path45.dirname(outPath), { recursive: true });
40521
- fs42.writeFileSync(outPath, body);
40574
+ fs43.mkdirSync(path45.dirname(outPath), { recursive: true });
40575
+ fs43.writeFileSync(outPath, body);
40522
40576
  fetchedCount++;
40523
40577
  } catch (e) {
40524
40578
  errors.push(`fetch shared ${entry.path}: ${e?.message ?? e}`);
@@ -40556,8 +40610,8 @@ ${formatManifestValidationIssues2(validation.issues)}`,
40556
40610
  errors.push(`refusing to write outside targetDir: ${entry.path}`);
40557
40611
  continue;
40558
40612
  }
40559
- fs42.mkdirSync(path45.dirname(outPath), { recursive: true });
40560
- fs42.writeFileSync(outPath, body);
40613
+ fs43.mkdirSync(path45.dirname(outPath), { recursive: true });
40614
+ fs43.writeFileSync(outPath, body);
40561
40615
  fetchedCount++;
40562
40616
  } catch (e) {
40563
40617
  errors.push(`fetch ${entry.path}: ${e?.message ?? e}`);
@@ -40585,7 +40639,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
40585
40639
  if (!["cli", "ide", "extension", "acp"].includes(category)) {
40586
40640
  return { success: false, error: `unknown category: ${category}` };
40587
40641
  }
40588
- const fs42 = __require("fs");
40642
+ const fs43 = __require("fs");
40589
40643
  const path45 = __require("path");
40590
40644
  try {
40591
40645
  const installRoot = this.getUpstreamInstallRoot();
@@ -40594,10 +40648,10 @@ ${formatManifestValidationIssues2(validation.issues)}`,
40594
40648
  if (!targetDir.startsWith(installRootResolved + path45.sep)) {
40595
40649
  return { success: false, error: "refusing to delete outside upstream root" };
40596
40650
  }
40597
- if (!fs42.existsSync(targetDir)) {
40651
+ if (!fs43.existsSync(targetDir)) {
40598
40652
  return { success: false, error: "not installed" };
40599
40653
  }
40600
- fs42.rmSync(targetDir, { recursive: true, force: true });
40654
+ fs43.rmSync(targetDir, { recursive: true, force: true });
40601
40655
  if (this._ctx.providerLoader) {
40602
40656
  this._ctx.providerLoader.reload();
40603
40657
  this._ctx.providerLoader.registerToDetector();
@@ -40613,28 +40667,28 @@ ${formatManifestValidationIssues2(validation.issues)}`,
40613
40667
  * the UI and by the update checker.
40614
40668
  */
40615
40669
  handleListInstalledProviders(_args) {
40616
- const fs42 = __require("fs");
40670
+ const fs43 = __require("fs");
40617
40671
  const path45 = __require("path");
40618
40672
  const installRoot = this.getUpstreamInstallRoot();
40619
- if (!fs42.existsSync(installRoot)) return { success: true, providers: [] };
40673
+ if (!fs43.existsSync(installRoot)) return { success: true, providers: [] };
40620
40674
  const CATEGORIES = ["cli", "ide", "extension", "acp"];
40621
40675
  const items = [];
40622
40676
  for (const category of CATEGORIES) {
40623
40677
  const categoryDir = path45.join(installRoot, category);
40624
- if (!fs42.existsSync(categoryDir)) continue;
40678
+ if (!fs43.existsSync(categoryDir)) continue;
40625
40679
  let entries;
40626
40680
  try {
40627
- entries = fs42.readdirSync(categoryDir);
40681
+ entries = fs43.readdirSync(categoryDir);
40628
40682
  } catch {
40629
40683
  continue;
40630
40684
  }
40631
40685
  for (const type of entries) {
40632
40686
  const v1Path = path45.join(categoryDir, type, "provider.v1.json");
40633
40687
  const v0Path = path45.join(categoryDir, type, "provider.json");
40634
- const manifestPath = fs42.existsSync(v1Path) ? v1Path : fs42.existsSync(v0Path) ? v0Path : null;
40688
+ const manifestPath = fs43.existsSync(v1Path) ? v1Path : fs43.existsSync(v0Path) ? v0Path : null;
40635
40689
  if (!manifestPath) continue;
40636
40690
  try {
40637
- const m = JSON.parse(fs42.readFileSync(manifestPath, "utf-8"));
40691
+ const m = JSON.parse(fs43.readFileSync(manifestPath, "utf-8"));
40638
40692
  const modelOptions = Array.isArray(m.modelOptions) ? m.modelOptions.filter((x) => typeof x === "string" && !!x.trim()) : [];
40639
40693
  const thinkingLevelOptions = Array.isArray(m.thinkingLevelOptions) ? m.thinkingLevelOptions.filter((x) => typeof x === "string" && !!x.trim()) : [];
40640
40694
  items.push({
@@ -40665,7 +40719,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
40665
40719
  const https = __require("https");
40666
40720
  const REGISTRY = resolveRegistryBaseUrl(loadConfig().registryUrl);
40667
40721
  function fetchJson(url) {
40668
- return new Promise((resolve25, reject) => {
40722
+ return new Promise((resolve26, reject) => {
40669
40723
  const req = https.get(url, { headers: { "User-Agent": "adhdev-daemon", "Accept": "application/json" }, timeout: 1e4 }, (res) => {
40670
40724
  if (res.statusCode !== 200) {
40671
40725
  reject(new Error(`HTTP ${res.statusCode}`));
@@ -40675,7 +40729,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
40675
40729
  res.on("data", (c) => chunks.push(c));
40676
40730
  res.on("end", () => {
40677
40731
  try {
40678
- resolve25(JSON.parse(Buffer.concat(chunks).toString("utf-8")));
40732
+ resolve26(JSON.parse(Buffer.concat(chunks).toString("utf-8")));
40679
40733
  } catch (e) {
40680
40734
  reject(e);
40681
40735
  }
@@ -40749,7 +40803,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
40749
40803
  if (!/^@[a-z0-9_-]+$/i.test(requestedName)) {
40750
40804
  return { success: false, error: "name must match @[a-z0-9_-]+" };
40751
40805
  }
40752
- const fs42 = __require("fs");
40806
+ const fs43 = __require("fs");
40753
40807
  const path45 = __require("path");
40754
40808
  const { spawnSync: spawnSync2 } = __require("child_process");
40755
40809
  const file = ext.loadExternalSources();
@@ -40760,8 +40814,8 @@ ${formatManifestValidationIssues2(validation.issues)}`,
40760
40814
  return { success: false, error: `source url+ref already registered (use a different name to track another ref)` };
40761
40815
  }
40762
40816
  const sourceDir = path45.join(ext.externalRoot(), requestedName);
40763
- if (!fs42.existsSync(ext.externalRoot())) fs42.mkdirSync(ext.externalRoot(), { recursive: true });
40764
- if (fs42.existsSync(sourceDir)) {
40817
+ if (!fs43.existsSync(ext.externalRoot())) fs43.mkdirSync(ext.externalRoot(), { recursive: true });
40818
+ if (fs43.existsSync(sourceDir)) {
40765
40819
  return { success: false, error: `directory already exists: ${sourceDir} (rename or remove first)` };
40766
40820
  }
40767
40821
  const clone = spawnSync2("git", ["clone", "--depth=1", "--branch", ref, "--", url, sourceDir], {
@@ -40771,7 +40825,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
40771
40825
  });
40772
40826
  if (clone.status !== 0) {
40773
40827
  try {
40774
- fs42.rmSync(sourceDir, { recursive: true, force: true });
40828
+ fs43.rmSync(sourceDir, { recursive: true, force: true });
40775
40829
  } catch {
40776
40830
  }
40777
40831
  return { success: false, error: `git clone failed: ${(clone.stderr || clone.stdout || "").trim() || "unknown error"}` };
@@ -40815,15 +40869,15 @@ ${formatManifestValidationIssues2(validation.issues)}`,
40815
40869
  const name = typeof args?.name === "string" ? args.name.trim() : "";
40816
40870
  if (!name) return { success: false, error: "name is required" };
40817
40871
  const ext = (init_external_sources(), __toCommonJS(external_sources_exports));
40818
- const fs42 = __require("fs");
40872
+ const fs43 = __require("fs");
40819
40873
  const path45 = __require("path");
40820
40874
  const file = ext.loadExternalSources();
40821
40875
  const match = file.sources.find((s2) => s2.name === name);
40822
40876
  if (!match) return { success: false, error: `source "${name}" not registered` };
40823
40877
  const sourceDir = path45.join(ext.externalRoot(), name);
40824
- if (fs42.existsSync(sourceDir)) {
40878
+ if (fs43.existsSync(sourceDir)) {
40825
40879
  try {
40826
- fs42.rmSync(sourceDir, { recursive: true, force: true });
40880
+ fs43.rmSync(sourceDir, { recursive: true, force: true });
40827
40881
  } catch (e) {
40828
40882
  return { success: false, error: `failed to delete ${sourceDir}: ${e?.message || e}` };
40829
40883
  }
@@ -40913,7 +40967,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
40913
40967
  try {
40914
40968
  const http3 = await import("http");
40915
40969
  const postData = JSON.stringify(body);
40916
- const result = await new Promise((resolve25, reject) => {
40970
+ const result = await new Promise((resolve26, reject) => {
40917
40971
  const req = http3.request({
40918
40972
  hostname: "127.0.0.1",
40919
40973
  port: 19280,
@@ -40925,9 +40979,9 @@ ${formatManifestValidationIssues2(validation.issues)}`,
40925
40979
  res.on("data", (chunk) => data += chunk);
40926
40980
  res.on("end", () => {
40927
40981
  try {
40928
- resolve25(JSON.parse(data));
40982
+ resolve26(JSON.parse(data));
40929
40983
  } catch {
40930
- resolve25({ raw: data });
40984
+ resolve26({ raw: data });
40931
40985
  }
40932
40986
  });
40933
40987
  });
@@ -40945,15 +40999,15 @@ ${formatManifestValidationIssues2(validation.issues)}`,
40945
40999
  if (!providerType) return { success: false, error: "providerType required" };
40946
41000
  try {
40947
41001
  const http3 = await import("http");
40948
- const result = await new Promise((resolve25, reject) => {
41002
+ const result = await new Promise((resolve26, reject) => {
40949
41003
  http3.get(`http://127.0.0.1:19280/api/providers/${providerType}/${endpoint}`, (res) => {
40950
41004
  let data = "";
40951
41005
  res.on("data", (chunk) => data += chunk);
40952
41006
  res.on("end", () => {
40953
41007
  try {
40954
- resolve25(JSON.parse(data));
41008
+ resolve26(JSON.parse(data));
40955
41009
  } catch {
40956
- resolve25({ raw: data });
41010
+ resolve26({ raw: data });
40957
41011
  }
40958
41012
  });
40959
41013
  }).on("error", reject);
@@ -40967,7 +41021,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
40967
41021
  try {
40968
41022
  const http3 = await import("http");
40969
41023
  const postData = JSON.stringify(args || {});
40970
- const result = await new Promise((resolve25, reject) => {
41024
+ const result = await new Promise((resolve26, reject) => {
40971
41025
  const req = http3.request({
40972
41026
  hostname: "127.0.0.1",
40973
41027
  port: 19280,
@@ -40979,9 +41033,9 @@ ${formatManifestValidationIssues2(validation.issues)}`,
40979
41033
  res.on("data", (chunk) => data += chunk);
40980
41034
  res.on("end", () => {
40981
41035
  try {
40982
- resolve25(JSON.parse(data));
41036
+ resolve26(JSON.parse(data));
40983
41037
  } catch {
40984
- resolve25({ raw: data });
41038
+ resolve26({ raw: data });
40985
41039
  }
40986
41040
  });
40987
41041
  });
@@ -41497,7 +41551,7 @@ var refineConfigHandlers = {
41497
41551
  // src/commands/low-family/diagnostics.ts
41498
41552
  init_logger();
41499
41553
  init_debug_trace();
41500
- import * as fs12 from "fs";
41554
+ import * as fs13 from "fs";
41501
41555
  var diagnosticsHandlers = {
41502
41556
  get_logs: async (_ctx, args) => {
41503
41557
  const count = parseInt(args?.count) || parseInt(args?.lines) || 100;
@@ -41514,8 +41568,8 @@ var diagnosticsHandlers = {
41514
41568
  if (sinceTs > 0) {
41515
41569
  return { success: true, logs: [], totalBuffered: 0 };
41516
41570
  }
41517
- if (fs12.existsSync(LOG_PATH)) {
41518
- const content = fs12.readFileSync(LOG_PATH, "utf-8");
41571
+ if (fs13.existsSync(LOG_PATH)) {
41572
+ const content = fs13.readFileSync(LOG_PATH, "utf-8");
41519
41573
  const allLines = content.split("\n");
41520
41574
  const recent = allLines.slice(-count).join("\n");
41521
41575
  return { success: true, logs: recent, totalLines: allLines.length };
@@ -41662,14 +41716,14 @@ var coordinatorPromptHandlers = {
41662
41716
  }
41663
41717
  },
41664
41718
  list_coordinator_prompts: async (_ctx, _args) => {
41665
- const fs42 = await import("fs");
41719
+ const fs43 = await import("fs");
41666
41720
  const path45 = await import("path");
41667
41721
  const os32 = await import("os");
41668
41722
  const dir = path45.join(os32.homedir(), ".adhdev", "coordinator-prompts");
41669
41723
  const entries = {};
41670
41724
  try {
41671
- if (fs42.existsSync(dir)) {
41672
- for (const name of fs42.readdirSync(dir)) {
41725
+ if (fs43.existsSync(dir)) {
41726
+ for (const name of fs43.readdirSync(dir)) {
41673
41727
  const matchOverride = name.match(/^([a-zA-Z0-9_.-]+)\.md$/);
41674
41728
  const matchAppend = name.match(/^([a-zA-Z0-9_.-]+)\.append\.md$/);
41675
41729
  const m = matchAppend || matchOverride;
@@ -41679,7 +41733,7 @@ var coordinatorPromptHandlers = {
41679
41733
  const full = path45.join(dir, name);
41680
41734
  let content = "";
41681
41735
  try {
41682
- content = fs42.readFileSync(full, "utf8");
41736
+ content = fs43.readFileSync(full, "utf8");
41683
41737
  } catch {
41684
41738
  }
41685
41739
  if (!entries[key2]) entries[key2] = { override: "", append: "" };
@@ -41693,7 +41747,7 @@ var coordinatorPromptHandlers = {
41693
41747
  return { success: true, dir, entries };
41694
41748
  },
41695
41749
  write_coordinator_prompt: async (_ctx, args) => {
41696
- const fs42 = await import("fs");
41750
+ const fs43 = await import("fs");
41697
41751
  const path45 = await import("path");
41698
41752
  const os32 = await import("os");
41699
41753
  const key2 = typeof args?.key === "string" ? args.key.trim() : "";
@@ -41706,11 +41760,11 @@ var coordinatorPromptHandlers = {
41706
41760
  const filename = kind === "append" ? `${key2}.append.md` : `${key2}.md`;
41707
41761
  const full = path45.join(dir, filename);
41708
41762
  try {
41709
- fs42.mkdirSync(dir, { recursive: true });
41763
+ fs43.mkdirSync(dir, { recursive: true });
41710
41764
  if (content.trim()) {
41711
- fs42.writeFileSync(full, content, { encoding: "utf8", mode: 384 });
41712
- } else if (fs42.existsSync(full)) {
41713
- fs42.unlinkSync(full);
41765
+ fs43.writeFileSync(full, content, { encoding: "utf8", mode: 384 });
41766
+ } else if (fs43.existsSync(full)) {
41767
+ fs43.unlinkSync(full);
41714
41768
  }
41715
41769
  return { success: true, path: full, kind, key: key2 };
41716
41770
  } catch (error) {
@@ -41826,21 +41880,21 @@ init_config();
41826
41880
  // src/commands/upgrade-helper.ts
41827
41881
  import { execFileSync as execFileSync3 } from "child_process";
41828
41882
  import { spawn } from "child_process";
41829
- import * as fs13 from "fs";
41883
+ import * as fs14 from "fs";
41830
41884
  import * as os13 from "os";
41831
41885
  import * as path20 from "path";
41832
41886
  var UPGRADE_HELPER_ENV = "ADHDEV_DAEMON_UPGRADE_HELPER";
41833
41887
  function getUpgradeLogPath() {
41834
41888
  const home = os13.homedir();
41835
41889
  const dir = path20.join(home, ".adhdev");
41836
- fs13.mkdirSync(dir, { recursive: true });
41890
+ fs14.mkdirSync(dir, { recursive: true });
41837
41891
  return path20.join(dir, "daemon-upgrade.log");
41838
41892
  }
41839
41893
  function appendUpgradeLog(message) {
41840
41894
  const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${message}
41841
41895
  `;
41842
41896
  try {
41843
- fs13.appendFileSync(getUpgradeLogPath(), line, "utf8");
41897
+ fs14.appendFileSync(getUpgradeLogPath(), line, "utf8");
41844
41898
  } catch {
41845
41899
  }
41846
41900
  }
@@ -41848,12 +41902,12 @@ function resolveSiblingNpmInvocation(nodeExecutable, platform10 = process.platfo
41848
41902
  const binDir = path20.dirname(nodeExecutable);
41849
41903
  if (platform10 === "win32") {
41850
41904
  const npmCliPath = path20.join(binDir, "node_modules", "npm", "bin", "npm-cli.js");
41851
- if (fs13.existsSync(npmCliPath)) {
41905
+ if (fs14.existsSync(npmCliPath)) {
41852
41906
  return { executable: nodeExecutable, argsPrefix: [npmCliPath], execOptions: getNpmExecOptions(platform10) };
41853
41907
  }
41854
41908
  for (const candidate of ["npm.exe", "npm"]) {
41855
41909
  const candidatePath = path20.join(binDir, candidate);
41856
- if (fs13.existsSync(candidatePath)) {
41910
+ if (fs14.existsSync(candidatePath)) {
41857
41911
  return { executable: candidatePath, argsPrefix: [], execOptions: getNpmExecOptions(platform10) };
41858
41912
  }
41859
41913
  }
@@ -41861,7 +41915,7 @@ function resolveSiblingNpmInvocation(nodeExecutable, platform10 = process.platfo
41861
41915
  }
41862
41916
  for (const candidate of ["npm"]) {
41863
41917
  const candidatePath = path20.join(binDir, candidate);
41864
- if (fs13.existsSync(candidatePath)) {
41918
+ if (fs14.existsSync(candidatePath)) {
41865
41919
  return { executable: candidatePath, argsPrefix: [], execOptions: getNpmExecOptions(platform10) };
41866
41920
  }
41867
41921
  }
@@ -41871,12 +41925,12 @@ function findCurrentPackageRoot(currentCliPath, packageName) {
41871
41925
  if (!currentCliPath) return null;
41872
41926
  let resolvedPath = currentCliPath;
41873
41927
  try {
41874
- resolvedPath = fs13.realpathSync.native(currentCliPath);
41928
+ resolvedPath = fs14.realpathSync.native(currentCliPath);
41875
41929
  } catch {
41876
41930
  }
41877
41931
  let currentDir = resolvedPath;
41878
41932
  try {
41879
- if (fs13.statSync(resolvedPath).isFile()) {
41933
+ if (fs14.statSync(resolvedPath).isFile()) {
41880
41934
  currentDir = path20.dirname(resolvedPath);
41881
41935
  }
41882
41936
  } catch {
@@ -41885,8 +41939,8 @@ function findCurrentPackageRoot(currentCliPath, packageName) {
41885
41939
  while (true) {
41886
41940
  const packageJsonPath = path20.join(currentDir, "package.json");
41887
41941
  try {
41888
- if (fs13.existsSync(packageJsonPath)) {
41889
- const parsed = JSON.parse(fs13.readFileSync(packageJsonPath, "utf8"));
41942
+ if (fs14.existsSync(packageJsonPath)) {
41943
+ const parsed = JSON.parse(fs14.readFileSync(packageJsonPath, "utf8"));
41890
41944
  if (parsed?.name === packageName) {
41891
41945
  const normalized = currentDir.replace(/\\/g, "/");
41892
41946
  return normalized.includes("/node_modules/") ? currentDir : null;
@@ -42027,7 +42081,7 @@ async function waitForPidExit(pid, timeoutMs) {
42027
42081
  while (Date.now() - start < timeoutMs) {
42028
42082
  try {
42029
42083
  process.kill(pid, 0);
42030
- await new Promise((resolve25) => setTimeout(resolve25, 250));
42084
+ await new Promise((resolve26) => setTimeout(resolve26, 250));
42031
42085
  } catch {
42032
42086
  return;
42033
42087
  }
@@ -42037,8 +42091,8 @@ async function stopSessionHostProcesses(appName) {
42037
42091
  const pidFile = path20.join(os13.homedir(), ".adhdev", `${appName}-session-host.pid`);
42038
42092
  let killedPid = null;
42039
42093
  try {
42040
- if (fs13.existsSync(pidFile)) {
42041
- const pid = Number.parseInt(fs13.readFileSync(pidFile, "utf8").trim(), 10);
42094
+ if (fs14.existsSync(pidFile)) {
42095
+ const pid = Number.parseInt(fs14.readFileSync(pidFile, "utf8").trim(), 10);
42042
42096
  if (Number.isFinite(pid) && pid !== process.pid && isManagedSessionHostPid(pid)) {
42043
42097
  if (killPid(pid)) killedPid = pid;
42044
42098
  }
@@ -42046,7 +42100,7 @@ async function stopSessionHostProcesses(appName) {
42046
42100
  } catch {
42047
42101
  } finally {
42048
42102
  try {
42049
- fs13.unlinkSync(pidFile);
42103
+ fs14.unlinkSync(pidFile);
42050
42104
  } catch {
42051
42105
  }
42052
42106
  }
@@ -42123,7 +42177,7 @@ function getUpgradeFailureNoticePath() {
42123
42177
  const home = os13.homedir();
42124
42178
  const dir = path20.join(home, ".adhdev");
42125
42179
  try {
42126
- fs13.mkdirSync(dir, { recursive: true });
42180
+ fs14.mkdirSync(dir, { recursive: true });
42127
42181
  } catch {
42128
42182
  }
42129
42183
  return path20.join(dir, "daemon-upgrade-last-error.txt");
@@ -42136,7 +42190,7 @@ function emitUpgradeFailureNotice(lines) {
42136
42190
  appendUpgradeLog(`Upgrade blocked \u2014 user action required:
42137
42191
  ${body}`);
42138
42192
  try {
42139
- fs13.writeFileSync(getUpgradeFailureNoticePath(), `[${(/* @__PURE__ */ new Date()).toISOString()}]
42193
+ fs14.writeFileSync(getUpgradeFailureNoticePath(), `[${(/* @__PURE__ */ new Date()).toISOString()}]
42140
42194
  ${body}
42141
42195
  `, "utf8");
42142
42196
  } catch {
@@ -42151,13 +42205,13 @@ function isRetriableInstallLockError(error) {
42151
42205
  function removeDaemonPidFile() {
42152
42206
  const pidFile = path20.join(os13.homedir(), ".adhdev", "daemon.pid");
42153
42207
  try {
42154
- fs13.unlinkSync(pidFile);
42208
+ fs14.unlinkSync(pidFile);
42155
42209
  } catch {
42156
42210
  }
42157
42211
  }
42158
42212
  function safeRemoveStaleEntry(target, label) {
42159
42213
  try {
42160
- fs13.rmSync(target, { recursive: true, force: true });
42214
+ fs14.rmSync(target, { recursive: true, force: true });
42161
42215
  appendUpgradeLog(`${label}: ${target}`);
42162
42216
  } catch (error) {
42163
42217
  appendUpgradeLog(`Skipped locked stale entry (${error?.code || "error"}): ${target} \u2014 ${error?.message || String(error)}`);
@@ -42178,19 +42232,19 @@ function cleanupStaleGlobalInstallDirs(pkgName, surface) {
42178
42232
  if (pkgName.startsWith("@")) {
42179
42233
  const [scope, name] = pkgName.split("/");
42180
42234
  const scopeDir = path20.join(npmRoot, scope);
42181
- if (!fs13.existsSync(scopeDir)) return;
42182
- for (const entry of fs13.readdirSync(scopeDir)) {
42235
+ if (!fs14.existsSync(scopeDir)) return;
42236
+ for (const entry of fs14.readdirSync(scopeDir)) {
42183
42237
  if (!entry.startsWith(`.${name}-`)) continue;
42184
42238
  safeRemoveStaleEntry(path20.join(scopeDir, entry), "Removed stale scoped staging dir");
42185
42239
  }
42186
42240
  } else {
42187
- for (const entry of fs13.readdirSync(npmRoot)) {
42241
+ for (const entry of fs14.readdirSync(npmRoot)) {
42188
42242
  if (!entry.startsWith(`.${pkgName}-`)) continue;
42189
42243
  safeRemoveStaleEntry(path20.join(npmRoot, entry), "Removed stale staging dir");
42190
42244
  }
42191
42245
  }
42192
- if (fs13.existsSync(binDir)) {
42193
- for (const entry of fs13.readdirSync(binDir)) {
42246
+ if (fs14.existsSync(binDir)) {
42247
+ for (const entry of fs14.readdirSync(binDir)) {
42194
42248
  if (!Array.from(binNames).some((name) => entry.startsWith(`.${name}-`))) continue;
42195
42249
  safeRemoveStaleEntry(path20.join(binDir, entry), "Removed stale bin staging entry");
42196
42250
  }
@@ -42253,7 +42307,7 @@ async function runDaemonUpgradeHelper(payload) {
42253
42307
  appendUpgradeLog(`Install attempt ${attempt} hit a file lock (${error?.code || "lock"}); clearing holders + staging and retrying after backoff`);
42254
42308
  await stopForeignNativeAddonHolders(installCommand.surface.packageRoot, { parentPid: payload.parentPid });
42255
42309
  cleanupStaleGlobalInstallDirs(payload.packageName, installCommand.surface);
42256
- await new Promise((resolve25) => setTimeout(resolve25, attempt * 1500));
42310
+ await new Promise((resolve26) => setTimeout(resolve26, attempt * 1500));
42257
42311
  continue;
42258
42312
  }
42259
42313
  if (isRetriableInstallLockError(error)) {
@@ -42281,7 +42335,7 @@ async function runDaemonUpgradeHelper(payload) {
42281
42335
  appendUpgradeLog(installOutput.trim());
42282
42336
  }
42283
42337
  if (process.platform === "win32") {
42284
- await new Promise((resolve25) => setTimeout(resolve25, 500));
42338
+ await new Promise((resolve26) => setTimeout(resolve26, 500));
42285
42339
  cleanupStaleGlobalInstallDirs(payload.packageName, installCommand.surface);
42286
42340
  appendUpgradeLog("Post-install staging cleanup complete");
42287
42341
  }
@@ -42447,7 +42501,7 @@ init_dist();
42447
42501
 
42448
42502
  // src/logging/log-tail-reader.ts
42449
42503
  init_logger();
42450
- import * as fs14 from "fs";
42504
+ import * as fs15 from "fs";
42451
42505
  var DEFAULT_TAIL_BYTES = 64 * 1024;
42452
42506
  var MAX_TAIL_BYTES = 128 * 1024;
42453
42507
  var READ_CHUNK_BYTES = 64 * 1024;
@@ -42464,9 +42518,9 @@ function clampTailBytes(tailBytes) {
42464
42518
  return Math.min(Math.floor(tailBytes), MAX_TAIL_BYTES);
42465
42519
  }
42466
42520
  function readByteBoundedTail(filePath, limitBytes) {
42467
- const fd = fs14.openSync(filePath, "r");
42521
+ const fd = fs15.openSync(filePath, "r");
42468
42522
  try {
42469
- const stat2 = fs14.fstatSync(fd);
42523
+ const stat2 = fs15.fstatSync(fd);
42470
42524
  const size = stat2.size;
42471
42525
  if (size === 0) return { text: "", truncated: false, bytesReturned: 0 };
42472
42526
  const want = Math.min(limitBytes, size);
@@ -42477,7 +42531,7 @@ function readByteBoundedTail(filePath, limitBytes) {
42477
42531
  while (position < size) {
42478
42532
  const chunkSize = Math.min(READ_CHUNK_BYTES, size - position);
42479
42533
  const chunk = Buffer.alloc(chunkSize);
42480
- fs14.readSync(fd, chunk, 0, chunkSize, position);
42534
+ fs15.readSync(fd, chunk, 0, chunkSize, position);
42481
42535
  buffers.push(chunk);
42482
42536
  position += chunkSize;
42483
42537
  }
@@ -42490,7 +42544,7 @@ function readByteBoundedTail(filePath, limitBytes) {
42490
42544
  }
42491
42545
  return { text: buf.toString("utf-8"), truncated, bytesReturned: buf.length };
42492
42546
  } finally {
42493
- fs14.closeSync(fd);
42547
+ fs15.closeSync(fd);
42494
42548
  }
42495
42549
  }
42496
42550
  function splitLogLines(text) {
@@ -42568,8 +42622,8 @@ function readDaemonLogTail(args = {}) {
42568
42622
  const limitBytes = clampTailBytes(args.tailBytes);
42569
42623
  const primaryPath = resolveLogPath(args.date);
42570
42624
  const backupPath = primaryPath.replace(/\.log$/, ".1.log");
42571
- const primaryExists = fs14.existsSync(primaryPath);
42572
- const backupExists = fs14.existsSync(backupPath);
42625
+ const primaryExists = fs15.existsSync(primaryPath);
42626
+ const backupExists = fs15.existsSync(backupPath);
42573
42627
  if (!primaryExists && !backupExists) {
42574
42628
  return errorResult(
42575
42629
  `No daemon log file at ${primaryPath} (dir: ${getDaemonLogDir()})`,
@@ -42608,7 +42662,7 @@ function readDaemonLogTail(args = {}) {
42608
42662
  try {
42609
42663
  for (const p of [backupExists ? backupPath : null, primaryExists ? primaryPath : null]) {
42610
42664
  if (!p) continue;
42611
- const buf = fs14.readFileSync(p);
42665
+ const buf = fs15.readFileSync(p);
42612
42666
  scannedBytes += buf.length;
42613
42667
  allLines = allLines.concat(splitLogLines(buf.toString("utf-8")));
42614
42668
  }
@@ -42814,16 +42868,16 @@ init_contracts2();
42814
42868
  init_provider_input_support();
42815
42869
  import * as os21 from "os";
42816
42870
  import * as crypto5 from "crypto";
42817
- import * as fs22 from "fs";
42871
+ import * as fs23 from "fs";
42818
42872
  init_hash();
42819
42873
 
42820
42874
  // src/providers/spec/route.ts
42821
42875
  init_provider_cli_adapter();
42822
- import * as fs20 from "fs";
42876
+ import * as fs21 from "fs";
42823
42877
  import * as path25 from "path";
42824
42878
 
42825
42879
  // src/providers/spec/fsm-driver.ts
42826
- import * as fs16 from "fs";
42880
+ import * as fs17 from "fs";
42827
42881
  import * as os18 from "os";
42828
42882
  import * as path23 from "path";
42829
42883
 
@@ -43003,7 +43057,7 @@ import { DEFAULT_SESSION_HOST_COLS as DEFAULT_SESSION_HOST_COLS6, DEFAULT_SESSIO
43003
43057
 
43004
43058
  // src/providers/spec/pre-launch-trust.ts
43005
43059
  init_logger();
43006
- import * as fs15 from "fs";
43060
+ import * as fs16 from "fs";
43007
43061
  import * as os17 from "os";
43008
43062
  import * as path22 from "path";
43009
43063
  function expandHome2(p) {
@@ -43013,7 +43067,7 @@ function expandHome2(p) {
43013
43067
  }
43014
43068
  function realWorkspacePath(workingDir) {
43015
43069
  try {
43016
- return fs15.realpathSync(workingDir);
43070
+ return fs16.realpathSync(workingDir);
43017
43071
  } catch {
43018
43072
  return path22.resolve(workingDir);
43019
43073
  }
@@ -43024,8 +43078,8 @@ function applyPreLaunchTrust(trust, workingDir) {
43024
43078
  const real = realWorkspacePath(workingDir);
43025
43079
  try {
43026
43080
  let parsed = {};
43027
- if (fs15.existsSync(settingsPath)) {
43028
- const text = fs15.readFileSync(settingsPath, "utf8");
43081
+ if (fs16.existsSync(settingsPath)) {
43082
+ const text = fs16.readFileSync(settingsPath, "utf8");
43029
43083
  if (text.trim().length > 0) {
43030
43084
  const json = JSON.parse(text);
43031
43085
  if (json && typeof json === "object" && !Array.isArray(json)) {
@@ -43041,8 +43095,8 @@ function applyPreLaunchTrust(trust, workingDir) {
43041
43095
  }
43042
43096
  list.push(real);
43043
43097
  parsed[key2] = list;
43044
- fs15.mkdirSync(path22.dirname(settingsPath), { recursive: true });
43045
- fs15.writeFileSync(settingsPath, `${JSON.stringify(parsed, null, 2)}
43098
+ fs16.mkdirSync(path22.dirname(settingsPath), { recursive: true });
43099
+ fs16.writeFileSync(settingsPath, `${JSON.stringify(parsed, null, 2)}
43046
43100
  `, "utf8");
43047
43101
  LOG.info("pre-launch-trust", `pre-trusted workspace in ${trust.settings_path} (key="${key2}")`);
43048
43102
  return real;
@@ -43405,7 +43459,7 @@ var FsmDriver = class {
43405
43459
  try {
43406
43460
  const dir = path23.dirname(this.opts.specPath);
43407
43461
  const base = path23.basename(this.opts.specPath);
43408
- this.specWatcher = fs16.watch(dir, { persistent: false }, (_event, filename) => {
43462
+ this.specWatcher = fs17.watch(dir, { persistent: false }, (_event, filename) => {
43409
43463
  if (filename && filename !== base) return;
43410
43464
  const res = loadFsmSpec(this.opts.specPath);
43411
43465
  if (!res.ok) {
@@ -44041,7 +44095,7 @@ var FsmDriver = class {
44041
44095
  const ext = guessExt(mime);
44042
44096
  const tmp = path23.join(os18.tmpdir(), `adhdev-attach-${Date.now()}${ext}`);
44043
44097
  try {
44044
- fs16.writeFileSync(tmp, Buffer.from(blob, "base64"));
44098
+ fs17.writeFileSync(tmp, Buffer.from(blob, "base64"));
44045
44099
  } catch {
44046
44100
  return;
44047
44101
  }
@@ -44175,7 +44229,7 @@ init_evaluator();
44175
44229
  // src/providers/spec/native-history-executor.ts
44176
44230
  init_logger();
44177
44231
  init_load_better_sqlite3();
44178
- import * as fs17 from "fs";
44232
+ import * as fs18 from "fs";
44179
44233
  import * as os19 from "os";
44180
44234
  import * as path24 from "path";
44181
44235
 
@@ -44198,7 +44252,7 @@ function executeJsonl(src, input) {
44198
44252
  const wsRaw = typeof input.workspace === "string" ? input.workspace : "";
44199
44253
  let wsReal = wsRaw;
44200
44254
  try {
44201
- if (wsRaw) wsReal = fs17.realpathSync(wsRaw);
44255
+ if (wsRaw) wsReal = fs18.realpathSync(wsRaw);
44202
44256
  } catch {
44203
44257
  }
44204
44258
  LOG.debug("NativeHistory", `jsonl unresolved: tried=${JSON.stringify(resolved)} sessionId=${requestedSessionId || "(none)"} wsRaw=${JSON.stringify(wsRaw)} wsReal=${JSON.stringify(wsReal)} rawSlug=${JSON.stringify(claudeProjectDirName(wsRaw))} realSlug=${JSON.stringify(claudeProjectDirName(wsReal))} (concrete miss + raw-slug retry + projects scan all failed)`);
@@ -44207,23 +44261,26 @@ function executeJsonl(src, input) {
44207
44261
  const mtime = safeMtimeMs(sourcePath);
44208
44262
  const lines = readJsonlLines(sourcePath);
44209
44263
  if (lines.length === 0) return null;
44210
- const transcriptWorkspace = readSessionMetaWorkspace(lines) ?? (src.workspace_from_input ? workspaceFromInputIfSlugMatches(sourcePath, input) : void 0);
44264
+ const transcriptWorkspace = readSessionMetaWorkspace(lines) ?? (src.workspace_from_sidecar ? readSidecarWorkspace(sourcePath, src.workspace_from_sidecar) : void 0) ?? (src.workspace_from_input ? workspaceFromInputIfSlugMatches(sourcePath, input) : void 0);
44211
44265
  let providerSessionId;
44212
44266
  if (src.session_id_from === "first_record" && src.session_id_path) {
44213
44267
  const v = jsonPathGet(lines[0], src.session_id_path);
44214
44268
  if (typeof v === "string" && v) providerSessionId = v;
44269
+ } else if (src.session_id_from === "dir_uuid") {
44270
+ providerSessionId = dirUuid(sourcePath) || void 0;
44215
44271
  } else if (src.session_id_from === "filename_uuid" || !src.session_id_from) {
44216
44272
  const m = path24.basename(sourcePath).match(UUID_RE);
44217
44273
  if (m) providerSessionId = m[1];
44218
44274
  }
44219
44275
  const requested = readRequestedSessionId(input) || "";
44220
- if (requested && providerSessionId && providerSessionId !== requested) return null;
44221
- const filter = src.message_filter ? compileWhere(src.message_filter.where) : null;
44276
+ if (requested && providerSessionId && !sameSessionUuid(providerSessionId, requested)) return null;
44277
+ const shapes = compileRecordShapes(src);
44222
44278
  const messages = [];
44223
44279
  for (let i = 0; i < lines.length; i += 1) {
44224
44280
  const rec = lines[i];
44225
- if (filter && !filter(rec)) continue;
44226
- for (const msg of projectMessages(rec, src.message_map, i, lines.length, mtime)) {
44281
+ const shape = shapes.pick(rec);
44282
+ if (!shape) continue;
44283
+ for (const msg of projectMessages(rec, shape.map, i, lines.length, mtime)) {
44227
44284
  if (transcriptWorkspace) msg.workspace = transcriptWorkspace;
44228
44285
  messages.push(msg);
44229
44286
  }
@@ -44248,11 +44305,22 @@ function resolveJsonlSourcePath(src, input) {
44248
44305
  const workspaceHint = typeof input.workspace === "string" && input.workspace.trim() ? input.workspace.trim() : "";
44249
44306
  let sourcePath = null;
44250
44307
  if (resolved.includes("*")) {
44251
- sourcePath = pickExactSessionFileAcrossGlob(resolved, filePat, requestedSessionId) || pickSessionBoundFileAcrossGlob(resolved, filePat, windowMs, sessionFloor, workspaceHint) || newestRecentFileAcrossGlob(resolved, filePat, windowMs, sessionFloor);
44308
+ if (src.session_id_from === "dir_uuid" || src.workspace_from_sidecar) {
44309
+ sourcePath = pickDirUuidFileAcrossGlob(resolved, filePat, requestedSessionId);
44310
+ if (!sourcePath && !requestedSessionId) {
44311
+ if (src.workspace_from_sidecar && workspaceHint) {
44312
+ sourcePath = pickSidecarWorkspaceFileAcrossGlob(resolved, filePat, windowMs, sessionFloor, workspaceHint, src.workspace_from_sidecar);
44313
+ } else {
44314
+ sourcePath = newestRecentFileAcrossGlob(resolved, filePat, windowMs, sessionFloor);
44315
+ }
44316
+ }
44317
+ } else {
44318
+ sourcePath = pickExactSessionFileAcrossGlob(resolved, filePat, requestedSessionId) || pickSessionBoundFileAcrossGlob(resolved, filePat, windowMs, sessionFloor, workspaceHint) || newestRecentFileAcrossGlob(resolved, filePat, windowMs, sessionFloor);
44319
+ }
44252
44320
  } else {
44253
44321
  let stat2 = null;
44254
44322
  try {
44255
- stat2 = fs17.statSync(resolved);
44323
+ stat2 = fs18.statSync(resolved);
44256
44324
  } catch {
44257
44325
  }
44258
44326
  if (stat2 && stat2.isFile()) {
@@ -44267,7 +44335,7 @@ function resolveJsonlSourcePath(src, input) {
44267
44335
  const resolvedRaw = expandPath2(src.path, input, { skipWorkspaceRealpath: true });
44268
44336
  if (resolvedRaw && resolvedRaw !== resolved) {
44269
44337
  try {
44270
- const rawStat = fs17.statSync(resolvedRaw);
44338
+ const rawStat = fs18.statSync(resolvedRaw);
44271
44339
  if (rawStat.isFile()) sourcePath = resolvedRaw;
44272
44340
  else if (rawStat.isDirectory()) {
44273
44341
  sourcePath = pickExactSessionFile(resolvedRaw, filePat, requestedSessionId) || (requestedSessionId ? null : newestRecentFile(resolvedRaw, filePat, windowMs, sessionFloor));
@@ -44290,12 +44358,61 @@ function readSessionMetaWorkspace(lines) {
44290
44358
  }
44291
44359
  return void 0;
44292
44360
  }
44361
+ function readSidecarWorkspace(sourcePath, cfg) {
44362
+ try {
44363
+ const sidecar = path24.resolve(path24.dirname(sourcePath), cfg.rel_path);
44364
+ const parsed = JSON.parse(fs18.readFileSync(sidecar, "utf8"));
44365
+ const v = jsonPathGet(parsed, cfg.workspace_path);
44366
+ return typeof v === "string" && v.trim() ? v.trim() : void 0;
44367
+ } catch {
44368
+ return void 0;
44369
+ }
44370
+ }
44371
+ function dirUuid(filePath) {
44372
+ const segs = path24.dirname(filePath).split(path24.sep);
44373
+ for (let i = segs.length - 1; i >= 0; i -= 1) {
44374
+ const m = segs[i].match(UUID_RE);
44375
+ if (m) return m[1];
44376
+ }
44377
+ return "";
44378
+ }
44379
+ function sameSessionUuid(a, b) {
44380
+ if (a === b) return true;
44381
+ const ua = a.match(UUID_RE)?.[1]?.toLowerCase();
44382
+ const ub = b.match(UUID_RE)?.[1]?.toLowerCase();
44383
+ return !!ua && !!ub && ua === ub;
44384
+ }
44385
+ function compileRecordShapes(src) {
44386
+ if (Array.isArray(src.records) && src.records.length > 0) {
44387
+ const compiled = src.records.map((r) => ({
44388
+ where: r.where ? compileWhere(r.where) : null,
44389
+ map: r.message_map
44390
+ }));
44391
+ return {
44392
+ pick: (record) => {
44393
+ for (const shape of compiled) {
44394
+ if (!shape.where || shape.where(record)) return { map: shape.map };
44395
+ }
44396
+ return null;
44397
+ }
44398
+ };
44399
+ }
44400
+ const filter = src.message_filter ? compileWhere(src.message_filter.where) : null;
44401
+ const map = src.message_map;
44402
+ return {
44403
+ pick: (record) => {
44404
+ if (!map) return null;
44405
+ if (filter && !filter(record)) return null;
44406
+ return { map };
44407
+ }
44408
+ };
44409
+ }
44293
44410
  function workspaceFromInputIfSlugMatches(sourcePath, input) {
44294
44411
  const wsRaw = typeof input.workspace === "string" ? input.workspace.trim() : "";
44295
44412
  if (!wsRaw) return void 0;
44296
44413
  let wsReal = wsRaw;
44297
44414
  try {
44298
- wsReal = fs17.realpathSync(wsRaw);
44415
+ wsReal = fs18.realpathSync(wsRaw);
44299
44416
  } catch {
44300
44417
  }
44301
44418
  const slugs = /* @__PURE__ */ new Set();
@@ -44319,7 +44436,7 @@ function workspaceFromInputIfSlugMatches(sourcePath, input) {
44319
44436
  function readJsonlLines(p) {
44320
44437
  let text;
44321
44438
  try {
44322
- text = fs17.readFileSync(p, "utf8");
44439
+ text = fs18.readFileSync(p, "utf8");
44323
44440
  } catch {
44324
44441
  return [];
44325
44442
  }
@@ -44336,7 +44453,7 @@ function readJsonlLines(p) {
44336
44453
  }
44337
44454
  function executeSqlite(src, input) {
44338
44455
  const resolved = expandPath2(src.path, input);
44339
- if (!resolved || !fs17.existsSync(resolved)) return null;
44456
+ if (!resolved || !fs18.existsSync(resolved)) return null;
44340
44457
  let Database;
44341
44458
  try {
44342
44459
  Database = loadBetterSqlite3();
@@ -44475,7 +44592,7 @@ function expandPath2(template, input, opts) {
44475
44592
  let workspaceResolved = workspaceRaw;
44476
44593
  if (workspaceRaw && !opts?.skipWorkspaceRealpath) {
44477
44594
  try {
44478
- workspaceResolved = fs17.realpathSync(workspaceRaw);
44595
+ workspaceResolved = fs18.realpathSync(workspaceRaw);
44479
44596
  } catch {
44480
44597
  }
44481
44598
  }
@@ -44514,7 +44631,7 @@ function scanProjectsRootForSessionFile(template, input, requestedSessionId) {
44514
44631
  if (!base) return null;
44515
44632
  let baseStat = null;
44516
44633
  try {
44517
- baseStat = fs17.statSync(base);
44634
+ baseStat = fs18.statSync(base);
44518
44635
  } catch {
44519
44636
  return null;
44520
44637
  }
@@ -44522,7 +44639,7 @@ function scanProjectsRootForSessionFile(template, input, requestedSessionId) {
44522
44639
  const needle = `${requestedSessionId.toLowerCase()}.jsonl`;
44523
44640
  const dirsToScan = [base];
44524
44641
  try {
44525
- for (const entry of fs17.readdirSync(base, { withFileTypes: true })) {
44642
+ for (const entry of fs18.readdirSync(base, { withFileTypes: true })) {
44526
44643
  if (entry.isDirectory()) dirsToScan.push(path24.join(base, entry.name));
44527
44644
  }
44528
44645
  } catch {
@@ -44530,7 +44647,7 @@ function scanProjectsRootForSessionFile(template, input, requestedSessionId) {
44530
44647
  for (const dir of dirsToScan) {
44531
44648
  let entries;
44532
44649
  try {
44533
- entries = fs17.readdirSync(dir, { withFileTypes: true });
44650
+ entries = fs18.readdirSync(dir, { withFileTypes: true });
44534
44651
  } catch {
44535
44652
  continue;
44536
44653
  }
@@ -44565,7 +44682,7 @@ function expandDirGlob(template) {
44565
44682
  for (const d of dirs) {
44566
44683
  let entries;
44567
44684
  try {
44568
- entries = fs17.readdirSync(d, { withFileTypes: true });
44685
+ entries = fs18.readdirSync(d, { withFileTypes: true });
44569
44686
  } catch {
44570
44687
  continue;
44571
44688
  }
@@ -44578,7 +44695,7 @@ function expandDirGlob(template) {
44578
44695
  const candidate = path24.join(d, seg);
44579
44696
  let stat2 = null;
44580
44697
  try {
44581
- stat2 = fs17.statSync(candidate);
44698
+ stat2 = fs18.statSync(candidate);
44582
44699
  } catch {
44583
44700
  continue;
44584
44701
  }
@@ -44592,7 +44709,7 @@ function expandDirGlob(template) {
44592
44709
  function walkAllDirs(root, out) {
44593
44710
  let entries;
44594
44711
  try {
44595
- entries = fs17.readdirSync(root, { withFileTypes: true });
44712
+ entries = fs18.readdirSync(root, { withFileTypes: true });
44596
44713
  } catch {
44597
44714
  return;
44598
44715
  }
@@ -44608,7 +44725,7 @@ function newestRecentFileAcrossGlob(template, pattern, windowMs, sessionFloorMs
44608
44725
  for (const d of dirs) {
44609
44726
  let entries;
44610
44727
  try {
44611
- entries = fs17.readdirSync(d, { withFileTypes: true });
44728
+ entries = fs18.readdirSync(d, { withFileTypes: true });
44612
44729
  } catch {
44613
44730
  continue;
44614
44731
  }
@@ -44635,7 +44752,7 @@ function newestRecentFileAcrossDateWindow(template, input, pattern, windowMs, se
44635
44752
  if (!resolved) continue;
44636
44753
  let entries;
44637
44754
  try {
44638
- entries = fs17.readdirSync(resolved, { withFileTypes: true });
44755
+ entries = fs18.readdirSync(resolved, { withFileTypes: true });
44639
44756
  } catch {
44640
44757
  continue;
44641
44758
  }
@@ -44664,7 +44781,7 @@ function expandPathForDate(template, input, day) {
44664
44781
  let workspaceResolved = workspaceRaw;
44665
44782
  if (workspaceRaw) {
44666
44783
  try {
44667
- workspaceResolved = fs17.realpathSync(workspaceRaw);
44784
+ workspaceResolved = fs18.realpathSync(workspaceRaw);
44668
44785
  } catch {
44669
44786
  }
44670
44787
  }
@@ -44689,7 +44806,7 @@ function expandPathForDate(template, input, day) {
44689
44806
  function newestRecentFile(dir, pattern, windowMs, sessionFloorMs = 0) {
44690
44807
  let entries;
44691
44808
  try {
44692
- entries = fs17.readdirSync(dir, { withFileTypes: true });
44809
+ entries = fs18.readdirSync(dir, { withFileTypes: true });
44693
44810
  } catch {
44694
44811
  return null;
44695
44812
  }
@@ -44706,7 +44823,7 @@ function newestRecentFile(dir, pattern, windowMs, sessionFloorMs = 0) {
44706
44823
  }
44707
44824
  function safeMtimeMs(p) {
44708
44825
  try {
44709
- return Math.floor(fs17.statSync(p).mtimeMs);
44826
+ return Math.floor(fs18.statSync(p).mtimeMs);
44710
44827
  } catch {
44711
44828
  return 0;
44712
44829
  }
@@ -44736,6 +44853,47 @@ function pickExactSessionFileAcrossGlob(template, pattern, requestedSessionId) {
44736
44853
  matches.sort((a, b) => safeMtimeMs(b) - safeMtimeMs(a));
44737
44854
  return matches[0] || null;
44738
44855
  }
44856
+ function pickDirUuidFileAcrossGlob(template, pattern, requestedSessionId) {
44857
+ if (!requestedSessionId) return null;
44858
+ const wantUuid = requestedSessionId.match(UUID_RE)?.[1]?.toLowerCase();
44859
+ if (!wantUuid) return null;
44860
+ const dirs = expandDirGlob(template);
44861
+ const matches = [];
44862
+ for (const d of dirs) {
44863
+ for (const p of listMatchingFiles(d, pattern)) {
44864
+ if (dirUuid(p).toLowerCase() === wantUuid) matches.push(p);
44865
+ }
44866
+ }
44867
+ matches.sort((a, b) => safeMtimeMs(b) - safeMtimeMs(a));
44868
+ return matches[0] || null;
44869
+ }
44870
+ function pickSidecarWorkspaceFileAcrossGlob(template, pattern, windowMs, sessionFloorMs, workspaceHint, sidecar) {
44871
+ if (!sidecar || !workspaceHint) return null;
44872
+ let wsResolved = workspaceHint;
44873
+ try {
44874
+ wsResolved = fs18.realpathSync(workspaceHint);
44875
+ } catch {
44876
+ }
44877
+ const dirs = expandDirGlob(template);
44878
+ const cutoff = Math.max(Date.now() - windowMs, sessionFloorMs);
44879
+ let best = null;
44880
+ for (const d of dirs) {
44881
+ for (const p of listMatchingFiles(d, pattern)) {
44882
+ const mtime = safeMtimeMs(p);
44883
+ if (mtime < cutoff) continue;
44884
+ const ws = readSidecarWorkspace(p, sidecar);
44885
+ if (!ws) continue;
44886
+ let wsReal = ws;
44887
+ try {
44888
+ wsReal = fs18.realpathSync(ws);
44889
+ } catch {
44890
+ }
44891
+ if (ws !== workspaceHint && wsReal !== wsResolved) continue;
44892
+ if (!best || mtime > best.mtime) best = { p, mtime };
44893
+ }
44894
+ }
44895
+ return best ? best.p : null;
44896
+ }
44739
44897
  function pickExactSessionFileAcrossDateWindow(template, input, pattern, requestedSessionId) {
44740
44898
  if (!requestedSessionId) return null;
44741
44899
  const matches = [];
@@ -44751,10 +44909,10 @@ function pickExactSessionFileAcrossDateWindow(template, input, pattern, requeste
44751
44909
  }
44752
44910
  function readCandidateSessionMeta(filePath) {
44753
44911
  try {
44754
- const fd = fs17.openSync(filePath, "r");
44912
+ const fd = fs18.openSync(filePath, "r");
44755
44913
  try {
44756
44914
  const buf = Buffer.alloc(8192);
44757
- const bytes = fs17.readSync(fd, buf, 0, buf.length, 0);
44915
+ const bytes = fs18.readSync(fd, buf, 0, buf.length, 0);
44758
44916
  if (bytes <= 0) return null;
44759
44917
  const text = buf.subarray(0, bytes).toString("utf8");
44760
44918
  const nl = text.indexOf("\n");
@@ -44772,7 +44930,7 @@ function readCandidateSessionMeta(filePath) {
44772
44930
  sessionTimestampMs: Number.isFinite(tsMs) ? tsMs : void 0
44773
44931
  };
44774
44932
  } finally {
44775
- fs17.closeSync(fd);
44933
+ fs18.closeSync(fd);
44776
44934
  }
44777
44935
  } catch {
44778
44936
  return null;
@@ -44782,7 +44940,7 @@ function pickBoundFromEntries(candidatePaths, sessionFloorMs, workspaceHint) {
44782
44940
  if (!sessionFloorMs || !workspaceHint || candidatePaths.length === 0) return null;
44783
44941
  let workspaceResolved = workspaceHint;
44784
44942
  try {
44785
- workspaceResolved = fs17.realpathSync(workspaceHint);
44943
+ workspaceResolved = fs18.realpathSync(workspaceHint);
44786
44944
  } catch {
44787
44945
  }
44788
44946
  let best = null;
@@ -44791,7 +44949,7 @@ function pickBoundFromEntries(candidatePaths, sessionFloorMs, workspaceHint) {
44791
44949
  if (!meta || !meta.cwd || meta.sessionTimestampMs == null) continue;
44792
44950
  let candidateCwd = meta.cwd;
44793
44951
  try {
44794
- candidateCwd = fs17.realpathSync(meta.cwd);
44952
+ candidateCwd = fs18.realpathSync(meta.cwd);
44795
44953
  } catch {
44796
44954
  }
44797
44955
  if (candidateCwd !== workspaceResolved && meta.cwd !== workspaceHint) continue;
@@ -44804,7 +44962,7 @@ function pickBoundFromEntries(candidatePaths, sessionFloorMs, workspaceHint) {
44804
44962
  function listMatchingFiles(dir, pattern) {
44805
44963
  let entries;
44806
44964
  try {
44807
- entries = fs17.readdirSync(dir, { withFileTypes: true });
44965
+ entries = fs18.readdirSync(dir, { withFileTypes: true });
44808
44966
  } catch {
44809
44967
  return [];
44810
44968
  }
@@ -45099,7 +45257,7 @@ function evalTerm(t, record) {
45099
45257
 
45100
45258
  // src/providers/spec/background-task-detector.ts
45101
45259
  init_logger();
45102
- import * as fs18 from "fs";
45260
+ import * as fs19 from "fs";
45103
45261
  var EMPTY = { active: false, count: 0, ids: [] };
45104
45262
  var TAIL_BYTES = 512 * 1024;
45105
45263
  function detectBackgroundTaskActive(cfg, input) {
@@ -45160,19 +45318,19 @@ function detectFromRecords(records) {
45160
45318
  return { active: true, count: unresolved.length, ids: unresolved };
45161
45319
  }
45162
45320
  function readTailJsonlLines(filePath, maxBytes) {
45163
- const stat2 = fs18.statSync(filePath);
45321
+ const stat2 = fs19.statSync(filePath);
45164
45322
  const size = stat2.size;
45165
45323
  const start = size > maxBytes ? size - maxBytes : 0;
45166
45324
  const length = size - start;
45167
45325
  if (length <= 0) return [];
45168
- const fd = fs18.openSync(filePath, "r");
45326
+ const fd = fs19.openSync(filePath, "r");
45169
45327
  let text;
45170
45328
  try {
45171
45329
  const buf = Buffer.alloc(length);
45172
- const bytes = fs18.readSync(fd, buf, 0, length, start);
45330
+ const bytes = fs19.readSync(fd, buf, 0, length, start);
45173
45331
  text = buf.subarray(0, bytes).toString("utf8");
45174
45332
  } finally {
45175
- fs18.closeSync(fd);
45333
+ fs19.closeSync(fd);
45176
45334
  }
45177
45335
  const rawLines = text.split("\n");
45178
45336
  if (start > 0 && rawLines.length > 0) rawLines.shift();
@@ -45190,12 +45348,12 @@ function readTailJsonlLines(filePath, maxBytes) {
45190
45348
 
45191
45349
  // src/providers/spec/cli-adapter.ts
45192
45350
  init_logger();
45193
- import * as fs19 from "fs";
45351
+ import * as fs20 from "fs";
45194
45352
  function stripAnsi3(text) {
45195
45353
  return String(text || "").replace(/\x1B\][^\x07]*(?:\x07|\x1B\\)/g, "").replace(/\x1B[P^_X][\s\S]*?(?:\x07|\x1B\\)/g, "").replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, "");
45196
45354
  }
45197
45355
  function delay(ms) {
45198
- return new Promise((resolve25) => setTimeout(resolve25, ms));
45356
+ return new Promise((resolve26) => setTimeout(resolve26, ms));
45199
45357
  }
45200
45358
  var SpecCliAdapter = class _SpecCliAdapter {
45201
45359
  cliType;
@@ -45259,7 +45417,7 @@ var SpecCliAdapter = class _SpecCliAdapter {
45259
45417
  * hermes ships a runtime MCP override. */
45260
45418
  spawnedEnv = {};
45261
45419
  constructor(specPath, workingDir, cliArgs, extraEnv, transportFactory) {
45262
- const raw = JSON.parse(fs19.readFileSync(specPath, "utf8"));
45420
+ const raw = JSON.parse(fs20.readFileSync(specPath, "utf8"));
45263
45421
  this.spec = {
45264
45422
  id: raw.id,
45265
45423
  name: raw.name,
@@ -45411,7 +45569,7 @@ var SpecCliAdapter = class _SpecCliAdapter {
45411
45569
  const steps = buildClaudeInteractiveTuiAnswerSteps(prompt, response);
45412
45570
  for (const step of steps) {
45413
45571
  this.driver.dispatch({ kind: "pty_write", data: step });
45414
- await new Promise((resolve25) => setTimeout(resolve25, 180));
45572
+ await new Promise((resolve26) => setTimeout(resolve26, 180));
45415
45573
  }
45416
45574
  } else {
45417
45575
  this.driver.dispatch({ kind: "pty_write", data: `${buildClaudeInteractiveToolResult(response)}
@@ -45967,7 +46125,7 @@ var SpecCliAdapter = class _SpecCliAdapter {
45967
46125
  let screenText = this.driver.snapshot();
45968
46126
  const deadline = Date.now() + _SpecCliAdapter.CLAUDE_TUI_PAGE_SETTLE_TIMEOUT_MS;
45969
46127
  while (!detectClaudeTuiMultiSelect(screenText) && Date.now() < deadline) {
45970
- await new Promise((resolve25) => setTimeout(resolve25, _SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
46128
+ await new Promise((resolve26) => setTimeout(resolve26, _SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
45971
46129
  screenText = this.driver.snapshot();
45972
46130
  }
45973
46131
  return screenText;
@@ -45976,12 +46134,12 @@ var SpecCliAdapter = class _SpecCliAdapter {
45976
46134
  const pages = [{ screenText: firstScreen, header: headers[0] }];
45977
46135
  for (let index = 1; index < headers.length; index += 1) {
45978
46136
  this.driver.dispatch({ kind: "pty_write", data: " " });
45979
- await new Promise((resolve25) => setTimeout(resolve25, _SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
46137
+ await new Promise((resolve26) => setTimeout(resolve26, _SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
45980
46138
  pages.push({ screenText: await this.snapshotSettledClaudeTuiPage(), header: headers[index] });
45981
46139
  }
45982
46140
  for (let index = headers.length - 1; index > 0; index -= 1) {
45983
46141
  this.driver.dispatch({ kind: "pty_write", data: "\x1B[Z" });
45984
- await new Promise((resolve25) => setTimeout(resolve25, _SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
46142
+ await new Promise((resolve26) => setTimeout(resolve26, _SpecCliAdapter.CLAUDE_TUI_PAGE_POLL_INTERVAL_MS));
45985
46143
  const reread = await this.snapshotSettledClaudeTuiPage();
45986
46144
  const landed = pages[index - 1];
45987
46145
  if (landed && !detectClaudeTuiMultiSelect(landed.screenText) && detectClaudeTuiMultiSelect(reread)) {
@@ -46081,10 +46239,10 @@ init_logger();
46081
46239
  function createCliAdapter(provider, workingDir, cliArgs, extraEnv, transportFactory) {
46082
46240
  const resolvedSpecPath = provider._resolvedSpecPath;
46083
46241
  const dir = provider._resolvedProviderDir;
46084
- let specPath = resolvedSpecPath && fs20.existsSync(resolvedSpecPath) ? resolvedSpecPath : void 0;
46242
+ let specPath = resolvedSpecPath && fs21.existsSync(resolvedSpecPath) ? resolvedSpecPath : void 0;
46085
46243
  if (!specPath && dir) {
46086
46244
  const legacy = path25.join(dir, "spec.json");
46087
- if (fs20.existsSync(legacy)) specPath = legacy;
46245
+ if (fs21.existsSync(legacy)) specPath = legacy;
46088
46246
  }
46089
46247
  if (specPath) {
46090
46248
  try {
@@ -46169,7 +46327,7 @@ init_working_dir();
46169
46327
  import * as os20 from "os";
46170
46328
  import * as path26 from "path";
46171
46329
  import * as crypto4 from "crypto";
46172
- import * as fs21 from "fs";
46330
+ import * as fs22 from "fs";
46173
46331
  var IMAGE_MIME_EXTENSIONS = {
46174
46332
  "image/png": ".png",
46175
46333
  "image/jpeg": ".jpg",
@@ -46204,9 +46362,9 @@ function materializeImageDataPart(part, index, dir) {
46204
46362
  if (!part.data) return null;
46205
46363
  const rawData = part.data.includes(",") ? part.data.split(",").pop() || "" : part.data;
46206
46364
  if (!rawData) return null;
46207
- fs21.mkdirSync(dir, { recursive: true });
46365
+ fs22.mkdirSync(dir, { recursive: true });
46208
46366
  const filePath = path26.join(dir, safeInputImageBasename(index, part.mimeType));
46209
- fs21.writeFileSync(filePath, Buffer.from(rawData, "base64"));
46367
+ fs22.writeFileSync(filePath, Buffer.from(rawData, "base64"));
46210
46368
  cleanupStaleMaterializedImages(dir);
46211
46369
  return filePath;
46212
46370
  }
@@ -46218,14 +46376,14 @@ function cleanupStaleMaterializedImages(dir) {
46218
46376
  if (now - lastMaterializedImageCleanupAt < MATERIALIZED_IMAGE_CLEANUP_INTERVAL_MS) return;
46219
46377
  lastMaterializedImageCleanupAt = now;
46220
46378
  try {
46221
- const entries = fs21.readdirSync(dir);
46379
+ const entries = fs22.readdirSync(dir);
46222
46380
  for (const entry of entries) {
46223
46381
  if (!entry.startsWith("adhdev-input-image-")) continue;
46224
46382
  const fullPath = path26.join(dir, entry);
46225
46383
  try {
46226
- const stat2 = fs21.statSync(fullPath);
46384
+ const stat2 = fs22.statSync(fullPath);
46227
46385
  if (now - stat2.mtimeMs > MATERIALIZED_IMAGE_MAX_AGE_MS) {
46228
- fs21.unlinkSync(fullPath);
46386
+ fs22.unlinkSync(fullPath);
46229
46387
  }
46230
46388
  } catch {
46231
46389
  }
@@ -46372,7 +46530,7 @@ async function waitForCliAdapterReady(adapter, options) {
46372
46530
  if (status === "stopped") {
46373
46531
  throw new Error("CLI runtime stopped before it became ready");
46374
46532
  }
46375
- await new Promise((resolve25) => setTimeout(resolve25, pollMs));
46533
+ await new Promise((resolve26) => setTimeout(resolve26, pollMs));
46376
46534
  }
46377
46535
  throw new Error(`CLI runtime did not become ready within ${timeoutMs}ms`);
46378
46536
  }
@@ -46886,7 +47044,7 @@ var CliProviderInstance = class _CliProviderInstance {
46886
47044
  const resolvedDbPath = probe.dbPath.replace(/^~/, os21.homedir());
46887
47045
  const now = Date.now();
46888
47046
  if (this.cachedSqliteDbMissingUntil > now) return null;
46889
- if (!fs22.existsSync(resolvedDbPath)) {
47047
+ if (!fs23.existsSync(resolvedDbPath)) {
46890
47048
  this.cachedSqliteDbMissingUntil = now + 1e4;
46891
47049
  return null;
46892
47050
  }
@@ -47470,7 +47628,7 @@ var CliProviderInstance = class _CliProviderInstance {
47470
47628
  const enterCount = cliCommand.enterCount || 1;
47471
47629
  await this.adapter.writeRaw(cliCommand.text + "\r");
47472
47630
  for (let i = 1; i < enterCount; i += 1) {
47473
- await new Promise((resolve25) => setTimeout(resolve25, 50));
47631
+ await new Promise((resolve26) => setTimeout(resolve26, 50));
47474
47632
  await this.adapter.writeRaw("\r");
47475
47633
  }
47476
47634
  }
@@ -47564,7 +47722,7 @@ var CliProviderInstance = class _CliProviderInstance {
47564
47722
  }
47565
47723
  if (this.lastExternalCompletionProbe?.sourcePath) {
47566
47724
  try {
47567
- fs22.statSync(this.lastExternalCompletionProbe.sourcePath);
47725
+ fs23.statSync(this.lastExternalCompletionProbe.sourcePath);
47568
47726
  } catch {
47569
47727
  }
47570
47728
  }
@@ -49260,7 +49418,7 @@ ${buttons.join("\n")}`;
49260
49418
  };
49261
49419
  addDir(this.workingDir);
49262
49420
  try {
49263
- addDir(fs22.realpathSync.native(this.workingDir));
49421
+ addDir(fs23.realpathSync.native(this.workingDir));
49264
49422
  } catch {
49265
49423
  }
49266
49424
  return Array.from(dirs);
@@ -49935,13 +50093,13 @@ var AcpProviderInstance = class {
49935
50093
  }
49936
50094
  this.currentStatus = "waiting_approval";
49937
50095
  this.detectStatusTransition();
49938
- const approved = await new Promise((resolve25) => {
49939
- this.permissionResolvers.push(resolve25);
50096
+ const approved = await new Promise((resolve26) => {
50097
+ this.permissionResolvers.push(resolve26);
49940
50098
  setTimeout(() => {
49941
- const idx = this.permissionResolvers.indexOf(resolve25);
50099
+ const idx = this.permissionResolvers.indexOf(resolve26);
49942
50100
  if (idx >= 0) {
49943
50101
  this.permissionResolvers.splice(idx, 1);
49944
- resolve25(false);
50102
+ resolve26(false);
49945
50103
  }
49946
50104
  }, 3e5);
49947
50105
  });
@@ -50677,7 +50835,7 @@ async function waitForZeroMessageStartingLaunch(adapter) {
50677
50835
  } catch {
50678
50836
  return false;
50679
50837
  }
50680
- await new Promise((resolve25) => setTimeout(resolve25, ZERO_MESSAGE_STARTING_SEND_WAIT_MS));
50838
+ await new Promise((resolve26) => setTimeout(resolve26, ZERO_MESSAGE_STARTING_SEND_WAIT_MS));
50681
50839
  try {
50682
50840
  return hasZeroMessageStartingLaunch(adapter);
50683
50841
  } catch {
@@ -51992,7 +52150,7 @@ import * as os27 from "os";
51992
52150
  import * as path37 from "path";
51993
52151
 
51994
52152
  // src/providers/provider-loader.ts
51995
- import * as fs28 from "fs";
52153
+ import * as fs29 from "fs";
51996
52154
  import * as path36 from "path";
51997
52155
  import * as os26 from "os";
51998
52156
  import * as chokidar from "chokidar";
@@ -52392,12 +52550,12 @@ function validateControl(control, errors) {
52392
52550
  init_external_sources();
52393
52551
 
52394
52552
  // src/providers/native-history/dispatcher.ts
52395
- import * as fs27 from "fs";
52553
+ import * as fs28 from "fs";
52396
52554
  import * as os25 from "os";
52397
52555
  import * as path34 from "path";
52398
52556
 
52399
52557
  // src/providers/native-history/claude-cli-transcript.ts
52400
- import * as fs23 from "fs";
52558
+ import * as fs24 from "fs";
52401
52559
  import * as path30 from "path";
52402
52560
  function extractTimestampValue(value) {
52403
52561
  if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;
@@ -52411,7 +52569,7 @@ function extractTimestampValue(value) {
52411
52569
  }
52412
52570
  function statMtimeMs(filePath) {
52413
52571
  try {
52414
- return fs23.statSync(filePath).mtimeMs;
52572
+ return fs24.statSync(filePath).mtimeMs;
52415
52573
  } catch {
52416
52574
  return 0;
52417
52575
  }
@@ -52481,7 +52639,7 @@ function extractUserContentParts(content) {
52481
52639
  function parseTranscriptFile(filePath, sessionId, workspaceFallback) {
52482
52640
  let raw;
52483
52641
  try {
52484
- raw = fs23.readFileSync(filePath, "utf-8");
52642
+ raw = fs24.readFileSync(filePath, "utf-8");
52485
52643
  } catch {
52486
52644
  return [];
52487
52645
  }
@@ -52557,7 +52715,7 @@ function readSession(sessionPath) {
52557
52715
  if (!sessionPath || !path30.isAbsolute(sessionPath)) return null;
52558
52716
  const basename14 = path30.basename(sessionPath, ".jsonl");
52559
52717
  if (!isSafeSessionId(basename14)) return null;
52560
- if (!fs23.existsSync(sessionPath)) return null;
52718
+ if (!fs24.existsSync(sessionPath)) return null;
52561
52719
  const sourceMtimeMs = statMtimeMs(sessionPath);
52562
52720
  const messages = parseTranscriptFile(sessionPath, basename14);
52563
52721
  if (messages.length === 0) return null;
@@ -52575,7 +52733,7 @@ function readSession(sessionPath) {
52575
52733
  }
52576
52734
 
52577
52735
  // src/providers/native-history/codex-cli-transcript.ts
52578
- import * as fs24 from "fs";
52736
+ import * as fs25 from "fs";
52579
52737
  import * as path31 from "path";
52580
52738
  function extractTimestampValue2(value) {
52581
52739
  if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;
@@ -52589,7 +52747,7 @@ function extractTimestampValue2(value) {
52589
52747
  }
52590
52748
  function statMtimeMs2(filePath) {
52591
52749
  try {
52592
- return fs24.statSync(filePath).mtimeMs;
52750
+ return fs25.statSync(filePath).mtimeMs;
52593
52751
  } catch {
52594
52752
  return 0;
52595
52753
  }
@@ -52686,7 +52844,7 @@ function pushAssistantStandardMessage(records, sessionId, receivedAt, content, w
52686
52844
  }
52687
52845
  function readSessionMeta(filePath) {
52688
52846
  try {
52689
- const firstLine = fs24.readFileSync(filePath, "utf-8").split("\n").find(Boolean);
52847
+ const firstLine = fs25.readFileSync(filePath, "utf-8").split("\n").find(Boolean);
52690
52848
  if (!firstLine) return null;
52691
52849
  const parsed = JSON.parse(firstLine);
52692
52850
  if (String(parsed.type ?? "") !== "session_meta") return null;
@@ -52698,7 +52856,7 @@ function readSessionMeta(filePath) {
52698
52856
  function parseSessionFile(filePath, sessionId, workspaceFallback) {
52699
52857
  let raw;
52700
52858
  try {
52701
- raw = fs24.readFileSync(filePath, "utf-8");
52859
+ raw = fs25.readFileSync(filePath, "utf-8");
52702
52860
  } catch {
52703
52861
  return [];
52704
52862
  }
@@ -52814,7 +52972,7 @@ function parseSessionFile(filePath, sessionId, workspaceFallback) {
52814
52972
  }
52815
52973
  function readSession2(sessionPath) {
52816
52974
  if (!sessionPath || !path31.isAbsolute(sessionPath)) return null;
52817
- if (!fs24.existsSync(sessionPath)) return null;
52975
+ if (!fs25.existsSync(sessionPath)) return null;
52818
52976
  const meta = readSessionMeta(sessionPath);
52819
52977
  const metaId = String(meta?.id ?? "").trim();
52820
52978
  const basename14 = path31.basename(sessionPath, ".jsonl");
@@ -52843,7 +53001,7 @@ function readSession2(sessionPath) {
52843
53001
  // src/providers/native-history/antigravity-cli-transcript.ts
52844
53002
  init_load_better_sqlite3();
52845
53003
  init_logger();
52846
- import * as fs25 from "fs";
53004
+ import * as fs26 from "fs";
52847
53005
  import * as path32 from "path";
52848
53006
  import * as os23 from "os";
52849
53007
  function extractTimestampValue3(value) {
@@ -52858,7 +53016,7 @@ function extractTimestampValue3(value) {
52858
53016
  }
52859
53017
  function statMtimeMs3(filePath) {
52860
53018
  try {
52861
- return fs25.statSync(filePath).mtimeMs;
53019
+ return fs26.statSync(filePath).mtimeMs;
52862
53020
  } catch {
52863
53021
  return 0;
52864
53022
  }
@@ -52887,12 +53045,12 @@ function resolvePathInside(root, ...segments) {
52887
53045
  function findBrainTranscriptPath(sessionId) {
52888
53046
  if (!isUuidLike(sessionId)) return null;
52889
53047
  const logsRoot = resolvePathInside(brainRoot(), sessionId, ".system_generated", "logs");
52890
- if (!logsRoot || !fs25.existsSync(logsRoot)) return null;
52891
- const candidates = ["transcript_full.jsonl", "transcript.jsonl"].map((file) => resolvePathInside(logsRoot, file)).filter((p) => p !== null && fs25.existsSync(p));
53048
+ if (!logsRoot || !fs26.existsSync(logsRoot)) return null;
53049
+ const candidates = ["transcript_full.jsonl", "transcript.jsonl"].map((file) => resolvePathInside(logsRoot, file)).filter((p) => p !== null && fs26.existsSync(p));
52892
53050
  if (candidates.length === 0) {
52893
53051
  let entries = [];
52894
53052
  try {
52895
- entries = fs25.readdirSync(logsRoot, { withFileTypes: true });
53053
+ entries = fs26.readdirSync(logsRoot, { withFileTypes: true });
52896
53054
  } catch {
52897
53055
  return null;
52898
53056
  }
@@ -52918,7 +53076,7 @@ function antigravityRowKind(rowType) {
52918
53076
  function parseBrainTranscript(filePath, sessionId, workspace) {
52919
53077
  let raw;
52920
53078
  try {
52921
- raw = fs25.readFileSync(filePath, "utf-8");
53079
+ raw = fs26.readFileSync(filePath, "utf-8");
52922
53080
  } catch {
52923
53081
  return null;
52924
53082
  }
@@ -52978,7 +53136,7 @@ function readHistoryRows() {
52978
53136
  const sourcePath = historyJsonlPath();
52979
53137
  let lines = [];
52980
53138
  try {
52981
- lines = fs25.readFileSync(sourcePath, "utf-8").split("\n").filter(Boolean);
53139
+ lines = fs26.readFileSync(sourcePath, "utf-8").split("\n").filter(Boolean);
52982
53140
  } catch {
52983
53141
  return [];
52984
53142
  }
@@ -53026,7 +53184,7 @@ function extractStringsFromBuffer(buf) {
53026
53184
  function parsePbFile(filePath, sessionId) {
53027
53185
  let buf;
53028
53186
  try {
53029
- buf = fs25.readFileSync(filePath);
53187
+ buf = fs26.readFileSync(filePath);
53030
53188
  } catch {
53031
53189
  return null;
53032
53190
  }
@@ -53374,7 +53532,7 @@ function readAntigravitySiblingFallback(sessionId, workspace) {
53374
53532
  }
53375
53533
  }
53376
53534
  const pbPath = resolvePathInside(conversationsRoot(), `${sessionId}.pb`);
53377
- if (pbPath && fs25.existsSync(pbPath)) {
53535
+ if (pbPath && fs26.existsSync(pbPath)) {
53378
53536
  const pbMessages = parsePbFile(pbPath, sessionId);
53379
53537
  if (pbMessages && pbMessages.length > 0) {
53380
53538
  return {
@@ -53393,7 +53551,7 @@ function readAntigravitySiblingFallback(sessionId, workspace) {
53393
53551
  }
53394
53552
  function readSession3(sessionPath, sessionId, workspace) {
53395
53553
  if (!sessionPath || !path32.isAbsolute(sessionPath)) return null;
53396
- if (!fs25.existsSync(sessionPath)) return null;
53554
+ if (!fs26.existsSync(sessionPath)) return null;
53397
53555
  const sourceMtimeMs = statMtimeMs3(sessionPath);
53398
53556
  const brainRootPath = brainRoot();
53399
53557
  if (sessionPath.startsWith(brainRootPath + path32.sep) && sessionPath.endsWith(".jsonl")) {
@@ -53455,20 +53613,20 @@ function readSession3(sessionPath, sessionId, workspace) {
53455
53613
 
53456
53614
  // src/providers/native-history/hermes-cli-transcript.ts
53457
53615
  init_load_better_sqlite3();
53458
- import * as fs26 from "fs";
53616
+ import * as fs27 from "fs";
53459
53617
  import * as path33 from "path";
53460
53618
  import * as os24 from "os";
53461
53619
  var HERMES_STATE_DB = path33.join(os24.homedir(), ".hermes", "state.db");
53462
53620
  var HERMES_LEGACY_SESSIONS_DIR = path33.join(os24.homedir(), ".hermes", "sessions");
53463
53621
  function statMtimeMs4(p) {
53464
53622
  try {
53465
- return Math.floor(fs26.statSync(p).mtimeMs);
53623
+ return Math.floor(fs27.statSync(p).mtimeMs);
53466
53624
  } catch {
53467
53625
  return 0;
53468
53626
  }
53469
53627
  }
53470
53628
  function openDb() {
53471
- if (!fs26.existsSync(HERMES_STATE_DB)) return null;
53629
+ if (!fs27.existsSync(HERMES_STATE_DB)) return null;
53472
53630
  try {
53473
53631
  const Database = loadBetterSqlite3();
53474
53632
  return new Database(HERMES_STATE_DB, { readonly: true, fileMustExist: true });
@@ -53564,10 +53722,10 @@ function readSession4(sessionPath, requestedSessionId) {
53564
53722
  }
53565
53723
  }
53566
53724
  }
53567
- if (!path33.isAbsolute(sessionPath) || !fs26.existsSync(sessionPath)) return null;
53725
+ if (!path33.isAbsolute(sessionPath) || !fs27.existsSync(sessionPath)) return null;
53568
53726
  let raw;
53569
53727
  try {
53570
- raw = JSON.parse(fs26.readFileSync(sessionPath, "utf8"));
53728
+ raw = JSON.parse(fs27.readFileSync(sessionPath, "utf8"));
53571
53729
  } catch {
53572
53730
  return null;
53573
53731
  }
@@ -53622,7 +53780,7 @@ function createNativeHistoryDispatcher(reader) {
53622
53780
  const ownerConfirmed = reader === "antigravity-cli" ? resolved?.ownerConfirmed === true : void 0;
53623
53781
  if (input.forceRefresh === true || input.args?.forceRefresh === true) {
53624
53782
  try {
53625
- fs27.statSync(sourcePath);
53783
+ fs28.statSync(sourcePath);
53626
53784
  } catch {
53627
53785
  }
53628
53786
  }
@@ -53674,10 +53832,10 @@ function resolveSourcePath(reader, workspace, sessionId, sessionStartedAtMs, ins
53674
53832
  }
53675
53833
  function resolveClaudePath(workspace, sessionId) {
53676
53834
  const dir = path34.join(os25.homedir(), ".claude", "projects", cwdAsDashes(workspace));
53677
- if (!fs27.existsSync(dir)) return null;
53835
+ if (!fs28.existsSync(dir)) return null;
53678
53836
  if (sessionId) {
53679
53837
  const candidate = path34.join(dir, `${sessionId}.jsonl`);
53680
- if (fs27.existsSync(candidate)) return candidate;
53838
+ if (fs28.existsSync(candidate)) return candidate;
53681
53839
  }
53682
53840
  return null;
53683
53841
  }
@@ -53689,7 +53847,7 @@ function resolveCodexPath(workspace, sessionId, sessionStartedAtMs) {
53689
53847
  return findCodexPathByRuntime(root, workspace, sessionStartedAtMs);
53690
53848
  }
53691
53849
  function findCodexPathBySessionId(root, sessionId) {
53692
- if (!fs27.existsSync(root)) return null;
53850
+ if (!fs28.existsSync(root)) return null;
53693
53851
  const needle = sessionId.toLowerCase();
53694
53852
  const matches = [];
53695
53853
  const stack = [root];
@@ -53697,7 +53855,7 @@ function findCodexPathBySessionId(root, sessionId) {
53697
53855
  const current = stack.pop();
53698
53856
  let entries = [];
53699
53857
  try {
53700
- entries = fs27.readdirSync(current, { withFileTypes: true });
53858
+ entries = fs28.readdirSync(current, { withFileTypes: true });
53701
53859
  } catch {
53702
53860
  continue;
53703
53861
  }
@@ -53717,7 +53875,7 @@ function findCodexPathBySessionId(root, sessionId) {
53717
53875
  return matches[0]?.p ?? null;
53718
53876
  }
53719
53877
  function findCodexPathByRuntime(root, workspace, sessionStartedAtMs) {
53720
- if (!fs27.existsSync(root) || !workspace) return null;
53878
+ if (!fs28.existsSync(root) || !workspace) return null;
53721
53879
  const workspaceResolved = resolveRealPath(workspace);
53722
53880
  const cutoff = Date.now() - RECENT_WINDOW_MS;
53723
53881
  const matches = [];
@@ -53726,7 +53884,7 @@ function findCodexPathByRuntime(root, workspace, sessionStartedAtMs) {
53726
53884
  const current = stack.pop();
53727
53885
  let entries = [];
53728
53886
  try {
53729
- entries = fs27.readdirSync(current, { withFileTypes: true });
53887
+ entries = fs28.readdirSync(current, { withFileTypes: true });
53730
53888
  } catch {
53731
53889
  continue;
53732
53890
  }
@@ -53751,10 +53909,10 @@ function findCodexPathByRuntime(root, workspace, sessionStartedAtMs) {
53751
53909
  }
53752
53910
  function readCodexSessionMeta(filePath) {
53753
53911
  try {
53754
- const fd = fs27.openSync(filePath, "r");
53912
+ const fd = fs28.openSync(filePath, "r");
53755
53913
  try {
53756
53914
  const buffer = Buffer.alloc(8192);
53757
- const bytes = fs27.readSync(fd, buffer, 0, buffer.length, 0);
53915
+ const bytes = fs28.readSync(fd, buffer, 0, buffer.length, 0);
53758
53916
  if (bytes <= 0) return null;
53759
53917
  const text = buffer.subarray(0, bytes).toString("utf8");
53760
53918
  const firstLine = text.slice(0, text.indexOf("\n") >= 0 ? text.indexOf("\n") : text.length).trim();
@@ -53769,7 +53927,7 @@ function readCodexSessionMeta(filePath) {
53769
53927
  timestampMs: Number.isFinite(timestampMs) ? timestampMs : void 0
53770
53928
  };
53771
53929
  } finally {
53772
- fs27.closeSync(fd);
53930
+ fs28.closeSync(fd);
53773
53931
  }
53774
53932
  } catch {
53775
53933
  return null;
@@ -53777,7 +53935,7 @@ function readCodexSessionMeta(filePath) {
53777
53935
  }
53778
53936
  function resolveRealPath(value) {
53779
53937
  try {
53780
- return fs27.realpathSync(value);
53938
+ return fs28.realpathSync(value);
53781
53939
  } catch {
53782
53940
  return value;
53783
53941
  }
@@ -53799,19 +53957,19 @@ function resolveAntigravityPath(workspace, sessionId, sessionStartedAtMs, instan
53799
53957
  const owner = antigravityOwnerToken(workspace, sessionStartedAtMs, instanceId);
53800
53958
  if (sessionId && isUuidLikeSessionId2(sessionId)) {
53801
53959
  const dbPath = path34.join(agyRoot, "conversations", `${sessionId}.db`);
53802
- if (fs27.existsSync(dbPath)) {
53960
+ if (fs28.existsSync(dbPath)) {
53803
53961
  if (owner) claimAntigravityConversation(sessionId, owner);
53804
53962
  return { path: dbPath, ownerConfirmed: true };
53805
53963
  }
53806
53964
  }
53807
53965
  const brainRoot2 = path34.join(agyRoot, "brain");
53808
- if (fs27.existsSync(brainRoot2)) {
53966
+ if (fs28.existsSync(brainRoot2)) {
53809
53967
  const cutoff = spawnAwareCutoff(sessionStartedAtMs);
53810
53968
  const nonEmptyBrain = (uuid, p) => {
53811
53969
  const t = path34.join(p, ".system_generated", "logs", "transcript.jsonl");
53812
- return fs27.existsSync(t) && safeSize(t) > 0 ? t : null;
53970
+ return fs28.existsSync(t) && safeSize(t) > 0 ? t : null;
53813
53971
  };
53814
- const all = fs27.readdirSync(brainRoot2, { withFileTypes: true }).filter((e) => e.isDirectory() && isUuidLikeSessionId2(e.name)).filter((e) => !isAntigravityConversationClaimedByOther(e.name, owner)).map((e) => {
53972
+ const all = fs28.readdirSync(brainRoot2, { withFileTypes: true }).filter((e) => e.isDirectory() && isUuidLikeSessionId2(e.name)).filter((e) => !isAntigravityConversationClaimedByOther(e.name, owner)).map((e) => {
53815
53973
  const p = path34.join(brainRoot2, e.name);
53816
53974
  return { uuid: e.name, p, mtime: safeMtime(p), birth: safeBirthtime(p) };
53817
53975
  }).filter((e) => e.mtime >= cutoff);
@@ -53842,7 +54000,7 @@ function resolveAntigravityPath(workspace, sessionId, sessionStartedAtMs, instan
53842
54000
  function pickUnboundConversationDb(convRoot, sessionFloorMs, owner) {
53843
54001
  let entries = [];
53844
54002
  try {
53845
- entries = fs27.readdirSync(convRoot, { withFileTypes: true });
54003
+ entries = fs28.readdirSync(convRoot, { withFileTypes: true });
53846
54004
  } catch {
53847
54005
  return null;
53848
54006
  }
@@ -53880,9 +54038,9 @@ function resolveHermesPath(workspace, sessionId) {
53880
54038
  void workspace;
53881
54039
  void sessionId;
53882
54040
  const dbPath = path34.join(os25.homedir(), ".hermes", "state.db");
53883
- if (fs27.existsSync(dbPath)) return dbPath;
54041
+ if (fs28.existsSync(dbPath)) return dbPath;
53884
54042
  const dir = path34.join(os25.homedir(), ".hermes", "sessions");
53885
- if (!fs27.existsSync(dir)) return null;
54043
+ if (!fs28.existsSync(dir)) return null;
53886
54044
  return newestRecentFile2(dir, /^session_.*\.json$/);
53887
54045
  }
53888
54046
  function readByReader(reader, sourcePath, sessionId, workspace, requestedProviderSid) {
@@ -53919,7 +54077,7 @@ var RECENT_WINDOW_MS = 5 * 60 * 1e3;
53919
54077
  function newestRecentFile2(dir, pattern) {
53920
54078
  try {
53921
54079
  const cutoff = Date.now() - RECENT_WINDOW_MS;
53922
- const entries = fs27.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);
54080
+ const entries = fs28.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);
53923
54081
  return entries[0]?.p ?? null;
53924
54082
  } catch {
53925
54083
  return null;
@@ -53927,14 +54085,14 @@ function newestRecentFile2(dir, pattern) {
53927
54085
  }
53928
54086
  function safeMtime(p) {
53929
54087
  try {
53930
- return Math.floor(fs27.statSync(p).mtimeMs);
54088
+ return Math.floor(fs28.statSync(p).mtimeMs);
53931
54089
  } catch {
53932
54090
  return 0;
53933
54091
  }
53934
54092
  }
53935
54093
  function safeBirthtime(p) {
53936
54094
  try {
53937
- const st = fs27.statSync(p);
54095
+ const st = fs28.statSync(p);
53938
54096
  const birth = Math.floor(st.birthtimeMs);
53939
54097
  return birth > 0 ? birth : Math.floor(st.mtimeMs);
53940
54098
  } catch {
@@ -53943,7 +54101,7 @@ function safeBirthtime(p) {
53943
54101
  }
53944
54102
  function safeSize(p) {
53945
54103
  try {
53946
- return fs27.statSync(p).size;
54104
+ return fs28.statSync(p).size;
53947
54105
  } catch {
53948
54106
  return 0;
53949
54107
  }
@@ -54037,9 +54195,9 @@ var ProviderLoader = class _ProviderLoader {
54037
54195
  static siblingStderrLogged = /* @__PURE__ */ new Set();
54038
54196
  static looksLikeProviderRoot(candidate) {
54039
54197
  try {
54040
- if (!fs28.existsSync(candidate) || !fs28.statSync(candidate).isDirectory()) return false;
54198
+ if (!fs29.existsSync(candidate) || !fs29.statSync(candidate).isDirectory()) return false;
54041
54199
  return ["ide", "extension", "cli", "acp"].some(
54042
- (category) => fs28.existsSync(path36.join(candidate, category))
54200
+ (category) => fs29.existsSync(path36.join(candidate, category))
54043
54201
  );
54044
54202
  } catch {
54045
54203
  return false;
@@ -54047,7 +54205,7 @@ var ProviderLoader = class _ProviderLoader {
54047
54205
  }
54048
54206
  static hasProviderRootMarker(candidate) {
54049
54207
  try {
54050
- return fs28.existsSync(path36.join(candidate, _ProviderLoader.SIBLING_MARKER_FILE));
54208
+ return fs29.existsSync(path36.join(candidate, _ProviderLoader.SIBLING_MARKER_FILE));
54051
54209
  } catch {
54052
54210
  return false;
54053
54211
  }
@@ -54112,12 +54270,12 @@ var ProviderLoader = class _ProviderLoader {
54112
54270
  const home = os26.homedir();
54113
54271
  const oldDir = path36.join(home, ".adhdev", "marketplace");
54114
54272
  const newDir = path36.join(home, ".adhdev", "external");
54115
- if (!fs28.existsSync(oldDir)) return;
54116
- if (fs28.existsSync(newDir)) {
54273
+ if (!fs29.existsSync(oldDir)) return;
54274
+ if (fs29.existsSync(newDir)) {
54117
54275
  this.log(`Migration skipped: both ~/.adhdev/marketplace and ~/.adhdev/external exist (marketplace dir is now inert and can be removed manually).`);
54118
54276
  return;
54119
54277
  }
54120
- fs28.renameSync(oldDir, newDir);
54278
+ fs29.renameSync(oldDir, newDir);
54121
54279
  this.log(`Migrated ~/.adhdev/marketplace \u2192 ~/.adhdev/external (one-time rename after provider source-layer cleanup).`);
54122
54280
  } catch (e) {
54123
54281
  this.log(`Marketplace\u2192external migration failed: ${e?.message || e}`);
@@ -54232,7 +54390,7 @@ var ProviderLoader = class _ProviderLoader {
54232
54390
  this.providers.clear();
54233
54391
  this.providerAvailability.clear();
54234
54392
  let upstreamCount = 0;
54235
- if (!this.disableUpstream && fs28.existsSync(this.upstreamDir)) {
54393
+ if (!this.disableUpstream && fs29.existsSync(this.upstreamDir)) {
54236
54394
  upstreamCount = this.loadDir(this.upstreamDir);
54237
54395
  if (upstreamCount > 0) {
54238
54396
  this.log(`Loaded ${upstreamCount} upstream providers (auto-updated)`);
@@ -54241,10 +54399,10 @@ var ProviderLoader = class _ProviderLoader {
54241
54399
  this.log("Upstream loading disabled (sourceMode=no-upstream)");
54242
54400
  }
54243
54401
  const externalDir = path36.join(os26.homedir(), ".adhdev", "external");
54244
- if (fs28.existsSync(externalDir)) {
54402
+ if (fs29.existsSync(externalDir)) {
54245
54403
  const rootEntries = (() => {
54246
54404
  try {
54247
- return fs28.readdirSync(externalDir, { withFileTypes: true });
54405
+ return fs29.readdirSync(externalDir, { withFileTypes: true });
54248
54406
  } catch {
54249
54407
  return [];
54250
54408
  }
@@ -54293,7 +54451,7 @@ var ProviderLoader = class _ProviderLoader {
54293
54451
  }
54294
54452
  }
54295
54453
  }
54296
- if (fs28.existsSync(this.userDir)) {
54454
+ if (fs29.existsSync(this.userDir)) {
54297
54455
  const userCount = this.loadDir(this.userDir, [".upstream"]);
54298
54456
  if (userCount > 0) {
54299
54457
  this.log(`Loaded ${userCount} user custom providers (never auto-updated)`);
@@ -54308,10 +54466,10 @@ var ProviderLoader = class _ProviderLoader {
54308
54466
  * Check if upstream directory exists and has providers.
54309
54467
  */
54310
54468
  hasUpstream() {
54311
- if (!fs28.existsSync(this.upstreamDir)) return false;
54469
+ if (!fs29.existsSync(this.upstreamDir)) return false;
54312
54470
  try {
54313
- return fs28.readdirSync(this.upstreamDir).some(
54314
- (d) => fs28.statSync(path36.join(this.upstreamDir, d)).isDirectory()
54471
+ return fs29.readdirSync(this.upstreamDir).some(
54472
+ (d) => fs29.statSync(path36.join(this.upstreamDir, d)).isDirectory()
54315
54473
  );
54316
54474
  } catch {
54317
54475
  return false;
@@ -54810,7 +54968,7 @@ var ProviderLoader = class _ProviderLoader {
54810
54968
  resolved._resolvedScriptsSource = `compatibility:${entry.ideVersion}`;
54811
54969
  if (providerDir) {
54812
54970
  const fullDir = path36.join(providerDir, entry.scriptDir);
54813
- resolved._resolvedScriptsPath = fs28.existsSync(path36.join(fullDir, "scripts.js")) ? path36.join(fullDir, "scripts.js") : fullDir;
54971
+ resolved._resolvedScriptsPath = fs29.existsSync(path36.join(fullDir, "scripts.js")) ? path36.join(fullDir, "scripts.js") : fullDir;
54814
54972
  }
54815
54973
  matched = true;
54816
54974
  }
@@ -54829,7 +54987,7 @@ var ProviderLoader = class _ProviderLoader {
54829
54987
  resolved._resolvedScriptsSource = "defaultScriptDir:version_miss";
54830
54988
  if (providerDir) {
54831
54989
  const fullDir = path36.join(providerDir, base.defaultScriptDir);
54832
- resolved._resolvedScriptsPath = fs28.existsSync(path36.join(fullDir, "scripts.js")) ? path36.join(fullDir, "scripts.js") : fullDir;
54990
+ resolved._resolvedScriptsPath = fs29.existsSync(path36.join(fullDir, "scripts.js")) ? path36.join(fullDir, "scripts.js") : fullDir;
54833
54991
  }
54834
54992
  }
54835
54993
  resolved._versionWarning = `Version ${currentVersion} not in compatibility matrix. Using default scripts.`;
@@ -54847,7 +55005,7 @@ var ProviderLoader = class _ProviderLoader {
54847
55005
  resolved._resolvedScriptsSource = `versions:${range}`;
54848
55006
  if (providerDir) {
54849
55007
  const fullDir = path36.join(providerDir, dirOverride);
54850
- resolved._resolvedScriptsPath = fs28.existsSync(path36.join(fullDir, "scripts.js")) ? path36.join(fullDir, "scripts.js") : fullDir;
55008
+ resolved._resolvedScriptsPath = fs29.existsSync(path36.join(fullDir, "scripts.js")) ? path36.join(fullDir, "scripts.js") : fullDir;
54851
55009
  }
54852
55010
  }
54853
55011
  } else if (override.scripts) {
@@ -54864,7 +55022,7 @@ var ProviderLoader = class _ProviderLoader {
54864
55022
  resolved._resolvedScriptsSource = "defaultScriptDir:no_version";
54865
55023
  if (providerDir) {
54866
55024
  const fullDir = path36.join(providerDir, base.defaultScriptDir);
54867
- resolved._resolvedScriptsPath = fs28.existsSync(path36.join(fullDir, "scripts.js")) ? path36.join(fullDir, "scripts.js") : fullDir;
55025
+ resolved._resolvedScriptsPath = fs29.existsSync(path36.join(fullDir, "scripts.js")) ? path36.join(fullDir, "scripts.js") : fullDir;
54868
55026
  }
54869
55027
  }
54870
55028
  }
@@ -54882,7 +55040,7 @@ var ProviderLoader = class _ProviderLoader {
54882
55040
  for (const [scriptName, override] of Object.entries(base.overrides)) {
54883
55041
  if (!override || typeof override.path !== "string") continue;
54884
55042
  const fullPath = path36.join(providerDir2, override.path);
54885
- if (!fs28.existsSync(fullPath)) {
55043
+ if (!fs29.existsSync(fullPath)) {
54886
55044
  this.log(` [overrides] ${base.type}: ${scriptName} path not found: ${fullPath}`);
54887
55045
  continue;
54888
55046
  }
@@ -54912,7 +55070,7 @@ var ProviderLoader = class _ProviderLoader {
54912
55070
  }
54913
55071
  if (providerDir) {
54914
55072
  try {
54915
- const fs42 = __require("fs");
55073
+ const fs43 = __require("fs");
54916
55074
  const path45 = __require("path");
54917
55075
  const candidates = [];
54918
55076
  if (Array.isArray(base.compatibility)) {
@@ -54924,13 +55082,13 @@ var ProviderLoader = class _ProviderLoader {
54924
55082
  }
54925
55083
  candidates.push(path45.join(providerDir, "specs", "default.json"));
54926
55084
  candidates.push(path45.join(providerDir, "spec.json"));
54927
- const specPath = candidates.find((p) => fs42.existsSync(p));
55085
+ const specPath = candidates.find((p) => fs43.existsSync(p));
54928
55086
  let nh;
54929
55087
  if (specPath) {
54930
55088
  resolved._resolvedSpecPath = specPath;
54931
55089
  let specControls;
54932
55090
  try {
54933
- const rawSpec = JSON.parse(fs42.readFileSync(specPath, "utf8"));
55091
+ const rawSpec = JSON.parse(fs43.readFileSync(specPath, "utf8"));
54934
55092
  specControls = rawSpec.control_bar;
54935
55093
  nh = rawSpec.native_history;
54936
55094
  } catch {
@@ -54969,7 +55127,7 @@ var ProviderLoader = class _ProviderLoader {
54969
55127
  reader = (input) => executeNativeHistory(nh, input);
54970
55128
  } else if (nh.override_path) {
54971
55129
  const overrideFile = path45.resolve(providerDir, nh.override_path);
54972
- if (fs42.existsSync(overrideFile)) {
55130
+ if (fs43.existsSync(overrideFile)) {
54973
55131
  try {
54974
55132
  registerProviderScriptRootSafely(path45.dirname(path45.dirname(providerDir)));
54975
55133
  delete __require.cache[__require.resolve(overrideFile)];
@@ -55014,7 +55172,7 @@ var ProviderLoader = class _ProviderLoader {
55014
55172
  return null;
55015
55173
  }
55016
55174
  const dir = path36.join(providerDir, scriptDir);
55017
- if (!fs28.existsSync(dir)) {
55175
+ if (!fs29.existsSync(dir)) {
55018
55176
  this.debugLog(`[loadScriptsFromDir] ${type}: dir not found: ${dir}`);
55019
55177
  return null;
55020
55178
  }
@@ -55022,7 +55180,7 @@ var ProviderLoader = class _ProviderLoader {
55022
55180
  const cached3 = this.scriptsCache.get(dir);
55023
55181
  if (cached3) return cached3;
55024
55182
  const scriptsJs = path36.join(dir, "scripts.js");
55025
- if (fs28.existsSync(scriptsJs)) {
55183
+ if (fs29.existsSync(scriptsJs)) {
55026
55184
  try {
55027
55185
  delete __require.cache[__require.resolve(scriptsJs)];
55028
55186
  const loaded = __require(scriptsJs);
@@ -55043,9 +55201,9 @@ var ProviderLoader = class _ProviderLoader {
55043
55201
  watch() {
55044
55202
  this.stopWatch();
55045
55203
  const watchDir = (dir) => {
55046
- if (!fs28.existsSync(dir)) {
55204
+ if (!fs29.existsSync(dir)) {
55047
55205
  try {
55048
- fs28.mkdirSync(dir, { recursive: true });
55206
+ fs29.mkdirSync(dir, { recursive: true });
55049
55207
  } catch {
55050
55208
  return;
55051
55209
  }
@@ -55137,14 +55295,14 @@ var ProviderLoader = class _ProviderLoader {
55137
55295
  const regMetaPath = path36.join(this.upstreamDir, _ProviderLoader.REGISTRY_META_FILE);
55138
55296
  let cachedChecksums = {};
55139
55297
  try {
55140
- if (fs28.existsSync(regMetaPath)) {
55141
- cachedChecksums = JSON.parse(fs28.readFileSync(regMetaPath, "utf-8")).checksums ?? {};
55298
+ if (fs29.existsSync(regMetaPath)) {
55299
+ cachedChecksums = JSON.parse(fs29.readFileSync(regMetaPath, "utf-8")).checksums ?? {};
55142
55300
  }
55143
55301
  } catch {
55144
55302
  }
55145
55303
  try {
55146
55304
  const listUrl = `${this.registryBaseUrl}/providers`;
55147
- const listBody = await new Promise((resolve25, reject) => {
55305
+ const listBody = await new Promise((resolve26, reject) => {
55148
55306
  const req = https.get(listUrl, { headers: { "User-Agent": "adhdev-daemon", "Accept": "application/json" }, timeout: 1e4 }, (res) => {
55149
55307
  if (res.statusCode !== 200) {
55150
55308
  reject(new Error(`registry list HTTP ${res.statusCode}`));
@@ -55152,7 +55310,7 @@ var ProviderLoader = class _ProviderLoader {
55152
55310
  }
55153
55311
  const chunks = [];
55154
55312
  res.on("data", (c) => chunks.push(c));
55155
- res.on("end", () => resolve25(Buffer.concat(chunks).toString("utf-8")));
55313
+ res.on("end", () => resolve26(Buffer.concat(chunks).toString("utf-8")));
55156
55314
  });
55157
55315
  req.on("error", reject);
55158
55316
  req.on("timeout", () => {
@@ -55168,7 +55326,7 @@ var ProviderLoader = class _ProviderLoader {
55168
55326
  const cacheKey = `${category}/${type}`;
55169
55327
  if (cachedChecksums[cacheKey] === checksum) continue;
55170
55328
  const dlUrl = `${this.registryBaseUrl}/providers/${type}/${version}/download`;
55171
- const manifestBody = await new Promise((resolve25, reject) => {
55329
+ const manifestBody = await new Promise((resolve26, reject) => {
55172
55330
  const req = https.get(dlUrl, { headers: { "User-Agent": "adhdev-daemon", "Accept": "application/json" }, timeout: 3e4 }, (res) => {
55173
55331
  if (res.statusCode !== 200) {
55174
55332
  reject(new Error(`registry download HTTP ${res.statusCode} for ${type}@${version}`));
@@ -55176,7 +55334,7 @@ var ProviderLoader = class _ProviderLoader {
55176
55334
  }
55177
55335
  const chunks = [];
55178
55336
  res.on("data", (c) => chunks.push(c));
55179
- res.on("end", () => resolve25(Buffer.concat(chunks).toString("utf-8")));
55337
+ res.on("end", () => resolve26(Buffer.concat(chunks).toString("utf-8")));
55180
55338
  });
55181
55339
  req.on("error", reject);
55182
55340
  req.on("timeout", () => {
@@ -55190,14 +55348,14 @@ var ProviderLoader = class _ProviderLoader {
55190
55348
  continue;
55191
55349
  }
55192
55350
  const providerDir = path36.join(this.upstreamDir, category, type);
55193
- fs28.mkdirSync(providerDir, { recursive: true });
55194
- fs28.writeFileSync(path36.join(providerDir, "provider.json"), manifestBody, "utf-8");
55351
+ fs29.mkdirSync(providerDir, { recursive: true });
55352
+ fs29.writeFileSync(path36.join(providerDir, "provider.json"), manifestBody, "utf-8");
55195
55353
  cachedChecksums[cacheKey] = checksum;
55196
55354
  updatedCount++;
55197
55355
  this.log(`\u2713 Registry updated: ${category}/${type}@${version}`);
55198
55356
  }
55199
- fs28.mkdirSync(this.upstreamDir, { recursive: true });
55200
- fs28.writeFileSync(regMetaPath, JSON.stringify({
55357
+ fs29.mkdirSync(this.upstreamDir, { recursive: true });
55358
+ fs29.writeFileSync(regMetaPath, JSON.stringify({
55201
55359
  checksums: cachedChecksums,
55202
55360
  syncedAt: (/* @__PURE__ */ new Date()).toISOString(),
55203
55361
  providerCount: list.providers.length
@@ -55222,8 +55380,8 @@ var ProviderLoader = class _ProviderLoader {
55222
55380
  let prevEtag = "";
55223
55381
  let prevTimestamp = 0;
55224
55382
  try {
55225
- if (fs28.existsSync(metaPath)) {
55226
- const meta = JSON.parse(fs28.readFileSync(metaPath, "utf-8"));
55383
+ if (fs29.existsSync(metaPath)) {
55384
+ const meta = JSON.parse(fs29.readFileSync(metaPath, "utf-8"));
55227
55385
  prevEtag = meta.etag || "";
55228
55386
  prevTimestamp = meta.timestamp || 0;
55229
55387
  }
@@ -55236,7 +55394,7 @@ var ProviderLoader = class _ProviderLoader {
55236
55394
  }
55237
55395
  const tarballTarget = resolveProviderTarballTarget(this.providerTarballUrl);
55238
55396
  try {
55239
- const etag = await new Promise((resolve25, reject) => {
55397
+ const etag = await new Promise((resolve26, reject) => {
55240
55398
  const options = {
55241
55399
  method: "HEAD",
55242
55400
  hostname: tarballTarget.hostname,
@@ -55254,7 +55412,7 @@ var ProviderLoader = class _ProviderLoader {
55254
55412
  headers: { "User-Agent": "adhdev-launcher" },
55255
55413
  timeout: 1e4
55256
55414
  }, (res2) => {
55257
- resolve25(res2.headers.etag || res2.headers["last-modified"] || "");
55415
+ resolve26(res2.headers.etag || res2.headers["last-modified"] || "");
55258
55416
  });
55259
55417
  req2.on("error", reject);
55260
55418
  req2.on("timeout", () => {
@@ -55263,7 +55421,7 @@ var ProviderLoader = class _ProviderLoader {
55263
55421
  });
55264
55422
  req2.end();
55265
55423
  } else {
55266
- resolve25(res.headers.etag || res.headers["last-modified"] || "");
55424
+ resolve26(res.headers.etag || res.headers["last-modified"] || "");
55267
55425
  }
55268
55426
  });
55269
55427
  req.on("error", reject);
@@ -55282,36 +55440,36 @@ var ProviderLoader = class _ProviderLoader {
55282
55440
  const tmpTar = path36.join(os26.tmpdir(), `adhdev-providers-${Date.now()}.tar.gz`);
55283
55441
  const tmpExtract = path36.join(os26.tmpdir(), `adhdev-providers-extract-${Date.now()}`);
55284
55442
  await this.downloadFile(tarballTarget.url, tmpTar);
55285
- fs28.mkdirSync(tmpExtract, { recursive: true });
55443
+ fs29.mkdirSync(tmpExtract, { recursive: true });
55286
55444
  await execAsync5(`tar -xzf "${tmpTar}" -C "${tmpExtract}"`, { timeout: 3e4 });
55287
- const extracted = fs28.readdirSync(tmpExtract);
55445
+ const extracted = fs29.readdirSync(tmpExtract);
55288
55446
  const rootDir = extracted.find(
55289
- (d) => fs28.statSync(path36.join(tmpExtract, d)).isDirectory() && d.startsWith("adhdev-providers")
55447
+ (d) => fs29.statSync(path36.join(tmpExtract, d)).isDirectory() && d.startsWith("adhdev-providers")
55290
55448
  );
55291
55449
  if (!rootDir) throw new Error("Unexpected tarball structure");
55292
55450
  const sourceDir = path36.join(tmpExtract, rootDir);
55293
55451
  const backupDir = this.upstreamDir + ".bak";
55294
- if (fs28.existsSync(this.upstreamDir)) {
55295
- if (fs28.existsSync(backupDir)) fs28.rmSync(backupDir, { recursive: true, force: true });
55296
- fs28.renameSync(this.upstreamDir, backupDir);
55452
+ if (fs29.existsSync(this.upstreamDir)) {
55453
+ if (fs29.existsSync(backupDir)) fs29.rmSync(backupDir, { recursive: true, force: true });
55454
+ fs29.renameSync(this.upstreamDir, backupDir);
55297
55455
  }
55298
55456
  try {
55299
55457
  this.copyDirRecursive(sourceDir, this.upstreamDir);
55300
55458
  this.writeMeta(metaPath, etag || `ts-${Date.now()}`, Date.now());
55301
- if (fs28.existsSync(backupDir)) fs28.rmSync(backupDir, { recursive: true, force: true });
55459
+ if (fs29.existsSync(backupDir)) fs29.rmSync(backupDir, { recursive: true, force: true });
55302
55460
  } catch (e) {
55303
- if (fs28.existsSync(backupDir)) {
55304
- if (fs28.existsSync(this.upstreamDir)) fs28.rmSync(this.upstreamDir, { recursive: true, force: true });
55305
- fs28.renameSync(backupDir, this.upstreamDir);
55461
+ if (fs29.existsSync(backupDir)) {
55462
+ if (fs29.existsSync(this.upstreamDir)) fs29.rmSync(this.upstreamDir, { recursive: true, force: true });
55463
+ fs29.renameSync(backupDir, this.upstreamDir);
55306
55464
  }
55307
55465
  throw e;
55308
55466
  }
55309
55467
  try {
55310
- fs28.rmSync(tmpTar, { force: true });
55468
+ fs29.rmSync(tmpTar, { force: true });
55311
55469
  } catch {
55312
55470
  }
55313
55471
  try {
55314
- fs28.rmSync(tmpExtract, { recursive: true, force: true });
55472
+ fs29.rmSync(tmpExtract, { recursive: true, force: true });
55315
55473
  } catch {
55316
55474
  }
55317
55475
  const upstreamCount = this.countProviders(this.upstreamDir);
@@ -55327,7 +55485,7 @@ var ProviderLoader = class _ProviderLoader {
55327
55485
  downloadFile(url, destPath) {
55328
55486
  const https = __require("https");
55329
55487
  const http3 = __require("http");
55330
- return new Promise((resolve25, reject) => {
55488
+ return new Promise((resolve26, reject) => {
55331
55489
  const doRequest = (reqUrl, redirectCount = 0) => {
55332
55490
  if (redirectCount > 5) {
55333
55491
  reject(new Error("Too many redirects"));
@@ -55343,11 +55501,11 @@ var ProviderLoader = class _ProviderLoader {
55343
55501
  reject(new Error(`HTTP ${res.statusCode}`));
55344
55502
  return;
55345
55503
  }
55346
- const ws = fs28.createWriteStream(destPath);
55504
+ const ws = fs29.createWriteStream(destPath);
55347
55505
  res.pipe(ws);
55348
55506
  ws.on("finish", () => {
55349
55507
  ws.close();
55350
- resolve25();
55508
+ resolve26();
55351
55509
  });
55352
55510
  ws.on("error", reject);
55353
55511
  });
@@ -55362,22 +55520,22 @@ var ProviderLoader = class _ProviderLoader {
55362
55520
  }
55363
55521
  /** Recursive directory copy */
55364
55522
  copyDirRecursive(src, dest) {
55365
- fs28.mkdirSync(dest, { recursive: true });
55366
- for (const entry of fs28.readdirSync(src, { withFileTypes: true })) {
55523
+ fs29.mkdirSync(dest, { recursive: true });
55524
+ for (const entry of fs29.readdirSync(src, { withFileTypes: true })) {
55367
55525
  const srcPath = path36.join(src, entry.name);
55368
55526
  const destPath = path36.join(dest, entry.name);
55369
55527
  if (entry.isDirectory()) {
55370
55528
  this.copyDirRecursive(srcPath, destPath);
55371
55529
  } else {
55372
- fs28.copyFileSync(srcPath, destPath);
55530
+ fs29.copyFileSync(srcPath, destPath);
55373
55531
  }
55374
55532
  }
55375
55533
  }
55376
55534
  /** .meta.json save */
55377
55535
  writeMeta(metaPath, etag, timestamp) {
55378
55536
  try {
55379
- fs28.mkdirSync(path36.dirname(metaPath), { recursive: true });
55380
- fs28.writeFileSync(metaPath, JSON.stringify({
55537
+ fs29.mkdirSync(path36.dirname(metaPath), { recursive: true });
55538
+ fs29.writeFileSync(metaPath, JSON.stringify({
55381
55539
  etag,
55382
55540
  timestamp,
55383
55541
  lastCheck: new Date(timestamp).toISOString(),
@@ -55388,11 +55546,11 @@ var ProviderLoader = class _ProviderLoader {
55388
55546
  }
55389
55547
  /** Count provider files (provider.v1.json or provider.json — at most one per dir). */
55390
55548
  countProviders(dir) {
55391
- if (!fs28.existsSync(dir)) return 0;
55549
+ if (!fs29.existsSync(dir)) return 0;
55392
55550
  let count = 0;
55393
55551
  const scan = (d) => {
55394
55552
  try {
55395
- const entries = fs28.readdirSync(d, { withFileTypes: true });
55553
+ const entries = fs29.readdirSync(d, { withFileTypes: true });
55396
55554
  const hasManifest = entries.some((e) => e.name === "provider.v1.json" || e.name === "provider.json");
55397
55555
  if (hasManifest) count++;
55398
55556
  for (const entry of entries) {
@@ -55622,13 +55780,13 @@ var ProviderLoader = class _ProviderLoader {
55622
55780
  if (!provider) return null;
55623
55781
  const cat = provider.category;
55624
55782
  const searchRoots = this.getProviderRoots();
55625
- const hasManifest = (dir) => fs28.existsSync(path36.join(dir, "provider.v1.json")) || fs28.existsSync(path36.join(dir, "provider.json"));
55783
+ const hasManifest = (dir) => fs29.existsSync(path36.join(dir, "provider.v1.json")) || fs29.existsSync(path36.join(dir, "provider.json"));
55626
55784
  const readManifestType = (dir) => {
55627
55785
  for (const file of ["provider.v1.json", "provider.json"]) {
55628
55786
  const p = path36.join(dir, file);
55629
- if (!fs28.existsSync(p)) continue;
55787
+ if (!fs29.existsSync(p)) continue;
55630
55788
  try {
55631
- const data = JSON.parse(fs28.readFileSync(p, "utf-8"));
55789
+ const data = JSON.parse(fs29.readFileSync(p, "utf-8"));
55632
55790
  if (typeof data?.type === "string") return data.type;
55633
55791
  } catch {
55634
55792
  }
@@ -55636,13 +55794,13 @@ var ProviderLoader = class _ProviderLoader {
55636
55794
  return null;
55637
55795
  };
55638
55796
  for (const root of searchRoots) {
55639
- if (!fs28.existsSync(root)) continue;
55797
+ if (!fs29.existsSync(root)) continue;
55640
55798
  const candidate = this.getProviderDir(root, cat, type);
55641
55799
  if (hasManifest(candidate)) return candidate;
55642
55800
  const catDir = path36.join(root, cat);
55643
- if (fs28.existsSync(catDir)) {
55801
+ if (fs29.existsSync(catDir)) {
55644
55802
  try {
55645
- for (const entry of fs28.readdirSync(catDir, { withFileTypes: true })) {
55803
+ for (const entry of fs29.readdirSync(catDir, { withFileTypes: true })) {
55646
55804
  if (!entry.isDirectory()) continue;
55647
55805
  const entryDir = path36.join(catDir, entry.name);
55648
55806
  const manifestType = readManifestType(entryDir);
@@ -55661,7 +55819,7 @@ var ProviderLoader = class _ProviderLoader {
55661
55819
  */
55662
55820
  buildScriptWrappersFromDir(dir) {
55663
55821
  const scriptsJs = path36.join(dir, "scripts.js");
55664
- if (fs28.existsSync(scriptsJs)) {
55822
+ if (fs29.existsSync(scriptsJs)) {
55665
55823
  try {
55666
55824
  delete __require.cache[__require.resolve(scriptsJs)];
55667
55825
  return __require(scriptsJs);
@@ -55671,13 +55829,13 @@ var ProviderLoader = class _ProviderLoader {
55671
55829
  const toCamel = (name) => name.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
55672
55830
  const result = {};
55673
55831
  try {
55674
- for (const file of fs28.readdirSync(dir)) {
55832
+ for (const file of fs29.readdirSync(dir)) {
55675
55833
  if (!file.endsWith(".js")) continue;
55676
55834
  const scriptName = toCamel(file.replace(".js", ""));
55677
55835
  const filePath = path36.join(dir, file);
55678
55836
  result[scriptName] = (...args) => {
55679
55837
  try {
55680
- let content = fs28.readFileSync(filePath, "utf-8");
55838
+ let content = fs29.readFileSync(filePath, "utf-8");
55681
55839
  if (args[0] && typeof args[0] === "object") {
55682
55840
  for (const [key2, val] of Object.entries(args[0])) {
55683
55841
  let v = val;
@@ -55723,12 +55881,12 @@ var ProviderLoader = class _ProviderLoader {
55723
55881
  * Structure: dir/category/agent-name/provider.{json,js}
55724
55882
  */
55725
55883
  loadDir(dir, excludeDirs) {
55726
- if (!fs28.existsSync(dir)) return 0;
55884
+ if (!fs29.existsSync(dir)) return 0;
55727
55885
  let count = 0;
55728
55886
  const scan = (d) => {
55729
55887
  let entries;
55730
55888
  try {
55731
- entries = fs28.readdirSync(d, { withFileTypes: true });
55889
+ entries = fs29.readdirSync(d, { withFileTypes: true });
55732
55890
  } catch {
55733
55891
  return;
55734
55892
  }
@@ -55738,7 +55896,7 @@ var ProviderLoader = class _ProviderLoader {
55738
55896
  const manifestFile = hasV1 ? "provider.v1.json" : "provider.json";
55739
55897
  const jsonPath = path36.join(d, manifestFile);
55740
55898
  try {
55741
- const raw = fs28.readFileSync(jsonPath, "utf-8");
55899
+ const raw = fs29.readFileSync(jsonPath, "utf-8");
55742
55900
  const mod = JSON.parse(raw);
55743
55901
  if (hasV1 && mod?.category === "cli") {
55744
55902
  try {
@@ -55777,7 +55935,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
55777
55935
  } else {
55778
55936
  const hasCompatibility = Array.isArray(normalizedProvider.compatibility);
55779
55937
  const scriptsPath = path36.join(d, "scripts.js");
55780
- if (!hasCompatibility && fs28.existsSync(scriptsPath)) {
55938
+ if (!hasCompatibility && fs29.existsSync(scriptsPath)) {
55781
55939
  try {
55782
55940
  registerProviderScriptRootSafely(path36.dirname(path36.dirname(d)));
55783
55941
  delete __require.cache[__require.resolve(scriptsPath)];
@@ -55903,10 +56061,10 @@ function findMacAppProcessPids(psOutput, appPaths) {
55903
56061
 
55904
56062
  // src/launch.ts
55905
56063
  async function execQuiet(command, options = {}) {
55906
- return new Promise((resolve25) => {
56064
+ return new Promise((resolve26) => {
55907
56065
  exec4(command, options, (error, stdout) => {
55908
- if (error) return resolve25("");
55909
- resolve25(stdout.toString());
56066
+ if (error) return resolve26("");
56067
+ resolve26(stdout.toString());
55910
56068
  });
55911
56069
  });
55912
56070
  }
@@ -55987,17 +56145,17 @@ async function findFreePort(ports) {
55987
56145
  throw new Error("No free port found");
55988
56146
  }
55989
56147
  function checkPortFree(port) {
55990
- return new Promise((resolve25) => {
56148
+ return new Promise((resolve26) => {
55991
56149
  const server = net.createServer();
55992
56150
  server.unref();
55993
- server.on("error", () => resolve25(false));
56151
+ server.on("error", () => resolve26(false));
55994
56152
  server.listen(port, "127.0.0.1", () => {
55995
- server.close(() => resolve25(true));
56153
+ server.close(() => resolve26(true));
55996
56154
  });
55997
56155
  });
55998
56156
  }
55999
56157
  async function isCdpActive(port) {
56000
- return new Promise((resolve25) => {
56158
+ return new Promise((resolve26) => {
56001
56159
  const req = __require("http").get(`http://127.0.0.1:${port}/json/version`, {
56002
56160
  timeout: 2e3
56003
56161
  }, (res) => {
@@ -56006,16 +56164,16 @@ async function isCdpActive(port) {
56006
56164
  res.on("end", () => {
56007
56165
  try {
56008
56166
  const info = JSON.parse(data);
56009
- resolve25(!!info["WebKit-Version"] || !!info["Browser"]);
56167
+ resolve26(!!info["WebKit-Version"] || !!info["Browser"]);
56010
56168
  } catch {
56011
- resolve25(false);
56169
+ resolve26(false);
56012
56170
  }
56013
56171
  });
56014
56172
  });
56015
- req.on("error", () => resolve25(false));
56173
+ req.on("error", () => resolve26(false));
56016
56174
  req.on("timeout", () => {
56017
56175
  req.destroy();
56018
- resolve25(false);
56176
+ resolve26(false);
56019
56177
  });
56020
56178
  });
56021
56179
  }
@@ -56151,7 +56309,7 @@ async function detectCurrentWorkspace(ideId) {
56151
56309
  }
56152
56310
  } else if (plat === "win32") {
56153
56311
  try {
56154
- const fs42 = __require("fs");
56312
+ const fs43 = __require("fs");
56155
56313
  const appNameMap = getMacAppIdentifiers();
56156
56314
  const appName = appNameMap[ideId];
56157
56315
  if (appName) {
@@ -56160,8 +56318,8 @@ async function detectCurrentWorkspace(ideId) {
56160
56318
  appName,
56161
56319
  "storage.json"
56162
56320
  );
56163
- if (fs42.existsSync(storagePath)) {
56164
- const data = JSON.parse(fs42.readFileSync(storagePath, "utf-8"));
56321
+ if (fs43.existsSync(storagePath)) {
56322
+ const data = JSON.parse(fs43.readFileSync(storagePath, "utf-8"));
56165
56323
  const workspaces = data?.openedPathsList?.workspaces3 || data?.openedPathsList?.entries || [];
56166
56324
  if (workspaces.length > 0) {
56167
56325
  const recent = workspaces[0];
@@ -56681,7 +56839,7 @@ var meshCrudHandlers = {
56681
56839
  MESH_JSON_CONFIG_LOCATIONS: MESH_JSON_CONFIG_LOCATIONS2
56682
56840
  } = await Promise.resolve().then(() => (init_mesh_json_config(), mesh_json_config_exports));
56683
56841
  const { mkdirSync: mkdirSync22, writeFileSync: writeFileSync24 } = await import("fs");
56684
- const { dirname: dirname17, join: join52 } = await import("path");
56842
+ const { dirname: dirname18, join: join52 } = await import("path");
56685
56843
  const scaffold = buildMeshJsonConfigScaffold2(mesh);
56686
56844
  const scaffoldJson = serializeMeshJsonConfigScaffold2(scaffold);
56687
56845
  const relativePath = MESH_JSON_CONFIG_LOCATIONS2[0];
@@ -56721,7 +56879,7 @@ var meshCrudHandlers = {
56721
56879
  note: "Dry-run: nothing written. Re-run with write=true to persist to the repo (commit target). meshes.json is untouched."
56722
56880
  };
56723
56881
  }
56724
- mkdirSync22(dirname17(absolutePath), { recursive: true });
56882
+ mkdirSync22(dirname18(absolutePath), { recursive: true });
56725
56883
  writeFileSync24(absolutePath, `${scaffoldJson}
56726
56884
  `, "utf-8");
56727
56885
  return {
@@ -57260,7 +57418,7 @@ var meshCrudHandlers = {
57260
57418
  const setupPromise = finishWorktreeSetup();
57261
57419
  const setupResult = await Promise.race([
57262
57420
  setupPromise.then((value) => ({ completed: true, value })),
57263
- new Promise((resolve25) => setTimeout(() => resolve25({ completed: false }), setupWaitMs))
57421
+ new Promise((resolve26) => setTimeout(() => resolve26({ completed: false }), setupWaitMs))
57264
57422
  ]);
57265
57423
  const emitBootstrapEvent = (eventStatus2, bootstrapState2, startedAtMs, extraPayload) => {
57266
57424
  try {
@@ -57755,7 +57913,7 @@ init_worktree_bootstrap_config();
57755
57913
  init_change_impact_config();
57756
57914
  init_mesh_config();
57757
57915
  import { existsSync as existsSync39, mkdirSync as mkdirSync15, writeFileSync as writeFileSync18 } from "fs";
57758
- import { dirname as dirname11, join as join43 } from "path";
57916
+ import { dirname as dirname12, join as join43 } from "path";
57759
57917
  var MESH_INIT_REFINE_CONFIG_PATH = MESH_REFINE_CONFIG_LOCATIONS[0];
57760
57918
  var MESH_INIT_WORKTREE_BOOTSTRAP_CONFIG_PATH = MESH_WORKTREE_BOOTSTRAP_CONFIG_LOCATIONS[0];
57761
57919
  var MESH_INIT_CHANGE_IMPACT_CONFIG_PATH = CHANGE_IMPACT_CONFIG_LOCATIONS[0];
@@ -57771,7 +57929,7 @@ var CANDIDATE_STALE_INPUTS = [
57771
57929
  ];
57772
57930
  function writeConfigFile(workspace, relativePath, config) {
57773
57931
  const target = join43(workspace, relativePath);
57774
- mkdirSync15(dirname11(target), { recursive: true });
57932
+ mkdirSync15(dirname12(target), { recursive: true });
57775
57933
  writeFileSync18(target, `${JSON.stringify(config, null, 2)}
57776
57934
  `, "utf-8");
57777
57935
  return target;
@@ -58149,7 +58307,7 @@ init_runtime_surface();
58149
58307
  init_mesh_coordinator();
58150
58308
  init_dist();
58151
58309
  import { join as pathJoin } from "path";
58152
- import * as fs29 from "fs";
58310
+ import * as fs30 from "fs";
58153
58311
  var meshCoordinatorLaunchHandlers = {
58154
58312
  launch_mesh_coordinator: async (ctx, args) => {
58155
58313
  const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
@@ -58389,15 +58547,15 @@ ${ptyResult.output.slice(-2e3)}`);
58389
58547
  }
58390
58548
  if (cliType === "codex-cli") {
58391
58549
  const repoMcpConfigPath = pathJoin(workspace, ".mcp.json");
58392
- if (fs29.existsSync(repoMcpConfigPath)) {
58550
+ if (fs30.existsSync(repoMcpConfigPath)) {
58393
58551
  try {
58394
58552
  const repoMcpConfig = parseMeshCoordinatorMcpConfig(
58395
- fs29.readFileSync(repoMcpConfigPath, "utf-8"),
58553
+ fs30.readFileSync(repoMcpConfigPath, "utf-8"),
58396
58554
  "claude_mcp_json"
58397
58555
  );
58398
58556
  const existingServers2 = repoMcpConfig.mcpServers;
58399
58557
  if (existingServers2 && typeof existingServers2 === "object" && !Array.isArray(existingServers2) && existingServers2[coordinatorSetup.serverName]) {
58400
- fs29.writeFileSync(repoMcpConfigPath, serializeMeshCoordinatorMcpConfig({
58558
+ fs30.writeFileSync(repoMcpConfigPath, serializeMeshCoordinatorMcpConfig({
58401
58559
  ...repoMcpConfig,
58402
58560
  mcpServers: {
58403
58561
  ...existingServers2,
@@ -58516,7 +58674,7 @@ ${ptyResult.output.slice(-2e3)}`);
58516
58674
  };
58517
58675
  }
58518
58676
  const { existsSync: existsSync55, readFileSync: readFileSync42, writeFileSync: writeFileSync24, copyFileSync: copyFileSync4, mkdirSync: mkdirSync22 } = await import("fs");
58519
- const { dirname: dirname17 } = await import("path");
58677
+ const { dirname: dirname18 } = await import("path");
58520
58678
  const mcpConfigPath = coordinatorSetup.configPath;
58521
58679
  const hermesManualFallback = cliType === "hermes-cli" && configFormat === "hermes_config_yaml" ? createHermesManualMeshCoordinatorSetup(meshId, workspace) : null;
58522
58680
  let hermesBaseConfig = null;
@@ -58551,7 +58709,7 @@ ${ptyResult.output.slice(-2e3)}`);
58551
58709
  };
58552
58710
  }
58553
58711
  try {
58554
- mkdirSync22(dirname17(mcpConfigPath), { recursive: true });
58712
+ mkdirSync22(dirname18(mcpConfigPath), { recursive: true });
58555
58713
  } catch (error) {
58556
58714
  const message = `Could not prepare MCP config path for automatic setup: ${error?.message || error}`;
58557
58715
  LOG.error("MeshCoordinator", message);
@@ -58561,7 +58719,7 @@ ${ptyResult.output.slice(-2e3)}`);
58561
58719
  const hadExistingMcpConfig = existsSync55(mcpConfigPath);
58562
58720
  let existingMcpConfig = hermesBaseConfig?.config || {};
58563
58721
  if (hermesBaseConfig) {
58564
- copyHermesCoordinatorCredentialFiles(hermesBaseConfig.sourceHome, dirname17(mcpConfigPath));
58722
+ copyHermesCoordinatorCredentialFiles(hermesBaseConfig.sourceHome, dirname18(mcpConfigPath));
58565
58723
  }
58566
58724
  if (hadExistingMcpConfig) {
58567
58725
  try {
@@ -58599,7 +58757,7 @@ ${ptyResult.output.slice(-2e3)}`);
58599
58757
  const cliArgs = [];
58600
58758
  const launchEnv = {};
58601
58759
  if (configFormat === "hermes_config_yaml") {
58602
- launchEnv.HERMES_HOME = dirname17(mcpConfigPath);
58760
+ launchEnv.HERMES_HOME = dirname18(mcpConfigPath);
58603
58761
  launchEnv.HERMES_IGNORE_USER_CONFIG = "";
58604
58762
  }
58605
58763
  let autoImportContextFilePath;
@@ -58690,13 +58848,13 @@ init_dist();
58690
58848
  init_mesh_events();
58691
58849
  init_mesh_routing();
58692
58850
  init_mesh_host_ownership();
58693
- import * as fs30 from "fs";
58851
+ import * as fs31 from "fs";
58694
58852
  import { hostname as osHostname } from "os";
58695
58853
 
58696
58854
  // src/mesh/preview-freshness.ts
58697
58855
  import { execFileSync as execFileSync6 } from "child_process";
58698
58856
  import { existsSync as existsSync41, readFileSync as readFileSync31 } from "fs";
58699
- import { resolve as resolve19 } from "path";
58857
+ import { resolve as resolve20 } from "path";
58700
58858
  var PREVIEW_DEPLOY_RECORD = ".adhdev/preview-deploy.json";
58701
58859
  var PREVIEW_PIPELINE_SCRIPTS = [
58702
58860
  "scripts/preview-freshness.mjs",
@@ -58704,7 +58862,7 @@ var PREVIEW_PIPELINE_SCRIPTS = [
58704
58862
  "scripts/deploy-preview-local.mjs"
58705
58863
  ];
58706
58864
  function hasDeployPreviewNpmScript(repoRoot) {
58707
- const pkgPath = resolve19(repoRoot, "package.json");
58865
+ const pkgPath = resolve20(repoRoot, "package.json");
58708
58866
  if (!existsSync41(pkgPath)) return false;
58709
58867
  try {
58710
58868
  const pkg = JSON.parse(readFileSync31(pkgPath, "utf8"));
@@ -58714,8 +58872,8 @@ function hasDeployPreviewNpmScript(repoRoot) {
58714
58872
  }
58715
58873
  }
58716
58874
  function isPreviewPipelineConfigured(repoRoot) {
58717
- if (existsSync41(resolve19(repoRoot, PREVIEW_DEPLOY_RECORD))) return true;
58718
- if (PREVIEW_PIPELINE_SCRIPTS.some((rel) => existsSync41(resolve19(repoRoot, rel)))) return true;
58875
+ if (existsSync41(resolve20(repoRoot, PREVIEW_DEPLOY_RECORD))) return true;
58876
+ if (PREVIEW_PIPELINE_SCRIPTS.some((rel) => existsSync41(resolve20(repoRoot, rel)))) return true;
58719
58877
  return hasDeployPreviewNpmScript(repoRoot);
58720
58878
  }
58721
58879
  function runGit2(repoRoot, args) {
@@ -58731,7 +58889,7 @@ function runGit2(repoRoot, args) {
58731
58889
  }
58732
58890
  }
58733
58891
  function readRecord6(repoRoot) {
58734
- const path45 = resolve19(repoRoot, PREVIEW_DEPLOY_RECORD);
58892
+ const path45 = resolve20(repoRoot, PREVIEW_DEPLOY_RECORD);
58735
58893
  if (!existsSync41(path45)) return null;
58736
58894
  try {
58737
58895
  const parsed = JSON.parse(readFileSync31(path45, "utf8"));
@@ -59051,7 +59209,7 @@ var meshStatusHandlers = {
59051
59209
  }
59052
59210
  }
59053
59211
  if (workspace) {
59054
- if (!fs30.existsSync(workspace)) {
59212
+ if (!fs31.existsSync(workspace)) {
59055
59213
  const inlineTransitGit = buildInlineMeshTransitGitStatus(node);
59056
59214
  let remoteProbeApplied = false;
59057
59215
  if (inlineTransitGit) {
@@ -59187,7 +59345,7 @@ var meshStatusHandlers = {
59187
59345
  backstop: { ...getMeshV2BackstopCounters() }
59188
59346
  };
59189
59347
  const previewFreshness = (() => {
59190
- const localRepoRoot = nodeStatuses.map((node) => readStringValue(node?.git?.repoRoot, node?.repoRoot, node?.workspace)).find((candidate) => !!candidate && fs30.existsSync(candidate));
59348
+ const localRepoRoot = nodeStatuses.map((node) => readStringValue(node?.git?.repoRoot, node?.repoRoot, node?.workspace)).find((candidate) => !!candidate && fs31.existsSync(candidate));
59191
59349
  return localRepoRoot ? buildPreviewFreshness(localRepoRoot) : void 0;
59192
59350
  })();
59193
59351
  const asyncRefineJobs = buildMeshAsyncRefineJobs({
@@ -59387,7 +59545,7 @@ init_dist();
59387
59545
  init_logger();
59388
59546
 
59389
59547
  // src/logging/command-log.ts
59390
- import * as fs31 from "fs";
59548
+ import * as fs32 from "fs";
59391
59549
  import * as path38 from "path";
59392
59550
  import * as os28 from "os";
59393
59551
  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");
@@ -59395,7 +59553,7 @@ var LOG_DIR2 = path38.join(ADHDEV_HOME2, "logs");
59395
59553
  var MAX_FILE_SIZE = 5 * 1024 * 1024;
59396
59554
  var MAX_DAYS = 7;
59397
59555
  try {
59398
- fs31.mkdirSync(LOG_DIR2, { recursive: true });
59556
+ fs32.mkdirSync(LOG_DIR2, { recursive: true });
59399
59557
  } catch {
59400
59558
  }
59401
59559
  var SENSITIVE_KEYS = /* @__PURE__ */ new Set([
@@ -59441,7 +59599,7 @@ function checkRotation() {
59441
59599
  }
59442
59600
  function cleanOldFiles() {
59443
59601
  try {
59444
- const files = fs31.readdirSync(LOG_DIR2).filter((f) => f.startsWith("commands-") && f.endsWith(".jsonl"));
59602
+ const files = fs32.readdirSync(LOG_DIR2).filter((f) => f.startsWith("commands-") && f.endsWith(".jsonl"));
59445
59603
  const cutoff = /* @__PURE__ */ new Date();
59446
59604
  cutoff.setDate(cutoff.getDate() - MAX_DAYS);
59447
59605
  const cutoffStr = cutoff.toISOString().slice(0, 10);
@@ -59449,7 +59607,7 @@ function cleanOldFiles() {
59449
59607
  const dateMatch = file.match(/commands-(\d{4}-\d{2}-\d{2})/);
59450
59608
  if (dateMatch && dateMatch[1] < cutoffStr) {
59451
59609
  try {
59452
- fs31.unlinkSync(path38.join(LOG_DIR2, file));
59610
+ fs32.unlinkSync(path38.join(LOG_DIR2, file));
59453
59611
  } catch {
59454
59612
  }
59455
59613
  }
@@ -59459,14 +59617,14 @@ function cleanOldFiles() {
59459
59617
  }
59460
59618
  function checkSize() {
59461
59619
  try {
59462
- const stat2 = fs31.statSync(currentFile);
59620
+ const stat2 = fs32.statSync(currentFile);
59463
59621
  if (stat2.size > MAX_FILE_SIZE) {
59464
59622
  const backup = currentFile.replace(".jsonl", ".1.jsonl");
59465
59623
  try {
59466
- fs31.unlinkSync(backup);
59624
+ fs32.unlinkSync(backup);
59467
59625
  } catch {
59468
59626
  }
59469
- fs31.renameSync(currentFile, backup);
59627
+ fs32.renameSync(currentFile, backup);
59470
59628
  }
59471
59629
  } catch {
59472
59630
  }
@@ -59499,14 +59657,14 @@ function logCommand(entry) {
59499
59657
  ...entry.error ? { err: entry.error } : {},
59500
59658
  ...entry.durationMs !== void 0 ? { ms: entry.durationMs } : {}
59501
59659
  });
59502
- fs31.appendFileSync(currentFile, line + "\n");
59660
+ fs32.appendFileSync(currentFile, line + "\n");
59503
59661
  } catch {
59504
59662
  }
59505
59663
  }
59506
59664
  function getRecentCommands(count = 50) {
59507
59665
  try {
59508
- if (!fs31.existsSync(currentFile)) return [];
59509
- const content = fs31.readFileSync(currentFile, "utf-8");
59666
+ if (!fs32.existsSync(currentFile)) return [];
59667
+ const content = fs32.readFileSync(currentFile, "utf-8");
59510
59668
  const lines = content.trim().split("\n").filter(Boolean);
59511
59669
  return lines.slice(-count).map((line) => {
59512
59670
  try {
@@ -59535,7 +59693,7 @@ cleanOldFiles();
59535
59693
  init_debug_trace();
59536
59694
  init_mesh_host_ownership();
59537
59695
  init_mesh_node_identity();
59538
- import * as fs35 from "fs";
59696
+ import * as fs36 from "fs";
59539
59697
 
59540
59698
  // src/commands/router-refine.ts
59541
59699
  init_logger();
@@ -59646,7 +59804,7 @@ init_refine_config();
59646
59804
  init_worktree_bootstrap_config();
59647
59805
  init_resolve_executable();
59648
59806
  import { basename as pathBasename, join as pathJoin2, resolve as pathResolve2 } from "path";
59649
- import * as fs32 from "fs";
59807
+ import * as fs33 from "fs";
59650
59808
  import { execFileSync as execFileSync7 } from "child_process";
59651
59809
  var GIT2 = process.platform === "win32" ? resolveWin32Executable("git") : "git";
59652
59810
  var REFINE_VALIDATION_TIMEOUT_MS = 12e4;
@@ -60004,7 +60162,7 @@ function isSubmoduleFastForward(submoduleRepoPath, baseCommit, branchCommit) {
60004
60162
  if (!baseCommit || !branchCommit) return false;
60005
60163
  if (baseCommit === branchCommit) return true;
60006
60164
  try {
60007
- if (!fs32.existsSync(submoduleRepoPath)) return false;
60165
+ if (!fs33.existsSync(submoduleRepoPath)) return false;
60008
60166
  execFileSync7(GIT2, ["cat-file", "-e", `${baseCommit}^{commit}`], { cwd: submoduleRepoPath, stdio: "ignore" });
60009
60167
  execFileSync7(GIT2, ["cat-file", "-e", `${branchCommit}^{commit}`], { cwd: submoduleRepoPath, stdio: "ignore" });
60010
60168
  execFileSync7(GIT2, ["merge-base", "--is-ancestor", baseCommit, branchCommit], { cwd: submoduleRepoPath, stdio: "ignore" });
@@ -60121,7 +60279,7 @@ function buildTreeWithGitlinksEqualized(repoRoot, commitish, paths, placeholderC
60121
60279
  return newTree || void 0;
60122
60280
  } finally {
60123
60281
  try {
60124
- fs32.rmSync(tmpIndex, { force: true });
60282
+ fs33.rmSync(tmpIndex, { force: true });
60125
60283
  } catch {
60126
60284
  }
60127
60285
  }
@@ -60196,7 +60354,7 @@ function synthesizeTrivialFastForwardMergeTree(repoRoot, baseHead, branchHead, g
60196
60354
  return newTree || void 0;
60197
60355
  } finally {
60198
60356
  try {
60199
- fs32.rmSync(tmpIndex, { force: true });
60357
+ fs33.rmSync(tmpIndex, { force: true });
60200
60358
  } catch {
60201
60359
  }
60202
60360
  }
@@ -60308,7 +60466,7 @@ async function runMeshRefineSubmoduleReachabilityGate(repoRoot, mergedTree, opti
60308
60466
  return { stdout: String(stdout || ""), stderr: String(stderr || ""), refspec };
60309
60467
  };
60310
60468
  const importCommitFromWorktreeSubmodule = async (submodulePath, worktreeSubmodulePath, commit) => {
60311
- if (!fs32.existsSync(worktreeSubmodulePath)) return false;
60469
+ if (!fs33.existsSync(worktreeSubmodulePath)) return false;
60312
60470
  try {
60313
60471
  await runGit3(worktreeSubmodulePath, ["cat-file", "-e", `${commit}^{commit}`]);
60314
60472
  } catch {
@@ -60332,7 +60490,7 @@ async function runMeshRefineSubmoduleReachabilityGate(repoRoot, mergedTree, opti
60332
60490
  };
60333
60491
  let submoduleDefaultBranch = "main";
60334
60492
  try {
60335
- if (!fs32.existsSync(submodulePath)) {
60493
+ if (!fs33.existsSync(submodulePath)) {
60336
60494
  entry.error = `Submodule checkout missing at ${gitlink.path}`;
60337
60495
  entry.publishRequired = true;
60338
60496
  if (options.allowAutoPublishSubmoduleMainCommits === true) {
@@ -60577,9 +60735,9 @@ async function runMeshRefineValidationGate(mesh, workspace, opts) {
60577
60735
  return ["npm", "pnpm", "yarn", "bun"].includes(command) && candidate.args.some((arg) => arg === "run" || arg === "test" || arg === "exec");
60578
60736
  };
60579
60737
  const dependenciesLikelyMissing = (cwd) => {
60580
- if (!fs32.existsSync(pathJoin2(cwd, "package.json"))) return false;
60581
- if (fs32.existsSync(pathJoin2(cwd, "node_modules"))) return false;
60582
- return ["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "bun.lock"].some((lock) => fs32.existsSync(pathJoin2(cwd, lock)));
60738
+ if (!fs33.existsSync(pathJoin2(cwd, "package.json"))) return false;
60739
+ if (fs33.existsSync(pathJoin2(cwd, "node_modules"))) return false;
60740
+ return ["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "bun.lock"].some((lock) => fs33.existsSync(pathJoin2(cwd, lock)));
60583
60741
  };
60584
60742
  const needsNodeModules = (candidate, cwd) => isPackageManagerValidation(candidate) && dependenciesLikelyMissing(cwd);
60585
60743
  const isDaemonScopedCommand = (candidate) => {
@@ -62478,7 +62636,7 @@ async function startMeshRefineJob(self, meshId, nodeId, args) {
62478
62636
  init_logger();
62479
62637
  init_dist();
62480
62638
  init_mesh_node_identity();
62481
- import * as fs33 from "fs";
62639
+ import * as fs34 from "fs";
62482
62640
  import { resolve as pathResolve3 } from "path";
62483
62641
  init_runtime_surface();
62484
62642
  init_repo_mesh_types();
@@ -62492,14 +62650,14 @@ function sessionMatchesMeshNode(self, record, node, nodeId, sessionIds) {
62492
62650
  return false;
62493
62651
  }
62494
62652
  async function bestEffortRemoveWorktreeDir(self, dir) {
62495
- if (!dir || !fs33.existsSync(dir)) return { removed: true, residue: false };
62496
- const sleep3 = (ms) => new Promise((resolve25) => setTimeout(resolve25, ms));
62653
+ if (!dir || !fs34.existsSync(dir)) return { removed: true, residue: false };
62654
+ const sleep3 = (ms) => new Promise((resolve26) => setTimeout(resolve26, ms));
62497
62655
  const ABSORB = /* @__PURE__ */ new Set(["EINVAL", "EPERM", "EBUSY", "ENOTEMPTY", "EACCES", "EMFILE", "ENFILE"]);
62498
62656
  let lastErr;
62499
62657
  for (let attempt = 0; attempt < 4; attempt++) {
62500
62658
  try {
62501
- fs33.rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
62502
- if (!fs33.existsSync(dir)) return { removed: true, residue: false };
62659
+ fs34.rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
62660
+ if (!fs34.existsSync(dir)) return { removed: true, residue: false };
62503
62661
  lastErr = new Error("directory still present after rmSync");
62504
62662
  } catch (e) {
62505
62663
  lastErr = e;
@@ -62510,7 +62668,7 @@ async function bestEffortRemoveWorktreeDir(self, dir) {
62510
62668
  }
62511
62669
  await sleep3(150 * (attempt + 1));
62512
62670
  }
62513
- return fs33.existsSync(dir) ? { removed: false, residue: true, error: String(lastErr?.message || lastErr || "unknown rm error") } : { removed: true, residue: false };
62671
+ return fs34.existsSync(dir) ? { removed: false, residue: true, error: String(lastErr?.message || lastErr || "unknown rm error") } : { removed: true, residue: false };
62514
62672
  }
62515
62673
  async function precheckLocalWorktreeRemovable(self, args) {
62516
62674
  const sessionPreservedNote = " The delegated session was left running (not stopped) \u2014 resolve the issue and retry mesh_remove_node.";
@@ -62523,10 +62681,10 @@ async function precheckLocalWorktreeRemovable(self, args) {
62523
62681
  recoveryHint: "Inspect the mesh node record before removing it, or remove stale metadata manually only after confirming no managed worktree remains." + sessionPreservedNote
62524
62682
  };
62525
62683
  }
62526
- if (!fs33.existsSync(workspace)) return { ok: true };
62684
+ if (!fs34.existsSync(workspace)) return { ok: true };
62527
62685
  const sourceNode = args.node?.clonedFromNodeId ? args.mesh?.nodes?.find((n) => meshNodeIdMatches(n, args.node.clonedFromNodeId)) : args.mesh?.nodes?.find((n) => !n.isLocalWorktree);
62528
62686
  const repoRoot = typeof sourceNode?.repoRoot === "string" && sourceNode.repoRoot.trim() ? sourceNode.repoRoot.trim() : typeof sourceNode?.workspace === "string" && sourceNode.workspace.trim() ? sourceNode.workspace.trim() : "";
62529
- if (!repoRoot || !fs33.existsSync(repoRoot)) {
62687
+ if (!repoRoot || !fs34.existsSync(repoRoot)) {
62530
62688
  return {
62531
62689
  ok: false,
62532
62690
  code: "mesh_worktree_cleanup_missing_source_repo",
@@ -62546,7 +62704,7 @@ async function precheckLocalWorktreeRemovable(self, args) {
62546
62704
  const normalizePath = (value) => {
62547
62705
  const resolved = pathResolve3(value);
62548
62706
  try {
62549
- return fs33.realpathSync(resolved);
62707
+ return fs34.realpathSync(resolved);
62550
62708
  } catch {
62551
62709
  return resolved;
62552
62710
  }
@@ -62608,13 +62766,13 @@ async function cleanupLocalWorktreeNode(self, args) {
62608
62766
  recoveryHint: "Inspect the mesh node record before removing it, or remove stale metadata manually only after confirming no managed worktree remains."
62609
62767
  };
62610
62768
  }
62611
- const worktreeExists = fs33.existsSync(workspace);
62769
+ const worktreeExists = fs34.existsSync(workspace);
62612
62770
  const sourceNode = args.node?.clonedFromNodeId ? args.mesh?.nodes?.find((n) => meshNodeIdMatches(n, args.node.clonedFromNodeId)) : args.mesh?.nodes?.find((n) => !n.isLocalWorktree);
62613
62771
  const repoRoot = typeof sourceNode?.repoRoot === "string" && sourceNode.repoRoot.trim() ? sourceNode.repoRoot.trim() : typeof sourceNode?.workspace === "string" && sourceNode.workspace.trim() ? sourceNode.workspace.trim() : "";
62614
62772
  if (!worktreeExists) {
62615
62773
  return { success: true, skipped: true, removedPath: workspace, repoRoot: repoRoot || void 0, reason: "worktree_path_missing" };
62616
62774
  }
62617
- if (!repoRoot || !fs33.existsSync(repoRoot)) {
62775
+ if (!repoRoot || !fs34.existsSync(repoRoot)) {
62618
62776
  return {
62619
62777
  success: false,
62620
62778
  code: "mesh_worktree_cleanup_missing_source_repo",
@@ -62634,7 +62792,7 @@ async function cleanupLocalWorktreeNode(self, args) {
62634
62792
  const normalizePath = (value) => {
62635
62793
  const resolved = pathResolve3(value);
62636
62794
  try {
62637
- return fs33.realpathSync(resolved);
62795
+ return fs34.realpathSync(resolved);
62638
62796
  } catch {
62639
62797
  return resolved;
62640
62798
  }
@@ -63273,7 +63431,7 @@ init_logger();
63273
63431
  import * as yaml5 from "js-yaml";
63274
63432
  import { homedir as homedir26 } from "os";
63275
63433
  import { join as pathJoin3, resolve as pathResolve4 } from "path";
63276
- import * as fs34 from "fs";
63434
+ import * as fs35 from "fs";
63277
63435
  function loadYamlModule() {
63278
63436
  return yaml5;
63279
63437
  }
@@ -63297,9 +63455,9 @@ function resolveHermesUserHome() {
63297
63455
  function loadHermesCoordinatorBaseConfig(targetConfigPath) {
63298
63456
  const sourceHome = resolveHermesUserHome();
63299
63457
  const sourceConfigPath = pathJoin3(sourceHome, "config.yaml");
63300
- if (!fs34.existsSync(sourceConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
63458
+ if (!fs35.existsSync(sourceConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
63301
63459
  if (pathResolve4(sourceConfigPath) === pathResolve4(targetConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
63302
- const parsed = parseMeshCoordinatorMcpConfig(fs34.readFileSync(sourceConfigPath, "utf-8"), "hermes_config_yaml");
63460
+ const parsed = parseMeshCoordinatorMcpConfig(fs35.readFileSync(sourceConfigPath, "utf-8"), "hermes_config_yaml");
63303
63461
  const { mcp_servers: _mcpServers, ...baseConfig } = parsed;
63304
63462
  return { config: baseConfig, sourceHome, sourceConfigPath };
63305
63463
  }
@@ -63336,9 +63494,9 @@ function copyHermesCoordinatorCredentialFiles(sourceHome, targetHome) {
63336
63494
  for (const fileName of [".env", "auth.json"]) {
63337
63495
  const sourcePath = pathJoin3(sourceHome, fileName);
63338
63496
  const targetPath = pathJoin3(targetHome, fileName);
63339
- if (!fs34.existsSync(sourcePath)) continue;
63497
+ if (!fs35.existsSync(sourcePath)) continue;
63340
63498
  try {
63341
- fs34.copyFileSync(sourcePath, targetPath);
63499
+ fs35.copyFileSync(sourcePath, targetPath);
63342
63500
  } catch (error) {
63343
63501
  LOG.warn("MeshCoordinator", `Could not copy Hermes ${fileName} into isolated coordinator home: ${error?.message || error}`);
63344
63502
  }
@@ -63739,7 +63897,7 @@ var DaemonCommandRouter = class {
63739
63897
  const nodeId = readInlineMeshNodeId(node);
63740
63898
  if (!nodeId || !tombstones.has(nodeId)) return true;
63741
63899
  const workspace = readStringValue(node?.workspace);
63742
- if (workspace && fs35.existsSync(workspace)) {
63900
+ if (workspace && fs36.existsSync(workspace)) {
63743
63901
  tombstones.delete(nodeId);
63744
63902
  return true;
63745
63903
  }
@@ -64552,7 +64710,7 @@ var ProviderStreamAdapter = class {
64552
64710
  const beforeCount = this.messageCount(before);
64553
64711
  const beforeSignature = this.lastMessageSignature(before);
64554
64712
  for (let attempt = 0; attempt < 12; attempt += 1) {
64555
- await new Promise((resolve25) => setTimeout(resolve25, 250));
64713
+ await new Promise((resolve26) => setTimeout(resolve26, 250));
64556
64714
  let state;
64557
64715
  try {
64558
64716
  state = await this.readChat(evaluate);
@@ -64574,7 +64732,7 @@ var ProviderStreamAdapter = class {
64574
64732
  if (this.messageCount(first) > 0 || this.lastMessageSignature(first)) {
64575
64733
  return first;
64576
64734
  }
64577
- await new Promise((resolve25) => setTimeout(resolve25, 150));
64735
+ await new Promise((resolve26) => setTimeout(resolve26, 150));
64578
64736
  const second = await this.readChat(evaluate);
64579
64737
  return this.messageCount(second) >= this.messageCount(first) ? second : first;
64580
64738
  }
@@ -64725,7 +64883,7 @@ var ProviderStreamAdapter = class {
64725
64883
  if (typeof data.error === "string" && data.error.trim()) return false;
64726
64884
  }
64727
64885
  for (let attempt = 0; attempt < 6; attempt += 1) {
64728
- await new Promise((resolve25) => setTimeout(resolve25, 250));
64886
+ await new Promise((resolve26) => setTimeout(resolve26, 250));
64729
64887
  const state = await this.readChat(evaluate);
64730
64888
  const title = this.getStateTitle(state);
64731
64889
  if (this.titlesMatch(title, sessionId)) return true;
@@ -65658,7 +65816,7 @@ init_io_contracts();
65658
65816
  init_chat_message_normalization();
65659
65817
 
65660
65818
  // src/providers/version-archive.ts
65661
- import * as fs36 from "fs";
65819
+ import * as fs37 from "fs";
65662
65820
  import * as path39 from "path";
65663
65821
  import * as os29 from "os";
65664
65822
  import { platform as platform8 } from "os";
@@ -65672,8 +65830,8 @@ var VersionArchive = class {
65672
65830
  }
65673
65831
  load() {
65674
65832
  try {
65675
- if (fs36.existsSync(ARCHIVE_PATH)) {
65676
- this.history = JSON.parse(fs36.readFileSync(ARCHIVE_PATH, "utf-8"));
65833
+ if (fs37.existsSync(ARCHIVE_PATH)) {
65834
+ this.history = JSON.parse(fs37.readFileSync(ARCHIVE_PATH, "utf-8"));
65677
65835
  }
65678
65836
  } catch {
65679
65837
  this.history = {};
@@ -65710,20 +65868,20 @@ var VersionArchive = class {
65710
65868
  }
65711
65869
  save() {
65712
65870
  try {
65713
- fs36.mkdirSync(path39.dirname(ARCHIVE_PATH), { recursive: true });
65714
- fs36.writeFileSync(ARCHIVE_PATH, JSON.stringify(this.history, null, 2));
65871
+ fs37.mkdirSync(path39.dirname(ARCHIVE_PATH), { recursive: true });
65872
+ fs37.writeFileSync(ARCHIVE_PATH, JSON.stringify(this.history, null, 2));
65715
65873
  } catch {
65716
65874
  }
65717
65875
  }
65718
65876
  };
65719
65877
  async function runCommand(cmd, timeout = 1e4) {
65720
- return new Promise((resolve25) => {
65878
+ return new Promise((resolve26) => {
65721
65879
  exec5(cmd, {
65722
65880
  encoding: "utf-8",
65723
65881
  timeout
65724
65882
  }, (error, stdout) => {
65725
- if (error) return resolve25(null);
65726
- resolve25(stdout.trim());
65883
+ if (error) return resolve26(null);
65884
+ resolve26(stdout.trim());
65727
65885
  });
65728
65886
  });
65729
65887
  }
@@ -65736,8 +65894,8 @@ function findBinary2(name) {
65736
65894
  for (const ext of exes) {
65737
65895
  const fullPath = path39.join(p, name + ext);
65738
65896
  try {
65739
- if (fs36.existsSync(fullPath)) {
65740
- const stat2 = fs36.statSync(fullPath);
65897
+ if (fs37.existsSync(fullPath)) {
65898
+ const stat2 = fs37.statSync(fullPath);
65741
65899
  if (stat2.isFile() && (isWin || stat2.mode & 73)) {
65742
65900
  return fullPath;
65743
65901
  }
@@ -65784,9 +65942,9 @@ function checkPathExists2(paths) {
65784
65942
  if (p.includes("*")) {
65785
65943
  const home = os29.homedir();
65786
65944
  const resolved = p.replace(/\*/g, home.split(path39.sep).pop() || "");
65787
- if (fs36.existsSync(resolved)) return resolved;
65945
+ if (fs37.existsSync(resolved)) return resolved;
65788
65946
  } else {
65789
- if (fs36.existsSync(p)) return p;
65947
+ if (fs37.existsSync(p)) return p;
65790
65948
  }
65791
65949
  }
65792
65950
  return null;
@@ -65794,7 +65952,7 @@ function checkPathExists2(paths) {
65794
65952
  async function getMacAppVersion(appPath) {
65795
65953
  if (platform8() !== "darwin" || !appPath.endsWith(".app")) return null;
65796
65954
  const plistPath = path39.join(appPath, "Contents", "Info.plist");
65797
- if (!fs36.existsSync(plistPath)) return null;
65955
+ if (!fs37.existsSync(plistPath)) return null;
65798
65956
  const raw = await runCommand(`/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "${plistPath}"`);
65799
65957
  return raw || null;
65800
65958
  }
@@ -65821,7 +65979,7 @@ async function detectAllVersions(loader, archive) {
65821
65979
  let resolvedBin = cliBin;
65822
65980
  if (!resolvedBin && appPath && currentOs === "darwin") {
65823
65981
  const bundled = path39.join(appPath, "Contents", "Resources", "app", "bin", provider.cli || "");
65824
- if (provider.cli && fs36.existsSync(bundled)) resolvedBin = bundled;
65982
+ if (provider.cli && fs37.existsSync(bundled)) resolvedBin = bundled;
65825
65983
  }
65826
65984
  info.installed = !!(appPath || resolvedBin);
65827
65985
  info.path = appPath || null;
@@ -65869,7 +66027,7 @@ async function detectAllVersions(loader, archive) {
65869
66027
 
65870
66028
  // src/daemon/dev-server.ts
65871
66029
  import * as http2 from "http";
65872
- import * as fs40 from "fs";
66030
+ import * as fs41 from "fs";
65873
66031
  import * as path43 from "path";
65874
66032
  init_config();
65875
66033
 
@@ -66222,7 +66380,7 @@ init_builders();
66222
66380
 
66223
66381
  // src/daemon/dev-cdp-handlers.ts
66224
66382
  init_logger();
66225
- import * as fs37 from "fs";
66383
+ import * as fs38 from "fs";
66226
66384
  import * as path40 from "path";
66227
66385
  async function handleCdpEvaluate(ctx, req, res) {
66228
66386
  const body = await ctx.readBody(req);
@@ -66402,17 +66560,17 @@ async function handleScriptHints(ctx, type, _req, res) {
66402
66560
  }
66403
66561
  let scriptsPath = "";
66404
66562
  const directScripts = path40.join(dir, "scripts.js");
66405
- if (fs37.existsSync(directScripts)) {
66563
+ if (fs38.existsSync(directScripts)) {
66406
66564
  scriptsPath = directScripts;
66407
66565
  } else {
66408
66566
  const scriptsDir = path40.join(dir, "scripts");
66409
- if (fs37.existsSync(scriptsDir)) {
66410
- const versions = fs37.readdirSync(scriptsDir).filter((d) => {
66411
- return fs37.statSync(path40.join(scriptsDir, d)).isDirectory();
66567
+ if (fs38.existsSync(scriptsDir)) {
66568
+ const versions = fs38.readdirSync(scriptsDir).filter((d) => {
66569
+ return fs38.statSync(path40.join(scriptsDir, d)).isDirectory();
66412
66570
  }).sort().reverse();
66413
66571
  for (const ver of versions) {
66414
66572
  const p = path40.join(scriptsDir, ver, "scripts.js");
66415
- if (fs37.existsSync(p)) {
66573
+ if (fs38.existsSync(p)) {
66416
66574
  scriptsPath = p;
66417
66575
  break;
66418
66576
  }
@@ -66424,7 +66582,7 @@ async function handleScriptHints(ctx, type, _req, res) {
66424
66582
  return;
66425
66583
  }
66426
66584
  try {
66427
- const source = fs37.readFileSync(scriptsPath, "utf-8");
66585
+ const source = fs38.readFileSync(scriptsPath, "utf-8");
66428
66586
  const hints = {};
66429
66587
  const funcRegex = /module\.exports\.(\w+)\s*=\s*function\s+\w+\s*\(params\)/g;
66430
66588
  let match;
@@ -67239,7 +67397,7 @@ async function handleDomContext(ctx, type, req, res) {
67239
67397
  }
67240
67398
 
67241
67399
  // src/daemon/dev-cli-debug.ts
67242
- import * as fs38 from "fs";
67400
+ import * as fs39 from "fs";
67243
67401
  import * as path41 from "path";
67244
67402
  function slugifyFixtureName(value) {
67245
67403
  const normalized = String(value || "").trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
@@ -67255,10 +67413,10 @@ function getCliFixtureDir(ctx, type) {
67255
67413
  function readCliFixture(ctx, type, name) {
67256
67414
  const fixtureDir = getCliFixtureDir(ctx, type);
67257
67415
  const filePath = path41.join(fixtureDir, `${name}.json`);
67258
- if (!fs38.existsSync(filePath)) {
67416
+ if (!fs39.existsSync(filePath)) {
67259
67417
  throw new Error(`Fixture not found: ${filePath}`);
67260
67418
  }
67261
- return JSON.parse(fs38.readFileSync(filePath, "utf-8"));
67419
+ return JSON.parse(fs39.readFileSync(filePath, "utf-8"));
67262
67420
  }
67263
67421
  function getExerciseTranscriptText(result) {
67264
67422
  const parts = [];
@@ -67423,7 +67581,7 @@ function getCliTargetBundle(ctx, type, instanceId) {
67423
67581
  return { target, instance, adapter };
67424
67582
  }
67425
67583
  function sleep2(ms) {
67426
- return new Promise((resolve25) => setTimeout(resolve25, ms));
67584
+ return new Promise((resolve26) => setTimeout(resolve26, ms));
67427
67585
  }
67428
67586
  async function waitForCliReady(ctx, type, instanceId, timeoutMs) {
67429
67587
  const startedAt = Date.now();
@@ -68003,7 +68161,7 @@ async function handleCliFixtureCapture(ctx, req, res) {
68003
68161
  return;
68004
68162
  }
68005
68163
  const fixtureDir = getCliFixtureDir(ctx, type);
68006
- fs38.mkdirSync(fixtureDir, { recursive: true });
68164
+ fs39.mkdirSync(fixtureDir, { recursive: true });
68007
68165
  const name = slugifyFixtureName(String(body?.name || `${type}-${Date.now()}`));
68008
68166
  const result = await runCliExerciseInternal(ctx, { ...request, type });
68009
68167
  const fixture = {
@@ -68031,7 +68189,7 @@ async function handleCliFixtureCapture(ctx, req, res) {
68031
68189
  notes: typeof body?.notes === "string" ? body.notes : void 0
68032
68190
  };
68033
68191
  const filePath = path41.join(fixtureDir, `${name}.json`);
68034
- fs38.writeFileSync(filePath, JSON.stringify(fixture, null, 2));
68192
+ fs39.writeFileSync(filePath, JSON.stringify(fixture, null, 2));
68035
68193
  ctx.json(res, 200, {
68036
68194
  saved: true,
68037
68195
  name,
@@ -68049,14 +68207,14 @@ async function handleCliFixtureCapture(ctx, req, res) {
68049
68207
  async function handleCliFixtureList(ctx, type, _req, res) {
68050
68208
  try {
68051
68209
  const fixtureDir = getCliFixtureDir(ctx, type);
68052
- if (!fs38.existsSync(fixtureDir)) {
68210
+ if (!fs39.existsSync(fixtureDir)) {
68053
68211
  ctx.json(res, 200, { fixtures: [], count: 0 });
68054
68212
  return;
68055
68213
  }
68056
- const fixtures = fs38.readdirSync(fixtureDir).filter((file) => file.endsWith(".json")).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" })).map((file) => {
68214
+ const fixtures = fs39.readdirSync(fixtureDir).filter((file) => file.endsWith(".json")).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" })).map((file) => {
68057
68215
  const fullPath = path41.join(fixtureDir, file);
68058
68216
  try {
68059
- const raw = JSON.parse(fs38.readFileSync(fullPath, "utf-8"));
68217
+ const raw = JSON.parse(fs39.readFileSync(fullPath, "utf-8"));
68060
68218
  return {
68061
68219
  name: raw.name || file.replace(/\.json$/i, ""),
68062
68220
  path: fullPath,
@@ -68189,7 +68347,7 @@ async function handleCliRaw(ctx, req, res) {
68189
68347
  }
68190
68348
 
68191
68349
  // src/daemon/dev-auto-implement.ts
68192
- import * as fs39 from "fs";
68350
+ import * as fs40 from "fs";
68193
68351
  import * as path42 from "path";
68194
68352
  import * as os30 from "os";
68195
68353
  import { DEFAULT_SESSION_HOST_COLS as DEFAULT_SESSION_HOST_COLS7, DEFAULT_SESSION_HOST_ROWS as DEFAULT_SESSION_HOST_ROWS7 } from "@adhdev/session-host-core";
@@ -68238,10 +68396,10 @@ function resolveAutoImplReference(ctx, category, requestedReference, targetType)
68238
68396
  return fallback?.type || null;
68239
68397
  }
68240
68398
  function getLatestScriptVersionDir(scriptsDir) {
68241
- if (!fs39.existsSync(scriptsDir)) return null;
68242
- const versions = fs39.readdirSync(scriptsDir).filter((d) => {
68399
+ if (!fs40.existsSync(scriptsDir)) return null;
68400
+ const versions = fs40.readdirSync(scriptsDir).filter((d) => {
68243
68401
  try {
68244
- return fs39.statSync(path42.join(scriptsDir, d)).isDirectory();
68402
+ return fs40.statSync(path42.join(scriptsDir, d)).isDirectory();
68245
68403
  } catch {
68246
68404
  return false;
68247
68405
  }
@@ -68263,13 +68421,13 @@ function resolveAutoImplWritableProviderDir(ctx, category, type, requestedDir) {
68263
68421
  if (!sourceDir) {
68264
68422
  return { dir: null, reason: `Provider source directory not found for '${type}'` };
68265
68423
  }
68266
- if (!fs39.existsSync(desiredDir)) {
68267
- fs39.mkdirSync(path42.dirname(desiredDir), { recursive: true });
68268
- fs39.cpSync(sourceDir, desiredDir, { recursive: true });
68424
+ if (!fs40.existsSync(desiredDir)) {
68425
+ fs40.mkdirSync(path42.dirname(desiredDir), { recursive: true });
68426
+ fs40.cpSync(sourceDir, desiredDir, { recursive: true });
68269
68427
  ctx.log(`Auto-implement writable copy created: ${desiredDir}`);
68270
68428
  }
68271
68429
  const providerJson = path42.join(desiredDir, "provider.json");
68272
- if (!fs39.existsSync(providerJson)) {
68430
+ if (!fs40.existsSync(providerJson)) {
68273
68431
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
68274
68432
  }
68275
68433
  return { dir: desiredDir };
@@ -68277,15 +68435,15 @@ function resolveAutoImplWritableProviderDir(ctx, category, type, requestedDir) {
68277
68435
  function loadAutoImplReferenceScripts(ctx, referenceType) {
68278
68436
  if (!referenceType) return {};
68279
68437
  const refDir = ctx.findProviderDir(referenceType);
68280
- if (!refDir || !fs39.existsSync(refDir)) return {};
68438
+ if (!refDir || !fs40.existsSync(refDir)) return {};
68281
68439
  const referenceScripts = {};
68282
68440
  const scriptsDir = path42.join(refDir, "scripts");
68283
68441
  const latestDir = getLatestScriptVersionDir(scriptsDir);
68284
68442
  if (!latestDir) return referenceScripts;
68285
- for (const file of fs39.readdirSync(latestDir)) {
68443
+ for (const file of fs40.readdirSync(latestDir)) {
68286
68444
  if (!file.endsWith(".js")) continue;
68287
68445
  try {
68288
- referenceScripts[file] = fs39.readFileSync(path42.join(latestDir, file), "utf-8");
68446
+ referenceScripts[file] = fs40.readFileSync(path42.join(latestDir, file), "utf-8");
68289
68447
  } catch {
68290
68448
  }
68291
68449
  }
@@ -68394,15 +68552,15 @@ async function handleAutoImplement(ctx, type, req, res) {
68394
68552
  const referenceScripts = loadAutoImplReferenceScripts(ctx, resolvedReference);
68395
68553
  const prompt = buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domContext, referenceScripts, comment, resolvedReference, verification);
68396
68554
  const tmpDir = path42.join(os30.tmpdir(), "adhdev-autoimpl");
68397
- if (!fs39.existsSync(tmpDir)) fs39.mkdirSync(tmpDir, { recursive: true });
68555
+ if (!fs40.existsSync(tmpDir)) fs40.mkdirSync(tmpDir, { recursive: true });
68398
68556
  const promptFile = path42.join(tmpDir, `prompt-${type}-${Date.now()}.md`);
68399
- fs39.writeFileSync(promptFile, prompt, "utf-8");
68557
+ fs40.writeFileSync(promptFile, prompt, "utf-8");
68400
68558
  ctx.log(`Auto-implement prompt written to ${promptFile} (${prompt.length} chars)`);
68401
68559
  const agentProvider = ctx.providerLoader.resolve(agent) || ctx.providerLoader.getMeta(agent);
68402
68560
  const spawn5 = agentProvider?.spawn;
68403
68561
  if (!spawn5?.command) {
68404
68562
  try {
68405
- fs39.unlinkSync(promptFile);
68563
+ fs40.unlinkSync(promptFile);
68406
68564
  } catch {
68407
68565
  }
68408
68566
  ctx.json(res, 400, { error: `Agent '${agent}' has no spawn config. Select a CLI provider with a spawn configuration.` });
@@ -68504,7 +68662,7 @@ async function handleAutoImplement(ctx, type, req, res) {
68504
68662
  } catch {
68505
68663
  }
68506
68664
  try {
68507
- fs39.unlinkSync(promptFile);
68665
+ fs40.unlinkSync(promptFile);
68508
68666
  } catch {
68509
68667
  }
68510
68668
  ctx.log(`Auto-implement (ACP) ${success ? "completed" : "failed"}: ${type} (exit: ${code})`);
@@ -68730,7 +68888,7 @@ async function handleAutoImplement(ctx, type, req, res) {
68730
68888
  }
68731
68889
  });
68732
68890
  try {
68733
- fs39.unlinkSync(promptFile);
68891
+ fs40.unlinkSync(promptFile);
68734
68892
  } catch {
68735
68893
  }
68736
68894
  ctx.log(`Auto-implement ${success ? "completed" : "failed"}: ${type} (exit: ${code})${verificationSummary ? ` verify=${verificationSummary.pass ? "pass" : "fail"}` : ""}`);
@@ -68835,10 +68993,10 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
68835
68993
  lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
68836
68994
  lines.push("These are the ONLY files you are allowed to modify. Replace the TODO stubs with working implementations.");
68837
68995
  lines.push("");
68838
- for (const file of fs39.readdirSync(latestScriptsDir)) {
68996
+ for (const file of fs40.readdirSync(latestScriptsDir)) {
68839
68997
  if (file.endsWith(".js") && targetFileNames.has(file)) {
68840
68998
  try {
68841
- const content = fs39.readFileSync(path42.join(latestScriptsDir, file), "utf-8");
68999
+ const content = fs40.readFileSync(path42.join(latestScriptsDir, file), "utf-8");
68842
69000
  lines.push(`### \`${file}\` \u270F\uFE0F EDIT`);
68843
69001
  lines.push("```javascript");
68844
69002
  lines.push(content);
@@ -68848,14 +69006,14 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
68848
69006
  }
68849
69007
  }
68850
69008
  }
68851
- const refFiles = fs39.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
69009
+ const refFiles = fs40.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
68852
69010
  if (refFiles.length > 0) {
68853
69011
  lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
68854
69012
  lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
68855
69013
  lines.push("");
68856
69014
  for (const file of refFiles) {
68857
69015
  try {
68858
- const content = fs39.readFileSync(path42.join(latestScriptsDir, file), "utf-8");
69016
+ const content = fs40.readFileSync(path42.join(latestScriptsDir, file), "utf-8");
68859
69017
  lines.push(`### \`${file}\` \u{1F512}`);
68860
69018
  lines.push("```javascript");
68861
69019
  lines.push(content);
@@ -68900,7 +69058,7 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
68900
69058
  const loadGuide = (name) => {
68901
69059
  try {
68902
69060
  const p = path42.join(docsDir, name);
68903
- if (fs39.existsSync(p)) return fs39.readFileSync(p, "utf-8");
69061
+ if (fs40.existsSync(p)) return fs40.readFileSync(p, "utf-8");
68904
69062
  } catch {
68905
69063
  }
68906
69064
  return null;
@@ -69144,11 +69302,11 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
69144
69302
  lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
69145
69303
  lines.push("These are the ONLY files you are allowed to modify. Replace TODO or heuristic-only logic with working PTY-aware implementations.");
69146
69304
  lines.push("");
69147
- for (const file of fs39.readdirSync(latestScriptsDir)) {
69305
+ for (const file of fs40.readdirSync(latestScriptsDir)) {
69148
69306
  if (!file.endsWith(".js")) continue;
69149
69307
  if (!targetFileNames.has(file)) continue;
69150
69308
  try {
69151
- const content = fs39.readFileSync(path42.join(latestScriptsDir, file), "utf-8");
69309
+ const content = fs40.readFileSync(path42.join(latestScriptsDir, file), "utf-8");
69152
69310
  lines.push(`### \`${file}\` \u270F\uFE0F EDIT`);
69153
69311
  lines.push("```javascript");
69154
69312
  lines.push(content);
@@ -69157,14 +69315,14 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
69157
69315
  } catch {
69158
69316
  }
69159
69317
  }
69160
- const refFiles = fs39.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
69318
+ const refFiles = fs40.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
69161
69319
  if (refFiles.length > 0) {
69162
69320
  lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
69163
69321
  lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
69164
69322
  lines.push("");
69165
69323
  for (const file of refFiles) {
69166
69324
  try {
69167
- const content = fs39.readFileSync(path42.join(latestScriptsDir, file), "utf-8");
69325
+ const content = fs40.readFileSync(path42.join(latestScriptsDir, file), "utf-8");
69168
69326
  lines.push(`### \`${file}\` \u{1F512}`);
69169
69327
  lines.push("```javascript");
69170
69328
  lines.push(content);
@@ -69201,7 +69359,7 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
69201
69359
  const loadGuide = (name) => {
69202
69360
  try {
69203
69361
  const p = path42.join(docsDir, name);
69204
- if (fs39.existsSync(p)) return fs39.readFileSync(p, "utf-8");
69362
+ if (fs40.existsSync(p)) return fs40.readFileSync(p, "utf-8");
69205
69363
  } catch {
69206
69364
  }
69207
69365
  return null;
@@ -69679,15 +69837,15 @@ var DevServer = class _DevServer {
69679
69837
  this.json(res, 500, { error: e.message });
69680
69838
  }
69681
69839
  });
69682
- return new Promise((resolve25, reject) => {
69840
+ return new Promise((resolve26, reject) => {
69683
69841
  this.server.listen(port, "127.0.0.1", () => {
69684
69842
  this.log(`Dev server listening on http://127.0.0.1:${port}`);
69685
- resolve25();
69843
+ resolve26();
69686
69844
  });
69687
69845
  this.server.on("error", (e) => {
69688
69846
  if (e.code === "EADDRINUSE") {
69689
69847
  this.log(`Port ${port} in use, skipping dev server`);
69690
- resolve25();
69848
+ resolve26();
69691
69849
  } else {
69692
69850
  reject(e);
69693
69851
  }
@@ -69769,20 +69927,20 @@ var DevServer = class _DevServer {
69769
69927
  child.stderr?.on("data", (d) => {
69770
69928
  stderr += d.toString().slice(0, 2e3);
69771
69929
  });
69772
- await new Promise((resolve25) => {
69930
+ await new Promise((resolve26) => {
69773
69931
  const timer = setTimeout(() => {
69774
69932
  child.kill();
69775
- resolve25();
69933
+ resolve26();
69776
69934
  }, 3e3);
69777
69935
  child.on("exit", () => {
69778
69936
  clearTimeout(timer);
69779
- resolve25();
69937
+ resolve26();
69780
69938
  });
69781
69939
  child.stdout?.once("data", () => {
69782
69940
  setTimeout(() => {
69783
69941
  child.kill();
69784
69942
  clearTimeout(timer);
69785
- resolve25();
69943
+ resolve26();
69786
69944
  }, 500);
69787
69945
  });
69788
69946
  });
@@ -69941,7 +70099,7 @@ var DevServer = class _DevServer {
69941
70099
  path43.join(process.cwd(), "packages/web-devconsole/dist")
69942
70100
  ];
69943
70101
  for (const dir of candidates) {
69944
- if (fs40.existsSync(path43.join(dir, "index.html"))) return dir;
70102
+ if (fs41.existsSync(path43.join(dir, "index.html"))) return dir;
69945
70103
  }
69946
70104
  return null;
69947
70105
  }
@@ -69953,7 +70111,7 @@ var DevServer = class _DevServer {
69953
70111
  }
69954
70112
  const htmlPath = path43.join(distDir, "index.html");
69955
70113
  try {
69956
- const html = fs40.readFileSync(htmlPath, "utf-8");
70114
+ const html = fs41.readFileSync(htmlPath, "utf-8");
69957
70115
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
69958
70116
  res.end(html);
69959
70117
  } catch (e) {
@@ -69983,7 +70141,7 @@ var DevServer = class _DevServer {
69983
70141
  return;
69984
70142
  }
69985
70143
  try {
69986
- const content = fs40.readFileSync(filePath);
70144
+ const content = fs41.readFileSync(filePath);
69987
70145
  const ext = path43.extname(filePath);
69988
70146
  const contentType = _DevServer.MIME_MAP[ext] || "application/octet-stream";
69989
70147
  res.writeHead(200, { "Content-Type": contentType, "Cache-Control": "public, max-age=31536000, immutable" });
@@ -70092,14 +70250,14 @@ var DevServer = class _DevServer {
70092
70250
  const files = [];
70093
70251
  const scan = (d, prefix) => {
70094
70252
  try {
70095
- for (const entry of fs40.readdirSync(d, { withFileTypes: true })) {
70253
+ for (const entry of fs41.readdirSync(d, { withFileTypes: true })) {
70096
70254
  if (entry.name.startsWith(".") || entry.name.endsWith(".bak")) continue;
70097
70255
  const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
70098
70256
  if (entry.isDirectory()) {
70099
70257
  files.push({ path: rel, size: 0, type: "dir" });
70100
70258
  scan(path43.join(d, entry.name), rel);
70101
70259
  } else {
70102
- const stat2 = fs40.statSync(path43.join(d, entry.name));
70260
+ const stat2 = fs41.statSync(path43.join(d, entry.name));
70103
70261
  files.push({ path: rel, size: stat2.size, type: "file" });
70104
70262
  }
70105
70263
  }
@@ -70127,11 +70285,11 @@ var DevServer = class _DevServer {
70127
70285
  this.json(res, 403, { error: "Forbidden" });
70128
70286
  return;
70129
70287
  }
70130
- if (!fs40.existsSync(fullPath) || fs40.statSync(fullPath).isDirectory()) {
70288
+ if (!fs41.existsSync(fullPath) || fs41.statSync(fullPath).isDirectory()) {
70131
70289
  this.json(res, 404, { error: `File not found: ${filePath}` });
70132
70290
  return;
70133
70291
  }
70134
- const content = fs40.readFileSync(fullPath, "utf-8");
70292
+ const content = fs41.readFileSync(fullPath, "utf-8");
70135
70293
  this.json(res, 200, { type, path: filePath, content, lines: content.split("\n").length });
70136
70294
  }
70137
70295
  /** POST /api/providers/:type/file — write a file { path, content } */
@@ -70153,9 +70311,9 @@ var DevServer = class _DevServer {
70153
70311
  return;
70154
70312
  }
70155
70313
  try {
70156
- if (fs40.existsSync(fullPath)) fs40.copyFileSync(fullPath, fullPath + ".bak");
70157
- fs40.mkdirSync(path43.dirname(fullPath), { recursive: true });
70158
- fs40.writeFileSync(fullPath, content, "utf-8");
70314
+ if (fs41.existsSync(fullPath)) fs41.copyFileSync(fullPath, fullPath + ".bak");
70315
+ fs41.mkdirSync(path43.dirname(fullPath), { recursive: true });
70316
+ fs41.writeFileSync(fullPath, content, "utf-8");
70159
70317
  this.log(`File saved: ${fullPath} (${content.length} chars)`);
70160
70318
  this.providerLoader.reload();
70161
70319
  this.json(res, 200, { saved: true, path: filePath, chars: content.length });
@@ -70172,8 +70330,8 @@ var DevServer = class _DevServer {
70172
70330
  }
70173
70331
  for (const name of ["scripts.js", "provider.json"]) {
70174
70332
  const p = path43.join(dir, name);
70175
- if (fs40.existsSync(p)) {
70176
- const source = fs40.readFileSync(p, "utf-8");
70333
+ if (fs41.existsSync(p)) {
70334
+ const source = fs41.readFileSync(p, "utf-8");
70177
70335
  this.json(res, 200, { type, path: p, source, lines: source.split("\n").length });
70178
70336
  return;
70179
70337
  }
@@ -70192,11 +70350,11 @@ var DevServer = class _DevServer {
70192
70350
  this.json(res, 404, { error: `Provider not found: ${type}` });
70193
70351
  return;
70194
70352
  }
70195
- const target = fs40.existsSync(path43.join(dir, "scripts.js")) ? "scripts.js" : "provider.json";
70353
+ const target = fs41.existsSync(path43.join(dir, "scripts.js")) ? "scripts.js" : "provider.json";
70196
70354
  const targetPath = path43.join(dir, target);
70197
70355
  try {
70198
- if (fs40.existsSync(targetPath)) fs40.copyFileSync(targetPath, targetPath + ".bak");
70199
- fs40.writeFileSync(targetPath, source, "utf-8");
70356
+ if (fs41.existsSync(targetPath)) fs41.copyFileSync(targetPath, targetPath + ".bak");
70357
+ fs41.writeFileSync(targetPath, source, "utf-8");
70200
70358
  this.log(`Saved provider: ${targetPath} (${source.length} chars)`);
70201
70359
  this.providerLoader.reload();
70202
70360
  this.json(res, 200, { saved: true, path: targetPath, chars: source.length });
@@ -70285,14 +70443,14 @@ var DevServer = class _DevServer {
70285
70443
  child.stderr?.on("data", (d) => {
70286
70444
  stderr += d.toString();
70287
70445
  });
70288
- await new Promise((resolve25) => {
70446
+ await new Promise((resolve26) => {
70289
70447
  const timer = setTimeout(() => {
70290
70448
  child.kill();
70291
- resolve25();
70449
+ resolve26();
70292
70450
  }, timeout);
70293
70451
  child.on("exit", () => {
70294
70452
  clearTimeout(timer);
70295
- resolve25();
70453
+ resolve26();
70296
70454
  });
70297
70455
  });
70298
70456
  const elapsed = Date.now() - start;
@@ -70341,20 +70499,20 @@ var DevServer = class _DevServer {
70341
70499
  let targetDir;
70342
70500
  targetDir = this.providerLoader.getUserProviderDir(category, type);
70343
70501
  const jsonPath = path43.join(targetDir, "provider.json");
70344
- if (fs40.existsSync(jsonPath)) {
70502
+ if (fs41.existsSync(jsonPath)) {
70345
70503
  this.json(res, 409, { error: `Provider already exists at ${targetDir}`, path: targetDir });
70346
70504
  return;
70347
70505
  }
70348
70506
  try {
70349
70507
  const result = generateFiles(type, name, category, { cdpPorts, cli, processName, installPath, binary, extensionId, version, osPaths, processNames });
70350
- fs40.mkdirSync(targetDir, { recursive: true });
70351
- fs40.writeFileSync(jsonPath, result["provider.json"], "utf-8");
70508
+ fs41.mkdirSync(targetDir, { recursive: true });
70509
+ fs41.writeFileSync(jsonPath, result["provider.json"], "utf-8");
70352
70510
  const createdFiles = ["provider.json"];
70353
70511
  if (result.files) {
70354
70512
  for (const [relPath, content] of Object.entries(result.files)) {
70355
70513
  const fullPath = path43.join(targetDir, relPath);
70356
- fs40.mkdirSync(path43.dirname(fullPath), { recursive: true });
70357
- fs40.writeFileSync(fullPath, content, "utf-8");
70514
+ fs41.mkdirSync(path43.dirname(fullPath), { recursive: true });
70515
+ fs41.writeFileSync(fullPath, content, "utf-8");
70358
70516
  createdFiles.push(relPath);
70359
70517
  }
70360
70518
  }
@@ -70403,10 +70561,10 @@ var DevServer = class _DevServer {
70403
70561
  }
70404
70562
  // ─── Phase 2: Auto-Implement Backend ───
70405
70563
  getLatestScriptVersionDir(scriptsDir) {
70406
- if (!fs40.existsSync(scriptsDir)) return null;
70407
- const versions = fs40.readdirSync(scriptsDir).filter((d) => {
70564
+ if (!fs41.existsSync(scriptsDir)) return null;
70565
+ const versions = fs41.readdirSync(scriptsDir).filter((d) => {
70408
70566
  try {
70409
- return fs40.statSync(path43.join(scriptsDir, d)).isDirectory();
70567
+ return fs41.statSync(path43.join(scriptsDir, d)).isDirectory();
70410
70568
  } catch {
70411
70569
  return false;
70412
70570
  }
@@ -70428,13 +70586,13 @@ var DevServer = class _DevServer {
70428
70586
  if (!sourceDir) {
70429
70587
  return { dir: null, reason: `Provider source directory not found for '${type}'` };
70430
70588
  }
70431
- if (!fs40.existsSync(desiredDir)) {
70432
- fs40.mkdirSync(path43.dirname(desiredDir), { recursive: true });
70433
- fs40.cpSync(sourceDir, desiredDir, { recursive: true });
70589
+ if (!fs41.existsSync(desiredDir)) {
70590
+ fs41.mkdirSync(path43.dirname(desiredDir), { recursive: true });
70591
+ fs41.cpSync(sourceDir, desiredDir, { recursive: true });
70434
70592
  this.log(`Auto-implement writable copy created: ${desiredDir}`);
70435
70593
  }
70436
70594
  const providerJson = path43.join(desiredDir, "provider.json");
70437
- if (!fs40.existsSync(providerJson)) {
70595
+ if (!fs41.existsSync(providerJson)) {
70438
70596
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
70439
70597
  }
70440
70598
  return { dir: desiredDir };
@@ -70491,14 +70649,14 @@ data: ${JSON.stringify(msg.data)}
70491
70649
  res.end(JSON.stringify(data, null, 2));
70492
70650
  }
70493
70651
  async readBody(req) {
70494
- return new Promise((resolve25) => {
70652
+ return new Promise((resolve26) => {
70495
70653
  let body = "";
70496
70654
  req.on("data", (chunk) => body += chunk);
70497
70655
  req.on("end", () => {
70498
70656
  try {
70499
- resolve25(JSON.parse(body));
70657
+ resolve26(JSON.parse(body));
70500
70658
  } catch {
70501
- resolve25({});
70659
+ resolve26({});
70502
70660
  }
70503
70661
  });
70504
70662
  });
@@ -71240,7 +71398,7 @@ async function waitForReady(endpoint, timeoutMs = STARTUP_TIMEOUT_MS, requiredRe
71240
71398
  const deadline = Date.now() + timeoutMs;
71241
71399
  while (Date.now() < deadline) {
71242
71400
  if (await canConnect(endpoint, requiredRequestTypes)) return;
71243
- await new Promise((resolve25) => setTimeout(resolve25, STARTUP_POLL_MS));
71401
+ await new Promise((resolve26) => setTimeout(resolve26, STARTUP_POLL_MS));
71244
71402
  }
71245
71403
  throw new Error(`Session host did not become ready within ${timeoutMs}ms`);
71246
71404
  }
@@ -71283,7 +71441,7 @@ async function listHostedCliRuntimes(endpoint) {
71283
71441
 
71284
71442
  // src/session-host/managed-host.ts
71285
71443
  import { execFileSync as execFileSync9, spawn as spawn4 } from "child_process";
71286
- import * as fs41 from "fs";
71444
+ import * as fs42 from "fs";
71287
71445
  import * as os31 from "os";
71288
71446
  import * as path44 from "path";
71289
71447
  import {
@@ -71307,7 +71465,7 @@ function createManagedSessionHost(options) {
71307
71465
  path44.resolve(__dirname, "../../vendor/session-host-daemon/index.js")
71308
71466
  ];
71309
71467
  for (const candidate of packagedCandidates) {
71310
- if (fs41.existsSync(candidate)) {
71468
+ if (fs42.existsSync(candidate)) {
71311
71469
  return candidate;
71312
71470
  }
71313
71471
  }
@@ -71319,8 +71477,8 @@ function createManagedSessionHost(options) {
71319
71477
  function getPid() {
71320
71478
  try {
71321
71479
  const pidFile = getPidFile();
71322
- if (!fs41.existsSync(pidFile)) return null;
71323
- const pid = Number.parseInt(fs41.readFileSync(pidFile, "utf8").trim(), 10);
71480
+ if (!fs42.existsSync(pidFile)) return null;
71481
+ const pid = Number.parseInt(fs42.readFileSync(pidFile, "utf8").trim(), 10);
71324
71482
  return Number.isFinite(pid) ? pid : null;
71325
71483
  } catch {
71326
71484
  return null;
@@ -71346,8 +71504,8 @@ function createManagedSessionHost(options) {
71346
71504
  let logFd = null;
71347
71505
  if (options.spawnStdio === "logfile") {
71348
71506
  const logDir = path44.join(os31.homedir(), ".adhdev", "logs");
71349
- fs41.mkdirSync(logDir, { recursive: true });
71350
- logFd = fs41.openSync(path44.join(logDir, "session-host.log"), "a");
71507
+ fs42.mkdirSync(logDir, { recursive: true });
71508
+ logFd = fs42.openSync(path44.join(logDir, "session-host.log"), "a");
71351
71509
  stdio = ["ignore", logFd, logFd];
71352
71510
  }
71353
71511
  const child = spawn4(process.execPath, [entry], {
@@ -71359,7 +71517,7 @@ function createManagedSessionHost(options) {
71359
71517
  child.unref();
71360
71518
  if (logFd !== null) {
71361
71519
  try {
71362
- fs41.closeSync(logFd);
71520
+ fs42.closeSync(logFd);
71363
71521
  } catch {
71364
71522
  }
71365
71523
  }
@@ -71368,8 +71526,8 @@ function createManagedSessionHost(options) {
71368
71526
  let stopped = false;
71369
71527
  const pidFile = getPidFile();
71370
71528
  try {
71371
- if (fs41.existsSync(pidFile)) {
71372
- const pid = Number.parseInt(fs41.readFileSync(pidFile, "utf8").trim(), 10);
71529
+ if (fs42.existsSync(pidFile)) {
71530
+ const pid = Number.parseInt(fs42.readFileSync(pidFile, "utf8").trim(), 10);
71373
71531
  if (Number.isFinite(pid) && pid !== process.pid && isManagedPid(pid)) {
71374
71532
  stopped = killPid2(pid) || stopped;
71375
71533
  }
@@ -71377,7 +71535,7 @@ function createManagedSessionHost(options) {
71377
71535
  } catch {
71378
71536
  } finally {
71379
71537
  try {
71380
- fs41.unlinkSync(pidFile);
71538
+ fs42.unlinkSync(pidFile);
71381
71539
  } catch {
71382
71540
  }
71383
71541
  }
@@ -71566,12 +71724,12 @@ async function installExtension(ide, extension) {
71566
71724
  const res = await fetch(extension.vsixUrl);
71567
71725
  if (res.ok) {
71568
71726
  const buffer = Buffer.from(await res.arrayBuffer());
71569
- const fs42 = await import("fs");
71570
- fs42.writeFileSync(vsixPath, buffer);
71571
- return new Promise((resolve25) => {
71727
+ const fs43 = await import("fs");
71728
+ fs43.writeFileSync(vsixPath, buffer);
71729
+ return new Promise((resolve26) => {
71572
71730
  const cmd = `"${ide.cliCommand}" --install-extension "${vsixPath}" --force`;
71573
71731
  exec6(cmd, { timeout: 6e4 }, (error, _stdout, stderr) => {
71574
- resolve25({
71732
+ resolve26({
71575
71733
  extensionId: extension.id,
71576
71734
  marketplaceId: extension.marketplaceId,
71577
71735
  success: !error,
@@ -71584,11 +71742,11 @@ async function installExtension(ide, extension) {
71584
71742
  } catch (e) {
71585
71743
  }
71586
71744
  }
71587
- return new Promise((resolve25) => {
71745
+ return new Promise((resolve26) => {
71588
71746
  const cmd = `"${ide.cliCommand}" --install-extension ${extension.marketplaceId} --force`;
71589
71747
  exec6(cmd, { timeout: 6e4 }, (error, stdout, stderr) => {
71590
71748
  if (error) {
71591
- resolve25({
71749
+ resolve26({
71592
71750
  extensionId: extension.id,
71593
71751
  marketplaceId: extension.marketplaceId,
71594
71752
  success: false,
@@ -71596,7 +71754,7 @@ async function installExtension(ide, extension) {
71596
71754
  error: stderr || error.message
71597
71755
  });
71598
71756
  } else {
71599
- resolve25({
71757
+ resolve26({
71600
71758
  extensionId: extension.id,
71601
71759
  marketplaceId: extension.marketplaceId,
71602
71760
  success: true,
@@ -72132,7 +72290,7 @@ async function startLocalIpcServer(opts) {
72132
72290
  }));
72133
72291
  }
72134
72292
  }
72135
- await new Promise((resolve25, reject) => {
72293
+ await new Promise((resolve26, reject) => {
72136
72294
  const onError = (error) => {
72137
72295
  httpServer?.off("listening", onListening);
72138
72296
  reject(error);
@@ -72140,7 +72298,7 @@ async function startLocalIpcServer(opts) {
72140
72298
  const onListening = () => {
72141
72299
  httpServer?.off("error", onError);
72142
72300
  listening = true;
72143
- resolve25();
72301
+ resolve26();
72144
72302
  };
72145
72303
  httpServer.once("error", onError);
72146
72304
  httpServer.once("listening", onListening);
@@ -72167,12 +72325,12 @@ async function startLocalIpcServer(opts) {
72167
72325
  }
72168
72326
  }
72169
72327
  clients.clear();
72170
- await new Promise((resolve25) => {
72328
+ await new Promise((resolve26) => {
72171
72329
  if (!httpServer) {
72172
- resolve25();
72330
+ resolve26();
72173
72331
  return;
72174
72332
  }
72175
- httpServer.close(() => resolve25());
72333
+ httpServer.close(() => resolve26());
72176
72334
  });
72177
72335
  httpServer = null;
72178
72336
  wss = null;
@@ -72194,11 +72352,11 @@ init_parse_session();
72194
72352
  // src/providers/sdk/v1/fixture-tooling/replay.ts
72195
72353
  init_provider_cli_shared();
72196
72354
  import { readFileSync as readFileSync40 } from "fs";
72197
- import { dirname as dirname15, resolve as resolve23 } from "path";
72355
+ import { dirname as dirname16, resolve as resolve24 } from "path";
72198
72356
 
72199
72357
  // src/providers/sdk/v1/validators/taint.ts
72200
72358
  import { readFileSync as readFileSync41, existsSync as existsSync54 } from "fs";
72201
- import { resolve as resolve24, dirname as dirname16, join as join51 } from "path";
72359
+ import { resolve as resolve25, dirname as dirname17, join as join51 } from "path";
72202
72360
 
72203
72361
  // src/providers/sdk/v1/validators/index.ts
72204
72362
  init_manifest();