adhdev 0.6.71 → 0.6.75

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/cli/index.js CHANGED
@@ -517,8 +517,8 @@ async function detectIDEs() {
517
517
  if ((0, import_fs2.existsSync)(bundledCli)) resolvedCli = bundledCli;
518
518
  }
519
519
  if (!resolvedCli && appPath && os18 === "win32") {
520
- const { dirname: dirname7 } = await import("path");
521
- const appDir = dirname7(appPath);
520
+ const { dirname: dirname9 } = await import("path");
521
+ const appDir = dirname9(appPath);
522
522
  const candidates = [
523
523
  `${appDir}\\\\bin\\\\${def.cli}.cmd`,
524
524
  `${appDir}\\\\bin\\\\${def.cli}`,
@@ -561,15 +561,15 @@ var init_ide_detector = __esm({
561
561
 
562
562
  // ../../oss/packages/daemon-core/src/detection/cli-detector.ts
563
563
  function execAsync(cmd, timeoutMs = 5e3) {
564
- return new Promise((resolve7) => {
564
+ return new Promise((resolve10) => {
565
565
  const child = (0, import_child_process2.exec)(cmd, { encoding: "utf-8", timeout: timeoutMs }, (err, stdout) => {
566
566
  if (err || !stdout?.trim()) {
567
- resolve7(null);
567
+ resolve10(null);
568
568
  } else {
569
- resolve7(stdout.trim());
569
+ resolve10(stdout.trim());
570
570
  }
571
571
  });
572
- child.on("error", () => resolve7(null));
572
+ child.on("error", () => resolve10(null));
573
573
  });
574
574
  }
575
575
  async function detectCLIs(providerLoader) {
@@ -700,8 +700,8 @@ function cleanOldLogs() {
700
700
  }
701
701
  function rotateSizeIfNeeded() {
702
702
  try {
703
- const stat = fs2.statSync(currentLogFile);
704
- if (stat.size > MAX_LOG_SIZE) {
703
+ const stat4 = fs2.statSync(currentLogFile);
704
+ if (stat4.size > MAX_LOG_SIZE) {
705
705
  const backup = currentLogFile.replace(".log", ".1.log");
706
706
  try {
707
707
  fs2.unlinkSync(backup);
@@ -830,8 +830,8 @@ var init_logger = __esm({
830
830
  try {
831
831
  const oldLog = path3.join(LOG_DIR, "daemon.log");
832
832
  if (fs2.existsSync(oldLog)) {
833
- const stat = fs2.statSync(oldLog);
834
- const oldDate = stat.mtime.toISOString().slice(0, 10);
833
+ const stat4 = fs2.statSync(oldLog);
834
+ const oldDate = stat4.mtime.toISOString().slice(0, 10);
835
835
  fs2.renameSync(oldLog, path3.join(LOG_DIR, `daemon-${oldDate}.log`));
836
836
  }
837
837
  const oldLogBackup = path3.join(LOG_DIR, "daemon.log.old");
@@ -955,7 +955,7 @@ var init_manager = __esm({
955
955
  * Returns multiple entries if multiple IDE windows are open on same port
956
956
  */
957
957
  static listAllTargets(port) {
958
- return new Promise((resolve7) => {
958
+ return new Promise((resolve10) => {
959
959
  const req = http.get(`http://127.0.0.1:${port}/json`, (res) => {
960
960
  let data = "";
961
961
  res.on("data", (chunk) => data += chunk.toString());
@@ -971,16 +971,16 @@ var init_manager = __esm({
971
971
  (t) => !isNonMain(t.title || "") && t.url?.includes("workbench.html") && !t.url?.includes("agent")
972
972
  );
973
973
  const fallbackPages = pages.filter((t) => !isNonMain(t.title || ""));
974
- resolve7(mainPages.length > 0 ? mainPages : fallbackPages);
974
+ resolve10(mainPages.length > 0 ? mainPages : fallbackPages);
975
975
  } catch {
976
- resolve7([]);
976
+ resolve10([]);
977
977
  }
978
978
  });
979
979
  });
980
- req.on("error", () => resolve7([]));
980
+ req.on("error", () => resolve10([]));
981
981
  req.setTimeout(2e3, () => {
982
982
  req.destroy();
983
- resolve7([]);
983
+ resolve10([]);
984
984
  });
985
985
  });
986
986
  }
@@ -1020,7 +1020,7 @@ var init_manager = __esm({
1020
1020
  }
1021
1021
  }
1022
1022
  findTargetOnPort(port) {
1023
- return new Promise((resolve7) => {
1023
+ return new Promise((resolve10) => {
1024
1024
  const req = http.get(`http://127.0.0.1:${port}/json`, (res) => {
1025
1025
  let data = "";
1026
1026
  res.on("data", (chunk) => data += chunk.toString());
@@ -1031,7 +1031,7 @@ var init_manager = __esm({
1031
1031
  (t) => (t.type === "page" || t.type === "browser" || t.type === "Page") && t.webSocketDebuggerUrl
1032
1032
  );
1033
1033
  if (pages.length === 0) {
1034
- resolve7(targets.find((t) => t.webSocketDebuggerUrl) || null);
1034
+ resolve10(targets.find((t) => t.webSocketDebuggerUrl) || null);
1035
1035
  return;
1036
1036
  }
1037
1037
  const mainPages = pages.filter((t) => !this.isNonMainTitle(t.title || ""));
@@ -1041,24 +1041,24 @@ var init_manager = __esm({
1041
1041
  const specific = list.find((t) => t.id === this._targetId);
1042
1042
  if (specific) {
1043
1043
  this._pageTitle = specific.title || "";
1044
- resolve7(specific);
1044
+ resolve10(specific);
1045
1045
  } else {
1046
1046
  this.log(`[CDP] Target ${this._targetId} not found in page list`);
1047
- resolve7(null);
1047
+ resolve10(null);
1048
1048
  }
1049
1049
  return;
1050
1050
  }
1051
1051
  this._pageTitle = list[0]?.title || "";
1052
- resolve7(list[0]);
1052
+ resolve10(list[0]);
1053
1053
  } catch {
1054
- resolve7(null);
1054
+ resolve10(null);
1055
1055
  }
1056
1056
  });
1057
1057
  });
1058
- req.on("error", () => resolve7(null));
1058
+ req.on("error", () => resolve10(null));
1059
1059
  req.setTimeout(2e3, () => {
1060
1060
  req.destroy();
1061
- resolve7(null);
1061
+ resolve10(null);
1062
1062
  });
1063
1063
  });
1064
1064
  }
@@ -1069,7 +1069,7 @@ var init_manager = __esm({
1069
1069
  this.extensionProviders = providers;
1070
1070
  }
1071
1071
  connectToTarget(wsUrl) {
1072
- return new Promise((resolve7) => {
1072
+ return new Promise((resolve10) => {
1073
1073
  this.ws = new import_ws.default(wsUrl);
1074
1074
  this.ws.on("open", async () => {
1075
1075
  this._connected = true;
@@ -1079,17 +1079,17 @@ var init_manager = __esm({
1079
1079
  }
1080
1080
  this.connectBrowserWs().catch(() => {
1081
1081
  });
1082
- resolve7(true);
1082
+ resolve10(true);
1083
1083
  });
1084
1084
  this.ws.on("message", (data) => {
1085
1085
  try {
1086
1086
  const msg = JSON.parse(data.toString());
1087
1087
  if (msg.id && this.pending.has(msg.id)) {
1088
- const { resolve: resolve8, reject } = this.pending.get(msg.id);
1088
+ const { resolve: resolve11, reject } = this.pending.get(msg.id);
1089
1089
  this.pending.delete(msg.id);
1090
1090
  this.failureCount = 0;
1091
1091
  if (msg.error) reject(new Error(msg.error.message));
1092
- else resolve8(msg.result);
1092
+ else resolve11(msg.result);
1093
1093
  } else if (msg.method === "Runtime.executionContextCreated") {
1094
1094
  this.contexts.add(msg.params.context.id);
1095
1095
  } else if (msg.method === "Runtime.executionContextDestroyed") {
@@ -1112,7 +1112,7 @@ var init_manager = __esm({
1112
1112
  this.ws.on("error", (err) => {
1113
1113
  this.log(`[CDP] WebSocket error: ${err.message}`);
1114
1114
  this._connected = false;
1115
- resolve7(false);
1115
+ resolve10(false);
1116
1116
  });
1117
1117
  });
1118
1118
  }
@@ -1126,7 +1126,7 @@ var init_manager = __esm({
1126
1126
  return;
1127
1127
  }
1128
1128
  this.log(`[CDP] Connecting browser WS for target discovery...`);
1129
- await new Promise((resolve7, reject) => {
1129
+ await new Promise((resolve10, reject) => {
1130
1130
  this.browserWs = new import_ws.default(browserWsUrl);
1131
1131
  this.browserWs.on("open", async () => {
1132
1132
  this._browserConnected = true;
@@ -1136,16 +1136,16 @@ var init_manager = __esm({
1136
1136
  } catch (e) {
1137
1137
  this.log(`[CDP] setDiscoverTargets failed: ${e.message}`);
1138
1138
  }
1139
- resolve7();
1139
+ resolve10();
1140
1140
  });
1141
1141
  this.browserWs.on("message", (data) => {
1142
1142
  try {
1143
1143
  const msg = JSON.parse(data.toString());
1144
1144
  if (msg.id && this.browserPending.has(msg.id)) {
1145
- const { resolve: resolve8, reject: reject2 } = this.browserPending.get(msg.id);
1145
+ const { resolve: resolve11, reject: reject2 } = this.browserPending.get(msg.id);
1146
1146
  this.browserPending.delete(msg.id);
1147
1147
  if (msg.error) reject2(new Error(msg.error.message));
1148
- else resolve8(msg.result);
1148
+ else resolve11(msg.result);
1149
1149
  }
1150
1150
  } catch {
1151
1151
  }
@@ -1165,31 +1165,31 @@ var init_manager = __esm({
1165
1165
  }
1166
1166
  }
1167
1167
  getBrowserWsUrl() {
1168
- return new Promise((resolve7) => {
1168
+ return new Promise((resolve10) => {
1169
1169
  const req = http.get(`http://127.0.0.1:${this.port}/json/version`, (res) => {
1170
1170
  let data = "";
1171
1171
  res.on("data", (chunk) => data += chunk.toString());
1172
1172
  res.on("end", () => {
1173
1173
  try {
1174
1174
  const info = JSON.parse(data);
1175
- resolve7(info.webSocketDebuggerUrl || null);
1175
+ resolve10(info.webSocketDebuggerUrl || null);
1176
1176
  } catch {
1177
- resolve7(null);
1177
+ resolve10(null);
1178
1178
  }
1179
1179
  });
1180
1180
  });
1181
- req.on("error", () => resolve7(null));
1181
+ req.on("error", () => resolve10(null));
1182
1182
  req.setTimeout(3e3, () => {
1183
1183
  req.destroy();
1184
- resolve7(null);
1184
+ resolve10(null);
1185
1185
  });
1186
1186
  });
1187
1187
  }
1188
1188
  sendBrowser(method, params = {}, timeoutMs = 15e3) {
1189
- return new Promise((resolve7, reject) => {
1189
+ return new Promise((resolve10, reject) => {
1190
1190
  if (!this.browserWs || !this._browserConnected) return reject(new Error("Browser WS not connected"));
1191
1191
  const id = this.browserMsgId++;
1192
- this.browserPending.set(id, { resolve: resolve7, reject });
1192
+ this.browserPending.set(id, { resolve: resolve10, reject });
1193
1193
  this.browserWs.send(JSON.stringify({ id, method, params }));
1194
1194
  setTimeout(() => {
1195
1195
  if (this.browserPending.has(id)) {
@@ -1229,11 +1229,11 @@ var init_manager = __esm({
1229
1229
  }
1230
1230
  // ─── CDP Protocol ────────────────────────────────────────
1231
1231
  sendInternal(method, params = {}, timeoutMs = 15e3) {
1232
- return new Promise((resolve7, reject) => {
1232
+ return new Promise((resolve10, reject) => {
1233
1233
  if (!this.ws || !this._connected) return reject(new Error("CDP not connected"));
1234
1234
  if (this.ws.readyState !== import_ws.default.OPEN) return reject(new Error("WebSocket not open"));
1235
1235
  const id = this.msgId++;
1236
- this.pending.set(id, { resolve: resolve7, reject });
1236
+ this.pending.set(id, { resolve: resolve10, reject });
1237
1237
  this.ws.send(JSON.stringify({ id, method, params }));
1238
1238
  setTimeout(() => {
1239
1239
  if (this.pending.has(id)) {
@@ -1482,7 +1482,7 @@ var init_manager = __esm({
1482
1482
  const browserWs = this.browserWs;
1483
1483
  let msgId = this.browserMsgId;
1484
1484
  const sendWs = (method, params = {}, sessionId) => {
1485
- return new Promise((resolve7, reject) => {
1485
+ return new Promise((resolve10, reject) => {
1486
1486
  const mid = msgId++;
1487
1487
  this.browserMsgId = msgId;
1488
1488
  const handler = (raw) => {
@@ -1491,7 +1491,7 @@ var init_manager = __esm({
1491
1491
  if (msg.id === mid) {
1492
1492
  browserWs.removeListener("message", handler);
1493
1493
  if (msg.error) reject(new Error(msg.error.message || JSON.stringify(msg.error)));
1494
- else resolve7(msg.result);
1494
+ else resolve10(msg.result);
1495
1495
  }
1496
1496
  } catch {
1497
1497
  }
@@ -1673,14 +1673,14 @@ var init_manager = __esm({
1673
1673
  if (!ws2 || ws2.readyState !== import_ws.default.OPEN) {
1674
1674
  throw new Error("CDP not connected");
1675
1675
  }
1676
- return new Promise((resolve7, reject) => {
1676
+ return new Promise((resolve10, reject) => {
1677
1677
  const id = getNextId();
1678
1678
  pendingMap.set(id, {
1679
1679
  resolve: (result) => {
1680
1680
  if (result?.result?.subtype === "error") {
1681
1681
  reject(new Error(result.result.description));
1682
1682
  } else {
1683
- resolve7(result?.result?.value);
1683
+ resolve10(result?.result?.value);
1684
1684
  }
1685
1685
  },
1686
1686
  reject
@@ -1712,10 +1712,10 @@ var init_manager = __esm({
1712
1712
  throw new Error("CDP not connected");
1713
1713
  }
1714
1714
  const sendViaSession = (method, params = {}) => {
1715
- return new Promise((resolve7, reject) => {
1715
+ return new Promise((resolve10, reject) => {
1716
1716
  const pendingMap = this._browserConnected ? this.browserPending : this.pending;
1717
1717
  const id = this._browserConnected ? this.browserMsgId++ : this.msgId++;
1718
- pendingMap.set(id, { resolve: resolve7, reject });
1718
+ pendingMap.set(id, { resolve: resolve10, reject });
1719
1719
  ws2.send(JSON.stringify({ id, sessionId, method, params }));
1720
1720
  setTimeout(() => {
1721
1721
  if (pendingMap.has(id)) {
@@ -2531,8 +2531,8 @@ ${next}`;
2531
2531
  const files = fs3.readdirSync(dirPath).filter((f) => f.endsWith(".jsonl") || f.endsWith(".terminal.log"));
2532
2532
  for (const file2 of files) {
2533
2533
  const filePath = path4.join(dirPath, file2);
2534
- const stat = fs3.statSync(filePath);
2535
- if (stat.mtimeMs < cutoff) {
2534
+ const stat4 = fs3.statSync(filePath);
2535
+ if (stat4.mtimeMs < cutoff) {
2536
2536
  fs3.unlinkSync(filePath);
2537
2537
  }
2538
2538
  }
@@ -5216,7 +5216,7 @@ var init_handler = __esm({
5216
5216
  try {
5217
5217
  const http3 = await import("http");
5218
5218
  const postData = JSON.stringify(body);
5219
- const result = await new Promise((resolve7, reject) => {
5219
+ const result = await new Promise((resolve10, reject) => {
5220
5220
  const req = http3.request({
5221
5221
  hostname: "127.0.0.1",
5222
5222
  port: 19280,
@@ -5228,9 +5228,9 @@ var init_handler = __esm({
5228
5228
  res.on("data", (chunk) => data += chunk);
5229
5229
  res.on("end", () => {
5230
5230
  try {
5231
- resolve7(JSON.parse(data));
5231
+ resolve10(JSON.parse(data));
5232
5232
  } catch {
5233
- resolve7({ raw: data });
5233
+ resolve10({ raw: data });
5234
5234
  }
5235
5235
  });
5236
5236
  });
@@ -5248,15 +5248,15 @@ var init_handler = __esm({
5248
5248
  if (!providerType) return { success: false, error: "providerType required" };
5249
5249
  try {
5250
5250
  const http3 = await import("http");
5251
- const result = await new Promise((resolve7, reject) => {
5251
+ const result = await new Promise((resolve10, reject) => {
5252
5252
  http3.get(`http://127.0.0.1:19280/api/providers/${providerType}/${endpoint}`, (res) => {
5253
5253
  let data = "";
5254
5254
  res.on("data", (chunk) => data += chunk);
5255
5255
  res.on("end", () => {
5256
5256
  try {
5257
- resolve7(JSON.parse(data));
5257
+ resolve10(JSON.parse(data));
5258
5258
  } catch {
5259
- resolve7({ raw: data });
5259
+ resolve10({ raw: data });
5260
5260
  }
5261
5261
  });
5262
5262
  }).on("error", reject);
@@ -5270,7 +5270,7 @@ var init_handler = __esm({
5270
5270
  try {
5271
5271
  const http3 = await import("http");
5272
5272
  const postData = JSON.stringify(args || {});
5273
- const result = await new Promise((resolve7, reject) => {
5273
+ const result = await new Promise((resolve10, reject) => {
5274
5274
  const req = http3.request({
5275
5275
  hostname: "127.0.0.1",
5276
5276
  port: 19280,
@@ -5282,9 +5282,9 @@ var init_handler = __esm({
5282
5282
  res.on("data", (chunk) => data += chunk);
5283
5283
  res.on("end", () => {
5284
5284
  try {
5285
- resolve7(JSON.parse(data));
5285
+ resolve10(JSON.parse(data));
5286
5286
  } catch {
5287
- resolve7({ raw: data });
5287
+ resolve10({ raw: data });
5288
5288
  }
5289
5289
  });
5290
5290
  });
@@ -5301,6 +5301,1755 @@ var init_handler = __esm({
5301
5301
  }
5302
5302
  });
5303
5303
 
5304
+ // ../../oss/packages/daemon-core/node_modules/readdirp/index.js
5305
+ function readdirp(root, options = {}) {
5306
+ let type = options.entryType || options.type;
5307
+ if (type === "both")
5308
+ type = EntryTypes.FILE_DIR_TYPE;
5309
+ if (type)
5310
+ options.type = type;
5311
+ if (!root) {
5312
+ throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
5313
+ } else if (typeof root !== "string") {
5314
+ throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");
5315
+ } else if (type && !ALL_TYPES.includes(type)) {
5316
+ throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
5317
+ }
5318
+ options.root = root;
5319
+ return new ReaddirpStream(options);
5320
+ }
5321
+ var import_promises, import_node_path, import_node_stream, EntryTypes, defaultOptions, RECURSIVE_ERROR_CODE, NORMAL_FLOW_ERRORS, ALL_TYPES, DIR_TYPES, FILE_TYPES, isNormalFlowError, wantBigintFsStats, emptyFn, normalizeFilter, ReaddirpStream;
5322
+ var init_readdirp = __esm({
5323
+ "../../oss/packages/daemon-core/node_modules/readdirp/index.js"() {
5324
+ "use strict";
5325
+ import_promises = require("fs/promises");
5326
+ import_node_path = require("path");
5327
+ import_node_stream = require("stream");
5328
+ EntryTypes = {
5329
+ FILE_TYPE: "files",
5330
+ DIR_TYPE: "directories",
5331
+ FILE_DIR_TYPE: "files_directories",
5332
+ EVERYTHING_TYPE: "all"
5333
+ };
5334
+ defaultOptions = {
5335
+ root: ".",
5336
+ fileFilter: (_entryInfo) => true,
5337
+ directoryFilter: (_entryInfo) => true,
5338
+ type: EntryTypes.FILE_TYPE,
5339
+ lstat: false,
5340
+ depth: 2147483648,
5341
+ alwaysStat: false,
5342
+ highWaterMark: 4096
5343
+ };
5344
+ Object.freeze(defaultOptions);
5345
+ RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR";
5346
+ NORMAL_FLOW_ERRORS = /* @__PURE__ */ new Set(["ENOENT", "EPERM", "EACCES", "ELOOP", RECURSIVE_ERROR_CODE]);
5347
+ ALL_TYPES = [
5348
+ EntryTypes.DIR_TYPE,
5349
+ EntryTypes.EVERYTHING_TYPE,
5350
+ EntryTypes.FILE_DIR_TYPE,
5351
+ EntryTypes.FILE_TYPE
5352
+ ];
5353
+ DIR_TYPES = /* @__PURE__ */ new Set([
5354
+ EntryTypes.DIR_TYPE,
5355
+ EntryTypes.EVERYTHING_TYPE,
5356
+ EntryTypes.FILE_DIR_TYPE
5357
+ ]);
5358
+ FILE_TYPES = /* @__PURE__ */ new Set([
5359
+ EntryTypes.EVERYTHING_TYPE,
5360
+ EntryTypes.FILE_DIR_TYPE,
5361
+ EntryTypes.FILE_TYPE
5362
+ ]);
5363
+ isNormalFlowError = (error48) => NORMAL_FLOW_ERRORS.has(error48.code);
5364
+ wantBigintFsStats = process.platform === "win32";
5365
+ emptyFn = (_entryInfo) => true;
5366
+ normalizeFilter = (filter) => {
5367
+ if (filter === void 0)
5368
+ return emptyFn;
5369
+ if (typeof filter === "function")
5370
+ return filter;
5371
+ if (typeof filter === "string") {
5372
+ const fl2 = filter.trim();
5373
+ return (entry) => entry.basename === fl2;
5374
+ }
5375
+ if (Array.isArray(filter)) {
5376
+ const trItems = filter.map((item) => item.trim());
5377
+ return (entry) => trItems.some((f) => entry.basename === f);
5378
+ }
5379
+ return emptyFn;
5380
+ };
5381
+ ReaddirpStream = class extends import_node_stream.Readable {
5382
+ parents;
5383
+ reading;
5384
+ parent;
5385
+ _stat;
5386
+ _maxDepth;
5387
+ _wantsDir;
5388
+ _wantsFile;
5389
+ _wantsEverything;
5390
+ _root;
5391
+ _isDirent;
5392
+ _statsProp;
5393
+ _rdOptions;
5394
+ _fileFilter;
5395
+ _directoryFilter;
5396
+ constructor(options = {}) {
5397
+ super({
5398
+ objectMode: true,
5399
+ autoDestroy: true,
5400
+ highWaterMark: options.highWaterMark
5401
+ });
5402
+ const opts = { ...defaultOptions, ...options };
5403
+ const { root, type } = opts;
5404
+ this._fileFilter = normalizeFilter(opts.fileFilter);
5405
+ this._directoryFilter = normalizeFilter(opts.directoryFilter);
5406
+ const statMethod = opts.lstat ? import_promises.lstat : import_promises.stat;
5407
+ if (wantBigintFsStats) {
5408
+ this._stat = (path15) => statMethod(path15, { bigint: true });
5409
+ } else {
5410
+ this._stat = statMethod;
5411
+ }
5412
+ this._maxDepth = opts.depth != null && Number.isSafeInteger(opts.depth) ? opts.depth : defaultOptions.depth;
5413
+ this._wantsDir = type ? DIR_TYPES.has(type) : false;
5414
+ this._wantsFile = type ? FILE_TYPES.has(type) : false;
5415
+ this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;
5416
+ this._root = (0, import_node_path.resolve)(root);
5417
+ this._isDirent = !opts.alwaysStat;
5418
+ this._statsProp = this._isDirent ? "dirent" : "stats";
5419
+ this._rdOptions = { encoding: "utf8", withFileTypes: this._isDirent };
5420
+ this.parents = [this._exploreDir(root, 1)];
5421
+ this.reading = false;
5422
+ this.parent = void 0;
5423
+ }
5424
+ async _read(batch) {
5425
+ if (this.reading)
5426
+ return;
5427
+ this.reading = true;
5428
+ try {
5429
+ while (!this.destroyed && batch > 0) {
5430
+ const par = this.parent;
5431
+ const fil = par && par.files;
5432
+ if (fil && fil.length > 0) {
5433
+ const { path: path15, depth } = par;
5434
+ const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path15));
5435
+ const awaited = await Promise.all(slice);
5436
+ for (const entry of awaited) {
5437
+ if (!entry)
5438
+ continue;
5439
+ if (this.destroyed)
5440
+ return;
5441
+ const entryType = await this._getEntryType(entry);
5442
+ if (entryType === "directory" && this._directoryFilter(entry)) {
5443
+ if (depth <= this._maxDepth) {
5444
+ this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
5445
+ }
5446
+ if (this._wantsDir) {
5447
+ this.push(entry);
5448
+ batch--;
5449
+ }
5450
+ } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) {
5451
+ if (this._wantsFile) {
5452
+ this.push(entry);
5453
+ batch--;
5454
+ }
5455
+ }
5456
+ }
5457
+ } else {
5458
+ const parent = this.parents.pop();
5459
+ if (!parent) {
5460
+ this.push(null);
5461
+ break;
5462
+ }
5463
+ this.parent = await parent;
5464
+ if (this.destroyed)
5465
+ return;
5466
+ }
5467
+ }
5468
+ } catch (error48) {
5469
+ this.destroy(error48);
5470
+ } finally {
5471
+ this.reading = false;
5472
+ }
5473
+ }
5474
+ async _exploreDir(path15, depth) {
5475
+ let files;
5476
+ try {
5477
+ files = await (0, import_promises.readdir)(path15, this._rdOptions);
5478
+ } catch (error48) {
5479
+ this._onError(error48);
5480
+ }
5481
+ return { files, depth, path: path15 };
5482
+ }
5483
+ async _formatEntry(dirent, path15) {
5484
+ let entry;
5485
+ const basename5 = this._isDirent ? dirent.name : dirent;
5486
+ try {
5487
+ const fullPath = (0, import_node_path.resolve)((0, import_node_path.join)(path15, basename5));
5488
+ entry = { path: (0, import_node_path.relative)(this._root, fullPath), fullPath, basename: basename5 };
5489
+ entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
5490
+ } catch (err) {
5491
+ this._onError(err);
5492
+ return;
5493
+ }
5494
+ return entry;
5495
+ }
5496
+ _onError(err) {
5497
+ if (isNormalFlowError(err) && !this.destroyed) {
5498
+ this.emit("warn", err);
5499
+ } else {
5500
+ this.destroy(err);
5501
+ }
5502
+ }
5503
+ async _getEntryType(entry) {
5504
+ if (!entry && this._statsProp in entry) {
5505
+ return "";
5506
+ }
5507
+ const stats = entry[this._statsProp];
5508
+ if (stats.isFile())
5509
+ return "file";
5510
+ if (stats.isDirectory())
5511
+ return "directory";
5512
+ if (stats && stats.isSymbolicLink()) {
5513
+ const full = entry.fullPath;
5514
+ try {
5515
+ const entryRealPath = await (0, import_promises.realpath)(full);
5516
+ const entryRealPathStats = await (0, import_promises.lstat)(entryRealPath);
5517
+ if (entryRealPathStats.isFile()) {
5518
+ return "file";
5519
+ }
5520
+ if (entryRealPathStats.isDirectory()) {
5521
+ const len = entryRealPath.length;
5522
+ if (full.startsWith(entryRealPath) && full.substr(len, 1) === import_node_path.sep) {
5523
+ const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
5524
+ recursiveError.code = RECURSIVE_ERROR_CODE;
5525
+ return this._onError(recursiveError);
5526
+ }
5527
+ return "directory";
5528
+ }
5529
+ } catch (error48) {
5530
+ this._onError(error48);
5531
+ return "";
5532
+ }
5533
+ }
5534
+ }
5535
+ _includeAsFile(entry) {
5536
+ const stats = entry && entry[this._statsProp];
5537
+ return stats && this._wantsEverything && !stats.isDirectory();
5538
+ }
5539
+ };
5540
+ }
5541
+ });
5542
+
5543
+ // ../../oss/packages/daemon-core/node_modules/chokidar/handler.js
5544
+ function createFsWatchInstance(path15, options, listener, errHandler, emitRaw) {
5545
+ const handleEvent = (rawEvent, evPath) => {
5546
+ listener(path15);
5547
+ emitRaw(rawEvent, evPath, { watchedPath: path15 });
5548
+ if (evPath && path15 !== evPath) {
5549
+ fsWatchBroadcast(sp.resolve(path15, evPath), KEY_LISTENERS, sp.join(path15, evPath));
5550
+ }
5551
+ };
5552
+ try {
5553
+ return (0, import_node_fs.watch)(path15, {
5554
+ persistent: options.persistent
5555
+ }, handleEvent);
5556
+ } catch (error48) {
5557
+ errHandler(error48);
5558
+ return void 0;
5559
+ }
5560
+ }
5561
+ var import_node_fs, import_promises2, import_node_os, sp, STR_DATA, STR_END, STR_CLOSE, EMPTY_FN, pl, isWindows, isMacos, isLinux, isFreeBSD, isIBMi, EVENTS, EV, THROTTLE_MODE_WATCH, statMethods, KEY_LISTENERS, KEY_ERR, KEY_RAW, HANDLER_KEYS, binaryExtensions, isBinaryPath, foreach, addAndConvert, clearItem, delFromSet, isEmptySet, FsWatchInstances, fsWatchBroadcast, setFsWatchListener, FsWatchFileInstances, setFsWatchFileListener, NodeFsHandler;
5562
+ var init_handler2 = __esm({
5563
+ "../../oss/packages/daemon-core/node_modules/chokidar/handler.js"() {
5564
+ "use strict";
5565
+ import_node_fs = require("fs");
5566
+ import_promises2 = require("fs/promises");
5567
+ import_node_os = require("os");
5568
+ sp = __toESM(require("path"), 1);
5569
+ STR_DATA = "data";
5570
+ STR_END = "end";
5571
+ STR_CLOSE = "close";
5572
+ EMPTY_FN = () => {
5573
+ };
5574
+ pl = process.platform;
5575
+ isWindows = pl === "win32";
5576
+ isMacos = pl === "darwin";
5577
+ isLinux = pl === "linux";
5578
+ isFreeBSD = pl === "freebsd";
5579
+ isIBMi = (0, import_node_os.type)() === "OS400";
5580
+ EVENTS = {
5581
+ ALL: "all",
5582
+ READY: "ready",
5583
+ ADD: "add",
5584
+ CHANGE: "change",
5585
+ ADD_DIR: "addDir",
5586
+ UNLINK: "unlink",
5587
+ UNLINK_DIR: "unlinkDir",
5588
+ RAW: "raw",
5589
+ ERROR: "error"
5590
+ };
5591
+ EV = EVENTS;
5592
+ THROTTLE_MODE_WATCH = "watch";
5593
+ statMethods = { lstat: import_promises2.lstat, stat: import_promises2.stat };
5594
+ KEY_LISTENERS = "listeners";
5595
+ KEY_ERR = "errHandlers";
5596
+ KEY_RAW = "rawEmitters";
5597
+ HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];
5598
+ binaryExtensions = /* @__PURE__ */ new Set([
5599
+ "3dm",
5600
+ "3ds",
5601
+ "3g2",
5602
+ "3gp",
5603
+ "7z",
5604
+ "a",
5605
+ "aac",
5606
+ "adp",
5607
+ "afdesign",
5608
+ "afphoto",
5609
+ "afpub",
5610
+ "ai",
5611
+ "aif",
5612
+ "aiff",
5613
+ "alz",
5614
+ "ape",
5615
+ "apk",
5616
+ "appimage",
5617
+ "ar",
5618
+ "arj",
5619
+ "asf",
5620
+ "au",
5621
+ "avi",
5622
+ "bak",
5623
+ "baml",
5624
+ "bh",
5625
+ "bin",
5626
+ "bk",
5627
+ "bmp",
5628
+ "btif",
5629
+ "bz2",
5630
+ "bzip2",
5631
+ "cab",
5632
+ "caf",
5633
+ "cgm",
5634
+ "class",
5635
+ "cmx",
5636
+ "cpio",
5637
+ "cr2",
5638
+ "cur",
5639
+ "dat",
5640
+ "dcm",
5641
+ "deb",
5642
+ "dex",
5643
+ "djvu",
5644
+ "dll",
5645
+ "dmg",
5646
+ "dng",
5647
+ "doc",
5648
+ "docm",
5649
+ "docx",
5650
+ "dot",
5651
+ "dotm",
5652
+ "dra",
5653
+ "DS_Store",
5654
+ "dsk",
5655
+ "dts",
5656
+ "dtshd",
5657
+ "dvb",
5658
+ "dwg",
5659
+ "dxf",
5660
+ "ecelp4800",
5661
+ "ecelp7470",
5662
+ "ecelp9600",
5663
+ "egg",
5664
+ "eol",
5665
+ "eot",
5666
+ "epub",
5667
+ "exe",
5668
+ "f4v",
5669
+ "fbs",
5670
+ "fh",
5671
+ "fla",
5672
+ "flac",
5673
+ "flatpak",
5674
+ "fli",
5675
+ "flv",
5676
+ "fpx",
5677
+ "fst",
5678
+ "fvt",
5679
+ "g3",
5680
+ "gh",
5681
+ "gif",
5682
+ "graffle",
5683
+ "gz",
5684
+ "gzip",
5685
+ "h261",
5686
+ "h263",
5687
+ "h264",
5688
+ "icns",
5689
+ "ico",
5690
+ "ief",
5691
+ "img",
5692
+ "ipa",
5693
+ "iso",
5694
+ "jar",
5695
+ "jpeg",
5696
+ "jpg",
5697
+ "jpgv",
5698
+ "jpm",
5699
+ "jxr",
5700
+ "key",
5701
+ "ktx",
5702
+ "lha",
5703
+ "lib",
5704
+ "lvp",
5705
+ "lz",
5706
+ "lzh",
5707
+ "lzma",
5708
+ "lzo",
5709
+ "m3u",
5710
+ "m4a",
5711
+ "m4v",
5712
+ "mar",
5713
+ "mdi",
5714
+ "mht",
5715
+ "mid",
5716
+ "midi",
5717
+ "mj2",
5718
+ "mka",
5719
+ "mkv",
5720
+ "mmr",
5721
+ "mng",
5722
+ "mobi",
5723
+ "mov",
5724
+ "movie",
5725
+ "mp3",
5726
+ "mp4",
5727
+ "mp4a",
5728
+ "mpeg",
5729
+ "mpg",
5730
+ "mpga",
5731
+ "mxu",
5732
+ "nef",
5733
+ "npx",
5734
+ "numbers",
5735
+ "nupkg",
5736
+ "o",
5737
+ "odp",
5738
+ "ods",
5739
+ "odt",
5740
+ "oga",
5741
+ "ogg",
5742
+ "ogv",
5743
+ "otf",
5744
+ "ott",
5745
+ "pages",
5746
+ "pbm",
5747
+ "pcx",
5748
+ "pdb",
5749
+ "pdf",
5750
+ "pea",
5751
+ "pgm",
5752
+ "pic",
5753
+ "png",
5754
+ "pnm",
5755
+ "pot",
5756
+ "potm",
5757
+ "potx",
5758
+ "ppa",
5759
+ "ppam",
5760
+ "ppm",
5761
+ "pps",
5762
+ "ppsm",
5763
+ "ppsx",
5764
+ "ppt",
5765
+ "pptm",
5766
+ "pptx",
5767
+ "psd",
5768
+ "pya",
5769
+ "pyc",
5770
+ "pyo",
5771
+ "pyv",
5772
+ "qt",
5773
+ "rar",
5774
+ "ras",
5775
+ "raw",
5776
+ "resources",
5777
+ "rgb",
5778
+ "rip",
5779
+ "rlc",
5780
+ "rmf",
5781
+ "rmvb",
5782
+ "rpm",
5783
+ "rtf",
5784
+ "rz",
5785
+ "s3m",
5786
+ "s7z",
5787
+ "scpt",
5788
+ "sgi",
5789
+ "shar",
5790
+ "snap",
5791
+ "sil",
5792
+ "sketch",
5793
+ "slk",
5794
+ "smv",
5795
+ "snk",
5796
+ "so",
5797
+ "stl",
5798
+ "suo",
5799
+ "sub",
5800
+ "swf",
5801
+ "tar",
5802
+ "tbz",
5803
+ "tbz2",
5804
+ "tga",
5805
+ "tgz",
5806
+ "thmx",
5807
+ "tif",
5808
+ "tiff",
5809
+ "tlz",
5810
+ "ttc",
5811
+ "ttf",
5812
+ "txz",
5813
+ "udf",
5814
+ "uvh",
5815
+ "uvi",
5816
+ "uvm",
5817
+ "uvp",
5818
+ "uvs",
5819
+ "uvu",
5820
+ "viv",
5821
+ "vob",
5822
+ "war",
5823
+ "wav",
5824
+ "wax",
5825
+ "wbmp",
5826
+ "wdp",
5827
+ "weba",
5828
+ "webm",
5829
+ "webp",
5830
+ "whl",
5831
+ "wim",
5832
+ "wm",
5833
+ "wma",
5834
+ "wmv",
5835
+ "wmx",
5836
+ "woff",
5837
+ "woff2",
5838
+ "wrm",
5839
+ "wvx",
5840
+ "xbm",
5841
+ "xif",
5842
+ "xla",
5843
+ "xlam",
5844
+ "xls",
5845
+ "xlsb",
5846
+ "xlsm",
5847
+ "xlsx",
5848
+ "xlt",
5849
+ "xltm",
5850
+ "xltx",
5851
+ "xm",
5852
+ "xmind",
5853
+ "xpi",
5854
+ "xpm",
5855
+ "xwd",
5856
+ "xz",
5857
+ "z",
5858
+ "zip",
5859
+ "zipx"
5860
+ ]);
5861
+ isBinaryPath = (filePath) => binaryExtensions.has(sp.extname(filePath).slice(1).toLowerCase());
5862
+ foreach = (val, fn2) => {
5863
+ if (val instanceof Set) {
5864
+ val.forEach(fn2);
5865
+ } else {
5866
+ fn2(val);
5867
+ }
5868
+ };
5869
+ addAndConvert = (main, prop, item) => {
5870
+ let container = main[prop];
5871
+ if (!(container instanceof Set)) {
5872
+ main[prop] = container = /* @__PURE__ */ new Set([container]);
5873
+ }
5874
+ container.add(item);
5875
+ };
5876
+ clearItem = (cont) => (key) => {
5877
+ const set2 = cont[key];
5878
+ if (set2 instanceof Set) {
5879
+ set2.clear();
5880
+ } else {
5881
+ delete cont[key];
5882
+ }
5883
+ };
5884
+ delFromSet = (main, prop, item) => {
5885
+ const container = main[prop];
5886
+ if (container instanceof Set) {
5887
+ container.delete(item);
5888
+ } else if (container === item) {
5889
+ delete main[prop];
5890
+ }
5891
+ };
5892
+ isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
5893
+ FsWatchInstances = /* @__PURE__ */ new Map();
5894
+ fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
5895
+ const cont = FsWatchInstances.get(fullPath);
5896
+ if (!cont)
5897
+ return;
5898
+ foreach(cont[listenerType], (listener) => {
5899
+ listener(val1, val2, val3);
5900
+ });
5901
+ };
5902
+ setFsWatchListener = (path15, fullPath, options, handlers) => {
5903
+ const { listener, errHandler, rawEmitter } = handlers;
5904
+ let cont = FsWatchInstances.get(fullPath);
5905
+ let watcher;
5906
+ if (!options.persistent) {
5907
+ watcher = createFsWatchInstance(path15, options, listener, errHandler, rawEmitter);
5908
+ if (!watcher)
5909
+ return;
5910
+ return watcher.close.bind(watcher);
5911
+ }
5912
+ if (cont) {
5913
+ addAndConvert(cont, KEY_LISTENERS, listener);
5914
+ addAndConvert(cont, KEY_ERR, errHandler);
5915
+ addAndConvert(cont, KEY_RAW, rawEmitter);
5916
+ } else {
5917
+ watcher = createFsWatchInstance(
5918
+ path15,
5919
+ options,
5920
+ fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
5921
+ errHandler,
5922
+ // no need to use broadcast here
5923
+ fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
5924
+ );
5925
+ if (!watcher)
5926
+ return;
5927
+ watcher.on(EV.ERROR, async (error48) => {
5928
+ const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
5929
+ if (cont)
5930
+ cont.watcherUnusable = true;
5931
+ if (isWindows && error48.code === "EPERM") {
5932
+ try {
5933
+ const fd = await (0, import_promises2.open)(path15, "r");
5934
+ await fd.close();
5935
+ broadcastErr(error48);
5936
+ } catch (err) {
5937
+ }
5938
+ } else {
5939
+ broadcastErr(error48);
5940
+ }
5941
+ });
5942
+ cont = {
5943
+ listeners: listener,
5944
+ errHandlers: errHandler,
5945
+ rawEmitters: rawEmitter,
5946
+ watcher
5947
+ };
5948
+ FsWatchInstances.set(fullPath, cont);
5949
+ }
5950
+ return () => {
5951
+ delFromSet(cont, KEY_LISTENERS, listener);
5952
+ delFromSet(cont, KEY_ERR, errHandler);
5953
+ delFromSet(cont, KEY_RAW, rawEmitter);
5954
+ if (isEmptySet(cont.listeners)) {
5955
+ cont.watcher.close();
5956
+ FsWatchInstances.delete(fullPath);
5957
+ HANDLER_KEYS.forEach(clearItem(cont));
5958
+ cont.watcher = void 0;
5959
+ Object.freeze(cont);
5960
+ }
5961
+ };
5962
+ };
5963
+ FsWatchFileInstances = /* @__PURE__ */ new Map();
5964
+ setFsWatchFileListener = (path15, fullPath, options, handlers) => {
5965
+ const { listener, rawEmitter } = handlers;
5966
+ let cont = FsWatchFileInstances.get(fullPath);
5967
+ const copts = cont && cont.options;
5968
+ if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
5969
+ (0, import_node_fs.unwatchFile)(fullPath);
5970
+ cont = void 0;
5971
+ }
5972
+ if (cont) {
5973
+ addAndConvert(cont, KEY_LISTENERS, listener);
5974
+ addAndConvert(cont, KEY_RAW, rawEmitter);
5975
+ } else {
5976
+ cont = {
5977
+ listeners: listener,
5978
+ rawEmitters: rawEmitter,
5979
+ options,
5980
+ watcher: (0, import_node_fs.watchFile)(fullPath, options, (curr, prev) => {
5981
+ foreach(cont.rawEmitters, (rawEmitter2) => {
5982
+ rawEmitter2(EV.CHANGE, fullPath, { curr, prev });
5983
+ });
5984
+ const currmtime = curr.mtimeMs;
5985
+ if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
5986
+ foreach(cont.listeners, (listener2) => listener2(path15, curr));
5987
+ }
5988
+ })
5989
+ };
5990
+ FsWatchFileInstances.set(fullPath, cont);
5991
+ }
5992
+ return () => {
5993
+ delFromSet(cont, KEY_LISTENERS, listener);
5994
+ delFromSet(cont, KEY_RAW, rawEmitter);
5995
+ if (isEmptySet(cont.listeners)) {
5996
+ FsWatchFileInstances.delete(fullPath);
5997
+ (0, import_node_fs.unwatchFile)(fullPath);
5998
+ cont.options = cont.watcher = void 0;
5999
+ Object.freeze(cont);
6000
+ }
6001
+ };
6002
+ };
6003
+ NodeFsHandler = class {
6004
+ fsw;
6005
+ _boundHandleError;
6006
+ constructor(fsW) {
6007
+ this.fsw = fsW;
6008
+ this._boundHandleError = (error48) => fsW._handleError(error48);
6009
+ }
6010
+ /**
6011
+ * Watch file for changes with fs_watchFile or fs_watch.
6012
+ * @param path to file or dir
6013
+ * @param listener on fs change
6014
+ * @returns closer for the watcher instance
6015
+ */
6016
+ _watchWithNodeFs(path15, listener) {
6017
+ const opts = this.fsw.options;
6018
+ const directory = sp.dirname(path15);
6019
+ const basename5 = sp.basename(path15);
6020
+ const parent = this.fsw._getWatchedDir(directory);
6021
+ parent.add(basename5);
6022
+ const absolutePath = sp.resolve(path15);
6023
+ const options = {
6024
+ persistent: opts.persistent
6025
+ };
6026
+ if (!listener)
6027
+ listener = EMPTY_FN;
6028
+ let closer;
6029
+ if (opts.usePolling) {
6030
+ const enableBin = opts.interval !== opts.binaryInterval;
6031
+ options.interval = enableBin && isBinaryPath(basename5) ? opts.binaryInterval : opts.interval;
6032
+ closer = setFsWatchFileListener(path15, absolutePath, options, {
6033
+ listener,
6034
+ rawEmitter: this.fsw._emitRaw
6035
+ });
6036
+ } else {
6037
+ closer = setFsWatchListener(path15, absolutePath, options, {
6038
+ listener,
6039
+ errHandler: this._boundHandleError,
6040
+ rawEmitter: this.fsw._emitRaw
6041
+ });
6042
+ }
6043
+ return closer;
6044
+ }
6045
+ /**
6046
+ * Watch a file and emit add event if warranted.
6047
+ * @returns closer for the watcher instance
6048
+ */
6049
+ _handleFile(file2, stats, initialAdd) {
6050
+ if (this.fsw.closed) {
6051
+ return;
6052
+ }
6053
+ const dirname9 = sp.dirname(file2);
6054
+ const basename5 = sp.basename(file2);
6055
+ const parent = this.fsw._getWatchedDir(dirname9);
6056
+ let prevStats = stats;
6057
+ if (parent.has(basename5))
6058
+ return;
6059
+ const listener = async (path15, newStats) => {
6060
+ if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file2, 5))
6061
+ return;
6062
+ if (!newStats || newStats.mtimeMs === 0) {
6063
+ try {
6064
+ const newStats2 = await (0, import_promises2.stat)(file2);
6065
+ if (this.fsw.closed)
6066
+ return;
6067
+ const at2 = newStats2.atimeMs;
6068
+ const mt2 = newStats2.mtimeMs;
6069
+ if (!at2 || at2 <= mt2 || mt2 !== prevStats.mtimeMs) {
6070
+ this.fsw._emit(EV.CHANGE, file2, newStats2);
6071
+ }
6072
+ if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats2.ino) {
6073
+ this.fsw._closeFile(path15);
6074
+ prevStats = newStats2;
6075
+ const closer2 = this._watchWithNodeFs(file2, listener);
6076
+ if (closer2)
6077
+ this.fsw._addPathCloser(path15, closer2);
6078
+ } else {
6079
+ prevStats = newStats2;
6080
+ }
6081
+ } catch (error48) {
6082
+ this.fsw._remove(dirname9, basename5);
6083
+ }
6084
+ } else if (parent.has(basename5)) {
6085
+ const at2 = newStats.atimeMs;
6086
+ const mt2 = newStats.mtimeMs;
6087
+ if (!at2 || at2 <= mt2 || mt2 !== prevStats.mtimeMs) {
6088
+ this.fsw._emit(EV.CHANGE, file2, newStats);
6089
+ }
6090
+ prevStats = newStats;
6091
+ }
6092
+ };
6093
+ const closer = this._watchWithNodeFs(file2, listener);
6094
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file2)) {
6095
+ if (!this.fsw._throttle(EV.ADD, file2, 0))
6096
+ return;
6097
+ this.fsw._emit(EV.ADD, file2, stats);
6098
+ }
6099
+ return closer;
6100
+ }
6101
+ /**
6102
+ * Handle symlinks encountered while reading a dir.
6103
+ * @param entry returned by readdirp
6104
+ * @param directory path of dir being read
6105
+ * @param path of this item
6106
+ * @param item basename of this item
6107
+ * @returns true if no more processing is needed for this entry.
6108
+ */
6109
+ async _handleSymlink(entry, directory, path15, item) {
6110
+ if (this.fsw.closed) {
6111
+ return;
6112
+ }
6113
+ const full = entry.fullPath;
6114
+ const dir = this.fsw._getWatchedDir(directory);
6115
+ if (!this.fsw.options.followSymlinks) {
6116
+ this.fsw._incrReadyCount();
6117
+ let linkPath;
6118
+ try {
6119
+ linkPath = await (0, import_promises2.realpath)(path15);
6120
+ } catch (e) {
6121
+ this.fsw._emitReady();
6122
+ return true;
6123
+ }
6124
+ if (this.fsw.closed)
6125
+ return;
6126
+ if (dir.has(item)) {
6127
+ if (this.fsw._symlinkPaths.get(full) !== linkPath) {
6128
+ this.fsw._symlinkPaths.set(full, linkPath);
6129
+ this.fsw._emit(EV.CHANGE, path15, entry.stats);
6130
+ }
6131
+ } else {
6132
+ dir.add(item);
6133
+ this.fsw._symlinkPaths.set(full, linkPath);
6134
+ this.fsw._emit(EV.ADD, path15, entry.stats);
6135
+ }
6136
+ this.fsw._emitReady();
6137
+ return true;
6138
+ }
6139
+ if (this.fsw._symlinkPaths.has(full)) {
6140
+ return true;
6141
+ }
6142
+ this.fsw._symlinkPaths.set(full, true);
6143
+ }
6144
+ _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
6145
+ directory = sp.join(directory, "");
6146
+ const throttleKey = target ? `${directory}:${target}` : directory;
6147
+ throttler = this.fsw._throttle("readdir", throttleKey, 1e3);
6148
+ if (!throttler)
6149
+ return;
6150
+ const previous = this.fsw._getWatchedDir(wh.path);
6151
+ const current = /* @__PURE__ */ new Set();
6152
+ let stream = this.fsw._readdirp(directory, {
6153
+ fileFilter: (entry) => wh.filterPath(entry),
6154
+ directoryFilter: (entry) => wh.filterDir(entry)
6155
+ });
6156
+ if (!stream)
6157
+ return;
6158
+ stream.on(STR_DATA, async (entry) => {
6159
+ if (this.fsw.closed) {
6160
+ stream = void 0;
6161
+ return;
6162
+ }
6163
+ const item = entry.path;
6164
+ let path15 = sp.join(directory, item);
6165
+ current.add(item);
6166
+ if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path15, item)) {
6167
+ return;
6168
+ }
6169
+ if (this.fsw.closed) {
6170
+ stream = void 0;
6171
+ return;
6172
+ }
6173
+ if (item === target || !target && !previous.has(item)) {
6174
+ this.fsw._incrReadyCount();
6175
+ path15 = sp.join(dir, sp.relative(dir, path15));
6176
+ this._addToNodeFs(path15, initialAdd, wh, depth + 1);
6177
+ }
6178
+ }).on(EV.ERROR, this._boundHandleError);
6179
+ return new Promise((resolve10, reject) => {
6180
+ if (!stream)
6181
+ return reject();
6182
+ stream.once(STR_END, () => {
6183
+ if (this.fsw.closed) {
6184
+ stream = void 0;
6185
+ return;
6186
+ }
6187
+ const wasThrottled = throttler ? throttler.clear() : false;
6188
+ resolve10(void 0);
6189
+ previous.getChildren().filter((item) => {
6190
+ return item !== directory && !current.has(item);
6191
+ }).forEach((item) => {
6192
+ this.fsw._remove(directory, item);
6193
+ });
6194
+ stream = void 0;
6195
+ if (wasThrottled)
6196
+ this._handleRead(directory, false, wh, target, dir, depth, throttler);
6197
+ });
6198
+ });
6199
+ }
6200
+ /**
6201
+ * Read directory to add / remove files from `@watched` list and re-read it on change.
6202
+ * @param dir fs path
6203
+ * @param stats
6204
+ * @param initialAdd
6205
+ * @param depth relative to user-supplied path
6206
+ * @param target child path targeted for watch
6207
+ * @param wh Common watch helpers for this path
6208
+ * @param realpath
6209
+ * @returns closer for the watcher instance.
6210
+ */
6211
+ async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath2) {
6212
+ const parentDir = this.fsw._getWatchedDir(sp.dirname(dir));
6213
+ const tracked = parentDir.has(sp.basename(dir));
6214
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
6215
+ this.fsw._emit(EV.ADD_DIR, dir, stats);
6216
+ }
6217
+ parentDir.add(sp.basename(dir));
6218
+ this.fsw._getWatchedDir(dir);
6219
+ let throttler;
6220
+ let closer;
6221
+ const oDepth = this.fsw.options.depth;
6222
+ if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath2)) {
6223
+ if (!target) {
6224
+ await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
6225
+ if (this.fsw.closed)
6226
+ return;
6227
+ }
6228
+ closer = this._watchWithNodeFs(dir, (dirPath, stats2) => {
6229
+ if (stats2 && stats2.mtimeMs === 0)
6230
+ return;
6231
+ this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
6232
+ });
6233
+ }
6234
+ return closer;
6235
+ }
6236
+ /**
6237
+ * Handle added file, directory, or glob pattern.
6238
+ * Delegates call to _handleFile / _handleDir after checks.
6239
+ * @param path to file or ir
6240
+ * @param initialAdd was the file added at watch instantiation?
6241
+ * @param priorWh depth relative to user-supplied path
6242
+ * @param depth Child path actually targeted for watch
6243
+ * @param target Child path actually targeted for watch
6244
+ */
6245
+ async _addToNodeFs(path15, initialAdd, priorWh, depth, target) {
6246
+ const ready = this.fsw._emitReady;
6247
+ if (this.fsw._isIgnored(path15) || this.fsw.closed) {
6248
+ ready();
6249
+ return false;
6250
+ }
6251
+ const wh = this.fsw._getWatchHelpers(path15);
6252
+ if (priorWh) {
6253
+ wh.filterPath = (entry) => priorWh.filterPath(entry);
6254
+ wh.filterDir = (entry) => priorWh.filterDir(entry);
6255
+ }
6256
+ try {
6257
+ const stats = await statMethods[wh.statMethod](wh.watchPath);
6258
+ if (this.fsw.closed)
6259
+ return;
6260
+ if (this.fsw._isIgnored(wh.watchPath, stats)) {
6261
+ ready();
6262
+ return false;
6263
+ }
6264
+ const follow = this.fsw.options.followSymlinks;
6265
+ let closer;
6266
+ if (stats.isDirectory()) {
6267
+ const absPath = sp.resolve(path15);
6268
+ const targetPath = follow ? await (0, import_promises2.realpath)(path15) : path15;
6269
+ if (this.fsw.closed)
6270
+ return;
6271
+ closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
6272
+ if (this.fsw.closed)
6273
+ return;
6274
+ if (absPath !== targetPath && targetPath !== void 0) {
6275
+ this.fsw._symlinkPaths.set(absPath, targetPath);
6276
+ }
6277
+ } else if (stats.isSymbolicLink()) {
6278
+ const targetPath = follow ? await (0, import_promises2.realpath)(path15) : path15;
6279
+ if (this.fsw.closed)
6280
+ return;
6281
+ const parent = sp.dirname(wh.watchPath);
6282
+ this.fsw._getWatchedDir(parent).add(wh.watchPath);
6283
+ this.fsw._emit(EV.ADD, wh.watchPath, stats);
6284
+ closer = await this._handleDir(parent, stats, initialAdd, depth, path15, wh, targetPath);
6285
+ if (this.fsw.closed)
6286
+ return;
6287
+ if (targetPath !== void 0) {
6288
+ this.fsw._symlinkPaths.set(sp.resolve(path15), targetPath);
6289
+ }
6290
+ } else {
6291
+ closer = this._handleFile(wh.watchPath, stats, initialAdd);
6292
+ }
6293
+ ready();
6294
+ if (closer)
6295
+ this.fsw._addPathCloser(path15, closer);
6296
+ return false;
6297
+ } catch (error48) {
6298
+ if (this.fsw._handleError(error48)) {
6299
+ ready();
6300
+ return path15;
6301
+ }
6302
+ }
6303
+ }
6304
+ };
6305
+ }
6306
+ });
6307
+
6308
+ // ../../oss/packages/daemon-core/node_modules/chokidar/index.js
6309
+ function arrify(item) {
6310
+ return Array.isArray(item) ? item : [item];
6311
+ }
6312
+ function createPattern(matcher) {
6313
+ if (typeof matcher === "function")
6314
+ return matcher;
6315
+ if (typeof matcher === "string")
6316
+ return (string4) => matcher === string4;
6317
+ if (matcher instanceof RegExp)
6318
+ return (string4) => matcher.test(string4);
6319
+ if (typeof matcher === "object" && matcher !== null) {
6320
+ return (string4) => {
6321
+ if (matcher.path === string4)
6322
+ return true;
6323
+ if (matcher.recursive) {
6324
+ const relative3 = sp2.relative(matcher.path, string4);
6325
+ if (!relative3) {
6326
+ return false;
6327
+ }
6328
+ return !relative3.startsWith("..") && !sp2.isAbsolute(relative3);
6329
+ }
6330
+ return false;
6331
+ };
6332
+ }
6333
+ return () => false;
6334
+ }
6335
+ function normalizePath(path15) {
6336
+ if (typeof path15 !== "string")
6337
+ throw new Error("string expected");
6338
+ path15 = sp2.normalize(path15);
6339
+ path15 = path15.replace(/\\/g, "/");
6340
+ let prepend = false;
6341
+ if (path15.startsWith("//"))
6342
+ prepend = true;
6343
+ path15 = path15.replace(DOUBLE_SLASH_RE, "/");
6344
+ if (prepend)
6345
+ path15 = "/" + path15;
6346
+ return path15;
6347
+ }
6348
+ function matchPatterns(patterns, testString, stats) {
6349
+ const path15 = normalizePath(testString);
6350
+ for (let index = 0; index < patterns.length; index++) {
6351
+ const pattern = patterns[index];
6352
+ if (pattern(path15, stats)) {
6353
+ return true;
6354
+ }
6355
+ }
6356
+ return false;
6357
+ }
6358
+ function anymatch(matchers, testString) {
6359
+ if (matchers == null) {
6360
+ throw new TypeError("anymatch: specify first argument");
6361
+ }
6362
+ const matchersArray = arrify(matchers);
6363
+ const patterns = matchersArray.map((matcher) => createPattern(matcher));
6364
+ if (testString == null) {
6365
+ return (testString2, stats) => {
6366
+ return matchPatterns(patterns, testString2, stats);
6367
+ };
6368
+ }
6369
+ return matchPatterns(patterns, testString);
6370
+ }
6371
+ function watch(paths, options = {}) {
6372
+ const watcher = new FSWatcher(options);
6373
+ watcher.add(paths);
6374
+ return watcher;
6375
+ }
6376
+ var import_node_events, import_node_fs2, import_promises3, sp2, SLASH, SLASH_SLASH, ONE_DOT, TWO_DOTS, STRING_TYPE, BACK_SLASH_RE, DOUBLE_SLASH_RE, DOT_RE, REPLACER_RE, isMatcherObject, unifyPaths, toUnix, normalizePathToUnix, normalizeIgnored, getAbsolutePath, EMPTY_SET, DirEntry, STAT_METHOD_F, STAT_METHOD_L, WatchHelper, FSWatcher;
6377
+ var init_chokidar = __esm({
6378
+ "../../oss/packages/daemon-core/node_modules/chokidar/index.js"() {
6379
+ "use strict";
6380
+ import_node_events = require("events");
6381
+ import_node_fs2 = require("fs");
6382
+ import_promises3 = require("fs/promises");
6383
+ sp2 = __toESM(require("path"), 1);
6384
+ init_readdirp();
6385
+ init_handler2();
6386
+ SLASH = "/";
6387
+ SLASH_SLASH = "//";
6388
+ ONE_DOT = ".";
6389
+ TWO_DOTS = "..";
6390
+ STRING_TYPE = "string";
6391
+ BACK_SLASH_RE = /\\/g;
6392
+ DOUBLE_SLASH_RE = /\/\//g;
6393
+ DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
6394
+ REPLACER_RE = /^\.[/\\]/;
6395
+ isMatcherObject = (matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp);
6396
+ unifyPaths = (paths_) => {
6397
+ const paths = arrify(paths_).flat();
6398
+ if (!paths.every((p) => typeof p === STRING_TYPE)) {
6399
+ throw new TypeError(`Non-string provided as watch path: ${paths}`);
6400
+ }
6401
+ return paths.map(normalizePathToUnix);
6402
+ };
6403
+ toUnix = (string4) => {
6404
+ let str = string4.replace(BACK_SLASH_RE, SLASH);
6405
+ let prepend = false;
6406
+ if (str.startsWith(SLASH_SLASH)) {
6407
+ prepend = true;
6408
+ }
6409
+ str = str.replace(DOUBLE_SLASH_RE, SLASH);
6410
+ if (prepend) {
6411
+ str = SLASH + str;
6412
+ }
6413
+ return str;
6414
+ };
6415
+ normalizePathToUnix = (path15) => toUnix(sp2.normalize(toUnix(path15)));
6416
+ normalizeIgnored = (cwd = "") => (path15) => {
6417
+ if (typeof path15 === "string") {
6418
+ return normalizePathToUnix(sp2.isAbsolute(path15) ? path15 : sp2.join(cwd, path15));
6419
+ } else {
6420
+ return path15;
6421
+ }
6422
+ };
6423
+ getAbsolutePath = (path15, cwd) => {
6424
+ if (sp2.isAbsolute(path15)) {
6425
+ return path15;
6426
+ }
6427
+ return sp2.join(cwd, path15);
6428
+ };
6429
+ EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set());
6430
+ DirEntry = class {
6431
+ path;
6432
+ _removeWatcher;
6433
+ items;
6434
+ constructor(dir, removeWatcher) {
6435
+ this.path = dir;
6436
+ this._removeWatcher = removeWatcher;
6437
+ this.items = /* @__PURE__ */ new Set();
6438
+ }
6439
+ add(item) {
6440
+ const { items } = this;
6441
+ if (!items)
6442
+ return;
6443
+ if (item !== ONE_DOT && item !== TWO_DOTS)
6444
+ items.add(item);
6445
+ }
6446
+ async remove(item) {
6447
+ const { items } = this;
6448
+ if (!items)
6449
+ return;
6450
+ items.delete(item);
6451
+ if (items.size > 0)
6452
+ return;
6453
+ const dir = this.path;
6454
+ try {
6455
+ await (0, import_promises3.readdir)(dir);
6456
+ } catch (err) {
6457
+ if (this._removeWatcher) {
6458
+ this._removeWatcher(sp2.dirname(dir), sp2.basename(dir));
6459
+ }
6460
+ }
6461
+ }
6462
+ has(item) {
6463
+ const { items } = this;
6464
+ if (!items)
6465
+ return;
6466
+ return items.has(item);
6467
+ }
6468
+ getChildren() {
6469
+ const { items } = this;
6470
+ if (!items)
6471
+ return [];
6472
+ return [...items.values()];
6473
+ }
6474
+ dispose() {
6475
+ this.items.clear();
6476
+ this.path = "";
6477
+ this._removeWatcher = EMPTY_FN;
6478
+ this.items = EMPTY_SET;
6479
+ Object.freeze(this);
6480
+ }
6481
+ };
6482
+ STAT_METHOD_F = "stat";
6483
+ STAT_METHOD_L = "lstat";
6484
+ WatchHelper = class {
6485
+ fsw;
6486
+ path;
6487
+ watchPath;
6488
+ fullWatchPath;
6489
+ dirParts;
6490
+ followSymlinks;
6491
+ statMethod;
6492
+ constructor(path15, follow, fsw) {
6493
+ this.fsw = fsw;
6494
+ const watchPath = path15;
6495
+ this.path = path15 = path15.replace(REPLACER_RE, "");
6496
+ this.watchPath = watchPath;
6497
+ this.fullWatchPath = sp2.resolve(watchPath);
6498
+ this.dirParts = [];
6499
+ this.dirParts.forEach((parts) => {
6500
+ if (parts.length > 1)
6501
+ parts.pop();
6502
+ });
6503
+ this.followSymlinks = follow;
6504
+ this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
6505
+ }
6506
+ entryPath(entry) {
6507
+ return sp2.join(this.watchPath, sp2.relative(this.watchPath, entry.fullPath));
6508
+ }
6509
+ filterPath(entry) {
6510
+ const { stats } = entry;
6511
+ if (stats && stats.isSymbolicLink())
6512
+ return this.filterDir(entry);
6513
+ const resolvedPath = this.entryPath(entry);
6514
+ return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
6515
+ }
6516
+ filterDir(entry) {
6517
+ return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
6518
+ }
6519
+ };
6520
+ FSWatcher = class extends import_node_events.EventEmitter {
6521
+ closed;
6522
+ options;
6523
+ _closers;
6524
+ _ignoredPaths;
6525
+ _throttled;
6526
+ _streams;
6527
+ _symlinkPaths;
6528
+ _watched;
6529
+ _pendingWrites;
6530
+ _pendingUnlinks;
6531
+ _readyCount;
6532
+ _emitReady;
6533
+ _closePromise;
6534
+ _userIgnored;
6535
+ _readyEmitted;
6536
+ _emitRaw;
6537
+ _boundRemove;
6538
+ _nodeFsHandler;
6539
+ // Not indenting methods for history sake; for now.
6540
+ constructor(_opts = {}) {
6541
+ super();
6542
+ this.closed = false;
6543
+ this._closers = /* @__PURE__ */ new Map();
6544
+ this._ignoredPaths = /* @__PURE__ */ new Set();
6545
+ this._throttled = /* @__PURE__ */ new Map();
6546
+ this._streams = /* @__PURE__ */ new Set();
6547
+ this._symlinkPaths = /* @__PURE__ */ new Map();
6548
+ this._watched = /* @__PURE__ */ new Map();
6549
+ this._pendingWrites = /* @__PURE__ */ new Map();
6550
+ this._pendingUnlinks = /* @__PURE__ */ new Map();
6551
+ this._readyCount = 0;
6552
+ this._readyEmitted = false;
6553
+ const awf = _opts.awaitWriteFinish;
6554
+ const DEF_AWF = { stabilityThreshold: 2e3, pollInterval: 100 };
6555
+ const opts = {
6556
+ // Defaults
6557
+ persistent: true,
6558
+ ignoreInitial: false,
6559
+ ignorePermissionErrors: false,
6560
+ interval: 100,
6561
+ binaryInterval: 300,
6562
+ followSymlinks: true,
6563
+ usePolling: false,
6564
+ // useAsync: false,
6565
+ atomic: true,
6566
+ // NOTE: overwritten later (depends on usePolling)
6567
+ ..._opts,
6568
+ // Change format
6569
+ ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
6570
+ awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? { ...DEF_AWF, ...awf } : false
6571
+ };
6572
+ if (isIBMi)
6573
+ opts.usePolling = true;
6574
+ if (opts.atomic === void 0)
6575
+ opts.atomic = !opts.usePolling;
6576
+ const envPoll = process.env.CHOKIDAR_USEPOLLING;
6577
+ if (envPoll !== void 0) {
6578
+ const envLower = envPoll.toLowerCase();
6579
+ if (envLower === "false" || envLower === "0")
6580
+ opts.usePolling = false;
6581
+ else if (envLower === "true" || envLower === "1")
6582
+ opts.usePolling = true;
6583
+ else
6584
+ opts.usePolling = !!envLower;
6585
+ }
6586
+ const envInterval = process.env.CHOKIDAR_INTERVAL;
6587
+ if (envInterval)
6588
+ opts.interval = Number.parseInt(envInterval, 10);
6589
+ let readyCalls = 0;
6590
+ this._emitReady = () => {
6591
+ readyCalls++;
6592
+ if (readyCalls >= this._readyCount) {
6593
+ this._emitReady = EMPTY_FN;
6594
+ this._readyEmitted = true;
6595
+ process.nextTick(() => this.emit(EVENTS.READY));
6596
+ }
6597
+ };
6598
+ this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args);
6599
+ this._boundRemove = this._remove.bind(this);
6600
+ this.options = opts;
6601
+ this._nodeFsHandler = new NodeFsHandler(this);
6602
+ Object.freeze(opts);
6603
+ }
6604
+ _addIgnoredPath(matcher) {
6605
+ if (isMatcherObject(matcher)) {
6606
+ for (const ignored of this._ignoredPaths) {
6607
+ if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) {
6608
+ return;
6609
+ }
6610
+ }
6611
+ }
6612
+ this._ignoredPaths.add(matcher);
6613
+ }
6614
+ _removeIgnoredPath(matcher) {
6615
+ this._ignoredPaths.delete(matcher);
6616
+ if (typeof matcher === "string") {
6617
+ for (const ignored of this._ignoredPaths) {
6618
+ if (isMatcherObject(ignored) && ignored.path === matcher) {
6619
+ this._ignoredPaths.delete(ignored);
6620
+ }
6621
+ }
6622
+ }
6623
+ }
6624
+ // Public methods
6625
+ /**
6626
+ * Adds paths to be watched on an existing FSWatcher instance.
6627
+ * @param paths_ file or file list. Other arguments are unused
6628
+ */
6629
+ add(paths_, _origAdd, _internal) {
6630
+ const { cwd } = this.options;
6631
+ this.closed = false;
6632
+ this._closePromise = void 0;
6633
+ let paths = unifyPaths(paths_);
6634
+ if (cwd) {
6635
+ paths = paths.map((path15) => {
6636
+ const absPath = getAbsolutePath(path15, cwd);
6637
+ return absPath;
6638
+ });
6639
+ }
6640
+ paths.forEach((path15) => {
6641
+ this._removeIgnoredPath(path15);
6642
+ });
6643
+ this._userIgnored = void 0;
6644
+ if (!this._readyCount)
6645
+ this._readyCount = 0;
6646
+ this._readyCount += paths.length;
6647
+ Promise.all(paths.map(async (path15) => {
6648
+ const res = await this._nodeFsHandler._addToNodeFs(path15, !_internal, void 0, 0, _origAdd);
6649
+ if (res)
6650
+ this._emitReady();
6651
+ return res;
6652
+ })).then((results) => {
6653
+ if (this.closed)
6654
+ return;
6655
+ results.forEach((item) => {
6656
+ if (item)
6657
+ this.add(sp2.dirname(item), sp2.basename(_origAdd || item));
6658
+ });
6659
+ });
6660
+ return this;
6661
+ }
6662
+ /**
6663
+ * Close watchers or start ignoring events from specified paths.
6664
+ */
6665
+ unwatch(paths_) {
6666
+ if (this.closed)
6667
+ return this;
6668
+ const paths = unifyPaths(paths_);
6669
+ const { cwd } = this.options;
6670
+ paths.forEach((path15) => {
6671
+ if (!sp2.isAbsolute(path15) && !this._closers.has(path15)) {
6672
+ if (cwd)
6673
+ path15 = sp2.join(cwd, path15);
6674
+ path15 = sp2.resolve(path15);
6675
+ }
6676
+ this._closePath(path15);
6677
+ this._addIgnoredPath(path15);
6678
+ if (this._watched.has(path15)) {
6679
+ this._addIgnoredPath({
6680
+ path: path15,
6681
+ recursive: true
6682
+ });
6683
+ }
6684
+ this._userIgnored = void 0;
6685
+ });
6686
+ return this;
6687
+ }
6688
+ /**
6689
+ * Close watchers and remove all listeners from watched paths.
6690
+ */
6691
+ close() {
6692
+ if (this._closePromise) {
6693
+ return this._closePromise;
6694
+ }
6695
+ this.closed = true;
6696
+ this.removeAllListeners();
6697
+ const closers = [];
6698
+ this._closers.forEach((closerList) => closerList.forEach((closer) => {
6699
+ const promise2 = closer();
6700
+ if (promise2 instanceof Promise)
6701
+ closers.push(promise2);
6702
+ }));
6703
+ this._streams.forEach((stream) => stream.destroy());
6704
+ this._userIgnored = void 0;
6705
+ this._readyCount = 0;
6706
+ this._readyEmitted = false;
6707
+ this._watched.forEach((dirent) => dirent.dispose());
6708
+ this._closers.clear();
6709
+ this._watched.clear();
6710
+ this._streams.clear();
6711
+ this._symlinkPaths.clear();
6712
+ this._throttled.clear();
6713
+ this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve();
6714
+ return this._closePromise;
6715
+ }
6716
+ /**
6717
+ * Expose list of watched paths
6718
+ * @returns for chaining
6719
+ */
6720
+ getWatched() {
6721
+ const watchList = {};
6722
+ this._watched.forEach((entry, dir) => {
6723
+ const key = this.options.cwd ? sp2.relative(this.options.cwd, dir) : dir;
6724
+ const index = key || ONE_DOT;
6725
+ watchList[index] = entry.getChildren().sort();
6726
+ });
6727
+ return watchList;
6728
+ }
6729
+ emitWithAll(event, args) {
6730
+ this.emit(event, ...args);
6731
+ if (event !== EVENTS.ERROR)
6732
+ this.emit(EVENTS.ALL, event, ...args);
6733
+ }
6734
+ // Common helpers
6735
+ // --------------
6736
+ /**
6737
+ * Normalize and emit events.
6738
+ * Calling _emit DOES NOT MEAN emit() would be called!
6739
+ * @param event Type of event
6740
+ * @param path File or directory path
6741
+ * @param stats arguments to be passed with event
6742
+ * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
6743
+ */
6744
+ async _emit(event, path15, stats) {
6745
+ if (this.closed)
6746
+ return;
6747
+ const opts = this.options;
6748
+ if (isWindows)
6749
+ path15 = sp2.normalize(path15);
6750
+ if (opts.cwd)
6751
+ path15 = sp2.relative(opts.cwd, path15);
6752
+ const args = [path15];
6753
+ if (stats != null)
6754
+ args.push(stats);
6755
+ const awf = opts.awaitWriteFinish;
6756
+ let pw;
6757
+ if (awf && (pw = this._pendingWrites.get(path15))) {
6758
+ pw.lastChange = /* @__PURE__ */ new Date();
6759
+ return this;
6760
+ }
6761
+ if (opts.atomic) {
6762
+ if (event === EVENTS.UNLINK) {
6763
+ this._pendingUnlinks.set(path15, [event, ...args]);
6764
+ setTimeout(() => {
6765
+ this._pendingUnlinks.forEach((entry, path16) => {
6766
+ this.emit(...entry);
6767
+ this.emit(EVENTS.ALL, ...entry);
6768
+ this._pendingUnlinks.delete(path16);
6769
+ });
6770
+ }, typeof opts.atomic === "number" ? opts.atomic : 100);
6771
+ return this;
6772
+ }
6773
+ if (event === EVENTS.ADD && this._pendingUnlinks.has(path15)) {
6774
+ event = EVENTS.CHANGE;
6775
+ this._pendingUnlinks.delete(path15);
6776
+ }
6777
+ }
6778
+ if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
6779
+ const awfEmit = (err, stats2) => {
6780
+ if (err) {
6781
+ event = EVENTS.ERROR;
6782
+ args[0] = err;
6783
+ this.emitWithAll(event, args);
6784
+ } else if (stats2) {
6785
+ if (args.length > 1) {
6786
+ args[1] = stats2;
6787
+ } else {
6788
+ args.push(stats2);
6789
+ }
6790
+ this.emitWithAll(event, args);
6791
+ }
6792
+ };
6793
+ this._awaitWriteFinish(path15, awf.stabilityThreshold, event, awfEmit);
6794
+ return this;
6795
+ }
6796
+ if (event === EVENTS.CHANGE) {
6797
+ const isThrottled = !this._throttle(EVENTS.CHANGE, path15, 50);
6798
+ if (isThrottled)
6799
+ return this;
6800
+ }
6801
+ if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
6802
+ const fullPath = opts.cwd ? sp2.join(opts.cwd, path15) : path15;
6803
+ let stats2;
6804
+ try {
6805
+ stats2 = await (0, import_promises3.stat)(fullPath);
6806
+ } catch (err) {
6807
+ }
6808
+ if (!stats2 || this.closed)
6809
+ return;
6810
+ args.push(stats2);
6811
+ }
6812
+ this.emitWithAll(event, args);
6813
+ return this;
6814
+ }
6815
+ /**
6816
+ * Common handler for errors
6817
+ * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
6818
+ */
6819
+ _handleError(error48) {
6820
+ const code = error48 && error48.code;
6821
+ if (error48 && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) {
6822
+ this.emit(EVENTS.ERROR, error48);
6823
+ }
6824
+ return error48 || this.closed;
6825
+ }
6826
+ /**
6827
+ * Helper utility for throttling
6828
+ * @param actionType type being throttled
6829
+ * @param path being acted upon
6830
+ * @param timeout duration of time to suppress duplicate actions
6831
+ * @returns tracking object or false if action should be suppressed
6832
+ */
6833
+ _throttle(actionType, path15, timeout) {
6834
+ if (!this._throttled.has(actionType)) {
6835
+ this._throttled.set(actionType, /* @__PURE__ */ new Map());
6836
+ }
6837
+ const action = this._throttled.get(actionType);
6838
+ if (!action)
6839
+ throw new Error("invalid throttle");
6840
+ const actionPath = action.get(path15);
6841
+ if (actionPath) {
6842
+ actionPath.count++;
6843
+ return false;
6844
+ }
6845
+ let timeoutObject;
6846
+ const clear = () => {
6847
+ const item = action.get(path15);
6848
+ const count = item ? item.count : 0;
6849
+ action.delete(path15);
6850
+ clearTimeout(timeoutObject);
6851
+ if (item)
6852
+ clearTimeout(item.timeoutObject);
6853
+ return count;
6854
+ };
6855
+ timeoutObject = setTimeout(clear, timeout);
6856
+ const thr = { timeoutObject, clear, count: 0 };
6857
+ action.set(path15, thr);
6858
+ return thr;
6859
+ }
6860
+ _incrReadyCount() {
6861
+ return this._readyCount++;
6862
+ }
6863
+ /**
6864
+ * Awaits write operation to finish.
6865
+ * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
6866
+ * @param path being acted upon
6867
+ * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
6868
+ * @param event
6869
+ * @param awfEmit Callback to be called when ready for event to be emitted.
6870
+ */
6871
+ _awaitWriteFinish(path15, threshold, event, awfEmit) {
6872
+ const awf = this.options.awaitWriteFinish;
6873
+ if (typeof awf !== "object")
6874
+ return;
6875
+ const pollInterval = awf.pollInterval;
6876
+ let timeoutHandler;
6877
+ let fullPath = path15;
6878
+ if (this.options.cwd && !sp2.isAbsolute(path15)) {
6879
+ fullPath = sp2.join(this.options.cwd, path15);
6880
+ }
6881
+ const now = /* @__PURE__ */ new Date();
6882
+ const writes = this._pendingWrites;
6883
+ function awaitWriteFinishFn(prevStat) {
6884
+ (0, import_node_fs2.stat)(fullPath, (err, curStat) => {
6885
+ if (err || !writes.has(path15)) {
6886
+ if (err && err.code !== "ENOENT")
6887
+ awfEmit(err);
6888
+ return;
6889
+ }
6890
+ const now2 = Number(/* @__PURE__ */ new Date());
6891
+ if (prevStat && curStat.size !== prevStat.size) {
6892
+ writes.get(path15).lastChange = now2;
6893
+ }
6894
+ const pw = writes.get(path15);
6895
+ const df = now2 - pw.lastChange;
6896
+ if (df >= threshold) {
6897
+ writes.delete(path15);
6898
+ awfEmit(void 0, curStat);
6899
+ } else {
6900
+ timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
6901
+ }
6902
+ });
6903
+ }
6904
+ if (!writes.has(path15)) {
6905
+ writes.set(path15, {
6906
+ lastChange: now,
6907
+ cancelWait: () => {
6908
+ writes.delete(path15);
6909
+ clearTimeout(timeoutHandler);
6910
+ return event;
6911
+ }
6912
+ });
6913
+ timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
6914
+ }
6915
+ }
6916
+ /**
6917
+ * Determines whether user has asked to ignore this path.
6918
+ */
6919
+ _isIgnored(path15, stats) {
6920
+ if (this.options.atomic && DOT_RE.test(path15))
6921
+ return true;
6922
+ if (!this._userIgnored) {
6923
+ const { cwd } = this.options;
6924
+ const ign = this.options.ignored;
6925
+ const ignored = (ign || []).map(normalizeIgnored(cwd));
6926
+ const ignoredPaths = [...this._ignoredPaths];
6927
+ const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];
6928
+ this._userIgnored = anymatch(list, void 0);
6929
+ }
6930
+ return this._userIgnored(path15, stats);
6931
+ }
6932
+ _isntIgnored(path15, stat4) {
6933
+ return !this._isIgnored(path15, stat4);
6934
+ }
6935
+ /**
6936
+ * Provides a set of common helpers and properties relating to symlink handling.
6937
+ * @param path file or directory pattern being watched
6938
+ */
6939
+ _getWatchHelpers(path15) {
6940
+ return new WatchHelper(path15, this.options.followSymlinks, this);
6941
+ }
6942
+ // Directory helpers
6943
+ // -----------------
6944
+ /**
6945
+ * Provides directory tracking objects
6946
+ * @param directory path of the directory
6947
+ */
6948
+ _getWatchedDir(directory) {
6949
+ const dir = sp2.resolve(directory);
6950
+ if (!this._watched.has(dir))
6951
+ this._watched.set(dir, new DirEntry(dir, this._boundRemove));
6952
+ return this._watched.get(dir);
6953
+ }
6954
+ // File helpers
6955
+ // ------------
6956
+ /**
6957
+ * Check for read permissions: https://stackoverflow.com/a/11781404/1358405
6958
+ */
6959
+ _hasReadPermissions(stats) {
6960
+ if (this.options.ignorePermissionErrors)
6961
+ return true;
6962
+ return Boolean(Number(stats.mode) & 256);
6963
+ }
6964
+ /**
6965
+ * Handles emitting unlink events for
6966
+ * files and directories, and via recursion, for
6967
+ * files and directories within directories that are unlinked
6968
+ * @param directory within which the following item is located
6969
+ * @param item base path of item/directory
6970
+ */
6971
+ _remove(directory, item, isDirectory) {
6972
+ const path15 = sp2.join(directory, item);
6973
+ const fullPath = sp2.resolve(path15);
6974
+ isDirectory = isDirectory != null ? isDirectory : this._watched.has(path15) || this._watched.has(fullPath);
6975
+ if (!this._throttle("remove", path15, 100))
6976
+ return;
6977
+ if (!isDirectory && this._watched.size === 1) {
6978
+ this.add(directory, item, true);
6979
+ }
6980
+ const wp = this._getWatchedDir(path15);
6981
+ const nestedDirectoryChildren = wp.getChildren();
6982
+ nestedDirectoryChildren.forEach((nested) => this._remove(path15, nested));
6983
+ const parent = this._getWatchedDir(directory);
6984
+ const wasTracked = parent.has(item);
6985
+ parent.remove(item);
6986
+ if (this._symlinkPaths.has(fullPath)) {
6987
+ this._symlinkPaths.delete(fullPath);
6988
+ }
6989
+ let relPath = path15;
6990
+ if (this.options.cwd)
6991
+ relPath = sp2.relative(this.options.cwd, path15);
6992
+ if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
6993
+ const event = this._pendingWrites.get(relPath).cancelWait();
6994
+ if (event === EVENTS.ADD)
6995
+ return;
6996
+ }
6997
+ this._watched.delete(path15);
6998
+ this._watched.delete(fullPath);
6999
+ const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
7000
+ if (wasTracked && !this._isIgnored(path15))
7001
+ this._emit(eventName, path15);
7002
+ this._closePath(path15);
7003
+ }
7004
+ /**
7005
+ * Closes all watchers for a path
7006
+ */
7007
+ _closePath(path15) {
7008
+ this._closeFile(path15);
7009
+ const dir = sp2.dirname(path15);
7010
+ this._getWatchedDir(dir).remove(sp2.basename(path15));
7011
+ }
7012
+ /**
7013
+ * Closes only file-specific watchers
7014
+ */
7015
+ _closeFile(path15) {
7016
+ const closers = this._closers.get(path15);
7017
+ if (!closers)
7018
+ return;
7019
+ closers.forEach((closer) => closer());
7020
+ this._closers.delete(path15);
7021
+ }
7022
+ _addPathCloser(path15, closer) {
7023
+ if (!closer)
7024
+ return;
7025
+ let list = this._closers.get(path15);
7026
+ if (!list) {
7027
+ list = [];
7028
+ this._closers.set(path15, list);
7029
+ }
7030
+ list.push(closer);
7031
+ }
7032
+ _readdirp(root, opts) {
7033
+ if (this.closed)
7034
+ return;
7035
+ const options = { type: EVENTS.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };
7036
+ let stream = readdirp(root, options);
7037
+ this._streams.add(stream);
7038
+ stream.once(STR_CLOSE, () => {
7039
+ stream = void 0;
7040
+ });
7041
+ stream.once(STR_END, () => {
7042
+ if (stream) {
7043
+ this._streams.delete(stream);
7044
+ stream = void 0;
7045
+ }
7046
+ });
7047
+ return stream;
7048
+ }
7049
+ };
7050
+ }
7051
+ });
7052
+
5304
7053
  // ../../oss/packages/daemon-core/src/providers/provider-loader.ts
5305
7054
  var fs5, path6, os7, ProviderLoader;
5306
7055
  var init_provider_loader = __esm({
@@ -5309,11 +7058,11 @@ var init_provider_loader = __esm({
5309
7058
  fs5 = __toESM(require("fs"));
5310
7059
  path6 = __toESM(require("path"));
5311
7060
  os7 = __toESM(require("os"));
7061
+ init_chokidar();
5312
7062
  init_ide_detector();
5313
7063
  init_logger();
5314
7064
  ProviderLoader = class _ProviderLoader {
5315
7065
  providers = /* @__PURE__ */ new Map();
5316
- builtinDirs;
5317
7066
  userDir;
5318
7067
  upstreamDir;
5319
7068
  disableUpstream;
@@ -5328,36 +7077,31 @@ var init_provider_loader = __esm({
5328
7077
  static GITHUB_TARBALL_URL = "https://github.com/vilmire/adhdev-providers/archive/refs/heads/main.tar.gz";
5329
7078
  static META_FILE = ".meta.json";
5330
7079
  constructor(options) {
5331
- if (options?.builtinDir) {
5332
- this.builtinDirs = Array.isArray(options.builtinDir) ? options.builtinDir : [options.builtinDir];
7080
+ this.logFn = options?.logFn || LOG.forComponent("Provider").asLogFn();
7081
+ const defaultProvidersDir = path6.join(os7.homedir(), ".adhdev", "providers");
7082
+ if (options?.userDir) {
7083
+ this.userDir = options.userDir;
7084
+ this.log(`Config 'providerDir' applied: ${this.userDir}`);
5333
7085
  } else {
5334
- this.builtinDirs = [];
7086
+ const localRepoPath = path6.resolve(__dirname, "../../../../../adhdev-providers");
7087
+ if (fs5.existsSync(localRepoPath)) {
7088
+ this.userDir = localRepoPath;
7089
+ this.log(`Auto-detected local public repository: ${this.userDir} (Dev workspace speedup)`);
7090
+ } else {
7091
+ this.userDir = defaultProvidersDir;
7092
+ this.log(`Using default user providers directory: ${this.userDir}`);
7093
+ }
5335
7094
  }
5336
- const defaultProvidersDir = path6.join(os7.homedir(), ".adhdev", "providers");
5337
- this.userDir = options?.userDir || defaultProvidersDir;
5338
7095
  this.upstreamDir = path6.join(defaultProvidersDir, ".upstream");
5339
7096
  this.disableUpstream = options?.disableUpstream ?? false;
5340
- this.logFn = options?.logFn || LOG.forComponent("Provider").asLogFn();
5341
7097
  }
5342
7098
  log(msg) {
5343
7099
  this.logFn(`[ProviderLoader] ${msg}`);
5344
7100
  }
5345
7101
  // ─── Public API ────────────────────────────────
5346
7102
  /**
5347
- * Ordered builtin roots used for local fallback/reference data.
5348
- */
5349
- getBuiltinDirs() {
5350
- return [...this.builtinDirs];
5351
- }
5352
- /**
5353
- * Primary builtin root used for local scaffolding/reference flows.
5354
- */
5355
- getPrimaryBuiltinDir() {
5356
- return this.builtinDirs[0];
5357
- }
5358
- /**
5359
- * User override root (~/.adhdev/providers by default).
5360
- */
7103
+ * User override root (~/.adhdev/providers by default).
7104
+ */
5361
7105
  getUserDir() {
5362
7106
  return this.userDir;
5363
7107
  }
@@ -5368,11 +7112,11 @@ var init_provider_loader = __esm({
5368
7112
  return this.upstreamDir;
5369
7113
  }
5370
7114
  /**
5371
- * Provider search order for on-disk lookups.
5372
- * Highest-priority editable overrides come first.
5373
- */
7115
+ * Provider search order for on-disk lookups.
7116
+ * Highest-priority editable overrides come first.
7117
+ */
5374
7118
  getProviderRoots() {
5375
- return [this.userDir, this.upstreamDir, ...this.builtinDirs];
7119
+ return [this.userDir, this.upstreamDir];
5376
7120
  }
5377
7121
  /**
5378
7122
  * Canonical provider directory shape for a given root.
@@ -5393,16 +7137,9 @@ var init_provider_loader = __esm({
5393
7137
  return this.getProviderDir(this.upstreamDir, category, type);
5394
7138
  }
5395
7139
  /**
5396
- * Canonical builtin directory for a provider.
7140
+ * Find the on-disk directory for a provider by type.
7141
+ * Search order: user override → upstream.
5397
7142
  */
5398
- getBuiltinProviderDir(category, type) {
5399
- const builtinRoot = this.getPrimaryBuiltinDir();
5400
- return builtinRoot ? this.getProviderDir(builtinRoot, category, type) : "";
5401
- }
5402
- /**
5403
- * Find the on-disk directory for a provider by type.
5404
- * Search order: user override → upstream → builtin fallback.
5405
- */
5406
7143
  findProviderDir(type) {
5407
7144
  return this.findProviderDirInternal(type);
5408
7145
  }
@@ -5767,13 +7504,12 @@ var init_provider_loader = __esm({
5767
7504
  }
5768
7505
  }
5769
7506
  const result = this.buildScriptWrappersFromDir(dir);
5770
- this.log(` [loadScriptsFromDir] ${type}: built wrappers from ${dir} (${Object.keys(result).length} scripts)`);
5771
7507
  this.scriptsCache.set(dir, result);
5772
7508
  return result;
5773
7509
  }
5774
7510
  /**
5775
- * Hot-reload: start watching for file changes
5776
- */
7511
+ * Hot-reload: start watching for file changes
7512
+ */
5777
7513
  watch() {
5778
7514
  this.stopWatch();
5779
7515
  const watchDir = (dir) => {
@@ -5785,18 +7521,27 @@ var init_provider_loader = __esm({
5785
7521
  }
5786
7522
  }
5787
7523
  try {
5788
- const watcher = fs5.watch(dir, { recursive: true }, (event, filename) => {
5789
- if (filename?.endsWith(".js") || filename?.endsWith(".json")) {
5790
- this.log(`File changed: ${filename}, reloading...`);
5791
- this.loadAll();
5792
- }
7524
+ const watcher = watch(dir, {
7525
+ ignored: /(^|[\/\\])\.\./,
7526
+ // ignore dotfiles
7527
+ persistent: true,
7528
+ ignoreInitial: true,
7529
+ awaitWriteFinish: { stabilityThreshold: 200, pollInterval: 50 }
5793
7530
  });
7531
+ const handleChange = (filePath) => {
7532
+ if (filePath.endsWith(".js") || filePath.endsWith(".json")) {
7533
+ this.log(`File changed: ${path6.basename(filePath)}, reloading...`);
7534
+ this.reload();
7535
+ }
7536
+ };
7537
+ watcher.on("add", handleChange).on("change", handleChange).on("unlink", handleChange);
7538
+ watcher.on("error", (err) => this.log(`Watch error: ${err.message}`));
5794
7539
  this.watchers.push(watcher);
7540
+ this.log(`Hot-reload watcher active: ${dir}`);
5795
7541
  } catch (e) {
5796
7542
  this.log(`Watch failed for ${dir}: ${e.message}`);
5797
7543
  }
5798
7544
  };
5799
- this.builtinDirs.forEach((dir) => watchDir(dir));
5800
7545
  watchDir(this.userDir);
5801
7546
  }
5802
7547
  /**
@@ -5857,7 +7602,7 @@ var init_provider_loader = __esm({
5857
7602
  return { updated: false };
5858
7603
  }
5859
7604
  try {
5860
- const etag = await new Promise((resolve7, reject) => {
7605
+ const etag = await new Promise((resolve10, reject) => {
5861
7606
  const options = {
5862
7607
  method: "HEAD",
5863
7608
  hostname: "github.com",
@@ -5875,7 +7620,7 @@ var init_provider_loader = __esm({
5875
7620
  headers: { "User-Agent": "adhdev-launcher" },
5876
7621
  timeout: 1e4
5877
7622
  }, (res2) => {
5878
- resolve7(res2.headers.etag || res2.headers["last-modified"] || "");
7623
+ resolve10(res2.headers.etag || res2.headers["last-modified"] || "");
5879
7624
  });
5880
7625
  req2.on("error", reject);
5881
7626
  req2.on("timeout", () => {
@@ -5884,7 +7629,7 @@ var init_provider_loader = __esm({
5884
7629
  });
5885
7630
  req2.end();
5886
7631
  } else {
5887
- resolve7(res.headers.etag || res.headers["last-modified"] || "");
7632
+ resolve10(res.headers.etag || res.headers["last-modified"] || "");
5888
7633
  }
5889
7634
  });
5890
7635
  req.on("error", reject);
@@ -5948,7 +7693,7 @@ var init_provider_loader = __esm({
5948
7693
  downloadFile(url2, destPath) {
5949
7694
  const https = require("https");
5950
7695
  const http3 = require("http");
5951
- return new Promise((resolve7, reject) => {
7696
+ return new Promise((resolve10, reject) => {
5952
7697
  const doRequest = (reqUrl, redirectCount = 0) => {
5953
7698
  if (redirectCount > 5) {
5954
7699
  reject(new Error("Too many redirects"));
@@ -5968,7 +7713,7 @@ var init_provider_loader = __esm({
5968
7713
  res.pipe(ws2);
5969
7714
  ws2.on("finish", () => {
5970
7715
  ws2.close();
5971
- resolve7();
7716
+ resolve10();
5972
7717
  });
5973
7718
  ws2.on("error", reject);
5974
7719
  });
@@ -6240,8 +7985,8 @@ var init_provider_loader = __esm({
6240
7985
  const existed = this.providers.has(mod.type);
6241
7986
  this.providers.set(mod.type, mod);
6242
7987
  count++;
6243
- const source = d.startsWith(this.userDir) && !d.includes(".upstream") ? "user" : d.startsWith(this.upstreamDir) ? "upstream" : "builtin";
6244
- const overrideWarning = existed && source === "user" ? " \u26A0 OVERRIDES builtin/upstream" : "";
7988
+ const source = d.startsWith(this.userDir) && !d.includes(".upstream") ? "user" : "upstream";
7989
+ const overrideWarning = existed && source === "user" ? " \u26A0 OVERRIDES upstream" : "";
6245
7990
  this.log(` ${existed ? "\u{1F504}" : "\u2705"} ${mod.type} (${mod.category}) \u2014 ${mod.name} [${source}]${overrideWarning}`);
6246
7991
  }
6247
7992
  } catch (e) {
@@ -6288,9 +8033,9 @@ var init_provider_loader = __esm({
6288
8033
  }
6289
8034
  }
6290
8035
  compareVersions(a, b2) {
6291
- const normalize2 = (v2) => v2.split(/[-_+]/)[0].split(".").map((x) => parseInt(x, 10) || 0);
6292
- const pa2 = normalize2(a);
6293
- const pb = normalize2(b2);
8036
+ const normalize3 = (v2) => v2.split(/[-_+]/)[0].split(".").map((x) => parseInt(x, 10) || 0);
8037
+ const pa2 = normalize3(a);
8038
+ const pb = normalize3(b2);
6294
8039
  for (let i = 0; i < Math.max(pa2.length, pb.length); i++) {
6295
8040
  const va2 = pa2[i] || 0;
6296
8041
  const vb = pb[i] || 0;
@@ -6334,17 +8079,17 @@ async function findFreePort(ports) {
6334
8079
  throw new Error("No free port found");
6335
8080
  }
6336
8081
  function checkPortFree(port) {
6337
- return new Promise((resolve7) => {
8082
+ return new Promise((resolve10) => {
6338
8083
  const server = net.createServer();
6339
8084
  server.unref();
6340
- server.on("error", () => resolve7(false));
8085
+ server.on("error", () => resolve10(false));
6341
8086
  server.listen(port, "127.0.0.1", () => {
6342
- server.close(() => resolve7(true));
8087
+ server.close(() => resolve10(true));
6343
8088
  });
6344
8089
  });
6345
8090
  }
6346
8091
  async function isCdpActive(port) {
6347
- return new Promise((resolve7) => {
8092
+ return new Promise((resolve10) => {
6348
8093
  const req = require("http").get(`http://127.0.0.1:${port}/json/version`, {
6349
8094
  timeout: 2e3
6350
8095
  }, (res) => {
@@ -6353,16 +8098,16 @@ async function isCdpActive(port) {
6353
8098
  res.on("end", () => {
6354
8099
  try {
6355
8100
  const info = JSON.parse(data);
6356
- resolve7(!!info["WebKit-Version"] || !!info["Browser"]);
8101
+ resolve10(!!info["WebKit-Version"] || !!info["Browser"]);
6357
8102
  } catch {
6358
- resolve7(false);
8103
+ resolve10(false);
6359
8104
  }
6360
8105
  });
6361
8106
  });
6362
- req.on("error", () => resolve7(false));
8107
+ req.on("error", () => resolve10(false));
6363
8108
  req.on("timeout", () => {
6364
8109
  req.destroy();
6365
- resolve7(false);
8110
+ resolve10(false);
6366
8111
  });
6367
8112
  });
6368
8113
  }
@@ -6710,8 +8455,8 @@ function cleanOldFiles() {
6710
8455
  }
6711
8456
  function checkSize() {
6712
8457
  try {
6713
- const stat = fs6.statSync(currentFile);
6714
- if (stat.size > MAX_FILE_SIZE) {
8458
+ const stat4 = fs6.statSync(currentFile);
8459
+ if (stat4.size > MAX_FILE_SIZE) {
6715
8460
  const backup = currentFile.replace(".jsonl", ".1.jsonl");
6716
8461
  try {
6717
8462
  fs6.unlinkSync(backup);
@@ -16719,9 +18464,9 @@ var init_provider_cli_adapter = __esm({
16719
18464
  const platformArch = `${os12.platform()}-${os12.arch()}`;
16720
18465
  const helper = path9.join(ptyDir, "prebuilds", platformArch, "spawn-helper");
16721
18466
  if (fs13.existsSync(helper)) {
16722
- const stat = fs13.statSync(helper);
16723
- if (!(stat.mode & 73)) {
16724
- fs13.chmodSync(helper, stat.mode | 493);
18467
+ const stat4 = fs13.statSync(helper);
18468
+ if (!(stat4.mode & 73)) {
18469
+ fs13.chmodSync(helper, stat4.mode | 493);
16725
18470
  LOG.info("CLI", "[node-pty] Fixed spawn-helper permissions");
16726
18471
  }
16727
18472
  }
@@ -16784,6 +18529,8 @@ var init_provider_cli_adapter = __esm({
16784
18529
  spawnAt = 0;
16785
18530
  // PTY I/O
16786
18531
  onPtyDataCallback = null;
18532
+ pendingOutputParseBuffer = "";
18533
+ pendingOutputParseTimer = null;
16787
18534
  ptyOutputBuffer = "";
16788
18535
  ptyOutputFlushTimer = null;
16789
18536
  // Server log forwarding
@@ -16879,6 +18626,16 @@ var init_provider_cli_adapter = __esm({
16879
18626
  setOnPtyData(callback) {
16880
18627
  this.onPtyDataCallback = callback;
16881
18628
  }
18629
+ flushPendingOutputParse() {
18630
+ if (this.pendingOutputParseTimer) {
18631
+ clearTimeout(this.pendingOutputParseTimer);
18632
+ this.pendingOutputParseTimer = null;
18633
+ }
18634
+ if (!this.pendingOutputParseBuffer) return;
18635
+ const rawData = this.pendingOutputParseBuffer;
18636
+ this.pendingOutputParseBuffer = "";
18637
+ this.handleOutput(rawData);
18638
+ }
16882
18639
  async spawn() {
16883
18640
  if (this.ptyProcess) return;
16884
18641
  if (!pty) throw new Error("node-pty is not installed");
@@ -16927,7 +18684,17 @@ var init_provider_cli_adapter = __esm({
16927
18684
  }
16928
18685
  }
16929
18686
  this.ptyProcess.onData((data) => {
16930
- this.handleOutput(data);
18687
+ if (Date.now() < this.resizeSuppressUntil) return;
18688
+ if (data.includes("\x1B[6n") || data.includes("\x1B[?6n")) {
18689
+ this.ptyProcess?.write("\x1B[1;1R");
18690
+ }
18691
+ this.pendingOutputParseBuffer += data;
18692
+ if (!this.pendingOutputParseTimer) {
18693
+ this.pendingOutputParseTimer = setTimeout(() => {
18694
+ this.pendingOutputParseTimer = null;
18695
+ this.flushPendingOutputParse();
18696
+ }, this.timeouts.ptyFlush);
18697
+ }
16931
18698
  if (this.onPtyDataCallback) {
16932
18699
  this.ptyOutputBuffer += data;
16933
18700
  if (!this.ptyOutputFlushTimer) {
@@ -16943,6 +18710,7 @@ var init_provider_cli_adapter = __esm({
16943
18710
  });
16944
18711
  this.ptyProcess.onExit(({ exitCode }) => {
16945
18712
  LOG.info("CLI", `[${this.cliType}] Exit code ${exitCode}`);
18713
+ this.flushPendingOutputParse();
16946
18714
  this.ptyProcess = null;
16947
18715
  this.setStatus("stopped", "pty_exit");
16948
18716
  this.ready = false;
@@ -16962,10 +18730,6 @@ var init_provider_cli_adapter = __esm({
16962
18730
  }
16963
18731
  // ─── Output Handling ────────────────────────────
16964
18732
  handleOutput(rawData) {
16965
- if (Date.now() < this.resizeSuppressUntil) return;
16966
- if (rawData.includes("\x1B[6n") || rawData.includes("\x1B[?6n")) {
16967
- this.ptyProcess?.write("\x1B[1;1R");
16968
- }
16969
18733
  this.terminalScreen.write(rawData);
16970
18734
  this.terminalHistory = mergeTerminalHistory(this.terminalHistory, this.terminalScreen.getText());
16971
18735
  const cleanData = stripAnsi(rawData);
@@ -17316,7 +19080,7 @@ ${data.message || ""}`.trim();
17316
19080
  if (this.startupParseGate) {
17317
19081
  const deadline = Date.now() + 1e4;
17318
19082
  while (this.startupParseGate && Date.now() < deadline) {
17319
- await new Promise((resolve7) => setTimeout(resolve7, 50));
19083
+ await new Promise((resolve10) => setTimeout(resolve10, 50));
17320
19084
  }
17321
19085
  }
17322
19086
  if (!this.ready) throw new Error(`${this.cliName} not ready (status: ${this.currentStatus})`);
@@ -17453,6 +19217,16 @@ ${data.message || ""}`.trim();
17453
19217
  clearTimeout(this.submitRetryTimer);
17454
19218
  this.submitRetryTimer = null;
17455
19219
  }
19220
+ if (this.pendingOutputParseTimer) {
19221
+ clearTimeout(this.pendingOutputParseTimer);
19222
+ this.pendingOutputParseTimer = null;
19223
+ }
19224
+ this.pendingOutputParseBuffer = "";
19225
+ if (this.ptyOutputFlushTimer) {
19226
+ clearTimeout(this.ptyOutputFlushTimer);
19227
+ this.ptyOutputFlushTimer = null;
19228
+ }
19229
+ this.ptyOutputBuffer = "";
17456
19230
  if (this.ptyProcess) {
17457
19231
  this.ptyProcess.write("");
17458
19232
  setTimeout(() => {
@@ -17478,6 +19252,16 @@ ${data.message || ""}`.trim();
17478
19252
  this.currentTurnScope = null;
17479
19253
  this.submitRetryUsed = false;
17480
19254
  this.submitRetryPromptSnippet = "";
19255
+ if (this.pendingOutputParseTimer) {
19256
+ clearTimeout(this.pendingOutputParseTimer);
19257
+ this.pendingOutputParseTimer = null;
19258
+ }
19259
+ this.pendingOutputParseBuffer = "";
19260
+ if (this.ptyOutputFlushTimer) {
19261
+ clearTimeout(this.ptyOutputFlushTimer);
19262
+ this.ptyOutputFlushTimer = null;
19263
+ }
19264
+ this.ptyOutputBuffer = "";
17481
19265
  this.terminalScreen.reset();
17482
19266
  this.onStatusChange?.();
17483
19267
  }
@@ -17555,6 +19339,8 @@ ${data.message || ""}`.trim();
17555
19339
  scriptNames: Object.keys(this.cliScripts).filter((k) => typeof this.cliScripts[k] === "function"),
17556
19340
  statusHistory: this.statusHistory.slice(-30),
17557
19341
  timeouts: this.timeouts,
19342
+ pendingOutputParseBufferLength: this.pendingOutputParseBuffer.length,
19343
+ pendingOutputParseScheduled: !!this.pendingOutputParseTimer,
17558
19344
  ptyAlive: !!this.ptyProcess
17559
19345
  };
17560
19346
  }
@@ -33859,8 +35645,8 @@ var init_acp = __esm({
33859
35645
  this.#requestHandler = requestHandler;
33860
35646
  this.#notificationHandler = notificationHandler;
33861
35647
  this.#stream = stream;
33862
- this.#closedPromise = new Promise((resolve7) => {
33863
- this.#abortController.signal.addEventListener("abort", () => resolve7());
35648
+ this.#closedPromise = new Promise((resolve10) => {
35649
+ this.#abortController.signal.addEventListener("abort", () => resolve10());
33864
35650
  });
33865
35651
  this.#receive();
33866
35652
  }
@@ -34009,8 +35795,8 @@ var init_acp = __esm({
34009
35795
  }
34010
35796
  async sendRequest(method, params) {
34011
35797
  const id = this.#nextRequestId++;
34012
- const responsePromise = new Promise((resolve7, reject) => {
34013
- this.#pendingResponses.set(id, { resolve: resolve7, reject });
35798
+ const responsePromise = new Promise((resolve10, reject) => {
35799
+ this.#pendingResponses.set(id, { resolve: resolve10, reject });
34014
35800
  });
34015
35801
  await this.#sendMessage({ jsonrpc: "2.0", id, method, params });
34016
35802
  return responsePromise;
@@ -34542,13 +36328,13 @@ var init_acp_provider_instance = __esm({
34542
36328
  }
34543
36329
  this.currentStatus = "waiting_approval";
34544
36330
  this.detectStatusTransition();
34545
- const approved = await new Promise((resolve7) => {
34546
- this.permissionResolvers.push(resolve7);
36331
+ const approved = await new Promise((resolve10) => {
36332
+ this.permissionResolvers.push(resolve10);
34547
36333
  setTimeout(() => {
34548
- const idx = this.permissionResolvers.indexOf(resolve7);
36334
+ const idx = this.permissionResolvers.indexOf(resolve10);
34549
36335
  if (idx >= 0) {
34550
36336
  this.permissionResolvers.splice(idx, 1);
34551
- resolve7(false);
36337
+ resolve10(false);
34552
36338
  }
34553
36339
  }, 3e5);
34554
36340
  });
@@ -36741,15 +38527,15 @@ var init_dev_server = __esm({
36741
38527
  this.json(res, 500, { error: e.message });
36742
38528
  }
36743
38529
  });
36744
- return new Promise((resolve7, reject) => {
38530
+ return new Promise((resolve10, reject) => {
36745
38531
  this.server.listen(port, "127.0.0.1", () => {
36746
38532
  this.log(`Dev server listening on http://127.0.0.1:${port}`);
36747
- resolve7();
38533
+ resolve10();
36748
38534
  });
36749
38535
  this.server.on("error", (e) => {
36750
38536
  if (e.code === "EADDRINUSE") {
36751
38537
  this.log(`Port ${port} in use, skipping dev server`);
36752
- resolve7();
38538
+ resolve10();
36753
38539
  } else {
36754
38540
  reject(e);
36755
38541
  }
@@ -36832,20 +38618,20 @@ var init_dev_server = __esm({
36832
38618
  child.stderr?.on("data", (d) => {
36833
38619
  stderr += d.toString().slice(0, 2e3);
36834
38620
  });
36835
- await new Promise((resolve7) => {
38621
+ await new Promise((resolve10) => {
36836
38622
  const timer = setTimeout(() => {
36837
38623
  child.kill();
36838
- resolve7();
38624
+ resolve10();
36839
38625
  }, 3e3);
36840
38626
  child.on("exit", () => {
36841
38627
  clearTimeout(timer);
36842
- resolve7();
38628
+ resolve10();
36843
38629
  });
36844
38630
  child.stdout?.once("data", () => {
36845
38631
  setTimeout(() => {
36846
38632
  child.kill();
36847
38633
  clearTimeout(timer);
36848
- resolve7();
38634
+ resolve10();
36849
38635
  }, 500);
36850
38636
  });
36851
38637
  });
@@ -37272,8 +39058,8 @@ var init_dev_server = __esm({
37272
39058
  files.push({ path: rel, size: 0, type: "dir" });
37273
39059
  scan(path12.join(d, entry.name), rel);
37274
39060
  } else {
37275
- const stat = fs10.statSync(path12.join(d, entry.name));
37276
- files.push({ path: rel, size: stat.size, type: "file" });
39061
+ const stat4 = fs10.statSync(path12.join(d, entry.name));
39062
+ files.push({ path: rel, size: stat4.size, type: "file" });
37277
39063
  }
37278
39064
  }
37279
39065
  } catch {
@@ -37589,14 +39375,14 @@ var init_dev_server = __esm({
37589
39375
  child.stderr?.on("data", (d) => {
37590
39376
  stderr += d.toString();
37591
39377
  });
37592
- await new Promise((resolve7) => {
39378
+ await new Promise((resolve10) => {
37593
39379
  const timer = setTimeout(() => {
37594
39380
  child.kill();
37595
- resolve7();
39381
+ resolve10();
37596
39382
  }, timeout);
37597
39383
  child.on("exit", () => {
37598
39384
  clearTimeout(timer);
37599
- resolve7();
39385
+ resolve10();
37600
39386
  });
37601
39387
  });
37602
39388
  const elapsed = Date.now() - start;
@@ -38440,25 +40226,63 @@ var init_dev_server = __esm({
38440
40226
  const ref = this.providerLoader.resolve(desired) || this.providerLoader.getMeta(desired);
38441
40227
  if (ref?.category === category) return desired;
38442
40228
  const all = this.providerLoader.getAll();
38443
- const fallback = all.find((p) => p.category === category && p.type !== targetType);
40229
+ const fallback = all.filter((p) => p.category === category && p.type !== targetType).sort((a, b2) => String(a.type || "").localeCompare(String(b2.type || ""), void 0, { numeric: true, sensitivity: "base" }))[0];
38444
40230
  return fallback?.type || null;
38445
40231
  }
38446
- loadAutoImplReferenceScripts(category, referenceType) {
38447
- if (!referenceType) return {};
38448
- const refDir = this.providerLoader.getUpstreamProviderDir(category, referenceType);
38449
- if (!fs10.existsSync(refDir)) return {};
38450
- const referenceScripts = {};
38451
- const scriptsDir = path12.join(refDir, "scripts");
38452
- if (!fs10.existsSync(scriptsDir)) return referenceScripts;
40232
+ getLatestScriptVersionDir(scriptsDir) {
40233
+ if (!fs10.existsSync(scriptsDir)) return null;
38453
40234
  const versions = fs10.readdirSync(scriptsDir).filter((d) => {
38454
40235
  try {
38455
40236
  return fs10.statSync(path12.join(scriptsDir, d)).isDirectory();
38456
40237
  } catch {
38457
40238
  return false;
38458
40239
  }
38459
- }).sort().reverse();
38460
- if (versions.length === 0) return referenceScripts;
38461
- const latestDir = path12.join(scriptsDir, versions[0]);
40240
+ }).sort((a, b2) => b2.localeCompare(a, void 0, { numeric: true, sensitivity: "base" }));
40241
+ if (versions.length === 0) return null;
40242
+ return path12.join(scriptsDir, versions[0]);
40243
+ }
40244
+ resolveAutoImplWritableProviderDir(category, type, requestedDir) {
40245
+ const canonicalUserDir = path12.resolve(this.providerLoader.getUserProviderDir(category, type));
40246
+ const desiredDir = requestedDir ? path12.resolve(requestedDir) : canonicalUserDir;
40247
+ if (desiredDir !== canonicalUserDir) {
40248
+ return null;
40249
+ }
40250
+ const userRoot = path12.resolve(this.providerLoader.getUserDir());
40251
+ if (desiredDir !== userRoot && !desiredDir.startsWith(`${userRoot}${path12.sep}`)) {
40252
+ return null;
40253
+ }
40254
+ const sourceDir = this.findProviderDir(type);
40255
+ if (!sourceDir) {
40256
+ return null;
40257
+ }
40258
+ if (!fs10.existsSync(desiredDir)) {
40259
+ fs10.mkdirSync(path12.dirname(desiredDir), { recursive: true });
40260
+ fs10.cpSync(sourceDir, desiredDir, { recursive: true });
40261
+ this.log(`Auto-implement writable copy created: ${desiredDir}`);
40262
+ }
40263
+ const providerJson = path12.join(desiredDir, "provider.json");
40264
+ if (!fs10.existsSync(providerJson)) {
40265
+ return null;
40266
+ }
40267
+ try {
40268
+ const providerData = JSON.parse(fs10.readFileSync(providerJson, "utf-8"));
40269
+ if (providerData.disableUpstream !== true) {
40270
+ providerData.disableUpstream = true;
40271
+ fs10.writeFileSync(providerJson, JSON.stringify(providerData, null, 2));
40272
+ }
40273
+ } catch {
40274
+ return null;
40275
+ }
40276
+ return desiredDir;
40277
+ }
40278
+ loadAutoImplReferenceScripts(referenceType) {
40279
+ if (!referenceType) return {};
40280
+ const refDir = this.findProviderDir(referenceType);
40281
+ if (!refDir || !fs10.existsSync(refDir)) return {};
40282
+ const referenceScripts = {};
40283
+ const scriptsDir = path12.join(refDir, "scripts");
40284
+ const latestDir = this.getLatestScriptVersionDir(scriptsDir);
40285
+ if (!latestDir) return referenceScripts;
38462
40286
  for (const file2 of fs10.readdirSync(latestDir)) {
38463
40287
  if (!file2.endsWith(".js")) continue;
38464
40288
  try {
@@ -38470,7 +40294,7 @@ var init_dev_server = __esm({
38470
40294
  }
38471
40295
  async handleAutoImplement(type, req, res) {
38472
40296
  const body = await this.readBody(req);
38473
- const { agent = "claude-cli", functions, reference = "antigravity", model, comment } = body;
40297
+ const { agent = "claude-cli", functions, reference, model, comment, providerDir: requestedProviderDir } = body;
38474
40298
  if (!functions || !Array.isArray(functions) || functions.length === 0) {
38475
40299
  this.json(res, 400, { error: 'functions[] is required (e.g. ["readChat", "sendMessage"])' });
38476
40300
  return;
@@ -38484,9 +40308,11 @@ var init_dev_server = __esm({
38484
40308
  this.json(res, 404, { error: `Provider not found: ${type}` });
38485
40309
  return;
38486
40310
  }
38487
- const providerDir = this.findProviderDir(type);
40311
+ const providerDir = this.resolveAutoImplWritableProviderDir(provider.category, type, requestedProviderDir);
38488
40312
  if (!providerDir) {
38489
- this.json(res, 404, { error: `Provider directory not found: ${type}` });
40313
+ this.json(res, 409, {
40314
+ error: `Auto-implement only writes to the canonical user provider directory for '${type}'.`
40315
+ });
38490
40316
  return;
38491
40317
  }
38492
40318
  try {
@@ -38508,7 +40334,7 @@ var init_dev_server = __esm({
38508
40334
  message: `Loading reference script (${resolvedReference || "none"})...`
38509
40335
  }
38510
40336
  });
38511
- const referenceScripts = this.loadAutoImplReferenceScripts(provider.category, resolvedReference);
40337
+ const referenceScripts = this.loadAutoImplReferenceScripts(resolvedReference);
38512
40338
  const prompt = this.buildAutoImplPrompt(type, provider, providerDir, functions, domContext, referenceScripts, comment, resolvedReference);
38513
40339
  const tmpDir = path12.join(os15.tmpdir(), "adhdev-autoimpl");
38514
40340
  if (!fs10.existsSync(tmpDir)) fs10.mkdirSync(tmpDir, { recursive: true });
@@ -38530,7 +40356,7 @@ var init_dev_server = __esm({
38530
40356
  this.sendAutoImplSSE({ event: "progress", data: { function: "_init", status: "spawning", message: `Spawning ACP agent: ${spawn3.command} ${(spawn3.args || []).join(" ")}` } });
38531
40357
  this.autoImplStatus = { running: true, type, progress: [] };
38532
40358
  const { ClientSideConnection: ClientSideConnection2, ndJsonStream: ndJsonStream2, PROTOCOL_VERSION: PROTOCOL_VERSION2 } = await Promise.resolve().then(() => (init_acp(), acp_exports));
38533
- const { Readable: Readable2, Writable: Writable2 } = await import("stream");
40359
+ const { Readable: Readable3, Writable: Writable2 } = await import("stream");
38534
40360
  const { spawn: spawnFn2 } = await import("child_process");
38535
40361
  const acpArgs = [...spawn3.args || []];
38536
40362
  if (model) {
@@ -38549,7 +40375,7 @@ var init_dev_server = __esm({
38549
40375
  this.sendAutoImplSSE({ event: "output", data: { chunk, stream: "stderr" } });
38550
40376
  });
38551
40377
  const webStdin = Writable2.toWeb(child2.stdin);
38552
- const webStdout = Readable2.toWeb(child2.stdout);
40378
+ const webStdout = Readable3.toWeb(child2.stdout);
38553
40379
  const stream = ndJsonStream2(webStdin, webStdout);
38554
40380
  const connection = new ClientSideConnection2((_agent) => ({
38555
40381
  // Auto-approve all tool calls for auto-implement
@@ -38864,29 +40690,20 @@ var init_dev_server = __esm({
38864
40690
  lines.push("These are the files you need to EDIT. They contain TODO stubs \u2014 replace them with working implementations.");
38865
40691
  lines.push("");
38866
40692
  const scriptsDir = path12.join(providerDir, "scripts");
38867
- if (fs10.existsSync(scriptsDir)) {
38868
- const versions = fs10.readdirSync(scriptsDir).filter((d) => {
38869
- try {
38870
- return fs10.statSync(path12.join(scriptsDir, d)).isDirectory();
38871
- } catch {
38872
- return false;
38873
- }
38874
- }).sort().reverse();
38875
- if (versions.length > 0) {
38876
- const vDir = path12.join(scriptsDir, versions[0]);
38877
- lines.push(`Scripts version directory: \`${vDir}\``);
38878
- lines.push("");
38879
- for (const file2 of fs10.readdirSync(vDir)) {
38880
- if (file2.endsWith(".js")) {
38881
- try {
38882
- const content = fs10.readFileSync(path12.join(vDir, file2), "utf-8");
38883
- lines.push(`### \`${file2}\``);
38884
- lines.push("```javascript");
38885
- lines.push(content);
38886
- lines.push("```");
38887
- lines.push("");
38888
- } catch {
38889
- }
40693
+ const latestScriptsDir = this.getLatestScriptVersionDir(scriptsDir);
40694
+ if (latestScriptsDir) {
40695
+ lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
40696
+ lines.push("");
40697
+ for (const file2 of fs10.readdirSync(latestScriptsDir)) {
40698
+ if (file2.endsWith(".js")) {
40699
+ try {
40700
+ const content = fs10.readFileSync(path12.join(latestScriptsDir, file2), "utf-8");
40701
+ lines.push(`### \`${file2}\``);
40702
+ lines.push("```javascript");
40703
+ lines.push(content);
40704
+ lines.push("```");
40705
+ lines.push("");
40706
+ } catch {
38890
40707
  }
38891
40708
  }
38892
40709
  }
@@ -38967,7 +40784,7 @@ var init_dev_server = __esm({
38967
40784
  lines.push("## Rules");
38968
40785
  lines.push("1. **Scripts WITHOUT params** \u2192 IIFE: `(() => { ... })()`");
38969
40786
  lines.push("2. **Scripts WITH params** \u2192 arrow: `(params) => { ... }` \u2014 router calls `(${script})(${JSON.stringify(params)})`");
38970
- lines.push("3. Use CSS selectors from the DOM analysis above");
40787
+ lines.push("3. If live DOM analysis is included above, use it. Otherwise, discover selectors yourself via CDP before coding.");
38971
40788
  lines.push("4. Always wrap in try-catch, return `JSON.stringify(result)`");
38972
40789
  lines.push("5. Do NOT modify `scripts.js` router \u2014 only edit individual `*.js` files");
38973
40790
  lines.push("6. All scripts run in the browser (CDP evaluate) \u2014 use DOM APIs only");
@@ -39016,8 +40833,12 @@ var init_dev_server = __esm({
39016
40833
  lines.push(" - `listSessions`: If sessions are unmounted when the panel is closed, try to explicitly interact with the UI to open the history/sessions view (e.g., clicking a history icon usually found near the chat header) BEFORE scraping.");
39017
40834
  lines.push(" - `switchSession`: Prove your switch was successful by subsequently calling `readChat` and explicitly checking that the chat context has actually changed.");
39018
40835
  lines.push("");
39019
- lines.push("## YOU MUST EXPLORE THE DOM YOURSELF!");
39020
- lines.push("I have NOT provided you with the DOM snapshot. You MUST use your command-line tools to discover the IDE structure dynamically!");
40836
+ lines.push("## DOM Exploration");
40837
+ if (domContext) {
40838
+ lines.push("A lightweight DOM snapshot is included above, but you MUST still verify selectors yourself before finalizing the scripts.");
40839
+ } else {
40840
+ lines.push("No DOM snapshot is included here. You MUST use your command-line tools to discover the IDE structure dynamically.");
40841
+ }
39021
40842
  lines.push("");
39022
40843
  lines.push("### 1. Evaluate JS to explore IDE DOM");
39023
40844
  lines.push("Use cURL to run JavaScript inside the IDE:");
@@ -39104,29 +40925,20 @@ var init_dev_server = __esm({
39104
40925
  lines.push("These are the files you need to edit. Replace TODO or heuristic-only logic with working PTY-aware implementations.");
39105
40926
  lines.push("");
39106
40927
  const scriptsDir = path12.join(providerDir, "scripts");
39107
- if (fs10.existsSync(scriptsDir)) {
39108
- const versions = fs10.readdirSync(scriptsDir).filter((d) => {
40928
+ const latestScriptsDir = this.getLatestScriptVersionDir(scriptsDir);
40929
+ if (latestScriptsDir) {
40930
+ lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
40931
+ lines.push("");
40932
+ for (const file2 of fs10.readdirSync(latestScriptsDir)) {
40933
+ if (!file2.endsWith(".js")) continue;
39109
40934
  try {
39110
- return fs10.statSync(path12.join(scriptsDir, d)).isDirectory();
40935
+ const content = fs10.readFileSync(path12.join(latestScriptsDir, file2), "utf-8");
40936
+ lines.push(`### \`${file2}\``);
40937
+ lines.push("```javascript");
40938
+ lines.push(content);
40939
+ lines.push("```");
40940
+ lines.push("");
39111
40941
  } catch {
39112
- return false;
39113
- }
39114
- }).sort().reverse();
39115
- if (versions.length > 0) {
39116
- const vDir = path12.join(scriptsDir, versions[0]);
39117
- lines.push(`Scripts version directory: \`${vDir}\``);
39118
- lines.push("");
39119
- for (const file2 of fs10.readdirSync(vDir)) {
39120
- if (!file2.endsWith(".js")) continue;
39121
- try {
39122
- const content = fs10.readFileSync(path12.join(vDir, file2), "utf-8");
39123
- lines.push(`### \`${file2}\``);
39124
- lines.push("```javascript");
39125
- lines.push(content);
39126
- lines.push("```");
39127
- lines.push("");
39128
- } catch {
39129
- }
39130
40942
  }
39131
40943
  }
39132
40944
  }
@@ -39340,14 +41152,14 @@ data: ${JSON.stringify(msg.data)}
39340
41152
  res.end(JSON.stringify(data, null, 2));
39341
41153
  }
39342
41154
  async readBody(req) {
39343
- return new Promise((resolve7) => {
41155
+ return new Promise((resolve10) => {
39344
41156
  let body = "";
39345
41157
  req.on("data", (chunk) => body += chunk);
39346
41158
  req.on("end", () => {
39347
41159
  try {
39348
- resolve7(JSON.parse(body));
41160
+ resolve10(JSON.parse(body));
39349
41161
  } catch {
39350
- resolve7({});
41162
+ resolve10({});
39351
41163
  }
39352
41164
  });
39353
41165
  });
@@ -39652,10 +41464,10 @@ async function installExtension(ide, extension) {
39652
41464
  const buffer = Buffer.from(await res.arrayBuffer());
39653
41465
  const fs13 = await import("fs");
39654
41466
  fs13.writeFileSync(vsixPath, buffer);
39655
- return new Promise((resolve7) => {
41467
+ return new Promise((resolve10) => {
39656
41468
  const cmd = `"${ide.cliCommand}" --install-extension "${vsixPath}" --force`;
39657
41469
  (0, import_child_process8.exec)(cmd, { timeout: 6e4 }, (error48, _stdout, stderr) => {
39658
- resolve7({
41470
+ resolve10({
39659
41471
  extensionId: extension.id,
39660
41472
  marketplaceId: extension.marketplaceId,
39661
41473
  success: !error48,
@@ -39668,11 +41480,11 @@ async function installExtension(ide, extension) {
39668
41480
  } catch (e) {
39669
41481
  }
39670
41482
  }
39671
- return new Promise((resolve7) => {
41483
+ return new Promise((resolve10) => {
39672
41484
  const cmd = `"${ide.cliCommand}" --install-extension ${extension.marketplaceId} --force`;
39673
41485
  (0, import_child_process8.exec)(cmd, { timeout: 6e4 }, (error48, stdout, stderr) => {
39674
41486
  if (error48) {
39675
- resolve7({
41487
+ resolve10({
39676
41488
  extensionId: extension.id,
39677
41489
  marketplaceId: extension.marketplaceId,
39678
41490
  success: false,
@@ -39680,7 +41492,7 @@ async function installExtension(ide, extension) {
39680
41492
  error: stderr || error48.message
39681
41493
  });
39682
41494
  } else {
39683
- resolve7({
41495
+ resolve10({
39684
41496
  extensionId: extension.id,
39685
41497
  marketplaceId: extension.marketplaceId,
39686
41498
  success: true,
@@ -39913,6 +41725,18 @@ async function initDaemonComponents(config2) {
39913
41725
  detectedIdes: detectedIdesRef
39914
41726
  };
39915
41727
  }
41728
+ async function startDaemonDevSupport(options) {
41729
+ const devServer = new DevServer({
41730
+ providerLoader: options.components.providerLoader,
41731
+ cdpManagers: options.components.cdpManagers,
41732
+ instanceManager: options.components.instanceManager,
41733
+ cliManager: options.components.cliManager,
41734
+ logFn: options.logFn
41735
+ });
41736
+ await devServer.start();
41737
+ options.components.providerLoader.watch();
41738
+ return devServer;
41739
+ }
39916
41740
  async function shutdownDaemonComponents(components) {
39917
41741
  const {
39918
41742
  poller,
@@ -39961,6 +41785,7 @@ var init_daemon_lifecycle = __esm({
39961
41785
  init_provider_loader();
39962
41786
  init_version_archive();
39963
41787
  init_provider_instance_manager();
41788
+ init_dev_server();
39964
41789
  init_ide_detector();
39965
41790
  init_logger();
39966
41791
  init_config();
@@ -40033,6 +41858,7 @@ __export(src_exports, {
40033
41858
  setLogLevel: () => setLogLevel,
40034
41859
  setupIdeInstance: () => setupIdeInstance,
40035
41860
  shutdownDaemonComponents: () => shutdownDaemonComponents,
41861
+ startDaemonDevSupport: () => startDaemonDevSupport,
40036
41862
  updateConfig: () => updateConfig
40037
41863
  });
40038
41864
  var init_src = __esm({
@@ -40521,13 +42347,13 @@ ${e?.stack || ""}`);
40521
42347
  } catch {
40522
42348
  }
40523
42349
  const http3 = esmRequire("https");
40524
- const data = await new Promise((resolve7, reject) => {
42350
+ const data = await new Promise((resolve10, reject) => {
40525
42351
  const req = http3.get(`${serverUrl}/api/v1/turn/credentials`, {
40526
42352
  headers: { "Authorization": `Bearer ${token}` }
40527
42353
  }, (res) => {
40528
42354
  let d = "";
40529
42355
  res.on("data", (c) => d += c);
40530
- res.on("end", () => resolve7(d));
42356
+ res.on("end", () => resolve10(d));
40531
42357
  });
40532
42358
  req.on("error", reject);
40533
42359
  req.setTimeout(5e3, () => {
@@ -41383,7 +43209,7 @@ var init_adhdev_daemon = __esm({
41383
43209
  fs12 = __toESM(require("fs"));
41384
43210
  path14 = __toESM(require("path"));
41385
43211
  import_chalk2 = __toESM(require("chalk"));
41386
- pkgVersion = "0.6.71";
43212
+ pkgVersion = "0.6.75";
41387
43213
  if (pkgVersion === "unknown") {
41388
43214
  try {
41389
43215
  const possiblePaths = [
@@ -41608,7 +43434,7 @@ ${err?.stack || ""}`);
41608
43434
  this.running = true;
41609
43435
  process.on("SIGINT", () => this.stop());
41610
43436
  process.on("SIGTERM", () => this.stop());
41611
- if (options.dev) {
43437
+ if (options.dev && this.components) {
41612
43438
  const devServer = new DevServer({
41613
43439
  providerLoader: this.components.providerLoader,
41614
43440
  cdpManagers: this.components.cdpManagers,
@@ -42194,7 +44020,7 @@ __export(cdp_utils_exports, {
42194
44020
  async function sendDaemonCommand(cmd, args = {}, port = 19222) {
42195
44021
  const WebSocket3 = (await import("ws")).default;
42196
44022
  const { DAEMON_WS_PATH: DAEMON_WS_PATH2 } = await Promise.resolve().then(() => (init_src(), src_exports));
42197
- return new Promise((resolve7, reject) => {
44023
+ return new Promise((resolve10, reject) => {
42198
44024
  const wsUrl = `ws://127.0.0.1:${port}${DAEMON_WS_PATH2 || "/daemon"}`;
42199
44025
  const ws2 = new WebSocket3(wsUrl);
42200
44026
  const timeout = setTimeout(() => {
@@ -42225,7 +44051,7 @@ async function sendDaemonCommand(cmd, args = {}, port = 19222) {
42225
44051
  if (msg.type === "daemon:command_result" || msg.type === "command_result") {
42226
44052
  clearTimeout(timeout);
42227
44053
  ws2.close();
42228
- resolve7(msg.payload?.result || msg.payload || msg);
44054
+ resolve10(msg.payload?.result || msg.payload || msg);
42229
44055
  }
42230
44056
  } catch {
42231
44057
  }
@@ -42242,13 +44068,13 @@ Is 'adhdev daemon' running?`));
42242
44068
  }
42243
44069
  async function directCdpEval(expression, port = 9222) {
42244
44070
  const http3 = await import("http");
42245
- const targets = await new Promise((resolve7, reject) => {
44071
+ const targets = await new Promise((resolve10, reject) => {
42246
44072
  http3.get(`http://127.0.0.1:${port}/json`, (res) => {
42247
44073
  let data = "";
42248
44074
  res.on("data", (c) => data += c);
42249
44075
  res.on("end", () => {
42250
44076
  try {
42251
- resolve7(JSON.parse(data));
44077
+ resolve10(JSON.parse(data));
42252
44078
  } catch {
42253
44079
  reject(new Error("Invalid JSON"));
42254
44080
  }
@@ -42261,7 +44087,7 @@ async function directCdpEval(expression, port = 9222) {
42261
44087
  const target = (mainPages.length > 0 ? mainPages[0] : pages[0]) || targets[0];
42262
44088
  if (!target?.webSocketDebuggerUrl) throw new Error("No CDP target found");
42263
44089
  const WebSocket3 = (await import("ws")).default;
42264
- return new Promise((resolve7, reject) => {
44090
+ return new Promise((resolve10, reject) => {
42265
44091
  const ws2 = new WebSocket3(target.webSocketDebuggerUrl);
42266
44092
  const timeout = setTimeout(() => {
42267
44093
  ws2.close();
@@ -42283,11 +44109,11 @@ async function directCdpEval(expression, port = 9222) {
42283
44109
  clearTimeout(timeout);
42284
44110
  ws2.close();
42285
44111
  if (msg.result?.result?.value !== void 0) {
42286
- resolve7(msg.result.result.value);
44112
+ resolve10(msg.result.result.value);
42287
44113
  } else if (msg.result?.exceptionDetails) {
42288
44114
  reject(new Error(msg.result.exceptionDetails.text));
42289
44115
  } else {
42290
- resolve7(msg.result);
44116
+ resolve10(msg.result);
42291
44117
  }
42292
44118
  }
42293
44119
  });
@@ -42930,7 +44756,7 @@ function registerProviderCommands(program2) {
42930
44756
  } catch {
42931
44757
  try {
42932
44758
  const http3 = await import("http");
42933
- const result = await new Promise((resolve7, reject) => {
44759
+ const result = await new Promise((resolve10, reject) => {
42934
44760
  const req = http3.request({
42935
44761
  hostname: "127.0.0.1",
42936
44762
  port: 19280,
@@ -42942,9 +44768,9 @@ function registerProviderCommands(program2) {
42942
44768
  res.on("data", (c) => data += c);
42943
44769
  res.on("end", () => {
42944
44770
  try {
42945
- resolve7(JSON.parse(data));
44771
+ resolve10(JSON.parse(data));
42946
44772
  } catch {
42947
- resolve7({ raw: data });
44773
+ resolve10({ raw: data });
42948
44774
  }
42949
44775
  });
42950
44776
  });
@@ -43047,12 +44873,12 @@ function registerProviderCommands(program2) {
43047
44873
  console.log(import_chalk6.default.yellow("Invalid port number."));
43048
44874
  continue;
43049
44875
  }
43050
- const isFree = await new Promise((resolve7) => {
44876
+ const isFree = await new Promise((resolve10) => {
43051
44877
  const server = net2.createServer();
43052
44878
  server.unref();
43053
- server.on("error", () => resolve7(false));
44879
+ server.on("error", () => resolve10(false));
43054
44880
  server.listen(port, "127.0.0.1", () => {
43055
- server.close(() => resolve7(true));
44881
+ server.close(() => resolve10(true));
43056
44882
  });
43057
44883
  });
43058
44884
  if (!isFree) {
@@ -43067,7 +44893,7 @@ function registerProviderCommands(program2) {
43067
44893
  rl.close();
43068
44894
  const location = options.builtin ? "builtin" : "user";
43069
44895
  const http3 = await import("http");
43070
- const result = await new Promise((resolve7, reject) => {
44896
+ const result = await new Promise((resolve10, reject) => {
43071
44897
  const postData = JSON.stringify({ type, name, category, location, cdpPorts, osPaths, processNames });
43072
44898
  const req = http3.request({
43073
44899
  hostname: "127.0.0.1",
@@ -43080,9 +44906,9 @@ function registerProviderCommands(program2) {
43080
44906
  res.on("data", (c) => data += c);
43081
44907
  res.on("end", () => {
43082
44908
  try {
43083
- resolve7(JSON.parse(data));
44909
+ resolve10(JSON.parse(data));
43084
44910
  } catch {
43085
- resolve7({ raw: data });
44911
+ resolve10({ raw: data });
43086
44912
  }
43087
44913
  });
43088
44914
  });
@@ -43094,7 +44920,7 @@ function registerProviderCommands(program2) {
43094
44920
  const fsMod = await import("fs");
43095
44921
  const { ProviderLoader: ProviderLoader2 } = await Promise.resolve().then(() => (init_src(), src_exports));
43096
44922
  const loader = new ProviderLoader2();
43097
- let targetDir = location === "builtin" ? loader.getBuiltinProviderDir(category, type) : loader.getUserProviderDir(category, type);
44923
+ let targetDir = location === "builtin" ? loader.getUpstreamProviderDir(category, type) : loader.getUserProviderDir(category, type);
43098
44924
  if (fsMod.existsSync(targetDir)) return { error: `Provider already exists at ${targetDir}` };
43099
44925
  const isExt = category === "extension";
43100
44926
  const isIde = category === "ide";
@@ -43193,60 +45019,23 @@ function registerProviderCommands(program2) {
43193
45019
  if (providerToFix && !isUserProvider(providerToFix)) {
43194
45020
  console.log(import_chalk6.default.yellow(`
43195
45021
  \u26A0\uFE0F [${type}] is an upstream provider.`));
43196
- console.log(import_chalk6.default.yellow(` Any local modifications will be normally OVERWRITTEN by the next auto-update!`));
43197
- console.log(import_chalk6.default.gray(` We can disable upstream updates for this provider so your local edits are preserved.`));
43198
- const actionAnswer = await inquirer2.prompt([{
43199
- type: "list",
43200
- name: "action",
43201
- message: `How would you like to proceed?`,
43202
- choices: [
43203
- { name: "Edit in-place (Copy locally and disable upstream updates)", value: "inplace" },
43204
- { name: `Clone to a custom provider ('my-${type}')`, value: "clone" },
43205
- { name: "Cancel", value: "cancel" }
43206
- ]
43207
- }]);
43208
- if (actionAnswer.action === "cancel") {
43209
- console.log(import_chalk6.default.red("\n\u2717 Fix aborted.\n"));
43210
- process.exit(1);
43211
- }
45022
+ console.log(import_chalk6.default.gray(` Preparing a writable local copy in the user providers directory and disabling upstream updates for this provider.`));
43212
45023
  const pathMod = await import("path");
43213
45024
  const fsMod2 = await import("fs");
43214
- const builtinSrc = loader.getBuiltinProviderDir(providerToFix.category, type);
43215
45025
  const downloadedSrc = loader.getUpstreamProviderDir(providerToFix.category, type);
43216
- const sourceDir = fsMod2.existsSync(builtinSrc) ? builtinSrc : downloadedSrc;
43217
- if (actionAnswer.action === "clone") {
43218
- const newType = `my-${type}`;
43219
- const targetDir = loader.getUserProviderDir(providerToFix.category, newType);
43220
- if (fsMod2.existsSync(targetDir)) {
43221
- console.log(import_chalk6.default.red(`
43222
- \u2717 Target directory already exists: ${targetDir}. Please delete it or fix it directly.`));
43223
- process.exit(1);
43224
- }
43225
- fsMod2.cpSync(sourceDir, targetDir, { recursive: true });
43226
- const pJsonPath = pathMod.join(targetDir, "provider.json");
43227
- if (fsMod2.existsSync(pJsonPath)) {
43228
- const pJson = JSON.parse(fsMod2.readFileSync(pJsonPath, "utf8"));
43229
- pJson.type = newType;
43230
- pJson.name = `My ${providerToFix.name}`;
43231
- fsMod2.writeFileSync(pJsonPath, JSON.stringify(pJson, null, 2));
43232
- }
43233
- console.log(import_chalk6.default.green(`
43234
- \u2713 Successfully cloned to [${newType}]`));
43235
- type = newType;
43236
- } else if (actionAnswer.action === "inplace") {
43237
- const targetDir = loader.getUserProviderDir(providerToFix.category, type);
43238
- if (!fsMod2.existsSync(targetDir)) {
43239
- fsMod2.cpSync(sourceDir, targetDir, { recursive: true });
43240
- }
43241
- const pJsonPath = pathMod.join(targetDir, "provider.json");
43242
- if (fsMod2.existsSync(pJsonPath)) {
43243
- const pJson = JSON.parse(fsMod2.readFileSync(pJsonPath, "utf8"));
43244
- pJson.disableUpstream = true;
43245
- fsMod2.writeFileSync(pJsonPath, JSON.stringify(pJson, null, 2));
43246
- }
43247
- console.log(import_chalk6.default.green(`
43248
- \u2713 Local copy created at [${targetDir}] with upstream updates disabled.`));
45026
+ const sourceDir = downloadedSrc;
45027
+ const targetDir2 = loader.getUserProviderDir(providerToFix.category, type);
45028
+ if (!fsMod2.existsSync(targetDir2)) {
45029
+ fsMod2.cpSync(sourceDir, targetDir2, { recursive: true });
43249
45030
  }
45031
+ const pJsonPath = pathMod.join(targetDir2, "provider.json");
45032
+ if (fsMod2.existsSync(pJsonPath)) {
45033
+ const pJson = JSON.parse(fsMod2.readFileSync(pJsonPath, "utf8"));
45034
+ pJson.disableUpstream = true;
45035
+ fsMod2.writeFileSync(pJsonPath, JSON.stringify(pJson, null, 2));
45036
+ }
45037
+ console.log(import_chalk6.default.green(`
45038
+ \u2713 Writable local copy ready at [${targetDir2}]`));
43250
45039
  }
43251
45040
  let agentName = options.agent || "codex-cli";
43252
45041
  const modelName = options.model;
@@ -43306,6 +45095,7 @@ function registerProviderCommands(program2) {
43306
45095
  userComment = commentAnswer.comment || "";
43307
45096
  }
43308
45097
  let consecutiveFailures = 0;
45098
+ const targetDir = loader.getUserProviderDir(providerToFix.category, type);
43309
45099
  console.log(import_chalk6.default.bold(`
43310
45100
  \u25B6\uFE0F Generating [${functionsToFix.length}] function(s) natively via autonomous agent for ${type}...`));
43311
45101
  if (userComment) {
@@ -43315,11 +45105,12 @@ function registerProviderCommands(program2) {
43315
45105
  const postData = JSON.stringify({
43316
45106
  functions: functionsToFix,
43317
45107
  agent: agentName,
45108
+ providerDir: targetDir,
43318
45109
  ...modelName ? { model: modelName } : {},
43319
45110
  ...userComment ? { comment: userComment } : {},
43320
45111
  reference
43321
45112
  });
43322
- const startResult = await new Promise((resolve7, reject) => {
45113
+ const startResult = await new Promise((resolve10, reject) => {
43323
45114
  const req = http3.request({
43324
45115
  hostname: "127.0.0.1",
43325
45116
  port: 19280,
@@ -43331,9 +45122,9 @@ function registerProviderCommands(program2) {
43331
45122
  res.on("data", (c) => data += c);
43332
45123
  res.on("end", () => {
43333
45124
  try {
43334
- resolve7(JSON.parse(data));
45125
+ resolve10(JSON.parse(data));
43335
45126
  } catch {
43336
- resolve7({ raw: data });
45127
+ resolve10({ raw: data });
43337
45128
  }
43338
45129
  });
43339
45130
  });
@@ -43357,13 +45148,12 @@ function registerProviderCommands(program2) {
43357
45148
  loader2.loadAll();
43358
45149
  const providerMeta = loader2.getMeta(type);
43359
45150
  if (!providerMeta) throw new Error(`Unknown provider: ${type}`);
43360
- const targetDir = loader2.getUserProviderDir(providerMeta.category, type);
43361
45151
  const fsMock = await import("fs");
43362
45152
  const logFile2 = pathMod.join(targetDir, `auto-impl.log`);
43363
45153
  fsMock.writeFileSync(logFile2, `=== Auto-Impl Started ===
43364
45154
  `);
43365
45155
  console.log(import_chalk6.default.gray(` Agent logs: ${logFile2}`));
43366
- await new Promise((resolve7, reject) => {
45156
+ await new Promise((resolve10, reject) => {
43367
45157
  http3.get(`http://127.0.0.1:19280${startResult.sseUrl}`, (res) => {
43368
45158
  let buffer = "";
43369
45159
  res.on("data", (chunk) => {
@@ -43400,7 +45190,7 @@ function registerProviderCommands(program2) {
43400
45190
  if (currentData.success === false) {
43401
45191
  reject(new Error(`Agent failed to implement scripts properly (exit: ${currentData.exitCode})`));
43402
45192
  } else {
43403
- resolve7();
45193
+ resolve10();
43404
45194
  }
43405
45195
  } else if (currentEvent === "error") {
43406
45196
  fsMock.appendFileSync(logFile2, `
@@ -43411,7 +45201,7 @@ function registerProviderCommands(program2) {
43411
45201
  }
43412
45202
  }
43413
45203
  });
43414
- res.on("end", resolve7);
45204
+ res.on("end", resolve10);
43415
45205
  }).on("error", reject);
43416
45206
  });
43417
45207
  console.log(import_chalk6.default.green(`
@@ -43470,7 +45260,7 @@ function registerProviderCommands(program2) {
43470
45260
  ideType: type,
43471
45261
  params: options.param ? { text: options.param, sessionId: options.param, buttonText: options.param } : {}
43472
45262
  });
43473
- const result = await new Promise((resolve7, reject) => {
45263
+ const result = await new Promise((resolve10, reject) => {
43474
45264
  const req = http3.request({
43475
45265
  hostname: "127.0.0.1",
43476
45266
  port: 19280,
@@ -43482,9 +45272,9 @@ function registerProviderCommands(program2) {
43482
45272
  res.on("data", (c) => data += c);
43483
45273
  res.on("end", () => {
43484
45274
  try {
43485
- resolve7(JSON.parse(data));
45275
+ resolve10(JSON.parse(data));
43486
45276
  } catch {
43487
- resolve7({ raw: data });
45277
+ resolve10({ raw: data });
43488
45278
  }
43489
45279
  });
43490
45280
  });
@@ -43520,15 +45310,15 @@ function registerProviderCommands(program2) {
43520
45310
  provider.command("source <type>").description("View source code of a provider").action(async (type) => {
43521
45311
  try {
43522
45312
  const http3 = await import("http");
43523
- const result = await new Promise((resolve7, reject) => {
45313
+ const result = await new Promise((resolve10, reject) => {
43524
45314
  http3.get(`http://127.0.0.1:19280/api/providers/${type}/source`, (res) => {
43525
45315
  let data = "";
43526
45316
  res.on("data", (c) => data += c);
43527
45317
  res.on("end", () => {
43528
45318
  try {
43529
- resolve7(JSON.parse(data));
45319
+ resolve10(JSON.parse(data));
43530
45320
  } catch {
43531
- resolve7({ raw: data });
45321
+ resolve10({ raw: data });
43532
45322
  }
43533
45323
  });
43534
45324
  }).on("error", () => {
@@ -43546,8 +45336,7 @@ function registerProviderCommands(program2) {
43546
45336
  }
43547
45337
  const possiblePaths = [
43548
45338
  pathMod.join(loader.getUserProviderDir(providerMeta.category, type), "provider.js"),
43549
- pathMod.join(loader.getUpstreamProviderDir(providerMeta.category, type), "provider.js"),
43550
- pathMod.join(loader.getBuiltinProviderDir(providerMeta.category, type), "provider.js")
45339
+ pathMod.join(loader.getUpstreamProviderDir(providerMeta.category, type), "provider.js")
43551
45340
  ];
43552
45341
  for (const p of possiblePaths) {
43553
45342
  if (fsMod.existsSync(p)) {
@@ -43577,7 +45366,7 @@ function registerProviderCommands(program2) {
43577
45366
  try {
43578
45367
  const http3 = await import("http");
43579
45368
  const postData = JSON.stringify({ script: "readChat", params: {} });
43580
- const result = await new Promise((resolve7, reject) => {
45369
+ const result = await new Promise((resolve10, reject) => {
43581
45370
  const req = http3.request({
43582
45371
  hostname: "127.0.0.1",
43583
45372
  port: 19280,
@@ -43589,9 +45378,9 @@ function registerProviderCommands(program2) {
43589
45378
  res2.on("data", (c) => data += c);
43590
45379
  res2.on("end", () => {
43591
45380
  try {
43592
- resolve7(JSON.parse(data));
45381
+ resolve10(JSON.parse(data));
43593
45382
  } catch {
43594
- resolve7({ raw: data });
45383
+ resolve10({ raw: data });
43595
45384
  }
43596
45385
  });
43597
45386
  });
@@ -43832,13 +45621,13 @@ function registerCdpCommands(program2) {
43832
45621
  cdp.command("screenshot").description("Capture IDE screenshot").option("-p, --port <port>", "CDP port", "9222").option("-o, --output <file>", "Output file path", "/tmp/cdp_screenshot.jpg").action(async (options) => {
43833
45622
  try {
43834
45623
  const http3 = await import("http");
43835
- const targets = await new Promise((resolve7, reject) => {
45624
+ const targets = await new Promise((resolve10, reject) => {
43836
45625
  http3.get(`http://127.0.0.1:${options.port}/json`, (res) => {
43837
45626
  let data = "";
43838
45627
  res.on("data", (c) => data += c);
43839
45628
  res.on("end", () => {
43840
45629
  try {
43841
- resolve7(JSON.parse(data));
45630
+ resolve10(JSON.parse(data));
43842
45631
  } catch {
43843
45632
  reject(new Error("Invalid JSON"));
43844
45633
  }
@@ -43852,7 +45641,7 @@ function registerCdpCommands(program2) {
43852
45641
  if (!target?.webSocketDebuggerUrl) throw new Error("No CDP target");
43853
45642
  const WebSocket3 = (await import("ws")).default;
43854
45643
  const ws2 = new WebSocket3(target.webSocketDebuggerUrl);
43855
- await new Promise((resolve7, reject) => {
45644
+ await new Promise((resolve10, reject) => {
43856
45645
  ws2.on("open", () => {
43857
45646
  ws2.send(JSON.stringify({ id: 1, method: "Page.captureScreenshot", params: { format: "jpeg", quality: 50 } }));
43858
45647
  });
@@ -43865,7 +45654,7 @@ function registerCdpCommands(program2) {
43865
45654
  \u2713 Screenshot saved to ${options.output}
43866
45655
  `));
43867
45656
  ws2.close();
43868
- resolve7();
45657
+ resolve10();
43869
45658
  }
43870
45659
  });
43871
45660
  ws2.on("error", (e) => reject(e));
@@ -43934,6 +45723,9 @@ if (process.argv.length <= 2) {
43934
45723
  }
43935
45724
  /*! Bundled license information:
43936
45725
 
45726
+ chokidar/index.js:
45727
+ (*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) *)
45728
+
43937
45729
  @xterm/xterm/lib/xterm.mjs:
43938
45730
  (**
43939
45731
  * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.