@adhdev/daemon-standalone 0.7.33 → 0.7.36

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
  }
@@ -16085,8 +16085,8 @@ var init_acp = __esm({
16085
16085
  this.#requestHandler = requestHandler;
16086
16086
  this.#notificationHandler = notificationHandler;
16087
16087
  this.#stream = stream;
16088
- this.#closedPromise = new Promise((resolve12) => {
16089
- this.#abortController.signal.addEventListener("abort", () => resolve12());
16088
+ this.#closedPromise = new Promise((resolve13) => {
16089
+ this.#abortController.signal.addEventListener("abort", () => resolve13());
16090
16090
  });
16091
16091
  this.#receive();
16092
16092
  }
@@ -16235,8 +16235,8 @@ var init_acp = __esm({
16235
16235
  }
16236
16236
  async sendRequest(method, params) {
16237
16237
  const id = this.#nextRequestId++;
16238
- const responsePromise = new Promise((resolve12, reject) => {
16239
- this.#pendingResponses.set(id, { resolve: resolve12, reject });
16238
+ const responsePromise = new Promise((resolve13, reject) => {
16239
+ this.#pendingResponses.set(id, { resolve: resolve13, reject });
16240
16240
  });
16241
16241
  await this.#sendMessage({ jsonrpc: "2.0", id, method, params });
16242
16242
  return responsePromise;
@@ -16334,7 +16334,7 @@ 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"));
16337
+ var path18 = __toESM(require("path"));
16338
16338
  var fs12 = __toESM(require("fs"));
16339
16339
  var os17 = __toESM(require("os"));
16340
16340
 
@@ -16348,13 +16348,14 @@ var import_path = require("path");
16348
16348
  var import_fs = require("fs");
16349
16349
  var import_crypto3 = require("crypto");
16350
16350
  var fs2 = __toESM(require("fs"), 1);
16351
- var path3 = __toESM(require("path"), 1);
16351
+ var path4 = __toESM(require("path"), 1);
16352
16352
  var os4 = __toESM(require("os"), 1);
16353
16353
  var os11 = __toESM(require("os"), 1);
16354
16354
  var os12 = __toESM(require("os"), 1);
16355
- var path9 = __toESM(require("path"), 1);
16355
+ var path10 = __toESM(require("path"), 1);
16356
16356
  var import_child_process = require("child_process");
16357
16357
  var path22 = __toESM(require("path"), 1);
16358
+ var path3 = __toESM(require("path"), 1);
16358
16359
  var import_child_process2 = require("child_process");
16359
16360
  var import_fs2 = require("fs");
16360
16361
  var import_os2 = require("os");
@@ -16366,17 +16367,17 @@ var import_ws = __toESM(require("ws"), 1);
16366
16367
  var http = __toESM(require("http"), 1);
16367
16368
  var crypto2 = __toESM(require("crypto"), 1);
16368
16369
  var fs3 = __toESM(require("fs"), 1);
16369
- var path4 = __toESM(require("path"), 1);
16370
+ var path5 = __toESM(require("path"), 1);
16370
16371
  var os5 = __toESM(require("os"), 1);
16371
16372
  var fs4 = __toESM(require("fs"), 1);
16372
- var path5 = __toESM(require("path"), 1);
16373
+ var path6 = __toESM(require("path"), 1);
16373
16374
  var os6 = __toESM(require("os"), 1);
16374
16375
  var import_child_process5 = require("child_process");
16375
16376
  var net2 = __toESM(require("net"), 1);
16376
16377
  var os8 = __toESM(require("os"), 1);
16377
- var path7 = __toESM(require("path"), 1);
16378
+ var path8 = __toESM(require("path"), 1);
16378
16379
  var fs5 = __toESM(require("fs"), 1);
16379
- var path6 = __toESM(require("path"), 1);
16380
+ var path7 = __toESM(require("path"), 1);
16380
16381
  var os7 = __toESM(require("os"), 1);
16381
16382
 
16382
16383
  // ../daemon-core/node_modules/chokidar/index.js
@@ -16469,7 +16470,7 @@ var ReaddirpStream = class extends import_node_stream.Readable {
16469
16470
  this._directoryFilter = normalizeFilter(opts.directoryFilter);
16470
16471
  const statMethod = opts.lstat ? import_promises.lstat : import_promises.stat;
16471
16472
  if (wantBigintFsStats) {
16472
- this._stat = (path18) => statMethod(path18, { bigint: true });
16473
+ this._stat = (path19) => statMethod(path19, { bigint: true });
16473
16474
  } else {
16474
16475
  this._stat = statMethod;
16475
16476
  }
@@ -16494,8 +16495,8 @@ var ReaddirpStream = class extends import_node_stream.Readable {
16494
16495
  const par = this.parent;
16495
16496
  const fil = par && par.files;
16496
16497
  if (fil && fil.length > 0) {
16497
- const { path: path18, depth } = par;
16498
- const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path18));
16498
+ const { path: path19, depth } = par;
16499
+ const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path19));
16499
16500
  const awaited = await Promise.all(slice);
16500
16501
  for (const entry of awaited) {
16501
16502
  if (!entry)
@@ -16535,20 +16536,20 @@ var ReaddirpStream = class extends import_node_stream.Readable {
16535
16536
  this.reading = false;
16536
16537
  }
16537
16538
  }
16538
- async _exploreDir(path18, depth) {
16539
+ async _exploreDir(path19, depth) {
16539
16540
  let files;
16540
16541
  try {
16541
- files = await (0, import_promises.readdir)(path18, this._rdOptions);
16542
+ files = await (0, import_promises.readdir)(path19, this._rdOptions);
16542
16543
  } catch (error48) {
16543
16544
  this._onError(error48);
16544
16545
  }
16545
- return { files, depth, path: path18 };
16546
+ return { files, depth, path: path19 };
16546
16547
  }
16547
- async _formatEntry(dirent, path18) {
16548
+ async _formatEntry(dirent, path19) {
16548
16549
  let entry;
16549
16550
  const basename7 = this._isDirent ? dirent.name : dirent;
16550
16551
  try {
16551
- const fullPath = (0, import_node_path.resolve)((0, import_node_path.join)(path18, basename7));
16552
+ const fullPath = (0, import_node_path.resolve)((0, import_node_path.join)(path19, basename7));
16552
16553
  entry = { path: (0, import_node_path.relative)(this._root, fullPath), fullPath, basename: basename7 };
16553
16554
  entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
16554
16555
  } catch (err) {
@@ -16948,16 +16949,16 @@ var delFromSet = (main2, prop, item) => {
16948
16949
  };
16949
16950
  var isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
16950
16951
  var FsWatchInstances = /* @__PURE__ */ new Map();
16951
- function createFsWatchInstance(path18, options, listener, errHandler, emitRaw) {
16952
+ function createFsWatchInstance(path19, options, listener, errHandler, emitRaw) {
16952
16953
  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));
16954
+ listener(path19);
16955
+ emitRaw(rawEvent, evPath, { watchedPath: path19 });
16956
+ if (evPath && path19 !== evPath) {
16957
+ fsWatchBroadcast(sp.resolve(path19, evPath), KEY_LISTENERS, sp.join(path19, evPath));
16957
16958
  }
16958
16959
  };
16959
16960
  try {
16960
- return (0, import_node_fs.watch)(path18, {
16961
+ return (0, import_node_fs.watch)(path19, {
16961
16962
  persistent: options.persistent
16962
16963
  }, handleEvent);
16963
16964
  } catch (error48) {
@@ -16973,12 +16974,12 @@ var fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
16973
16974
  listener(val1, val2, val3);
16974
16975
  });
16975
16976
  };
16976
- var setFsWatchListener = (path18, fullPath, options, handlers) => {
16977
+ var setFsWatchListener = (path19, fullPath, options, handlers) => {
16977
16978
  const { listener, errHandler, rawEmitter } = handlers;
16978
16979
  let cont = FsWatchInstances.get(fullPath);
16979
16980
  let watcher;
16980
16981
  if (!options.persistent) {
16981
- watcher = createFsWatchInstance(path18, options, listener, errHandler, rawEmitter);
16982
+ watcher = createFsWatchInstance(path19, options, listener, errHandler, rawEmitter);
16982
16983
  if (!watcher)
16983
16984
  return;
16984
16985
  return watcher.close.bind(watcher);
@@ -16989,7 +16990,7 @@ var setFsWatchListener = (path18, fullPath, options, handlers) => {
16989
16990
  addAndConvert(cont, KEY_RAW, rawEmitter);
16990
16991
  } else {
16991
16992
  watcher = createFsWatchInstance(
16992
- path18,
16993
+ path19,
16993
16994
  options,
16994
16995
  fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
16995
16996
  errHandler,
@@ -17004,7 +17005,7 @@ var setFsWatchListener = (path18, fullPath, options, handlers) => {
17004
17005
  cont.watcherUnusable = true;
17005
17006
  if (isWindows && error48.code === "EPERM") {
17006
17007
  try {
17007
- const fd = await (0, import_promises2.open)(path18, "r");
17008
+ const fd = await (0, import_promises2.open)(path19, "r");
17008
17009
  await fd.close();
17009
17010
  broadcastErr(error48);
17010
17011
  } catch (err) {
@@ -17035,7 +17036,7 @@ var setFsWatchListener = (path18, fullPath, options, handlers) => {
17035
17036
  };
17036
17037
  };
17037
17038
  var FsWatchFileInstances = /* @__PURE__ */ new Map();
17038
- var setFsWatchFileListener = (path18, fullPath, options, handlers) => {
17039
+ var setFsWatchFileListener = (path19, fullPath, options, handlers) => {
17039
17040
  const { listener, rawEmitter } = handlers;
17040
17041
  let cont = FsWatchFileInstances.get(fullPath);
17041
17042
  const copts = cont && cont.options;
@@ -17057,7 +17058,7 @@ var setFsWatchFileListener = (path18, fullPath, options, handlers) => {
17057
17058
  });
17058
17059
  const currmtime = curr.mtimeMs;
17059
17060
  if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
17060
- foreach(cont.listeners, (listener2) => listener2(path18, curr));
17061
+ foreach(cont.listeners, (listener2) => listener2(path19, curr));
17061
17062
  }
17062
17063
  })
17063
17064
  };
@@ -17087,13 +17088,13 @@ var NodeFsHandler = class {
17087
17088
  * @param listener on fs change
17088
17089
  * @returns closer for the watcher instance
17089
17090
  */
17090
- _watchWithNodeFs(path18, listener) {
17091
+ _watchWithNodeFs(path19, listener) {
17091
17092
  const opts = this.fsw.options;
17092
- const directory = sp.dirname(path18);
17093
- const basename7 = sp.basename(path18);
17093
+ const directory = sp.dirname(path19);
17094
+ const basename7 = sp.basename(path19);
17094
17095
  const parent = this.fsw._getWatchedDir(directory);
17095
17096
  parent.add(basename7);
17096
- const absolutePath = sp.resolve(path18);
17097
+ const absolutePath = sp.resolve(path19);
17097
17098
  const options = {
17098
17099
  persistent: opts.persistent
17099
17100
  };
@@ -17103,12 +17104,12 @@ var NodeFsHandler = class {
17103
17104
  if (opts.usePolling) {
17104
17105
  const enableBin = opts.interval !== opts.binaryInterval;
17105
17106
  options.interval = enableBin && isBinaryPath(basename7) ? opts.binaryInterval : opts.interval;
17106
- closer = setFsWatchFileListener(path18, absolutePath, options, {
17107
+ closer = setFsWatchFileListener(path19, absolutePath, options, {
17107
17108
  listener,
17108
17109
  rawEmitter: this.fsw._emitRaw
17109
17110
  });
17110
17111
  } else {
17111
- closer = setFsWatchListener(path18, absolutePath, options, {
17112
+ closer = setFsWatchListener(path19, absolutePath, options, {
17112
17113
  listener,
17113
17114
  errHandler: this._boundHandleError,
17114
17115
  rawEmitter: this.fsw._emitRaw
@@ -17130,7 +17131,7 @@ var NodeFsHandler = class {
17130
17131
  let prevStats = stats;
17131
17132
  if (parent.has(basename7))
17132
17133
  return;
17133
- const listener = async (path18, newStats) => {
17134
+ const listener = async (path19, newStats) => {
17134
17135
  if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file2, 5))
17135
17136
  return;
17136
17137
  if (!newStats || newStats.mtimeMs === 0) {
@@ -17144,11 +17145,11 @@ var NodeFsHandler = class {
17144
17145
  this.fsw._emit(EV.CHANGE, file2, newStats2);
17145
17146
  }
17146
17147
  if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats2.ino) {
17147
- this.fsw._closeFile(path18);
17148
+ this.fsw._closeFile(path19);
17148
17149
  prevStats = newStats2;
17149
17150
  const closer2 = this._watchWithNodeFs(file2, listener);
17150
17151
  if (closer2)
17151
- this.fsw._addPathCloser(path18, closer2);
17152
+ this.fsw._addPathCloser(path19, closer2);
17152
17153
  } else {
17153
17154
  prevStats = newStats2;
17154
17155
  }
@@ -17180,7 +17181,7 @@ var NodeFsHandler = class {
17180
17181
  * @param item basename of this item
17181
17182
  * @returns true if no more processing is needed for this entry.
17182
17183
  */
17183
- async _handleSymlink(entry, directory, path18, item) {
17184
+ async _handleSymlink(entry, directory, path19, item) {
17184
17185
  if (this.fsw.closed) {
17185
17186
  return;
17186
17187
  }
@@ -17190,7 +17191,7 @@ var NodeFsHandler = class {
17190
17191
  this.fsw._incrReadyCount();
17191
17192
  let linkPath;
17192
17193
  try {
17193
- linkPath = await (0, import_promises2.realpath)(path18);
17194
+ linkPath = await (0, import_promises2.realpath)(path19);
17194
17195
  } catch (e) {
17195
17196
  this.fsw._emitReady();
17196
17197
  return true;
@@ -17200,12 +17201,12 @@ var NodeFsHandler = class {
17200
17201
  if (dir.has(item)) {
17201
17202
  if (this.fsw._symlinkPaths.get(full) !== linkPath) {
17202
17203
  this.fsw._symlinkPaths.set(full, linkPath);
17203
- this.fsw._emit(EV.CHANGE, path18, entry.stats);
17204
+ this.fsw._emit(EV.CHANGE, path19, entry.stats);
17204
17205
  }
17205
17206
  } else {
17206
17207
  dir.add(item);
17207
17208
  this.fsw._symlinkPaths.set(full, linkPath);
17208
- this.fsw._emit(EV.ADD, path18, entry.stats);
17209
+ this.fsw._emit(EV.ADD, path19, entry.stats);
17209
17210
  }
17210
17211
  this.fsw._emitReady();
17211
17212
  return true;
@@ -17235,9 +17236,9 @@ var NodeFsHandler = class {
17235
17236
  return;
17236
17237
  }
17237
17238
  const item = entry.path;
17238
- let path18 = sp.join(directory, item);
17239
+ let path19 = sp.join(directory, item);
17239
17240
  current.add(item);
17240
- if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path18, item)) {
17241
+ if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path19, item)) {
17241
17242
  return;
17242
17243
  }
17243
17244
  if (this.fsw.closed) {
@@ -17246,11 +17247,11 @@ var NodeFsHandler = class {
17246
17247
  }
17247
17248
  if (item === target || !target && !previous.has(item)) {
17248
17249
  this.fsw._incrReadyCount();
17249
- path18 = sp.join(dir, sp.relative(dir, path18));
17250
- this._addToNodeFs(path18, initialAdd, wh, depth + 1);
17250
+ path19 = sp.join(dir, sp.relative(dir, path19));
17251
+ this._addToNodeFs(path19, initialAdd, wh, depth + 1);
17251
17252
  }
17252
17253
  }).on(EV.ERROR, this._boundHandleError);
17253
- return new Promise((resolve12, reject) => {
17254
+ return new Promise((resolve13, reject) => {
17254
17255
  if (!stream)
17255
17256
  return reject();
17256
17257
  stream.once(STR_END, () => {
@@ -17259,7 +17260,7 @@ var NodeFsHandler = class {
17259
17260
  return;
17260
17261
  }
17261
17262
  const wasThrottled = throttler ? throttler.clear() : false;
17262
- resolve12(void 0);
17263
+ resolve13(void 0);
17263
17264
  previous.getChildren().filter((item) => {
17264
17265
  return item !== directory && !current.has(item);
17265
17266
  }).forEach((item) => {
@@ -17316,13 +17317,13 @@ var NodeFsHandler = class {
17316
17317
  * @param depth Child path actually targeted for watch
17317
17318
  * @param target Child path actually targeted for watch
17318
17319
  */
17319
- async _addToNodeFs(path18, initialAdd, priorWh, depth, target) {
17320
+ async _addToNodeFs(path19, initialAdd, priorWh, depth, target) {
17320
17321
  const ready = this.fsw._emitReady;
17321
- if (this.fsw._isIgnored(path18) || this.fsw.closed) {
17322
+ if (this.fsw._isIgnored(path19) || this.fsw.closed) {
17322
17323
  ready();
17323
17324
  return false;
17324
17325
  }
17325
- const wh = this.fsw._getWatchHelpers(path18);
17326
+ const wh = this.fsw._getWatchHelpers(path19);
17326
17327
  if (priorWh) {
17327
17328
  wh.filterPath = (entry) => priorWh.filterPath(entry);
17328
17329
  wh.filterDir = (entry) => priorWh.filterDir(entry);
@@ -17338,8 +17339,8 @@ var NodeFsHandler = class {
17338
17339
  const follow = this.fsw.options.followSymlinks;
17339
17340
  let closer;
17340
17341
  if (stats.isDirectory()) {
17341
- const absPath = sp.resolve(path18);
17342
- const targetPath = follow ? await (0, import_promises2.realpath)(path18) : path18;
17342
+ const absPath = sp.resolve(path19);
17343
+ const targetPath = follow ? await (0, import_promises2.realpath)(path19) : path19;
17343
17344
  if (this.fsw.closed)
17344
17345
  return;
17345
17346
  closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
@@ -17349,29 +17350,29 @@ var NodeFsHandler = class {
17349
17350
  this.fsw._symlinkPaths.set(absPath, targetPath);
17350
17351
  }
17351
17352
  } else if (stats.isSymbolicLink()) {
17352
- const targetPath = follow ? await (0, import_promises2.realpath)(path18) : path18;
17353
+ const targetPath = follow ? await (0, import_promises2.realpath)(path19) : path19;
17353
17354
  if (this.fsw.closed)
17354
17355
  return;
17355
17356
  const parent = sp.dirname(wh.watchPath);
17356
17357
  this.fsw._getWatchedDir(parent).add(wh.watchPath);
17357
17358
  this.fsw._emit(EV.ADD, wh.watchPath, stats);
17358
- closer = await this._handleDir(parent, stats, initialAdd, depth, path18, wh, targetPath);
17359
+ closer = await this._handleDir(parent, stats, initialAdd, depth, path19, wh, targetPath);
17359
17360
  if (this.fsw.closed)
17360
17361
  return;
17361
17362
  if (targetPath !== void 0) {
17362
- this.fsw._symlinkPaths.set(sp.resolve(path18), targetPath);
17363
+ this.fsw._symlinkPaths.set(sp.resolve(path19), targetPath);
17363
17364
  }
17364
17365
  } else {
17365
17366
  closer = this._handleFile(wh.watchPath, stats, initialAdd);
17366
17367
  }
17367
17368
  ready();
17368
17369
  if (closer)
17369
- this.fsw._addPathCloser(path18, closer);
17370
+ this.fsw._addPathCloser(path19, closer);
17370
17371
  return false;
17371
17372
  } catch (error48) {
17372
17373
  if (this.fsw._handleError(error48)) {
17373
17374
  ready();
17374
- return path18;
17375
+ return path19;
17375
17376
  }
17376
17377
  }
17377
17378
  }
@@ -17414,24 +17415,24 @@ function createPattern(matcher) {
17414
17415
  }
17415
17416
  return () => false;
17416
17417
  }
17417
- function normalizePath(path18) {
17418
- if (typeof path18 !== "string")
17418
+ function normalizePath(path19) {
17419
+ if (typeof path19 !== "string")
17419
17420
  throw new Error("string expected");
17420
- path18 = sp2.normalize(path18);
17421
- path18 = path18.replace(/\\/g, "/");
17421
+ path19 = sp2.normalize(path19);
17422
+ path19 = path19.replace(/\\/g, "/");
17422
17423
  let prepend = false;
17423
- if (path18.startsWith("//"))
17424
+ if (path19.startsWith("//"))
17424
17425
  prepend = true;
17425
- path18 = path18.replace(DOUBLE_SLASH_RE, "/");
17426
+ path19 = path19.replace(DOUBLE_SLASH_RE, "/");
17426
17427
  if (prepend)
17427
- path18 = "/" + path18;
17428
- return path18;
17428
+ path19 = "/" + path19;
17429
+ return path19;
17429
17430
  }
17430
17431
  function matchPatterns(patterns, testString, stats) {
17431
- const path18 = normalizePath(testString);
17432
+ const path19 = normalizePath(testString);
17432
17433
  for (let index = 0; index < patterns.length; index++) {
17433
17434
  const pattern = patterns[index];
17434
- if (pattern(path18, stats)) {
17435
+ if (pattern(path19, stats)) {
17435
17436
  return true;
17436
17437
  }
17437
17438
  }
@@ -17469,19 +17470,19 @@ var toUnix = (string4) => {
17469
17470
  }
17470
17471
  return str;
17471
17472
  };
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));
17473
+ var normalizePathToUnix = (path19) => toUnix(sp2.normalize(toUnix(path19)));
17474
+ var normalizeIgnored = (cwd = "") => (path19) => {
17475
+ if (typeof path19 === "string") {
17476
+ return normalizePathToUnix(sp2.isAbsolute(path19) ? path19 : sp2.join(cwd, path19));
17476
17477
  } else {
17477
- return path18;
17478
+ return path19;
17478
17479
  }
17479
17480
  };
17480
- var getAbsolutePath = (path18, cwd) => {
17481
- if (sp2.isAbsolute(path18)) {
17482
- return path18;
17481
+ var getAbsolutePath = (path19, cwd) => {
17482
+ if (sp2.isAbsolute(path19)) {
17483
+ return path19;
17483
17484
  }
17484
- return sp2.join(cwd, path18);
17485
+ return sp2.join(cwd, path19);
17485
17486
  };
17486
17487
  var EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set());
17487
17488
  var DirEntry = class {
@@ -17546,10 +17547,10 @@ var WatchHelper = class {
17546
17547
  dirParts;
17547
17548
  followSymlinks;
17548
17549
  statMethod;
17549
- constructor(path18, follow, fsw) {
17550
+ constructor(path19, follow, fsw) {
17550
17551
  this.fsw = fsw;
17551
- const watchPath = path18;
17552
- this.path = path18 = path18.replace(REPLACER_RE, "");
17552
+ const watchPath = path19;
17553
+ this.path = path19 = path19.replace(REPLACER_RE, "");
17553
17554
  this.watchPath = watchPath;
17554
17555
  this.fullWatchPath = sp2.resolve(watchPath);
17555
17556
  this.dirParts = [];
@@ -17689,20 +17690,20 @@ var FSWatcher = class extends import_node_events.EventEmitter {
17689
17690
  this._closePromise = void 0;
17690
17691
  let paths = unifyPaths(paths_);
17691
17692
  if (cwd) {
17692
- paths = paths.map((path18) => {
17693
- const absPath = getAbsolutePath(path18, cwd);
17693
+ paths = paths.map((path19) => {
17694
+ const absPath = getAbsolutePath(path19, cwd);
17694
17695
  return absPath;
17695
17696
  });
17696
17697
  }
17697
- paths.forEach((path18) => {
17698
- this._removeIgnoredPath(path18);
17698
+ paths.forEach((path19) => {
17699
+ this._removeIgnoredPath(path19);
17699
17700
  });
17700
17701
  this._userIgnored = void 0;
17701
17702
  if (!this._readyCount)
17702
17703
  this._readyCount = 0;
17703
17704
  this._readyCount += paths.length;
17704
- Promise.all(paths.map(async (path18) => {
17705
- const res = await this._nodeFsHandler._addToNodeFs(path18, !_internal, void 0, 0, _origAdd);
17705
+ Promise.all(paths.map(async (path19) => {
17706
+ const res = await this._nodeFsHandler._addToNodeFs(path19, !_internal, void 0, 0, _origAdd);
17706
17707
  if (res)
17707
17708
  this._emitReady();
17708
17709
  return res;
@@ -17724,17 +17725,17 @@ var FSWatcher = class extends import_node_events.EventEmitter {
17724
17725
  return this;
17725
17726
  const paths = unifyPaths(paths_);
17726
17727
  const { cwd } = this.options;
17727
- paths.forEach((path18) => {
17728
- if (!sp2.isAbsolute(path18) && !this._closers.has(path18)) {
17728
+ paths.forEach((path19) => {
17729
+ if (!sp2.isAbsolute(path19) && !this._closers.has(path19)) {
17729
17730
  if (cwd)
17730
- path18 = sp2.join(cwd, path18);
17731
- path18 = sp2.resolve(path18);
17731
+ path19 = sp2.join(cwd, path19);
17732
+ path19 = sp2.resolve(path19);
17732
17733
  }
17733
- this._closePath(path18);
17734
- this._addIgnoredPath(path18);
17735
- if (this._watched.has(path18)) {
17734
+ this._closePath(path19);
17735
+ this._addIgnoredPath(path19);
17736
+ if (this._watched.has(path19)) {
17736
17737
  this._addIgnoredPath({
17737
- path: path18,
17738
+ path: path19,
17738
17739
  recursive: true
17739
17740
  });
17740
17741
  }
@@ -17798,38 +17799,38 @@ var FSWatcher = class extends import_node_events.EventEmitter {
17798
17799
  * @param stats arguments to be passed with event
17799
17800
  * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
17800
17801
  */
17801
- async _emit(event, path18, stats) {
17802
+ async _emit(event, path19, stats) {
17802
17803
  if (this.closed)
17803
17804
  return;
17804
17805
  const opts = this.options;
17805
17806
  if (isWindows)
17806
- path18 = sp2.normalize(path18);
17807
+ path19 = sp2.normalize(path19);
17807
17808
  if (opts.cwd)
17808
- path18 = sp2.relative(opts.cwd, path18);
17809
- const args = [path18];
17809
+ path19 = sp2.relative(opts.cwd, path19);
17810
+ const args = [path19];
17810
17811
  if (stats != null)
17811
17812
  args.push(stats);
17812
17813
  const awf = opts.awaitWriteFinish;
17813
17814
  let pw;
17814
- if (awf && (pw = this._pendingWrites.get(path18))) {
17815
+ if (awf && (pw = this._pendingWrites.get(path19))) {
17815
17816
  pw.lastChange = /* @__PURE__ */ new Date();
17816
17817
  return this;
17817
17818
  }
17818
17819
  if (opts.atomic) {
17819
17820
  if (event === EVENTS.UNLINK) {
17820
- this._pendingUnlinks.set(path18, [event, ...args]);
17821
+ this._pendingUnlinks.set(path19, [event, ...args]);
17821
17822
  setTimeout(() => {
17822
- this._pendingUnlinks.forEach((entry, path19) => {
17823
+ this._pendingUnlinks.forEach((entry, path20) => {
17823
17824
  this.emit(...entry);
17824
17825
  this.emit(EVENTS.ALL, ...entry);
17825
- this._pendingUnlinks.delete(path19);
17826
+ this._pendingUnlinks.delete(path20);
17826
17827
  });
17827
17828
  }, typeof opts.atomic === "number" ? opts.atomic : 100);
17828
17829
  return this;
17829
17830
  }
17830
- if (event === EVENTS.ADD && this._pendingUnlinks.has(path18)) {
17831
+ if (event === EVENTS.ADD && this._pendingUnlinks.has(path19)) {
17831
17832
  event = EVENTS.CHANGE;
17832
- this._pendingUnlinks.delete(path18);
17833
+ this._pendingUnlinks.delete(path19);
17833
17834
  }
17834
17835
  }
17835
17836
  if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
@@ -17847,16 +17848,16 @@ var FSWatcher = class extends import_node_events.EventEmitter {
17847
17848
  this.emitWithAll(event, args);
17848
17849
  }
17849
17850
  };
17850
- this._awaitWriteFinish(path18, awf.stabilityThreshold, event, awfEmit);
17851
+ this._awaitWriteFinish(path19, awf.stabilityThreshold, event, awfEmit);
17851
17852
  return this;
17852
17853
  }
17853
17854
  if (event === EVENTS.CHANGE) {
17854
- const isThrottled = !this._throttle(EVENTS.CHANGE, path18, 50);
17855
+ const isThrottled = !this._throttle(EVENTS.CHANGE, path19, 50);
17855
17856
  if (isThrottled)
17856
17857
  return this;
17857
17858
  }
17858
17859
  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;
17860
+ const fullPath = opts.cwd ? sp2.join(opts.cwd, path19) : path19;
17860
17861
  let stats2;
17861
17862
  try {
17862
17863
  stats2 = await (0, import_promises3.stat)(fullPath);
@@ -17887,23 +17888,23 @@ var FSWatcher = class extends import_node_events.EventEmitter {
17887
17888
  * @param timeout duration of time to suppress duplicate actions
17888
17889
  * @returns tracking object or false if action should be suppressed
17889
17890
  */
17890
- _throttle(actionType, path18, timeout) {
17891
+ _throttle(actionType, path19, timeout) {
17891
17892
  if (!this._throttled.has(actionType)) {
17892
17893
  this._throttled.set(actionType, /* @__PURE__ */ new Map());
17893
17894
  }
17894
17895
  const action = this._throttled.get(actionType);
17895
17896
  if (!action)
17896
17897
  throw new Error("invalid throttle");
17897
- const actionPath = action.get(path18);
17898
+ const actionPath = action.get(path19);
17898
17899
  if (actionPath) {
17899
17900
  actionPath.count++;
17900
17901
  return false;
17901
17902
  }
17902
17903
  let timeoutObject;
17903
17904
  const clear = () => {
17904
- const item = action.get(path18);
17905
+ const item = action.get(path19);
17905
17906
  const count = item ? item.count : 0;
17906
- action.delete(path18);
17907
+ action.delete(path19);
17907
17908
  clearTimeout(timeoutObject);
17908
17909
  if (item)
17909
17910
  clearTimeout(item.timeoutObject);
@@ -17911,7 +17912,7 @@ var FSWatcher = class extends import_node_events.EventEmitter {
17911
17912
  };
17912
17913
  timeoutObject = setTimeout(clear, timeout);
17913
17914
  const thr = { timeoutObject, clear, count: 0 };
17914
- action.set(path18, thr);
17915
+ action.set(path19, thr);
17915
17916
  return thr;
17916
17917
  }
17917
17918
  _incrReadyCount() {
@@ -17925,44 +17926,44 @@ var FSWatcher = class extends import_node_events.EventEmitter {
17925
17926
  * @param event
17926
17927
  * @param awfEmit Callback to be called when ready for event to be emitted.
17927
17928
  */
17928
- _awaitWriteFinish(path18, threshold, event, awfEmit) {
17929
+ _awaitWriteFinish(path19, threshold, event, awfEmit) {
17929
17930
  const awf = this.options.awaitWriteFinish;
17930
17931
  if (typeof awf !== "object")
17931
17932
  return;
17932
17933
  const pollInterval = awf.pollInterval;
17933
17934
  let timeoutHandler;
17934
- let fullPath = path18;
17935
- if (this.options.cwd && !sp2.isAbsolute(path18)) {
17936
- fullPath = sp2.join(this.options.cwd, path18);
17935
+ let fullPath = path19;
17936
+ if (this.options.cwd && !sp2.isAbsolute(path19)) {
17937
+ fullPath = sp2.join(this.options.cwd, path19);
17937
17938
  }
17938
17939
  const now = /* @__PURE__ */ new Date();
17939
17940
  const writes = this._pendingWrites;
17940
17941
  function awaitWriteFinishFn(prevStat) {
17941
17942
  (0, import_node_fs2.stat)(fullPath, (err, curStat) => {
17942
- if (err || !writes.has(path18)) {
17943
+ if (err || !writes.has(path19)) {
17943
17944
  if (err && err.code !== "ENOENT")
17944
17945
  awfEmit(err);
17945
17946
  return;
17946
17947
  }
17947
17948
  const now2 = Number(/* @__PURE__ */ new Date());
17948
17949
  if (prevStat && curStat.size !== prevStat.size) {
17949
- writes.get(path18).lastChange = now2;
17950
+ writes.get(path19).lastChange = now2;
17950
17951
  }
17951
- const pw = writes.get(path18);
17952
+ const pw = writes.get(path19);
17952
17953
  const df = now2 - pw.lastChange;
17953
17954
  if (df >= threshold) {
17954
- writes.delete(path18);
17955
+ writes.delete(path19);
17955
17956
  awfEmit(void 0, curStat);
17956
17957
  } else {
17957
17958
  timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
17958
17959
  }
17959
17960
  });
17960
17961
  }
17961
- if (!writes.has(path18)) {
17962
- writes.set(path18, {
17962
+ if (!writes.has(path19)) {
17963
+ writes.set(path19, {
17963
17964
  lastChange: now,
17964
17965
  cancelWait: () => {
17965
- writes.delete(path18);
17966
+ writes.delete(path19);
17966
17967
  clearTimeout(timeoutHandler);
17967
17968
  return event;
17968
17969
  }
@@ -17973,8 +17974,8 @@ var FSWatcher = class extends import_node_events.EventEmitter {
17973
17974
  /**
17974
17975
  * Determines whether user has asked to ignore this path.
17975
17976
  */
17976
- _isIgnored(path18, stats) {
17977
- if (this.options.atomic && DOT_RE.test(path18))
17977
+ _isIgnored(path19, stats) {
17978
+ if (this.options.atomic && DOT_RE.test(path19))
17978
17979
  return true;
17979
17980
  if (!this._userIgnored) {
17980
17981
  const { cwd } = this.options;
@@ -17984,17 +17985,17 @@ var FSWatcher = class extends import_node_events.EventEmitter {
17984
17985
  const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];
17985
17986
  this._userIgnored = anymatch(list, void 0);
17986
17987
  }
17987
- return this._userIgnored(path18, stats);
17988
+ return this._userIgnored(path19, stats);
17988
17989
  }
17989
- _isntIgnored(path18, stat4) {
17990
- return !this._isIgnored(path18, stat4);
17990
+ _isntIgnored(path19, stat4) {
17991
+ return !this._isIgnored(path19, stat4);
17991
17992
  }
17992
17993
  /**
17993
17994
  * Provides a set of common helpers and properties relating to symlink handling.
17994
17995
  * @param path file or directory pattern being watched
17995
17996
  */
17996
- _getWatchHelpers(path18) {
17997
- return new WatchHelper(path18, this.options.followSymlinks, this);
17997
+ _getWatchHelpers(path19) {
17998
+ return new WatchHelper(path19, this.options.followSymlinks, this);
17998
17999
  }
17999
18000
  // Directory helpers
18000
18001
  // -----------------
@@ -18026,63 +18027,63 @@ var FSWatcher = class extends import_node_events.EventEmitter {
18026
18027
  * @param item base path of item/directory
18027
18028
  */
18028
18029
  _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))
18030
+ const path19 = sp2.join(directory, item);
18031
+ const fullPath = sp2.resolve(path19);
18032
+ isDirectory = isDirectory != null ? isDirectory : this._watched.has(path19) || this._watched.has(fullPath);
18033
+ if (!this._throttle("remove", path19, 100))
18033
18034
  return;
18034
18035
  if (!isDirectory && this._watched.size === 1) {
18035
18036
  this.add(directory, item, true);
18036
18037
  }
18037
- const wp = this._getWatchedDir(path18);
18038
+ const wp = this._getWatchedDir(path19);
18038
18039
  const nestedDirectoryChildren = wp.getChildren();
18039
- nestedDirectoryChildren.forEach((nested) => this._remove(path18, nested));
18040
+ nestedDirectoryChildren.forEach((nested) => this._remove(path19, nested));
18040
18041
  const parent = this._getWatchedDir(directory);
18041
18042
  const wasTracked = parent.has(item);
18042
18043
  parent.remove(item);
18043
18044
  if (this._symlinkPaths.has(fullPath)) {
18044
18045
  this._symlinkPaths.delete(fullPath);
18045
18046
  }
18046
- let relPath = path18;
18047
+ let relPath = path19;
18047
18048
  if (this.options.cwd)
18048
- relPath = sp2.relative(this.options.cwd, path18);
18049
+ relPath = sp2.relative(this.options.cwd, path19);
18049
18050
  if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
18050
18051
  const event = this._pendingWrites.get(relPath).cancelWait();
18051
18052
  if (event === EVENTS.ADD)
18052
18053
  return;
18053
18054
  }
18054
- this._watched.delete(path18);
18055
+ this._watched.delete(path19);
18055
18056
  this._watched.delete(fullPath);
18056
18057
  const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
18057
- if (wasTracked && !this._isIgnored(path18))
18058
- this._emit(eventName, path18);
18059
- this._closePath(path18);
18058
+ if (wasTracked && !this._isIgnored(path19))
18059
+ this._emit(eventName, path19);
18060
+ this._closePath(path19);
18060
18061
  }
18061
18062
  /**
18062
18063
  * Closes all watchers for a path
18063
18064
  */
18064
- _closePath(path18) {
18065
- this._closeFile(path18);
18066
- const dir = sp2.dirname(path18);
18067
- this._getWatchedDir(dir).remove(sp2.basename(path18));
18065
+ _closePath(path19) {
18066
+ this._closeFile(path19);
18067
+ const dir = sp2.dirname(path19);
18068
+ this._getWatchedDir(dir).remove(sp2.basename(path19));
18068
18069
  }
18069
18070
  /**
18070
18071
  * Closes only file-specific watchers
18071
18072
  */
18072
- _closeFile(path18) {
18073
- const closers = this._closers.get(path18);
18073
+ _closeFile(path19) {
18074
+ const closers = this._closers.get(path19);
18074
18075
  if (!closers)
18075
18076
  return;
18076
18077
  closers.forEach((closer) => closer());
18077
- this._closers.delete(path18);
18078
+ this._closers.delete(path19);
18078
18079
  }
18079
- _addPathCloser(path18, closer) {
18080
+ _addPathCloser(path19, closer) {
18080
18081
  if (!closer)
18081
18082
  return;
18082
- let list = this._closers.get(path18);
18083
+ let list = this._closers.get(path19);
18083
18084
  if (!list) {
18084
18085
  list = [];
18085
- this._closers.set(path18, list);
18086
+ this._closers.set(path19, list);
18086
18087
  }
18087
18088
  list.push(closer);
18088
18089
  }
@@ -18112,12 +18113,12 @@ function watch(paths, options = {}) {
18112
18113
 
18113
18114
  // ../daemon-core/dist/index.mjs
18114
18115
  var fs6 = __toESM(require("fs"), 1);
18115
- var path8 = __toESM(require("path"), 1);
18116
+ var path9 = __toESM(require("path"), 1);
18116
18117
  var os9 = __toESM(require("os"), 1);
18117
18118
  var fs7 = __toESM(require("fs"), 1);
18118
18119
  var os10 = __toESM(require("os"), 1);
18119
18120
  var os13 = __toESM(require("os"), 1);
18120
- var path10 = __toESM(require("path"), 1);
18121
+ var path11 = __toESM(require("path"), 1);
18121
18122
  var crypto4 = __toESM(require("crypto"), 1);
18122
18123
  var import_chalk = __toESM(require("chalk"), 1);
18123
18124
  var crypto3 = __toESM(require("crypto"), 1);
@@ -18125,17 +18126,17 @@ var import_stream = require("stream");
18125
18126
  var import_child_process6 = require("child_process");
18126
18127
  init_acp();
18127
18128
  var fs8 = __toESM(require("fs"), 1);
18128
- var path11 = __toESM(require("path"), 1);
18129
+ var path12 = __toESM(require("path"), 1);
18129
18130
  var os14 = __toESM(require("os"), 1);
18130
18131
  var import_child_process7 = require("child_process");
18131
18132
  var import_os3 = require("os");
18132
18133
  var http2 = __toESM(require("http"), 1);
18133
18134
  var fs11 = __toESM(require("fs"), 1);
18134
- var path14 = __toESM(require("path"), 1);
18135
+ var path15 = __toESM(require("path"), 1);
18135
18136
  var fs9 = __toESM(require("fs"), 1);
18136
- var path12 = __toESM(require("path"), 1);
18137
- var fs10 = __toESM(require("fs"), 1);
18138
18137
  var path13 = __toESM(require("path"), 1);
18138
+ var fs10 = __toESM(require("fs"), 1);
18139
+ var path14 = __toESM(require("path"), 1);
18139
18140
  var os15 = __toESM(require("os"), 1);
18140
18141
 
18141
18142
  // ../session-host-core/dist/index.mjs
@@ -18205,8 +18206,8 @@ var SessionHostClient = class {
18205
18206
  }
18206
18207
  this.requestWaiters.clear();
18207
18208
  });
18208
- await new Promise((resolve12, reject) => {
18209
- socket.once("connect", () => resolve12());
18209
+ await new Promise((resolve13, reject) => {
18210
+ socket.once("connect", () => resolve13());
18210
18211
  socket.once("error", reject);
18211
18212
  });
18212
18213
  }
@@ -18225,7 +18226,7 @@ var SessionHostClient = class {
18225
18226
  requestId,
18226
18227
  request
18227
18228
  };
18228
- const response = await new Promise((resolve12, reject) => {
18229
+ const response = await new Promise((resolve13, reject) => {
18229
18230
  const timeout = setTimeout(() => {
18230
18231
  this.requestWaiters.delete(requestId);
18231
18232
  reject(new Error(`Session host request timed out after 30s (${request.type})`));
@@ -18233,7 +18234,7 @@ var SessionHostClient = class {
18233
18234
  this.requestWaiters.set(requestId, {
18234
18235
  resolve: (value) => {
18235
18236
  clearTimeout(timeout);
18236
- resolve12(value);
18237
+ resolve13(value);
18237
18238
  },
18238
18239
  reject: (error48) => {
18239
18240
  clearTimeout(timeout);
@@ -18252,12 +18253,12 @@ var SessionHostClient = class {
18252
18253
  waiter.reject(new Error("Session host client closed"));
18253
18254
  }
18254
18255
  this.requestWaiters.clear();
18255
- await new Promise((resolve12) => {
18256
+ await new Promise((resolve13) => {
18256
18257
  let settled = false;
18257
18258
  const done = () => {
18258
18259
  if (settled) return;
18259
18260
  settled = true;
18260
- resolve12();
18261
+ resolve13();
18261
18262
  };
18262
18263
  socket.once("close", done);
18263
18264
  socket.end();
@@ -18426,8 +18427,17 @@ function findWorkspaceByPath(config2, rawPath) {
18426
18427
  if (!abs) return void 0;
18427
18428
  return (config2.workspaces || []).find((w) => path.resolve(expandPath(w.path)) === abs);
18428
18429
  }
18429
- function addWorkspaceEntry(config2, rawPath, label) {
18430
+ function addWorkspaceEntry(config2, rawPath, label, options) {
18430
18431
  const abs = expandPath(rawPath);
18432
+ const createIfMissing = options?.createIfMissing === true;
18433
+ if (!abs) return { error: "Path required" };
18434
+ if (!fs.existsSync(abs) && createIfMissing) {
18435
+ try {
18436
+ fs.mkdirSync(abs, { recursive: true });
18437
+ } catch (e) {
18438
+ return { error: e?.message || "Could not create directory" };
18439
+ }
18440
+ }
18431
18441
  const v = validateWorkspacePath(abs);
18432
18442
  if (!v.ok) return { error: v.error };
18433
18443
  const list = [...config2.workspaces || []];
@@ -18648,6 +18658,8 @@ var init_config = __esm2({
18648
18658
  workspaces: [],
18649
18659
  defaultWorkspaceId: null,
18650
18660
  recentWorkspaceActivity: [],
18661
+ recentActivity: [],
18662
+ recentSessionReads: {},
18651
18663
  machineNickname: null,
18652
18664
  machineId: void 0,
18653
18665
  machineSecret: null,
@@ -18667,7 +18679,7 @@ function checkDateRotation() {
18667
18679
  const today = getDateStr();
18668
18680
  if (today !== currentDate) {
18669
18681
  currentDate = today;
18670
- currentLogFile = path3.join(LOG_DIR, `daemon-${currentDate}.log`);
18682
+ currentLogFile = path4.join(LOG_DIR, `daemon-${currentDate}.log`);
18671
18683
  cleanOldLogs();
18672
18684
  }
18673
18685
  }
@@ -18681,7 +18693,7 @@ function cleanOldLogs() {
18681
18693
  const dateMatch = file2.match(/daemon-(\d{4}-\d{2}-\d{2})/);
18682
18694
  if (dateMatch && dateMatch[1] < cutoffStr) {
18683
18695
  try {
18684
- fs2.unlinkSync(path3.join(LOG_DIR, file2));
18696
+ fs2.unlinkSync(path4.join(LOG_DIR, file2));
18685
18697
  } catch {
18686
18698
  }
18687
18699
  }
@@ -18821,7 +18833,7 @@ var init_logger = __esm2({
18821
18833
  LEVEL_NUM = { debug: 0, info: 1, warn: 2, error: 3 };
18822
18834
  LEVEL_LABEL = { debug: "DBG", info: "INF", warn: "WRN", error: "ERR" };
18823
18835
  currentLevel = "info";
18824
- LOG_DIR = process.platform === "win32" ? path3.join(process.env.LOCALAPPDATA || process.env.APPDATA || path3.join(os4.homedir(), "AppData", "Local"), "adhdev", "logs") : process.platform === "darwin" ? path3.join(os4.homedir(), "Library", "Logs", "adhdev") : path3.join(os4.homedir(), ".local", "share", "adhdev", "logs");
18836
+ LOG_DIR = process.platform === "win32" ? path4.join(process.env.LOCALAPPDATA || process.env.APPDATA || path4.join(os4.homedir(), "AppData", "Local"), "adhdev", "logs") : process.platform === "darwin" ? path4.join(os4.homedir(), "Library", "Logs", "adhdev") : path4.join(os4.homedir(), ".local", "share", "adhdev", "logs");
18825
18837
  MAX_LOG_SIZE = 5 * 1024 * 1024;
18826
18838
  MAX_LOG_DAYS = 7;
18827
18839
  try {
@@ -18829,16 +18841,16 @@ var init_logger = __esm2({
18829
18841
  } catch {
18830
18842
  }
18831
18843
  currentDate = getDateStr();
18832
- currentLogFile = path3.join(LOG_DIR, `daemon-${currentDate}.log`);
18844
+ currentLogFile = path4.join(LOG_DIR, `daemon-${currentDate}.log`);
18833
18845
  cleanOldLogs();
18834
18846
  try {
18835
- const oldLog = path3.join(LOG_DIR, "daemon.log");
18847
+ const oldLog = path4.join(LOG_DIR, "daemon.log");
18836
18848
  if (fs2.existsSync(oldLog)) {
18837
18849
  const stat4 = fs2.statSync(oldLog);
18838
18850
  const oldDate = stat4.mtime.toISOString().slice(0, 10);
18839
- fs2.renameSync(oldLog, path3.join(LOG_DIR, `daemon-${oldDate}.log`));
18851
+ fs2.renameSync(oldLog, path4.join(LOG_DIR, `daemon-${oldDate}.log`));
18840
18852
  }
18841
- const oldLogBackup = path3.join(LOG_DIR, "daemon.log.old");
18853
+ const oldLogBackup = path4.join(LOG_DIR, "daemon.log.old");
18842
18854
  if (fs2.existsSync(oldLogBackup)) {
18843
18855
  fs2.unlinkSync(oldLogBackup);
18844
18856
  }
@@ -18870,7 +18882,7 @@ var init_logger = __esm2({
18870
18882
  }
18871
18883
  };
18872
18884
  interceptorInstalled = false;
18873
- LOG_PATH = path3.join(LOG_DIR, `daemon-${getDateStr()}.log`);
18885
+ LOG_PATH = path4.join(LOG_DIR, `daemon-${getDateStr()}.log`);
18874
18886
  }
18875
18887
  });
18876
18888
  function isModuleNotFoundError(error48, ref) {
@@ -19033,6 +19045,12 @@ var init_xterm_backend = __esm2({
19033
19045
  };
19034
19046
  }
19035
19047
  });
19048
+ function getTerminalBackendRuntimeStatus() {
19049
+ const preference = resolveTerminalBackendPreference();
19050
+ const ghosttyAvailable = isGhosttyVtBackendAvailable();
19051
+ const backend = preference === "ghostty-vt" || preference === "auto" && ghosttyAvailable ? "ghostty-vt" : "xterm";
19052
+ return { backend, preference, ghosttyAvailable };
19053
+ }
19036
19054
  function createTerminalBackend(options, preference) {
19037
19055
  const ghosttyAvailable = isGhosttyVtBackendAvailable();
19038
19056
  if (preference === "ghostty-vt") {
@@ -19189,7 +19207,7 @@ function findBinary(name) {
19189
19207
  }
19190
19208
  }
19191
19209
  function isScriptBinary(binaryPath) {
19192
- if (!path9.isAbsolute(binaryPath)) return false;
19210
+ if (!path10.isAbsolute(binaryPath)) return false;
19193
19211
  try {
19194
19212
  const fs122 = __require("fs");
19195
19213
  const resolved = fs122.realpathSync(binaryPath);
@@ -19205,7 +19223,7 @@ function isScriptBinary(binaryPath) {
19205
19223
  }
19206
19224
  }
19207
19225
  function looksLikeMachOOrElf(filePath) {
19208
- if (!path9.isAbsolute(filePath)) return false;
19226
+ if (!path10.isAbsolute(filePath)) return false;
19209
19227
  try {
19210
19228
  const fs122 = __require("fs");
19211
19229
  const resolved = fs122.realpathSync(filePath);
@@ -19332,9 +19350,9 @@ var init_provider_cli_adapter = __esm2({
19332
19350
  if (os12.platform() !== "win32") {
19333
19351
  try {
19334
19352
  const fs122 = __require("fs");
19335
- const ptyDir = path9.resolve(path9.dirname(__require.resolve("node-pty")), "..");
19353
+ const ptyDir = path10.resolve(path10.dirname(__require.resolve("node-pty")), "..");
19336
19354
  const platformArch = `${os12.platform()}-${os12.arch()}`;
19337
- const helper = path9.join(ptyDir, "prebuilds", platformArch, "spawn-helper");
19355
+ const helper = path10.join(ptyDir, "prebuilds", platformArch, "spawn-helper");
19338
19356
  if (fs122.existsSync(helper)) {
19339
19357
  const stat4 = fs122.statSync(helper);
19340
19358
  if (!(stat4.mode & 73)) {
@@ -19523,7 +19541,7 @@ var init_provider_cli_adapter = __esm2({
19523
19541
  LOG.info("CLI", `[${this.cliType}] Spawning in ${this.workingDir}`);
19524
19542
  let shellCmd;
19525
19543
  let shellArgs;
19526
- const useShellUnix = !isWin && (!!spawnConfig.shell || !path9.isAbsolute(binaryPath) || isScriptBinary(binaryPath) || !looksLikeMachOOrElf(binaryPath));
19544
+ const useShellUnix = !isWin && (!!spawnConfig.shell || !path10.isAbsolute(binaryPath) || isScriptBinary(binaryPath) || !looksLikeMachOOrElf(binaryPath));
19527
19545
  const useShell = isWin ? !!spawnConfig.shell : useShellUnix;
19528
19546
  if (useShell) {
19529
19547
  if (!spawnConfig.shell && !isWin) {
@@ -19948,7 +19966,7 @@ ${data.message || ""}`.trim();
19948
19966
  if (this.startupParseGate) {
19949
19967
  const deadline = Date.now() + 1e4;
19950
19968
  while (this.startupParseGate && Date.now() < deadline) {
19951
- await new Promise((resolve92) => setTimeout(resolve92, 50));
19969
+ await new Promise((resolve102) => setTimeout(resolve102, 50));
19952
19970
  }
19953
19971
  }
19954
19972
  if (!this.ready) throw new Error(`${this.cliName} not ready (status: ${this.currentStatus})`);
@@ -20116,17 +20134,17 @@ ${data.message || ""}`.trim();
20116
20134
  }
20117
20135
  }
20118
20136
  waitForStopped(timeoutMs) {
20119
- return new Promise((resolve92) => {
20137
+ return new Promise((resolve102) => {
20120
20138
  const startedAt = Date.now();
20121
20139
  const timer = setInterval(() => {
20122
20140
  if (!this.ptyProcess || this.currentStatus === "stopped") {
20123
20141
  clearInterval(timer);
20124
- resolve92(true);
20142
+ resolve102(true);
20125
20143
  return;
20126
20144
  }
20127
20145
  if (Date.now() - startedAt >= timeoutMs) {
20128
20146
  clearInterval(timer);
20129
- resolve92(false);
20147
+ resolve102(false);
20130
20148
  }
20131
20149
  }, 100);
20132
20150
  });
@@ -20354,6 +20372,49 @@ function removeActivityForPath(config2, rawPath) {
20354
20372
  )
20355
20373
  };
20356
20374
  }
20375
+ init_workspaces();
20376
+ var MAX_ACTIVITY2 = 30;
20377
+ function normalizeWorkspace(workspace) {
20378
+ if (!workspace) return "";
20379
+ try {
20380
+ return path3.resolve(expandPath(workspace));
20381
+ } catch {
20382
+ return path3.resolve(workspace);
20383
+ }
20384
+ }
20385
+ function buildRecentActivityKey(entry) {
20386
+ return `${entry.kind}:${entry.providerType}:${normalizeWorkspace(entry.workspace)}`;
20387
+ }
20388
+ function appendRecentActivity(config2, entry) {
20389
+ const nextEntry = {
20390
+ ...entry,
20391
+ workspace: entry.workspace ? normalizeWorkspace(entry.workspace) : void 0,
20392
+ id: buildRecentActivityKey(entry),
20393
+ lastUsedAt: entry.lastUsedAt || Date.now()
20394
+ };
20395
+ const filtered = (config2.recentActivity || []).filter((item) => item.id !== nextEntry.id);
20396
+ return {
20397
+ ...config2,
20398
+ recentActivity: [nextEntry, ...filtered].slice(0, MAX_ACTIVITY2)
20399
+ };
20400
+ }
20401
+ function getRecentActivity(config2, limit = 20) {
20402
+ return [...config2.recentActivity || []].sort((a, b) => b.lastUsedAt - a.lastUsedAt).slice(0, limit);
20403
+ }
20404
+ function getRecentSessionSeenAt(config2, recentKey) {
20405
+ return config2.recentSessionReads?.[recentKey] || 0;
20406
+ }
20407
+ function markRecentSessionSeen(config2, recentKey, seenAt = Date.now()) {
20408
+ const prev = config2.recentSessionReads || {};
20409
+ const nextSeenAt = Math.max(prev[recentKey] || 0, seenAt);
20410
+ return {
20411
+ ...config2,
20412
+ recentSessionReads: {
20413
+ ...prev,
20414
+ [recentKey]: nextSeenAt
20415
+ }
20416
+ };
20417
+ }
20357
20418
  var BUILTIN_IDE_DEFINITIONS = [];
20358
20419
  var registeredIDEs = /* @__PURE__ */ new Map();
20359
20420
  function registerIDEDefinition(def) {
@@ -20453,15 +20514,15 @@ function parseVersion(raw) {
20453
20514
  return match ? match[1] : raw.split("\n")[0].slice(0, 100);
20454
20515
  }
20455
20516
  function execAsync(cmd, timeoutMs = 5e3) {
20456
- return new Promise((resolve92) => {
20517
+ return new Promise((resolve102) => {
20457
20518
  const child = (0, import_child_process3.exec)(cmd, { encoding: "utf-8", timeout: timeoutMs }, (err, stdout) => {
20458
20519
  if (err || !stdout?.trim()) {
20459
- resolve92(null);
20520
+ resolve102(null);
20460
20521
  } else {
20461
- resolve92(stdout.trim());
20522
+ resolve102(stdout.trim());
20462
20523
  }
20463
20524
  });
20464
- child.on("error", () => resolve92(null));
20525
+ child.on("error", () => resolve102(null));
20465
20526
  });
20466
20527
  }
20467
20528
  async function detectCLIs(providerLoader) {
@@ -20620,7 +20681,7 @@ var DaemonCdpManager = class {
20620
20681
  * Returns multiple entries if multiple IDE windows are open on same port
20621
20682
  */
20622
20683
  static listAllTargets(port) {
20623
- return new Promise((resolve92) => {
20684
+ return new Promise((resolve102) => {
20624
20685
  const req = http.get(`http://127.0.0.1:${port}/json`, (res) => {
20625
20686
  let data = "";
20626
20687
  res.on("data", (chunk) => data += chunk.toString());
@@ -20636,16 +20697,16 @@ var DaemonCdpManager = class {
20636
20697
  (t) => !isNonMain(t.title || "") && t.url?.includes("workbench.html") && !t.url?.includes("agent")
20637
20698
  );
20638
20699
  const fallbackPages = pages.filter((t) => !isNonMain(t.title || ""));
20639
- resolve92(mainPages.length > 0 ? mainPages : fallbackPages);
20700
+ resolve102(mainPages.length > 0 ? mainPages : fallbackPages);
20640
20701
  } catch {
20641
- resolve92([]);
20702
+ resolve102([]);
20642
20703
  }
20643
20704
  });
20644
20705
  });
20645
- req.on("error", () => resolve92([]));
20706
+ req.on("error", () => resolve102([]));
20646
20707
  req.setTimeout(2e3, () => {
20647
20708
  req.destroy();
20648
- resolve92([]);
20709
+ resolve102([]);
20649
20710
  });
20650
20711
  });
20651
20712
  }
@@ -20685,7 +20746,7 @@ var DaemonCdpManager = class {
20685
20746
  }
20686
20747
  }
20687
20748
  findTargetOnPort(port) {
20688
- return new Promise((resolve92) => {
20749
+ return new Promise((resolve102) => {
20689
20750
  const req = http.get(`http://127.0.0.1:${port}/json`, (res) => {
20690
20751
  let data = "";
20691
20752
  res.on("data", (chunk) => data += chunk.toString());
@@ -20696,7 +20757,7 @@ var DaemonCdpManager = class {
20696
20757
  (t) => (t.type === "page" || t.type === "browser" || t.type === "Page") && t.webSocketDebuggerUrl
20697
20758
  );
20698
20759
  if (pages.length === 0) {
20699
- resolve92(targets.find((t) => t.webSocketDebuggerUrl) || null);
20760
+ resolve102(targets.find((t) => t.webSocketDebuggerUrl) || null);
20700
20761
  return;
20701
20762
  }
20702
20763
  const mainPages = pages.filter((t) => !this.isNonMainTitle(t.title || ""));
@@ -20706,24 +20767,24 @@ var DaemonCdpManager = class {
20706
20767
  const specific = list.find((t) => t.id === this._targetId);
20707
20768
  if (specific) {
20708
20769
  this._pageTitle = specific.title || "";
20709
- resolve92(specific);
20770
+ resolve102(specific);
20710
20771
  } else {
20711
20772
  this.log(`[CDP] Target ${this._targetId} not found in page list`);
20712
- resolve92(null);
20773
+ resolve102(null);
20713
20774
  }
20714
20775
  return;
20715
20776
  }
20716
20777
  this._pageTitle = list[0]?.title || "";
20717
- resolve92(list[0]);
20778
+ resolve102(list[0]);
20718
20779
  } catch {
20719
- resolve92(null);
20780
+ resolve102(null);
20720
20781
  }
20721
20782
  });
20722
20783
  });
20723
- req.on("error", () => resolve92(null));
20784
+ req.on("error", () => resolve102(null));
20724
20785
  req.setTimeout(2e3, () => {
20725
20786
  req.destroy();
20726
- resolve92(null);
20787
+ resolve102(null);
20727
20788
  });
20728
20789
  });
20729
20790
  }
@@ -20734,7 +20795,7 @@ var DaemonCdpManager = class {
20734
20795
  this.extensionProviders = providers;
20735
20796
  }
20736
20797
  connectToTarget(wsUrl) {
20737
- return new Promise((resolve92) => {
20798
+ return new Promise((resolve102) => {
20738
20799
  this.ws = new import_ws.default(wsUrl);
20739
20800
  this.ws.on("open", async () => {
20740
20801
  this._connected = true;
@@ -20744,17 +20805,17 @@ var DaemonCdpManager = class {
20744
20805
  }
20745
20806
  this.connectBrowserWs().catch(() => {
20746
20807
  });
20747
- resolve92(true);
20808
+ resolve102(true);
20748
20809
  });
20749
20810
  this.ws.on("message", (data) => {
20750
20811
  try {
20751
20812
  const msg = JSON.parse(data.toString());
20752
20813
  if (msg.id && this.pending.has(msg.id)) {
20753
- const { resolve: resolve102, reject } = this.pending.get(msg.id);
20814
+ const { resolve: resolve112, reject } = this.pending.get(msg.id);
20754
20815
  this.pending.delete(msg.id);
20755
20816
  this.failureCount = 0;
20756
20817
  if (msg.error) reject(new Error(msg.error.message));
20757
- else resolve102(msg.result);
20818
+ else resolve112(msg.result);
20758
20819
  } else if (msg.method === "Runtime.executionContextCreated") {
20759
20820
  this.contexts.add(msg.params.context.id);
20760
20821
  } else if (msg.method === "Runtime.executionContextDestroyed") {
@@ -20777,7 +20838,7 @@ var DaemonCdpManager = class {
20777
20838
  this.ws.on("error", (err) => {
20778
20839
  this.log(`[CDP] WebSocket error: ${err.message}`);
20779
20840
  this._connected = false;
20780
- resolve92(false);
20841
+ resolve102(false);
20781
20842
  });
20782
20843
  });
20783
20844
  }
@@ -20791,7 +20852,7 @@ var DaemonCdpManager = class {
20791
20852
  return;
20792
20853
  }
20793
20854
  this.log(`[CDP] Connecting browser WS for target discovery...`);
20794
- await new Promise((resolve92, reject) => {
20855
+ await new Promise((resolve102, reject) => {
20795
20856
  this.browserWs = new import_ws.default(browserWsUrl);
20796
20857
  this.browserWs.on("open", async () => {
20797
20858
  this._browserConnected = true;
@@ -20801,16 +20862,16 @@ var DaemonCdpManager = class {
20801
20862
  } catch (e) {
20802
20863
  this.log(`[CDP] setDiscoverTargets failed: ${e.message}`);
20803
20864
  }
20804
- resolve92();
20865
+ resolve102();
20805
20866
  });
20806
20867
  this.browserWs.on("message", (data) => {
20807
20868
  try {
20808
20869
  const msg = JSON.parse(data.toString());
20809
20870
  if (msg.id && this.browserPending.has(msg.id)) {
20810
- const { resolve: resolve102, reject: reject2 } = this.browserPending.get(msg.id);
20871
+ const { resolve: resolve112, reject: reject2 } = this.browserPending.get(msg.id);
20811
20872
  this.browserPending.delete(msg.id);
20812
20873
  if (msg.error) reject2(new Error(msg.error.message));
20813
- else resolve102(msg.result);
20874
+ else resolve112(msg.result);
20814
20875
  }
20815
20876
  } catch {
20816
20877
  }
@@ -20830,31 +20891,31 @@ var DaemonCdpManager = class {
20830
20891
  }
20831
20892
  }
20832
20893
  getBrowserWsUrl() {
20833
- return new Promise((resolve92) => {
20894
+ return new Promise((resolve102) => {
20834
20895
  const req = http.get(`http://127.0.0.1:${this.port}/json/version`, (res) => {
20835
20896
  let data = "";
20836
20897
  res.on("data", (chunk) => data += chunk.toString());
20837
20898
  res.on("end", () => {
20838
20899
  try {
20839
20900
  const info = JSON.parse(data);
20840
- resolve92(info.webSocketDebuggerUrl || null);
20901
+ resolve102(info.webSocketDebuggerUrl || null);
20841
20902
  } catch {
20842
- resolve92(null);
20903
+ resolve102(null);
20843
20904
  }
20844
20905
  });
20845
20906
  });
20846
- req.on("error", () => resolve92(null));
20907
+ req.on("error", () => resolve102(null));
20847
20908
  req.setTimeout(3e3, () => {
20848
20909
  req.destroy();
20849
- resolve92(null);
20910
+ resolve102(null);
20850
20911
  });
20851
20912
  });
20852
20913
  }
20853
20914
  sendBrowser(method, params = {}, timeoutMs = 15e3) {
20854
- return new Promise((resolve92, reject) => {
20915
+ return new Promise((resolve102, reject) => {
20855
20916
  if (!this.browserWs || !this._browserConnected) return reject(new Error("Browser WS not connected"));
20856
20917
  const id = this.browserMsgId++;
20857
- this.browserPending.set(id, { resolve: resolve92, reject });
20918
+ this.browserPending.set(id, { resolve: resolve102, reject });
20858
20919
  this.browserWs.send(JSON.stringify({ id, method, params }));
20859
20920
  setTimeout(() => {
20860
20921
  if (this.browserPending.has(id)) {
@@ -20894,11 +20955,11 @@ var DaemonCdpManager = class {
20894
20955
  }
20895
20956
  // ─── CDP Protocol ────────────────────────────────────────
20896
20957
  sendInternal(method, params = {}, timeoutMs = 15e3) {
20897
- return new Promise((resolve92, reject) => {
20958
+ return new Promise((resolve102, reject) => {
20898
20959
  if (!this.ws || !this._connected) return reject(new Error("CDP not connected"));
20899
20960
  if (this.ws.readyState !== import_ws.default.OPEN) return reject(new Error("WebSocket not open"));
20900
20961
  const id = this.msgId++;
20901
- this.pending.set(id, { resolve: resolve92, reject });
20962
+ this.pending.set(id, { resolve: resolve102, reject });
20902
20963
  this.ws.send(JSON.stringify({ id, method, params }));
20903
20964
  setTimeout(() => {
20904
20965
  if (this.pending.has(id)) {
@@ -21147,7 +21208,7 @@ var DaemonCdpManager = class {
21147
21208
  const browserWs = this.browserWs;
21148
21209
  let msgId = this.browserMsgId;
21149
21210
  const sendWs = (method, params = {}, sessionId) => {
21150
- return new Promise((resolve92, reject) => {
21211
+ return new Promise((resolve102, reject) => {
21151
21212
  const mid = msgId++;
21152
21213
  this.browserMsgId = msgId;
21153
21214
  const handler = (raw) => {
@@ -21156,7 +21217,7 @@ var DaemonCdpManager = class {
21156
21217
  if (msg.id === mid) {
21157
21218
  browserWs.removeListener("message", handler);
21158
21219
  if (msg.error) reject(new Error(msg.error.message || JSON.stringify(msg.error)));
21159
- else resolve92(msg.result);
21220
+ else resolve102(msg.result);
21160
21221
  }
21161
21222
  } catch {
21162
21223
  }
@@ -21347,14 +21408,14 @@ var DaemonCdpManager = class {
21347
21408
  if (!ws || ws.readyState !== import_ws.default.OPEN) {
21348
21409
  throw new Error("CDP not connected");
21349
21410
  }
21350
- return new Promise((resolve92, reject) => {
21411
+ return new Promise((resolve102, reject) => {
21351
21412
  const id = getNextId();
21352
21413
  pendingMap.set(id, {
21353
21414
  resolve: (result) => {
21354
21415
  if (result?.result?.subtype === "error") {
21355
21416
  reject(new Error(result.result.description));
21356
21417
  } else {
21357
- resolve92(result?.result?.value);
21418
+ resolve102(result?.result?.value);
21358
21419
  }
21359
21420
  },
21360
21421
  reject
@@ -21386,10 +21447,10 @@ var DaemonCdpManager = class {
21386
21447
  throw new Error("CDP not connected");
21387
21448
  }
21388
21449
  const sendViaSession = (method, params = {}) => {
21389
- return new Promise((resolve92, reject) => {
21450
+ return new Promise((resolve102, reject) => {
21390
21451
  const pendingMap = this._browserConnected ? this.browserPending : this.pending;
21391
21452
  const id = this._browserConnected ? this.browserMsgId++ : this.msgId++;
21392
- pendingMap.set(id, { resolve: resolve92, reject });
21453
+ pendingMap.set(id, { resolve: resolve102, reject });
21393
21454
  ws.send(JSON.stringify({ id, sessionId, method, params }));
21394
21455
  setTimeout(() => {
21395
21456
  if (pendingMap.has(id)) {
@@ -21932,6 +21993,7 @@ var ExtensionProviderInstance = class {
21932
21993
  activeModal = null;
21933
21994
  currentModel = "";
21934
21995
  currentMode = "";
21996
+ controlValues = {};
21935
21997
  lastAgentStatus = "idle";
21936
21998
  generatingStartedAt = 0;
21937
21999
  monitor;
@@ -21977,6 +22039,8 @@ var ExtensionProviderInstance = class {
21977
22039
  } : null,
21978
22040
  currentModel: this.currentModel || void 0,
21979
22041
  currentPlan: this.currentMode || void 0,
22042
+ controlValues: this.controlValues,
22043
+ providerControls: this.provider.controls,
21980
22044
  agentStreams: this.agentStreams,
21981
22045
  instanceId: this.instanceId,
21982
22046
  lastUpdated: Date.now(),
@@ -21991,6 +22055,7 @@ var ExtensionProviderInstance = class {
21991
22055
  if (data?.activeModal !== void 0) this.activeModal = data.activeModal;
21992
22056
  if (data?.model) this.currentModel = data.model;
21993
22057
  if (data?.mode) this.currentMode = data.mode;
22058
+ if (data?.controlValues) this.controlValues = data.controlValues;
21994
22059
  if (typeof data?.sessionId === "string" && data.sessionId.trim()) this.chatId = data.sessionId;
21995
22060
  if (typeof data?.title === "string" && data.title.trim()) this.chatTitle = data.title;
21996
22061
  if (typeof data?.agentName === "string" && data.agentName.trim()) this.agentName = data.agentName;
@@ -22080,7 +22145,7 @@ var ExtensionProviderInstance = class {
22080
22145
  return title || this.agentName || this.provider.name;
22081
22146
  }
22082
22147
  };
22083
- var HISTORY_DIR = path4.join(os5.homedir(), ".adhdev", "history");
22148
+ var HISTORY_DIR = path5.join(os5.homedir(), ".adhdev", "history");
22084
22149
  var RETAIN_DAYS = 30;
22085
22150
  var ChatHistoryWriter = class {
22086
22151
  /** Last seen message count per agent (deduplication) */
@@ -22123,11 +22188,11 @@ var ChatHistoryWriter = class {
22123
22188
  });
22124
22189
  }
22125
22190
  if (newMessages.length === 0) return;
22126
- const dir = path4.join(HISTORY_DIR, this.sanitize(agentType));
22191
+ const dir = path5.join(HISTORY_DIR, this.sanitize(agentType));
22127
22192
  fs3.mkdirSync(dir, { recursive: true });
22128
22193
  const date5 = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
22129
22194
  const filePrefix = instanceId ? `${this.sanitize(instanceId)}_` : "";
22130
- const filePath = path4.join(dir, `${filePrefix}${date5}.jsonl`);
22195
+ const filePath = path5.join(dir, `${filePrefix}${date5}.jsonl`);
22131
22196
  const lines = newMessages.map((m) => JSON.stringify(m)).join("\n") + "\n";
22132
22197
  fs3.appendFileSync(filePath, lines, "utf-8");
22133
22198
  const prevCount = this.lastSeenCounts.get(dedupKey) || 0;
@@ -22171,11 +22236,11 @@ ${next}`;
22171
22236
  this.lastSeenTerminal.set(dedupKey, next);
22172
22237
  return;
22173
22238
  }
22174
- const dir = path4.join(HISTORY_DIR, this.sanitize(agentType));
22239
+ const dir = path5.join(HISTORY_DIR, this.sanitize(agentType));
22175
22240
  fs3.mkdirSync(dir, { recursive: true });
22176
22241
  const date5 = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
22177
22242
  const filePrefix = instanceId ? `${this.sanitize(instanceId)}_` : "";
22178
- const filePath = path4.join(dir, `${filePrefix}${date5}.terminal.log`);
22243
+ const filePath = path5.join(dir, `${filePrefix}${date5}.terminal.log`);
22179
22244
  fs3.appendFileSync(filePath, delta, "utf-8");
22180
22245
  this.lastSeenTerminal.set(dedupKey, next);
22181
22246
  if (!this.rotated) {
@@ -22199,10 +22264,10 @@ ${next}`;
22199
22264
  const cutoff = Date.now() - RETAIN_DAYS * 24 * 60 * 60 * 1e3;
22200
22265
  const agentDirs = fs3.readdirSync(HISTORY_DIR, { withFileTypes: true }).filter((d) => d.isDirectory());
22201
22266
  for (const dir of agentDirs) {
22202
- const dirPath = path4.join(HISTORY_DIR, dir.name);
22267
+ const dirPath = path5.join(HISTORY_DIR, dir.name);
22203
22268
  const files = fs3.readdirSync(dirPath).filter((f) => f.endsWith(".jsonl") || f.endsWith(".terminal.log"));
22204
22269
  for (const file2 of files) {
22205
- const filePath = path4.join(dirPath, file2);
22270
+ const filePath = path5.join(dirPath, file2);
22206
22271
  const stat4 = fs3.statSync(filePath);
22207
22272
  if (stat4.mtimeMs < cutoff) {
22208
22273
  fs3.unlinkSync(filePath);
@@ -22220,7 +22285,7 @@ ${next}`;
22220
22285
  function readChatHistory(agentType, offset = 0, limit = 30, instanceId) {
22221
22286
  try {
22222
22287
  const sanitized = agentType.replace(/[^a-zA-Z0-9_-]/g, "_");
22223
- const dir = path4.join(HISTORY_DIR, sanitized);
22288
+ const dir = path5.join(HISTORY_DIR, sanitized);
22224
22289
  if (!fs3.existsSync(dir)) return { messages: [], hasMore: false };
22225
22290
  const sanitizedInstance = instanceId?.replace(/[^a-zA-Z0-9_-]/g, "_");
22226
22291
  const files = fs3.readdirSync(dir).filter((f) => {
@@ -22234,7 +22299,7 @@ function readChatHistory(agentType, offset = 0, limit = 30, instanceId) {
22234
22299
  const needed = offset + limit + 1;
22235
22300
  for (const file2 of files) {
22236
22301
  if (allMessages.length >= needed) break;
22237
- const filePath = path4.join(dir, file2);
22302
+ const filePath = path5.join(dir, file2);
22238
22303
  const content = fs3.readFileSync(filePath, "utf-8");
22239
22304
  const lines = content.trim().split("\n").filter(Boolean);
22240
22305
  for (let i = lines.length - 1; i >= 0; i--) {
@@ -22341,6 +22406,8 @@ var IdeProviderInstance = class {
22341
22406
  currentModel: this.cachedChat?.model || void 0,
22342
22407
  currentPlan: this.cachedChat?.mode || void 0,
22343
22408
  currentAutoApprove: this.cachedChat?.autoApprove || void 0,
22409
+ controlValues: this.cachedChat?.controlValues || void 0,
22410
+ providerControls: this.provider.controls,
22344
22411
  instanceId: this.instanceId,
22345
22412
  lastUpdated: Date.now(),
22346
22413
  settings: this.settings,
@@ -22899,6 +22966,50 @@ function isCdpConnected(cdpManagers, key) {
22899
22966
  const m = findCdpManager(cdpManagers, key);
22900
22967
  return m?.isConnected ?? false;
22901
22968
  }
22969
+ function buildFallbackControls(providerControls, serverModel, serverMode, acpConfigOptions, acpModes) {
22970
+ if (providerControls && providerControls.length > 0) return providerControls;
22971
+ const controls = [];
22972
+ const isAcp = !!(acpConfigOptions || acpModes);
22973
+ const modelFromAcp = acpConfigOptions?.find((c) => c.category === "model");
22974
+ if (!isAcp || modelFromAcp) {
22975
+ controls.push({
22976
+ id: "model",
22977
+ type: "select",
22978
+ label: "Model",
22979
+ icon: "\u{1F916}",
22980
+ placement: "bar",
22981
+ dynamic: !modelFromAcp,
22982
+ listScript: "listModels",
22983
+ setScript: "setModel",
22984
+ readFrom: "model",
22985
+ ...modelFromAcp && {
22986
+ options: modelFromAcp.options.map((o) => ({ value: o.value, label: o.name || o.value }))
22987
+ }
22988
+ });
22989
+ }
22990
+ const modeFromAcp = acpModes && acpModes.length > 0;
22991
+ const thoughtFromAcp = !modeFromAcp && acpConfigOptions?.find((c) => c.category !== "model");
22992
+ if (!isAcp || modeFromAcp || thoughtFromAcp) {
22993
+ controls.push({
22994
+ id: "mode",
22995
+ type: thoughtFromAcp ? "cycle" : "select",
22996
+ label: thoughtFromAcp ? "Thinking" : "Mode",
22997
+ icon: thoughtFromAcp ? "\u{1F9E0}" : "\u26A1",
22998
+ placement: "bar",
22999
+ dynamic: !modeFromAcp && !thoughtFromAcp,
23000
+ listScript: "listModes",
23001
+ setScript: thoughtFromAcp ? "setThinkingLevel" : "setMode",
23002
+ readFrom: "mode",
23003
+ ...modeFromAcp && {
23004
+ options: acpModes.map((m) => ({ value: m.id, label: m.name || m.id }))
23005
+ },
23006
+ ...thoughtFromAcp && {
23007
+ options: thoughtFromAcp.options.map((o) => ({ value: o.value, label: o.name || o.value }))
23008
+ }
23009
+ });
23010
+ }
23011
+ return controls;
23012
+ }
22902
23013
  var IDE_SESSION_CAPABILITIES = [
22903
23014
  "read_chat",
22904
23015
  "send_message",
@@ -22957,8 +23068,15 @@ function buildIdeWorkspaceSession(state, cdpManagers) {
22957
23068
  currentModel: state.currentModel,
22958
23069
  currentPlan: state.currentPlan,
22959
23070
  currentAutoApprove: state.currentAutoApprove,
23071
+ controlValues: state.controlValues,
23072
+ providerControls: buildFallbackControls(
23073
+ state.providerControls,
23074
+ state.currentModel,
23075
+ state.currentPlan
23076
+ ),
22960
23077
  errorMessage: state.errorMessage,
22961
- errorReason: state.errorReason
23078
+ errorReason: state.errorReason,
23079
+ lastUpdated: state.lastUpdated
22962
23080
  };
22963
23081
  }
22964
23082
  function buildExtensionAgentSession(parent, ext) {
@@ -22979,8 +23097,15 @@ function buildExtensionAgentSession(parent, ext) {
22979
23097
  capabilities: EXTENSION_SESSION_CAPABILITIES,
22980
23098
  currentModel: ext.currentModel,
22981
23099
  currentPlan: ext.currentPlan,
23100
+ controlValues: ext.controlValues,
23101
+ providerControls: buildFallbackControls(
23102
+ ext.providerControls,
23103
+ ext.currentModel,
23104
+ ext.currentPlan
23105
+ ),
22982
23106
  errorMessage: ext.errorMessage,
22983
- errorReason: ext.errorReason
23107
+ errorReason: ext.errorReason,
23108
+ lastUpdated: ext.lastUpdated
22984
23109
  };
22985
23110
  }
22986
23111
  function buildCliSession(state) {
@@ -23005,8 +23130,13 @@ function buildCliSession(state) {
23005
23130
  resume: state.resume,
23006
23131
  activeChat,
23007
23132
  capabilities: PTY_SESSION_CAPABILITIES,
23133
+ controlValues: state.controlValues,
23134
+ providerControls: buildFallbackControls(
23135
+ state.providerControls
23136
+ ),
23008
23137
  errorMessage: state.errorMessage,
23009
- errorReason: state.errorReason
23138
+ errorReason: state.errorReason,
23139
+ lastUpdated: state.lastUpdated
23010
23140
  };
23011
23141
  }
23012
23142
  function buildAcpSession(state) {
@@ -23029,8 +23159,17 @@ function buildAcpSession(state) {
23029
23159
  currentPlan: state.currentPlan,
23030
23160
  acpConfigOptions: state.acpConfigOptions,
23031
23161
  acpModes: state.acpModes,
23162
+ controlValues: state.controlValues,
23163
+ providerControls: buildFallbackControls(
23164
+ state.providerControls,
23165
+ state.currentModel,
23166
+ state.currentPlan,
23167
+ state.acpConfigOptions,
23168
+ state.acpModes
23169
+ ),
23032
23170
  errorMessage: state.errorMessage,
23033
- errorReason: state.errorReason
23171
+ errorReason: state.errorReason,
23172
+ lastUpdated: state.lastUpdated
23034
23173
  };
23035
23174
  }
23036
23175
  function buildSessionEntries(allStates, cdpManagers) {
@@ -24101,11 +24240,11 @@ function resolveSafePath(requestedPath) {
24101
24240
  const home = os6.homedir();
24102
24241
  let resolved;
24103
24242
  if (requestedPath.startsWith("~")) {
24104
- resolved = path5.join(home, requestedPath.slice(1));
24105
- } else if (path5.isAbsolute(requestedPath)) {
24243
+ resolved = path6.join(home, requestedPath.slice(1));
24244
+ } else if (path6.isAbsolute(requestedPath)) {
24106
24245
  resolved = requestedPath;
24107
24246
  } else {
24108
- resolved = path5.resolve(requestedPath);
24247
+ resolved = path6.resolve(requestedPath);
24109
24248
  }
24110
24249
  return resolved;
24111
24250
  }
@@ -24121,7 +24260,7 @@ async function handleFileRead(h, args) {
24121
24260
  async function handleFileWrite(h, args) {
24122
24261
  try {
24123
24262
  const filePath = resolveSafePath(args?.path);
24124
- fs4.mkdirSync(path5.dirname(filePath), { recursive: true });
24263
+ fs4.mkdirSync(path6.dirname(filePath), { recursive: true });
24125
24264
  fs4.writeFileSync(filePath, args?.content || "", "utf-8");
24126
24265
  return { success: true, path: filePath };
24127
24266
  } catch (e) {
@@ -24135,7 +24274,7 @@ async function handleFileList(h, args) {
24135
24274
  const files = entries.map((e) => ({
24136
24275
  name: e.name,
24137
24276
  type: e.isDirectory() ? "directory" : "file",
24138
- size: e.isFile() ? fs4.statSync(path5.join(dirPath, e.name)).size : void 0
24277
+ size: e.isFile() ? fs4.statSync(path6.join(dirPath, e.name)).size : void 0
24139
24278
  }));
24140
24279
  return { success: true, files, path: dirPath };
24141
24280
  } catch (e) {
@@ -24353,9 +24492,10 @@ function handleWorkspaceList() {
24353
24492
  function handleWorkspaceAdd(args) {
24354
24493
  const rawPath = (args?.path || args?.dir || "").trim();
24355
24494
  const label = (args?.label || "").trim() || void 0;
24495
+ const createIfMissing = args?.createIfMissing === true;
24356
24496
  if (!rawPath) return { success: false, error: "path required" };
24357
24497
  const config2 = loadConfig();
24358
- const result = addWorkspaceEntry(config2, rawPath, label);
24498
+ const result = addWorkspaceEntry(config2, rawPath, label, { createIfMissing });
24359
24499
  if ("error" in result) return { success: false, error: result.error };
24360
24500
  let cfg = appendWorkspaceActivity(result.config, result.entry.path, {});
24361
24501
  saveConfig(cfg);
@@ -24847,7 +24987,7 @@ var DaemonCommandHandler = class {
24847
24987
  try {
24848
24988
  const http3 = await import("http");
24849
24989
  const postData = JSON.stringify(body);
24850
- const result = await new Promise((resolve92, reject) => {
24990
+ const result = await new Promise((resolve102, reject) => {
24851
24991
  const req = http3.request({
24852
24992
  hostname: "127.0.0.1",
24853
24993
  port: 19280,
@@ -24859,9 +24999,9 @@ var DaemonCommandHandler = class {
24859
24999
  res.on("data", (chunk) => data += chunk);
24860
25000
  res.on("end", () => {
24861
25001
  try {
24862
- resolve92(JSON.parse(data));
25002
+ resolve102(JSON.parse(data));
24863
25003
  } catch {
24864
- resolve92({ raw: data });
25004
+ resolve102({ raw: data });
24865
25005
  }
24866
25006
  });
24867
25007
  });
@@ -24879,15 +25019,15 @@ var DaemonCommandHandler = class {
24879
25019
  if (!providerType) return { success: false, error: "providerType required" };
24880
25020
  try {
24881
25021
  const http3 = await import("http");
24882
- const result = await new Promise((resolve92, reject) => {
25022
+ const result = await new Promise((resolve102, reject) => {
24883
25023
  http3.get(`http://127.0.0.1:19280/api/providers/${providerType}/${endpoint}`, (res) => {
24884
25024
  let data = "";
24885
25025
  res.on("data", (chunk) => data += chunk);
24886
25026
  res.on("end", () => {
24887
25027
  try {
24888
- resolve92(JSON.parse(data));
25028
+ resolve102(JSON.parse(data));
24889
25029
  } catch {
24890
- resolve92({ raw: data });
25030
+ resolve102({ raw: data });
24891
25031
  }
24892
25032
  });
24893
25033
  }).on("error", reject);
@@ -24901,7 +25041,7 @@ var DaemonCommandHandler = class {
24901
25041
  try {
24902
25042
  const http3 = await import("http");
24903
25043
  const postData = JSON.stringify(args || {});
24904
- const result = await new Promise((resolve92, reject) => {
25044
+ const result = await new Promise((resolve102, reject) => {
24905
25045
  const req = http3.request({
24906
25046
  hostname: "127.0.0.1",
24907
25047
  port: 19280,
@@ -24913,9 +25053,9 @@ var DaemonCommandHandler = class {
24913
25053
  res.on("data", (chunk) => data += chunk);
24914
25054
  res.on("end", () => {
24915
25055
  try {
24916
- resolve92(JSON.parse(data));
25056
+ resolve102(JSON.parse(data));
24917
25057
  } catch {
24918
- resolve92({ raw: data });
25058
+ resolve102({ raw: data });
24919
25059
  }
24920
25060
  });
24921
25061
  });
@@ -24947,12 +25087,12 @@ var ProviderLoader = class _ProviderLoader {
24947
25087
  static META_FILE = ".meta.json";
24948
25088
  constructor(options) {
24949
25089
  this.logFn = options?.logFn || LOG.forComponent("Provider").asLogFn();
24950
- const defaultProvidersDir = path6.join(os7.homedir(), ".adhdev", "providers");
25090
+ const defaultProvidersDir = path7.join(os7.homedir(), ".adhdev", "providers");
24951
25091
  if (options?.userDir) {
24952
25092
  this.userDir = options.userDir;
24953
25093
  this.log(`Config 'providerDir' applied: ${this.userDir}`);
24954
25094
  } else {
24955
- const localRepoPath = path6.resolve(__dirname, "../../../../../adhdev-providers");
25095
+ const localRepoPath = path7.resolve(__dirname, "../../../../../adhdev-providers");
24956
25096
  if (fs5.existsSync(localRepoPath)) {
24957
25097
  this.userDir = localRepoPath;
24958
25098
  this.log(`Auto-detected local public repository: ${this.userDir} (Dev workspace speedup)`);
@@ -24961,7 +25101,7 @@ var ProviderLoader = class _ProviderLoader {
24961
25101
  this.log(`Using default user providers directory: ${this.userDir}`);
24962
25102
  }
24963
25103
  }
24964
- this.upstreamDir = path6.join(defaultProvidersDir, ".upstream");
25104
+ this.upstreamDir = path7.join(defaultProvidersDir, ".upstream");
24965
25105
  this.disableUpstream = options?.disableUpstream ?? false;
24966
25106
  }
24967
25107
  log(msg) {
@@ -24991,7 +25131,7 @@ var ProviderLoader = class _ProviderLoader {
24991
25131
  * Canonical provider directory shape for a given root.
24992
25132
  */
24993
25133
  getProviderDir(root, category, type) {
24994
- return path6.join(root, category, type);
25134
+ return path7.join(root, category, type);
24995
25135
  }
24996
25136
  /**
24997
25137
  * Canonical user override directory for a provider.
@@ -25018,7 +25158,7 @@ var ProviderLoader = class _ProviderLoader {
25018
25158
  resolveProviderFile(type, ...segments) {
25019
25159
  const dir = this.findProviderDirInternal(type);
25020
25160
  if (!dir) return null;
25021
- return path6.join(dir, ...segments);
25161
+ return path7.join(dir, ...segments);
25022
25162
  }
25023
25163
  /**
25024
25164
  * Load all providers (3-tier priority)
@@ -25056,7 +25196,7 @@ var ProviderLoader = class _ProviderLoader {
25056
25196
  if (!fs5.existsSync(this.upstreamDir)) return false;
25057
25197
  try {
25058
25198
  return fs5.readdirSync(this.upstreamDir).some(
25059
- (d) => fs5.statSync(path6.join(this.upstreamDir, d)).isDirectory()
25199
+ (d) => fs5.statSync(path7.join(this.upstreamDir, d)).isDirectory()
25060
25200
  );
25061
25201
  } catch {
25062
25202
  return false;
@@ -25348,14 +25488,14 @@ var ProviderLoader = class _ProviderLoader {
25348
25488
  this.log(` [loadScriptsFromDir] ${type}: providerDir not found`);
25349
25489
  return null;
25350
25490
  }
25351
- const dir = path6.join(providerDir, scriptDir);
25491
+ const dir = path7.join(providerDir, scriptDir);
25352
25492
  if (!fs5.existsSync(dir)) {
25353
25493
  this.log(` [loadScriptsFromDir] ${type}: dir not found: ${dir}`);
25354
25494
  return null;
25355
25495
  }
25356
25496
  const cached2 = this.scriptsCache.get(dir);
25357
25497
  if (cached2) return cached2;
25358
- const scriptsJs = path6.join(dir, "scripts.js");
25498
+ const scriptsJs = path7.join(dir, "scripts.js");
25359
25499
  if (fs5.existsSync(scriptsJs)) {
25360
25500
  try {
25361
25501
  delete __require.cache[__require.resolve(scriptsJs)];
@@ -25394,7 +25534,7 @@ var ProviderLoader = class _ProviderLoader {
25394
25534
  });
25395
25535
  const handleChange = (filePath) => {
25396
25536
  if (filePath.endsWith(".js") || filePath.endsWith(".json")) {
25397
- this.log(`File changed: ${path6.basename(filePath)}, reloading...`);
25537
+ this.log(`File changed: ${path7.basename(filePath)}, reloading...`);
25398
25538
  this.reload();
25399
25539
  }
25400
25540
  };
@@ -25449,7 +25589,7 @@ var ProviderLoader = class _ProviderLoader {
25449
25589
  }
25450
25590
  const https = __require("https");
25451
25591
  const { execSync: execSync7 } = __require("child_process");
25452
- const metaPath = path6.join(this.upstreamDir, _ProviderLoader.META_FILE);
25592
+ const metaPath = path7.join(this.upstreamDir, _ProviderLoader.META_FILE);
25453
25593
  let prevEtag = "";
25454
25594
  let prevTimestamp = 0;
25455
25595
  try {
@@ -25466,7 +25606,7 @@ var ProviderLoader = class _ProviderLoader {
25466
25606
  return { updated: false };
25467
25607
  }
25468
25608
  try {
25469
- const etag = await new Promise((resolve92, reject) => {
25609
+ const etag = await new Promise((resolve102, reject) => {
25470
25610
  const options = {
25471
25611
  method: "HEAD",
25472
25612
  hostname: "github.com",
@@ -25484,7 +25624,7 @@ var ProviderLoader = class _ProviderLoader {
25484
25624
  headers: { "User-Agent": "adhdev-launcher" },
25485
25625
  timeout: 1e4
25486
25626
  }, (res2) => {
25487
- resolve92(res2.headers.etag || res2.headers["last-modified"] || "");
25627
+ resolve102(res2.headers.etag || res2.headers["last-modified"] || "");
25488
25628
  });
25489
25629
  req2.on("error", reject);
25490
25630
  req2.on("timeout", () => {
@@ -25493,7 +25633,7 @@ var ProviderLoader = class _ProviderLoader {
25493
25633
  });
25494
25634
  req2.end();
25495
25635
  } else {
25496
- resolve92(res.headers.etag || res.headers["last-modified"] || "");
25636
+ resolve102(res.headers.etag || res.headers["last-modified"] || "");
25497
25637
  }
25498
25638
  });
25499
25639
  req.on("error", reject);
@@ -25509,17 +25649,17 @@ var ProviderLoader = class _ProviderLoader {
25509
25649
  return { updated: false };
25510
25650
  }
25511
25651
  this.log("Downloading latest providers from GitHub...");
25512
- const tmpTar = path6.join(os7.tmpdir(), `adhdev-providers-${Date.now()}.tar.gz`);
25513
- const tmpExtract = path6.join(os7.tmpdir(), `adhdev-providers-extract-${Date.now()}`);
25652
+ const tmpTar = path7.join(os7.tmpdir(), `adhdev-providers-${Date.now()}.tar.gz`);
25653
+ const tmpExtract = path7.join(os7.tmpdir(), `adhdev-providers-extract-${Date.now()}`);
25514
25654
  await this.downloadFile(_ProviderLoader.GITHUB_TARBALL_URL, tmpTar);
25515
25655
  fs5.mkdirSync(tmpExtract, { recursive: true });
25516
25656
  execSync7(`tar -xzf "${tmpTar}" -C "${tmpExtract}"`, { timeout: 3e4 });
25517
25657
  const extracted = fs5.readdirSync(tmpExtract);
25518
25658
  const rootDir = extracted.find(
25519
- (d) => fs5.statSync(path6.join(tmpExtract, d)).isDirectory() && d.startsWith("adhdev-providers")
25659
+ (d) => fs5.statSync(path7.join(tmpExtract, d)).isDirectory() && d.startsWith("adhdev-providers")
25520
25660
  );
25521
25661
  if (!rootDir) throw new Error("Unexpected tarball structure");
25522
- const sourceDir = path6.join(tmpExtract, rootDir);
25662
+ const sourceDir = path7.join(tmpExtract, rootDir);
25523
25663
  const backupDir = this.upstreamDir + ".bak";
25524
25664
  if (fs5.existsSync(this.upstreamDir)) {
25525
25665
  if (fs5.existsSync(backupDir)) fs5.rmSync(backupDir, { recursive: true, force: true });
@@ -25557,7 +25697,7 @@ var ProviderLoader = class _ProviderLoader {
25557
25697
  downloadFile(url2, destPath) {
25558
25698
  const https = __require("https");
25559
25699
  const http3 = __require("http");
25560
- return new Promise((resolve92, reject) => {
25700
+ return new Promise((resolve102, reject) => {
25561
25701
  const doRequest = (reqUrl, redirectCount = 0) => {
25562
25702
  if (redirectCount > 5) {
25563
25703
  reject(new Error("Too many redirects"));
@@ -25577,7 +25717,7 @@ var ProviderLoader = class _ProviderLoader {
25577
25717
  res.pipe(ws);
25578
25718
  ws.on("finish", () => {
25579
25719
  ws.close();
25580
- resolve92();
25720
+ resolve102();
25581
25721
  });
25582
25722
  ws.on("error", reject);
25583
25723
  });
@@ -25594,8 +25734,8 @@ var ProviderLoader = class _ProviderLoader {
25594
25734
  copyDirRecursive(src, dest) {
25595
25735
  fs5.mkdirSync(dest, { recursive: true });
25596
25736
  for (const entry of fs5.readdirSync(src, { withFileTypes: true })) {
25597
- const srcPath = path6.join(src, entry.name);
25598
- const destPath = path6.join(dest, entry.name);
25737
+ const srcPath = path7.join(src, entry.name);
25738
+ const destPath = path7.join(dest, entry.name);
25599
25739
  if (entry.isDirectory()) {
25600
25740
  this.copyDirRecursive(srcPath, destPath);
25601
25741
  } else {
@@ -25606,7 +25746,7 @@ var ProviderLoader = class _ProviderLoader {
25606
25746
  /** .meta.json save */
25607
25747
  writeMeta(metaPath, etag, timestamp) {
25608
25748
  try {
25609
- fs5.mkdirSync(path6.dirname(metaPath), { recursive: true });
25749
+ fs5.mkdirSync(path7.dirname(metaPath), { recursive: true });
25610
25750
  fs5.writeFileSync(metaPath, JSON.stringify({
25611
25751
  etag,
25612
25752
  timestamp,
@@ -25623,7 +25763,7 @@ var ProviderLoader = class _ProviderLoader {
25623
25763
  const scan = (d) => {
25624
25764
  try {
25625
25765
  for (const entry of fs5.readdirSync(d, { withFileTypes: true })) {
25626
- if (entry.isDirectory()) scan(path6.join(d, entry.name));
25766
+ if (entry.isDirectory()) scan(path7.join(d, entry.name));
25627
25767
  else if (entry.name === "provider.json") count++;
25628
25768
  }
25629
25769
  } catch {
@@ -25722,17 +25862,17 @@ var ProviderLoader = class _ProviderLoader {
25722
25862
  for (const root of searchRoots) {
25723
25863
  if (!fs5.existsSync(root)) continue;
25724
25864
  const candidate = this.getProviderDir(root, cat, type);
25725
- if (fs5.existsSync(path6.join(candidate, "provider.json"))) return candidate;
25726
- const catDir = path6.join(root, cat);
25865
+ if (fs5.existsSync(path7.join(candidate, "provider.json"))) return candidate;
25866
+ const catDir = path7.join(root, cat);
25727
25867
  if (fs5.existsSync(catDir)) {
25728
25868
  try {
25729
25869
  for (const entry of fs5.readdirSync(catDir, { withFileTypes: true })) {
25730
25870
  if (!entry.isDirectory()) continue;
25731
- const jsonPath = path6.join(catDir, entry.name, "provider.json");
25871
+ const jsonPath = path7.join(catDir, entry.name, "provider.json");
25732
25872
  if (fs5.existsSync(jsonPath)) {
25733
25873
  try {
25734
25874
  const data = JSON.parse(fs5.readFileSync(jsonPath, "utf-8"));
25735
- if (data.type === type) return path6.join(catDir, entry.name);
25875
+ if (data.type === type) return path7.join(catDir, entry.name);
25736
25876
  } catch {
25737
25877
  }
25738
25878
  }
@@ -25749,7 +25889,7 @@ var ProviderLoader = class _ProviderLoader {
25749
25889
  * (template substitution is NOT applied here — scripts.js handles that)
25750
25890
  */
25751
25891
  buildScriptWrappersFromDir(dir) {
25752
- const scriptsJs = path6.join(dir, "scripts.js");
25892
+ const scriptsJs = path7.join(dir, "scripts.js");
25753
25893
  if (fs5.existsSync(scriptsJs)) {
25754
25894
  try {
25755
25895
  delete __require.cache[__require.resolve(scriptsJs)];
@@ -25763,7 +25903,7 @@ var ProviderLoader = class _ProviderLoader {
25763
25903
  for (const file2 of fs5.readdirSync(dir)) {
25764
25904
  if (!file2.endsWith(".js")) continue;
25765
25905
  const scriptName = toCamel(file2.replace(".js", ""));
25766
- const filePath = path6.join(dir, file2);
25906
+ const filePath = path7.join(dir, file2);
25767
25907
  result[scriptName] = (...args) => {
25768
25908
  try {
25769
25909
  let content = fs5.readFileSync(filePath, "utf-8");
@@ -25823,7 +25963,7 @@ var ProviderLoader = class _ProviderLoader {
25823
25963
  }
25824
25964
  const hasJson = entries.some((e) => e.name === "provider.json");
25825
25965
  if (hasJson) {
25826
- const jsonPath = path6.join(d, "provider.json");
25966
+ const jsonPath = path7.join(d, "provider.json");
25827
25967
  try {
25828
25968
  const raw = fs5.readFileSync(jsonPath, "utf-8");
25829
25969
  const mod = JSON.parse(raw);
@@ -25836,7 +25976,7 @@ var ProviderLoader = class _ProviderLoader {
25836
25976
  delete mod.extensionIdPattern_flags;
25837
25977
  }
25838
25978
  const hasCompatibility = Array.isArray(mod.compatibility);
25839
- const scriptsPath = path6.join(d, "scripts.js");
25979
+ const scriptsPath = path7.join(d, "scripts.js");
25840
25980
  if (!hasCompatibility && fs5.existsSync(scriptsPath)) {
25841
25981
  try {
25842
25982
  delete __require.cache[__require.resolve(scriptsPath)];
@@ -25862,7 +26002,7 @@ var ProviderLoader = class _ProviderLoader {
25862
26002
  if (!entry.isDirectory()) continue;
25863
26003
  if (entry.name.startsWith("_") || entry.name.startsWith(".")) continue;
25864
26004
  if (excludeDirs && d === dir && excludeDirs.includes(entry.name)) continue;
25865
- scan(path6.join(d, entry.name));
26005
+ scan(path7.join(d, entry.name));
25866
26006
  }
25867
26007
  }
25868
26008
  };
@@ -25940,17 +26080,17 @@ async function findFreePort(ports) {
25940
26080
  throw new Error("No free port found");
25941
26081
  }
25942
26082
  function checkPortFree(port) {
25943
- return new Promise((resolve92) => {
26083
+ return new Promise((resolve102) => {
25944
26084
  const server = net2.createServer();
25945
26085
  server.unref();
25946
- server.on("error", () => resolve92(false));
26086
+ server.on("error", () => resolve102(false));
25947
26087
  server.listen(port, "127.0.0.1", () => {
25948
- server.close(() => resolve92(true));
26088
+ server.close(() => resolve102(true));
25949
26089
  });
25950
26090
  });
25951
26091
  }
25952
26092
  async function isCdpActive(port) {
25953
- return new Promise((resolve92) => {
26093
+ return new Promise((resolve102) => {
25954
26094
  const req = __require("http").get(`http://127.0.0.1:${port}/json/version`, {
25955
26095
  timeout: 2e3
25956
26096
  }, (res) => {
@@ -25959,16 +26099,16 @@ async function isCdpActive(port) {
25959
26099
  res.on("end", () => {
25960
26100
  try {
25961
26101
  const info = JSON.parse(data);
25962
- resolve92(!!info["WebKit-Version"] || !!info["Browser"]);
26102
+ resolve102(!!info["WebKit-Version"] || !!info["Browser"]);
25963
26103
  } catch {
25964
- resolve92(false);
26104
+ resolve102(false);
25965
26105
  }
25966
26106
  });
25967
26107
  });
25968
- req.on("error", () => resolve92(false));
26108
+ req.on("error", () => resolve102(false));
25969
26109
  req.on("timeout", () => {
25970
26110
  req.destroy();
25971
- resolve92(false);
26111
+ resolve102(false);
25972
26112
  });
25973
26113
  });
25974
26114
  }
@@ -26087,8 +26227,8 @@ function detectCurrentWorkspace(ideId) {
26087
26227
  const appNameMap = getMacAppIdentifiers();
26088
26228
  const appName = appNameMap[ideId];
26089
26229
  if (appName) {
26090
- const storagePath = path7.join(
26091
- process.env.APPDATA || path7.join(os8.homedir(), "AppData", "Roaming"),
26230
+ const storagePath = path8.join(
26231
+ process.env.APPDATA || path8.join(os8.homedir(), "AppData", "Roaming"),
26092
26232
  appName,
26093
26233
  "storage.json"
26094
26234
  );
@@ -26255,7 +26395,7 @@ init_config();
26255
26395
  init_workspaces();
26256
26396
  init_config();
26257
26397
  init_logger();
26258
- var LOG_DIR2 = process.platform === "win32" ? path8.join(process.env.LOCALAPPDATA || process.env.APPDATA || path8.join(os9.homedir(), "AppData", "Local"), "adhdev", "logs") : process.platform === "darwin" ? path8.join(os9.homedir(), "Library", "Logs", "adhdev") : path8.join(os9.homedir(), ".local", "share", "adhdev", "logs");
26398
+ var LOG_DIR2 = process.platform === "win32" ? path9.join(process.env.LOCALAPPDATA || process.env.APPDATA || path9.join(os9.homedir(), "AppData", "Local"), "adhdev", "logs") : process.platform === "darwin" ? path9.join(os9.homedir(), "Library", "Logs", "adhdev") : path9.join(os9.homedir(), ".local", "share", "adhdev", "logs");
26259
26399
  var MAX_FILE_SIZE = 5 * 1024 * 1024;
26260
26400
  var MAX_DAYS = 7;
26261
26401
  try {
@@ -26293,13 +26433,13 @@ function getDateStr2() {
26293
26433
  return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
26294
26434
  }
26295
26435
  var currentDate2 = getDateStr2();
26296
- var currentFile = path8.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
26436
+ var currentFile = path9.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
26297
26437
  var writeCount2 = 0;
26298
26438
  function checkRotation() {
26299
26439
  const today = getDateStr2();
26300
26440
  if (today !== currentDate2) {
26301
26441
  currentDate2 = today;
26302
- currentFile = path8.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
26442
+ currentFile = path9.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
26303
26443
  cleanOldFiles();
26304
26444
  }
26305
26445
  }
@@ -26313,7 +26453,7 @@ function cleanOldFiles() {
26313
26453
  const dateMatch = file2.match(/commands-(\d{4}-\d{2}-\d{2})/);
26314
26454
  if (dateMatch && dateMatch[1] < cutoffStr) {
26315
26455
  try {
26316
- fs6.unlinkSync(path8.join(LOG_DIR2, file2));
26456
+ fs6.unlinkSync(path9.join(LOG_DIR2, file2));
26317
26457
  } catch {
26318
26458
  }
26319
26459
  }
@@ -26514,9 +26654,27 @@ var DaemonCommandRouter = class {
26514
26654
  this.deps.onIdeConnected?.();
26515
26655
  if (result.success && resolvedWorkspace) {
26516
26656
  try {
26517
- saveConfig(appendWorkspaceActivity(loadConfig(), resolvedWorkspace, {
26657
+ let next = appendWorkspaceActivity(loadConfig(), resolvedWorkspace, {
26518
26658
  kind: "ide",
26519
26659
  agentType: result.ideId
26660
+ });
26661
+ next = appendRecentActivity(next, {
26662
+ kind: "ide",
26663
+ providerType: result.ideId || ideKey,
26664
+ providerName: result.ideId || ideKey,
26665
+ workspace: resolvedWorkspace,
26666
+ title: result.ideId || ideKey
26667
+ });
26668
+ saveConfig(next);
26669
+ } catch {
26670
+ }
26671
+ } else if (result.success && (result.ideId || ideKey)) {
26672
+ try {
26673
+ saveConfig(appendRecentActivity(loadConfig(), {
26674
+ kind: "ide",
26675
+ providerType: result.ideId || ideKey,
26676
+ providerName: result.ideId || ideKey,
26677
+ title: result.ideId || ideKey
26520
26678
  }));
26521
26679
  } catch {
26522
26680
  }
@@ -26536,6 +26694,30 @@ var DaemonCommandRouter = class {
26536
26694
  updateConfig({ userName: name });
26537
26695
  return { success: true, userName: name };
26538
26696
  }
26697
+ case "mark_recent_seen": {
26698
+ const kind = args?.kind;
26699
+ const providerType = args?.providerType;
26700
+ if (!kind || !providerType) {
26701
+ return { success: false, error: "kind and providerType are required" };
26702
+ }
26703
+ const recentKey = args?.recentKey || buildRecentActivityKey({
26704
+ kind,
26705
+ providerType,
26706
+ workspace: args?.workspace || null
26707
+ });
26708
+ const next = markRecentSessionSeen(
26709
+ loadConfig(),
26710
+ recentKey,
26711
+ typeof args?.seenAt === "number" ? args.seenAt : Date.now()
26712
+ );
26713
+ saveConfig(next);
26714
+ this.deps.onStatusChange?.();
26715
+ return {
26716
+ success: true,
26717
+ recentKey,
26718
+ seenAt: next.recentSessionReads?.[recentKey] || Date.now()
26719
+ };
26720
+ }
26539
26721
  // ─── Daemon Self-Upgrade ───
26540
26722
  case "daemon_upgrade": {
26541
26723
  LOG.info("Upgrade", "Remote upgrade requested from dashboard");
@@ -26554,9 +26736,9 @@ var DaemonCommandRouter = class {
26554
26736
  setTimeout(() => {
26555
26737
  LOG.info("Upgrade", "Restarting daemon with new version...");
26556
26738
  try {
26557
- const path152 = __require("path");
26739
+ const path162 = __require("path");
26558
26740
  const fs122 = __require("fs");
26559
- const pidFile = path152.join(process.env.HOME || process.env.USERPROFILE || "", ".adhdev", "daemon.pid");
26741
+ const pidFile = path162.join(process.env.HOME || process.env.USERPROFILE || "", ".adhdev", "daemon.pid");
26560
26742
  if (fs122.existsSync(pidFile)) fs122.unlinkSync(pidFile);
26561
26743
  } catch {
26562
26744
  }
@@ -26650,6 +26832,7 @@ var DaemonCommandRouter = class {
26650
26832
  init_logger();
26651
26833
  init_config();
26652
26834
  init_workspaces();
26835
+ init_terminal_screen();
26653
26836
  function buildDetectedIdeInfos(detectedIdes, cdpManagers) {
26654
26837
  return detectedIdes.filter((ide) => ide.installed !== false).map((ide) => ({
26655
26838
  id: ide.id,
@@ -26668,14 +26851,127 @@ function buildAvailableProviders(providerLoader) {
26668
26851
  category: provider.category
26669
26852
  }));
26670
26853
  }
26854
+ function parseMessageTime(value) {
26855
+ if (typeof value === "number" && Number.isFinite(value)) return value;
26856
+ if (typeof value === "string") {
26857
+ const parsed = Date.parse(value);
26858
+ if (Number.isFinite(parsed)) return parsed;
26859
+ }
26860
+ return 0;
26861
+ }
26862
+ function getSessionMessageUpdatedAt(session) {
26863
+ const lastMessage = session.activeChat?.messages?.at?.(-1);
26864
+ if (!lastMessage) return 0;
26865
+ return parseMessageTime(lastMessage.timestamp) || parseMessageTime(lastMessage.receivedAt) || parseMessageTime(lastMessage.createdAt) || 0;
26866
+ }
26867
+ function getSessionLastUsedAt(session) {
26868
+ return getSessionMessageUpdatedAt(session) || session.lastUpdated || Date.now();
26869
+ }
26870
+ function getSessionKind(session) {
26871
+ return session.transport === "cdp-page" || session.transport === "cdp-webview" ? "ide" : session.transport === "acp" ? "acp" : "cli";
26872
+ }
26873
+ function getLastMessageRole(session) {
26874
+ const role = session.activeChat?.messages?.at?.(-1)?.role;
26875
+ return typeof role === "string" ? role : "";
26876
+ }
26877
+ function getUnreadState(hasContentChange, status, lastUsedAt, lastSeenAt, lastRole) {
26878
+ if (status === "waiting_approval") {
26879
+ return { unread: false, inboxBucket: "needs_attention" };
26880
+ }
26881
+ if (status === "generating" || status === "starting") {
26882
+ return { unread: false, inboxBucket: "working" };
26883
+ }
26884
+ const unread = hasContentChange && lastUsedAt > lastSeenAt && lastRole !== "user" && lastRole !== "human";
26885
+ return { unread, inboxBucket: unread ? "task_complete" : "idle" };
26886
+ }
26887
+ function buildRecentSessions(sessions, recentActivity, readState) {
26888
+ const live = sessions.filter((session) => !session.parentId && session.status !== "stopped").map((session) => {
26889
+ const kind = getSessionKind(session);
26890
+ const recentKey = buildRecentActivityKey({
26891
+ kind,
26892
+ providerType: session.providerType,
26893
+ workspace: session.workspace
26894
+ });
26895
+ const lastSeenAt = readState[recentKey] || 0;
26896
+ const lastUsedAt = getSessionLastUsedAt(session);
26897
+ const { unread, inboxBucket } = getUnreadState(
26898
+ getSessionMessageUpdatedAt(session) > 0,
26899
+ session.status,
26900
+ lastUsedAt,
26901
+ lastSeenAt,
26902
+ getLastMessageRole(session)
26903
+ );
26904
+ return {
26905
+ id: session.id,
26906
+ recentKey,
26907
+ sessionId: session.id,
26908
+ providerType: session.providerType,
26909
+ providerName: session.providerName,
26910
+ kind,
26911
+ title: session.activeChat?.title || session.title || session.providerName,
26912
+ workspace: session.workspace,
26913
+ currentModel: session.currentModel,
26914
+ status: session.status,
26915
+ lastUsedAt,
26916
+ unread,
26917
+ lastSeenAt,
26918
+ inboxBucket
26919
+ };
26920
+ });
26921
+ const seen = new Set(live.map((item) => `${item.kind}:${item.providerType}:${item.workspace || ""}`));
26922
+ const persisted = recentActivity.filter((item) => !seen.has(`${item.kind}:${item.providerType}:${item.workspace || ""}`)).map((item) => {
26923
+ const lastSeenAt = readState[item.id] || 0;
26924
+ const unread = item.lastUsedAt > lastSeenAt;
26925
+ return {
26926
+ id: item.id,
26927
+ recentKey: item.id,
26928
+ sessionId: item.sessionId || null,
26929
+ providerType: item.providerType,
26930
+ providerName: item.providerName,
26931
+ kind: item.kind,
26932
+ title: item.title || item.providerName,
26933
+ workspace: item.workspace,
26934
+ currentModel: item.currentModel,
26935
+ lastUsedAt: item.lastUsedAt,
26936
+ unread,
26937
+ lastSeenAt,
26938
+ inboxBucket: unread ? "task_complete" : "idle"
26939
+ };
26940
+ });
26941
+ return [...live, ...persisted].sort((a, b) => b.lastUsedAt - a.lastUsedAt).slice(0, 12);
26942
+ }
26671
26943
  function buildStatusSnapshot(options) {
26672
26944
  const cfg = loadConfig();
26673
26945
  const wsState = getWorkspaceState(cfg);
26674
26946
  const memSnap = getHostMemorySnapshot();
26947
+ const recentActivity = getRecentActivity(cfg, 20);
26675
26948
  const sessions = buildSessionEntries(
26676
26949
  options.allStates,
26677
26950
  options.cdpManagers
26678
26951
  );
26952
+ const readState = cfg.recentSessionReads || {};
26953
+ for (const session of sessions) {
26954
+ const kind = getSessionKind(session);
26955
+ const recentKey = buildRecentActivityKey({
26956
+ kind,
26957
+ providerType: session.providerType,
26958
+ workspace: session.workspace
26959
+ });
26960
+ const lastSeenAt = getRecentSessionSeenAt(cfg, recentKey);
26961
+ const lastUsedAt = getSessionLastUsedAt(session);
26962
+ const { unread, inboxBucket } = getUnreadState(
26963
+ getSessionMessageUpdatedAt(session) > 0,
26964
+ session.status,
26965
+ lastUsedAt,
26966
+ lastSeenAt,
26967
+ getLastMessageRole(session)
26968
+ );
26969
+ session.recentKey = recentKey;
26970
+ session.lastSeenAt = lastSeenAt;
26971
+ session.unread = unread;
26972
+ session.inboxBucket = inboxBucket;
26973
+ }
26974
+ const terminalBackend = getTerminalBackendRuntimeStatus();
26679
26975
  return {
26680
26976
  instanceId: options.instanceId,
26681
26977
  version: options.version,
@@ -26701,6 +26997,8 @@ function buildStatusSnapshot(options) {
26701
26997
  defaultWorkspaceId: wsState.defaultWorkspaceId,
26702
26998
  defaultWorkspacePath: wsState.defaultWorkspacePath,
26703
26999
  workspaceActivity: getWorkspaceActivity(cfg, 15),
27000
+ recentSessions: buildRecentSessions(sessions, recentActivity, readState),
27001
+ terminalBackend,
26704
27002
  availableProviders: buildAvailableProviders(options.providerLoader)
26705
27003
  };
26706
27004
  }
@@ -26797,7 +27095,10 @@ var CliProviderInstance = class {
26797
27095
  writeOwner: runtime.writeOwner || null,
26798
27096
  attachedClients: runtime.attachedClients || []
26799
27097
  } : void 0,
26800
- resume: this.provider.resume
27098
+ resume: this.provider.resume,
27099
+ controlValues: void 0,
27100
+ // CLI controls not yet wired from stream
27101
+ providerControls: this.provider.controls
26801
27102
  };
26802
27103
  }
26803
27104
  onEvent(event, data) {
@@ -27064,7 +27365,12 @@ var AcpProviderInstance = class {
27064
27365
  acpModes: this.availableModes,
27065
27366
  // Error details for dashboard display
27066
27367
  errorMessage: this.errorMessage || void 0,
27067
- errorReason: this.errorReason || void 0
27368
+ errorReason: this.errorReason || void 0,
27369
+ controlValues: {
27370
+ ...this.currentModel ? { model: this.currentModel } : {},
27371
+ ...this.currentMode ? { mode: this.currentMode } : {}
27372
+ },
27373
+ providerControls: this.provider.controls
27068
27374
  };
27069
27375
  }
27070
27376
  onEvent(event, data) {
@@ -27363,13 +27669,13 @@ var AcpProviderInstance = class {
27363
27669
  }
27364
27670
  this.currentStatus = "waiting_approval";
27365
27671
  this.detectStatusTransition();
27366
- const approved = await new Promise((resolve92) => {
27367
- this.permissionResolvers.push(resolve92);
27672
+ const approved = await new Promise((resolve102) => {
27673
+ this.permissionResolvers.push(resolve102);
27368
27674
  setTimeout(() => {
27369
- const idx = this.permissionResolvers.indexOf(resolve92);
27675
+ const idx = this.permissionResolvers.indexOf(resolve102);
27370
27676
  if (idx >= 0) {
27371
27677
  this.permissionResolvers.splice(idx, 1);
27372
- resolve92(false);
27678
+ resolve102(false);
27373
27679
  }
27374
27680
  }, 3e5);
27375
27681
  });
@@ -27860,6 +28166,13 @@ var DaemonCliManager = class {
27860
28166
  console.error(colorize("red", ` \u2717 Failed to save recent workspace: ${e}`));
27861
28167
  }
27862
28168
  }
28169
+ persistRecentActivity(entry) {
28170
+ try {
28171
+ saveConfig(appendRecentActivity(loadConfig(), entry));
28172
+ } catch (e) {
28173
+ console.error(colorize("red", ` \u2717 Failed to save recent activity: ${e}`));
28174
+ }
28175
+ }
27863
28176
  getTransportFactory(runtimeId, providerType, workspace, cliArgs, attachExisting = false) {
27864
28177
  return this.deps.createPtyTransportFactory?.({
27865
28178
  runtimeId,
@@ -27942,7 +28255,7 @@ var DaemonCliManager = class {
27942
28255
  async startSession(cliType, workingDir, cliArgs, initialModel) {
27943
28256
  const trimmed = (workingDir || "").trim();
27944
28257
  if (!trimmed) throw new Error("working directory required");
27945
- const resolvedDir = trimmed.startsWith("~") ? trimmed.replace(/^~/, os13.homedir()) : path10.resolve(trimmed);
28258
+ const resolvedDir = trimmed.startsWith("~") ? trimmed.replace(/^~/, os13.homedir()) : path11.resolve(trimmed);
27946
28259
  const normalizedType = this.providerLoader.resolveAlias(cliType);
27947
28260
  const provider = this.providerLoader.getByAlias(cliType);
27948
28261
  const key = crypto4.randomUUID();
@@ -28018,6 +28331,15 @@ ${installInfo}`
28018
28331
  } catch (e) {
28019
28332
  LOG.warn("CLI", `ACP history save failed: ${e?.message}`);
28020
28333
  }
28334
+ this.persistRecentActivity({
28335
+ kind: "acp",
28336
+ providerType: normalizedType,
28337
+ providerName: provider.displayName || provider.name || normalizedType,
28338
+ workspace: resolvedDir,
28339
+ currentModel: initialModel,
28340
+ sessionId,
28341
+ title: provider.displayName || provider.name || normalizedType
28342
+ });
28021
28343
  this.deps.onStatusChange();
28022
28344
  return;
28023
28345
  }
@@ -28080,6 +28402,15 @@ ${installInfo}`
28080
28402
  } catch (e) {
28081
28403
  LOG.warn("CLI", `CLI history save failed: ${e?.message}`);
28082
28404
  }
28405
+ this.persistRecentActivity({
28406
+ kind: "cli",
28407
+ providerType: normalizedType,
28408
+ providerName: provider?.displayName || provider?.name || normalizedType,
28409
+ workspace: resolvedDir,
28410
+ currentModel: initialModel,
28411
+ sessionId: key,
28412
+ title: provider?.displayName || provider?.name || normalizedType
28413
+ });
28083
28414
  this.deps.onStatusChange();
28084
28415
  }
28085
28416
  async stopSession(key) {
@@ -28319,11 +28650,24 @@ var ProviderStreamAdapter = class {
28319
28650
  hasScript(name) {
28320
28651
  return typeof this.provider.scripts?.[name] === "function";
28321
28652
  }
28653
+ summarizeRaw(raw) {
28654
+ try {
28655
+ if (typeof raw === "string") return raw.replace(/\s+/g, " ").trim().slice(0, 240);
28656
+ if (raw == null) return String(raw);
28657
+ return JSON.stringify(raw).replace(/\s+/g, " ").trim().slice(0, 240);
28658
+ } catch {
28659
+ return Object.prototype.toString.call(raw);
28660
+ }
28661
+ }
28662
+ isTransportError(reason) {
28663
+ return /Session with given id not found/i.test(reason) || /CDP not connected/i.test(reason) || /Target closed/i.test(reason) || /WebSocket not open/i.test(reason) || /not connected/i.test(reason) || /execution context/i.test(reason) || /Cannot find context with specified id/i.test(reason);
28664
+ }
28322
28665
  async readChat(evaluate) {
28323
28666
  const script = this.callScript("readChat");
28324
28667
  if (!script) return this.errorState("readChat script not available");
28668
+ let raw = null;
28325
28669
  try {
28326
- const raw = await evaluate(script);
28670
+ raw = await evaluate(script);
28327
28671
  const data = typeof raw === "string" ? JSON.parse(raw) : raw;
28328
28672
  if (data?.error) {
28329
28673
  const state2 = this.errorState(data.error);
@@ -28343,12 +28687,31 @@ var ProviderStreamAdapter = class {
28343
28687
  mode: data.mode,
28344
28688
  activeModal: data.activeModal
28345
28689
  };
28690
+ if (this.provider.controls?.length) {
28691
+ const cv = {};
28692
+ for (const ctrl of this.provider.controls) {
28693
+ if (!ctrl.readFrom) continue;
28694
+ const val = data[ctrl.readFrom];
28695
+ if (val !== void 0 && val !== null) {
28696
+ cv[ctrl.id] = typeof val === "object" ? val.name || val.id || String(val) : val;
28697
+ }
28698
+ }
28699
+ if (data.model && !cv["model"]) cv["model"] = data.model;
28700
+ if (data.mode && !cv["mode"]) cv["mode"] = data.mode;
28701
+ if (Object.keys(cv).length > 0) state.controlValues = cv;
28702
+ }
28346
28703
  if (state.messages.length > 0) {
28347
28704
  this.lastSuccessState = state;
28348
28705
  }
28349
28706
  return state;
28350
- } catch {
28351
- const state = this.errorState(`Failed to parse ${this.agentName} state`);
28707
+ } catch (error48) {
28708
+ const reason = error48 instanceof Error ? error48.message : String(error48);
28709
+ if (this.isTransportError(reason)) {
28710
+ throw error48 instanceof Error ? error48 : new Error(reason);
28711
+ }
28712
+ const preview = this.summarizeRaw(raw);
28713
+ const detail = preview ? ` (reason=${reason}; raw=${preview})` : ` (reason=${reason})`;
28714
+ const state = this.errorState(`Failed to parse ${this.agentName} state${detail}`);
28352
28715
  if (this.lastSuccessState?.messages?.length) {
28353
28716
  state.messages = this.lastSuccessState.messages;
28354
28717
  }
@@ -28443,6 +28806,9 @@ var DaemonAgentStreamManager = class {
28443
28806
  getActiveSessionId(parentSessionId) {
28444
28807
  return this.activeSessionIdByParent.get(parentSessionId) || null;
28445
28808
  }
28809
+ isRecoverableSessionError(message) {
28810
+ return message.includes("timeout") || message.includes("not connected") || message.includes("Session") || message.includes("Target closed") || message.includes("execution context") || message.includes("context with specified id");
28811
+ }
28446
28812
  getSessionTarget(sessionId) {
28447
28813
  return this.sessionRegistry?.get(sessionId);
28448
28814
  }
@@ -28544,6 +28910,10 @@ var DaemonAgentStreamManager = class {
28544
28910
  const evaluate = (expr, timeout) => cdp.evaluateInSessionFrame(agent.cdpSessionId, expr, timeout);
28545
28911
  const state = await agent.adapter.readChat(evaluate);
28546
28912
  LOG.debug("AgentStream", `[AgentStream] readChat(${type}) result: status=${state.status} msgs=${state.messages?.length || 0} model=${state.model || ""}${state.status === "error" ? " error=" + JSON.stringify(state.error || state._error || "unknown") : ""}`);
28913
+ const stateError = String(state.error || state._error || "");
28914
+ if (state.status === "error" && this.isRecoverableSessionError(stateError)) {
28915
+ throw new Error(stateError);
28916
+ }
28547
28917
  agent.lastState = state;
28548
28918
  agent.lastError = null;
28549
28919
  if (state.status === "panel_hidden") {
@@ -28554,7 +28924,7 @@ var DaemonAgentStreamManager = class {
28554
28924
  const errorMsg = e?.message || String(e);
28555
28925
  this.logFn(`[AgentStream] readChat(${type}) error: ${errorMsg.slice(0, 200)}`);
28556
28926
  agent.lastError = errorMsg;
28557
- if (errorMsg.includes("timeout") || errorMsg.includes("not connected") || errorMsg.includes("Session")) {
28927
+ if (this.isRecoverableSessionError(errorMsg)) {
28558
28928
  try {
28559
28929
  await cdp.detachAgent(agent.cdpSessionId);
28560
28930
  } catch {
@@ -29033,7 +29403,7 @@ var ProviderInstanceManager = class {
29033
29403
  this.eventListeners = [];
29034
29404
  }
29035
29405
  };
29036
- var ARCHIVE_PATH = path11.join(os14.homedir(), ".adhdev", "version-history.json");
29406
+ var ARCHIVE_PATH = path12.join(os14.homedir(), ".adhdev", "version-history.json");
29037
29407
  var MAX_ENTRIES_PER_PROVIDER = 20;
29038
29408
  var VersionArchive = class {
29039
29409
  history = {};
@@ -29080,7 +29450,7 @@ var VersionArchive = class {
29080
29450
  }
29081
29451
  save() {
29082
29452
  try {
29083
- fs8.mkdirSync(path11.dirname(ARCHIVE_PATH), { recursive: true });
29453
+ fs8.mkdirSync(path12.dirname(ARCHIVE_PATH), { recursive: true });
29084
29454
  fs8.writeFileSync(ARCHIVE_PATH, JSON.stringify(this.history, null, 2));
29085
29455
  } catch {
29086
29456
  }
@@ -29121,7 +29491,7 @@ function checkPathExists2(paths) {
29121
29491
  for (const p of paths) {
29122
29492
  if (p.includes("*")) {
29123
29493
  const home = os14.homedir();
29124
- const resolved = p.replace(/\*/g, home.split(path11.sep).pop() || "");
29494
+ const resolved = p.replace(/\*/g, home.split(path12.sep).pop() || "");
29125
29495
  if (fs8.existsSync(resolved)) return resolved;
29126
29496
  } else {
29127
29497
  if (fs8.existsSync(p)) return p;
@@ -29131,7 +29501,7 @@ function checkPathExists2(paths) {
29131
29501
  }
29132
29502
  function getMacAppVersion(appPath) {
29133
29503
  if ((0, import_os3.platform)() !== "darwin" || !appPath.endsWith(".app")) return null;
29134
- const plistPath = path11.join(appPath, "Contents", "Info.plist");
29504
+ const plistPath = path12.join(appPath, "Contents", "Info.plist");
29135
29505
  if (!fs8.existsSync(plistPath)) return null;
29136
29506
  const raw = runCommand(`/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "${plistPath}"`);
29137
29507
  return raw || null;
@@ -29158,7 +29528,7 @@ async function detectAllVersions(loader, archive) {
29158
29528
  const cliBin = provider.cli ? findBinary2(provider.cli) : null;
29159
29529
  let resolvedBin = cliBin;
29160
29530
  if (!resolvedBin && appPath && currentOs === "darwin") {
29161
- const bundled = path11.join(appPath, "Contents", "Resources", "app", "bin", provider.cli || "");
29531
+ const bundled = path12.join(appPath, "Contents", "Resources", "app", "bin", provider.cli || "");
29162
29532
  if (provider.cli && fs8.existsSync(bundled)) resolvedBin = bundled;
29163
29533
  }
29164
29534
  info.installed = !!(appPath || resolvedBin);
@@ -29701,17 +30071,17 @@ async function handleScriptHints(ctx, type, _req, res) {
29701
30071
  return;
29702
30072
  }
29703
30073
  let scriptsPath = "";
29704
- const directScripts = path12.join(dir, "scripts.js");
30074
+ const directScripts = path13.join(dir, "scripts.js");
29705
30075
  if (fs9.existsSync(directScripts)) {
29706
30076
  scriptsPath = directScripts;
29707
30077
  } else {
29708
- const scriptsDir = path12.join(dir, "scripts");
30078
+ const scriptsDir = path13.join(dir, "scripts");
29709
30079
  if (fs9.existsSync(scriptsDir)) {
29710
30080
  const versions = fs9.readdirSync(scriptsDir).filter((d) => {
29711
- return fs9.statSync(path12.join(scriptsDir, d)).isDirectory();
30081
+ return fs9.statSync(path13.join(scriptsDir, d)).isDirectory();
29712
30082
  }).sort().reverse();
29713
30083
  for (const ver of versions) {
29714
- const p = path12.join(scriptsDir, ver, "scripts.js");
30084
+ const p = path13.join(scriptsDir, ver, "scripts.js");
29715
30085
  if (fs9.existsSync(p)) {
29716
30086
  scriptsPath = p;
29717
30087
  break;
@@ -30779,22 +31149,22 @@ function getLatestScriptVersionDir(scriptsDir) {
30779
31149
  if (!fs10.existsSync(scriptsDir)) return null;
30780
31150
  const versions = fs10.readdirSync(scriptsDir).filter((d) => {
30781
31151
  try {
30782
- return fs10.statSync(path13.join(scriptsDir, d)).isDirectory();
31152
+ return fs10.statSync(path14.join(scriptsDir, d)).isDirectory();
30783
31153
  } catch {
30784
31154
  return false;
30785
31155
  }
30786
31156
  }).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" }));
30787
31157
  if (versions.length === 0) return null;
30788
- return path13.join(scriptsDir, versions[0]);
31158
+ return path14.join(scriptsDir, versions[0]);
30789
31159
  }
30790
31160
  function resolveAutoImplWritableProviderDir(ctx, category, type, requestedDir) {
30791
- const canonicalUserDir = path13.resolve(ctx.providerLoader.getUserProviderDir(category, type));
30792
- const desiredDir = requestedDir ? path13.resolve(requestedDir) : canonicalUserDir;
30793
- const upstreamRoot = path13.resolve(ctx.providerLoader.getUpstreamDir());
30794
- if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path13.sep}`)) {
31161
+ const canonicalUserDir = path14.resolve(ctx.providerLoader.getUserProviderDir(category, type));
31162
+ const desiredDir = requestedDir ? path14.resolve(requestedDir) : canonicalUserDir;
31163
+ const upstreamRoot = path14.resolve(ctx.providerLoader.getUpstreamDir());
31164
+ if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path14.sep}`)) {
30795
31165
  return { dir: null, reason: `Refusing to write into upstream provider directory: ${desiredDir}` };
30796
31166
  }
30797
- if (path13.basename(desiredDir) !== type) {
31167
+ if (path14.basename(desiredDir) !== type) {
30798
31168
  return { dir: null, reason: `Requested writable provider directory must end with '${type}': ${desiredDir}` };
30799
31169
  }
30800
31170
  const sourceDir = ctx.findProviderDir(type);
@@ -30802,11 +31172,11 @@ function resolveAutoImplWritableProviderDir(ctx, category, type, requestedDir) {
30802
31172
  return { dir: null, reason: `Provider source directory not found for '${type}'` };
30803
31173
  }
30804
31174
  if (!fs10.existsSync(desiredDir)) {
30805
- fs10.mkdirSync(path13.dirname(desiredDir), { recursive: true });
31175
+ fs10.mkdirSync(path14.dirname(desiredDir), { recursive: true });
30806
31176
  fs10.cpSync(sourceDir, desiredDir, { recursive: true });
30807
31177
  ctx.log(`Auto-implement writable copy created: ${desiredDir}`);
30808
31178
  }
30809
- const providerJson = path13.join(desiredDir, "provider.json");
31179
+ const providerJson = path14.join(desiredDir, "provider.json");
30810
31180
  if (!fs10.existsSync(providerJson)) {
30811
31181
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
30812
31182
  }
@@ -30829,13 +31199,13 @@ function loadAutoImplReferenceScripts(ctx, referenceType) {
30829
31199
  const refDir = ctx.findProviderDir(referenceType);
30830
31200
  if (!refDir || !fs10.existsSync(refDir)) return {};
30831
31201
  const referenceScripts = {};
30832
- const scriptsDir = path13.join(refDir, "scripts");
31202
+ const scriptsDir = path14.join(refDir, "scripts");
30833
31203
  const latestDir = getLatestScriptVersionDir(scriptsDir);
30834
31204
  if (!latestDir) return referenceScripts;
30835
31205
  for (const file2 of fs10.readdirSync(latestDir)) {
30836
31206
  if (!file2.endsWith(".js")) continue;
30837
31207
  try {
30838
- referenceScripts[file2] = fs10.readFileSync(path13.join(latestDir, file2), "utf-8");
31208
+ referenceScripts[file2] = fs10.readFileSync(path14.join(latestDir, file2), "utf-8");
30839
31209
  } catch {
30840
31210
  }
30841
31211
  }
@@ -30886,9 +31256,9 @@ async function handleAutoImplement(ctx, type, req, res) {
30886
31256
  });
30887
31257
  const referenceScripts = loadAutoImplReferenceScripts(ctx, resolvedReference);
30888
31258
  const prompt = buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domContext, referenceScripts, comment, resolvedReference);
30889
- const tmpDir = path13.join(os15.tmpdir(), "adhdev-autoimpl");
31259
+ const tmpDir = path14.join(os15.tmpdir(), "adhdev-autoimpl");
30890
31260
  if (!fs10.existsSync(tmpDir)) fs10.mkdirSync(tmpDir, { recursive: true });
30891
- const promptFile = path13.join(tmpDir, `prompt-${type}-${Date.now()}.md`);
31261
+ const promptFile = path14.join(tmpDir, `prompt-${type}-${Date.now()}.md`);
30892
31262
  fs10.writeFileSync(promptFile, prompt, "utf-8");
30893
31263
  ctx.log(`Auto-implement prompt written to ${promptFile} (${prompt.length} chars)`);
30894
31264
  const agentProvider = ctx.providerLoader.resolve(agent) || ctx.providerLoader.getMeta(agent);
@@ -31259,7 +31629,7 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
31259
31629
  setMode: "set_mode.js"
31260
31630
  };
31261
31631
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
31262
- const scriptsDir = path13.join(providerDir, "scripts");
31632
+ const scriptsDir = path14.join(providerDir, "scripts");
31263
31633
  const latestScriptsDir = getLatestScriptVersionDir(scriptsDir);
31264
31634
  if (latestScriptsDir) {
31265
31635
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -31270,7 +31640,7 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
31270
31640
  for (const file2 of fs10.readdirSync(latestScriptsDir)) {
31271
31641
  if (file2.endsWith(".js") && targetFileNames.has(file2)) {
31272
31642
  try {
31273
- const content = fs10.readFileSync(path13.join(latestScriptsDir, file2), "utf-8");
31643
+ const content = fs10.readFileSync(path14.join(latestScriptsDir, file2), "utf-8");
31274
31644
  lines.push(`### \`${file2}\` \u270F\uFE0F EDIT`);
31275
31645
  lines.push("```javascript");
31276
31646
  lines.push(content);
@@ -31287,7 +31657,7 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
31287
31657
  lines.push("");
31288
31658
  for (const file2 of refFiles) {
31289
31659
  try {
31290
- const content = fs10.readFileSync(path13.join(latestScriptsDir, file2), "utf-8");
31660
+ const content = fs10.readFileSync(path14.join(latestScriptsDir, file2), "utf-8");
31291
31661
  lines.push(`### \`${file2}\` \u{1F512}`);
31292
31662
  lines.push("```javascript");
31293
31663
  lines.push(content);
@@ -31328,10 +31698,10 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
31328
31698
  lines.push("");
31329
31699
  }
31330
31700
  }
31331
- const docsDir = path13.join(providerDir, "../../docs");
31701
+ const docsDir = path14.join(providerDir, "../../docs");
31332
31702
  const loadGuide = (name) => {
31333
31703
  try {
31334
- const p = path13.join(docsDir, name);
31704
+ const p = path14.join(docsDir, name);
31335
31705
  if (fs10.existsSync(p)) return fs10.readFileSync(p, "utf-8");
31336
31706
  } catch {
31337
31707
  }
@@ -31505,7 +31875,7 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
31505
31875
  parseApproval: "parse_approval.js"
31506
31876
  };
31507
31877
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
31508
- const scriptsDir = path13.join(providerDir, "scripts");
31878
+ const scriptsDir = path14.join(providerDir, "scripts");
31509
31879
  const latestScriptsDir = getLatestScriptVersionDir(scriptsDir);
31510
31880
  if (latestScriptsDir) {
31511
31881
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -31517,7 +31887,7 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
31517
31887
  if (!file2.endsWith(".js")) continue;
31518
31888
  if (!targetFileNames.has(file2)) continue;
31519
31889
  try {
31520
- const content = fs10.readFileSync(path13.join(latestScriptsDir, file2), "utf-8");
31890
+ const content = fs10.readFileSync(path14.join(latestScriptsDir, file2), "utf-8");
31521
31891
  lines.push(`### \`${file2}\` \u270F\uFE0F EDIT`);
31522
31892
  lines.push("```javascript");
31523
31893
  lines.push(content);
@@ -31533,7 +31903,7 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
31533
31903
  lines.push("");
31534
31904
  for (const file2 of refFiles) {
31535
31905
  try {
31536
- const content = fs10.readFileSync(path13.join(latestScriptsDir, file2), "utf-8");
31906
+ const content = fs10.readFileSync(path14.join(latestScriptsDir, file2), "utf-8");
31537
31907
  lines.push(`### \`${file2}\` \u{1F512}`);
31538
31908
  lines.push("```javascript");
31539
31909
  lines.push(content);
@@ -31566,10 +31936,10 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
31566
31936
  lines.push("");
31567
31937
  }
31568
31938
  }
31569
- const docsDir = path13.join(providerDir, "../../docs");
31939
+ const docsDir = path14.join(providerDir, "../../docs");
31570
31940
  const loadGuide = (name) => {
31571
31941
  try {
31572
- const p = path13.join(docsDir, name);
31942
+ const p = path14.join(docsDir, name);
31573
31943
  if (fs10.existsSync(p)) return fs10.readFileSync(p, "utf-8");
31574
31944
  } catch {
31575
31945
  }
@@ -31825,8 +32195,8 @@ var DevServer = class _DevServer {
31825
32195
  }
31826
32196
  getEndpointList() {
31827
32197
  return this.routes.map((r) => {
31828
- const path152 = typeof r.pattern === "string" ? r.pattern : r.pattern.source.replace(/\\\//g, "/").replace(/\(\[.*?\]\+\)/g, ":type").replace(/[\^$]/g, "");
31829
- return `${r.method.padEnd(5)} ${path152}`;
32198
+ const path162 = typeof r.pattern === "string" ? r.pattern : r.pattern.source.replace(/\\\//g, "/").replace(/\(\[.*?\]\+\)/g, ":type").replace(/[\^$]/g, "");
32199
+ return `${r.method.padEnd(5)} ${path162}`;
31830
32200
  });
31831
32201
  }
31832
32202
  async start(port = DEV_SERVER_PORT) {
@@ -31857,15 +32227,15 @@ var DevServer = class _DevServer {
31857
32227
  this.json(res, 500, { error: e.message });
31858
32228
  }
31859
32229
  });
31860
- return new Promise((resolve92, reject) => {
32230
+ return new Promise((resolve102, reject) => {
31861
32231
  this.server.listen(port, "127.0.0.1", () => {
31862
32232
  this.log(`Dev server listening on http://127.0.0.1:${port}`);
31863
- resolve92();
32233
+ resolve102();
31864
32234
  });
31865
32235
  this.server.on("error", (e) => {
31866
32236
  if (e.code === "EADDRINUSE") {
31867
32237
  this.log(`Port ${port} in use, skipping dev server`);
31868
- resolve92();
32238
+ resolve102();
31869
32239
  } else {
31870
32240
  reject(e);
31871
32241
  }
@@ -31948,20 +32318,20 @@ var DevServer = class _DevServer {
31948
32318
  child.stderr?.on("data", (d) => {
31949
32319
  stderr += d.toString().slice(0, 2e3);
31950
32320
  });
31951
- await new Promise((resolve92) => {
32321
+ await new Promise((resolve102) => {
31952
32322
  const timer = setTimeout(() => {
31953
32323
  child.kill();
31954
- resolve92();
32324
+ resolve102();
31955
32325
  }, 3e3);
31956
32326
  child.on("exit", () => {
31957
32327
  clearTimeout(timer);
31958
- resolve92();
32328
+ resolve102();
31959
32329
  });
31960
32330
  child.stdout?.once("data", () => {
31961
32331
  setTimeout(() => {
31962
32332
  child.kill();
31963
32333
  clearTimeout(timer);
31964
- resolve92();
32334
+ resolve102();
31965
32335
  }, 500);
31966
32336
  });
31967
32337
  });
@@ -32108,12 +32478,12 @@ var DevServer = class _DevServer {
32108
32478
  // ─── DevConsole SPA ───
32109
32479
  getConsoleDistDir() {
32110
32480
  const candidates = [
32111
- path14.resolve(__dirname, "../../web-devconsole/dist"),
32112
- path14.resolve(__dirname, "../../../web-devconsole/dist"),
32113
- path14.join(process.cwd(), "packages/web-devconsole/dist")
32481
+ path15.resolve(__dirname, "../../web-devconsole/dist"),
32482
+ path15.resolve(__dirname, "../../../web-devconsole/dist"),
32483
+ path15.join(process.cwd(), "packages/web-devconsole/dist")
32114
32484
  ];
32115
32485
  for (const dir of candidates) {
32116
- if (fs11.existsSync(path14.join(dir, "index.html"))) return dir;
32486
+ if (fs11.existsSync(path15.join(dir, "index.html"))) return dir;
32117
32487
  }
32118
32488
  return null;
32119
32489
  }
@@ -32123,7 +32493,7 @@ var DevServer = class _DevServer {
32123
32493
  this.json(res, 500, { error: "DevConsole not found. Run: npm run build -w packages/web-devconsole" });
32124
32494
  return;
32125
32495
  }
32126
- const htmlPath = path14.join(distDir, "index.html");
32496
+ const htmlPath = path15.join(distDir, "index.html");
32127
32497
  try {
32128
32498
  const html = fs11.readFileSync(htmlPath, "utf-8");
32129
32499
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
@@ -32148,15 +32518,15 @@ var DevServer = class _DevServer {
32148
32518
  this.json(res, 404, { error: "Not found" });
32149
32519
  return;
32150
32520
  }
32151
- const safePath = path14.normalize(pathname).replace(/^\.\.\//, "");
32152
- const filePath = path14.join(distDir, safePath);
32521
+ const safePath = path15.normalize(pathname).replace(/^\.\.\//, "");
32522
+ const filePath = path15.join(distDir, safePath);
32153
32523
  if (!filePath.startsWith(distDir)) {
32154
32524
  this.json(res, 403, { error: "Forbidden" });
32155
32525
  return;
32156
32526
  }
32157
32527
  try {
32158
32528
  const content = fs11.readFileSync(filePath);
32159
- const ext = path14.extname(filePath);
32529
+ const ext = path15.extname(filePath);
32160
32530
  const contentType = _DevServer.MIME_MAP[ext] || "application/octet-stream";
32161
32531
  res.writeHead(200, { "Content-Type": contentType, "Cache-Control": "public, max-age=31536000, immutable" });
32162
32532
  res.end(content);
@@ -32269,9 +32639,9 @@ var DevServer = class _DevServer {
32269
32639
  const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
32270
32640
  if (entry.isDirectory()) {
32271
32641
  files.push({ path: rel, size: 0, type: "dir" });
32272
- scan(path14.join(d, entry.name), rel);
32642
+ scan(path15.join(d, entry.name), rel);
32273
32643
  } else {
32274
- const stat4 = fs11.statSync(path14.join(d, entry.name));
32644
+ const stat4 = fs11.statSync(path15.join(d, entry.name));
32275
32645
  files.push({ path: rel, size: stat4.size, type: "file" });
32276
32646
  }
32277
32647
  }
@@ -32294,7 +32664,7 @@ var DevServer = class _DevServer {
32294
32664
  this.json(res, 404, { error: `Provider directory not found: ${type}` });
32295
32665
  return;
32296
32666
  }
32297
- const fullPath = path14.resolve(dir, path14.normalize(filePath));
32667
+ const fullPath = path15.resolve(dir, path15.normalize(filePath));
32298
32668
  if (!fullPath.startsWith(dir)) {
32299
32669
  this.json(res, 403, { error: "Forbidden" });
32300
32670
  return;
@@ -32319,14 +32689,14 @@ var DevServer = class _DevServer {
32319
32689
  this.json(res, 404, { error: `Provider directory not found: ${type}` });
32320
32690
  return;
32321
32691
  }
32322
- const fullPath = path14.resolve(dir, path14.normalize(filePath));
32692
+ const fullPath = path15.resolve(dir, path15.normalize(filePath));
32323
32693
  if (!fullPath.startsWith(dir)) {
32324
32694
  this.json(res, 403, { error: "Forbidden" });
32325
32695
  return;
32326
32696
  }
32327
32697
  try {
32328
32698
  if (fs11.existsSync(fullPath)) fs11.copyFileSync(fullPath, fullPath + ".bak");
32329
- fs11.mkdirSync(path14.dirname(fullPath), { recursive: true });
32699
+ fs11.mkdirSync(path15.dirname(fullPath), { recursive: true });
32330
32700
  fs11.writeFileSync(fullPath, content, "utf-8");
32331
32701
  this.log(`File saved: ${fullPath} (${content.length} chars)`);
32332
32702
  this.providerLoader.reload();
@@ -32343,7 +32713,7 @@ var DevServer = class _DevServer {
32343
32713
  return;
32344
32714
  }
32345
32715
  for (const name of ["scripts.js", "provider.json"]) {
32346
- const p = path14.join(dir, name);
32716
+ const p = path15.join(dir, name);
32347
32717
  if (fs11.existsSync(p)) {
32348
32718
  const source = fs11.readFileSync(p, "utf-8");
32349
32719
  this.json(res, 200, { type, path: p, source, lines: source.split("\n").length });
@@ -32364,8 +32734,8 @@ var DevServer = class _DevServer {
32364
32734
  this.json(res, 404, { error: `Provider not found: ${type}` });
32365
32735
  return;
32366
32736
  }
32367
- const target = fs11.existsSync(path14.join(dir, "scripts.js")) ? "scripts.js" : "provider.json";
32368
- const targetPath = path14.join(dir, target);
32737
+ const target = fs11.existsSync(path15.join(dir, "scripts.js")) ? "scripts.js" : "provider.json";
32738
+ const targetPath = path15.join(dir, target);
32369
32739
  try {
32370
32740
  if (fs11.existsSync(targetPath)) fs11.copyFileSync(targetPath, targetPath + ".bak");
32371
32741
  fs11.writeFileSync(targetPath, source, "utf-8");
@@ -32470,14 +32840,14 @@ var DevServer = class _DevServer {
32470
32840
  child.stderr?.on("data", (d) => {
32471
32841
  stderr += d.toString();
32472
32842
  });
32473
- await new Promise((resolve92) => {
32843
+ await new Promise((resolve102) => {
32474
32844
  const timer = setTimeout(() => {
32475
32845
  child.kill();
32476
- resolve92();
32846
+ resolve102();
32477
32847
  }, timeout);
32478
32848
  child.on("exit", () => {
32479
32849
  clearTimeout(timer);
32480
- resolve92();
32850
+ resolve102();
32481
32851
  });
32482
32852
  });
32483
32853
  const elapsed = Date.now() - start;
@@ -32525,7 +32895,7 @@ var DevServer = class _DevServer {
32525
32895
  }
32526
32896
  let targetDir;
32527
32897
  targetDir = this.providerLoader.getUserProviderDir(category, type);
32528
- const jsonPath = path14.join(targetDir, "provider.json");
32898
+ const jsonPath = path15.join(targetDir, "provider.json");
32529
32899
  if (fs11.existsSync(jsonPath)) {
32530
32900
  this.json(res, 409, { error: `Provider already exists at ${targetDir}`, path: targetDir });
32531
32901
  return;
@@ -32537,8 +32907,8 @@ var DevServer = class _DevServer {
32537
32907
  const createdFiles = ["provider.json"];
32538
32908
  if (result.files) {
32539
32909
  for (const [relPath, content] of Object.entries(result.files)) {
32540
- const fullPath = path14.join(targetDir, relPath);
32541
- fs11.mkdirSync(path14.dirname(fullPath), { recursive: true });
32910
+ const fullPath = path15.join(targetDir, relPath);
32911
+ fs11.mkdirSync(path15.dirname(fullPath), { recursive: true });
32542
32912
  fs11.writeFileSync(fullPath, content, "utf-8");
32543
32913
  createdFiles.push(relPath);
32544
32914
  }
@@ -32591,22 +32961,22 @@ var DevServer = class _DevServer {
32591
32961
  if (!fs11.existsSync(scriptsDir)) return null;
32592
32962
  const versions = fs11.readdirSync(scriptsDir).filter((d) => {
32593
32963
  try {
32594
- return fs11.statSync(path14.join(scriptsDir, d)).isDirectory();
32964
+ return fs11.statSync(path15.join(scriptsDir, d)).isDirectory();
32595
32965
  } catch {
32596
32966
  return false;
32597
32967
  }
32598
32968
  }).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" }));
32599
32969
  if (versions.length === 0) return null;
32600
- return path14.join(scriptsDir, versions[0]);
32970
+ return path15.join(scriptsDir, versions[0]);
32601
32971
  }
32602
32972
  resolveAutoImplWritableProviderDir(category, type, requestedDir) {
32603
- const canonicalUserDir = path14.resolve(this.providerLoader.getUserProviderDir(category, type));
32604
- const desiredDir = requestedDir ? path14.resolve(requestedDir) : canonicalUserDir;
32605
- const upstreamRoot = path14.resolve(this.providerLoader.getUpstreamDir());
32606
- if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path14.sep}`)) {
32973
+ const canonicalUserDir = path15.resolve(this.providerLoader.getUserProviderDir(category, type));
32974
+ const desiredDir = requestedDir ? path15.resolve(requestedDir) : canonicalUserDir;
32975
+ const upstreamRoot = path15.resolve(this.providerLoader.getUpstreamDir());
32976
+ if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path15.sep}`)) {
32607
32977
  return { dir: null, reason: `Refusing to write into upstream provider directory: ${desiredDir}` };
32608
32978
  }
32609
- if (path14.basename(desiredDir) !== type) {
32979
+ if (path15.basename(desiredDir) !== type) {
32610
32980
  return { dir: null, reason: `Requested writable provider directory must end with '${type}': ${desiredDir}` };
32611
32981
  }
32612
32982
  const sourceDir = this.findProviderDir(type);
@@ -32614,11 +32984,11 @@ var DevServer = class _DevServer {
32614
32984
  return { dir: null, reason: `Provider source directory not found for '${type}'` };
32615
32985
  }
32616
32986
  if (!fs11.existsSync(desiredDir)) {
32617
- fs11.mkdirSync(path14.dirname(desiredDir), { recursive: true });
32987
+ fs11.mkdirSync(path15.dirname(desiredDir), { recursive: true });
32618
32988
  fs11.cpSync(sourceDir, desiredDir, { recursive: true });
32619
32989
  this.log(`Auto-implement writable copy created: ${desiredDir}`);
32620
32990
  }
32621
- const providerJson = path14.join(desiredDir, "provider.json");
32991
+ const providerJson = path15.join(desiredDir, "provider.json");
32622
32992
  if (!fs11.existsSync(providerJson)) {
32623
32993
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
32624
32994
  }
@@ -32666,7 +33036,7 @@ var DevServer = class _DevServer {
32666
33036
  setMode: "set_mode.js"
32667
33037
  };
32668
33038
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
32669
- const scriptsDir = path14.join(providerDir, "scripts");
33039
+ const scriptsDir = path15.join(providerDir, "scripts");
32670
33040
  const latestScriptsDir = this.getLatestScriptVersionDir(scriptsDir);
32671
33041
  if (latestScriptsDir) {
32672
33042
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -32677,7 +33047,7 @@ var DevServer = class _DevServer {
32677
33047
  for (const file2 of fs11.readdirSync(latestScriptsDir)) {
32678
33048
  if (file2.endsWith(".js") && targetFileNames.has(file2)) {
32679
33049
  try {
32680
- const content = fs11.readFileSync(path14.join(latestScriptsDir, file2), "utf-8");
33050
+ const content = fs11.readFileSync(path15.join(latestScriptsDir, file2), "utf-8");
32681
33051
  lines.push(`### \`${file2}\` \u270F\uFE0F EDIT`);
32682
33052
  lines.push("```javascript");
32683
33053
  lines.push(content);
@@ -32694,7 +33064,7 @@ var DevServer = class _DevServer {
32694
33064
  lines.push("");
32695
33065
  for (const file2 of refFiles) {
32696
33066
  try {
32697
- const content = fs11.readFileSync(path14.join(latestScriptsDir, file2), "utf-8");
33067
+ const content = fs11.readFileSync(path15.join(latestScriptsDir, file2), "utf-8");
32698
33068
  lines.push(`### \`${file2}\` \u{1F512}`);
32699
33069
  lines.push("```javascript");
32700
33070
  lines.push(content);
@@ -32735,10 +33105,10 @@ var DevServer = class _DevServer {
32735
33105
  lines.push("");
32736
33106
  }
32737
33107
  }
32738
- const docsDir = path14.join(providerDir, "../../docs");
33108
+ const docsDir = path15.join(providerDir, "../../docs");
32739
33109
  const loadGuide = (name) => {
32740
33110
  try {
32741
- const p = path14.join(docsDir, name);
33111
+ const p = path15.join(docsDir, name);
32742
33112
  if (fs11.existsSync(p)) return fs11.readFileSync(p, "utf-8");
32743
33113
  } catch {
32744
33114
  }
@@ -32912,7 +33282,7 @@ var DevServer = class _DevServer {
32912
33282
  parseApproval: "parse_approval.js"
32913
33283
  };
32914
33284
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
32915
- const scriptsDir = path14.join(providerDir, "scripts");
33285
+ const scriptsDir = path15.join(providerDir, "scripts");
32916
33286
  const latestScriptsDir = this.getLatestScriptVersionDir(scriptsDir);
32917
33287
  if (latestScriptsDir) {
32918
33288
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -32924,7 +33294,7 @@ var DevServer = class _DevServer {
32924
33294
  if (!file2.endsWith(".js")) continue;
32925
33295
  if (!targetFileNames.has(file2)) continue;
32926
33296
  try {
32927
- const content = fs11.readFileSync(path14.join(latestScriptsDir, file2), "utf-8");
33297
+ const content = fs11.readFileSync(path15.join(latestScriptsDir, file2), "utf-8");
32928
33298
  lines.push(`### \`${file2}\` \u270F\uFE0F EDIT`);
32929
33299
  lines.push("```javascript");
32930
33300
  lines.push(content);
@@ -32940,7 +33310,7 @@ var DevServer = class _DevServer {
32940
33310
  lines.push("");
32941
33311
  for (const file2 of refFiles) {
32942
33312
  try {
32943
- const content = fs11.readFileSync(path14.join(latestScriptsDir, file2), "utf-8");
33313
+ const content = fs11.readFileSync(path15.join(latestScriptsDir, file2), "utf-8");
32944
33314
  lines.push(`### \`${file2}\` \u{1F512}`);
32945
33315
  lines.push("```javascript");
32946
33316
  lines.push(content);
@@ -32973,10 +33343,10 @@ var DevServer = class _DevServer {
32973
33343
  lines.push("");
32974
33344
  }
32975
33345
  }
32976
- const docsDir = path14.join(providerDir, "../../docs");
33346
+ const docsDir = path15.join(providerDir, "../../docs");
32977
33347
  const loadGuide = (name) => {
32978
33348
  try {
32979
- const p = path14.join(docsDir, name);
33349
+ const p = path15.join(docsDir, name);
32980
33350
  if (fs11.existsSync(p)) return fs11.readFileSync(p, "utf-8");
32981
33351
  } catch {
32982
33352
  }
@@ -33133,14 +33503,14 @@ data: ${JSON.stringify(msg.data)}
33133
33503
  res.end(JSON.stringify(data, null, 2));
33134
33504
  }
33135
33505
  async readBody(req) {
33136
- return new Promise((resolve92) => {
33506
+ return new Promise((resolve102) => {
33137
33507
  let body = "";
33138
33508
  req.on("data", (chunk) => body += chunk);
33139
33509
  req.on("end", () => {
33140
33510
  try {
33141
- resolve92(JSON.parse(body));
33511
+ resolve102(JSON.parse(body));
33142
33512
  } catch {
33143
- resolve92({});
33513
+ resolve102({});
33144
33514
  }
33145
33515
  });
33146
33516
  });
@@ -33549,7 +33919,7 @@ async function waitForReady(endpoint, timeoutMs = STARTUP_TIMEOUT_MS) {
33549
33919
  const deadline = Date.now() + timeoutMs;
33550
33920
  while (Date.now() < deadline) {
33551
33921
  if (await canConnect(endpoint)) return;
33552
- await new Promise((resolve92) => setTimeout(resolve92, STARTUP_POLL_MS));
33922
+ await new Promise((resolve102) => setTimeout(resolve102, STARTUP_POLL_MS));
33553
33923
  }
33554
33924
  throw new Error(`Session host did not become ready within ${timeoutMs}ms`);
33555
33925
  }
@@ -33831,12 +34201,12 @@ async function shutdownDaemonComponents(components) {
33831
34201
 
33832
34202
  // src/session-host.ts
33833
34203
  var import_child_process8 = require("child_process");
33834
- var path15 = __toESM(require("path"));
34204
+ var path16 = __toESM(require("path"));
33835
34205
  var SESSION_HOST_APP_NAME = process.env.ADHDEV_SESSION_HOST_NAME || "adhdev";
33836
34206
  function resolveSessionHostEntry() {
33837
34207
  const localCandidates = [
33838
- path15.resolve(__dirname, "../vendor/session-host-daemon/index.js"),
33839
- path15.resolve(__dirname, "../../vendor/session-host-daemon/index.js")
34208
+ path16.resolve(__dirname, "../vendor/session-host-daemon/index.js"),
34209
+ path16.resolve(__dirname, "../../vendor/session-host-daemon/index.js")
33840
34210
  ];
33841
34211
  for (const candidate of localCandidates) {
33842
34212
  if (require("fs").existsSync(candidate)) {
@@ -33854,9 +34224,9 @@ async function runSessionHostCli(args) {
33854
34224
  ADHDEV_SESSION_HOST_NAME: SESSION_HOST_APP_NAME
33855
34225
  }
33856
34226
  });
33857
- return await new Promise((resolve12, reject) => {
34227
+ return await new Promise((resolve13, reject) => {
33858
34228
  child.on("error", reject);
33859
- child.on("exit", (code) => resolve12(code ?? 0));
34229
+ child.on("exit", (code) => resolve13(code ?? 0));
33860
34230
  });
33861
34231
  }
33862
34232
  async function ensureSessionHostReady2() {
@@ -33963,8 +34333,8 @@ var AdhMuxControlClient = class {
33963
34333
  }
33964
34334
  this.waiters.clear();
33965
34335
  });
33966
- await new Promise((resolve12, reject) => {
33967
- socket.once("connect", () => resolve12());
34336
+ await new Promise((resolve13, reject) => {
34337
+ socket.once("connect", () => resolve13());
33968
34338
  socket.once("error", reject);
33969
34339
  });
33970
34340
  }
@@ -33973,8 +34343,8 @@ var AdhMuxControlClient = class {
33973
34343
  if (!this.socket) throw new Error("adhmux control socket unavailable");
33974
34344
  const requestId = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
33975
34345
  const envelope = { kind: "request", requestId, request };
33976
- const response = await new Promise((resolve12, reject) => {
33977
- this.waiters.set(requestId, { resolve: resolve12, reject });
34346
+ const response = await new Promise((resolve13, reject) => {
34347
+ this.waiters.set(requestId, { resolve: resolve13, reject });
33978
34348
  this.socket?.write(serializeEnvelope2(envelope));
33979
34349
  });
33980
34350
  return response;
@@ -33993,12 +34363,12 @@ var AdhMuxControlClient = class {
33993
34363
  waiter.reject(new Error("adhmux control client closed"));
33994
34364
  }
33995
34365
  this.waiters.clear();
33996
- await new Promise((resolve12) => {
34366
+ await new Promise((resolve13) => {
33997
34367
  let settled = false;
33998
34368
  const done = () => {
33999
34369
  if (settled) return;
34000
34370
  settled = true;
34001
- resolve12();
34371
+ resolve13();
34002
34372
  };
34003
34373
  socket.once("close", done);
34004
34374
  socket.end();
@@ -34056,8 +34426,8 @@ var pkgVersion = process.env.ADHDEV_PKG_VERSION || "unknown";
34056
34426
  if (pkgVersion === "unknown") {
34057
34427
  try {
34058
34428
  const possiblePaths = [
34059
- path17.join(__dirname, "..", "package.json"),
34060
- path17.join(__dirname, "package.json")
34429
+ path18.join(__dirname, "..", "package.json"),
34430
+ path18.join(__dirname, "package.json")
34061
34431
  ];
34062
34432
  for (const candidate of possiblePaths) {
34063
34433
  try {
@@ -34078,10 +34448,42 @@ var StandaloneServer = class {
34078
34448
  clients = /* @__PURE__ */ new Set();
34079
34449
  authToken = null;
34080
34450
  statusTimer = null;
34451
+ lastStatusBroadcastAt = 0;
34452
+ statusBroadcastPending = false;
34081
34453
  running = false;
34082
34454
  components = null;
34083
34455
  devServer = null;
34084
34456
  sessionHostEndpoint = null;
34457
+ isRecoverableSessionHostError(error48) {
34458
+ const message = error48 instanceof Error ? error48.message : String(error48);
34459
+ return message.includes("ECONNREFUSED") || message.includes("ENOENT") || message.includes("Session host socket unavailable");
34460
+ }
34461
+ async ensureActiveSessionHostEndpoint() {
34462
+ const endpoint = await ensureSessionHostReady2();
34463
+ this.sessionHostEndpoint = endpoint;
34464
+ return endpoint;
34465
+ }
34466
+ async createSessionHostClient() {
34467
+ let endpoint = this.sessionHostEndpoint;
34468
+ if (!endpoint) {
34469
+ endpoint = await this.ensureActiveSessionHostEndpoint();
34470
+ }
34471
+ let client = new SessionHostClient({ endpoint });
34472
+ try {
34473
+ await client.connect();
34474
+ return client;
34475
+ } catch (error48) {
34476
+ await client.close().catch(() => {
34477
+ });
34478
+ if (!this.isRecoverableSessionHostError(error48)) {
34479
+ throw error48;
34480
+ }
34481
+ }
34482
+ endpoint = await this.ensureActiveSessionHostEndpoint();
34483
+ client = new SessionHostClient({ endpoint });
34484
+ await client.connect();
34485
+ return client;
34486
+ }
34085
34487
  async start(options = {}) {
34086
34488
  const port = options.port || DEFAULT_PORT;
34087
34489
  const host = options.host || "127.0.0.1";
@@ -34102,7 +34504,7 @@ var StandaloneServer = class {
34102
34504
  }
34103
34505
  }
34104
34506
  }),
34105
- onStatusChange: () => this.broadcastStatus(),
34507
+ onStatusChange: () => this.scheduleBroadcastStatus(),
34106
34508
  removeAgentTracking: () => {
34107
34509
  },
34108
34510
  createPtyTransportFactory: ({ runtimeId, providerType, workspace, cliArgs, attachExisting }) => new SessionHostPtyTransportFactory({
@@ -34119,11 +34521,11 @@ var StandaloneServer = class {
34119
34521
  }),
34120
34522
  listHostedCliRuntimes: async () => listHostedCliRuntimes2(sessionHostEndpoint)
34121
34523
  },
34122
- onStatusChange: () => this.broadcastStatus(),
34524
+ onStatusChange: () => this.scheduleBroadcastStatus(),
34123
34525
  onStreamsUpdated: (ideType, streams) => {
34124
34526
  if (!this.components) return;
34125
34527
  forwardAgentStreamsToIdeInstance(this.components.instanceManager, ideType, streams);
34126
- this.broadcastStatus();
34528
+ this.scheduleBroadcastStatus();
34127
34529
  },
34128
34530
  tickIntervalMs: 3e3,
34129
34531
  cdpScanIntervalMs: 15e3
@@ -34158,12 +34560,12 @@ var StandaloneServer = class {
34158
34560
  }
34159
34561
  });
34160
34562
  this.statusTimer = setInterval(() => {
34161
- this.broadcastStatus();
34563
+ this.scheduleBroadcastStatus();
34162
34564
  }, STATUS_INTERVAL);
34163
34565
  this.running = true;
34164
- await new Promise((resolve12) => {
34566
+ await new Promise((resolve13) => {
34165
34567
  this.httpServer.listen(port, host, () => {
34166
- resolve12();
34568
+ resolve13();
34167
34569
  });
34168
34570
  });
34169
34571
  console.log("");
@@ -34309,7 +34711,7 @@ var StandaloneServer = class {
34309
34711
  }
34310
34712
  if (action === "snapshot" && method === "GET") {
34311
34713
  void (async () => {
34312
- const client = new SessionHostClient({ endpoint: this.sessionHostEndpoint || void 0 });
34714
+ const client = await this.createSessionHostClient();
34313
34715
  try {
34314
34716
  const snapshot = await client.request({
34315
34717
  type: "get_snapshot",
@@ -34357,9 +34759,9 @@ var StandaloneServer = class {
34357
34759
  }
34358
34760
  if (publicDir) {
34359
34761
  const filePath = url2 === "/" ? "/index.html" : url2;
34360
- const fullPath = path17.join(publicDir, filePath);
34762
+ const fullPath = path18.join(publicDir, filePath);
34361
34763
  if (fs12.existsSync(fullPath) && fs12.statSync(fullPath).isFile()) {
34362
- const ext = path17.extname(fullPath);
34764
+ const ext = path18.extname(fullPath);
34363
34765
  const mimeTypes = {
34364
34766
  ".html": "text/html",
34365
34767
  ".js": "application/javascript",
@@ -34374,7 +34776,7 @@ var StandaloneServer = class {
34374
34776
  fs12.createReadStream(fullPath).pipe(res);
34375
34777
  return;
34376
34778
  }
34377
- const indexPath = path17.join(publicDir, "index.html");
34779
+ const indexPath = path18.join(publicDir, "index.html");
34378
34780
  if (fs12.existsSync(indexPath) && !url2.startsWith("/api/")) {
34379
34781
  res.writeHead(200, { "Content-Type": "text/html" });
34380
34782
  fs12.createReadStream(indexPath).pipe(res);
@@ -34429,8 +34831,7 @@ var StandaloneServer = class {
34429
34831
  req.on("aborted", cleanup);
34430
34832
  }
34431
34833
  async handleRuntimeEvents(req, res, sessionId) {
34432
- const client = new SessionHostClient({ endpoint: this.sessionHostEndpoint || void 0 });
34433
- await client.connect();
34834
+ const client = await this.createSessionHostClient();
34434
34835
  res.writeHead(200, {
34435
34836
  "Content-Type": "text/event-stream",
34436
34837
  "Cache-Control": "no-cache, no-transform",
@@ -34530,9 +34931,8 @@ var StandaloneServer = class {
34530
34931
  });
34531
34932
  }
34532
34933
  async pushWsRuntimeSnapshots(ws) {
34533
- if (!this.components || !this.sessionHostEndpoint || ws.readyState !== import_ws2.WebSocket.OPEN) return;
34534
- const client = new SessionHostClient({ endpoint: this.sessionHostEndpoint || void 0 });
34535
- await client.connect();
34934
+ if (!this.components || ws.readyState !== import_ws2.WebSocket.OPEN) return;
34935
+ const client = await this.createSessionHostClient();
34536
34936
  try {
34537
34937
  const states = this.components.instanceManager.collectAllStates();
34538
34938
  for (const state of states) {
@@ -34581,11 +34981,27 @@ var StandaloneServer = class {
34581
34981
  return { success: false, error: "Components not initialized" };
34582
34982
  }
34583
34983
  const result = await this.components.router.execute(type, args, "standalone");
34584
- if (type.startsWith("workspace_")) this.broadcastStatus();
34984
+ if (type.startsWith("workspace_")) this.scheduleBroadcastStatus();
34585
34985
  return result;
34586
34986
  }
34987
+ scheduleBroadcastStatus() {
34988
+ const now = Date.now();
34989
+ const elapsed = now - this.lastStatusBroadcastAt;
34990
+ const minInterval = 500;
34991
+ if (elapsed >= minInterval) {
34992
+ this.broadcastStatus();
34993
+ return;
34994
+ }
34995
+ if (this.statusBroadcastPending) return;
34996
+ this.statusBroadcastPending = true;
34997
+ setTimeout(() => {
34998
+ this.statusBroadcastPending = false;
34999
+ this.broadcastStatus();
35000
+ }, minInterval - elapsed);
35001
+ }
34587
35002
  broadcastStatus() {
34588
35003
  if (this.clients.size === 0) return;
35004
+ this.lastStatusBroadcastAt = Date.now();
34589
35005
  const status = this.getStatus();
34590
35006
  const msg = JSON.stringify({ type: "status", data: status });
34591
35007
  const cdpCount = [...this.components.cdpManagers.values()].filter((m) => m.isConnected).length;
@@ -34708,12 +35124,12 @@ Runtime commands:
34708
35124
  }
34709
35125
  if (!options.publicDir) {
34710
35126
  const candidates = [
34711
- path17.join(__dirname, "../../web-standalone/dist"),
34712
- path17.join(__dirname, "../public"),
34713
- path17.join(process.cwd(), "public")
35127
+ path18.join(__dirname, "../../web-standalone/dist"),
35128
+ path18.join(__dirname, "../public"),
35129
+ path18.join(process.cwd(), "public")
34714
35130
  ];
34715
35131
  for (const candidate of candidates) {
34716
- if (fs12.existsSync(path17.join(candidate, "index.html"))) {
35132
+ if (fs12.existsSync(path18.join(candidate, "index.html"))) {
34717
35133
  options.publicDir = candidate;
34718
35134
  break;
34719
35135
  }