@adhdev/daemon-core 0.9.82-rc.317 → 0.9.82-rc.318

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
@@ -348,10 +348,10 @@ function readInjected(value) {
348
348
  }
349
349
  function getDaemonBuildInfo() {
350
350
  if (cached) return cached;
351
- const commit = readInjected(true ? "b4484284652748bf8096f40a00eb5cb463963576" : void 0) ?? "unknown";
352
- const commitShort = readInjected(true ? "b4484284" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
353
- const version = readInjected(true ? "0.9.82-rc.317" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
354
- const builtAt = readInjected(true ? "2026-06-18T08:55:18.955Z" : void 0);
351
+ const commit = readInjected(true ? "506ca246e28984a3b699b04c4601117f62ba2d81" : void 0) ?? "unknown";
352
+ const commitShort = readInjected(true ? "506ca246" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
353
+ const version = readInjected(true ? "0.9.82-rc.318" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
354
+ const builtAt = readInjected(true ? "2026-06-18T12:46:04.472Z" : void 0);
355
355
  cached = builtAt ? { commit, commitShort, version, builtAt } : { commit, commitShort, version };
356
356
  return cached;
357
357
  }
@@ -7907,10 +7907,412 @@ var init_mesh_events_stale = __esm({
7907
7907
  }
7908
7908
  });
7909
7909
 
7910
- // src/detection/cli-detector.ts
7911
- import { exec } from "child_process";
7910
+ // src/cli-adapters/spawn-env.ts
7911
+ import {
7912
+ sanitizeSpawnEnv,
7913
+ applyTerminalColorEnv,
7914
+ ensureNodePtySpawnHelperPermissions
7915
+ } from "@adhdev/session-host-core";
7916
+ var init_spawn_env = __esm({
7917
+ "src/cli-adapters/spawn-env.ts"() {
7918
+ "use strict";
7919
+ }
7920
+ });
7921
+
7922
+ // src/cli-adapters/provider-cli-shared.ts
7912
7923
  import * as os5 from "os";
7913
7924
  import * as path10 from "path";
7925
+ function stripAnsi(str) {
7926
+ return str.replace(/\x1B\][^\x07]*(?:\x07|\x1B\\)/g, "").replace(/\x1B[P^_X][\s\S]*?(?:\x07|\x1B\\)/g, "").replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, "");
7927
+ }
7928
+ function parseCount(params, fallback = 1) {
7929
+ const first = Number(String(params || "").split(";")[0] || fallback);
7930
+ return Math.max(1, Number.isFinite(first) ? first : fallback);
7931
+ }
7932
+ function isCombiningMark(ch) {
7933
+ return /[\u0300-\u036F\u1AB0-\u1AFF\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/.test(ch);
7934
+ }
7935
+ function isWideCodePoint(ch) {
7936
+ const cp = ch.codePointAt(0) || 0;
7937
+ return cp >= 4352 && (cp <= 4447 || cp === 9001 || cp === 9002 || cp >= 11904 && cp <= 42191 && cp !== 12351 || cp >= 44032 && cp <= 55203 || cp >= 63744 && cp <= 64255 || cp >= 65040 && cp <= 65049 || cp >= 65072 && cp <= 65135 || cp >= 65280 && cp <= 65376 || cp >= 65504 && cp <= 65510 || cp >= 127744 && cp <= 129791);
7938
+ }
7939
+ function stripTerminalNoise(str) {
7940
+ return String(str || "").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/g, "").replace(/\r+/g, "\n").replace(/[ \t]+\n/g, "\n").replace(/\n{4,}/g, "\n\n\n");
7941
+ }
7942
+ function sanitizeTerminalText(str) {
7943
+ const accumulator = new TerminalTranscriptAccumulator();
7944
+ return stripTerminalNoise(stripAnsi(accumulator.append(str)));
7945
+ }
7946
+ function listCliScriptNames(scripts) {
7947
+ if (!scripts) return [];
7948
+ return Object.entries(scripts).filter(([, fn]) => typeof fn === "function").map(([name]) => name);
7949
+ }
7950
+ function splitCliScreenLines(text) {
7951
+ return String(text || "").replace(/\u0007/g, "").replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n").map((line) => line.replace(/\s+$/, ""));
7952
+ }
7953
+ function isPromptLikeCliLine(line) {
7954
+ const trimmed = String(line || "").trim();
7955
+ if (!trimmed) return false;
7956
+ return /^[❯›>]\s*(?:$|\S.*)$/.test(trimmed);
7957
+ }
7958
+ function buildCliScreenSnapshot(text) {
7959
+ const normalizedText = String(text || "").replace(/\r\n/g, "\n").replace(/\r/g, "\n");
7960
+ const rawLines = splitCliScreenLines(normalizedText);
7961
+ const lines = rawLines.map((line, index, arr) => {
7962
+ const trimmed = String(line || "").trim();
7963
+ return {
7964
+ index,
7965
+ fromTop: index,
7966
+ fromBottom: arr.length - index - 1,
7967
+ text: line,
7968
+ trimmed,
7969
+ isEmpty: trimmed.length === 0
7970
+ };
7971
+ });
7972
+ const nonEmptyLines = lines.filter((line) => !line.isEmpty);
7973
+ const firstNonEmptyLine = nonEmptyLines[0] ?? null;
7974
+ const lastNonEmptyLine = nonEmptyLines[nonEmptyLines.length - 1] ?? null;
7975
+ let promptLineIndex = -1;
7976
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
7977
+ if (isPromptLikeCliLine(lines[i].text)) {
7978
+ promptLineIndex = i;
7979
+ break;
7980
+ }
7981
+ }
7982
+ return {
7983
+ text: normalizedText,
7984
+ lineCount: lines.length,
7985
+ lines,
7986
+ nonEmptyLines,
7987
+ firstNonEmptyLineIndex: firstNonEmptyLine?.index ?? -1,
7988
+ lastNonEmptyLineIndex: lastNonEmptyLine?.index ?? -1,
7989
+ firstNonEmptyLine,
7990
+ lastNonEmptyLine,
7991
+ promptLineIndex,
7992
+ promptLine: promptLineIndex >= 0 ? lines[promptLineIndex] : null,
7993
+ linesAbovePrompt: promptLineIndex >= 0 ? lines.slice(0, promptLineIndex) : [...lines],
7994
+ linesBelowPrompt: promptLineIndex >= 0 ? lines.slice(promptLineIndex + 1) : []
7995
+ };
7996
+ }
7997
+ function findBinary(name) {
7998
+ const trimmed = String(name || "").trim();
7999
+ if (!trimmed) return trimmed;
8000
+ const expanded = trimmed.startsWith("~") ? path10.join(os5.homedir(), trimmed.slice(1)) : trimmed;
8001
+ if (path10.isAbsolute(expanded) || expanded.includes("/") || expanded.includes("\\")) {
8002
+ return path10.isAbsolute(expanded) ? expanded : path10.resolve(expanded);
8003
+ }
8004
+ const isWin = os5.platform() === "win32";
8005
+ const paths = (process.env.PATH || "").split(path10.delimiter);
8006
+ const extraDirs = [];
8007
+ if (isWin) {
8008
+ if (process.env.APPDATA) extraDirs.push(path10.join(process.env.APPDATA, "npm"));
8009
+ try {
8010
+ extraDirs.push(path10.dirname(process.execPath));
8011
+ } catch {
8012
+ }
8013
+ } else {
8014
+ extraDirs.push(path10.join(os5.homedir(), ".npm-global", "bin"));
8015
+ extraDirs.push("/usr/local/bin", "/opt/homebrew/bin");
8016
+ try {
8017
+ extraDirs.push(path10.dirname(process.execPath));
8018
+ } catch {
8019
+ }
8020
+ }
8021
+ const searchDirs = [...paths, ...extraDirs];
8022
+ const exes = isWin ? [".exe", ".cmd", ".bat", ""] : [""];
8023
+ for (const p of searchDirs) {
8024
+ if (!p) continue;
8025
+ for (const ext of exes) {
8026
+ const fullPath = path10.join(p, trimmed + ext);
8027
+ try {
8028
+ const fs31 = __require("fs");
8029
+ if (fs31.existsSync(fullPath)) {
8030
+ const stat2 = fs31.statSync(fullPath);
8031
+ if (stat2.isFile() && (isWin || stat2.mode & 73)) {
8032
+ return fullPath;
8033
+ }
8034
+ }
8035
+ } catch {
8036
+ }
8037
+ }
8038
+ }
8039
+ return isWin ? `${trimmed}.cmd` : trimmed;
8040
+ }
8041
+ function isScriptBinary(binaryPath) {
8042
+ if (!path10.isAbsolute(binaryPath)) return false;
8043
+ try {
8044
+ const fs31 = __require("fs");
8045
+ const resolved = fs31.realpathSync(binaryPath);
8046
+ const head = Buffer.alloc(8);
8047
+ const fd = fs31.openSync(resolved, "r");
8048
+ fs31.readSync(fd, head, 0, 8, 0);
8049
+ fs31.closeSync(fd);
8050
+ let i = 0;
8051
+ if (head[0] === 239 && head[1] === 187 && head[2] === 191) i = 3;
8052
+ return head[i] === 35 && head[i + 1] === 33;
8053
+ } catch {
8054
+ return false;
8055
+ }
8056
+ }
8057
+ function looksLikeMachOOrElf(filePath) {
8058
+ if (!path10.isAbsolute(filePath)) return false;
8059
+ try {
8060
+ const fs31 = __require("fs");
8061
+ const resolved = fs31.realpathSync(filePath);
8062
+ const buf = Buffer.alloc(8);
8063
+ const fd = fs31.openSync(resolved, "r");
8064
+ fs31.readSync(fd, buf, 0, 8, 0);
8065
+ fs31.closeSync(fd);
8066
+ let i = 0;
8067
+ if (buf[0] === 239 && buf[1] === 187 && buf[2] === 191) i = 3;
8068
+ const b = buf.subarray(i);
8069
+ if (b.length < 4) return false;
8070
+ if (b[0] === 127 && b[1] === 69 && b[2] === 76 && b[3] === 70) return true;
8071
+ const le = b.readUInt32LE(0);
8072
+ const be = b.readUInt32BE(0);
8073
+ const magics = [4277009102, 4277009103, 3405691582, 3199925962];
8074
+ return magics.some((m) => m === le || m === be);
8075
+ } catch {
8076
+ return false;
8077
+ }
8078
+ }
8079
+ function shSingleQuote(arg) {
8080
+ if (/^[a-zA-Z0-9@%_+=:,./-]+$/.test(arg)) return arg;
8081
+ if (os5.platform() === "win32") {
8082
+ return `"${arg.replace(/"/g, '""')}"`;
8083
+ }
8084
+ return `'${arg.replace(/'/g, `'\\''`)}'`;
8085
+ }
8086
+ function estimatePromptDisplayLines(text, cols = 80) {
8087
+ const normalized = String(text || "").replace(/\r/g, "");
8088
+ if (!normalized) return 1;
8089
+ return normalized.split("\n").reduce((sum, line) => sum + Math.max(1, Math.ceil(Math.max(1, line.length) / cols)), 0);
8090
+ }
8091
+ function extractPromptRetrySnippet(text) {
8092
+ const lines = String(text || "").replace(/\r/g, "").split("\n").map((line) => line.trim()).filter(Boolean);
8093
+ const candidate = lines[lines.length - 1] || lines[0] || "";
8094
+ return candidate.slice(-120);
8095
+ }
8096
+ function normalizePromptText(text) {
8097
+ return String(text || "").replace(/\s+/g, " ").trim();
8098
+ }
8099
+ function compactPromptText(text) {
8100
+ return String(text || "").replace(/\s+/g, "").trim();
8101
+ }
8102
+ function promptLikelyVisible(screenText, promptSnippet) {
8103
+ const snippet = normalizePromptText(promptSnippet);
8104
+ if (!snippet) return false;
8105
+ const normalizedScreen = normalizePromptText(screenText);
8106
+ if (normalizedScreen.includes(snippet)) return true;
8107
+ const compactScreen = compactPromptText(screenText);
8108
+ const compactSnippet = compactPromptText(promptSnippet);
8109
+ if (compactSnippet && compactScreen.includes(compactSnippet)) return true;
8110
+ const tokens = snippet.split(/[^A-Za-z0-9_.:/-]+/).map((token) => token.trim()).filter((token) => token.length >= 4);
8111
+ if (tokens.length === 0) return false;
8112
+ const required = Math.min(tokens.length, 3);
8113
+ const matched = tokens.filter(
8114
+ (token) => normalizedScreen.includes(token) || compactScreen.includes(compactPromptText(token))
8115
+ ).length;
8116
+ return matched >= required;
8117
+ }
8118
+ function normalizeScreenSnapshot(text) {
8119
+ return sanitizeTerminalText(String(text || "")).replace(/\s+/g, " ").trim();
8120
+ }
8121
+ function parsePatternEntry(x) {
8122
+ if (x instanceof RegExp) return x;
8123
+ if (x && typeof x === "object" && typeof x.source === "string") {
8124
+ try {
8125
+ const s = x;
8126
+ return new RegExp(s.source, s.flags || "");
8127
+ } catch {
8128
+ return null;
8129
+ }
8130
+ }
8131
+ return null;
8132
+ }
8133
+ function coercePatternArray(raw) {
8134
+ if (!Array.isArray(raw)) return [];
8135
+ return raw.map(parsePatternEntry).filter((r) => r != null);
8136
+ }
8137
+ function normalizeCliProviderForRuntime(raw) {
8138
+ const patterns = raw && typeof raw === "object" ? raw.patterns : void 0;
8139
+ return {
8140
+ patterns: {
8141
+ approval: coercePatternArray(
8142
+ patterns && typeof patterns === "object" ? patterns.approval : void 0
8143
+ )
8144
+ }
8145
+ };
8146
+ }
8147
+ var TerminalTranscriptAccumulator, buildCliSpawnEnv;
8148
+ var init_provider_cli_shared = __esm({
8149
+ "src/cli-adapters/provider-cli-shared.ts"() {
8150
+ "use strict";
8151
+ init_spawn_env();
8152
+ TerminalTranscriptAccumulator = class {
8153
+ lines = [[]];
8154
+ row = 0;
8155
+ col = 0;
8156
+ savedCursor = null;
8157
+ pendingEscape = "";
8158
+ append(data) {
8159
+ const input = this.pendingEscape + String(data || "");
8160
+ this.pendingEscape = "";
8161
+ for (let i = 0; i < input.length; i += 1) {
8162
+ let ch = input[i];
8163
+ if (ch === "\x1B") {
8164
+ const consumed = this.consumeEscape(input.slice(i));
8165
+ if (consumed === 0) {
8166
+ this.pendingEscape = input.slice(i);
8167
+ break;
8168
+ }
8169
+ i += consumed - 1;
8170
+ continue;
8171
+ }
8172
+ const cp = input.codePointAt(i);
8173
+ if (cp && cp > 65535) {
8174
+ ch = String.fromCodePoint(cp);
8175
+ i += 1;
8176
+ }
8177
+ this.writeControlOrChar(ch);
8178
+ }
8179
+ return this.getText();
8180
+ }
8181
+ reset() {
8182
+ this.lines = [[]];
8183
+ this.row = 0;
8184
+ this.col = 0;
8185
+ this.savedCursor = null;
8186
+ this.pendingEscape = "";
8187
+ }
8188
+ getText() {
8189
+ return this.lines.map((line) => line.join("").replace(/[ \t]+$/g, "")).join("\n");
8190
+ }
8191
+ ensureRow(row = this.row) {
8192
+ while (this.lines.length <= row) this.lines.push([]);
8193
+ }
8194
+ writeControlOrChar(ch) {
8195
+ if (ch === "\r") {
8196
+ this.col = 0;
8197
+ return;
8198
+ }
8199
+ if (ch === "\n") {
8200
+ this.row += 1;
8201
+ this.col = 0;
8202
+ this.ensureRow();
8203
+ return;
8204
+ }
8205
+ if (ch === "\b") {
8206
+ this.col = Math.max(0, this.col - 1);
8207
+ return;
8208
+ }
8209
+ if (ch < " " || ch === "\x7F") return;
8210
+ this.ensureRow();
8211
+ const line = this.lines[this.row];
8212
+ if (isCombiningMark(ch) && this.col > 0) {
8213
+ line[this.col - 1] = `${line[this.col - 1] || ""}${ch}`;
8214
+ return;
8215
+ }
8216
+ while (line.length < this.col) line.push(" ");
8217
+ const wide = isWideCodePoint(ch);
8218
+ line[this.col] = ch;
8219
+ if (wide) line[this.col + 1] = "";
8220
+ this.col += wide ? 2 : 1;
8221
+ }
8222
+ consumeEscape(seq) {
8223
+ if (seq.length < 2) return 0;
8224
+ const next = seq[1];
8225
+ if (next === "7") {
8226
+ this.savedCursor = { row: this.row, col: this.col };
8227
+ return 2;
8228
+ }
8229
+ if (next === "8") {
8230
+ if (this.savedCursor) {
8231
+ this.row = this.savedCursor.row;
8232
+ this.col = this.savedCursor.col;
8233
+ this.ensureRow();
8234
+ }
8235
+ return 2;
8236
+ }
8237
+ if (next === "]") {
8238
+ const bel = seq.indexOf("\x07", 2);
8239
+ const st = seq.indexOf("\x1B\\", 2);
8240
+ const end = bel >= 0 && (st < 0 || bel < st) ? bel + 1 : st >= 0 ? st + 2 : 0;
8241
+ return end;
8242
+ }
8243
+ if (next === "[") {
8244
+ const match = seq.match(/^\x1B\[([0-?]*)([ -/]*)([@-~])/);
8245
+ if (!match) return seq.length < 32 ? 0 : 1;
8246
+ this.applyCsi(match[1] || "", match[3]);
8247
+ return match[0].length;
8248
+ }
8249
+ if (/[P^_X]/.test(next)) {
8250
+ const bel = seq.indexOf("\x07", 2);
8251
+ const st = seq.indexOf("\x1B\\", 2);
8252
+ const end = bel >= 0 && (st < 0 || bel < st) ? bel + 1 : st >= 0 ? st + 2 : 0;
8253
+ return end;
8254
+ }
8255
+ return 2;
8256
+ }
8257
+ applyCsi(params, final) {
8258
+ const count = parseCount(params);
8259
+ this.ensureRow();
8260
+ if (final === "A") this.row = Math.max(0, this.row - count);
8261
+ else if (final === "B") this.row += count;
8262
+ else if (final === "C") {
8263
+ const line = this.lines[this.row];
8264
+ for (let c = this.col; c < this.col + count; c += 1) {
8265
+ if (line[c] === void 0) line[c] = " ";
8266
+ }
8267
+ this.col += count;
8268
+ } else if (final === "D") this.col = Math.max(0, this.col - count);
8269
+ else if (final === "G") this.col = Math.max(0, count - 1);
8270
+ else if (final === "H" || final === "f") {
8271
+ const parts = String(params || "").split(";");
8272
+ this.row = Math.max(0, (Number(parts[0] || 1) || 1) - 1);
8273
+ this.col = Math.max(0, (Number(parts[1] || 1) || 1) - 1);
8274
+ } else if (final === "J") {
8275
+ const mode = Number(params || 0) || 0;
8276
+ if (mode === 2 || mode === 3) {
8277
+ this.lines = [[]];
8278
+ this.row = 0;
8279
+ this.col = 0;
8280
+ } else if (mode === 0) {
8281
+ this.lines[this.row] = this.lines[this.row].slice(0, this.col);
8282
+ this.lines.splice(this.row + 1);
8283
+ } else if (mode === 1) {
8284
+ for (let r = 0; r < this.row; r += 1) this.lines[r] = [];
8285
+ const line = this.lines[this.row];
8286
+ for (let c = 0; c <= Math.min(this.col, line.length - 1); c += 1) line[c] = " ";
8287
+ }
8288
+ } else if (final === "K") {
8289
+ const mode = Number(params || 0) || 0;
8290
+ const line = this.lines[this.row];
8291
+ if (mode === 2) this.lines[this.row] = [];
8292
+ else if (mode === 1) {
8293
+ for (let c = 0; c <= Math.min(this.col, line.length - 1); c += 1) line[c] = " ";
8294
+ } else {
8295
+ this.lines[this.row] = line.slice(0, this.col);
8296
+ }
8297
+ } else if (final === "s") {
8298
+ this.savedCursor = { row: this.row, col: this.col };
8299
+ } else if (final === "u") {
8300
+ if (this.savedCursor) {
8301
+ this.row = this.savedCursor.row;
8302
+ this.col = this.savedCursor.col;
8303
+ }
8304
+ }
8305
+ this.ensureRow();
8306
+ }
8307
+ };
8308
+ buildCliSpawnEnv = sanitizeSpawnEnv;
8309
+ }
8310
+ });
8311
+
8312
+ // src/detection/cli-detector.ts
8313
+ import { exec } from "child_process";
8314
+ import * as os6 from "os";
8315
+ import * as path11 from "path";
7914
8316
  import { existsSync as existsSync13 } from "fs";
7915
8317
  function parseVersion(raw) {
7916
8318
  const match = raw.match(/v?(\d+\.\d+(?:\.\d+)?(?:-[a-zA-Z0-9.]+)?)/);
@@ -7923,22 +8325,31 @@ function shellQuote(value) {
7923
8325
  function expandHome(value) {
7924
8326
  const trimmed = value.trim();
7925
8327
  if (!trimmed.startsWith("~")) return trimmed;
7926
- return path10.join(os5.homedir(), trimmed.slice(1));
8328
+ return path11.join(os6.homedir(), trimmed.slice(1));
7927
8329
  }
7928
8330
  function isExplicitCommandPath(command) {
7929
8331
  const trimmed = command.trim();
7930
- return path10.isAbsolute(trimmed) || trimmed.includes("/") || trimmed.includes("\\") || trimmed.startsWith("~");
8332
+ return path11.isAbsolute(trimmed) || trimmed.includes("/") || trimmed.includes("\\") || trimmed.startsWith("~");
7931
8333
  }
7932
8334
  function resolveCommandPath(command) {
7933
8335
  const trimmed = command.trim();
7934
8336
  if (!trimmed) return null;
7935
8337
  if (isExplicitCommandPath(trimmed)) {
7936
8338
  const expanded = expandHome(trimmed);
7937
- const candidate = path10.isAbsolute(expanded) ? expanded : path10.resolve(expanded);
8339
+ const candidate = path11.isAbsolute(expanded) ? expanded : path11.resolve(expanded);
7938
8340
  return existsSync13(candidate) ? candidate : null;
7939
8341
  }
7940
8342
  return null;
7941
8343
  }
8344
+ async function resolveDetectionPath(command, whichCmd) {
8345
+ const explicitPath = resolveCommandPath(command);
8346
+ if (explicitPath) return explicitPath;
8347
+ const whichResult = await execAsync(`${whichCmd} ${shellQuote(command)}`);
8348
+ if (whichResult) return whichResult.split("\n")[0];
8349
+ const resolved = findBinary(command);
8350
+ if (path11.isAbsolute(resolved) && existsSync13(resolved)) return resolved;
8351
+ return null;
8352
+ }
7942
8353
  function execAsync(cmd, timeoutMs = 5e3) {
7943
8354
  return new Promise((resolve24) => {
7944
8355
  const child = exec(cmd, {
@@ -7956,17 +8367,15 @@ function execAsync(cmd, timeoutMs = 5e3) {
7956
8367
  });
7957
8368
  }
7958
8369
  async function detectCLIs(providerLoader, options) {
7959
- const platform10 = os5.platform();
8370
+ const platform10 = os6.platform();
7960
8371
  const whichCmd = platform10 === "win32" ? "where" : "which";
7961
8372
  const includeVersion = options?.includeVersion !== false;
7962
8373
  const cliList = providerLoader ? providerLoader.getCliDetectionList() : [];
7963
8374
  const results = await Promise.all(
7964
8375
  cliList.map(async (cli) => {
7965
8376
  try {
7966
- const explicitPath = resolveCommandPath(cli.command);
7967
- const pathResult = explicitPath || await execAsync(`${whichCmd} ${shellQuote(cli.command)}`);
7968
- if (!pathResult) return { ...cli, installed: false };
7969
- const firstPath = explicitPath || pathResult.split("\n")[0];
8377
+ const firstPath = await resolveDetectionPath(cli.command, whichCmd);
8378
+ if (!firstPath) return { ...cli, installed: false };
7970
8379
  let version;
7971
8380
  if (includeVersion) {
7972
8381
  const versionCommands = [
@@ -8000,13 +8409,11 @@ async function detectCLI(cliId, providerLoader, options) {
8000
8409
  const cliList = providerLoader.getCliDetectionList();
8001
8410
  const target = cliList.find((c) => c.id === resolvedId);
8002
8411
  if (target) {
8003
- const platform10 = os5.platform();
8412
+ const platform10 = os6.platform();
8004
8413
  const whichCmd = platform10 === "win32" ? "where" : "which";
8005
8414
  try {
8006
- const explicitPath = resolveCommandPath(target.command);
8007
- const pathResult = explicitPath || await execAsync(`${whichCmd} ${shellQuote(target.command)}`);
8008
- if (!pathResult) return null;
8009
- const firstPath = explicitPath || pathResult.split("\n")[0];
8415
+ const firstPath = await resolveDetectionPath(target.command, whichCmd);
8416
+ if (!firstPath) return null;
8010
8417
  let version;
8011
8418
  if (options?.includeVersion !== false) {
8012
8419
  const versionCommands = [
@@ -8038,6 +8445,7 @@ async function detectCLI(cliId, providerLoader, options) {
8038
8445
  var init_cli_detector = __esm({
8039
8446
  "src/detection/cli-detector.ts"() {
8040
8447
  "use strict";
8448
+ init_provider_cli_shared();
8041
8449
  }
8042
8450
  });
8043
8451
 
@@ -10641,19 +11049,19 @@ __export(external_sources_exports, {
10641
11049
  sourcesProviding: () => sourcesProviding
10642
11050
  });
10643
11051
  import * as fs8 from "fs";
10644
- import * as os10 from "os";
10645
- import * as path15 from "path";
11052
+ import * as os11 from "os";
11053
+ import * as path16 from "path";
10646
11054
  function adhdevDir() {
10647
- return path15.join(os10.homedir(), ".adhdev");
11055
+ return path16.join(os11.homedir(), ".adhdev");
10648
11056
  }
10649
11057
  function externalRoot() {
10650
- return path15.join(adhdevDir(), "external");
11058
+ return path16.join(adhdevDir(), "external");
10651
11059
  }
10652
11060
  function sourcesFilePath() {
10653
- return path15.join(adhdevDir(), SOURCES_FILENAME);
11061
+ return path16.join(adhdevDir(), SOURCES_FILENAME);
10654
11062
  }
10655
11063
  function activeFilePath() {
10656
- return path15.join(adhdevDir(), ACTIVE_FILENAME);
11064
+ return path16.join(adhdevDir(), ACTIVE_FILENAME);
10657
11065
  }
10658
11066
  function ensureAdhdevDir() {
10659
11067
  const d = adhdevDir();
@@ -10720,7 +11128,7 @@ function inventoryExternalSources() {
10720
11128
  for (const sourceEntry of entries) {
10721
11129
  if (!sourceEntry.isDirectory()) continue;
10722
11130
  const sourceName = sourceEntry.name;
10723
- const sourceDir = path15.join(root, sourceName);
11131
+ const sourceDir = path16.join(root, sourceName);
10724
11132
  const providers = {};
10725
11133
  let categoryEntries;
10726
11134
  try {
@@ -10731,7 +11139,7 @@ function inventoryExternalSources() {
10731
11139
  for (const categoryEntry of categoryEntries) {
10732
11140
  if (!categoryEntry.isDirectory()) continue;
10733
11141
  const category = categoryEntry.name;
10734
- const categoryDir = path15.join(sourceDir, category);
11142
+ const categoryDir = path16.join(sourceDir, category);
10735
11143
  let typeEntries;
10736
11144
  try {
10737
11145
  typeEntries = fs8.readdirSync(categoryDir, { withFileTypes: true });
@@ -10741,9 +11149,9 @@ function inventoryExternalSources() {
10741
11149
  const types = [];
10742
11150
  for (const typeEntry of typeEntries) {
10743
11151
  if (!typeEntry.isDirectory()) continue;
10744
- const typeDir = path15.join(categoryDir, typeEntry.name);
10745
- const hasV1 = fs8.existsSync(path15.join(typeDir, "provider.v1.json"));
10746
- const hasV0 = fs8.existsSync(path15.join(typeDir, "provider.json"));
11152
+ const typeDir = path16.join(categoryDir, typeEntry.name);
11153
+ const hasV1 = fs8.existsSync(path16.join(typeDir, "provider.v1.json"));
11154
+ const hasV0 = fs8.existsSync(path16.join(typeDir, "provider.json"));
10747
11155
  if (hasV1 || hasV0) types.push(typeEntry.name);
10748
11156
  }
10749
11157
  if (types.length > 0) providers[category] = types;
@@ -10947,27 +11355,34 @@ var init_terminal_screen = __esm({
10947
11355
  }
10948
11356
  });
10949
11357
 
10950
- // src/cli-adapters/spawn-env.ts
10951
- import {
10952
- sanitizeSpawnEnv,
10953
- applyTerminalColorEnv,
10954
- ensureNodePtySpawnHelperPermissions
10955
- } from "@adhdev/session-host-core";
10956
- var init_spawn_env = __esm({
10957
- "src/cli-adapters/spawn-env.ts"() {
10958
- "use strict";
10959
- }
10960
- });
10961
-
10962
11358
  // src/cli-adapters/resolve-executable.ts
10963
11359
  import { execFileSync } from "child_process";
10964
11360
  import { existsSync as existsSync20 } from "fs";
10965
- import * as path16 from "path";
11361
+ import * as path17 from "path";
11362
+ function resolveWin32GlobalBin(trimmed) {
11363
+ if (path17.isAbsolute(trimmed) || trimmed.includes("/") || trimmed.includes("\\")) {
11364
+ return null;
11365
+ }
11366
+ const extraDirs = [];
11367
+ if (process.env.APPDATA) extraDirs.push(path17.join(process.env.APPDATA, "npm"));
11368
+ try {
11369
+ extraDirs.push(path17.dirname(process.execPath));
11370
+ } catch {
11371
+ }
11372
+ for (const dir of extraDirs) {
11373
+ if (!dir) continue;
11374
+ for (const ext of WIN_EXEC_EXT) {
11375
+ const full = path17.join(dir, trimmed + ext);
11376
+ if (existsSync20(full)) return full;
11377
+ }
11378
+ }
11379
+ return null;
11380
+ }
10966
11381
  function resolveWin32Executable(command) {
10967
11382
  if (process.platform !== "win32") return command;
10968
11383
  const trimmed = (command || "").trim();
10969
11384
  if (!trimmed) return command;
10970
- if (path16.isAbsolute(trimmed) && existsSync20(trimmed)) return trimmed;
11385
+ if (path17.isAbsolute(trimmed) && existsSync20(trimmed)) return trimmed;
10971
11386
  try {
10972
11387
  const out = execFileSync("where", [trimmed], {
10973
11388
  encoding: "utf8",
@@ -10975,18 +11390,21 @@ function resolveWin32Executable(command) {
10975
11390
  }).trim();
10976
11391
  if (out) {
10977
11392
  const matches = out.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
10978
- const direct = matches.find((m) => DIRECT_EXEC_EXT.has(path16.extname(m).toLowerCase()));
11393
+ const direct = matches.find((m) => DIRECT_EXEC_EXT.has(path17.extname(m).toLowerCase()));
10979
11394
  return direct || matches[0] || command;
10980
11395
  }
10981
11396
  } catch {
10982
11397
  }
11398
+ const globalBin = resolveWin32GlobalBin(trimmed);
11399
+ if (globalBin) return globalBin;
10983
11400
  return command;
10984
11401
  }
10985
- var DIRECT_EXEC_EXT;
11402
+ var DIRECT_EXEC_EXT, WIN_EXEC_EXT;
10986
11403
  var init_resolve_executable = __esm({
10987
11404
  "src/cli-adapters/resolve-executable.ts"() {
10988
11405
  "use strict";
10989
11406
  DIRECT_EXEC_EXT = /* @__PURE__ */ new Set([".exe", ".com"]);
11407
+ WIN_EXEC_EXT = [".exe", ".com", ".cmd", ".bat"];
10990
11408
  }
10991
11409
  });
10992
11410
 
@@ -10995,7 +11413,7 @@ var pty_transport_exports = {};
10995
11413
  __export(pty_transport_exports, {
10996
11414
  NodePtyTransportFactory: () => NodePtyTransportFactory
10997
11415
  });
10998
- import * as os11 from "os";
11416
+ import * as os12 from "os";
10999
11417
  function loadNodePty() {
11000
11418
  if (cachedPty !== void 0) return cachedPty;
11001
11419
  try {
@@ -11049,9 +11467,9 @@ var init_pty_transport = __esm({
11049
11467
  try {
11050
11468
  const fs31 = __require("fs");
11051
11469
  const stat2 = fs31.statSync(cwd);
11052
- if (!stat2.isDirectory()) cwd = os11.homedir();
11470
+ if (!stat2.isDirectory()) cwd = os12.homedir();
11053
11471
  } catch {
11054
- cwd = os11.homedir();
11472
+ cwd = os12.homedir();
11055
11473
  }
11056
11474
  }
11057
11475
  const handle = pty.spawn(resolveWin32Executable(command), args, {
@@ -11067,396 +11485,6 @@ var init_pty_transport = __esm({
11067
11485
  }
11068
11486
  });
11069
11487
 
11070
- // src/cli-adapters/provider-cli-shared.ts
11071
- import * as os12 from "os";
11072
- import * as path17 from "path";
11073
- function stripAnsi(str) {
11074
- return str.replace(/\x1B\][^\x07]*(?:\x07|\x1B\\)/g, "").replace(/\x1B[P^_X][\s\S]*?(?:\x07|\x1B\\)/g, "").replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, "");
11075
- }
11076
- function parseCount(params, fallback = 1) {
11077
- const first = Number(String(params || "").split(";")[0] || fallback);
11078
- return Math.max(1, Number.isFinite(first) ? first : fallback);
11079
- }
11080
- function isCombiningMark(ch) {
11081
- return /[\u0300-\u036F\u1AB0-\u1AFF\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/.test(ch);
11082
- }
11083
- function isWideCodePoint(ch) {
11084
- const cp = ch.codePointAt(0) || 0;
11085
- return cp >= 4352 && (cp <= 4447 || cp === 9001 || cp === 9002 || cp >= 11904 && cp <= 42191 && cp !== 12351 || cp >= 44032 && cp <= 55203 || cp >= 63744 && cp <= 64255 || cp >= 65040 && cp <= 65049 || cp >= 65072 && cp <= 65135 || cp >= 65280 && cp <= 65376 || cp >= 65504 && cp <= 65510 || cp >= 127744 && cp <= 129791);
11086
- }
11087
- function stripTerminalNoise(str) {
11088
- return String(str || "").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/g, "").replace(/\r+/g, "\n").replace(/[ \t]+\n/g, "\n").replace(/\n{4,}/g, "\n\n\n");
11089
- }
11090
- function sanitizeTerminalText(str) {
11091
- const accumulator = new TerminalTranscriptAccumulator();
11092
- return stripTerminalNoise(stripAnsi(accumulator.append(str)));
11093
- }
11094
- function listCliScriptNames(scripts) {
11095
- if (!scripts) return [];
11096
- return Object.entries(scripts).filter(([, fn]) => typeof fn === "function").map(([name]) => name);
11097
- }
11098
- function splitCliScreenLines(text) {
11099
- return String(text || "").replace(/\u0007/g, "").replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n").map((line) => line.replace(/\s+$/, ""));
11100
- }
11101
- function isPromptLikeCliLine(line) {
11102
- const trimmed = String(line || "").trim();
11103
- if (!trimmed) return false;
11104
- return /^[❯›>]\s*(?:$|\S.*)$/.test(trimmed);
11105
- }
11106
- function buildCliScreenSnapshot(text) {
11107
- const normalizedText = String(text || "").replace(/\r\n/g, "\n").replace(/\r/g, "\n");
11108
- const rawLines = splitCliScreenLines(normalizedText);
11109
- const lines = rawLines.map((line, index, arr) => {
11110
- const trimmed = String(line || "").trim();
11111
- return {
11112
- index,
11113
- fromTop: index,
11114
- fromBottom: arr.length - index - 1,
11115
- text: line,
11116
- trimmed,
11117
- isEmpty: trimmed.length === 0
11118
- };
11119
- });
11120
- const nonEmptyLines = lines.filter((line) => !line.isEmpty);
11121
- const firstNonEmptyLine = nonEmptyLines[0] ?? null;
11122
- const lastNonEmptyLine = nonEmptyLines[nonEmptyLines.length - 1] ?? null;
11123
- let promptLineIndex = -1;
11124
- for (let i = lines.length - 1; i >= 0; i -= 1) {
11125
- if (isPromptLikeCliLine(lines[i].text)) {
11126
- promptLineIndex = i;
11127
- break;
11128
- }
11129
- }
11130
- return {
11131
- text: normalizedText,
11132
- lineCount: lines.length,
11133
- lines,
11134
- nonEmptyLines,
11135
- firstNonEmptyLineIndex: firstNonEmptyLine?.index ?? -1,
11136
- lastNonEmptyLineIndex: lastNonEmptyLine?.index ?? -1,
11137
- firstNonEmptyLine,
11138
- lastNonEmptyLine,
11139
- promptLineIndex,
11140
- promptLine: promptLineIndex >= 0 ? lines[promptLineIndex] : null,
11141
- linesAbovePrompt: promptLineIndex >= 0 ? lines.slice(0, promptLineIndex) : [...lines],
11142
- linesBelowPrompt: promptLineIndex >= 0 ? lines.slice(promptLineIndex + 1) : []
11143
- };
11144
- }
11145
- function findBinary(name) {
11146
- const trimmed = String(name || "").trim();
11147
- if (!trimmed) return trimmed;
11148
- const expanded = trimmed.startsWith("~") ? path17.join(os12.homedir(), trimmed.slice(1)) : trimmed;
11149
- if (path17.isAbsolute(expanded) || expanded.includes("/") || expanded.includes("\\")) {
11150
- return path17.isAbsolute(expanded) ? expanded : path17.resolve(expanded);
11151
- }
11152
- const isWin = os12.platform() === "win32";
11153
- const paths = (process.env.PATH || "").split(path17.delimiter);
11154
- const extraDirs = [];
11155
- if (isWin) {
11156
- if (process.env.APPDATA) extraDirs.push(path17.join(process.env.APPDATA, "npm"));
11157
- try {
11158
- extraDirs.push(path17.dirname(process.execPath));
11159
- } catch {
11160
- }
11161
- } else {
11162
- extraDirs.push(path17.join(os12.homedir(), ".npm-global", "bin"));
11163
- extraDirs.push("/usr/local/bin", "/opt/homebrew/bin");
11164
- try {
11165
- extraDirs.push(path17.dirname(process.execPath));
11166
- } catch {
11167
- }
11168
- }
11169
- const searchDirs = [...paths, ...extraDirs];
11170
- const exes = isWin ? [".exe", ".cmd", ".bat", ""] : [""];
11171
- for (const p of searchDirs) {
11172
- if (!p) continue;
11173
- for (const ext of exes) {
11174
- const fullPath = path17.join(p, trimmed + ext);
11175
- try {
11176
- const fs31 = __require("fs");
11177
- if (fs31.existsSync(fullPath)) {
11178
- const stat2 = fs31.statSync(fullPath);
11179
- if (stat2.isFile() && (isWin || stat2.mode & 73)) {
11180
- return fullPath;
11181
- }
11182
- }
11183
- } catch {
11184
- }
11185
- }
11186
- }
11187
- return isWin ? `${trimmed}.cmd` : trimmed;
11188
- }
11189
- function isScriptBinary(binaryPath) {
11190
- if (!path17.isAbsolute(binaryPath)) return false;
11191
- try {
11192
- const fs31 = __require("fs");
11193
- const resolved = fs31.realpathSync(binaryPath);
11194
- const head = Buffer.alloc(8);
11195
- const fd = fs31.openSync(resolved, "r");
11196
- fs31.readSync(fd, head, 0, 8, 0);
11197
- fs31.closeSync(fd);
11198
- let i = 0;
11199
- if (head[0] === 239 && head[1] === 187 && head[2] === 191) i = 3;
11200
- return head[i] === 35 && head[i + 1] === 33;
11201
- } catch {
11202
- return false;
11203
- }
11204
- }
11205
- function looksLikeMachOOrElf(filePath) {
11206
- if (!path17.isAbsolute(filePath)) return false;
11207
- try {
11208
- const fs31 = __require("fs");
11209
- const resolved = fs31.realpathSync(filePath);
11210
- const buf = Buffer.alloc(8);
11211
- const fd = fs31.openSync(resolved, "r");
11212
- fs31.readSync(fd, buf, 0, 8, 0);
11213
- fs31.closeSync(fd);
11214
- let i = 0;
11215
- if (buf[0] === 239 && buf[1] === 187 && buf[2] === 191) i = 3;
11216
- const b = buf.subarray(i);
11217
- if (b.length < 4) return false;
11218
- if (b[0] === 127 && b[1] === 69 && b[2] === 76 && b[3] === 70) return true;
11219
- const le = b.readUInt32LE(0);
11220
- const be = b.readUInt32BE(0);
11221
- const magics = [4277009102, 4277009103, 3405691582, 3199925962];
11222
- return magics.some((m) => m === le || m === be);
11223
- } catch {
11224
- return false;
11225
- }
11226
- }
11227
- function shSingleQuote(arg) {
11228
- if (/^[a-zA-Z0-9@%_+=:,./-]+$/.test(arg)) return arg;
11229
- if (os12.platform() === "win32") {
11230
- return `"${arg.replace(/"/g, '""')}"`;
11231
- }
11232
- return `'${arg.replace(/'/g, `'\\''`)}'`;
11233
- }
11234
- function estimatePromptDisplayLines(text, cols = 80) {
11235
- const normalized = String(text || "").replace(/\r/g, "");
11236
- if (!normalized) return 1;
11237
- return normalized.split("\n").reduce((sum, line) => sum + Math.max(1, Math.ceil(Math.max(1, line.length) / cols)), 0);
11238
- }
11239
- function extractPromptRetrySnippet(text) {
11240
- const lines = String(text || "").replace(/\r/g, "").split("\n").map((line) => line.trim()).filter(Boolean);
11241
- const candidate = lines[lines.length - 1] || lines[0] || "";
11242
- return candidate.slice(-120);
11243
- }
11244
- function normalizePromptText(text) {
11245
- return String(text || "").replace(/\s+/g, " ").trim();
11246
- }
11247
- function compactPromptText(text) {
11248
- return String(text || "").replace(/\s+/g, "").trim();
11249
- }
11250
- function promptLikelyVisible(screenText, promptSnippet) {
11251
- const snippet = normalizePromptText(promptSnippet);
11252
- if (!snippet) return false;
11253
- const normalizedScreen = normalizePromptText(screenText);
11254
- if (normalizedScreen.includes(snippet)) return true;
11255
- const compactScreen = compactPromptText(screenText);
11256
- const compactSnippet = compactPromptText(promptSnippet);
11257
- if (compactSnippet && compactScreen.includes(compactSnippet)) return true;
11258
- const tokens = snippet.split(/[^A-Za-z0-9_.:/-]+/).map((token) => token.trim()).filter((token) => token.length >= 4);
11259
- if (tokens.length === 0) return false;
11260
- const required = Math.min(tokens.length, 3);
11261
- const matched = tokens.filter(
11262
- (token) => normalizedScreen.includes(token) || compactScreen.includes(compactPromptText(token))
11263
- ).length;
11264
- return matched >= required;
11265
- }
11266
- function normalizeScreenSnapshot(text) {
11267
- return sanitizeTerminalText(String(text || "")).replace(/\s+/g, " ").trim();
11268
- }
11269
- function parsePatternEntry(x) {
11270
- if (x instanceof RegExp) return x;
11271
- if (x && typeof x === "object" && typeof x.source === "string") {
11272
- try {
11273
- const s = x;
11274
- return new RegExp(s.source, s.flags || "");
11275
- } catch {
11276
- return null;
11277
- }
11278
- }
11279
- return null;
11280
- }
11281
- function coercePatternArray(raw) {
11282
- if (!Array.isArray(raw)) return [];
11283
- return raw.map(parsePatternEntry).filter((r) => r != null);
11284
- }
11285
- function normalizeCliProviderForRuntime(raw) {
11286
- const patterns = raw && typeof raw === "object" ? raw.patterns : void 0;
11287
- return {
11288
- patterns: {
11289
- approval: coercePatternArray(
11290
- patterns && typeof patterns === "object" ? patterns.approval : void 0
11291
- )
11292
- }
11293
- };
11294
- }
11295
- var TerminalTranscriptAccumulator, buildCliSpawnEnv;
11296
- var init_provider_cli_shared = __esm({
11297
- "src/cli-adapters/provider-cli-shared.ts"() {
11298
- "use strict";
11299
- init_spawn_env();
11300
- TerminalTranscriptAccumulator = class {
11301
- lines = [[]];
11302
- row = 0;
11303
- col = 0;
11304
- savedCursor = null;
11305
- pendingEscape = "";
11306
- append(data) {
11307
- const input = this.pendingEscape + String(data || "");
11308
- this.pendingEscape = "";
11309
- for (let i = 0; i < input.length; i += 1) {
11310
- let ch = input[i];
11311
- if (ch === "\x1B") {
11312
- const consumed = this.consumeEscape(input.slice(i));
11313
- if (consumed === 0) {
11314
- this.pendingEscape = input.slice(i);
11315
- break;
11316
- }
11317
- i += consumed - 1;
11318
- continue;
11319
- }
11320
- const cp = input.codePointAt(i);
11321
- if (cp && cp > 65535) {
11322
- ch = String.fromCodePoint(cp);
11323
- i += 1;
11324
- }
11325
- this.writeControlOrChar(ch);
11326
- }
11327
- return this.getText();
11328
- }
11329
- reset() {
11330
- this.lines = [[]];
11331
- this.row = 0;
11332
- this.col = 0;
11333
- this.savedCursor = null;
11334
- this.pendingEscape = "";
11335
- }
11336
- getText() {
11337
- return this.lines.map((line) => line.join("").replace(/[ \t]+$/g, "")).join("\n");
11338
- }
11339
- ensureRow(row = this.row) {
11340
- while (this.lines.length <= row) this.lines.push([]);
11341
- }
11342
- writeControlOrChar(ch) {
11343
- if (ch === "\r") {
11344
- this.col = 0;
11345
- return;
11346
- }
11347
- if (ch === "\n") {
11348
- this.row += 1;
11349
- this.col = 0;
11350
- this.ensureRow();
11351
- return;
11352
- }
11353
- if (ch === "\b") {
11354
- this.col = Math.max(0, this.col - 1);
11355
- return;
11356
- }
11357
- if (ch < " " || ch === "\x7F") return;
11358
- this.ensureRow();
11359
- const line = this.lines[this.row];
11360
- if (isCombiningMark(ch) && this.col > 0) {
11361
- line[this.col - 1] = `${line[this.col - 1] || ""}${ch}`;
11362
- return;
11363
- }
11364
- while (line.length < this.col) line.push(" ");
11365
- const wide = isWideCodePoint(ch);
11366
- line[this.col] = ch;
11367
- if (wide) line[this.col + 1] = "";
11368
- this.col += wide ? 2 : 1;
11369
- }
11370
- consumeEscape(seq) {
11371
- if (seq.length < 2) return 0;
11372
- const next = seq[1];
11373
- if (next === "7") {
11374
- this.savedCursor = { row: this.row, col: this.col };
11375
- return 2;
11376
- }
11377
- if (next === "8") {
11378
- if (this.savedCursor) {
11379
- this.row = this.savedCursor.row;
11380
- this.col = this.savedCursor.col;
11381
- this.ensureRow();
11382
- }
11383
- return 2;
11384
- }
11385
- if (next === "]") {
11386
- const bel = seq.indexOf("\x07", 2);
11387
- const st = seq.indexOf("\x1B\\", 2);
11388
- const end = bel >= 0 && (st < 0 || bel < st) ? bel + 1 : st >= 0 ? st + 2 : 0;
11389
- return end;
11390
- }
11391
- if (next === "[") {
11392
- const match = seq.match(/^\x1B\[([0-?]*)([ -/]*)([@-~])/);
11393
- if (!match) return seq.length < 32 ? 0 : 1;
11394
- this.applyCsi(match[1] || "", match[3]);
11395
- return match[0].length;
11396
- }
11397
- if (/[P^_X]/.test(next)) {
11398
- const bel = seq.indexOf("\x07", 2);
11399
- const st = seq.indexOf("\x1B\\", 2);
11400
- const end = bel >= 0 && (st < 0 || bel < st) ? bel + 1 : st >= 0 ? st + 2 : 0;
11401
- return end;
11402
- }
11403
- return 2;
11404
- }
11405
- applyCsi(params, final) {
11406
- const count = parseCount(params);
11407
- this.ensureRow();
11408
- if (final === "A") this.row = Math.max(0, this.row - count);
11409
- else if (final === "B") this.row += count;
11410
- else if (final === "C") {
11411
- const line = this.lines[this.row];
11412
- for (let c = this.col; c < this.col + count; c += 1) {
11413
- if (line[c] === void 0) line[c] = " ";
11414
- }
11415
- this.col += count;
11416
- } else if (final === "D") this.col = Math.max(0, this.col - count);
11417
- else if (final === "G") this.col = Math.max(0, count - 1);
11418
- else if (final === "H" || final === "f") {
11419
- const parts = String(params || "").split(";");
11420
- this.row = Math.max(0, (Number(parts[0] || 1) || 1) - 1);
11421
- this.col = Math.max(0, (Number(parts[1] || 1) || 1) - 1);
11422
- } else if (final === "J") {
11423
- const mode = Number(params || 0) || 0;
11424
- if (mode === 2 || mode === 3) {
11425
- this.lines = [[]];
11426
- this.row = 0;
11427
- this.col = 0;
11428
- } else if (mode === 0) {
11429
- this.lines[this.row] = this.lines[this.row].slice(0, this.col);
11430
- this.lines.splice(this.row + 1);
11431
- } else if (mode === 1) {
11432
- for (let r = 0; r < this.row; r += 1) this.lines[r] = [];
11433
- const line = this.lines[this.row];
11434
- for (let c = 0; c <= Math.min(this.col, line.length - 1); c += 1) line[c] = " ";
11435
- }
11436
- } else if (final === "K") {
11437
- const mode = Number(params || 0) || 0;
11438
- const line = this.lines[this.row];
11439
- if (mode === 2) this.lines[this.row] = [];
11440
- else if (mode === 1) {
11441
- for (let c = 0; c <= Math.min(this.col, line.length - 1); c += 1) line[c] = " ";
11442
- } else {
11443
- this.lines[this.row] = line.slice(0, this.col);
11444
- }
11445
- } else if (final === "s") {
11446
- this.savedCursor = { row: this.row, col: this.col };
11447
- } else if (final === "u") {
11448
- if (this.savedCursor) {
11449
- this.row = this.savedCursor.row;
11450
- this.col = this.savedCursor.col;
11451
- }
11452
- }
11453
- this.ensureRow();
11454
- }
11455
- };
11456
- buildCliSpawnEnv = sanitizeSpawnEnv;
11457
- }
11458
- });
11459
-
11460
11488
  // src/providers/sdk/v1/builders/cli/visible-region.ts
11461
11489
  function compile(re, flags) {
11462
11490
  try {
@@ -18672,7 +18700,7 @@ var P2pRelayFailureError = class extends Error {
18672
18700
  // src/config/state-store.ts
18673
18701
  init_config();
18674
18702
  import { existsSync as existsSync15, readFileSync as readFileSync11, writeFileSync as writeFileSync7 } from "fs";
18675
- import { join as join15 } from "path";
18703
+ import { join as join16 } from "path";
18676
18704
  var DEFAULT_STATE = {
18677
18705
  recentActivity: [],
18678
18706
  savedProviderSessions: [],
@@ -18685,7 +18713,7 @@ function isPlainObject2(value) {
18685
18713
  return !!value && typeof value === "object" && !Array.isArray(value);
18686
18714
  }
18687
18715
  function getStatePath() {
18688
- return join15(getConfigDir(), "state.json");
18716
+ return join16(getConfigDir(), "state.json");
18689
18717
  }
18690
18718
  function normalizeState(raw) {
18691
18719
  const parsed = isPlainObject2(raw) ? raw : {};
@@ -18744,8 +18772,8 @@ function resetState() {
18744
18772
  import { exec as exec2 } from "child_process";
18745
18773
  import { promisify as promisify4 } from "util";
18746
18774
  import { existsSync as existsSync16, statSync as statSync6 } from "fs";
18747
- import { platform as platform2, homedir as homedir7 } from "os";
18748
- import * as path11 from "path";
18775
+ import { platform as platform3, homedir as homedir8 } from "os";
18776
+ import * as path12 from "path";
18749
18777
  var execAsync2 = promisify4(exec2);
18750
18778
  var BUILTIN_IDE_DEFINITIONS = [];
18751
18779
  var registeredIDEs = /* @__PURE__ */ new Map();
@@ -18765,18 +18793,18 @@ function getMergedDefinitions() {
18765
18793
  function findCliCommand(command) {
18766
18794
  const trimmed = String(command || "").trim();
18767
18795
  if (!trimmed) return null;
18768
- if (path11.isAbsolute(trimmed) || trimmed.includes("/") || trimmed.includes("\\") || trimmed.startsWith("~")) {
18769
- const candidate = trimmed.startsWith("~") ? path11.join(homedir7(), trimmed.slice(1)) : trimmed;
18770
- const resolved = path11.isAbsolute(candidate) ? candidate : path11.resolve(candidate);
18796
+ if (path12.isAbsolute(trimmed) || trimmed.includes("/") || trimmed.includes("\\") || trimmed.startsWith("~")) {
18797
+ const candidate = trimmed.startsWith("~") ? path12.join(homedir8(), trimmed.slice(1)) : trimmed;
18798
+ const resolved = path12.isAbsolute(candidate) ? candidate : path12.resolve(candidate);
18771
18799
  return existsSync16(resolved) ? resolved : null;
18772
18800
  }
18773
- const isWin = platform2() === "win32";
18801
+ const isWin = platform3() === "win32";
18774
18802
  const paths = (process.env.PATH || "").split(isWin ? ";" : ":");
18775
18803
  const exes = isWin ? [".exe", ".cmd", ".bat", ""] : [""];
18776
18804
  for (const p of paths) {
18777
18805
  if (!p) continue;
18778
18806
  for (const ext of exes) {
18779
- const fullPath = path11.join(p, trimmed + ext);
18807
+ const fullPath = path12.join(p, trimmed + ext);
18780
18808
  try {
18781
18809
  if (existsSync16(fullPath)) {
18782
18810
  const stat2 = statSync6(fullPath);
@@ -18802,9 +18830,9 @@ async function getIdeVersion(cliCommand) {
18802
18830
  }
18803
18831
  }
18804
18832
  function checkPathExists(paths) {
18805
- const home = homedir7();
18833
+ const home = homedir8();
18806
18834
  for (const p of paths) {
18807
- const normalized = p.startsWith("~") ? path11.join(home, p.slice(1)) : p;
18835
+ const normalized = p.startsWith("~") ? path12.join(home, p.slice(1)) : p;
18808
18836
  if (normalized.includes("*")) {
18809
18837
  const username = home.split(/[\\/]/).pop() || "";
18810
18838
  const resolved = normalized.replace("*", username);
@@ -18816,7 +18844,7 @@ function checkPathExists(paths) {
18816
18844
  return null;
18817
18845
  }
18818
18846
  async function detectIDEs(providerLoader) {
18819
- const os30 = platform2();
18847
+ const os30 = platform3();
18820
18848
  const results = [];
18821
18849
  for (const def of getMergedDefinitions()) {
18822
18850
  const cliPath = findCliCommand(providerLoader?.getIdeCliCommand(def.id, def.cli) || def.cli);
@@ -18827,8 +18855,8 @@ async function detectIDEs(providerLoader) {
18827
18855
  if (existsSync16(bundledCli)) resolvedCli = bundledCli;
18828
18856
  }
18829
18857
  if (!resolvedCli && appPath && os30 === "win32") {
18830
- const { dirname: dirname15 } = await import("path");
18831
- const appDir = dirname15(appPath);
18858
+ const { dirname: dirname16 } = await import("path");
18859
+ const appDir = dirname16(appPath);
18832
18860
  const candidates = [
18833
18861
  `${appDir}\\\\bin\\\\${def.cli}.cmd`,
18834
18862
  `${appDir}\\\\bin\\\\${def.cli}`,
@@ -18863,14 +18891,14 @@ async function detectIDEs(providerLoader) {
18863
18891
  init_cli_detector();
18864
18892
 
18865
18893
  // src/system/host-memory.ts
18866
- import * as os6 from "os";
18894
+ import * as os7 from "os";
18867
18895
  import { exec as exec3 } from "child_process";
18868
18896
  import { promisify as promisify5 } from "util";
18869
18897
  var execAsync3 = promisify5(exec3);
18870
18898
  var cachedDarwinAvail = null;
18871
18899
  var darwinMemoryInterval = null;
18872
18900
  async function updateDarwinMemoryCache() {
18873
- if (os6.platform() !== "darwin") return;
18901
+ if (os7.platform() !== "darwin") return;
18874
18902
  try {
18875
18903
  const { stdout } = await execAsync3("vm_stat", {
18876
18904
  encoding: "utf-8",
@@ -18894,19 +18922,19 @@ async function updateDarwinMemoryCache() {
18894
18922
  const fileBacked = counts["file_backed"] ?? 0;
18895
18923
  const availPages = free + inactive + speculative + purgeable + fileBacked;
18896
18924
  const bytes = availPages * pageSize;
18897
- cachedDarwinAvail = Number.isFinite(bytes) && bytes >= 0 ? Math.min(bytes, os6.totalmem()) : null;
18925
+ cachedDarwinAvail = Number.isFinite(bytes) && bytes >= 0 ? Math.min(bytes, os7.totalmem()) : null;
18898
18926
  } catch {
18899
18927
  }
18900
18928
  }
18901
18929
  function getHostMemorySnapshot() {
18902
- if (os6.platform() === "darwin" && !darwinMemoryInterval) {
18930
+ if (os7.platform() === "darwin" && !darwinMemoryInterval) {
18903
18931
  updateDarwinMemoryCache();
18904
18932
  darwinMemoryInterval = setInterval(updateDarwinMemoryCache, 3e3);
18905
18933
  darwinMemoryInterval.unref();
18906
18934
  }
18907
- const totalMem = os6.totalmem();
18908
- const freeMem = os6.freemem();
18909
- const availableMem = os6.platform() === "darwin" ? cachedDarwinAvail ?? freeMem : freeMem;
18935
+ const totalMem = os7.totalmem();
18936
+ const freeMem = os7.freemem();
18937
+ const availableMem = os7.platform() === "darwin" ? cachedDarwinAvail ?? freeMem : freeMem;
18910
18938
  return {
18911
18939
  totalMem,
18912
18940
  freeMem,
@@ -21268,9 +21296,9 @@ ${cleanBody}`;
21268
21296
 
