@adhdev/daemon-standalone 0.7.42 → 0.7.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -283,10 +283,10 @@ function mergeDefs(...defs) {
283
283
  function cloneDef(schema) {
284
284
  return mergeDefs(schema._zod.def);
285
285
  }
286
- function getElementAtPath(obj, path18) {
287
- if (!path18)
286
+ function getElementAtPath(obj, path19) {
287
+ if (!path19)
288
288
  return obj;
289
- return path18.reduce((acc, key) => acc?.[key], obj);
289
+ return path19.reduce((acc, key) => acc?.[key], obj);
290
290
  }
291
291
  function promiseAllObject(promisesObj) {
292
292
  const keys = Object.keys(promisesObj);
@@ -598,11 +598,11 @@ function aborted(x, startIndex = 0) {
598
598
  }
599
599
  return false;
600
600
  }
601
- function prefixIssues(path18, issues) {
601
+ function prefixIssues(path19, issues) {
602
602
  return issues.map((iss) => {
603
603
  var _a2;
604
604
  (_a2 = iss).path ?? (_a2.path = []);
605
- iss.path.unshift(path18);
605
+ iss.path.unshift(path19);
606
606
  return iss;
607
607
  });
608
608
  }
@@ -845,7 +845,7 @@ function formatError(error48, mapper = (issue2) => issue2.message) {
845
845
  }
846
846
  function treeifyError(error48, mapper = (issue2) => issue2.message) {
847
847
  const result = { errors: [] };
848
- const processError = (error49, path18 = []) => {
848
+ const processError = (error49, path19 = []) => {
849
849
  var _a2, _b;
850
850
  for (const issue2 of error49.issues) {
851
851
  if (issue2.code === "invalid_union" && issue2.errors.length) {
@@ -855,7 +855,7 @@ function treeifyError(error48, mapper = (issue2) => issue2.message) {
855
855
  } else if (issue2.code === "invalid_element") {
856
856
  processError({ issues: issue2.issues }, issue2.path);
857
857
  } else {
858
- const fullpath = [...path18, ...issue2.path];
858
+ const fullpath = [...path19, ...issue2.path];
859
859
  if (fullpath.length === 0) {
860
860
  result.errors.push(mapper(issue2));
861
861
  continue;
@@ -887,8 +887,8 @@ function treeifyError(error48, mapper = (issue2) => issue2.message) {
887
887
  }
888
888
  function toDotPath(_path) {
889
889
  const segs = [];
890
- const path18 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
891
- for (const seg of path18) {
890
+ const path19 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
891
+ for (const seg of path19) {
892
892
  if (typeof seg === "number")
893
893
  segs.push(`[${seg}]`);
894
894
  else if (typeof seg === "symbol")
@@ -13652,13 +13652,13 @@ function resolveRef(ref, ctx) {
13652
13652
  if (!ref.startsWith("#")) {
13653
13653
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
13654
13654
  }
13655
- const path18 = ref.slice(1).split("/").filter(Boolean);
13656
- if (path18.length === 0) {
13655
+ const path19 = ref.slice(1).split("/").filter(Boolean);
13656
+ if (path19.length === 0) {
13657
13657
  return ctx.rootSchema;
13658
13658
  }
13659
13659
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
13660
- if (path18[0] === defsKey) {
13661
- const key = path18[1];
13660
+ if (path19[0] === defsKey) {
13661
+ const key = path19[1];
13662
13662
  if (!key || !ctx.defs[key]) {
13663
13663
  throw new Error(`Reference not found: ${ref}`);
13664
13664
  }
@@ -16334,9 +16334,9 @@ var init_acp = __esm({
16334
16334
  // src/index.ts
16335
16335
  var import_http = require("http");
16336
16336
  var import_ws2 = require("ws");
16337
- var path17 = __toESM(require("path"));
16338
- var fs12 = __toESM(require("fs"));
16339
- var os17 = __toESM(require("os"));
16337
+ var path18 = __toESM(require("path"));
16338
+ var fs13 = __toESM(require("fs"));
16339
+ var os18 = __toESM(require("os"));
16340
16340
 
16341
16341
  // ../daemon-core/dist/index.mjs
16342
16342
  var import_os = require("os");
@@ -16346,9 +16346,9 @@ var import_crypto2 = require("crypto");
16346
16346
  var fs2 = __toESM(require("fs"), 1);
16347
16347
  var path3 = __toESM(require("path"), 1);
16348
16348
  var os4 = __toESM(require("os"), 1);
16349
- var os11 = __toESM(require("os"), 1);
16350
16349
  var os12 = __toESM(require("os"), 1);
16351
- var path9 = __toESM(require("path"), 1);
16350
+ var os13 = __toESM(require("os"), 1);
16351
+ var path10 = __toESM(require("path"), 1);
16352
16352
  var import_child_process = require("child_process");
16353
16353
  var fs = __toESM(require("fs"), 1);
16354
16354
  var os2 = __toESM(require("os"), 1);
@@ -16469,7 +16469,7 @@ var ReaddirpStream = class extends import_node_stream.Readable {
16469
16469
  this._directoryFilter = normalizeFilter(opts.directoryFilter);
16470
16470
  const statMethod = opts.lstat ? import_promises.lstat : import_promises.stat;
16471
16471
  if (wantBigintFsStats) {
16472
- this._stat = (path18) => statMethod(path18, { bigint: true });
16472
+ this._stat = (path19) => statMethod(path19, { bigint: true });
16473
16473
  } else {
16474
16474
  this._stat = statMethod;
16475
16475
  }
@@ -16494,8 +16494,8 @@ var ReaddirpStream = class extends import_node_stream.Readable {
16494
16494
  const par = this.parent;
16495
16495
  const fil = par && par.files;
16496
16496
  if (fil && fil.length > 0) {
16497
- const { path: path18, depth } = par;
16498
- const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path18));
16497
+ const { path: path19, depth } = par;
16498
+ const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path19));
16499
16499
  const awaited = await Promise.all(slice);
16500
16500
  for (const entry of awaited) {
16501
16501
  if (!entry)
@@ -16535,20 +16535,20 @@ var ReaddirpStream = class extends import_node_stream.Readable {
16535
16535
  this.reading = false;
16536
16536
  }
16537
16537
  }
16538
- async _exploreDir(path18, depth) {
16538
+ async _exploreDir(path19, depth) {
16539
16539
  let files;
16540
16540
  try {
16541
- files = await (0, import_promises.readdir)(path18, this._rdOptions);
16541
+ files = await (0, import_promises.readdir)(path19, this._rdOptions);
16542
16542
  } catch (error48) {
16543
16543
  this._onError(error48);
16544
16544
  }
16545
- return { files, depth, path: path18 };
16545
+ return { files, depth, path: path19 };
16546
16546
  }
16547
- async _formatEntry(dirent, path18) {
16547
+ async _formatEntry(dirent, path19) {
16548
16548
  let entry;
16549
16549
  const basename7 = this._isDirent ? dirent.name : dirent;
16550
16550
  try {
16551
- const fullPath = (0, import_node_path.resolve)((0, import_node_path.join)(path18, basename7));
16551
+ const fullPath = (0, import_node_path.resolve)((0, import_node_path.join)(path19, basename7));
16552
16552
  entry = { path: (0, import_node_path.relative)(this._root, fullPath), fullPath, basename: basename7 };
16553
16553
  entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
16554
16554
  } catch (err) {
@@ -16948,16 +16948,16 @@ var delFromSet = (main2, prop, item) => {
16948
16948
  };
16949
16949
  var isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
16950
16950
  var FsWatchInstances = /* @__PURE__ */ new Map();
16951
- function createFsWatchInstance(path18, options, listener, errHandler, emitRaw) {
16951
+ function createFsWatchInstance(path19, options, listener, errHandler, emitRaw) {
16952
16952
  const handleEvent = (rawEvent, evPath) => {
16953
- listener(path18);
16954
- emitRaw(rawEvent, evPath, { watchedPath: path18 });
16955
- if (evPath && path18 !== evPath) {
16956
- fsWatchBroadcast(sp.resolve(path18, evPath), KEY_LISTENERS, sp.join(path18, evPath));
16953
+ listener(path19);
16954
+ emitRaw(rawEvent, evPath, { watchedPath: path19 });
16955
+ if (evPath && path19 !== evPath) {
16956
+ fsWatchBroadcast(sp.resolve(path19, evPath), KEY_LISTENERS, sp.join(path19, evPath));
16957
16957
  }
16958
16958
  };
16959
16959
  try {
16960
- return (0, import_node_fs.watch)(path18, {
16960
+ return (0, import_node_fs.watch)(path19, {
16961
16961
  persistent: options.persistent
16962
16962
  }, handleEvent);
16963
16963
  } catch (error48) {
@@ -16973,12 +16973,12 @@ var fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
16973
16973
  listener(val1, val2, val3);
16974
16974
  });
16975
16975
  };
16976
- var setFsWatchListener = (path18, fullPath, options, handlers) => {
16976
+ var setFsWatchListener = (path19, fullPath, options, handlers) => {
16977
16977
  const { listener, errHandler, rawEmitter } = handlers;
16978
16978
  let cont = FsWatchInstances.get(fullPath);
16979
16979
  let watcher;
16980
16980
  if (!options.persistent) {
16981
- watcher = createFsWatchInstance(path18, options, listener, errHandler, rawEmitter);
16981
+ watcher = createFsWatchInstance(path19, options, listener, errHandler, rawEmitter);
16982
16982
  if (!watcher)
16983
16983
  return;
16984
16984
  return watcher.close.bind(watcher);
@@ -16989,7 +16989,7 @@ var setFsWatchListener = (path18, fullPath, options, handlers) => {
16989
16989
  addAndConvert(cont, KEY_RAW, rawEmitter);
16990
16990
  } else {
16991
16991
  watcher = createFsWatchInstance(
16992
- path18,
16992
+ path19,
16993
16993
  options,
16994
16994
  fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
16995
16995
  errHandler,
@@ -17004,7 +17004,7 @@ var setFsWatchListener = (path18, fullPath, options, handlers) => {
17004
17004
  cont.watcherUnusable = true;
17005
17005
  if (isWindows && error48.code === "EPERM") {
17006
17006
  try {
17007
- const fd = await (0, import_promises2.open)(path18, "r");
17007
+ const fd = await (0, import_promises2.open)(path19, "r");
17008
17008
  await fd.close();
17009
17009
  broadcastErr(error48);
17010
17010
  } catch (err) {
@@ -17035,7 +17035,7 @@ var setFsWatchListener = (path18, fullPath, options, handlers) => {
17035
17035
  };
17036
17036
  };
17037
17037
  var FsWatchFileInstances = /* @__PURE__ */ new Map();
17038
- var setFsWatchFileListener = (path18, fullPath, options, handlers) => {
17038
+ var setFsWatchFileListener = (path19, fullPath, options, handlers) => {
17039
17039
  const { listener, rawEmitter } = handlers;
17040
17040
  let cont = FsWatchFileInstances.get(fullPath);
17041
17041
  const copts = cont && cont.options;
@@ -17057,7 +17057,7 @@ var setFsWatchFileListener = (path18, fullPath, options, handlers) => {
17057
17057
  });
17058
17058
  const currmtime = curr.mtimeMs;
17059
17059
  if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
17060
- foreach(cont.listeners, (listener2) => listener2(path18, curr));
17060
+ foreach(cont.listeners, (listener2) => listener2(path19, curr));
17061
17061
  }
17062
17062
  })
17063
17063
  };
@@ -17087,13 +17087,13 @@ var NodeFsHandler = class {
17087
17087
  * @param listener on fs change
17088
17088
  * @returns closer for the watcher instance
17089
17089
  */
17090
- _watchWithNodeFs(path18, listener) {
17090
+ _watchWithNodeFs(path19, listener) {
17091
17091
  const opts = this.fsw.options;
17092
- const directory = sp.dirname(path18);
17093
- const basename7 = sp.basename(path18);
17092
+ const directory = sp.dirname(path19);
17093
+ const basename7 = sp.basename(path19);
17094
17094
  const parent = this.fsw._getWatchedDir(directory);
17095
17095
  parent.add(basename7);
17096
- const absolutePath = sp.resolve(path18);
17096
+ const absolutePath = sp.resolve(path19);
17097
17097
  const options = {
17098
17098
  persistent: opts.persistent
17099
17099
  };
@@ -17103,12 +17103,12 @@ var NodeFsHandler = class {
17103
17103
  if (opts.usePolling) {
17104
17104
  const enableBin = opts.interval !== opts.binaryInterval;
17105
17105
  options.interval = enableBin && isBinaryPath(basename7) ? opts.binaryInterval : opts.interval;
17106
- closer = setFsWatchFileListener(path18, absolutePath, options, {
17106
+ closer = setFsWatchFileListener(path19, absolutePath, options, {
17107
17107
  listener,
17108
17108
  rawEmitter: this.fsw._emitRaw
17109
17109
  });
17110
17110
  } else {
17111
- closer = setFsWatchListener(path18, absolutePath, options, {
17111
+ closer = setFsWatchListener(path19, absolutePath, options, {
17112
17112
  listener,
17113
17113
  errHandler: this._boundHandleError,
17114
17114
  rawEmitter: this.fsw._emitRaw
@@ -17130,7 +17130,7 @@ var NodeFsHandler = class {
17130
17130
  let prevStats = stats;
17131
17131
  if (parent.has(basename7))
17132
17132
  return;
17133
- const listener = async (path18, newStats) => {
17133
+ const listener = async (path19, newStats) => {
17134
17134
  if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file2, 5))
17135
17135
  return;
17136
17136
  if (!newStats || newStats.mtimeMs === 0) {
@@ -17144,11 +17144,11 @@ var NodeFsHandler = class {
17144
17144
  this.fsw._emit(EV.CHANGE, file2, newStats2);
17145
17145
  }
17146
17146
  if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats2.ino) {
17147
- this.fsw._closeFile(path18);
17147
+ this.fsw._closeFile(path19);
17148
17148
  prevStats = newStats2;
17149
17149
  const closer2 = this._watchWithNodeFs(file2, listener);
17150
17150
  if (closer2)
17151
- this.fsw._addPathCloser(path18, closer2);
17151
+ this.fsw._addPathCloser(path19, closer2);
17152
17152
  } else {
17153
17153
  prevStats = newStats2;
17154
17154
  }
@@ -17180,7 +17180,7 @@ var NodeFsHandler = class {
17180
17180
  * @param item basename of this item
17181
17181
  * @returns true if no more processing is needed for this entry.
17182
17182
  */
17183
- async _handleSymlink(entry, directory, path18, item) {
17183
+ async _handleSymlink(entry, directory, path19, item) {
17184
17184
  if (this.fsw.closed) {
17185
17185
  return;
17186
17186
  }
@@ -17190,7 +17190,7 @@ var NodeFsHandler = class {
17190
17190
  this.fsw._incrReadyCount();
17191
17191
  let linkPath;
17192
17192
  try {
17193
- linkPath = await (0, import_promises2.realpath)(path18);
17193
+ linkPath = await (0, import_promises2.realpath)(path19);
17194
17194
  } catch (e) {
17195
17195
  this.fsw._emitReady();
17196
17196
  return true;
@@ -17200,12 +17200,12 @@ var NodeFsHandler = class {
17200
17200
  if (dir.has(item)) {
17201
17201
  if (this.fsw._symlinkPaths.get(full) !== linkPath) {
17202
17202
  this.fsw._symlinkPaths.set(full, linkPath);
17203
- this.fsw._emit(EV.CHANGE, path18, entry.stats);
17203
+ this.fsw._emit(EV.CHANGE, path19, entry.stats);
17204
17204
  }
17205
17205
  } else {
17206
17206
  dir.add(item);
17207
17207
  this.fsw._symlinkPaths.set(full, linkPath);
17208
- this.fsw._emit(EV.ADD, path18, entry.stats);
17208
+ this.fsw._emit(EV.ADD, path19, entry.stats);
17209
17209
  }
17210
17210
  this.fsw._emitReady();
17211
17211
  return true;
@@ -17235,9 +17235,9 @@ var NodeFsHandler = class {
17235
17235
  return;
17236
17236
  }
17237
17237
  const item = entry.path;
17238
- let path18 = sp.join(directory, item);
17238
+ let path19 = sp.join(directory, item);
17239
17239
  current.add(item);
17240
- if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path18, item)) {
17240
+ if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path19, item)) {
17241
17241
  return;
17242
17242
  }
17243
17243
  if (this.fsw.closed) {
@@ -17246,8 +17246,8 @@ var NodeFsHandler = class {
17246
17246
  }
17247
17247
  if (item === target || !target && !previous.has(item)) {
17248
17248
  this.fsw._incrReadyCount();
17249
- path18 = sp.join(dir, sp.relative(dir, path18));
17250
- this._addToNodeFs(path18, initialAdd, wh, depth + 1);
17249
+ path19 = sp.join(dir, sp.relative(dir, path19));
17250
+ this._addToNodeFs(path19, initialAdd, wh, depth + 1);
17251
17251
  }
17252
17252
  }).on(EV.ERROR, this._boundHandleError);
17253
17253
  return new Promise((resolve12, reject) => {
@@ -17316,13 +17316,13 @@ var NodeFsHandler = class {
17316
17316
  * @param depth Child path actually targeted for watch
17317
17317
  * @param target Child path actually targeted for watch
17318
17318
  */
17319
- async _addToNodeFs(path18, initialAdd, priorWh, depth, target) {
17319
+ async _addToNodeFs(path19, initialAdd, priorWh, depth, target) {
17320
17320
  const ready = this.fsw._emitReady;
17321
- if (this.fsw._isIgnored(path18) || this.fsw.closed) {
17321
+ if (this.fsw._isIgnored(path19) || this.fsw.closed) {
17322
17322
  ready();
17323
17323
  return false;
17324
17324
  }
17325
- const wh = this.fsw._getWatchHelpers(path18);
17325
+ const wh = this.fsw._getWatchHelpers(path19);
17326
17326
  if (priorWh) {
17327
17327
  wh.filterPath = (entry) => priorWh.filterPath(entry);
17328
17328
  wh.filterDir = (entry) => priorWh.filterDir(entry);
@@ -17338,8 +17338,8 @@ var NodeFsHandler = class {
17338
17338
  const follow = this.fsw.options.followSymlinks;
17339
17339
  let closer;
17340
17340
  if (stats.isDirectory()) {
17341
- const absPath = sp.resolve(path18);
17342
- const targetPath = follow ? await (0, import_promises2.realpath)(path18) : path18;
17341
+ const absPath = sp.resolve(path19);
17342
+ const targetPath = follow ? await (0, import_promises2.realpath)(path19) : path19;
17343
17343
  if (this.fsw.closed)
17344
17344
  return;
17345
17345
  closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
@@ -17349,29 +17349,29 @@ var NodeFsHandler = class {
17349
17349
  this.fsw._symlinkPaths.set(absPath, targetPath);
17350
17350
  }
17351
17351
  } else if (stats.isSymbolicLink()) {
17352
- const targetPath = follow ? await (0, import_promises2.realpath)(path18) : path18;
17352
+ const targetPath = follow ? await (0, import_promises2.realpath)(path19) : path19;
17353
17353
  if (this.fsw.closed)
17354
17354
  return;
17355
17355
  const parent = sp.dirname(wh.watchPath);
17356
17356
  this.fsw._getWatchedDir(parent).add(wh.watchPath);
17357
17357
  this.fsw._emit(EV.ADD, wh.watchPath, stats);
17358
- closer = await this._handleDir(parent, stats, initialAdd, depth, path18, wh, targetPath);
17358
+ closer = await this._handleDir(parent, stats, initialAdd, depth, path19, wh, targetPath);
17359
17359
  if (this.fsw.closed)
17360
17360
  return;
17361
17361
  if (targetPath !== void 0) {
17362
- this.fsw._symlinkPaths.set(sp.resolve(path18), targetPath);
17362
+ this.fsw._symlinkPaths.set(sp.resolve(path19), targetPath);
17363
17363
  }
17364
17364
  } else {
17365
17365
  closer = this._handleFile(wh.watchPath, stats, initialAdd);
17366
17366
  }
17367
17367
  ready();
17368
17368
  if (closer)
17369
- this.fsw._addPathCloser(path18, closer);
17369
+ this.fsw._addPathCloser(path19, closer);
17370
17370
  return false;
17371
17371
  } catch (error48) {
17372
17372
  if (this.fsw._handleError(error48)) {
17373
17373
  ready();
17374
- return path18;
17374
+ return path19;
17375
17375
  }
17376
17376
  }
17377
17377
  }
@@ -17414,24 +17414,24 @@ function createPattern(matcher) {
17414
17414
  }
17415
17415
  return () => false;
17416
17416
  }
17417
- function normalizePath(path18) {
17418
- if (typeof path18 !== "string")
17417
+ function normalizePath(path19) {
17418
+ if (typeof path19 !== "string")
17419
17419
  throw new Error("string expected");
17420
- path18 = sp2.normalize(path18);
17421
- path18 = path18.replace(/\\/g, "/");
17420
+ path19 = sp2.normalize(path19);
17421
+ path19 = path19.replace(/\\/g, "/");
17422
17422
  let prepend = false;
17423
- if (path18.startsWith("//"))
17423
+ if (path19.startsWith("//"))
17424
17424
  prepend = true;
17425
- path18 = path18.replace(DOUBLE_SLASH_RE, "/");
17425
+ path19 = path19.replace(DOUBLE_SLASH_RE, "/");
17426
17426
  if (prepend)
17427
- path18 = "/" + path18;
17428
- return path18;
17427
+ path19 = "/" + path19;
17428
+ return path19;
17429
17429
  }
17430
17430
  function matchPatterns(patterns, testString, stats) {
17431
- const path18 = normalizePath(testString);
17431
+ const path19 = normalizePath(testString);
17432
17432
  for (let index = 0; index < patterns.length; index++) {
17433
17433
  const pattern = patterns[index];
17434
- if (pattern(path18, stats)) {
17434
+ if (pattern(path19, stats)) {
17435
17435
  return true;
17436
17436
  }
17437
17437
  }
@@ -17469,19 +17469,19 @@ var toUnix = (string4) => {
17469
17469
  }
17470
17470
  return str;
17471
17471
  };
17472
- var normalizePathToUnix = (path18) => toUnix(sp2.normalize(toUnix(path18)));
17473
- var normalizeIgnored = (cwd = "") => (path18) => {
17474
- if (typeof path18 === "string") {
17475
- return normalizePathToUnix(sp2.isAbsolute(path18) ? path18 : sp2.join(cwd, path18));
17472
+ var normalizePathToUnix = (path19) => toUnix(sp2.normalize(toUnix(path19)));
17473
+ var normalizeIgnored = (cwd = "") => (path19) => {
17474
+ if (typeof path19 === "string") {
17475
+ return normalizePathToUnix(sp2.isAbsolute(path19) ? path19 : sp2.join(cwd, path19));
17476
17476
  } else {
17477
- return path18;
17477
+ return path19;
17478
17478
  }
17479
17479
  };
17480
- var getAbsolutePath = (path18, cwd) => {
17481
- if (sp2.isAbsolute(path18)) {
17482
- return path18;
17480
+ var getAbsolutePath = (path19, cwd) => {
17481
+ if (sp2.isAbsolute(path19)) {
17482
+ return path19;
17483
17483
  }
17484
- return sp2.join(cwd, path18);
17484
+ return sp2.join(cwd, path19);
17485
17485
  };
17486
17486
  var EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set());
17487
17487
  var DirEntry = class {
@@ -17546,10 +17546,10 @@ var WatchHelper = class {
17546
17546
  dirParts;
17547
17547
  followSymlinks;
17548
17548
  statMethod;
17549
- constructor(path18, follow, fsw) {
17549
+ constructor(path19, follow, fsw) {
17550
17550
  this.fsw = fsw;
17551
- const watchPath = path18;
17552
- this.path = path18 = path18.replace(REPLACER_RE, "");
17551
+ const watchPath = path19;
17552
+ this.path = path19 = path19.replace(REPLACER_RE, "");
17553
17553
  this.watchPath = watchPath;
17554
17554
  this.fullWatchPath = sp2.resolve(watchPath);
17555
17555
  this.dirParts = [];
@@ -17689,20 +17689,20 @@ var FSWatcher = class extends import_node_events.EventEmitter {
17689
17689
  this._closePromise = void 0;
17690
17690
  let paths = unifyPaths(paths_);
17691
17691
  if (cwd) {
17692
- paths = paths.map((path18) => {
17693
- const absPath = getAbsolutePath(path18, cwd);
17692
+ paths = paths.map((path19) => {
17693
+ const absPath = getAbsolutePath(path19, cwd);
17694
17694
  return absPath;
17695
17695
  });
17696
17696
  }
17697
- paths.forEach((path18) => {
17698
- this._removeIgnoredPath(path18);
17697
+ paths.forEach((path19) => {
17698
+ this._removeIgnoredPath(path19);
17699
17699
  });
17700
17700
  this._userIgnored = void 0;
17701
17701
  if (!this._readyCount)
17702
17702
  this._readyCount = 0;
17703
17703
  this._readyCount += paths.length;
17704
- Promise.all(paths.map(async (path18) => {
17705
- const res = await this._nodeFsHandler._addToNodeFs(path18, !_internal, void 0, 0, _origAdd);
17704
+ Promise.all(paths.map(async (path19) => {
17705
+ const res = await this._nodeFsHandler._addToNodeFs(path19, !_internal, void 0, 0, _origAdd);
17706
17706
  if (res)
17707
17707
  this._emitReady();
17708
17708
  return res;
@@ -17724,17 +17724,17 @@ var FSWatcher = class extends import_node_events.EventEmitter {
17724
17724
  return this;
17725
17725
  const paths = unifyPaths(paths_);
17726
17726
  const { cwd } = this.options;
17727
- paths.forEach((path18) => {
17728
- if (!sp2.isAbsolute(path18) && !this._closers.has(path18)) {
17727
+ paths.forEach((path19) => {
17728
+ if (!sp2.isAbsolute(path19) && !this._closers.has(path19)) {
17729
17729
  if (cwd)
17730
- path18 = sp2.join(cwd, path18);
17731
- path18 = sp2.resolve(path18);
17730
+ path19 = sp2.join(cwd, path19);
17731
+ path19 = sp2.resolve(path19);
17732
17732
  }
17733
- this._closePath(path18);
17734
- this._addIgnoredPath(path18);
17735
- if (this._watched.has(path18)) {
17733
+ this._closePath(path19);
17734
+ this._addIgnoredPath(path19);
17735
+ if (this._watched.has(path19)) {
17736
17736
  this._addIgnoredPath({
17737
- path: path18,
17737
+ path: path19,
17738
17738
  recursive: true
17739
17739
  });
17740
17740
  }
@@ -17798,38 +17798,38 @@ var FSWatcher = class extends import_node_events.EventEmitter {
17798
17798
  * @param stats arguments to be passed with event
17799
17799
  * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
17800
17800
  */
17801
- async _emit(event, path18, stats) {
17801
+ async _emit(event, path19, stats) {
17802
17802
  if (this.closed)
17803
17803
  return;
17804
17804
  const opts = this.options;
17805
17805
  if (isWindows)
17806
- path18 = sp2.normalize(path18);
17806
+ path19 = sp2.normalize(path19);
17807
17807
  if (opts.cwd)
17808
- path18 = sp2.relative(opts.cwd, path18);
17809
- const args = [path18];
17808
+ path19 = sp2.relative(opts.cwd, path19);
17809
+ const args = [path19];
17810
17810
  if (stats != null)
17811
17811
  args.push(stats);
17812
17812
  const awf = opts.awaitWriteFinish;
17813
17813
  let pw;
17814
- if (awf && (pw = this._pendingWrites.get(path18))) {
17814
+ if (awf && (pw = this._pendingWrites.get(path19))) {
17815
17815
  pw.lastChange = /* @__PURE__ */ new Date();
17816
17816
  return this;
17817
17817
  }
17818
17818
  if (opts.atomic) {
17819
17819
  if (event === EVENTS.UNLINK) {
17820
- this._pendingUnlinks.set(path18, [event, ...args]);
17820
+ this._pendingUnlinks.set(path19, [event, ...args]);
17821
17821
  setTimeout(() => {
17822
- this._pendingUnlinks.forEach((entry, path19) => {
17822
+ this._pendingUnlinks.forEach((entry, path20) => {
17823
17823
  this.emit(...entry);
17824
17824
  this.emit(EVENTS.ALL, ...entry);
17825
- this._pendingUnlinks.delete(path19);
17825
+ this._pendingUnlinks.delete(path20);
17826
17826
  });
17827
17827
  }, typeof opts.atomic === "number" ? opts.atomic : 100);
17828
17828
  return this;
17829
17829
  }
17830
- if (event === EVENTS.ADD && this._pendingUnlinks.has(path18)) {
17830
+ if (event === EVENTS.ADD && this._pendingUnlinks.has(path19)) {
17831
17831
  event = EVENTS.CHANGE;
17832
- this._pendingUnlinks.delete(path18);
17832
+ this._pendingUnlinks.delete(path19);
17833
17833
  }
17834
17834
  }
17835
17835
  if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
@@ -17847,16 +17847,16 @@ var FSWatcher = class extends import_node_events.EventEmitter {
17847
17847
  this.emitWithAll(event, args);
17848
17848
  }
17849
17849
  };
17850
- this._awaitWriteFinish(path18, awf.stabilityThreshold, event, awfEmit);
17850
+ this._awaitWriteFinish(path19, awf.stabilityThreshold, event, awfEmit);
17851
17851
  return this;
17852
17852
  }
17853
17853
  if (event === EVENTS.CHANGE) {
17854
- const isThrottled = !this._throttle(EVENTS.CHANGE, path18, 50);
17854
+ const isThrottled = !this._throttle(EVENTS.CHANGE, path19, 50);
17855
17855
  if (isThrottled)
17856
17856
  return this;
17857
17857
  }
17858
17858
  if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
17859
- const fullPath = opts.cwd ? sp2.join(opts.cwd, path18) : path18;
17859
+ const fullPath = opts.cwd ? sp2.join(opts.cwd, path19) : path19;
17860
17860
  let stats2;
17861
17861
  try {
17862
17862
  stats2 = await (0, import_promises3.stat)(fullPath);
@@ -17887,23 +17887,23 @@ var FSWatcher = class extends import_node_events.EventEmitter {
17887
17887
  * @param timeout duration of time to suppress duplicate actions
17888
17888
  * @returns tracking object or false if action should be suppressed
17889
17889
  */
17890
- _throttle(actionType, path18, timeout) {
17890
+ _throttle(actionType, path19, timeout) {
17891
17891
  if (!this._throttled.has(actionType)) {
17892
17892
  this._throttled.set(actionType, /* @__PURE__ */ new Map());
17893
17893
  }
17894
17894
  const action = this._throttled.get(actionType);
17895
17895
  if (!action)
17896
17896
  throw new Error("invalid throttle");
17897
- const actionPath = action.get(path18);
17897
+ const actionPath = action.get(path19);
17898
17898
  if (actionPath) {
17899
17899
  actionPath.count++;
17900
17900
  return false;
17901
17901
  }
17902
17902
  let timeoutObject;
17903
17903
  const clear = () => {
17904
- const item = action.get(path18);
17904
+ const item = action.get(path19);
17905
17905
  const count = item ? item.count : 0;
17906
- action.delete(path18);
17906
+ action.delete(path19);
17907
17907
  clearTimeout(timeoutObject);
17908
17908
  if (item)
17909
17909
  clearTimeout(item.timeoutObject);
@@ -17911,7 +17911,7 @@ var FSWatcher = class extends import_node_events.EventEmitter {
17911
17911
  };
17912
17912
  timeoutObject = setTimeout(clear, timeout);
17913
17913
  const thr = { timeoutObject, clear, count: 0 };
17914
- action.set(path18, thr);
17914
+ action.set(path19, thr);
17915
17915
  return thr;
17916
17916
  }
17917
17917
  _incrReadyCount() {
@@ -17925,44 +17925,44 @@ var FSWatcher = class extends import_node_events.EventEmitter {
17925
17925
  * @param event
17926
17926
  * @param awfEmit Callback to be called when ready for event to be emitted.
17927
17927
  */
17928
- _awaitWriteFinish(path18, threshold, event, awfEmit) {
17928
+ _awaitWriteFinish(path19, threshold, event, awfEmit) {
17929
17929
  const awf = this.options.awaitWriteFinish;
17930
17930
  if (typeof awf !== "object")
17931
17931
  return;
17932
17932
  const pollInterval = awf.pollInterval;
17933
17933
  let timeoutHandler;
17934
- let fullPath = path18;
17935
- if (this.options.cwd && !sp2.isAbsolute(path18)) {
17936
- fullPath = sp2.join(this.options.cwd, path18);
17934
+ let fullPath = path19;
17935
+ if (this.options.cwd && !sp2.isAbsolute(path19)) {
17936
+ fullPath = sp2.join(this.options.cwd, path19);
17937
17937
  }
17938
17938
  const now = /* @__PURE__ */ new Date();
17939
17939
  const writes = this._pendingWrites;
17940
17940
  function awaitWriteFinishFn(prevStat) {
17941
17941
  (0, import_node_fs2.stat)(fullPath, (err, curStat) => {
17942
- if (err || !writes.has(path18)) {
17942
+ if (err || !writes.has(path19)) {
17943
17943
  if (err && err.code !== "ENOENT")
17944
17944
  awfEmit(err);
17945
17945
  return;
17946
17946
  }
17947
17947
  const now2 = Number(/* @__PURE__ */ new Date());
17948
17948
  if (prevStat && curStat.size !== prevStat.size) {
17949
- writes.get(path18).lastChange = now2;
17949
+ writes.get(path19).lastChange = now2;
17950
17950
  }
17951
- const pw = writes.get(path18);
17951
+ const pw = writes.get(path19);
17952
17952
  const df = now2 - pw.lastChange;
17953
17953
  if (df >= threshold) {
17954
- writes.delete(path18);
17954
+ writes.delete(path19);
17955
17955
  awfEmit(void 0, curStat);
17956
17956
  } else {
17957
17957
  timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
17958
17958
  }
17959
17959
  });
17960
17960
  }
17961
- if (!writes.has(path18)) {
17962
- writes.set(path18, {
17961
+ if (!writes.has(path19)) {
17962
+ writes.set(path19, {
17963
17963
  lastChange: now,
17964
17964
  cancelWait: () => {
17965
- writes.delete(path18);
17965
+ writes.delete(path19);
17966
17966
  clearTimeout(timeoutHandler);
17967
17967
  return event;
17968
17968
  }
@@ -17973,8 +17973,8 @@ var FSWatcher = class extends import_node_events.EventEmitter {
17973
17973
  /**
17974
17974
  * Determines whether user has asked to ignore this path.
17975
17975
  */
17976
- _isIgnored(path18, stats) {
17977
- if (this.options.atomic && DOT_RE.test(path18))
17976
+ _isIgnored(path19, stats) {
17977
+ if (this.options.atomic && DOT_RE.test(path19))
17978
17978
  return true;
17979
17979
  if (!this._userIgnored) {
17980
17980
  const { cwd } = this.options;
@@ -17984,17 +17984,17 @@ var FSWatcher = class extends import_node_events.EventEmitter {
17984
17984
  const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];
17985
17985
  this._userIgnored = anymatch(list, void 0);
17986
17986
  }
17987
- return this._userIgnored(path18, stats);
17987
+ return this._userIgnored(path19, stats);
17988
17988
  }
17989
- _isntIgnored(path18, stat4) {
17990
- return !this._isIgnored(path18, stat4);
17989
+ _isntIgnored(path19, stat4) {
17990
+ return !this._isIgnored(path19, stat4);
17991
17991
  }
17992
17992
  /**
17993
17993
  * Provides a set of common helpers and properties relating to symlink handling.
17994
17994
  * @param path file or directory pattern being watched
17995
17995
  */
17996
- _getWatchHelpers(path18) {
17997
- return new WatchHelper(path18, this.options.followSymlinks, this);
17996
+ _getWatchHelpers(path19) {
17997
+ return new WatchHelper(path19, this.options.followSymlinks, this);
17998
17998
  }
17999
17999
  // Directory helpers
18000
18000
  // -----------------
@@ -18026,63 +18026,63 @@ var FSWatcher = class extends import_node_events.EventEmitter {
18026
18026
  * @param item base path of item/directory
18027
18027
  */
18028
18028
  _remove(directory, item, isDirectory) {
18029
- const path18 = sp2.join(directory, item);
18030
- const fullPath = sp2.resolve(path18);
18031
- isDirectory = isDirectory != null ? isDirectory : this._watched.has(path18) || this._watched.has(fullPath);
18032
- if (!this._throttle("remove", path18, 100))
18029
+ const path19 = sp2.join(directory, item);
18030
+ const fullPath = sp2.resolve(path19);
18031
+ isDirectory = isDirectory != null ? isDirectory : this._watched.has(path19) || this._watched.has(fullPath);
18032
+ if (!this._throttle("remove", path19, 100))
18033
18033
  return;
18034
18034
  if (!isDirectory && this._watched.size === 1) {
18035
18035
  this.add(directory, item, true);
18036
18036
  }
18037
- const wp = this._getWatchedDir(path18);
18037
+ const wp = this._getWatchedDir(path19);
18038
18038
  const nestedDirectoryChildren = wp.getChildren();
18039
- nestedDirectoryChildren.forEach((nested) => this._remove(path18, nested));
18039
+ nestedDirectoryChildren.forEach((nested) => this._remove(path19, nested));
18040
18040
  const parent = this._getWatchedDir(directory);
18041
18041
  const wasTracked = parent.has(item);
18042
18042
  parent.remove(item);
18043
18043
  if (this._symlinkPaths.has(fullPath)) {
18044
18044
  this._symlinkPaths.delete(fullPath);
18045
18045
  }
18046
- let relPath = path18;
18046
+ let relPath = path19;
18047
18047
  if (this.options.cwd)
18048
- relPath = sp2.relative(this.options.cwd, path18);
18048
+ relPath = sp2.relative(this.options.cwd, path19);
18049
18049
  if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
18050
18050
  const event = this._pendingWrites.get(relPath).cancelWait();
18051
18051
  if (event === EVENTS.ADD)
18052
18052
  return;
18053
18053
  }
18054
- this._watched.delete(path18);
18054
+ this._watched.delete(path19);
18055
18055
  this._watched.delete(fullPath);
18056
18056
  const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
18057
- if (wasTracked && !this._isIgnored(path18))
18058
- this._emit(eventName, path18);
18059
- this._closePath(path18);
18057
+ if (wasTracked && !this._isIgnored(path19))
18058
+ this._emit(eventName, path19);
18059
+ this._closePath(path19);
18060
18060
  }
18061
18061
  /**
18062
18062
  * Closes all watchers for a path
18063
18063
  */
18064
- _closePath(path18) {
18065
- this._closeFile(path18);
18066
- const dir = sp2.dirname(path18);
18067
- this._getWatchedDir(dir).remove(sp2.basename(path18));
18064
+ _closePath(path19) {
18065
+ this._closeFile(path19);
18066
+ const dir = sp2.dirname(path19);
18067
+ this._getWatchedDir(dir).remove(sp2.basename(path19));
18068
18068
  }
18069
18069
  /**
18070
18070
  * Closes only file-specific watchers
18071
18071
  */
18072
- _closeFile(path18) {
18073
- const closers = this._closers.get(path18);
18072
+ _closeFile(path19) {
18073
+ const closers = this._closers.get(path19);
18074
18074
  if (!closers)
18075
18075
  return;
18076
18076
  closers.forEach((closer) => closer());
18077
- this._closers.delete(path18);
18077
+ this._closers.delete(path19);
18078
18078
  }
18079
- _addPathCloser(path18, closer) {
18079
+ _addPathCloser(path19, closer) {
18080
18080
  if (!closer)
18081
18081
  return;
18082
- let list = this._closers.get(path18);
18082
+ let list = this._closers.get(path19);
18083
18083
  if (!list) {
18084
18084
  list = [];
18085
- this._closers.set(path18, list);
18085
+ this._closers.set(path19, list);
18086
18086
  }
18087
18087
  list.push(closer);
18088
18088
  }
@@ -18115,28 +18115,33 @@ var fs6 = __toESM(require("fs"), 1);
18115
18115
  var path8 = __toESM(require("path"), 1);
18116
18116
  var os9 = __toESM(require("os"), 1);
18117
18117
  var os10 = __toESM(require("os"), 1);
18118
+ var import_child_process6 = require("child_process");
18119
+ var import_child_process7 = require("child_process");
18118
18120
  var fs7 = __toESM(require("fs"), 1);
18119
- var os13 = __toESM(require("os"), 1);
18120
- var path10 = __toESM(require("path"), 1);
18121
+ var os11 = __toESM(require("os"), 1);
18122
+ var path9 = __toESM(require("path"), 1);
18123
+ var fs8 = __toESM(require("fs"), 1);
18124
+ var os14 = __toESM(require("os"), 1);
18125
+ var path11 = __toESM(require("path"), 1);
18121
18126
  var crypto4 = __toESM(require("crypto"), 1);
18122
18127
  var import_chalk = __toESM(require("chalk"), 1);
18123
18128
  var crypto3 = __toESM(require("crypto"), 1);
18124
18129
  var import_stream = require("stream");
18125
- var import_child_process6 = require("child_process");
18130
+ var import_child_process8 = require("child_process");
18126
18131
  init_acp();
18127
- var fs8 = __toESM(require("fs"), 1);
18128
- var path11 = __toESM(require("path"), 1);
18129
- var os14 = __toESM(require("os"), 1);
18130
- var import_child_process7 = require("child_process");
18131
- var import_os3 = require("os");
18132
- var http2 = __toESM(require("http"), 1);
18133
- var fs11 = __toESM(require("fs"), 1);
18134
- var path14 = __toESM(require("path"), 1);
18135
18132
  var fs9 = __toESM(require("fs"), 1);
18136
18133
  var path12 = __toESM(require("path"), 1);
18134
+ var os15 = __toESM(require("os"), 1);
18135
+ var import_child_process9 = require("child_process");
18136
+ var import_os3 = require("os");
18137
+ var http2 = __toESM(require("http"), 1);
18138
+ var fs12 = __toESM(require("fs"), 1);
18139
+ var path15 = __toESM(require("path"), 1);
18137
18140
  var fs10 = __toESM(require("fs"), 1);
18138
18141
  var path13 = __toESM(require("path"), 1);
18139
- var os15 = __toESM(require("os"), 1);
18142
+ var fs11 = __toESM(require("fs"), 1);
18143
+ var path14 = __toESM(require("path"), 1);
18144
+ var os16 = __toESM(require("os"), 1);
18140
18145
 
18141
18146
  // ../session-host-core/dist/index.mjs
18142
18147
  var os = __toESM(require("os"), 1);
@@ -18785,6 +18790,9 @@ var init_ghostty_vt_backend = __esm2({
18785
18790
  getText() {
18786
18791
  return this.terminal.formatPlainText({ trim: true }) || "";
18787
18792
  }
18793
+ getCursorPosition() {
18794
+ return this.terminal.getCursorPosition();
18795
+ }
18788
18796
  dispose() {
18789
18797
  this.terminal.dispose();
18790
18798
  }
@@ -18841,6 +18849,13 @@ var init_xterm_backend = __esm2({
18841
18849
  while (last > first && !lines[last - 1]?.trim()) last--;
18842
18850
  return lines.slice(first, last).join("\n");
18843
18851
  }
18852
+ getCursorPosition() {
18853
+ const buffer = this.terminal.buffer.active;
18854
+ return {
18855
+ col: Math.max(0, buffer.cursorX || 0),
18856
+ row: Math.max(0, buffer.cursorY || 0)
18857
+ };
18858
+ }
18844
18859
  dispose() {
18845
18860
  this.terminal.dispose();
18846
18861
  }
@@ -18927,6 +18942,9 @@ var init_terminal_screen = __esm2({
18927
18942
  getText() {
18928
18943
  return this.terminal.getText();
18929
18944
  }
18945
+ getCursorPosition() {
18946
+ return this.terminal.getCursorPosition();
18947
+ }
18930
18948
  dispose() {
18931
18949
  this.terminal.dispose();
18932
18950
  }
@@ -18956,6 +18974,7 @@ var init_pty_transport = __esm2({
18956
18974
  this.handle = handle;
18957
18975
  }
18958
18976
  ready = Promise.resolve();
18977
+ terminalQueriesHandled = false;
18959
18978
  get pid() {
18960
18979
  return this.handle.pid;
18961
18980
  }
@@ -18982,7 +19001,7 @@ var init_pty_transport = __esm2({
18982
19001
  spawn(command, args, options) {
18983
19002
  if (!pty) throw new Error("node-pty is not installed");
18984
19003
  const handle = pty.spawn(command, args, {
18985
- name: os11.platform() === "win32" ? "xterm-color" : "xterm-256color",
19004
+ name: os12.platform() === "win32" ? "xterm-color" : "xterm-256color",
18986
19005
  cols: options.cols,
18987
19006
  rows: options.rows,
18988
19007
  cwd: options.cwd,
@@ -19007,8 +19026,34 @@ function stripTerminalNoise(str) {
19007
19026
  function sanitizeTerminalText(str) {
19008
19027
  return stripTerminalNoise(stripAnsi(str));
19009
19028
  }
19029
+ function buildCliSpawnEnv(baseEnv, overrides) {
19030
+ const env = {};
19031
+ const source = { ...baseEnv, ...overrides || {} };
19032
+ for (const [key, value] of Object.entries(source)) {
19033
+ if (typeof value !== "string") continue;
19034
+ env[key] = value;
19035
+ }
19036
+ for (const key of Object.keys(env)) {
19037
+ if (key === "INIT_CWD" || key === "NO_COLOR" || key === "FORCE_COLOR" || key === "npm_command" || key === "npm_execpath" || key === "npm_node_execpath" || key.startsWith("npm_") || key.startsWith("npm_config_") || key.startsWith("npm_package_") || key.startsWith("npm_lifecycle_") || key.startsWith("PNPM_") || key.startsWith("YARN_") || key.startsWith("BUN_")) {
19038
+ delete env[key];
19039
+ }
19040
+ }
19041
+ return env;
19042
+ }
19043
+ function computeTerminalQueryTail(buffer) {
19044
+ const prefixes = ["\x1B[6n", "\x1B[?6n"];
19045
+ const maxLength = prefixes.reduce((n, value) => Math.max(n, value.length), 0) - 1;
19046
+ const start = Math.max(0, buffer.length - maxLength);
19047
+ for (let i = start; i < buffer.length; i++) {
19048
+ const suffix = buffer.slice(i);
19049
+ if (prefixes.some((pattern) => suffix.length < pattern.length && pattern.startsWith(suffix))) {
19050
+ return suffix;
19051
+ }
19052
+ }
19053
+ return "";
19054
+ }
19010
19055
  function findBinary(name) {
19011
- const isWin = os12.platform() === "win32";
19056
+ const isWin = os13.platform() === "win32";
19012
19057
  try {
19013
19058
  const cmd = isWin ? `where ${name}` : `which ${name}`;
19014
19059
  return (0, import_child_process.execSync)(cmd, { encoding: "utf-8", timeout: 5e3, stdio: ["pipe", "pipe", "pipe"] }).trim().split("\n")[0].trim();
@@ -19017,14 +19062,14 @@ function findBinary(name) {
19017
19062
  }
19018
19063
  }
19019
19064
  function isScriptBinary(binaryPath) {
19020
- if (!path9.isAbsolute(binaryPath)) return false;
19065
+ if (!path10.isAbsolute(binaryPath)) return false;
19021
19066
  try {
19022
- const fs122 = __require("fs");
19023
- const resolved = fs122.realpathSync(binaryPath);
19067
+ const fs132 = __require("fs");
19068
+ const resolved = fs132.realpathSync(binaryPath);
19024
19069
  const head = Buffer.alloc(8);
19025
- const fd = fs122.openSync(resolved, "r");
19026
- fs122.readSync(fd, head, 0, 8, 0);
19027
- fs122.closeSync(fd);
19070
+ const fd = fs132.openSync(resolved, "r");
19071
+ fs132.readSync(fd, head, 0, 8, 0);
19072
+ fs132.closeSync(fd);
19028
19073
  let i = 0;
19029
19074
  if (head[0] === 239 && head[1] === 187 && head[2] === 191) i = 3;
19030
19075
  return head[i] === 35 && head[i + 1] === 33;
@@ -19033,14 +19078,14 @@ function isScriptBinary(binaryPath) {
19033
19078
  }
19034
19079
  }
19035
19080
  function looksLikeMachOOrElf(filePath) {
19036
- if (!path9.isAbsolute(filePath)) return false;
19081
+ if (!path10.isAbsolute(filePath)) return false;
19037
19082
  try {
19038
- const fs122 = __require("fs");
19039
- const resolved = fs122.realpathSync(filePath);
19083
+ const fs132 = __require("fs");
19084
+ const resolved = fs132.realpathSync(filePath);
19040
19085
  const buf = Buffer.alloc(8);
19041
- const fd = fs122.openSync(resolved, "r");
19042
- fs122.readSync(fd, buf, 0, 8, 0);
19043
- fs122.closeSync(fd);
19086
+ const fd = fs132.openSync(resolved, "r");
19087
+ fs132.readSync(fd, buf, 0, 8, 0);
19088
+ fs132.closeSync(fd);
19044
19089
  let i = 0;
19045
19090
  if (buf[0] === 239 && buf[1] === 187 && buf[2] === 191) i = 3;
19046
19091
  const b = buf.subarray(i);
@@ -19056,7 +19101,7 @@ function looksLikeMachOOrElf(filePath) {
19056
19101
  }
19057
19102
  function shSingleQuote(arg) {
19058
19103
  if (/^[a-zA-Z0-9@%_+=:,./-]+$/.test(arg)) return arg;
19059
- if (os12.platform() === "win32") {
19104
+ if (os13.platform() === "win32") {
19060
19105
  return `"${arg.replace(/"/g, '""')}"`;
19061
19106
  }
19062
19107
  return `'${arg.replace(/'/g, `'\\''`)}'`;
@@ -19093,36 +19138,6 @@ function promptLikelyVisible(screenText, promptSnippet) {
19093
19138
  ).length;
19094
19139
  return matched >= required2;
19095
19140
  }
19096
- function splitHistoryLines(text) {
19097
- return String(text || "").split("\n").map((line) => line.replace(/\s+$/, ""));
19098
- }
19099
- function normalizeHistoryLine(line) {
19100
- return String(line || "").replace(/\s+/g, " ").trim();
19101
- }
19102
- function mergeTerminalHistory(existing, snapshot) {
19103
- const next = String(snapshot || "").trim();
19104
- if (!next) return existing;
19105
- const prev = String(existing || "").trim();
19106
- if (!prev) return next;
19107
- if (prev === next || prev.endsWith(next)) return prev;
19108
- const prevLines = splitHistoryLines(prev);
19109
- const nextLines = splitHistoryLines(next);
19110
- const prevNorm = prevLines.map(normalizeHistoryLine);
19111
- const nextNorm = nextLines.map(normalizeHistoryLine);
19112
- const maxOverlap = Math.min(prevLines.length, nextLines.length);
19113
- for (let overlap = maxOverlap; overlap >= 1; overlap -= 1) {
19114
- const prevTail = prevNorm.slice(prevNorm.length - overlap);
19115
- const nextHead = nextNorm.slice(0, overlap);
19116
- if (prevTail.every((line, index) => line === nextHead[index])) {
19117
- return [...prevLines, ...nextLines.slice(overlap)].join("\n").trim();
19118
- }
19119
- }
19120
- const compactPrev = prevNorm.join("\n");
19121
- const compactNext = nextNorm.join("\n");
19122
- if (compactPrev.includes(compactNext)) return prev;
19123
- return `${prev}
19124
- ${next}`.trim();
19125
- }
19126
19141
  function parsePatternEntry(x) {
19127
19142
  if (x instanceof RegExp) return x;
19128
19143
  if (x && typeof x === "object" && typeof x.source === "string") {
@@ -19157,16 +19172,16 @@ var init_provider_cli_adapter = __esm2({
19157
19172
  init_pty_transport();
19158
19173
  try {
19159
19174
  pty2 = __require("node-pty");
19160
- if (os12.platform() !== "win32") {
19175
+ if (os13.platform() !== "win32") {
19161
19176
  try {
19162
- const fs122 = __require("fs");
19163
- const ptyDir = path9.resolve(path9.dirname(__require.resolve("node-pty")), "..");
19164
- const platformArch = `${os12.platform()}-${os12.arch()}`;
19165
- const helper = path9.join(ptyDir, "prebuilds", platformArch, "spawn-helper");
19166
- if (fs122.existsSync(helper)) {
19167
- const stat4 = fs122.statSync(helper);
19177
+ const fs132 = __require("fs");
19178
+ const ptyDir = path10.resolve(path10.dirname(__require.resolve("node-pty")), "..");
19179
+ const platformArch = `${os13.platform()}-${os13.arch()}`;
19180
+ const helper = path10.join(ptyDir, "prebuilds", platformArch, "spawn-helper");
19181
+ if (fs132.existsSync(helper)) {
19182
+ const stat4 = fs132.statSync(helper);
19168
19183
  if (!(stat4.mode & 73)) {
19169
- fs122.chmodSync(helper, stat4.mode | 493);
19184
+ fs132.chmodSync(helper, stat4.mode | 493);
19170
19185
  LOG.info("CLI", "[node-pty] Fixed spawn-helper permissions");
19171
19186
  }
19172
19187
  }
@@ -19183,7 +19198,7 @@ var init_provider_cli_adapter = __esm2({
19183
19198
  this.transportFactory = transportFactory;
19184
19199
  this.cliType = provider.type;
19185
19200
  this.cliName = provider.name;
19186
- this.workingDir = workingDir.startsWith("~") ? workingDir.replace(/^~/, os12.homedir()) : workingDir;
19201
+ this.workingDir = workingDir.startsWith("~") ? workingDir.replace(/^~/, os13.homedir()) : workingDir;
19187
19202
  const t = provider.timeouts || {};
19188
19203
  this.timeouts = {
19189
19204
  ptyFlush: t.ptyFlush ?? 50,
@@ -19235,6 +19250,7 @@ var init_provider_cli_adapter = __esm2({
19235
19250
  pendingOutputParseTimer = null;
19236
19251
  ptyOutputBuffer = "";
19237
19252
  ptyOutputFlushTimer = null;
19253
+ pendingTerminalQueryTail = "";
19238
19254
  // Server log forwarding
19239
19255
  serverConn = null;
19240
19256
  logBuffer = [];
@@ -19266,9 +19282,7 @@ var init_provider_cli_adapter = __esm2({
19266
19282
  /** Full accumulated raw PTY output (with ANSI) */
19267
19283
  accumulatedRawBuffer = "";
19268
19284
  /** Current visible terminal screen snapshot */
19269
- terminalScreen = new TerminalScreen(40, 120);
19270
- /** Rolling append-only terminal transcript built from screen snapshots */
19271
- terminalHistory = "";
19285
+ terminalScreen = new TerminalScreen(30, 100);
19272
19286
  /** Max accumulated buffer size (last 50KB) */
19273
19287
  static MAX_ACCUMULATED_BUFFER = 5e4;
19274
19288
  currentTurnScope = null;
@@ -19290,15 +19304,13 @@ var init_provider_cli_adapter = __esm2({
19290
19304
  return text.slice(start);
19291
19305
  }
19292
19306
  buildParseInput(baseMessages, partialResponse, scope) {
19293
- const buffer = scope ? this.sliceFromOffset(this.terminalHistory, scope.terminalHistoryStart) || this.sliceFromOffset(this.accumulatedBuffer, scope.bufferStart) || this.accumulatedBuffer : this.accumulatedBuffer;
19307
+ const buffer = scope ? this.sliceFromOffset(this.accumulatedBuffer, scope.bufferStart) || this.accumulatedBuffer : this.accumulatedBuffer;
19294
19308
  const rawBuffer = scope ? this.sliceFromOffset(this.accumulatedRawBuffer, scope.rawBufferStart) || this.accumulatedRawBuffer : this.accumulatedRawBuffer;
19295
- const terminalHistory = scope ? this.sliceFromOffset(this.terminalHistory, scope.terminalHistoryStart) || this.terminalHistory : this.terminalHistory;
19296
19309
  return {
19297
19310
  buffer,
19298
19311
  rawBuffer,
19299
19312
  recentBuffer: buffer.slice(-1e3) || this.recentOutputBuffer,
19300
19313
  screenText: this.terminalScreen.getText(),
19301
- terminalHistory,
19302
19314
  messages: [...baseMessages],
19303
19315
  partialResponse
19304
19316
  };
@@ -19353,12 +19365,12 @@ var init_provider_cli_adapter = __esm2({
19353
19365
  if (this.ptyProcess) return;
19354
19366
  const { spawn: spawnConfig } = this.provider;
19355
19367
  const binaryPath = findBinary(spawnConfig.command);
19356
- const isWin = os12.platform() === "win32";
19368
+ const isWin = os13.platform() === "win32";
19357
19369
  const allArgs = [...spawnConfig.args, ...this.extraArgs];
19358
19370
  LOG.info("CLI", `[${this.cliType}] Spawning in ${this.workingDir}`);
19359
19371
  let shellCmd;
19360
19372
  let shellArgs;
19361
- const useShellUnix = !isWin && (!!spawnConfig.shell || !path9.isAbsolute(binaryPath) || isScriptBinary(binaryPath) || !looksLikeMachOOrElf(binaryPath));
19373
+ const useShellUnix = !isWin && (!!spawnConfig.shell || !path10.isAbsolute(binaryPath) || isScriptBinary(binaryPath) || !looksLikeMachOOrElf(binaryPath));
19362
19374
  const useShell = isWin ? !!spawnConfig.shell : useShellUnix;
19363
19375
  if (useShell) {
19364
19376
  if (!spawnConfig.shell && !isWin) {
@@ -19376,13 +19388,10 @@ var init_provider_cli_adapter = __esm2({
19376
19388
  shellArgs = allArgs;
19377
19389
  }
19378
19390
  const ptyOpts = {
19379
- cols: 120,
19380
- rows: 40,
19391
+ cols: 100,
19392
+ rows: 30,
19381
19393
  cwd: this.workingDir,
19382
- env: {
19383
- ...process.env,
19384
- ...spawnConfig.env
19385
- }
19394
+ env: buildCliSpawnEnv(process.env, spawnConfig.env)
19386
19395
  };
19387
19396
  try {
19388
19397
  this.ptyProcess = this.transportFactory.spawn(shellCmd, shellArgs, ptyOpts);
@@ -19400,8 +19409,8 @@ var init_provider_cli_adapter = __esm2({
19400
19409
  }
19401
19410
  this.ptyProcess.onData((data) => {
19402
19411
  if (Date.now() < this.resizeSuppressUntil) return;
19403
- if (data.includes("\x1B[6n") || data.includes("\x1B[?6n")) {
19404
- this.ptyProcess?.write("\x1B[1;1R");
19412
+ if (!this.ptyProcess?.terminalQueriesHandled) {
19413
+ this.respondToTerminalQueries(data);
19405
19414
  }
19406
19415
  this.pendingOutputParseBuffer += data;
19407
19416
  if (!this.pendingOutputParseTimer) {
@@ -19436,8 +19445,8 @@ var init_provider_cli_adapter = __esm2({
19436
19445
  this.spawnAt = Date.now();
19437
19446
  this.startupParseGate = true;
19438
19447
  this.startupBuffer = "";
19439
- this.terminalScreen.reset(40, 120);
19440
- this.terminalHistory = "";
19448
+ this.terminalScreen.reset(30, 100);
19449
+ this.pendingTerminalQueryTail = "";
19441
19450
  this.currentTurnScope = null;
19442
19451
  this.ready = false;
19443
19452
  await this.ptyProcess.ready;
@@ -19447,7 +19456,6 @@ var init_provider_cli_adapter = __esm2({
19447
19456
  // ─── Output Handling ────────────────────────────
19448
19457
  handleOutput(rawData) {
19449
19458
  this.terminalScreen.write(rawData);
19450
- this.terminalHistory = mergeTerminalHistory(this.terminalHistory, this.terminalScreen.getText());
19451
19459
  const cleanData = sanitizeTerminalText(rawData);
19452
19460
  if (this.isWaitingForResponse && cleanData) {
19453
19461
  this.responseBuffer = (this.responseBuffer + cleanData).slice(-8e3);
@@ -19723,8 +19731,7 @@ var init_provider_cli_adapter = __esm2({
19723
19731
  status: this.currentStatus,
19724
19732
  messages: [...this.committedMessages],
19725
19733
  workingDir: this.workingDir,
19726
- activeModal: this.activeModal,
19727
- terminalHistory: this.terminalHistory
19734
+ activeModal: this.activeModal
19728
19735
  };
19729
19736
  }
19730
19737
  /**
@@ -19742,7 +19749,6 @@ var init_provider_cli_adapter = __esm2({
19742
19749
  id: parsed.id || "cli_session",
19743
19750
  status: parsed.status || this.currentStatus,
19744
19751
  title: parsed.title || this.cliName,
19745
- terminalHistory: this.terminalHistory,
19746
19752
  messages: parsed.messages,
19747
19753
  activeModal: parsed.activeModal ?? this.activeModal
19748
19754
  };
@@ -19752,7 +19758,6 @@ var init_provider_cli_adapter = __esm2({
19752
19758
  id: "cli_session",
19753
19759
  status: this.currentStatus,
19754
19760
  title: this.cliName,
19755
- terminalHistory: this.terminalHistory,
19756
19761
  messages: messages.slice(-50).map((message, index) => ({
19757
19762
  id: `msg_${index}`,
19758
19763
  role: message.role,
@@ -19820,10 +19825,9 @@ ${data.message || ""}`.trim();
19820
19825
  prompt: text,
19821
19826
  startedAt: Date.now(),
19822
19827
  bufferStart: this.accumulatedBuffer.length,
19823
- rawBufferStart: this.accumulatedRawBuffer.length,
19824
- terminalHistoryStart: this.terminalHistory.length
19828
+ rawBufferStart: this.accumulatedRawBuffer.length
19825
19829
  };
19826
- LOG.info("CLI", `[${this.cliType}] sendMessage turn scope buffer=${this.currentTurnScope.bufferStart} raw=${this.currentTurnScope.rawBufferStart} terminal=${this.currentTurnScope.terminalHistoryStart} prompt=${JSON.stringify(text).slice(0, 120)}`);
19830
+ LOG.info("CLI", `[${this.cliType}] sendMessage turn scope buffer=${this.currentTurnScope.bufferStart} raw=${this.currentTurnScope.rawBufferStart} prompt=${JSON.stringify(text).slice(0, 120)}`);
19827
19831
  this.submitRetryUsed = false;
19828
19832
  this.submitRetryPromptSnippet = extractPromptRetrySnippet(text);
19829
19833
  const normalizedPromptSnippet = normalizePromptText(this.submitRetryPromptSnippet);
@@ -20008,6 +20012,7 @@ ${data.message || ""}`.trim();
20008
20012
  this.pendingOutputParseTimer = null;
20009
20013
  }
20010
20014
  this.pendingOutputParseBuffer = "";
20015
+ this.pendingTerminalQueryTail = "";
20011
20016
  if (this.ptyOutputFlushTimer) {
20012
20017
  clearTimeout(this.ptyOutputFlushTimer);
20013
20018
  this.ptyOutputFlushTimer = null;
@@ -20047,6 +20052,7 @@ ${data.message || ""}`.trim();
20047
20052
  this.pendingOutputParseTimer = null;
20048
20053
  }
20049
20054
  this.pendingOutputParseBuffer = "";
20055
+ this.pendingTerminalQueryTail = "";
20050
20056
  if (this.ptyOutputFlushTimer) {
20051
20057
  clearTimeout(this.ptyOutputFlushTimer);
20052
20058
  this.ptyOutputFlushTimer = null;
@@ -20073,7 +20079,6 @@ ${data.message || ""}`.trim();
20073
20079
  this.syncMessageViews();
20074
20080
  this.accumulatedBuffer = "";
20075
20081
  this.accumulatedRawBuffer = "";
20076
- this.terminalHistory = "";
20077
20082
  this.currentTurnScope = null;
20078
20083
  this.submitRetryUsed = false;
20079
20084
  this.submitRetryPromptSnippet = "";
@@ -20082,6 +20087,7 @@ ${data.message || ""}`.trim();
20082
20087
  this.pendingOutputParseTimer = null;
20083
20088
  }
20084
20089
  this.pendingOutputParseBuffer = "";
20090
+ this.pendingTerminalQueryTail = "";
20085
20091
  if (this.ptyOutputFlushTimer) {
20086
20092
  clearTimeout(this.ptyOutputFlushTimer);
20087
20093
  this.ptyOutputFlushTimer = null;
@@ -20143,7 +20149,6 @@ ${data.message || ""}`.trim();
20143
20149
  structuredMessages: this.structuredMessages.slice(-20),
20144
20150
  messageCount: this.committedMessages.length,
20145
20151
  screenText: sanitizeTerminalText(this.terminalScreen.getText()).slice(-4e3),
20146
- terminalHistory: this.terminalHistory.slice(-8e3),
20147
20152
  currentTurnScope: this.currentTurnScope,
20148
20153
  startupBuffer: this.startupBuffer.slice(-4e3),
20149
20154
  recentOutputBuffer: this.recentOutputBuffer.slice(-500),
@@ -20171,6 +20176,20 @@ ${data.message || ""}`.trim();
20171
20176
  ptyAlive: !!this.ptyProcess
20172
20177
  };
20173
20178
  }
20179
+ respondToTerminalQueries(data) {
20180
+ if (!this.ptyProcess || !data) return;
20181
+ const combined = this.pendingTerminalQueryTail + data;
20182
+ const regex = /\x1b\[(\?)?6n/g;
20183
+ let match;
20184
+ while ((match = regex.exec(combined)) !== null) {
20185
+ const cursor = this.terminalScreen.getCursorPosition();
20186
+ const row = Math.max(1, (cursor.row | 0) + 1);
20187
+ const col = Math.max(1, (cursor.col | 0) + 1);
20188
+ const response = match[1] ? `\x1B[?${row};${col}R` : `\x1B[${row};${col}R`;
20189
+ this.ptyProcess.write(response);
20190
+ }
20191
+ this.pendingTerminalQueryTail = computeTerminalQueryTail(combined);
20192
+ }
20174
20193
  };
20175
20194
  }
20176
20195
  });
@@ -20438,18 +20457,18 @@ function checkPathExists(paths) {
20438
20457
  return null;
20439
20458
  }
20440
20459
  async function detectIDEs() {
20441
- const os162 = (0, import_os2.platform)();
20460
+ const os172 = (0, import_os2.platform)();
20442
20461
  const results = [];
20443
20462
  for (const def of getMergedDefinitions()) {
20444
20463
  const cliPath = findCliCommand(def.cli);
20445
- const appPath = checkPathExists(def.paths[os162] || []);
20464
+ const appPath = checkPathExists(def.paths[os172] || []);
20446
20465
  const installed = !!(cliPath || appPath);
20447
20466
  let resolvedCli = cliPath;
20448
- if (!resolvedCli && appPath && os162 === "darwin") {
20467
+ if (!resolvedCli && appPath && os172 === "darwin") {
20449
20468
  const bundledCli = `${appPath}/Contents/Resources/app/bin/${def.cli}`;
20450
20469
  if ((0, import_fs2.existsSync)(bundledCli)) resolvedCli = bundledCli;
20451
20470
  }
20452
- if (!resolvedCli && appPath && os162 === "win32") {
20471
+ if (!resolvedCli && appPath && os172 === "win32") {
20453
20472
  const { dirname: dirname72 } = await import("path");
20454
20473
  const appDir = dirname72(appPath);
20455
20474
  const candidates = [
@@ -22149,8 +22168,6 @@ var ChatHistoryWriter = class {
22149
22168
  lastSeenCounts = /* @__PURE__ */ new Map();
22150
22169
  /** Last seen message hash per agent (deduplication) */
22151
22170
  lastSeenHashes = /* @__PURE__ */ new Map();
22152
- /** Last seen append-only terminal transcript per agent */
22153
- lastSeenTerminal = /* @__PURE__ */ new Map();
22154
22171
  rotated = false;
22155
22172
  /**
22156
22173
  * Append new messages to history
@@ -22208,51 +22225,10 @@ var ChatHistoryWriter = class {
22208
22225
  } catch {
22209
22226
  }
22210
22227
  }
22211
- appendTerminalHistory(agentType, terminalHistory, sessionTitle, instanceId) {
22212
- const next = String(terminalHistory || "");
22213
- if (!next.trim()) return;
22214
- try {
22215
- const dedupKey = instanceId ? `${agentType}:${instanceId}:terminal` : `${agentType}:terminal`;
22216
- const prev = this.lastSeenTerminal.get(dedupKey) || "";
22217
- if (prev === next) return;
22218
- let delta = "";
22219
- if (!prev) {
22220
- delta = next;
22221
- } else if (next.startsWith(prev)) {
22222
- delta = next.slice(prev.length);
22223
- } else if (prev.includes(next)) {
22224
- this.lastSeenTerminal.set(dedupKey, next);
22225
- return;
22226
- } else {
22227
- delta = `
22228
-
22229
- [terminal snapshot reset ${(/* @__PURE__ */ new Date()).toISOString()} | ${sessionTitle || agentType}]
22230
- ${next}`;
22231
- }
22232
- if (!delta) {
22233
- this.lastSeenTerminal.set(dedupKey, next);
22234
- return;
22235
- }
22236
- const dir = path4.join(HISTORY_DIR, this.sanitize(agentType));
22237
- fs3.mkdirSync(dir, { recursive: true });
22238
- const date5 = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
22239
- const filePrefix = instanceId ? `${this.sanitize(instanceId)}_` : "";
22240
- const filePath = path4.join(dir, `${filePrefix}${date5}.terminal.log`);
22241
- fs3.appendFileSync(filePath, delta, "utf-8");
22242
- this.lastSeenTerminal.set(dedupKey, next);
22243
- if (!this.rotated) {
22244
- this.rotated = true;
22245
- this.rotateOldFiles().catch(() => {
22246
- });
22247
- }
22248
- } catch {
22249
- }
22250
- }
22251
22228
  /** Called when agent session is explicitly changed */
22252
22229
  onSessionChange(agentType) {
22253
22230
  this.lastSeenHashes.delete(agentType);
22254
22231
  this.lastSeenCounts.delete(agentType);
22255
- this.lastSeenTerminal.delete(`${agentType}:terminal`);
22256
22232
  }
22257
22233
  /** Delete history files older than 30 days */
22258
22234
  async rotateOldFiles() {
@@ -22943,7 +22919,6 @@ var STATUS_ACTIVE_CHAT_MESSAGE_LIMIT = 60;
22943
22919
  var STATUS_ACTIVE_CHAT_TOTAL_BYTES_LIMIT = 96 * 1024;
22944
22920
  var STATUS_ACTIVE_CHAT_STRING_LIMIT = 4 * 1024;
22945
22921
  var STATUS_ACTIVE_CHAT_FALLBACK_STRING_LIMIT = 1024;
22946
- var STATUS_TERMINAL_HISTORY_LIMIT = 8 * 1024;
22947
22922
  var STATUS_INPUT_CONTENT_LIMIT = 2 * 1024;
22948
22923
  var STATUS_MODAL_MESSAGE_LIMIT = 2 * 1024;
22949
22924
  var STATUS_MODAL_BUTTON_LIMIT = 120;
@@ -22952,11 +22927,6 @@ function truncateString(value, maxChars) {
22952
22927
  if (maxChars <= 12) return value.slice(0, Math.max(0, maxChars));
22953
22928
  return `${value.slice(0, maxChars - 12)}...[truncated]`;
22954
22929
  }
22955
- function truncateStringTail(value, maxChars) {
22956
- if (value.length <= maxChars) return value;
22957
- if (maxChars <= 12) return value.slice(value.length - Math.max(0, maxChars));
22958
- return `...[truncated]${value.slice(value.length - (maxChars - 12))}`;
22959
- }
22960
22930
  function trimStructuredStrings(value, maxChars) {
22961
22931
  if (typeof value === "string") return truncateString(value, maxChars);
22962
22932
  if (Array.isArray(value)) return value.map((item) => trimStructuredStrings(item, maxChars));
@@ -23024,7 +22994,6 @@ function normalizeActiveChatData(activeChat) {
23024
22994
  (button) => truncateString(String(button || ""), STATUS_MODAL_BUTTON_LIMIT)
23025
22995
  )
23026
22996
  } : activeChat.activeModal,
23027
- terminalHistory: activeChat.terminalHistory ? truncateStringTail(activeChat.terminalHistory, STATUS_TERMINAL_HISTORY_LIMIT) : activeChat.terminalHistory,
23028
22997
  inputContent: activeChat.inputContent ? truncateString(activeChat.inputContent, STATUS_INPUT_CONTENT_LIMIT) : activeChat.inputContent
23029
22998
  };
23030
22999
  }
@@ -26285,7 +26254,7 @@ function detectCurrentWorkspace(ideId) {
26285
26254
  }
26286
26255
  } else if (plat === "win32") {
26287
26256
  try {
26288
- const fs122 = __require("fs");
26257
+ const fs132 = __require("fs");
26289
26258
  const appNameMap = getMacAppIdentifiers();
26290
26259
  const appName = appNameMap[ideId];
26291
26260
  if (appName) {
@@ -26294,8 +26263,8 @@ function detectCurrentWorkspace(ideId) {
26294
26263
  appName,
26295
26264
  "storage.json"
26296
26265
  );
26297
- if (fs122.existsSync(storagePath)) {
26298
- const data = JSON.parse(fs122.readFileSync(storagePath, "utf-8"));
26266
+ if (fs132.existsSync(storagePath)) {
26267
+ const data = JSON.parse(fs132.readFileSync(storagePath, "utf-8"));
26299
26268
  const workspaces = data?.openedPathsList?.workspaces3 || data?.openedPathsList?.entries || [];
26300
26269
  if (workspaces.length > 0) {
26301
26270
  const recent = workspaces[0];
@@ -26699,6 +26668,182 @@ function buildStatusSnapshot(options) {
26699
26668
  availableProviders: buildAvailableProviders(options.providerLoader)
26700
26669
  };
26701
26670
  }
26671
+ var UPGRADE_HELPER_ENV = "ADHDEV_DAEMON_UPGRADE_HELPER";
26672
+ function getUpgradeLogPath() {
26673
+ const home = os11.homedir();
26674
+ const dir = path9.join(home, ".adhdev");
26675
+ fs7.mkdirSync(dir, { recursive: true });
26676
+ return path9.join(dir, "daemon-upgrade.log");
26677
+ }
26678
+ function appendUpgradeLog(message) {
26679
+ const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${message}
26680
+ `;
26681
+ try {
26682
+ fs7.appendFileSync(getUpgradeLogPath(), line, "utf8");
26683
+ } catch {
26684
+ }
26685
+ }
26686
+ function getNpmExecutable() {
26687
+ return process.platform === "win32" ? "npm.cmd" : "npm";
26688
+ }
26689
+ function killPid(pid) {
26690
+ try {
26691
+ if (process.platform === "win32") {
26692
+ (0, import_child_process6.execFileSync)("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore" });
26693
+ } else {
26694
+ process.kill(pid, "SIGTERM");
26695
+ }
26696
+ return true;
26697
+ } catch {
26698
+ return false;
26699
+ }
26700
+ }
26701
+ async function waitForPidExit(pid, timeoutMs) {
26702
+ const start = Date.now();
26703
+ while (Date.now() - start < timeoutMs) {
26704
+ try {
26705
+ process.kill(pid, 0);
26706
+ await new Promise((resolve92) => setTimeout(resolve92, 250));
26707
+ } catch {
26708
+ return;
26709
+ }
26710
+ }
26711
+ }
26712
+ function stopSessionHostProcesses(appName) {
26713
+ const pidFile = path9.join(os11.homedir(), ".adhdev", `${appName}-session-host.pid`);
26714
+ try {
26715
+ if (fs7.existsSync(pidFile)) {
26716
+ const pid = Number.parseInt(fs7.readFileSync(pidFile, "utf8").trim(), 10);
26717
+ if (Number.isFinite(pid)) {
26718
+ killPid(pid);
26719
+ }
26720
+ }
26721
+ } catch {
26722
+ } finally {
26723
+ try {
26724
+ fs7.unlinkSync(pidFile);
26725
+ } catch {
26726
+ }
26727
+ }
26728
+ if (process.platform !== "win32") {
26729
+ try {
26730
+ const raw = (0, import_child_process6.execFileSync)("pgrep", ["-f", "session-host-daemon"], { encoding: "utf8" }).trim();
26731
+ for (const line of raw.split("\n")) {
26732
+ const pid = Number.parseInt(line.trim(), 10);
26733
+ if (Number.isFinite(pid)) {
26734
+ killPid(pid);
26735
+ }
26736
+ }
26737
+ } catch {
26738
+ }
26739
+ }
26740
+ }
26741
+ function removeDaemonPidFile() {
26742
+ const pidFile = path9.join(os11.homedir(), ".adhdev", "daemon.pid");
26743
+ try {
26744
+ fs7.unlinkSync(pidFile);
26745
+ } catch {
26746
+ }
26747
+ }
26748
+ function cleanupStaleGlobalInstallDirs(pkgName) {
26749
+ const npmRoot = (0, import_child_process6.execFileSync)(getNpmExecutable(), ["root", "-g"], { encoding: "utf8" }).trim();
26750
+ if (!npmRoot) return;
26751
+ const npmPrefix = (0, import_child_process6.execFileSync)(getNpmExecutable(), ["prefix", "-g"], { encoding: "utf8" }).trim();
26752
+ const binDir = process.platform === "win32" ? npmPrefix : path9.join(npmPrefix, "bin");
26753
+ const packageBaseName = pkgName.startsWith("@") ? pkgName.split("/")[1] : pkgName;
26754
+ const binNames = /* @__PURE__ */ new Set([packageBaseName]);
26755
+ if (pkgName === "@adhdev/daemon-standalone") {
26756
+ binNames.add("adhdev-standalone");
26757
+ }
26758
+ if (pkgName.startsWith("@")) {
26759
+ const [scope, name] = pkgName.split("/");
26760
+ const scopeDir = path9.join(npmRoot, scope);
26761
+ if (!fs7.existsSync(scopeDir)) return;
26762
+ for (const entry of fs7.readdirSync(scopeDir)) {
26763
+ if (!entry.startsWith(`.${name}-`)) continue;
26764
+ fs7.rmSync(path9.join(scopeDir, entry), { recursive: true, force: true });
26765
+ appendUpgradeLog(`Removed stale scoped staging dir: ${path9.join(scopeDir, entry)}`);
26766
+ }
26767
+ } else {
26768
+ for (const entry of fs7.readdirSync(npmRoot)) {
26769
+ if (!entry.startsWith(`.${pkgName}-`)) continue;
26770
+ fs7.rmSync(path9.join(npmRoot, entry), { recursive: true, force: true });
26771
+ appendUpgradeLog(`Removed stale staging dir: ${path9.join(npmRoot, entry)}`);
26772
+ }
26773
+ }
26774
+ if (fs7.existsSync(binDir)) {
26775
+ for (const entry of fs7.readdirSync(binDir)) {
26776
+ if (![...binNames].some((name) => entry.startsWith(`.${name}-`))) continue;
26777
+ fs7.rmSync(path9.join(binDir, entry), { recursive: true, force: true });
26778
+ appendUpgradeLog(`Removed stale bin staging entry: ${path9.join(binDir, entry)}`);
26779
+ }
26780
+ }
26781
+ }
26782
+ function spawnDetachedDaemonUpgradeHelper(payload) {
26783
+ const env = { ...process.env, [UPGRADE_HELPER_ENV]: JSON.stringify(payload) };
26784
+ const child = (0, import_child_process7.spawn)(process.execPath, process.argv.slice(1), {
26785
+ detached: true,
26786
+ stdio: "ignore",
26787
+ windowsHide: true,
26788
+ cwd: payload.cwd || process.cwd(),
26789
+ env
26790
+ });
26791
+ child.unref();
26792
+ }
26793
+ async function runDaemonUpgradeHelper(payload) {
26794
+ const restartArgv = Array.isArray(payload.restartArgv) ? payload.restartArgv : [];
26795
+ const sessionHostAppName = payload.sessionHostAppName || process.env.ADHDEV_SESSION_HOST_NAME || "adhdev";
26796
+ appendUpgradeLog(`Upgrade helper started for ${payload.packageName}@${payload.targetVersion}`);
26797
+ if (Number.isFinite(payload.parentPid) && payload.parentPid > 0) {
26798
+ appendUpgradeLog(`Waiting for parent pid ${payload.parentPid} to exit`);
26799
+ await waitForPidExit(payload.parentPid, 15e3);
26800
+ }
26801
+ stopSessionHostProcesses(sessionHostAppName);
26802
+ removeDaemonPidFile();
26803
+ cleanupStaleGlobalInstallDirs(payload.packageName);
26804
+ const spec = `${payload.packageName}@${payload.targetVersion || "latest"}`;
26805
+ appendUpgradeLog(`Installing ${spec}`);
26806
+ const installOutput = (0, import_child_process6.execFileSync)(
26807
+ getNpmExecutable(),
26808
+ ["install", "-g", spec, "--force"],
26809
+ {
26810
+ encoding: "utf8",
26811
+ stdio: "pipe",
26812
+ maxBuffer: 20 * 1024 * 1024
26813
+ }
26814
+ );
26815
+ if (installOutput.trim()) {
26816
+ appendUpgradeLog(installOutput.trim());
26817
+ }
26818
+ if (restartArgv.length > 0) {
26819
+ const env = { ...process.env };
26820
+ delete env[UPGRADE_HELPER_ENV];
26821
+ appendUpgradeLog(`Restarting daemon with args: ${restartArgv.join(" ")}`);
26822
+ const child = (0, import_child_process7.spawn)(process.execPath, restartArgv, {
26823
+ detached: true,
26824
+ stdio: "ignore",
26825
+ windowsHide: true,
26826
+ cwd: payload.cwd || process.cwd(),
26827
+ env
26828
+ });
26829
+ child.unref();
26830
+ } else {
26831
+ appendUpgradeLog("No restart argv provided; upgrade completed without restart");
26832
+ }
26833
+ }
26834
+ async function maybeRunDaemonUpgradeHelperFromEnv() {
26835
+ const raw = process.env[UPGRADE_HELPER_ENV];
26836
+ if (!raw) return false;
26837
+ delete process.env[UPGRADE_HELPER_ENV];
26838
+ try {
26839
+ const payload = JSON.parse(raw);
26840
+ await runDaemonUpgradeHelper(payload);
26841
+ process.exit(0);
26842
+ } catch (error48) {
26843
+ appendUpgradeLog(`Upgrade helper failed: ${error48?.stack || error48?.message || String(error48)}`);
26844
+ process.exit(1);
26845
+ }
26846
+ }
26702
26847
  var CHAT_COMMANDS = [
26703
26848
  "send_chat",
26704
26849
  "new_chat",
@@ -26769,8 +26914,8 @@ var DaemonCommandRouter = class {
26769
26914
  if (logs.length > 0) {
26770
26915
  return { success: true, logs, totalBuffered: logs.length };
26771
26916
  }
26772
- if (fs7.existsSync(LOG_PATH)) {
26773
- const content = fs7.readFileSync(LOG_PATH, "utf-8");
26917
+ if (fs8.existsSync(LOG_PATH)) {
26918
+ const content = fs8.readFileSync(LOG_PATH, "utf-8");
26774
26919
  const allLines = content.split("\n");
26775
26920
  const recent = allLines.slice(-count).join("\n");
26776
26921
  return { success: true, logs: recent, totalLines: allLines.length };
@@ -26918,31 +27063,35 @@ var DaemonCommandRouter = class {
26918
27063
  const pkgName = isStandalone ? "@adhdev/daemon-standalone" : "adhdev";
26919
27064
  const latest = execSync7(`npm view ${pkgName} version`, { encoding: "utf-8", timeout: 1e4 }).trim();
26920
27065
  LOG.info("Upgrade", `Latest ${pkgName}: v${latest}`);
26921
- execSync7(`npm install -g ${pkgName}@latest --force`, {
26922
- encoding: "utf-8",
26923
- timeout: 12e4,
26924
- stdio: ["pipe", "pipe", "pipe"]
27066
+ let currentInstalled = null;
27067
+ try {
27068
+ const currentJson = execSync7(`npm ls -g ${pkgName} --depth=0 --json`, {
27069
+ encoding: "utf-8",
27070
+ timeout: 1e4,
27071
+ stdio: ["pipe", "pipe", "pipe"]
27072
+ }).trim();
27073
+ const parsed = JSON.parse(currentJson);
27074
+ currentInstalled = parsed?.dependencies?.[pkgName]?.version || null;
27075
+ } catch {
27076
+ }
27077
+ if (currentInstalled === latest) {
27078
+ LOG.info("Upgrade", `Already on latest version v${latest}; skipping install`);
27079
+ return { success: true, upgraded: false, alreadyLatest: true, version: latest };
27080
+ }
27081
+ spawnDetachedDaemonUpgradeHelper({
27082
+ packageName: pkgName,
27083
+ targetVersion: latest,
27084
+ parentPid: process.pid,
27085
+ restartArgv: process.argv.slice(1),
27086
+ cwd: process.cwd(),
27087
+ sessionHostAppName: process.env.ADHDEV_SESSION_HOST_NAME || "adhdev"
26925
27088
  });
26926
- LOG.info("Upgrade", `\u2705 Upgraded to v${latest}`);
27089
+ LOG.info("Upgrade", `Scheduled detached upgrade to v${latest}`);
26927
27090
  setTimeout(() => {
26928
- LOG.info("Upgrade", "Restarting daemon with new version...");
26929
- try {
26930
- const path152 = __require("path");
26931
- const fs122 = __require("fs");
26932
- const pidFile = path152.join(process.env.HOME || process.env.USERPROFILE || "", ".adhdev", "daemon.pid");
26933
- if (fs122.existsSync(pidFile)) fs122.unlinkSync(pidFile);
26934
- } catch {
26935
- }
26936
- const { spawn: spawn32 } = __require("child_process");
26937
- const child = spawn32(process.execPath, process.argv.slice(1), {
26938
- detached: true,
26939
- stdio: "ignore",
26940
- env: { ...process.env }
26941
- });
26942
- child.unref();
27091
+ LOG.info("Upgrade", "Exiting daemon so detached upgrader can continue...");
26943
27092
  process.exit(0);
26944
27093
  }, 3e3);
26945
- return { success: true, upgraded: true, version: latest };
27094
+ return { success: true, upgraded: true, version: latest, restarting: true };
26946
27095
  } catch (e) {
26947
27096
  LOG.error("Upgrade", `Failed: ${e.message}`);
26948
27097
  return { success: false, error: e.message };
@@ -27033,7 +27182,7 @@ var CliProviderInstance = class {
27033
27182
  this.cliArgs = cliArgs;
27034
27183
  this.type = provider.type;
27035
27184
  this.instanceId = instanceId || crypto3.randomUUID();
27036
- this.presentationMode = "terminal";
27185
+ this.presentationMode = "chat";
27037
27186
  this.adapter = new ProviderCliAdapter(provider, workingDir, cliArgs, transportFactory);
27038
27187
  this.monitor = new StatusMonitor();
27039
27188
  this.historyWriter = new ChatHistoryWriter();
@@ -27080,14 +27229,6 @@ var CliProviderInstance = class {
27080
27229
  const parsedStatus = this.adapter.getScriptParsedStatus?.() || null;
27081
27230
  const runtime = this.adapter.getRuntimeMetadata();
27082
27231
  const dirName = this.workingDir.split("/").filter(Boolean).pop() || "session";
27083
- if (adapterStatus.terminalHistory?.trim()) {
27084
- this.historyWriter.appendTerminalHistory(
27085
- this.type,
27086
- adapterStatus.terminalHistory,
27087
- `${this.provider.name} \xB7 ${dirName}`,
27088
- this.instanceId
27089
- );
27090
- }
27091
27232
  return {
27092
27233
  type: this.type,
27093
27234
  name: this.provider.name,
@@ -27100,7 +27241,6 @@ var CliProviderInstance = class {
27100
27241
  status: parsedStatus?.status || adapterStatus.status,
27101
27242
  messages: Array.isArray(parsedStatus?.messages) ? parsedStatus.messages : [],
27102
27243
  activeModal: parsedStatus?.activeModal ?? adapterStatus.activeModal,
27103
- terminalHistory: adapterStatus.terminalHistory,
27104
27244
  inputContent: ""
27105
27245
  },
27106
27246
  workspace: this.workingDir,
@@ -27593,7 +27733,7 @@ var AcpProviderInstance = class {
27593
27733
  this.errorMessage = null;
27594
27734
  this.errorReason = null;
27595
27735
  this.stderrBuffer = [];
27596
- this.process = (0, import_child_process6.spawn)(command, args, {
27736
+ this.process = (0, import_child_process8.spawn)(command, args, {
27597
27737
  cwd: this.workingDir,
27598
27738
  env,
27599
27739
  stdio: ["pipe", "pipe", "pipe"],
@@ -28274,7 +28414,7 @@ var DaemonCliManager = class {
28274
28414
  async startSession(cliType, workingDir, cliArgs, initialModel) {
28275
28415
  const trimmed = (workingDir || "").trim();
28276
28416
  if (!trimmed) throw new Error("working directory required");
28277
- const resolvedDir = trimmed.startsWith("~") ? trimmed.replace(/^~/, os13.homedir()) : path10.resolve(trimmed);
28417
+ const resolvedDir = trimmed.startsWith("~") ? trimmed.replace(/^~/, os14.homedir()) : path11.resolve(trimmed);
28278
28418
  const normalizedType = this.providerLoader.resolveAlias(cliType);
28279
28419
  const provider = this.providerLoader.getByAlias(cliType);
28280
28420
  const key = crypto4.randomUUID();
@@ -29455,7 +29595,7 @@ var ProviderInstanceManager = class {
29455
29595
  this.eventListeners = [];
29456
29596
  }
29457
29597
  };
29458
- var ARCHIVE_PATH = path11.join(os14.homedir(), ".adhdev", "version-history.json");
29598
+ var ARCHIVE_PATH = path12.join(os15.homedir(), ".adhdev", "version-history.json");
29459
29599
  var MAX_ENTRIES_PER_PROVIDER = 20;
29460
29600
  var VersionArchive = class {
29461
29601
  history = {};
@@ -29464,8 +29604,8 @@ var VersionArchive = class {
29464
29604
  }
29465
29605
  load() {
29466
29606
  try {
29467
- if (fs8.existsSync(ARCHIVE_PATH)) {
29468
- this.history = JSON.parse(fs8.readFileSync(ARCHIVE_PATH, "utf-8"));
29607
+ if (fs9.existsSync(ARCHIVE_PATH)) {
29608
+ this.history = JSON.parse(fs9.readFileSync(ARCHIVE_PATH, "utf-8"));
29469
29609
  }
29470
29610
  } catch {
29471
29611
  this.history = {};
@@ -29502,15 +29642,15 @@ var VersionArchive = class {
29502
29642
  }
29503
29643
  save() {
29504
29644
  try {
29505
- fs8.mkdirSync(path11.dirname(ARCHIVE_PATH), { recursive: true });
29506
- fs8.writeFileSync(ARCHIVE_PATH, JSON.stringify(this.history, null, 2));
29645
+ fs9.mkdirSync(path12.dirname(ARCHIVE_PATH), { recursive: true });
29646
+ fs9.writeFileSync(ARCHIVE_PATH, JSON.stringify(this.history, null, 2));
29507
29647
  } catch {
29508
29648
  }
29509
29649
  }
29510
29650
  };
29511
29651
  function runCommand(cmd, timeout = 1e4) {
29512
29652
  try {
29513
- return (0, import_child_process7.execSync)(cmd, {
29653
+ return (0, import_child_process9.execSync)(cmd, {
29514
29654
  encoding: "utf-8",
29515
29655
  timeout,
29516
29656
  stdio: ["pipe", "pipe", "pipe"]
@@ -29542,19 +29682,19 @@ function getVersion(binary, versionCommand) {
29542
29682
  function checkPathExists2(paths) {
29543
29683
  for (const p of paths) {
29544
29684
  if (p.includes("*")) {
29545
- const home = os14.homedir();
29546
- const resolved = p.replace(/\*/g, home.split(path11.sep).pop() || "");
29547
- if (fs8.existsSync(resolved)) return resolved;
29685
+ const home = os15.homedir();
29686
+ const resolved = p.replace(/\*/g, home.split(path12.sep).pop() || "");
29687
+ if (fs9.existsSync(resolved)) return resolved;
29548
29688
  } else {
29549
- if (fs8.existsSync(p)) return p;
29689
+ if (fs9.existsSync(p)) return p;
29550
29690
  }
29551
29691
  }
29552
29692
  return null;
29553
29693
  }
29554
29694
  function getMacAppVersion(appPath) {
29555
29695
  if ((0, import_os3.platform)() !== "darwin" || !appPath.endsWith(".app")) return null;
29556
- const plistPath = path11.join(appPath, "Contents", "Info.plist");
29557
- if (!fs8.existsSync(plistPath)) return null;
29696
+ const plistPath = path12.join(appPath, "Contents", "Info.plist");
29697
+ if (!fs9.existsSync(plistPath)) return null;
29558
29698
  const raw = runCommand(`/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "${plistPath}"`);
29559
29699
  return raw || null;
29560
29700
  }
@@ -29580,8 +29720,8 @@ async function detectAllVersions(loader, archive) {
29580
29720
  const cliBin = provider.cli ? findBinary2(provider.cli) : null;
29581
29721
  let resolvedBin = cliBin;
29582
29722
  if (!resolvedBin && appPath && currentOs === "darwin") {
29583
- const bundled = path11.join(appPath, "Contents", "Resources", "app", "bin", provider.cli || "");
29584
- if (provider.cli && fs8.existsSync(bundled)) resolvedBin = bundled;
29723
+ const bundled = path12.join(appPath, "Contents", "Resources", "app", "bin", provider.cli || "");
29724
+ if (provider.cli && fs9.existsSync(bundled)) resolvedBin = bundled;
29585
29725
  }
29586
29726
  info.installed = !!(appPath || resolvedBin);
29587
29727
  info.path = appPath || null;
@@ -30123,18 +30263,18 @@ async function handleScriptHints(ctx, type, _req, res) {
30123
30263
  return;
30124
30264
  }
30125
30265
  let scriptsPath = "";
30126
- const directScripts = path12.join(dir, "scripts.js");
30127
- if (fs9.existsSync(directScripts)) {
30266
+ const directScripts = path13.join(dir, "scripts.js");
30267
+ if (fs10.existsSync(directScripts)) {
30128
30268
  scriptsPath = directScripts;
30129
30269
  } else {
30130
- const scriptsDir = path12.join(dir, "scripts");
30131
- if (fs9.existsSync(scriptsDir)) {
30132
- const versions = fs9.readdirSync(scriptsDir).filter((d) => {
30133
- return fs9.statSync(path12.join(scriptsDir, d)).isDirectory();
30270
+ const scriptsDir = path13.join(dir, "scripts");
30271
+ if (fs10.existsSync(scriptsDir)) {
30272
+ const versions = fs10.readdirSync(scriptsDir).filter((d) => {
30273
+ return fs10.statSync(path13.join(scriptsDir, d)).isDirectory();
30134
30274
  }).sort().reverse();
30135
30275
  for (const ver of versions) {
30136
- const p = path12.join(scriptsDir, ver, "scripts.js");
30137
- if (fs9.existsSync(p)) {
30276
+ const p = path13.join(scriptsDir, ver, "scripts.js");
30277
+ if (fs10.existsSync(p)) {
30138
30278
  scriptsPath = p;
30139
30279
  break;
30140
30280
  }
@@ -30146,7 +30286,7 @@ async function handleScriptHints(ctx, type, _req, res) {
30146
30286
  return;
30147
30287
  }
30148
30288
  try {
30149
- const source = fs9.readFileSync(scriptsPath, "utf-8");
30289
+ const source = fs10.readFileSync(scriptsPath, "utf-8");
30150
30290
  const hints = {};
30151
30291
  const funcRegex = /module\.exports\.(\w+)\s*=\s*function\s+\w+\s*\(params\)/g;
30152
30292
  let match;
@@ -31198,45 +31338,45 @@ function resolveAutoImplReference(ctx, category, requestedReference, targetType)
31198
31338
  return fallback?.type || null;
31199
31339
  }
31200
31340
  function getLatestScriptVersionDir(scriptsDir) {
31201
- if (!fs10.existsSync(scriptsDir)) return null;
31202
- const versions = fs10.readdirSync(scriptsDir).filter((d) => {
31341
+ if (!fs11.existsSync(scriptsDir)) return null;
31342
+ const versions = fs11.readdirSync(scriptsDir).filter((d) => {
31203
31343
  try {
31204
- return fs10.statSync(path13.join(scriptsDir, d)).isDirectory();
31344
+ return fs11.statSync(path14.join(scriptsDir, d)).isDirectory();
31205
31345
  } catch {
31206
31346
  return false;
31207
31347
  }
31208
31348
  }).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" }));
31209
31349
  if (versions.length === 0) return null;
31210
- return path13.join(scriptsDir, versions[0]);
31350
+ return path14.join(scriptsDir, versions[0]);
31211
31351
  }
31212
31352
  function resolveAutoImplWritableProviderDir(ctx, category, type, requestedDir) {
31213
- const canonicalUserDir = path13.resolve(ctx.providerLoader.getUserProviderDir(category, type));
31214
- const desiredDir = requestedDir ? path13.resolve(requestedDir) : canonicalUserDir;
31215
- const upstreamRoot = path13.resolve(ctx.providerLoader.getUpstreamDir());
31216
- if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path13.sep}`)) {
31353
+ const canonicalUserDir = path14.resolve(ctx.providerLoader.getUserProviderDir(category, type));
31354
+ const desiredDir = requestedDir ? path14.resolve(requestedDir) : canonicalUserDir;
31355
+ const upstreamRoot = path14.resolve(ctx.providerLoader.getUpstreamDir());
31356
+ if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path14.sep}`)) {
31217
31357
  return { dir: null, reason: `Refusing to write into upstream provider directory: ${desiredDir}` };
31218
31358
  }
31219
- if (path13.basename(desiredDir) !== type) {
31359
+ if (path14.basename(desiredDir) !== type) {
31220
31360
  return { dir: null, reason: `Requested writable provider directory must end with '${type}': ${desiredDir}` };
31221
31361
  }
31222
31362
  const sourceDir = ctx.findProviderDir(type);
31223
31363
  if (!sourceDir) {
31224
31364
  return { dir: null, reason: `Provider source directory not found for '${type}'` };
31225
31365
  }
31226
- if (!fs10.existsSync(desiredDir)) {
31227
- fs10.mkdirSync(path13.dirname(desiredDir), { recursive: true });
31228
- fs10.cpSync(sourceDir, desiredDir, { recursive: true });
31366
+ if (!fs11.existsSync(desiredDir)) {
31367
+ fs11.mkdirSync(path14.dirname(desiredDir), { recursive: true });
31368
+ fs11.cpSync(sourceDir, desiredDir, { recursive: true });
31229
31369
  ctx.log(`Auto-implement writable copy created: ${desiredDir}`);
31230
31370
  }
31231
- const providerJson = path13.join(desiredDir, "provider.json");
31232
- if (!fs10.existsSync(providerJson)) {
31371
+ const providerJson = path14.join(desiredDir, "provider.json");
31372
+ if (!fs11.existsSync(providerJson)) {
31233
31373
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
31234
31374
  }
31235
31375
  try {
31236
- const providerData = JSON.parse(fs10.readFileSync(providerJson, "utf-8"));
31376
+ const providerData = JSON.parse(fs11.readFileSync(providerJson, "utf-8"));
31237
31377
  if (providerData.disableUpstream !== true) {
31238
31378
  providerData.disableUpstream = true;
31239
- fs10.writeFileSync(providerJson, JSON.stringify(providerData, null, 2));
31379
+ fs11.writeFileSync(providerJson, JSON.stringify(providerData, null, 2));
31240
31380
  }
31241
31381
  } catch (error48) {
31242
31382
  return {
@@ -31249,15 +31389,15 @@ function resolveAutoImplWritableProviderDir(ctx, category, type, requestedDir) {
31249
31389
  function loadAutoImplReferenceScripts(ctx, referenceType) {
31250
31390
  if (!referenceType) return {};
31251
31391
  const refDir = ctx.findProviderDir(referenceType);
31252
- if (!refDir || !fs10.existsSync(refDir)) return {};
31392
+ if (!refDir || !fs11.existsSync(refDir)) return {};
31253
31393
  const referenceScripts = {};
31254
- const scriptsDir = path13.join(refDir, "scripts");
31394
+ const scriptsDir = path14.join(refDir, "scripts");
31255
31395
  const latestDir = getLatestScriptVersionDir(scriptsDir);
31256
31396
  if (!latestDir) return referenceScripts;
31257
- for (const file2 of fs10.readdirSync(latestDir)) {
31397
+ for (const file2 of fs11.readdirSync(latestDir)) {
31258
31398
  if (!file2.endsWith(".js")) continue;
31259
31399
  try {
31260
- referenceScripts[file2] = fs10.readFileSync(path13.join(latestDir, file2), "utf-8");
31400
+ referenceScripts[file2] = fs11.readFileSync(path14.join(latestDir, file2), "utf-8");
31261
31401
  } catch {
31262
31402
  }
31263
31403
  }
@@ -31308,16 +31448,16 @@ async function handleAutoImplement(ctx, type, req, res) {
31308
31448
  });
31309
31449
  const referenceScripts = loadAutoImplReferenceScripts(ctx, resolvedReference);
31310
31450
  const prompt = buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domContext, referenceScripts, comment, resolvedReference);
31311
- const tmpDir = path13.join(os15.tmpdir(), "adhdev-autoimpl");
31312
- if (!fs10.existsSync(tmpDir)) fs10.mkdirSync(tmpDir, { recursive: true });
31313
- const promptFile = path13.join(tmpDir, `prompt-${type}-${Date.now()}.md`);
31314
- fs10.writeFileSync(promptFile, prompt, "utf-8");
31451
+ const tmpDir = path14.join(os16.tmpdir(), "adhdev-autoimpl");
31452
+ if (!fs11.existsSync(tmpDir)) fs11.mkdirSync(tmpDir, { recursive: true });
31453
+ const promptFile = path14.join(tmpDir, `prompt-${type}-${Date.now()}.md`);
31454
+ fs11.writeFileSync(promptFile, prompt, "utf-8");
31315
31455
  ctx.log(`Auto-implement prompt written to ${promptFile} (${prompt.length} chars)`);
31316
31456
  const agentProvider = ctx.providerLoader.resolve(agent) || ctx.providerLoader.getMeta(agent);
31317
- const spawn32 = agentProvider?.spawn;
31318
- if (!spawn32?.command) {
31457
+ const spawn42 = agentProvider?.spawn;
31458
+ if (!spawn42?.command) {
31319
31459
  try {
31320
- fs10.unlinkSync(promptFile);
31460
+ fs11.unlinkSync(promptFile);
31321
31461
  } catch {
31322
31462
  }
31323
31463
  ctx.json(res, 400, { error: `Agent '${agent}' has no spawn config. Select a CLI provider with a spawn configuration.` });
@@ -31325,21 +31465,21 @@ async function handleAutoImplement(ctx, type, req, res) {
31325
31465
  }
31326
31466
  const agentCategory = agentProvider?.category;
31327
31467
  if (agentCategory === "acp") {
31328
- sendAutoImplSSE(ctx, { event: "progress", data: { function: "_init", status: "spawning", message: `Spawning ACP agent: ${spawn32.command} ${(spawn32.args || []).join(" ")}` } });
31468
+ sendAutoImplSSE(ctx, { event: "progress", data: { function: "_init", status: "spawning", message: `Spawning ACP agent: ${spawn42.command} ${(spawn42.args || []).join(" ")}` } });
31329
31469
  ctx.autoImplStatus = { running: true, type, progress: [] };
31330
31470
  const { ClientSideConnection: ClientSideConnection2, ndJsonStream: ndJsonStream2, PROTOCOL_VERSION: PROTOCOL_VERSION2 } = await Promise.resolve().then(() => (init_acp(), acp_exports));
31331
31471
  const { Readable: Readable22, Writable: Writable2 } = await import("stream");
31332
31472
  const { spawn: spawnFn2 } = await import("child_process");
31333
- const acpArgs = [...spawn32.args || []];
31473
+ const acpArgs = [...spawn42.args || []];
31334
31474
  if (model) {
31335
31475
  acpArgs.push("--model", model);
31336
31476
  ctx.log(`Auto-implement ACP using model: ${model}`);
31337
31477
  }
31338
- const child2 = spawnFn2(spawn32.command, acpArgs, {
31478
+ const child2 = spawnFn2(spawn42.command, acpArgs, {
31339
31479
  cwd: providerDir,
31340
31480
  stdio: ["pipe", "pipe", "pipe"],
31341
- shell: spawn32.shell ?? false,
31342
- env: { ...process.env, ...spawn32.env || {} }
31481
+ shell: spawn42.shell ?? false,
31482
+ env: { ...process.env, ...spawn42.env || {} }
31343
31483
  });
31344
31484
  ctx.autoImplProcess = child2;
31345
31485
  child2.stderr?.on("data", (d) => {
@@ -31418,7 +31558,7 @@ async function handleAutoImplement(ctx, type, req, res) {
31418
31558
  } catch {
31419
31559
  }
31420
31560
  try {
31421
- fs10.unlinkSync(promptFile);
31561
+ fs11.unlinkSync(promptFile);
31422
31562
  } catch {
31423
31563
  }
31424
31564
  ctx.log(`Auto-implement (ACP) ${success2 ? "completed" : "failed"}: ${type} (exit: ${code})`);
@@ -31449,7 +31589,7 @@ async function handleAutoImplement(ctx, type, req, res) {
31449
31589
  ctx.json(res, 202, {
31450
31590
  started: true,
31451
31591
  type,
31452
- agent: spawn32.command,
31592
+ agent: spawn42.command,
31453
31593
  functions,
31454
31594
  providerDir,
31455
31595
  message: "ACP Auto-implement started. Connect to SSE for progress.",
@@ -31457,11 +31597,11 @@ async function handleAutoImplement(ctx, type, req, res) {
31457
31597
  });
31458
31598
  return;
31459
31599
  }
31460
- const command = spawn32.command;
31600
+ const command = spawn42.command;
31461
31601
  const interactiveFlags = ["--yolo", "--interactive", "-i"];
31462
- const baseArgs = [...spawn32.args || []].filter((a) => !interactiveFlags.includes(a));
31602
+ const baseArgs = [...spawn42.args || []].filter((a) => !interactiveFlags.includes(a));
31463
31603
  let shellCmd;
31464
- const isWin = os15.platform() === "win32";
31604
+ const isWin = os16.platform() === "win32";
31465
31605
  const escapeArg = (a) => isWin ? `"${a.replace(/"/g, '""')}"` : `'${a.replace(/'/g, "'\\''")}'`;
31466
31606
  if (command === "claude") {
31467
31607
  const args = [...baseArgs, "--dangerously-skip-permissions"];
@@ -31504,13 +31644,13 @@ async function handleAutoImplement(ctx, type, req, res) {
31504
31644
  try {
31505
31645
  const pty3 = __require("node-pty");
31506
31646
  ctx.log(`Auto-implement spawn (PTY): ${shellCmd}`);
31507
- const isWin2 = os15.platform() === "win32";
31647
+ const isWin2 = os16.platform() === "win32";
31508
31648
  child = pty3.spawn(isWin2 ? "cmd.exe" : process.env.SHELL || "/bin/zsh", [isWin2 ? "/c" : "-c", shellCmd], {
31509
31649
  name: "xterm-256color",
31510
31650
  cols: 120,
31511
31651
  rows: 40,
31512
31652
  cwd: providerDir,
31513
- env: { ...process.env, ...spawn32.env || {} }
31653
+ env: { ...process.env, ...spawn42.env || {} }
31514
31654
  });
31515
31655
  isPty = true;
31516
31656
  } catch (err) {
@@ -31522,7 +31662,7 @@ async function handleAutoImplement(ctx, type, req, res) {
31522
31662
  stdio: ["pipe", "pipe", "pipe"],
31523
31663
  env: {
31524
31664
  ...process.env,
31525
- ...spawn32.env || {},
31665
+ ...spawn42.env || {},
31526
31666
  ...command === "gemini" ? { SANDBOX: "1", GEMINI_CLI_NO_RELAUNCH: "1" } : {}
31527
31667
  }
31528
31668
  });
@@ -31598,7 +31738,7 @@ async function handleAutoImplement(ctx, type, req, res) {
31598
31738
  } catch {
31599
31739
  }
31600
31740
  try {
31601
- fs10.unlinkSync(promptFile);
31741
+ fs11.unlinkSync(promptFile);
31602
31742
  } catch {
31603
31743
  }
31604
31744
  });
@@ -31634,7 +31774,7 @@ async function handleAutoImplement(ctx, type, req, res) {
31634
31774
  } catch {
31635
31775
  }
31636
31776
  try {
31637
- fs10.unlinkSync(promptFile);
31777
+ fs11.unlinkSync(promptFile);
31638
31778
  } catch {
31639
31779
  }
31640
31780
  ctx.log(`Auto-implement ${success2 ? "completed" : "failed"}: ${type} (exit: ${code})`);
@@ -31681,7 +31821,7 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
31681
31821
  setMode: "set_mode.js"
31682
31822
  };
31683
31823
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
31684
- const scriptsDir = path13.join(providerDir, "scripts");
31824
+ const scriptsDir = path14.join(providerDir, "scripts");
31685
31825
  const latestScriptsDir = getLatestScriptVersionDir(scriptsDir);
31686
31826
  if (latestScriptsDir) {
31687
31827
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -31689,10 +31829,10 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
31689
31829
  lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
31690
31830
  lines.push("These are the ONLY files you are allowed to modify. Replace the TODO stubs with working implementations.");
31691
31831
  lines.push("");
31692
- for (const file2 of fs10.readdirSync(latestScriptsDir)) {
31832
+ for (const file2 of fs11.readdirSync(latestScriptsDir)) {
31693
31833
  if (file2.endsWith(".js") && targetFileNames.has(file2)) {
31694
31834
  try {
31695
- const content = fs10.readFileSync(path13.join(latestScriptsDir, file2), "utf-8");
31835
+ const content = fs11.readFileSync(path14.join(latestScriptsDir, file2), "utf-8");
31696
31836
  lines.push(`### \`${file2}\` \u270F\uFE0F EDIT`);
31697
31837
  lines.push("```javascript");
31698
31838
  lines.push(content);
@@ -31702,14 +31842,14 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
31702
31842
  }
31703
31843
  }
31704
31844
  }
31705
- const refFiles = fs10.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
31845
+ const refFiles = fs11.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
31706
31846
  if (refFiles.length > 0) {
31707
31847
  lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
31708
31848
  lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
31709
31849
  lines.push("");
31710
31850
  for (const file2 of refFiles) {
31711
31851
  try {
31712
- const content = fs10.readFileSync(path13.join(latestScriptsDir, file2), "utf-8");
31852
+ const content = fs11.readFileSync(path14.join(latestScriptsDir, file2), "utf-8");
31713
31853
  lines.push(`### \`${file2}\` \u{1F512}`);
31714
31854
  lines.push("```javascript");
31715
31855
  lines.push(content);
@@ -31750,11 +31890,11 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
31750
31890
  lines.push("");
31751
31891
  }
31752
31892
  }
31753
- const docsDir = path13.join(providerDir, "../../docs");
31893
+ const docsDir = path14.join(providerDir, "../../docs");
31754
31894
  const loadGuide = (name) => {
31755
31895
  try {
31756
- const p = path13.join(docsDir, name);
31757
- if (fs10.existsSync(p)) return fs10.readFileSync(p, "utf-8");
31896
+ const p = path14.join(docsDir, name);
31897
+ if (fs11.existsSync(p)) return fs11.readFileSync(p, "utf-8");
31758
31898
  } catch {
31759
31899
  }
31760
31900
  return null;
@@ -31927,7 +32067,7 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
31927
32067
  parseApproval: "parse_approval.js"
31928
32068
  };
31929
32069
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
31930
- const scriptsDir = path13.join(providerDir, "scripts");
32070
+ const scriptsDir = path14.join(providerDir, "scripts");
31931
32071
  const latestScriptsDir = getLatestScriptVersionDir(scriptsDir);
31932
32072
  if (latestScriptsDir) {
31933
32073
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -31935,11 +32075,11 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
31935
32075
  lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
31936
32076
  lines.push("These are the ONLY files you are allowed to modify. Replace TODO or heuristic-only logic with working PTY-aware implementations.");
31937
32077
  lines.push("");
31938
- for (const file2 of fs10.readdirSync(latestScriptsDir)) {
32078
+ for (const file2 of fs11.readdirSync(latestScriptsDir)) {
31939
32079
  if (!file2.endsWith(".js")) continue;
31940
32080
  if (!targetFileNames.has(file2)) continue;
31941
32081
  try {
31942
- const content = fs10.readFileSync(path13.join(latestScriptsDir, file2), "utf-8");
32082
+ const content = fs11.readFileSync(path14.join(latestScriptsDir, file2), "utf-8");
31943
32083
  lines.push(`### \`${file2}\` \u270F\uFE0F EDIT`);
31944
32084
  lines.push("```javascript");
31945
32085
  lines.push(content);
@@ -31948,14 +32088,14 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
31948
32088
  } catch {
31949
32089
  }
31950
32090
  }
31951
- const refFiles = fs10.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
32091
+ const refFiles = fs11.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
31952
32092
  if (refFiles.length > 0) {
31953
32093
  lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
31954
32094
  lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
31955
32095
  lines.push("");
31956
32096
  for (const file2 of refFiles) {
31957
32097
  try {
31958
- const content = fs10.readFileSync(path13.join(latestScriptsDir, file2), "utf-8");
32098
+ const content = fs11.readFileSync(path14.join(latestScriptsDir, file2), "utf-8");
31959
32099
  lines.push(`### \`${file2}\` \u{1F512}`);
31960
32100
  lines.push("```javascript");
31961
32101
  lines.push(content);
@@ -31988,11 +32128,11 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
31988
32128
  lines.push("");
31989
32129
  }
31990
32130
  }
31991
- const docsDir = path13.join(providerDir, "../../docs");
32131
+ const docsDir = path14.join(providerDir, "../../docs");
31992
32132
  const loadGuide = (name) => {
31993
32133
  try {
31994
- const p = path13.join(docsDir, name);
31995
- if (fs10.existsSync(p)) return fs10.readFileSync(p, "utf-8");
32134
+ const p = path14.join(docsDir, name);
32135
+ if (fs11.existsSync(p)) return fs11.readFileSync(p, "utf-8");
31996
32136
  } catch {
31997
32137
  }
31998
32138
  return null;
@@ -32247,8 +32387,8 @@ var DevServer = class _DevServer {
32247
32387
  }
32248
32388
  getEndpointList() {
32249
32389
  return this.routes.map((r) => {
32250
- const path152 = typeof r.pattern === "string" ? r.pattern : r.pattern.source.replace(/\\\//g, "/").replace(/\(\[.*?\]\+\)/g, ":type").replace(/[\^$]/g, "");
32251
- return `${r.method.padEnd(5)} ${path152}`;
32390
+ const path162 = typeof r.pattern === "string" ? r.pattern : r.pattern.source.replace(/\\\//g, "/").replace(/\(\[.*?\]\+\)/g, ":type").replace(/[\^$]/g, "");
32391
+ return `${r.method.padEnd(5)} ${path162}`;
32252
32392
  });
32253
32393
  }
32254
32394
  async start(port = DEV_SERVER_PORT) {
@@ -32349,16 +32489,16 @@ var DevServer = class _DevServer {
32349
32489
  this.json(res, 404, { error: `Provider not found: ${type}` });
32350
32490
  return;
32351
32491
  }
32352
- const spawn32 = provider.spawn;
32353
- if (!spawn32) {
32492
+ const spawn42 = provider.spawn;
32493
+ if (!spawn42) {
32354
32494
  this.json(res, 400, { error: `Provider ${type} has no spawn config` });
32355
32495
  return;
32356
32496
  }
32357
32497
  const { spawn: spawnFn } = await import("child_process");
32358
32498
  const start = Date.now();
32359
32499
  try {
32360
- const child = spawnFn(spawn32.command, [...spawn32.args || []], {
32361
- shell: spawn32.shell ?? false,
32500
+ const child = spawnFn(spawn42.command, [...spawn42.args || []], {
32501
+ shell: spawn42.shell ?? false,
32362
32502
  timeout: 5e3,
32363
32503
  stdio: ["pipe", "pipe", "pipe"]
32364
32504
  });
@@ -32390,7 +32530,7 @@ var DevServer = class _DevServer {
32390
32530
  const elapsed = Date.now() - start;
32391
32531
  this.json(res, 200, {
32392
32532
  success: true,
32393
- command: `${spawn32.command} ${(spawn32.args || []).join(" ")}`,
32533
+ command: `${spawn42.command} ${(spawn42.args || []).join(" ")}`,
32394
32534
  elapsed,
32395
32535
  stdout: stdout.trim(),
32396
32536
  stderr: stderr.trim(),
@@ -32400,7 +32540,7 @@ var DevServer = class _DevServer {
32400
32540
  const elapsed = Date.now() - start;
32401
32541
  this.json(res, 200, {
32402
32542
  success: false,
32403
- command: `${spawn32.command} ${(spawn32.args || []).join(" ")}`,
32543
+ command: `${spawn42.command} ${(spawn42.args || []).join(" ")}`,
32404
32544
  elapsed,
32405
32545
  error: e.message
32406
32546
  });
@@ -32530,12 +32670,12 @@ var DevServer = class _DevServer {
32530
32670
  // ─── DevConsole SPA ───
32531
32671
  getConsoleDistDir() {
32532
32672
  const candidates = [
32533
- path14.resolve(__dirname, "../../web-devconsole/dist"),
32534
- path14.resolve(__dirname, "../../../web-devconsole/dist"),
32535
- path14.join(process.cwd(), "packages/web-devconsole/dist")
32673
+ path15.resolve(__dirname, "../../web-devconsole/dist"),
32674
+ path15.resolve(__dirname, "../../../web-devconsole/dist"),
32675
+ path15.join(process.cwd(), "packages/web-devconsole/dist")
32536
32676
  ];
32537
32677
  for (const dir of candidates) {
32538
- if (fs11.existsSync(path14.join(dir, "index.html"))) return dir;
32678
+ if (fs12.existsSync(path15.join(dir, "index.html"))) return dir;
32539
32679
  }
32540
32680
  return null;
32541
32681
  }
@@ -32545,9 +32685,9 @@ var DevServer = class _DevServer {
32545
32685
  this.json(res, 500, { error: "DevConsole not found. Run: npm run build -w packages/web-devconsole" });
32546
32686
  return;
32547
32687
  }
32548
- const htmlPath = path14.join(distDir, "index.html");
32688
+ const htmlPath = path15.join(distDir, "index.html");
32549
32689
  try {
32550
- const html = fs11.readFileSync(htmlPath, "utf-8");
32690
+ const html = fs12.readFileSync(htmlPath, "utf-8");
32551
32691
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
32552
32692
  res.end(html);
32553
32693
  } catch (e) {
@@ -32570,15 +32710,15 @@ var DevServer = class _DevServer {
32570
32710
  this.json(res, 404, { error: "Not found" });
32571
32711
  return;
32572
32712
  }
32573
- const safePath = path14.normalize(pathname).replace(/^\.\.\//, "");
32574
- const filePath = path14.join(distDir, safePath);
32713
+ const safePath = path15.normalize(pathname).replace(/^\.\.\//, "");
32714
+ const filePath = path15.join(distDir, safePath);
32575
32715
  if (!filePath.startsWith(distDir)) {
32576
32716
  this.json(res, 403, { error: "Forbidden" });
32577
32717
  return;
32578
32718
  }
32579
32719
  try {
32580
- const content = fs11.readFileSync(filePath);
32581
- const ext = path14.extname(filePath);
32720
+ const content = fs12.readFileSync(filePath);
32721
+ const ext = path15.extname(filePath);
32582
32722
  const contentType = _DevServer.MIME_MAP[ext] || "application/octet-stream";
32583
32723
  res.writeHead(200, { "Content-Type": contentType, "Cache-Control": "public, max-age=31536000, immutable" });
32584
32724
  res.end(content);
@@ -32686,14 +32826,14 @@ var DevServer = class _DevServer {
32686
32826
  const files = [];
32687
32827
  const scan = (d, prefix) => {
32688
32828
  try {
32689
- for (const entry of fs11.readdirSync(d, { withFileTypes: true })) {
32829
+ for (const entry of fs12.readdirSync(d, { withFileTypes: true })) {
32690
32830
  if (entry.name.startsWith(".") || entry.name.endsWith(".bak")) continue;
32691
32831
  const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
32692
32832
  if (entry.isDirectory()) {
32693
32833
  files.push({ path: rel, size: 0, type: "dir" });
32694
- scan(path14.join(d, entry.name), rel);
32834
+ scan(path15.join(d, entry.name), rel);
32695
32835
  } else {
32696
- const stat4 = fs11.statSync(path14.join(d, entry.name));
32836
+ const stat4 = fs12.statSync(path15.join(d, entry.name));
32697
32837
  files.push({ path: rel, size: stat4.size, type: "file" });
32698
32838
  }
32699
32839
  }
@@ -32716,16 +32856,16 @@ var DevServer = class _DevServer {
32716
32856
  this.json(res, 404, { error: `Provider directory not found: ${type}` });
32717
32857
  return;
32718
32858
  }
32719
- const fullPath = path14.resolve(dir, path14.normalize(filePath));
32859
+ const fullPath = path15.resolve(dir, path15.normalize(filePath));
32720
32860
  if (!fullPath.startsWith(dir)) {
32721
32861
  this.json(res, 403, { error: "Forbidden" });
32722
32862
  return;
32723
32863
  }
32724
- if (!fs11.existsSync(fullPath) || fs11.statSync(fullPath).isDirectory()) {
32864
+ if (!fs12.existsSync(fullPath) || fs12.statSync(fullPath).isDirectory()) {
32725
32865
  this.json(res, 404, { error: `File not found: ${filePath}` });
32726
32866
  return;
32727
32867
  }
32728
- const content = fs11.readFileSync(fullPath, "utf-8");
32868
+ const content = fs12.readFileSync(fullPath, "utf-8");
32729
32869
  this.json(res, 200, { type, path: filePath, content, lines: content.split("\n").length });
32730
32870
  }
32731
32871
  /** POST /api/providers/:type/file — write a file { path, content } */
@@ -32741,15 +32881,15 @@ var DevServer = class _DevServer {
32741
32881
  this.json(res, 404, { error: `Provider directory not found: ${type}` });
32742
32882
  return;
32743
32883
  }
32744
- const fullPath = path14.resolve(dir, path14.normalize(filePath));
32884
+ const fullPath = path15.resolve(dir, path15.normalize(filePath));
32745
32885
  if (!fullPath.startsWith(dir)) {
32746
32886
  this.json(res, 403, { error: "Forbidden" });
32747
32887
  return;
32748
32888
  }
32749
32889
  try {
32750
- if (fs11.existsSync(fullPath)) fs11.copyFileSync(fullPath, fullPath + ".bak");
32751
- fs11.mkdirSync(path14.dirname(fullPath), { recursive: true });
32752
- fs11.writeFileSync(fullPath, content, "utf-8");
32890
+ if (fs12.existsSync(fullPath)) fs12.copyFileSync(fullPath, fullPath + ".bak");
32891
+ fs12.mkdirSync(path15.dirname(fullPath), { recursive: true });
32892
+ fs12.writeFileSync(fullPath, content, "utf-8");
32753
32893
  this.log(`File saved: ${fullPath} (${content.length} chars)`);
32754
32894
  this.providerLoader.reload();
32755
32895
  this.json(res, 200, { saved: true, path: filePath, chars: content.length });
@@ -32765,9 +32905,9 @@ var DevServer = class _DevServer {
32765
32905
  return;
32766
32906
  }
32767
32907
  for (const name of ["scripts.js", "provider.json"]) {
32768
- const p = path14.join(dir, name);
32769
- if (fs11.existsSync(p)) {
32770
- const source = fs11.readFileSync(p, "utf-8");
32908
+ const p = path15.join(dir, name);
32909
+ if (fs12.existsSync(p)) {
32910
+ const source = fs12.readFileSync(p, "utf-8");
32771
32911
  this.json(res, 200, { type, path: p, source, lines: source.split("\n").length });
32772
32912
  return;
32773
32913
  }
@@ -32786,11 +32926,11 @@ var DevServer = class _DevServer {
32786
32926
  this.json(res, 404, { error: `Provider not found: ${type}` });
32787
32927
  return;
32788
32928
  }
32789
- const target = fs11.existsSync(path14.join(dir, "scripts.js")) ? "scripts.js" : "provider.json";
32790
- const targetPath = path14.join(dir, target);
32929
+ const target = fs12.existsSync(path15.join(dir, "scripts.js")) ? "scripts.js" : "provider.json";
32930
+ const targetPath = path15.join(dir, target);
32791
32931
  try {
32792
- if (fs11.existsSync(targetPath)) fs11.copyFileSync(targetPath, targetPath + ".bak");
32793
- fs11.writeFileSync(targetPath, source, "utf-8");
32932
+ if (fs12.existsSync(targetPath)) fs12.copyFileSync(targetPath, targetPath + ".bak");
32933
+ fs12.writeFileSync(targetPath, source, "utf-8");
32794
32934
  this.log(`Saved provider: ${targetPath} (${source.length} chars)`);
32795
32935
  this.providerLoader.reload();
32796
32936
  this.json(res, 200, { saved: true, path: targetPath, chars: source.length });
@@ -32869,20 +33009,20 @@ var DevServer = class _DevServer {
32869
33009
  this.json(res, 404, { error: `Provider not found: ${type}` });
32870
33010
  return;
32871
33011
  }
32872
- const spawn32 = provider.spawn;
32873
- if (!spawn32) {
33012
+ const spawn42 = provider.spawn;
33013
+ if (!spawn42) {
32874
33014
  this.json(res, 400, { error: `Provider ${type} has no spawn config` });
32875
33015
  return;
32876
33016
  }
32877
33017
  const { spawn: spawnFn } = await import("child_process");
32878
33018
  const start = Date.now();
32879
33019
  try {
32880
- const args = [...spawn32.args || [], message];
32881
- const child = spawnFn(spawn32.command, args, {
32882
- shell: spawn32.shell ?? false,
33020
+ const args = [...spawn42.args || [], message];
33021
+ const child = spawnFn(spawn42.command, args, {
33022
+ shell: spawn42.shell ?? false,
32883
33023
  timeout,
32884
33024
  stdio: ["pipe", "pipe", "pipe"],
32885
- env: { ...process.env, ...spawn32.env || {} }
33025
+ env: { ...process.env, ...spawn42.env || {} }
32886
33026
  });
32887
33027
  let stdout = "";
32888
33028
  let stderr = "";
@@ -32947,21 +33087,21 @@ var DevServer = class _DevServer {
32947
33087
  }
32948
33088
  let targetDir;
32949
33089
  targetDir = this.providerLoader.getUserProviderDir(category, type);
32950
- const jsonPath = path14.join(targetDir, "provider.json");
32951
- if (fs11.existsSync(jsonPath)) {
33090
+ const jsonPath = path15.join(targetDir, "provider.json");
33091
+ if (fs12.existsSync(jsonPath)) {
32952
33092
  this.json(res, 409, { error: `Provider already exists at ${targetDir}`, path: targetDir });
32953
33093
  return;
32954
33094
  }
32955
33095
  try {
32956
33096
  const result = generateFiles(type, name, category, { cdpPorts, cli, processName, installPath, binary, extensionId, version: version2, osPaths, processNames });
32957
- fs11.mkdirSync(targetDir, { recursive: true });
32958
- fs11.writeFileSync(jsonPath, result["provider.json"], "utf-8");
33097
+ fs12.mkdirSync(targetDir, { recursive: true });
33098
+ fs12.writeFileSync(jsonPath, result["provider.json"], "utf-8");
32959
33099
  const createdFiles = ["provider.json"];
32960
33100
  if (result.files) {
32961
33101
  for (const [relPath, content] of Object.entries(result.files)) {
32962
- const fullPath = path14.join(targetDir, relPath);
32963
- fs11.mkdirSync(path14.dirname(fullPath), { recursive: true });
32964
- fs11.writeFileSync(fullPath, content, "utf-8");
33102
+ const fullPath = path15.join(targetDir, relPath);
33103
+ fs12.mkdirSync(path15.dirname(fullPath), { recursive: true });
33104
+ fs12.writeFileSync(fullPath, content, "utf-8");
32965
33105
  createdFiles.push(relPath);
32966
33106
  }
32967
33107
  }
@@ -33010,45 +33150,45 @@ var DevServer = class _DevServer {
33010
33150
  }
33011
33151
  // ─── Phase 2: Auto-Implement Backend ───
33012
33152
  getLatestScriptVersionDir(scriptsDir) {
33013
- if (!fs11.existsSync(scriptsDir)) return null;
33014
- const versions = fs11.readdirSync(scriptsDir).filter((d) => {
33153
+ if (!fs12.existsSync(scriptsDir)) return null;
33154
+ const versions = fs12.readdirSync(scriptsDir).filter((d) => {
33015
33155
  try {
33016
- return fs11.statSync(path14.join(scriptsDir, d)).isDirectory();
33156
+ return fs12.statSync(path15.join(scriptsDir, d)).isDirectory();
33017
33157
  } catch {
33018
33158
  return false;
33019
33159
  }
33020
33160
  }).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" }));
33021
33161
  if (versions.length === 0) return null;
33022
- return path14.join(scriptsDir, versions[0]);
33162
+ return path15.join(scriptsDir, versions[0]);
33023
33163
  }
33024
33164
  resolveAutoImplWritableProviderDir(category, type, requestedDir) {
33025
- const canonicalUserDir = path14.resolve(this.providerLoader.getUserProviderDir(category, type));
33026
- const desiredDir = requestedDir ? path14.resolve(requestedDir) : canonicalUserDir;
33027
- const upstreamRoot = path14.resolve(this.providerLoader.getUpstreamDir());
33028
- if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path14.sep}`)) {
33165
+ const canonicalUserDir = path15.resolve(this.providerLoader.getUserProviderDir(category, type));
33166
+ const desiredDir = requestedDir ? path15.resolve(requestedDir) : canonicalUserDir;
33167
+ const upstreamRoot = path15.resolve(this.providerLoader.getUpstreamDir());
33168
+ if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path15.sep}`)) {
33029
33169
  return { dir: null, reason: `Refusing to write into upstream provider directory: ${desiredDir}` };
33030
33170
  }
33031
- if (path14.basename(desiredDir) !== type) {
33171
+ if (path15.basename(desiredDir) !== type) {
33032
33172
  return { dir: null, reason: `Requested writable provider directory must end with '${type}': ${desiredDir}` };
33033
33173
  }
33034
33174
  const sourceDir = this.findProviderDir(type);
33035
33175
  if (!sourceDir) {
33036
33176
  return { dir: null, reason: `Provider source directory not found for '${type}'` };
33037
33177
  }
33038
- if (!fs11.existsSync(desiredDir)) {
33039
- fs11.mkdirSync(path14.dirname(desiredDir), { recursive: true });
33040
- fs11.cpSync(sourceDir, desiredDir, { recursive: true });
33178
+ if (!fs12.existsSync(desiredDir)) {
33179
+ fs12.mkdirSync(path15.dirname(desiredDir), { recursive: true });
33180
+ fs12.cpSync(sourceDir, desiredDir, { recursive: true });
33041
33181
  this.log(`Auto-implement writable copy created: ${desiredDir}`);
33042
33182
  }
33043
- const providerJson = path14.join(desiredDir, "provider.json");
33044
- if (!fs11.existsSync(providerJson)) {
33183
+ const providerJson = path15.join(desiredDir, "provider.json");
33184
+ if (!fs12.existsSync(providerJson)) {
33045
33185
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
33046
33186
  }
33047
33187
  try {
33048
- const providerData = JSON.parse(fs11.readFileSync(providerJson, "utf-8"));
33188
+ const providerData = JSON.parse(fs12.readFileSync(providerJson, "utf-8"));
33049
33189
  if (providerData.disableUpstream !== true) {
33050
33190
  providerData.disableUpstream = true;
33051
- fs11.writeFileSync(providerJson, JSON.stringify(providerData, null, 2));
33191
+ fs12.writeFileSync(providerJson, JSON.stringify(providerData, null, 2));
33052
33192
  }
33053
33193
  } catch (error48) {
33054
33194
  return {
@@ -33088,7 +33228,7 @@ var DevServer = class _DevServer {
33088
33228
  setMode: "set_mode.js"
33089
33229
  };
33090
33230
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
33091
- const scriptsDir = path14.join(providerDir, "scripts");
33231
+ const scriptsDir = path15.join(providerDir, "scripts");
33092
33232
  const latestScriptsDir = this.getLatestScriptVersionDir(scriptsDir);
33093
33233
  if (latestScriptsDir) {
33094
33234
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -33096,10 +33236,10 @@ var DevServer = class _DevServer {
33096
33236
  lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
33097
33237
  lines.push("These are the ONLY files you are allowed to modify. Replace the TODO stubs with working implementations.");
33098
33238
  lines.push("");
33099
- for (const file2 of fs11.readdirSync(latestScriptsDir)) {
33239
+ for (const file2 of fs12.readdirSync(latestScriptsDir)) {
33100
33240
  if (file2.endsWith(".js") && targetFileNames.has(file2)) {
33101
33241
  try {
33102
- const content = fs11.readFileSync(path14.join(latestScriptsDir, file2), "utf-8");
33242
+ const content = fs12.readFileSync(path15.join(latestScriptsDir, file2), "utf-8");
33103
33243
  lines.push(`### \`${file2}\` \u270F\uFE0F EDIT`);
33104
33244
  lines.push("```javascript");
33105
33245
  lines.push(content);
@@ -33109,14 +33249,14 @@ var DevServer = class _DevServer {
33109
33249
  }
33110
33250
  }
33111
33251
  }
33112
- const refFiles = fs11.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
33252
+ const refFiles = fs12.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
33113
33253
  if (refFiles.length > 0) {
33114
33254
  lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
33115
33255
  lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
33116
33256
  lines.push("");
33117
33257
  for (const file2 of refFiles) {
33118
33258
  try {
33119
- const content = fs11.readFileSync(path14.join(latestScriptsDir, file2), "utf-8");
33259
+ const content = fs12.readFileSync(path15.join(latestScriptsDir, file2), "utf-8");
33120
33260
  lines.push(`### \`${file2}\` \u{1F512}`);
33121
33261
  lines.push("```javascript");
33122
33262
  lines.push(content);
@@ -33157,11 +33297,11 @@ var DevServer = class _DevServer {
33157
33297
  lines.push("");
33158
33298
  }
33159
33299
  }
33160
- const docsDir = path14.join(providerDir, "../../docs");
33300
+ const docsDir = path15.join(providerDir, "../../docs");
33161
33301
  const loadGuide = (name) => {
33162
33302
  try {
33163
- const p = path14.join(docsDir, name);
33164
- if (fs11.existsSync(p)) return fs11.readFileSync(p, "utf-8");
33303
+ const p = path15.join(docsDir, name);
33304
+ if (fs12.existsSync(p)) return fs12.readFileSync(p, "utf-8");
33165
33305
  } catch {
33166
33306
  }
33167
33307
  return null;
@@ -33334,7 +33474,7 @@ var DevServer = class _DevServer {
33334
33474
  parseApproval: "parse_approval.js"
33335
33475
  };
33336
33476
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
33337
- const scriptsDir = path14.join(providerDir, "scripts");
33477
+ const scriptsDir = path15.join(providerDir, "scripts");
33338
33478
  const latestScriptsDir = this.getLatestScriptVersionDir(scriptsDir);
33339
33479
  if (latestScriptsDir) {
33340
33480
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -33342,11 +33482,11 @@ var DevServer = class _DevServer {
33342
33482
  lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
33343
33483
  lines.push("These are the ONLY files you are allowed to modify. Replace TODO or heuristic-only logic with working PTY-aware implementations.");
33344
33484
  lines.push("");
33345
- for (const file2 of fs11.readdirSync(latestScriptsDir)) {
33485
+ for (const file2 of fs12.readdirSync(latestScriptsDir)) {
33346
33486
  if (!file2.endsWith(".js")) continue;
33347
33487
  if (!targetFileNames.has(file2)) continue;
33348
33488
  try {
33349
- const content = fs11.readFileSync(path14.join(latestScriptsDir, file2), "utf-8");
33489
+ const content = fs12.readFileSync(path15.join(latestScriptsDir, file2), "utf-8");
33350
33490
  lines.push(`### \`${file2}\` \u270F\uFE0F EDIT`);
33351
33491
  lines.push("```javascript");
33352
33492
  lines.push(content);
@@ -33355,14 +33495,14 @@ var DevServer = class _DevServer {
33355
33495
  } catch {
33356
33496
  }
33357
33497
  }
33358
- const refFiles = fs11.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
33498
+ const refFiles = fs12.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
33359
33499
  if (refFiles.length > 0) {
33360
33500
  lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
33361
33501
  lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
33362
33502
  lines.push("");
33363
33503
  for (const file2 of refFiles) {
33364
33504
  try {
33365
- const content = fs11.readFileSync(path14.join(latestScriptsDir, file2), "utf-8");
33505
+ const content = fs12.readFileSync(path15.join(latestScriptsDir, file2), "utf-8");
33366
33506
  lines.push(`### \`${file2}\` \u{1F512}`);
33367
33507
  lines.push("```javascript");
33368
33508
  lines.push(content);
@@ -33395,11 +33535,11 @@ var DevServer = class _DevServer {
33395
33535
  lines.push("");
33396
33536
  }
33397
33537
  }
33398
- const docsDir = path14.join(providerDir, "../../docs");
33538
+ const docsDir = path15.join(providerDir, "../../docs");
33399
33539
  const loadGuide = (name) => {
33400
33540
  try {
33401
- const p = path14.join(docsDir, name);
33402
- if (fs11.existsSync(p)) return fs11.readFileSync(p, "utf-8");
33541
+ const p = path15.join(docsDir, name);
33542
+ if (fs12.existsSync(p)) return fs12.readFileSync(p, "utf-8");
33403
33543
  } catch {
33404
33544
  }
33405
33545
  return null;
@@ -33625,6 +33765,7 @@ var SessionHostRuntimeTransport = class {
33625
33765
  this.ready = this.boot();
33626
33766
  }
33627
33767
  ready;
33768
+ terminalQueriesHandled = true;
33628
33769
  client;
33629
33770
  dataCallbacks = /* @__PURE__ */ new Set();
33630
33771
  exitCallbacks = /* @__PURE__ */ new Set();
@@ -34252,13 +34393,27 @@ async function shutdownDaemonComponents(components) {
34252
34393
  }
34253
34394
 
34254
34395
  // src/session-host.ts
34255
- var import_child_process8 = require("child_process");
34256
- var path15 = __toESM(require("path"));
34396
+ var import_child_process10 = require("child_process");
34397
+ var path16 = __toESM(require("path"));
34257
34398
  var SESSION_HOST_APP_NAME = process.env.ADHDEV_SESSION_HOST_NAME || "adhdev";
34399
+ function buildSessionHostEnv(baseEnv) {
34400
+ const env = {};
34401
+ for (const [key, value] of Object.entries(baseEnv)) {
34402
+ if (typeof value !== "string") continue;
34403
+ env[key] = value;
34404
+ }
34405
+ for (const key of Object.keys(env)) {
34406
+ if (key === "INIT_CWD" || key === "NO_COLOR" || key === "FORCE_COLOR" || key === "npm_command" || key === "npm_execpath" || key === "npm_node_execpath" || key.startsWith("npm_") || key.startsWith("npm_config_") || key.startsWith("npm_package_") || key.startsWith("npm_lifecycle_") || key.startsWith("PNPM_") || key.startsWith("YARN_") || key.startsWith("BUN_")) {
34407
+ delete env[key];
34408
+ }
34409
+ }
34410
+ env.ADHDEV_SESSION_HOST_NAME = SESSION_HOST_APP_NAME;
34411
+ return env;
34412
+ }
34258
34413
  function resolveSessionHostEntry() {
34259
34414
  const localCandidates = [
34260
- path15.resolve(__dirname, "../vendor/session-host-daemon/index.js"),
34261
- path15.resolve(__dirname, "../../vendor/session-host-daemon/index.js")
34415
+ path16.resolve(__dirname, "../vendor/session-host-daemon/index.js"),
34416
+ path16.resolve(__dirname, "../../vendor/session-host-daemon/index.js")
34262
34417
  ];
34263
34418
  for (const candidate of localCandidates) {
34264
34419
  if (require("fs").existsSync(candidate)) {
@@ -34269,12 +34424,9 @@ function resolveSessionHostEntry() {
34269
34424
  }
34270
34425
  async function runSessionHostCli(args) {
34271
34426
  const entry = resolveSessionHostEntry();
34272
- const child = (0, import_child_process8.spawn)(process.execPath, [entry, ...args], {
34427
+ const child = (0, import_child_process10.spawn)(process.execPath, [entry, ...args], {
34273
34428
  stdio: "inherit",
34274
- env: {
34275
- ...process.env,
34276
- ADHDEV_SESSION_HOST_NAME: SESSION_HOST_APP_NAME
34277
- }
34429
+ env: buildSessionHostEnv(process.env)
34278
34430
  });
34279
34431
  return await new Promise((resolve12, reject) => {
34280
34432
  child.on("error", reject);
@@ -34286,14 +34438,11 @@ async function ensureSessionHostReady2() {
34286
34438
  appName: SESSION_HOST_APP_NAME,
34287
34439
  spawnHost: () => {
34288
34440
  const entry = resolveSessionHostEntry();
34289
- const child = (0, import_child_process8.spawn)(process.execPath, [entry], {
34441
+ const child = (0, import_child_process10.spawn)(process.execPath, [entry], {
34290
34442
  detached: true,
34291
34443
  stdio: "ignore",
34292
34444
  windowsHide: true,
34293
- env: {
34294
- ...process.env,
34295
- ADHDEV_SESSION_HOST_NAME: SESSION_HOST_APP_NAME
34296
- }
34445
+ env: buildSessionHostEnv(process.env)
34297
34446
  });
34298
34447
  child.unref();
34299
34448
  }
@@ -34478,12 +34627,12 @@ var pkgVersion = process.env.ADHDEV_PKG_VERSION || "unknown";
34478
34627
  if (pkgVersion === "unknown") {
34479
34628
  try {
34480
34629
  const possiblePaths = [
34481
- path17.join(__dirname, "..", "package.json"),
34482
- path17.join(__dirname, "package.json")
34630
+ path18.join(__dirname, "..", "package.json"),
34631
+ path18.join(__dirname, "package.json")
34483
34632
  ];
34484
34633
  for (const candidate of possiblePaths) {
34485
34634
  try {
34486
- const data = JSON.parse(fs12.readFileSync(candidate, "utf-8"));
34635
+ const data = JSON.parse(fs13.readFileSync(candidate, "utf-8"));
34487
34636
  if (data.version) {
34488
34637
  pkgVersion = data.version;
34489
34638
  break;
@@ -34826,9 +34975,9 @@ var StandaloneServer = class {
34826
34975
  }
34827
34976
  if (publicDir) {
34828
34977
  const filePath = url2 === "/" ? "/index.html" : url2;
34829
- const fullPath = path17.join(publicDir, filePath);
34830
- if (fs12.existsSync(fullPath) && fs12.statSync(fullPath).isFile()) {
34831
- const ext = path17.extname(fullPath);
34978
+ const fullPath = path18.join(publicDir, filePath);
34979
+ if (fs13.existsSync(fullPath) && fs13.statSync(fullPath).isFile()) {
34980
+ const ext = path18.extname(fullPath);
34832
34981
  const mimeTypes = {
34833
34982
  ".html": "text/html",
34834
34983
  ".js": "application/javascript",
@@ -34840,13 +34989,13 @@ var StandaloneServer = class {
34840
34989
  ".woff2": "font/woff2"
34841
34990
  };
34842
34991
  res.writeHead(200, { "Content-Type": mimeTypes[ext] || "application/octet-stream" });
34843
- fs12.createReadStream(fullPath).pipe(res);
34992
+ fs13.createReadStream(fullPath).pipe(res);
34844
34993
  return;
34845
34994
  }
34846
- const indexPath = path17.join(publicDir, "index.html");
34847
- if (fs12.existsSync(indexPath) && !url2.startsWith("/api/")) {
34995
+ const indexPath = path18.join(publicDir, "index.html");
34996
+ if (fs13.existsSync(indexPath) && !url2.startsWith("/api/")) {
34848
34997
  res.writeHead(200, { "Content-Type": "text/html" });
34849
- fs12.createReadStream(indexPath).pipe(res);
34998
+ fs13.createReadStream(indexPath).pipe(res);
34850
34999
  return;
34851
35000
  }
34852
35001
  }
@@ -35087,7 +35236,7 @@ var StandaloneServer = class {
35087
35236
  }
35088
35237
  // ─── Network ───
35089
35238
  getLanIPs() {
35090
- const interfaces = os17.networkInterfaces();
35239
+ const interfaces = os18.networkInterfaces();
35091
35240
  const ips = [];
35092
35241
  for (const iface of Object.values(interfaces)) {
35093
35242
  if (!iface) continue;
@@ -35131,6 +35280,10 @@ var StandaloneServer = class {
35131
35280
  }
35132
35281
  };
35133
35282
  async function main() {
35283
+ const helperMode = await maybeRunDaemonUpgradeHelperFromEnv();
35284
+ if (helperMode) {
35285
+ return;
35286
+ }
35134
35287
  const args = process.argv.slice(2);
35135
35288
  const primaryCommand = args[0] || "";
35136
35289
  if (primaryCommand === "attach") {
@@ -35197,12 +35350,12 @@ Runtime commands:
35197
35350
  }
35198
35351
  if (!options.publicDir) {
35199
35352
  const candidates = [
35200
- path17.join(__dirname, "../../web-standalone/dist"),
35201
- path17.join(__dirname, "../public"),
35202
- path17.join(process.cwd(), "public")
35353
+ path18.join(__dirname, "../../web-standalone/dist"),
35354
+ path18.join(__dirname, "../public"),
35355
+ path18.join(process.cwd(), "public")
35203
35356
  ];
35204
35357
  for (const candidate of candidates) {
35205
- if (fs12.existsSync(path17.join(candidate, "index.html"))) {
35358
+ if (fs13.existsSync(path18.join(candidate, "index.html"))) {
35206
35359
  options.publicDir = candidate;
35207
35360
  break;
35208
35361
  }