21269
21297
  // src/config/chat-history.ts
21270
21298
  import * as fs5 from "fs";
21271
- import * as path12 from "path";
21272
- import * as os7 from "os";
21273
- var HISTORY_DIR = path12.join(os7.homedir(), ".adhdev", "history");
21299
+ import * as path13 from "path";
21300
+ import * as os8 from "os";
21301
+ var HISTORY_DIR = path13.join(os8.homedir(), ".adhdev", "history");
21274
21302
  var RETAIN_DAYS = 30;
21275
21303
  var SAVED_HISTORY_INDEX_VERSION = 1;
21276
21304
  var SAVED_HISTORY_INDEX_FILE = ".saved-history-index.json";
@@ -21456,7 +21484,7 @@ function extractSavedHistorySessionIdFromFile(file) {
21456
21484
  function buildSavedHistoryFileSignatureMap(dir, files) {
21457
21485
  return new Map(files.map((file) => {
21458
21486
  try {
21459
- const stat2 = fs5.statSync(path12.join(dir, file));
21487
+ const stat2 = fs5.statSync(path13.join(dir, file));
21460
21488
  return [file, `${file}:${stat2.size}:${Math.trunc(stat2.mtimeMs)}`];
21461
21489
  } catch {
21462
21490
  return [file, `${file}:missing`];
@@ -21467,7 +21495,7 @@ function buildSavedHistoryCacheSignature(files, fileSignatures) {
21467
21495
  return files.map((file) => fileSignatures.get(file) || `${file}:missing`).join("|");
21468
21496
  }
21469
21497
  function getSavedHistoryIndexFilePath(dir) {
21470
- return path12.join(dir, SAVED_HISTORY_INDEX_FILE);
21498
+ return path13.join(dir, SAVED_HISTORY_INDEX_FILE);
21471
21499
  }
21472
21500
  function getSavedHistoryIndexLockPath(dir) {
21473
21501
  return `${getSavedHistoryIndexFilePath(dir)}${SAVED_HISTORY_INDEX_LOCK_SUFFIX}`;
@@ -21569,7 +21597,7 @@ function savePersistedSavedHistoryIndex(dir, entries) {
21569
21597
  }
21570
21598
  for (const file of Array.from(currentEntries.keys())) {
21571
21599
  if (incomingFiles.has(file)) continue;
21572
- if (!fs5.existsSync(path12.join(dir, file))) {
21600
+ if (!fs5.existsSync(path13.join(dir, file))) {
21573
21601
  currentEntries.delete(file);
21574
21602
  }
21575
21603
  }
@@ -21595,7 +21623,7 @@ function historyDirectoryHasFilesNewerThanIndex(dir) {
21595
21623
  const indexStat = fs5.statSync(getSavedHistoryIndexFilePath(dir));
21596
21624
  const files = listHistoryFiles(dir);
21597
21625
  for (const file of files) {
21598
- const stat2 = fs5.statSync(path12.join(dir, file));
21626
+ const stat2 = fs5.statSync(path13.join(dir, file));
21599
21627
  if (stat2.mtimeMs > indexStat.mtimeMs) return true;
21600
21628
  }
21601
21629
  return false;
@@ -21605,14 +21633,14 @@ function historyDirectoryHasFilesNewerThanIndex(dir) {
21605
21633
  }
21606
21634
  function buildSavedHistoryFileSignature(dir, file) {
21607
21635
  try {
21608
- const stat2 = fs5.statSync(path12.join(dir, file));
21636
+ const stat2 = fs5.statSync(path13.join(dir, file));
21609
21637
  return `${file}:${stat2.size}:${Math.trunc(stat2.mtimeMs)}`;
21610
21638
  } catch {
21611
21639
  return `${file}:missing`;
21612
21640
  }
21613
21641
  }
21614
21642
  function persistSavedHistoryFileSummaryEntry(agentType, dir, file, updater) {
21615
- const filePath = path12.join(dir, file);
21643
+ const filePath = path13.join(dir, file);
21616
21644
  const result = withLockedPersistedSavedHistoryIndex(dir, (entries) => {
21617
21645
  const currentEntry = entries.get(file) || null;
21618
21646
  const nextSummary = updater(currentEntry?.summary || null);
@@ -21685,7 +21713,7 @@ function updateSavedHistoryIndexForAppendedMessages(agentType, dir, file, histor
21685
21713
  function computeSavedHistoryFileSummary(dir, file) {
21686
21714
  const historySessionId = extractSavedHistorySessionIdFromFile(file);
21687
21715
  if (!historySessionId) return null;
21688
- const filePath = path12.join(dir, file);
21716
+ const filePath = path13.join(dir, file);
21689
21717
  const content = fs5.readFileSync(filePath, "utf-8");
21690
21718
  const lines = content.split("\n").filter(Boolean);
21691
21719
  let messageCount = 0;
@@ -21772,7 +21800,7 @@ function computeSavedHistorySessionSummaries(agentType, dir, files, fileSignatur
21772
21800
  const summaryBySessionId = /* @__PURE__ */ new Map();
21773
21801
  const nextPersistedEntries = /* @__PURE__ */ new Map();
21774
21802
  for (const file of files.slice().sort()) {
21775
- const filePath = path12.join(dir, file);
21803
+ const filePath = path13.join(dir, file);
21776
21804
  const signature = fileSignatures.get(file) || `${file}:missing`;
21777
21805
  const cached2 = savedHistoryFileSummaryCache.get(filePath);
21778
21806
  const persisted = persistedEntries.get(file);
@@ -21892,12 +21920,12 @@ var ChatHistoryWriter = class {
21892
21920
  });
21893
21921
  }
21894
21922
  if (newMessages.length === 0) return;
21895
- const dir = path12.join(HISTORY_DIR, this.sanitize(agentType));
21923
+ const dir = path13.join(HISTORY_DIR, this.sanitize(agentType));
21896
21924
  fs5.mkdirSync(dir, { recursive: true });
21897
21925
  const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
21898
21926
  const filePrefix = effectiveHistoryKey ? `${this.sanitize(effectiveHistoryKey)}_` : "";
21899
21927
  const fileName = `${filePrefix}${date}.jsonl`;
21900
- const filePath = path12.join(dir, fileName);
21928
+ const filePath = path13.join(dir, fileName);
21901
21929
  const lines = newMessages.map((m) => JSON.stringify(m)).join("\n") + "\n";
21902
21930
  fs5.appendFileSync(filePath, lines, "utf-8");
21903
21931
  updateSavedHistoryIndexForAppendedMessages(agentType, dir, fileName, effectiveHistoryKey, newMessages);
@@ -21988,11 +22016,11 @@ var ChatHistoryWriter = class {
21988
22016
  const ws = String(workspace || "").trim();
21989
22017
  if (!id || !ws) return;
21990
22018
  try {
21991
- const dir = path12.join(HISTORY_DIR, this.sanitize(agentType));
22019
+ const dir = path13.join(HISTORY_DIR, this.sanitize(agentType));
21992
22020
  fs5.mkdirSync(dir, { recursive: true });
21993
22021
  const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
21994
22022
  const fileName = `${this.sanitize(id)}_${date}.jsonl`;
21995
- const filePath = path12.join(dir, fileName);
22023
+ const filePath = path13.join(dir, fileName);
21996
22024
  const record = {
21997
22025
  ts: (/* @__PURE__ */ new Date()).toISOString(),
21998
22026
  receivedAt: Date.now(),
@@ -22038,14 +22066,14 @@ var ChatHistoryWriter = class {
22038
22066
  this.lastSeenCounts.set(toDedupKey, Math.max(fromCount, this.lastSeenCounts.get(toDedupKey) || 0));
22039
22067
  this.lastSeenCounts.delete(fromDedupKey);
22040
22068
  }
22041
- const dir = path12.join(HISTORY_DIR, this.sanitize(agentType));
22069
+ const dir = path13.join(HISTORY_DIR, this.sanitize(agentType));
22042
22070
  if (!fs5.existsSync(dir)) return;
22043
22071
  const fromPrefix = `${this.sanitize(fromId)}_`;
22044
22072
  const toPrefix = `${this.sanitize(toId)}_`;
22045
22073
  const files = fs5.readdirSync(dir).filter((file) => file.startsWith(fromPrefix) && file.endsWith(".jsonl"));
22046
22074
  for (const file of files) {
22047
- const sourcePath = path12.join(dir, file);
22048
- const targetPath = path12.join(dir, `${toPrefix}${file.slice(fromPrefix.length)}`);
22075
+ const sourcePath = path13.join(dir, file);
22076
+ const targetPath = path13.join(dir, `${toPrefix}${file.slice(fromPrefix.length)}`);
22049
22077
  const sourceLines = fs5.readFileSync(sourcePath, "utf-8").split("\n").filter(Boolean);
22050
22078
  const rewritten = sourceLines.map((line) => {
22051
22079
  try {
@@ -22079,13 +22107,13 @@ var ChatHistoryWriter = class {
22079
22107
  const sessionId = String(historySessionId || "").trim();
22080
22108
  if (!sessionId) return;
22081
22109
  try {
22082
- const dir = path12.join(HISTORY_DIR, this.sanitize(agentType));
22110
+ const dir = path13.join(HISTORY_DIR, this.sanitize(agentType));
22083
22111
  if (!fs5.existsSync(dir)) return;
22084
22112
  const prefix = `${this.sanitize(sessionId)}_`;
22085
22113
  const files = fs5.readdirSync(dir).filter((file) => file.startsWith(prefix) && file.endsWith(".jsonl")).sort();
22086
22114
  const seen = /* @__PURE__ */ new Set();
22087
22115
  for (const file of files) {
22088
- const filePath = path12.join(dir, file);
22116
+ const filePath = path13.join(dir, file);
22089
22117
  const lines = fs5.readFileSync(filePath, "utf-8").split("\n").filter(Boolean);
22090
22118
  const next = [];
22091
22119
  for (const line of lines) {
@@ -22139,11 +22167,11 @@ var ChatHistoryWriter = class {
22139
22167
  const cutoff = Date.now() - RETAIN_DAYS * 24 * 60 * 60 * 1e3;
22140
22168
  const agentDirs = fs5.readdirSync(HISTORY_DIR, { withFileTypes: true }).filter((d) => d.isDirectory());
22141
22169
  for (const dir of agentDirs) {
22142
- const dirPath = path12.join(HISTORY_DIR, dir.name);
22170
+ const dirPath = path13.join(HISTORY_DIR, dir.name);
22143
22171
  const files = fs5.readdirSync(dirPath).filter((f) => f.endsWith(".jsonl") || f.endsWith(".terminal.log"));
22144
22172
  let removedAny = false;
22145
22173
  for (const file of files) {
22146
- const filePath = path12.join(dirPath, file);
22174
+ const filePath = path13.join(dirPath, file);
22147
22175
  const stat2 = fs5.statSync(filePath);
22148
22176
  if (stat2.mtimeMs < cutoff) {
22149
22177
  fs5.unlinkSync(filePath);
@@ -22346,7 +22374,7 @@ function readBoundedTailRecords(agentType, dir, files, needed) {
22346
22374
  const seen = /* @__PURE__ */ new Set();
22347
22375
  let readAllFiles = true;
22348
22376
  for (let f = 0; f < files.length; f++) {
22349
- const filePath = path12.join(dir, files[f]);
22377
+ const filePath = path13.join(dir, files[f]);
22350
22378
  const remaining = Math.max(0, needed - collected.length);
22351
22379
  const perFileNeeded = Math.min(needed, remaining + BOUNDED_TAIL_SLACK);
22352
22380
  const { lines, coversWholeFile } = readFileTailLines(filePath, perFileNeeded);
@@ -22379,7 +22407,7 @@ function readBoundedTailRecords(agentType, dir, files, needed) {
22379
22407
  function readChatHistory(agentType, offset = 0, limit = 30, historySessionId, excludeRecentCount = 0, historyBehavior) {
22380
22408
  try {
22381
22409
  const sanitized = agentType.replace(/[^a-zA-Z0-9_-]/g, "_");
22382
- const dir = path12.join(HISTORY_DIR, sanitized);
22410
+ const dir = path13.join(HISTORY_DIR, sanitized);
22383
22411
  if (!fs5.existsSync(dir)) return { messages: [], hasMore: false };
22384
22412
  const files = listHistoryFiles(dir, historySessionId);
22385
22413
  const bounded = isBoundedTailRequest(limit, offset, excludeRecentCount);
@@ -22402,7 +22430,7 @@ function readChatHistory(agentType, offset = 0, limit = 30, historySessionId, ex
22402
22430
  const allMessages = [];
22403
22431
  const seen = /* @__PURE__ */ new Set();
22404
22432
  for (const file of files) {
22405
- const filePath = path12.join(dir, file);
22433
+ const filePath = path13.join(dir, file);
22406
22434
  const content = fs5.readFileSync(filePath, "utf-8");
22407
22435
  const lines = content.trim().split("\n").filter(Boolean);
22408
22436
  for (let i = 0; i < lines.length; i++) {
@@ -22426,7 +22454,7 @@ function readChatHistory(agentType, offset = 0, limit = 30, historySessionId, ex
22426
22454
  function listSavedHistorySessions(agentType, options = {}, historyBehavior) {
22427
22455
  try {
22428
22456
  const sanitized = agentType.replace(/[^a-zA-Z0-9_-]/g, "_");
22429
- const dir = path12.join(HISTORY_DIR, sanitized);
22457
+ const dir = path13.join(HISTORY_DIR, sanitized);
22430
22458
  if (!fs5.existsSync(dir)) {
22431
22459
  savedHistorySessionCache.delete(sanitized);
22432
22460
  return { sessions: [], hasMore: false };
@@ -22487,11 +22515,11 @@ function listSavedHistorySessions(agentType, options = {}, historyBehavior) {
22487
22515
  }
22488
22516
  function readExistingSessionStartRecord(agentType, historySessionId) {
22489
22517
  try {
22490
- const dir = path12.join(HISTORY_DIR, agentType);
22518
+ const dir = path13.join(HISTORY_DIR, agentType);
22491
22519
  if (!fs5.existsSync(dir)) return null;
22492
22520
  const files = listHistoryFiles(dir, historySessionId).sort();
22493
22521
  for (const file of files) {
22494
- const lines = fs5.readFileSync(path12.join(dir, file), "utf-8").split("\n").filter(Boolean);
22522
+ const lines = fs5.readFileSync(path13.join(dir, file), "utf-8").split("\n").filter(Boolean);
22495
22523
  for (const line of lines) {
22496
22524
  try {
22497
22525
  const parsed = JSON.parse(line);
@@ -22511,16 +22539,16 @@ function readExistingSessionStartRecord(agentType, historySessionId) {
22511
22539
  function rewriteCanonicalSavedHistory(agentType, historySessionId, records) {
22512
22540
  if (records.length === 0) return false;
22513
22541
  try {
22514
- const dir = path12.join(HISTORY_DIR, agentType);
22542
+ const dir = path13.join(HISTORY_DIR, agentType);
22515
22543
  fs5.mkdirSync(dir, { recursive: true });
22516
22544
  const prefix = `${historySessionId.replace(/[^a-zA-Z0-9_-]/g, "_")}_`;
22517
22545
  for (const file of fs5.readdirSync(dir)) {
22518
22546
  if (file.startsWith(prefix) && file.endsWith(".jsonl")) {
22519
- fs5.unlinkSync(path12.join(dir, file));
22547
+ fs5.unlinkSync(path13.join(dir, file));
22520
22548
  }
22521
22549
  }
22522
22550
  const targetDate = new Date(records[records.length - 1].receivedAt || Date.now()).toISOString().slice(0, 10);
22523
- const filePath = path12.join(dir, `${prefix}${targetDate}.jsonl`);
22551
+ const filePath = path13.join(dir, `${prefix}${targetDate}.jsonl`);
22524
22552
  fs5.writeFileSync(filePath, `${records.map((record) => JSON.stringify(record)).join("\n")}
22525
22553
  `, "utf-8");
22526
22554
  invalidatePersistedSavedHistoryIndex(agentType, dir);
@@ -25115,8 +25143,8 @@ function resolveLegacyProviderScript(fn, scriptName, params) {
25115
25143
 
25116
25144
  // src/commands/chat-commands.ts
25117
25145
  import * as fs6 from "fs";
25118
- import * as os8 from "os";
25119
- import * as path13 from "path";
25146
+ import * as os9 from "os";
25147
+ import * as path14 from "path";
25120
25148
  import { randomUUID as randomUUID11 } from "crypto";
25121
25149
  init_logger();
25122
25150
 
@@ -26165,7 +26193,7 @@ function readExactRuntimeMirrorMessages(args) {
26165
26193
  function normalizeComparableWorkspace(value) {
26166
26194
  const text = typeof value === "string" ? value.trim() : "";
26167
26195
  if (!text) return "";
26168
- return path13.resolve(text);
26196
+ return path14.resolve(text);
26169
26197
  }
26170
26198
  function isCurrentRuntimePtySafelyAttributed(args) {
26171
26199
  if (args.adapter.cliType !== "codex-cli") return false;
@@ -26650,7 +26678,7 @@ function buildDebugBundleText(bundle) {
26650
26678
  }
26651
26679
  function getChatDebugBundleDir() {
26652
26680
  const override = typeof process.env.ADHDEV_DEBUG_BUNDLE_DIR === "string" ? process.env.ADHDEV_DEBUG_BUNDLE_DIR.trim() : "";
26653
- return override || path13.join(os8.homedir(), ".adhdev", "debug-bundles", "chat");
26681
+ return override || path14.join(os9.homedir(), ".adhdev", "debug-bundles", "chat");
26654
26682
  }
26655
26683
  function safeBundleIdSegment(value, fallback) {
26656
26684
  const normalized = String(value || fallback).trim().replace(/[^A-Za-z0-9_.-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80);
@@ -26707,7 +26735,7 @@ function storeChatDebugBundleOnDaemon(bundle, targetSessionId) {
26707
26735
  const bundleId = createChatDebugBundleId(targetSessionId);
26708
26736
  const dir = getChatDebugBundleDir();
26709
26737
  fs6.mkdirSync(dir, { recursive: true });
26710
- const savedPath = path13.join(dir, `${bundleId}.json`);
26738
+ const savedPath = path14.join(dir, `${bundleId}.json`);
26711
26739
  const json = `${JSON.stringify(bundle, null, 2)}
26712
26740
  `;
26713
26741
  fs6.writeFileSync(savedPath, json, { encoding: "utf8", mode: 384 });
@@ -28271,8 +28299,8 @@ async function handleResolveAction(h, args) {
28271
28299
 
28272
28300
  // src/commands/cdp-commands.ts
28273
28301
  import * as fs7 from "fs";
28274
- import * as path14 from "path";
28275
- import * as os9 from "os";
28302
+ import * as path15 from "path";
28303
+ import * as os10 from "os";
28276
28304
  var KEY_TO_VK = {
28277
28305
  Backspace: 8,
28278
28306
  Tab: 9,
@@ -28526,27 +28554,27 @@ function normalizeWindowsRequestedPath(requestedPath) {
28526
28554
  function resolveSafePath(requestedPath) {
28527
28555
  const rawPath = typeof requestedPath === "string" ? requestedPath.trim() : "";
28528
28556
  const inputPath = rawPath || ".";
28529
- const home = os9.homedir();
28557
+ const home = os10.homedir();
28530
28558
  if (inputPath.startsWith("~")) {
28531
- return path14.resolve(path14.join(home, inputPath.slice(1)));
28559
+ return path15.resolve(path15.join(home, inputPath.slice(1)));
28532
28560
  }
28533
28561
  if (process.platform === "win32") {
28534
28562
  const normalized = normalizeWindowsRequestedPath(inputPath);
28535
- if (path14.win32.isAbsolute(normalized)) {
28536
- return path14.win32.normalize(normalized);
28563
+ if (path15.win32.isAbsolute(normalized)) {
28564
+ return path15.win32.normalize(normalized);
28537
28565
  }
28538
- return path14.win32.resolve(normalized);
28566
+ return path15.win32.resolve(normalized);
28539
28567
  }
28540
- if (path14.isAbsolute(inputPath)) {
28541
- return path14.normalize(inputPath);
28568
+ if (path15.isAbsolute(inputPath)) {
28569
+ return path15.normalize(inputPath);
28542
28570
  }
28543
- return path14.resolve(inputPath);
28571
+ return path15.resolve(inputPath);
28544
28572
  }
28545
28573
  function listDirectoryEntriesSafe(dirPath) {
28546
28574
  const entries = fs7.readdirSync(dirPath, { withFileTypes: true });
28547
28575
  const files = [];
28548
28576
  for (const entry of entries) {
28549
- const entryPath = path14.join(dirPath, entry.name);
28577
+ const entryPath = path15.join(dirPath, entry.name);
28550
28578
  try {
28551
28579
  if (entry.isDirectory()) {
28552
28580
  files.push({ name: entry.name, type: "directory" });
@@ -28600,7 +28628,7 @@ async function handleFileRead(h, args) {
28600
28628
  async function handleFileWrite(h, args) {
28601
28629
  try {
28602
28630
  const filePath = resolveSafePath(args?.path);
28603
- fs7.mkdirSync(path14.dirname(filePath), { recursive: true });
28631
+ fs7.mkdirSync(path15.dirname(filePath), { recursive: true });
28604
28632
  fs7.writeFileSync(filePath, args?.content || "", "utf-8");
28605
28633
  return { success: true, path: filePath };
28606
28634
  } catch (e) {
@@ -41436,7 +41464,7 @@ init_mesh_refine_status();
41436
41464
 
41437
41465
  // src/mesh/mesh-init.ts
41438
41466
  import { existsSync as existsSync35, mkdirSync as mkdirSync15, writeFileSync as writeFileSync17 } from "fs";
41439
- import { dirname as dirname8, join as join37 } from "path";
41467
+ import { dirname as dirname9, join as join38 } from "path";
41440
41468
  var MESH_INIT_REFINE_CONFIG_PATH = MESH_REFINE_CONFIG_LOCATIONS[0];
41441
41469
  var MESH_INIT_WORKTREE_BOOTSTRAP_CONFIG_PATH = MESH_WORKTREE_BOOTSTRAP_CONFIG_LOCATIONS[0];
41442
41470
  var CANDIDATE_STALE_INPUTS = [
@@ -41450,22 +41478,22 @@ var CANDIDATE_STALE_INPUTS = [
41450
41478
  "requirements.txt"
41451
41479
  ];
41452
41480
  function writeConfigFile(workspace, relativePath, config) {
41453
- const target = join37(workspace, relativePath);
41454
- mkdirSync15(dirname8(target), { recursive: true });
41481
+ const target = join38(workspace, relativePath);
41482
+ mkdirSync15(dirname9(target), { recursive: true });
41455
41483
  writeFileSync17(target, `${JSON.stringify(config, null, 2)}
41456
41484
  `, "utf-8");
41457
41485
  return target;
41458
41486
  }
41459
41487
  function suggestMeshWorktreeBootstrapConfig(workspace) {
41460
41488
  const commands = [];
41461
- const hasPackageJson = existsSync35(join37(workspace, "package.json"));
41462
- const hasNpmLock = existsSync35(join37(workspace, "package-lock.json"));
41489
+ const hasPackageJson = existsSync35(join38(workspace, "package.json"));
41490
+ const hasNpmLock = existsSync35(join38(workspace, "package-lock.json"));
41463
41491
  if (hasPackageJson) {
41464
41492
  commands.push(
41465
41493
  hasNpmLock ? { command: "npm", args: ["ci"] } : { command: "npm", args: ["install"] }
41466
41494
  );
41467
41495
  }
41468
- const staleInputs = CANDIDATE_STALE_INPUTS.filter((relative5) => existsSync35(join37(workspace, relative5)));
41496
+ const staleInputs = CANDIDATE_STALE_INPUTS.filter((relative5) => existsSync35(join38(workspace, relative5)));
41469
41497
  if (!commands.length) {
41470
41498
  return { commands, staleInputs };
41471
41499
  }
@@ -41533,7 +41561,7 @@ function runMeshInit(mesh, workspace, detected, options = {}) {
41533
41561
  }
41534
41562
  function applyConfigSuggestion(input) {
41535
41563
  const { workspace, relativePath, existing, suggestedConfig, validate, write, overwrite } = input;
41536
- const absolute = join37(workspace, relativePath);
41564
+ const absolute = join38(workspace, relativePath);
41537
41565
  if (existing !== void 0 && !overwrite) {
41538
41566
  return { path: absolute, relativePath, written: false, skippedReason: "already_exists", config: existing };
41539
41567
  }
@@ -48861,7 +48889,7 @@ ${ptyResult.output.slice(-2e3)}`);
48861
48889
  };
48862
48890
  }
48863
48891
  const { existsSync: existsSync44, readFileSync: readFileSync35, writeFileSync: writeFileSync23, copyFileSync: copyFileSync4, mkdirSync: mkdirSync21 } = await import("fs");
48864
- const { dirname: dirname15 } = await import("path");
48892
+ const { dirname: dirname16 } = await import("path");
48865
48893
  const mcpConfigPath = coordinatorSetup.configPath;
48866
48894
  const hermesManualFallback = cliType === "hermes-cli" && configFormat === "hermes_config_yaml" ? createHermesManualMeshCoordinatorSetup(meshId, workspace) : null;
48867
48895
  let hermesBaseConfig = null;
@@ -48896,7 +48924,7 @@ ${ptyResult.output.slice(-2e3)}`);
48896
48924
  };
48897
48925
  }
48898
48926
  try {
48899
- mkdirSync21(dirname15(mcpConfigPath), { recursive: true });
48927
+ mkdirSync21(dirname16(mcpConfigPath), { recursive: true });
48900
48928
  } catch (error) {
48901
48929
  const message = `Could not prepare MCP config path for automatic setup: ${error?.message || error}`;
48902
48930
  LOG.error("MeshCoordinator", message);
@@ -48906,7 +48934,7 @@ ${ptyResult.output.slice(-2e3)}`);
48906
48934
  const hadExistingMcpConfig = existsSync44(mcpConfigPath);
48907
48935
  let existingMcpConfig = hermesBaseConfig?.config || {};
48908
48936
  if (hermesBaseConfig) {
48909
- copyHermesCoordinatorCredentialFiles(hermesBaseConfig.sourceHome, dirname15(mcpConfigPath));
48937
+ copyHermesCoordinatorCredentialFiles(hermesBaseConfig.sourceHome, dirname16(mcpConfigPath));
48910
48938
  }
48911
48939
  if (hadExistingMcpConfig) {
48912
48940
  try {
@@ -48944,7 +48972,7 @@ ${ptyResult.output.slice(-2e3)}`);
48944
48972
  const cliArgs = [];
48945
48973
  const launchEnv = {};
48946
48974
  if (configFormat === "hermes_config_yaml") {
48947
- launchEnv.HERMES_HOME = dirname15(mcpConfigPath);
48975
+ launchEnv.HERMES_HOME = dirname16(mcpConfigPath);
48948
48976
  launchEnv.HERMES_IGNORE_USER_CONFIG = "";
48949
48977
  }
48950
48978
  let autoImportContextFilePath;
@@ -57969,11 +57997,11 @@ init_parse_session();
57969
57997
  // src/providers/sdk/v1/fixture-tooling/replay.ts
57970
57998
  init_provider_cli_shared();
57971
57999
  import { readFileSync as readFileSync33 } from "fs";
57972
- import { dirname as dirname13, resolve as resolve22 } from "path";
58000
+ import { dirname as dirname14, resolve as resolve22 } from "path";
57973
58001
 
57974
58002
  // src/providers/sdk/v1/validators/taint.ts
57975
58003
  import { readFileSync as readFileSync34, existsSync as existsSync43 } from "fs";
57976
- import { resolve as resolve23, dirname as dirname14, join as join44 } from "path";
58004
+ import { resolve as resolve23, dirname as dirname15, join as join45 } from "path";
57977
58005
 
57978
58006
  // src/providers/sdk/v1/validators/index.ts
57979
58007
  init_manifest();