adhdev 0.6.72 → 0.6.76

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}`,
@@ -560,16 +560,20 @@ var init_ide_detector = __esm({
560
560
  });
561
561
 
562
562
  // ../../oss/packages/daemon-core/src/detection/cli-detector.ts
563
+ function parseVersion(raw) {
564
+ const match = raw.match(/v?(\d+\.\d+(?:\.\d+)?(?:-[a-zA-Z0-9.]+)?)/);
565
+ return match ? match[1] : raw.split("\n")[0].slice(0, 100);
566
+ }
563
567
  function execAsync(cmd, timeoutMs = 5e3) {
564
- return new Promise((resolve7) => {
568
+ return new Promise((resolve10) => {
565
569
  const child = (0, import_child_process2.exec)(cmd, { encoding: "utf-8", timeout: timeoutMs }, (err, stdout) => {
566
570
  if (err || !stdout?.trim()) {
567
- resolve7(null);
571
+ resolve10(null);
568
572
  } else {
569
- resolve7(stdout.trim());
573
+ resolve10(stdout.trim());
570
574
  }
571
575
  });
572
- child.on("error", () => resolve7(null));
576
+ child.on("error", () => resolve10(null));
573
577
  });
574
578
  }
575
579
  async function detectCLIs(providerLoader) {
@@ -584,10 +588,18 @@ async function detectCLIs(providerLoader) {
584
588
  const firstPath = pathResult.split("\n")[0];
585
589
  let version2;
586
590
  try {
587
- const versionResult = await execAsync(`${cli.command} --version 2>/dev/null`, 3e3);
588
- if (versionResult) {
589
- const match = versionResult.match(/(\d+\.\d+[\.\d]*)/);
590
- version2 = match ? match[1] : versionResult.split("\n")[0].slice(0, 30);
591
+ const versionCommands = [
592
+ cli.versionCommand,
593
+ `${cli.command} --version 2>/dev/null`,
594
+ `${cli.command} -V 2>/dev/null`,
595
+ `${cli.command} -v 2>/dev/null`
596
+ ].filter((v2) => !!v2);
597
+ for (const versionCommand of versionCommands) {
598
+ const versionResult = await execAsync(versionCommand, 3e3);
599
+ if (versionResult) {
600
+ version2 = parseVersion(versionResult);
601
+ break;
602
+ }
591
603
  }
592
604
  } catch {
593
605
  }
@@ -700,8 +712,8 @@ function cleanOldLogs() {
700
712
  }
701
713
  function rotateSizeIfNeeded() {
702
714
  try {
703
- const stat = fs2.statSync(currentLogFile);
704
- if (stat.size > MAX_LOG_SIZE) {
715
+ const stat4 = fs2.statSync(currentLogFile);
716
+ if (stat4.size > MAX_LOG_SIZE) {
705
717
  const backup = currentLogFile.replace(".log", ".1.log");
706
718
  try {
707
719
  fs2.unlinkSync(backup);
@@ -830,8 +842,8 @@ var init_logger = __esm({
830
842
  try {
831
843
  const oldLog = path3.join(LOG_DIR, "daemon.log");
832
844
  if (fs2.existsSync(oldLog)) {
833
- const stat = fs2.statSync(oldLog);
834
- const oldDate = stat.mtime.toISOString().slice(0, 10);
845
+ const stat4 = fs2.statSync(oldLog);
846
+ const oldDate = stat4.mtime.toISOString().slice(0, 10);
835
847
  fs2.renameSync(oldLog, path3.join(LOG_DIR, `daemon-${oldDate}.log`));
836
848
  }
837
849
  const oldLogBackup = path3.join(LOG_DIR, "daemon.log.old");
@@ -955,7 +967,7 @@ var init_manager = __esm({
955
967
  * Returns multiple entries if multiple IDE windows are open on same port
956
968
  */
957
969
  static listAllTargets(port) {
958
- return new Promise((resolve7) => {
970
+ return new Promise((resolve10) => {
959
971
  const req = http.get(`http://127.0.0.1:${port}/json`, (res) => {
960
972
  let data = "";
961
973
  res.on("data", (chunk) => data += chunk.toString());
@@ -971,16 +983,16 @@ var init_manager = __esm({
971
983
  (t) => !isNonMain(t.title || "") && t.url?.includes("workbench.html") && !t.url?.includes("agent")
972
984
  );
973
985
  const fallbackPages = pages.filter((t) => !isNonMain(t.title || ""));
974
- resolve7(mainPages.length > 0 ? mainPages : fallbackPages);
986
+ resolve10(mainPages.length > 0 ? mainPages : fallbackPages);
975
987
  } catch {
976
- resolve7([]);
988
+ resolve10([]);
977
989
  }
978
990
  });
979
991
  });
980
- req.on("error", () => resolve7([]));
992
+ req.on("error", () => resolve10([]));
981
993
  req.setTimeout(2e3, () => {
982
994
  req.destroy();
983
- resolve7([]);
995
+ resolve10([]);
984
996
  });
985
997
  });
986
998
  }
@@ -1020,7 +1032,7 @@ var init_manager = __esm({
1020
1032
  }
1021
1033
  }
1022
1034
  findTargetOnPort(port) {
1023
- return new Promise((resolve7) => {
1035
+ return new Promise((resolve10) => {
1024
1036
  const req = http.get(`http://127.0.0.1:${port}/json`, (res) => {
1025
1037
  let data = "";
1026
1038
  res.on("data", (chunk) => data += chunk.toString());
@@ -1031,7 +1043,7 @@ var init_manager = __esm({
1031
1043
  (t) => (t.type === "page" || t.type === "browser" || t.type === "Page") && t.webSocketDebuggerUrl
1032
1044
  );
1033
1045
  if (pages.length === 0) {
1034
- resolve7(targets.find((t) => t.webSocketDebuggerUrl) || null);
1046
+ resolve10(targets.find((t) => t.webSocketDebuggerUrl) || null);
1035
1047
  return;
1036
1048
  }
1037
1049
  const mainPages = pages.filter((t) => !this.isNonMainTitle(t.title || ""));
@@ -1041,24 +1053,24 @@ var init_manager = __esm({
1041
1053
  const specific = list.find((t) => t.id === this._targetId);
1042
1054
  if (specific) {
1043
1055
  this._pageTitle = specific.title || "";
1044
- resolve7(specific);
1056
+ resolve10(specific);
1045
1057
  } else {
1046
1058
  this.log(`[CDP] Target ${this._targetId} not found in page list`);
1047
- resolve7(null);
1059
+ resolve10(null);
1048
1060
  }
1049
1061
  return;
1050
1062
  }
1051
1063
  this._pageTitle = list[0]?.title || "";
1052
- resolve7(list[0]);
1064
+ resolve10(list[0]);
1053
1065
  } catch {
1054
- resolve7(null);
1066
+ resolve10(null);
1055
1067
  }
1056
1068
  });
1057
1069
  });
1058
- req.on("error", () => resolve7(null));
1070
+ req.on("error", () => resolve10(null));
1059
1071
  req.setTimeout(2e3, () => {
1060
1072
  req.destroy();
1061
- resolve7(null);
1073
+ resolve10(null);
1062
1074
  });
1063
1075
  });
1064
1076
  }
@@ -1069,7 +1081,7 @@ var init_manager = __esm({
1069
1081
  this.extensionProviders = providers;
1070
1082
  }
1071
1083
  connectToTarget(wsUrl) {
1072
- return new Promise((resolve7) => {
1084
+ return new Promise((resolve10) => {
1073
1085
  this.ws = new import_ws.default(wsUrl);
1074
1086
  this.ws.on("open", async () => {
1075
1087
  this._connected = true;
@@ -1079,17 +1091,17 @@ var init_manager = __esm({
1079
1091
  }
1080
1092
  this.connectBrowserWs().catch(() => {
1081
1093
  });
1082
- resolve7(true);
1094
+ resolve10(true);
1083
1095
  });
1084
1096
  this.ws.on("message", (data) => {
1085
1097
  try {
1086
1098
  const msg = JSON.parse(data.toString());
1087
1099
  if (msg.id && this.pending.has(msg.id)) {
1088
- const { resolve: resolve8, reject } = this.pending.get(msg.id);
1100
+ const { resolve: resolve11, reject } = this.pending.get(msg.id);
1089
1101
  this.pending.delete(msg.id);
1090
1102
  this.failureCount = 0;
1091
1103
  if (msg.error) reject(new Error(msg.error.message));
1092
- else resolve8(msg.result);
1104
+ else resolve11(msg.result);
1093
1105
  } else if (msg.method === "Runtime.executionContextCreated") {
1094
1106
  this.contexts.add(msg.params.context.id);
1095
1107
  } else if (msg.method === "Runtime.executionContextDestroyed") {
@@ -1112,7 +1124,7 @@ var init_manager = __esm({
1112
1124
  this.ws.on("error", (err) => {
1113
1125
  this.log(`[CDP] WebSocket error: ${err.message}`);
1114
1126
  this._connected = false;
1115
- resolve7(false);
1127
+ resolve10(false);
1116
1128
  });
1117
1129
  });
1118
1130
  }
@@ -1126,7 +1138,7 @@ var init_manager = __esm({
1126
1138
  return;
1127
1139
  }
1128
1140
  this.log(`[CDP] Connecting browser WS for target discovery...`);
1129
- await new Promise((resolve7, reject) => {
1141
+ await new Promise((resolve10, reject) => {
1130
1142
  this.browserWs = new import_ws.default(browserWsUrl);
1131
1143
  this.browserWs.on("open", async () => {
1132
1144
  this._browserConnected = true;
@@ -1136,16 +1148,16 @@ var init_manager = __esm({
1136
1148
  } catch (e) {
1137
1149
  this.log(`[CDP] setDiscoverTargets failed: ${e.message}`);
1138
1150
  }
1139
- resolve7();
1151
+ resolve10();
1140
1152
  });
1141
1153
  this.browserWs.on("message", (data) => {
1142
1154
  try {
1143
1155
  const msg = JSON.parse(data.toString());
1144
1156
  if (msg.id && this.browserPending.has(msg.id)) {
1145
- const { resolve: resolve8, reject: reject2 } = this.browserPending.get(msg.id);
1157
+ const { resolve: resolve11, reject: reject2 } = this.browserPending.get(msg.id);
1146
1158
  this.browserPending.delete(msg.id);
1147
1159
  if (msg.error) reject2(new Error(msg.error.message));
1148
- else resolve8(msg.result);
1160
+ else resolve11(msg.result);
1149
1161
  }
1150
1162
  } catch {
1151
1163
  }
@@ -1165,31 +1177,31 @@ var init_manager = __esm({
1165
1177
  }
1166
1178
  }
1167
1179
  getBrowserWsUrl() {
1168
- return new Promise((resolve7) => {
1180
+ return new Promise((resolve10) => {
1169
1181
  const req = http.get(`http://127.0.0.1:${this.port}/json/version`, (res) => {
1170
1182
  let data = "";
1171
1183
  res.on("data", (chunk) => data += chunk.toString());
1172
1184
  res.on("end", () => {
1173
1185
  try {
1174
1186
  const info = JSON.parse(data);
1175
- resolve7(info.webSocketDebuggerUrl || null);
1187
+ resolve10(info.webSocketDebuggerUrl || null);
1176
1188
  } catch {
1177
- resolve7(null);
1189
+ resolve10(null);
1178
1190
  }
1179
1191
  });
1180
1192
  });
1181
- req.on("error", () => resolve7(null));
1193
+ req.on("error", () => resolve10(null));
1182
1194
  req.setTimeout(3e3, () => {
1183
1195
  req.destroy();
1184
- resolve7(null);
1196
+ resolve10(null);
1185
1197
  });
1186
1198
  });
1187
1199
  }
1188
1200
  sendBrowser(method, params = {}, timeoutMs = 15e3) {
1189
- return new Promise((resolve7, reject) => {
1201
+ return new Promise((resolve10, reject) => {
1190
1202
  if (!this.browserWs || !this._browserConnected) return reject(new Error("Browser WS not connected"));
1191
1203
  const id = this.browserMsgId++;
1192
- this.browserPending.set(id, { resolve: resolve7, reject });
1204
+ this.browserPending.set(id, { resolve: resolve10, reject });
1193
1205
  this.browserWs.send(JSON.stringify({ id, method, params }));
1194
1206
  setTimeout(() => {
1195
1207
  if (this.browserPending.has(id)) {
@@ -1229,11 +1241,11 @@ var init_manager = __esm({
1229
1241
  }
1230
1242
  // ─── CDP Protocol ────────────────────────────────────────
1231
1243
  sendInternal(method, params = {}, timeoutMs = 15e3) {
1232
- return new Promise((resolve7, reject) => {
1244
+ return new Promise((resolve10, reject) => {
1233
1245
  if (!this.ws || !this._connected) return reject(new Error("CDP not connected"));
1234
1246
  if (this.ws.readyState !== import_ws.default.OPEN) return reject(new Error("WebSocket not open"));
1235
1247
  const id = this.msgId++;
1236
- this.pending.set(id, { resolve: resolve7, reject });
1248
+ this.pending.set(id, { resolve: resolve10, reject });
1237
1249
  this.ws.send(JSON.stringify({ id, method, params }));
1238
1250
  setTimeout(() => {
1239
1251
  if (this.pending.has(id)) {
@@ -1482,7 +1494,7 @@ var init_manager = __esm({
1482
1494
  const browserWs = this.browserWs;
1483
1495
  let msgId = this.browserMsgId;
1484
1496
  const sendWs = (method, params = {}, sessionId) => {
1485
- return new Promise((resolve7, reject) => {
1497
+ return new Promise((resolve10, reject) => {
1486
1498
  const mid = msgId++;
1487
1499
  this.browserMsgId = msgId;
1488
1500
  const handler = (raw) => {
@@ -1491,7 +1503,7 @@ var init_manager = __esm({
1491
1503
  if (msg.id === mid) {
1492
1504
  browserWs.removeListener("message", handler);
1493
1505
  if (msg.error) reject(new Error(msg.error.message || JSON.stringify(msg.error)));
1494
- else resolve7(msg.result);
1506
+ else resolve10(msg.result);
1495
1507
  }
1496
1508
  } catch {
1497
1509
  }
@@ -1673,14 +1685,14 @@ var init_manager = __esm({
1673
1685
  if (!ws2 || ws2.readyState !== import_ws.default.OPEN) {
1674
1686
  throw new Error("CDP not connected");
1675
1687
  }
1676
- return new Promise((resolve7, reject) => {
1688
+ return new Promise((resolve10, reject) => {
1677
1689
  const id = getNextId();
1678
1690
  pendingMap.set(id, {
1679
1691
  resolve: (result) => {
1680
1692
  if (result?.result?.subtype === "error") {
1681
1693
  reject(new Error(result.result.description));
1682
1694
  } else {
1683
- resolve7(result?.result?.value);
1695
+ resolve10(result?.result?.value);
1684
1696
  }
1685
1697
  },
1686
1698
  reject
@@ -1712,10 +1724,10 @@ var init_manager = __esm({
1712
1724
  throw new Error("CDP not connected");
1713
1725
  }
1714
1726
  const sendViaSession = (method, params = {}) => {
1715
- return new Promise((resolve7, reject) => {
1727
+ return new Promise((resolve10, reject) => {
1716
1728
  const pendingMap = this._browserConnected ? this.browserPending : this.pending;
1717
1729
  const id = this._browserConnected ? this.browserMsgId++ : this.msgId++;
1718
- pendingMap.set(id, { resolve: resolve7, reject });
1730
+ pendingMap.set(id, { resolve: resolve10, reject });
1719
1731
  ws2.send(JSON.stringify({ id, sessionId, method, params }));
1720
1732
  setTimeout(() => {
1721
1733
  if (pendingMap.has(id)) {
@@ -2531,8 +2543,8 @@ ${next}`;
2531
2543
  const files = fs3.readdirSync(dirPath).filter((f) => f.endsWith(".jsonl") || f.endsWith(".terminal.log"));
2532
2544
  for (const file2 of files) {
2533
2545
  const filePath = path4.join(dirPath, file2);
2534
- const stat = fs3.statSync(filePath);
2535
- if (stat.mtimeMs < cutoff) {
2546
+ const stat4 = fs3.statSync(filePath);
2547
+ if (stat4.mtimeMs < cutoff) {
2536
2548
  fs3.unlinkSync(filePath);
2537
2549
  }
2538
2550
  }
@@ -3378,7 +3390,7 @@ function buildManagedClis(cliStates) {
3378
3390
  cliType: s15.type,
3379
3391
  cliName: s15.name,
3380
3392
  status: s15.status,
3381
- mode: s15.mode,
3393
+ mode: "terminal",
3382
3394
  workspace: s15.workspace || "",
3383
3395
  activeChat: s15.activeChat
3384
3396
  }));
@@ -4972,8 +4984,13 @@ var init_handler = __esm({
4972
4984
  getCliAdapter(type) {
4973
4985
  const target = type || this._currentIdeType;
4974
4986
  if (!target || !this._ctx.adapters) return null;
4987
+ let normalizedTarget = target;
4988
+ const colonIdx = normalizedTarget.lastIndexOf(":");
4989
+ if (colonIdx >= 0) normalizedTarget = normalizedTarget.substring(colonIdx + 1);
4990
+ const direct = this._ctx.adapters.get(normalizedTarget);
4991
+ if (direct) return direct;
4975
4992
  for (const [key, adapter] of this._ctx.adapters.entries()) {
4976
- if (adapter.cliType === target || key.startsWith(target)) {
4993
+ if (adapter.cliType === target || adapter.cliType === normalizedTarget || key === normalizedTarget || key.startsWith(target) || key.startsWith(normalizedTarget)) {
4977
4994
  return adapter;
4978
4995
  }
4979
4996
  }
@@ -5216,7 +5233,7 @@ var init_handler = __esm({
5216
5233
  try {
5217
5234
  const http3 = await import("http");
5218
5235
  const postData = JSON.stringify(body);
5219
- const result = await new Promise((resolve7, reject) => {
5236
+ const result = await new Promise((resolve10, reject) => {
5220
5237
  const req = http3.request({
5221
5238
  hostname: "127.0.0.1",
5222
5239
  port: 19280,
@@ -5228,9 +5245,9 @@ var init_handler = __esm({
5228
5245
  res.on("data", (chunk) => data += chunk);
5229
5246
  res.on("end", () => {
5230
5247
  try {
5231
- resolve7(JSON.parse(data));
5248
+ resolve10(JSON.parse(data));
5232
5249
  } catch {
5233
- resolve7({ raw: data });
5250
+ resolve10({ raw: data });
5234
5251
  }
5235
5252
  });
5236
5253
  });
@@ -5248,15 +5265,15 @@ var init_handler = __esm({
5248
5265
  if (!providerType) return { success: false, error: "providerType required" };
5249
5266
  try {
5250
5267
  const http3 = await import("http");
5251
- const result = await new Promise((resolve7, reject) => {
5268
+ const result = await new Promise((resolve10, reject) => {
5252
5269
  http3.get(`http://127.0.0.1:19280/api/providers/${providerType}/${endpoint}`, (res) => {
5253
5270
  let data = "";
5254
5271
  res.on("data", (chunk) => data += chunk);
5255
5272
  res.on("end", () => {
5256
5273
  try {
5257
- resolve7(JSON.parse(data));
5274
+ resolve10(JSON.parse(data));
5258
5275
  } catch {
5259
- resolve7({ raw: data });
5276
+ resolve10({ raw: data });
5260
5277
  }
5261
5278
  });
5262
5279
  }).on("error", reject);
@@ -5270,7 +5287,7 @@ var init_handler = __esm({
5270
5287
  try {
5271
5288
  const http3 = await import("http");
5272
5289
  const postData = JSON.stringify(args || {});
5273
- const result = await new Promise((resolve7, reject) => {
5290
+ const result = await new Promise((resolve10, reject) => {
5274
5291
  const req = http3.request({
5275
5292
  hostname: "127.0.0.1",
5276
5293
  port: 19280,
@@ -5282,9 +5299,9 @@ var init_handler = __esm({
5282
5299
  res.on("data", (chunk) => data += chunk);
5283
5300
  res.on("end", () => {
5284
5301
  try {
5285
- resolve7(JSON.parse(data));
5302
+ resolve10(JSON.parse(data));
5286
5303
  } catch {
5287
- resolve7({ raw: data });
5304
+ resolve10({ raw: data });
5288
5305
  }
5289
5306
  });
5290
5307
  });
@@ -5301,6 +5318,1755 @@ var init_handler = __esm({
5301
5318
  }
5302
5319
  });
5303
5320
 
5321
+ // ../../oss/packages/daemon-core/node_modules/readdirp/index.js
5322
+ function readdirp(root, options = {}) {
5323
+ let type = options.entryType || options.type;
5324
+ if (type === "both")
5325
+ type = EntryTypes.FILE_DIR_TYPE;
5326
+ if (type)
5327
+ options.type = type;
5328
+ if (!root) {
5329
+ throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
5330
+ } else if (typeof root !== "string") {
5331
+ throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");
5332
+ } else if (type && !ALL_TYPES.includes(type)) {
5333
+ throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
5334
+ }
5335
+ options.root = root;
5336
+ return new ReaddirpStream(options);
5337
+ }
5338
+ 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;
5339
+ var init_readdirp = __esm({
5340
+ "../../oss/packages/daemon-core/node_modules/readdirp/index.js"() {
5341
+ "use strict";
5342
+ import_promises = require("fs/promises");
5343
+ import_node_path = require("path");
5344
+ import_node_stream = require("stream");
5345
+ EntryTypes = {
5346
+ FILE_TYPE: "files",
5347
+ DIR_TYPE: "directories",
5348
+ FILE_DIR_TYPE: "files_directories",
5349
+ EVERYTHING_TYPE: "all"
5350
+ };
5351
+ defaultOptions = {
5352
+ root: ".",
5353
+ fileFilter: (_entryInfo) => true,
5354
+ directoryFilter: (_entryInfo) => true,
5355
+ type: EntryTypes.FILE_TYPE,
5356
+ lstat: false,
5357
+ depth: 2147483648,
5358
+ alwaysStat: false,
5359
+ highWaterMark: 4096
5360
+ };
5361
+ Object.freeze(defaultOptions);
5362
+ RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR";
5363
+ NORMAL_FLOW_ERRORS = /* @__PURE__ */ new Set(["ENOENT", "EPERM", "EACCES", "ELOOP", RECURSIVE_ERROR_CODE]);
5364
+ ALL_TYPES = [
5365
+ EntryTypes.DIR_TYPE,
5366
+ EntryTypes.EVERYTHING_TYPE,
5367
+ EntryTypes.FILE_DIR_TYPE,
5368
+ EntryTypes.FILE_TYPE
5369
+ ];
5370
+ DIR_TYPES = /* @__PURE__ */ new Set([
5371
+ EntryTypes.DIR_TYPE,
5372
+ EntryTypes.EVERYTHING_TYPE,
5373
+ EntryTypes.FILE_DIR_TYPE
5374
+ ]);
5375
+ FILE_TYPES = /* @__PURE__ */ new Set([
5376
+ EntryTypes.EVERYTHING_TYPE,
5377
+ EntryTypes.FILE_DIR_TYPE,
5378
+ EntryTypes.FILE_TYPE
5379
+ ]);
5380
+ isNormalFlowError = (error48) => NORMAL_FLOW_ERRORS.has(error48.code);
5381
+ wantBigintFsStats = process.platform === "win32";
5382
+ emptyFn = (_entryInfo) => true;
5383
+ normalizeFilter = (filter) => {
5384
+ if (filter === void 0)
5385
+ return emptyFn;
5386
+ if (typeof filter === "function")
5387
+ return filter;
5388
+ if (typeof filter === "string") {
5389
+ const fl2 = filter.trim();
5390
+ return (entry) => entry.basename === fl2;
5391
+ }
5392
+ if (Array.isArray(filter)) {
5393
+ const trItems = filter.map((item) => item.trim());
5394
+ return (entry) => trItems.some((f) => entry.basename === f);
5395
+ }
5396
+ return emptyFn;
5397
+ };
5398
+ ReaddirpStream = class extends import_node_stream.Readable {
5399
+ parents;
5400
+ reading;
5401
+ parent;
5402
+ _stat;
5403
+ _maxDepth;
5404
+ _wantsDir;
5405
+ _wantsFile;
5406
+ _wantsEverything;
5407
+ _root;
5408
+ _isDirent;
5409
+ _statsProp;
5410
+ _rdOptions;
5411
+ _fileFilter;
5412
+ _directoryFilter;
5413
+ constructor(options = {}) {
5414
+ super({
5415
+ objectMode: true,
5416
+ autoDestroy: true,
5417
+ highWaterMark: options.highWaterMark
5418
+ });
5419
+ const opts = { ...defaultOptions, ...options };
5420
+ const { root, type } = opts;
5421
+ this._fileFilter = normalizeFilter(opts.fileFilter);
5422
+ this._directoryFilter = normalizeFilter(opts.directoryFilter);
5423
+ const statMethod = opts.lstat ? import_promises.lstat : import_promises.stat;
5424
+ if (wantBigintFsStats) {
5425
+ this._stat = (path15) => statMethod(path15, { bigint: true });
5426
+ } else {
5427
+ this._stat = statMethod;
5428
+ }
5429
+ this._maxDepth = opts.depth != null && Number.isSafeInteger(opts.depth) ? opts.depth : defaultOptions.depth;
5430
+ this._wantsDir = type ? DIR_TYPES.has(type) : false;
5431
+ this._wantsFile = type ? FILE_TYPES.has(type) : false;
5432
+ this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;
5433
+ this._root = (0, import_node_path.resolve)(root);
5434
+ this._isDirent = !opts.alwaysStat;
5435
+ this._statsProp = this._isDirent ? "dirent" : "stats";
5436
+ this._rdOptions = { encoding: "utf8", withFileTypes: this._isDirent };
5437
+ this.parents = [this._exploreDir(root, 1)];
5438
+ this.reading = false;
5439
+ this.parent = void 0;
5440
+ }
5441
+ async _read(batch) {
5442
+ if (this.reading)
5443
+ return;
5444
+ this.reading = true;
5445
+ try {
5446
+ while (!this.destroyed && batch > 0) {
5447
+ const par = this.parent;
5448
+ const fil = par && par.files;
5449
+ if (fil && fil.length > 0) {
5450
+ const { path: path15, depth } = par;
5451
+ const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path15));
5452
+ const awaited = await Promise.all(slice);
5453
+ for (const entry of awaited) {
5454
+ if (!entry)
5455
+ continue;
5456
+ if (this.destroyed)
5457
+ return;
5458
+ const entryType = await this._getEntryType(entry);
5459
+ if (entryType === "directory" && this._directoryFilter(entry)) {
5460
+ if (depth <= this._maxDepth) {
5461
+ this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
5462
+ }
5463
+ if (this._wantsDir) {
5464
+ this.push(entry);
5465
+ batch--;
5466
+ }
5467
+ } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) {
5468
+ if (this._wantsFile) {
5469
+ this.push(entry);
5470
+ batch--;
5471
+ }
5472
+ }
5473
+ }
5474
+ } else {
5475
+ const parent = this.parents.pop();
5476
+ if (!parent) {
5477
+ this.push(null);
5478
+ break;
5479
+ }
5480
+ this.parent = await parent;
5481
+ if (this.destroyed)
5482
+ return;
5483
+ }
5484
+ }
5485
+ } catch (error48) {
5486
+ this.destroy(error48);
5487
+ } finally {
5488
+ this.reading = false;
5489
+ }
5490
+ }
5491
+ async _exploreDir(path15, depth) {
5492
+ let files;
5493
+ try {
5494
+ files = await (0, import_promises.readdir)(path15, this._rdOptions);
5495
+ } catch (error48) {
5496
+ this._onError(error48);
5497
+ }
5498
+ return { files, depth, path: path15 };
5499
+ }
5500
+ async _formatEntry(dirent, path15) {
5501
+ let entry;
5502
+ const basename6 = this._isDirent ? dirent.name : dirent;
5503
+ try {
5504
+ const fullPath = (0, import_node_path.resolve)((0, import_node_path.join)(path15, basename6));
5505
+ entry = { path: (0, import_node_path.relative)(this._root, fullPath), fullPath, basename: basename6 };
5506
+ entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
5507
+ } catch (err) {
5508
+ this._onError(err);
5509
+ return;
5510
+ }
5511
+ return entry;
5512
+ }
5513
+ _onError(err) {
5514
+ if (isNormalFlowError(err) && !this.destroyed) {
5515
+ this.emit("warn", err);
5516
+ } else {
5517
+ this.destroy(err);
5518
+ }
5519
+ }
5520
+ async _getEntryType(entry) {
5521
+ if (!entry && this._statsProp in entry) {
5522
+ return "";
5523
+ }
5524
+ const stats = entry[this._statsProp];
5525
+ if (stats.isFile())
5526
+ return "file";
5527
+ if (stats.isDirectory())
5528
+ return "directory";
5529
+ if (stats && stats.isSymbolicLink()) {
5530
+ const full = entry.fullPath;
5531
+ try {
5532
+ const entryRealPath = await (0, import_promises.realpath)(full);
5533
+ const entryRealPathStats = await (0, import_promises.lstat)(entryRealPath);
5534
+ if (entryRealPathStats.isFile()) {
5535
+ return "file";
5536
+ }
5537
+ if (entryRealPathStats.isDirectory()) {
5538
+ const len = entryRealPath.length;
5539
+ if (full.startsWith(entryRealPath) && full.substr(len, 1) === import_node_path.sep) {
5540
+ const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
5541
+ recursiveError.code = RECURSIVE_ERROR_CODE;
5542
+ return this._onError(recursiveError);
5543
+ }
5544
+ return "directory";
5545
+ }
5546
+ } catch (error48) {
5547
+ this._onError(error48);
5548
+ return "";
5549
+ }
5550
+ }
5551
+ }
5552
+ _includeAsFile(entry) {
5553
+ const stats = entry && entry[this._statsProp];
5554
+ return stats && this._wantsEverything && !stats.isDirectory();
5555
+ }
5556
+ };
5557
+ }
5558
+ });
5559
+
5560
+ // ../../oss/packages/daemon-core/node_modules/chokidar/handler.js
5561
+ function createFsWatchInstance(path15, options, listener, errHandler, emitRaw) {
5562
+ const handleEvent = (rawEvent, evPath) => {
5563
+ listener(path15);
5564
+ emitRaw(rawEvent, evPath, { watchedPath: path15 });
5565
+ if (evPath && path15 !== evPath) {
5566
+ fsWatchBroadcast(sp.resolve(path15, evPath), KEY_LISTENERS, sp.join(path15, evPath));
5567
+ }
5568
+ };
5569
+ try {
5570
+ return (0, import_node_fs.watch)(path15, {
5571
+ persistent: options.persistent
5572
+ }, handleEvent);
5573
+ } catch (error48) {
5574
+ errHandler(error48);
5575
+ return void 0;
5576
+ }
5577
+ }
5578
+ 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;
5579
+ var init_handler2 = __esm({
5580
+ "../../oss/packages/daemon-core/node_modules/chokidar/handler.js"() {
5581
+ "use strict";
5582
+ import_node_fs = require("fs");
5583
+ import_promises2 = require("fs/promises");
5584
+ import_node_os = require("os");
5585
+ sp = __toESM(require("path"), 1);
5586
+ STR_DATA = "data";
5587
+ STR_END = "end";
5588
+ STR_CLOSE = "close";
5589
+ EMPTY_FN = () => {
5590
+ };
5591
+ pl = process.platform;
5592
+ isWindows = pl === "win32";
5593
+ isMacos = pl === "darwin";
5594
+ isLinux = pl === "linux";
5595
+ isFreeBSD = pl === "freebsd";
5596
+ isIBMi = (0, import_node_os.type)() === "OS400";
5597
+ EVENTS = {
5598
+ ALL: "all",
5599
+ READY: "ready",
5600
+ ADD: "add",
5601
+ CHANGE: "change",
5602
+ ADD_DIR: "addDir",
5603
+ UNLINK: "unlink",
5604
+ UNLINK_DIR: "unlinkDir",
5605
+ RAW: "raw",
5606
+ ERROR: "error"
5607
+ };
5608
+ EV = EVENTS;
5609
+ THROTTLE_MODE_WATCH = "watch";
5610
+ statMethods = { lstat: import_promises2.lstat, stat: import_promises2.stat };
5611
+ KEY_LISTENERS = "listeners";
5612
+ KEY_ERR = "errHandlers";
5613
+ KEY_RAW = "rawEmitters";
5614
+ HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];
5615
+ binaryExtensions = /* @__PURE__ */ new Set([
5616
+ "3dm",
5617
+ "3ds",
5618
+ "3g2",
5619
+ "3gp",
5620
+ "7z",
5621
+ "a",
5622
+ "aac",
5623
+ "adp",
5624
+ "afdesign",
5625
+ "afphoto",
5626
+ "afpub",
5627
+ "ai",
5628
+ "aif",
5629
+ "aiff",
5630
+ "alz",
5631
+ "ape",
5632
+ "apk",
5633
+ "appimage",
5634
+ "ar",
5635
+ "arj",
5636
+ "asf",
5637
+ "au",
5638
+ "avi",
5639
+ "bak",
5640
+ "baml",
5641
+ "bh",
5642
+ "bin",
5643
+ "bk",
5644
+ "bmp",
5645
+ "btif",
5646
+ "bz2",
5647
+ "bzip2",
5648
+ "cab",
5649
+ "caf",
5650
+ "cgm",
5651
+ "class",
5652
+ "cmx",
5653
+ "cpio",
5654
+ "cr2",
5655
+ "cur",
5656
+ "dat",
5657
+ "dcm",
5658
+ "deb",
5659
+ "dex",
5660
+ "djvu",
5661
+ "dll",
5662
+ "dmg",
5663
+ "dng",
5664
+ "doc",
5665
+ "docm",
5666
+ "docx",
5667
+ "dot",
5668
+ "dotm",
5669
+ "dra",
5670
+ "DS_Store",
5671
+ "dsk",
5672
+ "dts",
5673
+ "dtshd",
5674
+ "dvb",
5675
+ "dwg",
5676
+ "dxf",
5677
+ "ecelp4800",
5678
+ "ecelp7470",
5679
+ "ecelp9600",
5680
+ "egg",
5681
+ "eol",
5682
+ "eot",
5683
+ "epub",
5684
+ "exe",
5685
+ "f4v",
5686
+ "fbs",
5687
+ "fh",
5688
+ "fla",
5689
+ "flac",
5690
+ "flatpak",
5691
+ "fli",
5692
+ "flv",
5693
+ "fpx",
5694
+ "fst",
5695
+ "fvt",
5696
+ "g3",
5697
+ "gh",
5698
+ "gif",
5699
+ "graffle",
5700
+ "gz",
5701
+ "gzip",
5702
+ "h261",
5703
+ "h263",
5704
+ "h264",
5705
+ "icns",
5706
+ "ico",
5707
+ "ief",
5708
+ "img",
5709
+ "ipa",
5710
+ "iso",
5711
+ "jar",
5712
+ "jpeg",
5713
+ "jpg",
5714
+ "jpgv",
5715
+ "jpm",
5716
+ "jxr",
5717
+ "key",
5718
+ "ktx",
5719
+ "lha",
5720
+ "lib",
5721
+ "lvp",
5722
+ "lz",
5723
+ "lzh",
5724
+ "lzma",
5725
+ "lzo",
5726
+ "m3u",
5727
+ "m4a",
5728
+ "m4v",
5729
+ "mar",
5730
+ "mdi",
5731
+ "mht",
5732
+ "mid",
5733
+ "midi",
5734
+ "mj2",
5735
+ "mka",
5736
+ "mkv",
5737
+ "mmr",
5738
+ "mng",
5739
+ "mobi",
5740
+ "mov",
5741
+ "movie",
5742
+ "mp3",
5743
+ "mp4",
5744
+ "mp4a",
5745
+ "mpeg",
5746
+ "mpg",
5747
+ "mpga",
5748
+ "mxu",
5749
+ "nef",
5750
+ "npx",
5751
+ "numbers",
5752
+ "nupkg",
5753
+ "o",
5754
+ "odp",
5755
+ "ods",
5756
+ "odt",
5757
+ "oga",
5758
+ "ogg",
5759
+ "ogv",
5760
+ "otf",
5761
+ "ott",
5762
+ "pages",
5763
+ "pbm",
5764
+ "pcx",
5765
+ "pdb",
5766
+ "pdf",
5767
+ "pea",
5768
+ "pgm",
5769
+ "pic",
5770
+ "png",
5771
+ "pnm",
5772
+ "pot",
5773
+ "potm",
5774
+ "potx",
5775
+ "ppa",
5776
+ "ppam",
5777
+ "ppm",
5778
+ "pps",
5779
+ "ppsm",
5780
+ "ppsx",
5781
+ "ppt",
5782
+ "pptm",
5783
+ "pptx",
5784
+ "psd",
5785
+ "pya",
5786
+ "pyc",
5787
+ "pyo",
5788
+ "pyv",
5789
+ "qt",
5790
+ "rar",
5791
+ "ras",
5792
+ "raw",
5793
+ "resources",
5794
+ "rgb",
5795
+ "rip",
5796
+ "rlc",
5797
+ "rmf",
5798
+ "rmvb",
5799
+ "rpm",
5800
+ "rtf",
5801
+ "rz",
5802
+ "s3m",
5803
+ "s7z",
5804
+ "scpt",
5805
+ "sgi",
5806
+ "shar",
5807
+ "snap",
5808
+ "sil",
5809
+ "sketch",
5810
+ "slk",
5811
+ "smv",
5812
+ "snk",
5813
+ "so",
5814
+ "stl",
5815
+ "suo",
5816
+ "sub",
5817
+ "swf",
5818
+ "tar",
5819
+ "tbz",
5820
+ "tbz2",
5821
+ "tga",
5822
+ "tgz",
5823
+ "thmx",
5824
+ "tif",
5825
+ "tiff",
5826
+ "tlz",
5827
+ "ttc",
5828
+ "ttf",
5829
+ "txz",
5830
+ "udf",
5831
+ "uvh",
5832
+ "uvi",
5833
+ "uvm",
5834
+ "uvp",
5835
+ "uvs",
5836
+ "uvu",
5837
+ "viv",
5838
+ "vob",
5839
+ "war",
5840
+ "wav",
5841
+ "wax",
5842
+ "wbmp",
5843
+ "wdp",
5844
+ "weba",
5845
+ "webm",
5846
+ "webp",
5847
+ "whl",
5848
+ "wim",
5849
+ "wm",
5850
+ "wma",
5851
+ "wmv",
5852
+ "wmx",
5853
+ "woff",
5854
+ "woff2",
5855
+ "wrm",
5856
+ "wvx",
5857
+ "xbm",
5858
+ "xif",
5859
+ "xla",
5860
+ "xlam",
5861
+ "xls",
5862
+ "xlsb",
5863
+ "xlsm",
5864
+ "xlsx",
5865
+ "xlt",
5866
+ "xltm",
5867
+ "xltx",
5868
+ "xm",
5869
+ "xmind",
5870
+ "xpi",
5871
+ "xpm",
5872
+ "xwd",
5873
+ "xz",
5874
+ "z",
5875
+ "zip",
5876
+ "zipx"
5877
+ ]);
5878
+ isBinaryPath = (filePath) => binaryExtensions.has(sp.extname(filePath).slice(1).toLowerCase());
5879
+ foreach = (val, fn2) => {
5880
+ if (val instanceof Set) {
5881
+ val.forEach(fn2);
5882
+ } else {
5883
+ fn2(val);
5884
+ }
5885
+ };
5886
+ addAndConvert = (main, prop, item) => {
5887
+ let container = main[prop];
5888
+ if (!(container instanceof Set)) {
5889
+ main[prop] = container = /* @__PURE__ */ new Set([container]);
5890
+ }
5891
+ container.add(item);
5892
+ };
5893
+ clearItem = (cont) => (key) => {
5894
+ const set2 = cont[key];
5895
+ if (set2 instanceof Set) {
5896
+ set2.clear();
5897
+ } else {
5898
+ delete cont[key];
5899
+ }
5900
+ };
5901
+ delFromSet = (main, prop, item) => {
5902
+ const container = main[prop];
5903
+ if (container instanceof Set) {
5904
+ container.delete(item);
5905
+ } else if (container === item) {
5906
+ delete main[prop];
5907
+ }
5908
+ };
5909
+ isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
5910
+ FsWatchInstances = /* @__PURE__ */ new Map();
5911
+ fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
5912
+ const cont = FsWatchInstances.get(fullPath);
5913
+ if (!cont)
5914
+ return;
5915
+ foreach(cont[listenerType], (listener) => {
5916
+ listener(val1, val2, val3);
5917
+ });
5918
+ };
5919
+ setFsWatchListener = (path15, fullPath, options, handlers) => {
5920
+ const { listener, errHandler, rawEmitter } = handlers;
5921
+ let cont = FsWatchInstances.get(fullPath);
5922
+ let watcher;
5923
+ if (!options.persistent) {
5924
+ watcher = createFsWatchInstance(path15, options, listener, errHandler, rawEmitter);
5925
+ if (!watcher)
5926
+ return;
5927
+ return watcher.close.bind(watcher);
5928
+ }
5929
+ if (cont) {
5930
+ addAndConvert(cont, KEY_LISTENERS, listener);
5931
+ addAndConvert(cont, KEY_ERR, errHandler);
5932
+ addAndConvert(cont, KEY_RAW, rawEmitter);
5933
+ } else {
5934
+ watcher = createFsWatchInstance(
5935
+ path15,
5936
+ options,
5937
+ fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
5938
+ errHandler,
5939
+ // no need to use broadcast here
5940
+ fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
5941
+ );
5942
+ if (!watcher)
5943
+ return;
5944
+ watcher.on(EV.ERROR, async (error48) => {
5945
+ const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
5946
+ if (cont)
5947
+ cont.watcherUnusable = true;
5948
+ if (isWindows && error48.code === "EPERM") {
5949
+ try {
5950
+ const fd = await (0, import_promises2.open)(path15, "r");
5951
+ await fd.close();
5952
+ broadcastErr(error48);
5953
+ } catch (err) {
5954
+ }
5955
+ } else {
5956
+ broadcastErr(error48);
5957
+ }
5958
+ });
5959
+ cont = {
5960
+ listeners: listener,
5961
+ errHandlers: errHandler,
5962
+ rawEmitters: rawEmitter,
5963
+ watcher
5964
+ };
5965
+ FsWatchInstances.set(fullPath, cont);
5966
+ }
5967
+ return () => {
5968
+ delFromSet(cont, KEY_LISTENERS, listener);
5969
+ delFromSet(cont, KEY_ERR, errHandler);
5970
+ delFromSet(cont, KEY_RAW, rawEmitter);
5971
+ if (isEmptySet(cont.listeners)) {
5972
+ cont.watcher.close();
5973
+ FsWatchInstances.delete(fullPath);
5974
+ HANDLER_KEYS.forEach(clearItem(cont));
5975
+ cont.watcher = void 0;
5976
+ Object.freeze(cont);
5977
+ }
5978
+ };
5979
+ };
5980
+ FsWatchFileInstances = /* @__PURE__ */ new Map();
5981
+ setFsWatchFileListener = (path15, fullPath, options, handlers) => {
5982
+ const { listener, rawEmitter } = handlers;
5983
+ let cont = FsWatchFileInstances.get(fullPath);
5984
+ const copts = cont && cont.options;
5985
+ if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
5986
+ (0, import_node_fs.unwatchFile)(fullPath);
5987
+ cont = void 0;
5988
+ }
5989
+ if (cont) {
5990
+ addAndConvert(cont, KEY_LISTENERS, listener);
5991
+ addAndConvert(cont, KEY_RAW, rawEmitter);
5992
+ } else {
5993
+ cont = {
5994
+ listeners: listener,
5995
+ rawEmitters: rawEmitter,
5996
+ options,
5997
+ watcher: (0, import_node_fs.watchFile)(fullPath, options, (curr, prev) => {
5998
+ foreach(cont.rawEmitters, (rawEmitter2) => {
5999
+ rawEmitter2(EV.CHANGE, fullPath, { curr, prev });
6000
+ });
6001
+ const currmtime = curr.mtimeMs;
6002
+ if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
6003
+ foreach(cont.listeners, (listener2) => listener2(path15, curr));
6004
+ }
6005
+ })
6006
+ };
6007
+ FsWatchFileInstances.set(fullPath, cont);
6008
+ }
6009
+ return () => {
6010
+ delFromSet(cont, KEY_LISTENERS, listener);
6011
+ delFromSet(cont, KEY_RAW, rawEmitter);
6012
+ if (isEmptySet(cont.listeners)) {
6013
+ FsWatchFileInstances.delete(fullPath);
6014
+ (0, import_node_fs.unwatchFile)(fullPath);
6015
+ cont.options = cont.watcher = void 0;
6016
+ Object.freeze(cont);
6017
+ }
6018
+ };
6019
+ };
6020
+ NodeFsHandler = class {
6021
+ fsw;
6022
+ _boundHandleError;
6023
+ constructor(fsW) {
6024
+ this.fsw = fsW;
6025
+ this._boundHandleError = (error48) => fsW._handleError(error48);
6026
+ }
6027
+ /**
6028
+ * Watch file for changes with fs_watchFile or fs_watch.
6029
+ * @param path to file or dir
6030
+ * @param listener on fs change
6031
+ * @returns closer for the watcher instance
6032
+ */
6033
+ _watchWithNodeFs(path15, listener) {
6034
+ const opts = this.fsw.options;
6035
+ const directory = sp.dirname(path15);
6036
+ const basename6 = sp.basename(path15);
6037
+ const parent = this.fsw._getWatchedDir(directory);
6038
+ parent.add(basename6);
6039
+ const absolutePath = sp.resolve(path15);
6040
+ const options = {
6041
+ persistent: opts.persistent
6042
+ };
6043
+ if (!listener)
6044
+ listener = EMPTY_FN;
6045
+ let closer;
6046
+ if (opts.usePolling) {
6047
+ const enableBin = opts.interval !== opts.binaryInterval;
6048
+ options.interval = enableBin && isBinaryPath(basename6) ? opts.binaryInterval : opts.interval;
6049
+ closer = setFsWatchFileListener(path15, absolutePath, options, {
6050
+ listener,
6051
+ rawEmitter: this.fsw._emitRaw
6052
+ });
6053
+ } else {
6054
+ closer = setFsWatchListener(path15, absolutePath, options, {
6055
+ listener,
6056
+ errHandler: this._boundHandleError,
6057
+ rawEmitter: this.fsw._emitRaw
6058
+ });
6059
+ }
6060
+ return closer;
6061
+ }
6062
+ /**
6063
+ * Watch a file and emit add event if warranted.
6064
+ * @returns closer for the watcher instance
6065
+ */
6066
+ _handleFile(file2, stats, initialAdd) {
6067
+ if (this.fsw.closed) {
6068
+ return;
6069
+ }
6070
+ const dirname9 = sp.dirname(file2);
6071
+ const basename6 = sp.basename(file2);
6072
+ const parent = this.fsw._getWatchedDir(dirname9);
6073
+ let prevStats = stats;
6074
+ if (parent.has(basename6))
6075
+ return;
6076
+ const listener = async (path15, newStats) => {
6077
+ if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file2, 5))
6078
+ return;
6079
+ if (!newStats || newStats.mtimeMs === 0) {
6080
+ try {
6081
+ const newStats2 = await (0, import_promises2.stat)(file2);
6082
+ if (this.fsw.closed)
6083
+ return;
6084
+ const at2 = newStats2.atimeMs;
6085
+ const mt2 = newStats2.mtimeMs;
6086
+ if (!at2 || at2 <= mt2 || mt2 !== prevStats.mtimeMs) {
6087
+ this.fsw._emit(EV.CHANGE, file2, newStats2);
6088
+ }
6089
+ if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats2.ino) {
6090
+ this.fsw._closeFile(path15);
6091
+ prevStats = newStats2;
6092
+ const closer2 = this._watchWithNodeFs(file2, listener);
6093
+ if (closer2)
6094
+ this.fsw._addPathCloser(path15, closer2);
6095
+ } else {
6096
+ prevStats = newStats2;
6097
+ }
6098
+ } catch (error48) {
6099
+ this.fsw._remove(dirname9, basename6);
6100
+ }
6101
+ } else if (parent.has(basename6)) {
6102
+ const at2 = newStats.atimeMs;
6103
+ const mt2 = newStats.mtimeMs;
6104
+ if (!at2 || at2 <= mt2 || mt2 !== prevStats.mtimeMs) {
6105
+ this.fsw._emit(EV.CHANGE, file2, newStats);
6106
+ }
6107
+ prevStats = newStats;
6108
+ }
6109
+ };
6110
+ const closer = this._watchWithNodeFs(file2, listener);
6111
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file2)) {
6112
+ if (!this.fsw._throttle(EV.ADD, file2, 0))
6113
+ return;
6114
+ this.fsw._emit(EV.ADD, file2, stats);
6115
+ }
6116
+ return closer;
6117
+ }
6118
+ /**
6119
+ * Handle symlinks encountered while reading a dir.
6120
+ * @param entry returned by readdirp
6121
+ * @param directory path of dir being read
6122
+ * @param path of this item
6123
+ * @param item basename of this item
6124
+ * @returns true if no more processing is needed for this entry.
6125
+ */
6126
+ async _handleSymlink(entry, directory, path15, item) {
6127
+ if (this.fsw.closed) {
6128
+ return;
6129
+ }
6130
+ const full = entry.fullPath;
6131
+ const dir = this.fsw._getWatchedDir(directory);
6132
+ if (!this.fsw.options.followSymlinks) {
6133
+ this.fsw._incrReadyCount();
6134
+ let linkPath;
6135
+ try {
6136
+ linkPath = await (0, import_promises2.realpath)(path15);
6137
+ } catch (e) {
6138
+ this.fsw._emitReady();
6139
+ return true;
6140
+ }
6141
+ if (this.fsw.closed)
6142
+ return;
6143
+ if (dir.has(item)) {
6144
+ if (this.fsw._symlinkPaths.get(full) !== linkPath) {
6145
+ this.fsw._symlinkPaths.set(full, linkPath);
6146
+ this.fsw._emit(EV.CHANGE, path15, entry.stats);
6147
+ }
6148
+ } else {
6149
+ dir.add(item);
6150
+ this.fsw._symlinkPaths.set(full, linkPath);
6151
+ this.fsw._emit(EV.ADD, path15, entry.stats);
6152
+ }
6153
+ this.fsw._emitReady();
6154
+ return true;
6155
+ }
6156
+ if (this.fsw._symlinkPaths.has(full)) {
6157
+ return true;
6158
+ }
6159
+ this.fsw._symlinkPaths.set(full, true);
6160
+ }
6161
+ _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
6162
+ directory = sp.join(directory, "");
6163
+ const throttleKey = target ? `${directory}:${target}` : directory;
6164
+ throttler = this.fsw._throttle("readdir", throttleKey, 1e3);
6165
+ if (!throttler)
6166
+ return;
6167
+ const previous = this.fsw._getWatchedDir(wh.path);
6168
+ const current = /* @__PURE__ */ new Set();
6169
+ let stream = this.fsw._readdirp(directory, {
6170
+ fileFilter: (entry) => wh.filterPath(entry),
6171
+ directoryFilter: (entry) => wh.filterDir(entry)
6172
+ });
6173
+ if (!stream)
6174
+ return;
6175
+ stream.on(STR_DATA, async (entry) => {
6176
+ if (this.fsw.closed) {
6177
+ stream = void 0;
6178
+ return;
6179
+ }
6180
+ const item = entry.path;
6181
+ let path15 = sp.join(directory, item);
6182
+ current.add(item);
6183
+ if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path15, item)) {
6184
+ return;
6185
+ }
6186
+ if (this.fsw.closed) {
6187
+ stream = void 0;
6188
+ return;
6189
+ }
6190
+ if (item === target || !target && !previous.has(item)) {
6191
+ this.fsw._incrReadyCount();
6192
+ path15 = sp.join(dir, sp.relative(dir, path15));
6193
+ this._addToNodeFs(path15, initialAdd, wh, depth + 1);
6194
+ }
6195
+ }).on(EV.ERROR, this._boundHandleError);
6196
+ return new Promise((resolve10, reject) => {
6197
+ if (!stream)
6198
+ return reject();
6199
+ stream.once(STR_END, () => {
6200
+ if (this.fsw.closed) {
6201
+ stream = void 0;
6202
+ return;
6203
+ }
6204
+ const wasThrottled = throttler ? throttler.clear() : false;
6205
+ resolve10(void 0);
6206
+ previous.getChildren().filter((item) => {
6207
+ return item !== directory && !current.has(item);
6208
+ }).forEach((item) => {
6209
+ this.fsw._remove(directory, item);
6210
+ });
6211
+ stream = void 0;
6212
+ if (wasThrottled)
6213
+ this._handleRead(directory, false, wh, target, dir, depth, throttler);
6214
+ });
6215
+ });
6216
+ }
6217
+ /**
6218
+ * Read directory to add / remove files from `@watched` list and re-read it on change.
6219
+ * @param dir fs path
6220
+ * @param stats
6221
+ * @param initialAdd
6222
+ * @param depth relative to user-supplied path
6223
+ * @param target child path targeted for watch
6224
+ * @param wh Common watch helpers for this path
6225
+ * @param realpath
6226
+ * @returns closer for the watcher instance.
6227
+ */
6228
+ async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath2) {
6229
+ const parentDir = this.fsw._getWatchedDir(sp.dirname(dir));
6230
+ const tracked = parentDir.has(sp.basename(dir));
6231
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
6232
+ this.fsw._emit(EV.ADD_DIR, dir, stats);
6233
+ }
6234
+ parentDir.add(sp.basename(dir));
6235
+ this.fsw._getWatchedDir(dir);
6236
+ let throttler;
6237
+ let closer;
6238
+ const oDepth = this.fsw.options.depth;
6239
+ if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath2)) {
6240
+ if (!target) {
6241
+ await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
6242
+ if (this.fsw.closed)
6243
+ return;
6244
+ }
6245
+ closer = this._watchWithNodeFs(dir, (dirPath, stats2) => {
6246
+ if (stats2 && stats2.mtimeMs === 0)
6247
+ return;
6248
+ this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
6249
+ });
6250
+ }
6251
+ return closer;
6252
+ }
6253
+ /**
6254
+ * Handle added file, directory, or glob pattern.
6255
+ * Delegates call to _handleFile / _handleDir after checks.
6256
+ * @param path to file or ir
6257
+ * @param initialAdd was the file added at watch instantiation?
6258
+ * @param priorWh depth relative to user-supplied path
6259
+ * @param depth Child path actually targeted for watch
6260
+ * @param target Child path actually targeted for watch
6261
+ */
6262
+ async _addToNodeFs(path15, initialAdd, priorWh, depth, target) {
6263
+ const ready = this.fsw._emitReady;
6264
+ if (this.fsw._isIgnored(path15) || this.fsw.closed) {
6265
+ ready();
6266
+ return false;
6267
+ }
6268
+ const wh = this.fsw._getWatchHelpers(path15);
6269
+ if (priorWh) {
6270
+ wh.filterPath = (entry) => priorWh.filterPath(entry);
6271
+ wh.filterDir = (entry) => priorWh.filterDir(entry);
6272
+ }
6273
+ try {
6274
+ const stats = await statMethods[wh.statMethod](wh.watchPath);
6275
+ if (this.fsw.closed)
6276
+ return;
6277
+ if (this.fsw._isIgnored(wh.watchPath, stats)) {
6278
+ ready();
6279
+ return false;
6280
+ }
6281
+ const follow = this.fsw.options.followSymlinks;
6282
+ let closer;
6283
+ if (stats.isDirectory()) {
6284
+ const absPath = sp.resolve(path15);
6285
+ const targetPath = follow ? await (0, import_promises2.realpath)(path15) : path15;
6286
+ if (this.fsw.closed)
6287
+ return;
6288
+ closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
6289
+ if (this.fsw.closed)
6290
+ return;
6291
+ if (absPath !== targetPath && targetPath !== void 0) {
6292
+ this.fsw._symlinkPaths.set(absPath, targetPath);
6293
+ }
6294
+ } else if (stats.isSymbolicLink()) {
6295
+ const targetPath = follow ? await (0, import_promises2.realpath)(path15) : path15;
6296
+ if (this.fsw.closed)
6297
+ return;
6298
+ const parent = sp.dirname(wh.watchPath);
6299
+ this.fsw._getWatchedDir(parent).add(wh.watchPath);
6300
+ this.fsw._emit(EV.ADD, wh.watchPath, stats);
6301
+ closer = await this._handleDir(parent, stats, initialAdd, depth, path15, wh, targetPath);
6302
+ if (this.fsw.closed)
6303
+ return;
6304
+ if (targetPath !== void 0) {
6305
+ this.fsw._symlinkPaths.set(sp.resolve(path15), targetPath);
6306
+ }
6307
+ } else {
6308
+ closer = this._handleFile(wh.watchPath, stats, initialAdd);
6309
+ }
6310
+ ready();
6311
+ if (closer)
6312
+ this.fsw._addPathCloser(path15, closer);
6313
+ return false;
6314
+ } catch (error48) {
6315
+ if (this.fsw._handleError(error48)) {
6316
+ ready();
6317
+ return path15;
6318
+ }
6319
+ }
6320
+ }
6321
+ };
6322
+ }
6323
+ });
6324
+
6325
+ // ../../oss/packages/daemon-core/node_modules/chokidar/index.js
6326
+ function arrify(item) {
6327
+ return Array.isArray(item) ? item : [item];
6328
+ }
6329
+ function createPattern(matcher) {
6330
+ if (typeof matcher === "function")
6331
+ return matcher;
6332
+ if (typeof matcher === "string")
6333
+ return (string4) => matcher === string4;
6334
+ if (matcher instanceof RegExp)
6335
+ return (string4) => matcher.test(string4);
6336
+ if (typeof matcher === "object" && matcher !== null) {
6337
+ return (string4) => {
6338
+ if (matcher.path === string4)
6339
+ return true;
6340
+ if (matcher.recursive) {
6341
+ const relative3 = sp2.relative(matcher.path, string4);
6342
+ if (!relative3) {
6343
+ return false;
6344
+ }
6345
+ return !relative3.startsWith("..") && !sp2.isAbsolute(relative3);
6346
+ }
6347
+ return false;
6348
+ };
6349
+ }
6350
+ return () => false;
6351
+ }
6352
+ function normalizePath(path15) {
6353
+ if (typeof path15 !== "string")
6354
+ throw new Error("string expected");
6355
+ path15 = sp2.normalize(path15);
6356
+ path15 = path15.replace(/\\/g, "/");
6357
+ let prepend = false;
6358
+ if (path15.startsWith("//"))
6359
+ prepend = true;
6360
+ path15 = path15.replace(DOUBLE_SLASH_RE, "/");
6361
+ if (prepend)
6362
+ path15 = "/" + path15;
6363
+ return path15;
6364
+ }
6365
+ function matchPatterns(patterns, testString, stats) {
6366
+ const path15 = normalizePath(testString);
6367
+ for (let index = 0; index < patterns.length; index++) {
6368
+ const pattern = patterns[index];
6369
+ if (pattern(path15, stats)) {
6370
+ return true;
6371
+ }
6372
+ }
6373
+ return false;
6374
+ }
6375
+ function anymatch(matchers, testString) {
6376
+ if (matchers == null) {
6377
+ throw new TypeError("anymatch: specify first argument");
6378
+ }
6379
+ const matchersArray = arrify(matchers);
6380
+ const patterns = matchersArray.map((matcher) => createPattern(matcher));
6381
+ if (testString == null) {
6382
+ return (testString2, stats) => {
6383
+ return matchPatterns(patterns, testString2, stats);
6384
+ };
6385
+ }
6386
+ return matchPatterns(patterns, testString);
6387
+ }
6388
+ function watch(paths, options = {}) {
6389
+ const watcher = new FSWatcher(options);
6390
+ watcher.add(paths);
6391
+ return watcher;
6392
+ }
6393
+ 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;
6394
+ var init_chokidar = __esm({
6395
+ "../../oss/packages/daemon-core/node_modules/chokidar/index.js"() {
6396
+ "use strict";
6397
+ import_node_events = require("events");
6398
+ import_node_fs2 = require("fs");
6399
+ import_promises3 = require("fs/promises");
6400
+ sp2 = __toESM(require("path"), 1);
6401
+ init_readdirp();
6402
+ init_handler2();
6403
+ SLASH = "/";
6404
+ SLASH_SLASH = "//";
6405
+ ONE_DOT = ".";
6406
+ TWO_DOTS = "..";
6407
+ STRING_TYPE = "string";
6408
+ BACK_SLASH_RE = /\\/g;
6409
+ DOUBLE_SLASH_RE = /\/\//g;
6410
+ DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
6411
+ REPLACER_RE = /^\.[/\\]/;
6412
+ isMatcherObject = (matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp);
6413
+ unifyPaths = (paths_) => {
6414
+ const paths = arrify(paths_).flat();
6415
+ if (!paths.every((p) => typeof p === STRING_TYPE)) {
6416
+ throw new TypeError(`Non-string provided as watch path: ${paths}`);
6417
+ }
6418
+ return paths.map(normalizePathToUnix);
6419
+ };
6420
+ toUnix = (string4) => {
6421
+ let str = string4.replace(BACK_SLASH_RE, SLASH);
6422
+ let prepend = false;
6423
+ if (str.startsWith(SLASH_SLASH)) {
6424
+ prepend = true;
6425
+ }
6426
+ str = str.replace(DOUBLE_SLASH_RE, SLASH);
6427
+ if (prepend) {
6428
+ str = SLASH + str;
6429
+ }
6430
+ return str;
6431
+ };
6432
+ normalizePathToUnix = (path15) => toUnix(sp2.normalize(toUnix(path15)));
6433
+ normalizeIgnored = (cwd = "") => (path15) => {
6434
+ if (typeof path15 === "string") {
6435
+ return normalizePathToUnix(sp2.isAbsolute(path15) ? path15 : sp2.join(cwd, path15));
6436
+ } else {
6437
+ return path15;
6438
+ }
6439
+ };
6440
+ getAbsolutePath = (path15, cwd) => {
6441
+ if (sp2.isAbsolute(path15)) {
6442
+ return path15;
6443
+ }
6444
+ return sp2.join(cwd, path15);
6445
+ };
6446
+ EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set());
6447
+ DirEntry = class {
6448
+ path;
6449
+ _removeWatcher;
6450
+ items;
6451
+ constructor(dir, removeWatcher) {
6452
+ this.path = dir;
6453
+ this._removeWatcher = removeWatcher;
6454
+ this.items = /* @__PURE__ */ new Set();
6455
+ }
6456
+ add(item) {
6457
+ const { items } = this;
6458
+ if (!items)
6459
+ return;
6460
+ if (item !== ONE_DOT && item !== TWO_DOTS)
6461
+ items.add(item);
6462
+ }
6463
+ async remove(item) {
6464
+ const { items } = this;
6465
+ if (!items)
6466
+ return;
6467
+ items.delete(item);
6468
+ if (items.size > 0)
6469
+ return;
6470
+ const dir = this.path;
6471
+ try {
6472
+ await (0, import_promises3.readdir)(dir);
6473
+ } catch (err) {
6474
+ if (this._removeWatcher) {
6475
+ this._removeWatcher(sp2.dirname(dir), sp2.basename(dir));
6476
+ }
6477
+ }
6478
+ }
6479
+ has(item) {
6480
+ const { items } = this;
6481
+ if (!items)
6482
+ return;
6483
+ return items.has(item);
6484
+ }
6485
+ getChildren() {
6486
+ const { items } = this;
6487
+ if (!items)
6488
+ return [];
6489
+ return [...items.values()];
6490
+ }
6491
+ dispose() {
6492
+ this.items.clear();
6493
+ this.path = "";
6494
+ this._removeWatcher = EMPTY_FN;
6495
+ this.items = EMPTY_SET;
6496
+ Object.freeze(this);
6497
+ }
6498
+ };
6499
+ STAT_METHOD_F = "stat";
6500
+ STAT_METHOD_L = "lstat";
6501
+ WatchHelper = class {
6502
+ fsw;
6503
+ path;
6504
+ watchPath;
6505
+ fullWatchPath;
6506
+ dirParts;
6507
+ followSymlinks;
6508
+ statMethod;
6509
+ constructor(path15, follow, fsw) {
6510
+ this.fsw = fsw;
6511
+ const watchPath = path15;
6512
+ this.path = path15 = path15.replace(REPLACER_RE, "");
6513
+ this.watchPath = watchPath;
6514
+ this.fullWatchPath = sp2.resolve(watchPath);
6515
+ this.dirParts = [];
6516
+ this.dirParts.forEach((parts) => {
6517
+ if (parts.length > 1)
6518
+ parts.pop();
6519
+ });
6520
+ this.followSymlinks = follow;
6521
+ this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
6522
+ }
6523
+ entryPath(entry) {
6524
+ return sp2.join(this.watchPath, sp2.relative(this.watchPath, entry.fullPath));
6525
+ }
6526
+ filterPath(entry) {
6527
+ const { stats } = entry;
6528
+ if (stats && stats.isSymbolicLink())
6529
+ return this.filterDir(entry);
6530
+ const resolvedPath = this.entryPath(entry);
6531
+ return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
6532
+ }
6533
+ filterDir(entry) {
6534
+ return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
6535
+ }
6536
+ };
6537
+ FSWatcher = class extends import_node_events.EventEmitter {
6538
+ closed;
6539
+ options;
6540
+ _closers;
6541
+ _ignoredPaths;
6542
+ _throttled;
6543
+ _streams;
6544
+ _symlinkPaths;
6545
+ _watched;
6546
+ _pendingWrites;
6547
+ _pendingUnlinks;
6548
+ _readyCount;
6549
+ _emitReady;
6550
+ _closePromise;
6551
+ _userIgnored;
6552
+ _readyEmitted;
6553
+ _emitRaw;
6554
+ _boundRemove;
6555
+ _nodeFsHandler;
6556
+ // Not indenting methods for history sake; for now.
6557
+ constructor(_opts = {}) {
6558
+ super();
6559
+ this.closed = false;
6560
+ this._closers = /* @__PURE__ */ new Map();
6561
+ this._ignoredPaths = /* @__PURE__ */ new Set();
6562
+ this._throttled = /* @__PURE__ */ new Map();
6563
+ this._streams = /* @__PURE__ */ new Set();
6564
+ this._symlinkPaths = /* @__PURE__ */ new Map();
6565
+ this._watched = /* @__PURE__ */ new Map();
6566
+ this._pendingWrites = /* @__PURE__ */ new Map();
6567
+ this._pendingUnlinks = /* @__PURE__ */ new Map();
6568
+ this._readyCount = 0;
6569
+ this._readyEmitted = false;
6570
+ const awf = _opts.awaitWriteFinish;
6571
+ const DEF_AWF = { stabilityThreshold: 2e3, pollInterval: 100 };
6572
+ const opts = {
6573
+ // Defaults
6574
+ persistent: true,
6575
+ ignoreInitial: false,
6576
+ ignorePermissionErrors: false,
6577
+ interval: 100,
6578
+ binaryInterval: 300,
6579
+ followSymlinks: true,
6580
+ usePolling: false,
6581
+ // useAsync: false,
6582
+ atomic: true,
6583
+ // NOTE: overwritten later (depends on usePolling)
6584
+ ..._opts,
6585
+ // Change format
6586
+ ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
6587
+ awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? { ...DEF_AWF, ...awf } : false
6588
+ };
6589
+ if (isIBMi)
6590
+ opts.usePolling = true;
6591
+ if (opts.atomic === void 0)
6592
+ opts.atomic = !opts.usePolling;
6593
+ const envPoll = process.env.CHOKIDAR_USEPOLLING;
6594
+ if (envPoll !== void 0) {
6595
+ const envLower = envPoll.toLowerCase();
6596
+ if (envLower === "false" || envLower === "0")
6597
+ opts.usePolling = false;
6598
+ else if (envLower === "true" || envLower === "1")
6599
+ opts.usePolling = true;
6600
+ else
6601
+ opts.usePolling = !!envLower;
6602
+ }
6603
+ const envInterval = process.env.CHOKIDAR_INTERVAL;
6604
+ if (envInterval)
6605
+ opts.interval = Number.parseInt(envInterval, 10);
6606
+ let readyCalls = 0;
6607
+ this._emitReady = () => {
6608
+ readyCalls++;
6609
+ if (readyCalls >= this._readyCount) {
6610
+ this._emitReady = EMPTY_FN;
6611
+ this._readyEmitted = true;
6612
+ process.nextTick(() => this.emit(EVENTS.READY));
6613
+ }
6614
+ };
6615
+ this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args);
6616
+ this._boundRemove = this._remove.bind(this);
6617
+ this.options = opts;
6618
+ this._nodeFsHandler = new NodeFsHandler(this);
6619
+ Object.freeze(opts);
6620
+ }
6621
+ _addIgnoredPath(matcher) {
6622
+ if (isMatcherObject(matcher)) {
6623
+ for (const ignored of this._ignoredPaths) {
6624
+ if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) {
6625
+ return;
6626
+ }
6627
+ }
6628
+ }
6629
+ this._ignoredPaths.add(matcher);
6630
+ }
6631
+ _removeIgnoredPath(matcher) {
6632
+ this._ignoredPaths.delete(matcher);
6633
+ if (typeof matcher === "string") {
6634
+ for (const ignored of this._ignoredPaths) {
6635
+ if (isMatcherObject(ignored) && ignored.path === matcher) {
6636
+ this._ignoredPaths.delete(ignored);
6637
+ }
6638
+ }
6639
+ }
6640
+ }
6641
+ // Public methods
6642
+ /**
6643
+ * Adds paths to be watched on an existing FSWatcher instance.
6644
+ * @param paths_ file or file list. Other arguments are unused
6645
+ */
6646
+ add(paths_, _origAdd, _internal) {
6647
+ const { cwd } = this.options;
6648
+ this.closed = false;
6649
+ this._closePromise = void 0;
6650
+ let paths = unifyPaths(paths_);
6651
+ if (cwd) {
6652
+ paths = paths.map((path15) => {
6653
+ const absPath = getAbsolutePath(path15, cwd);
6654
+ return absPath;
6655
+ });
6656
+ }
6657
+ paths.forEach((path15) => {
6658
+ this._removeIgnoredPath(path15);
6659
+ });
6660
+ this._userIgnored = void 0;
6661
+ if (!this._readyCount)
6662
+ this._readyCount = 0;
6663
+ this._readyCount += paths.length;
6664
+ Promise.all(paths.map(async (path15) => {
6665
+ const res = await this._nodeFsHandler._addToNodeFs(path15, !_internal, void 0, 0, _origAdd);
6666
+ if (res)
6667
+ this._emitReady();
6668
+ return res;
6669
+ })).then((results) => {
6670
+ if (this.closed)
6671
+ return;
6672
+ results.forEach((item) => {
6673
+ if (item)
6674
+ this.add(sp2.dirname(item), sp2.basename(_origAdd || item));
6675
+ });
6676
+ });
6677
+ return this;
6678
+ }
6679
+ /**
6680
+ * Close watchers or start ignoring events from specified paths.
6681
+ */
6682
+ unwatch(paths_) {
6683
+ if (this.closed)
6684
+ return this;
6685
+ const paths = unifyPaths(paths_);
6686
+ const { cwd } = this.options;
6687
+ paths.forEach((path15) => {
6688
+ if (!sp2.isAbsolute(path15) && !this._closers.has(path15)) {
6689
+ if (cwd)
6690
+ path15 = sp2.join(cwd, path15);
6691
+ path15 = sp2.resolve(path15);
6692
+ }
6693
+ this._closePath(path15);
6694
+ this._addIgnoredPath(path15);
6695
+ if (this._watched.has(path15)) {
6696
+ this._addIgnoredPath({
6697
+ path: path15,
6698
+ recursive: true
6699
+ });
6700
+ }
6701
+ this._userIgnored = void 0;
6702
+ });
6703
+ return this;
6704
+ }
6705
+ /**
6706
+ * Close watchers and remove all listeners from watched paths.
6707
+ */
6708
+ close() {
6709
+ if (this._closePromise) {
6710
+ return this._closePromise;
6711
+ }
6712
+ this.closed = true;
6713
+ this.removeAllListeners();
6714
+ const closers = [];
6715
+ this._closers.forEach((closerList) => closerList.forEach((closer) => {
6716
+ const promise2 = closer();
6717
+ if (promise2 instanceof Promise)
6718
+ closers.push(promise2);
6719
+ }));
6720
+ this._streams.forEach((stream) => stream.destroy());
6721
+ this._userIgnored = void 0;
6722
+ this._readyCount = 0;
6723
+ this._readyEmitted = false;
6724
+ this._watched.forEach((dirent) => dirent.dispose());
6725
+ this._closers.clear();
6726
+ this._watched.clear();
6727
+ this._streams.clear();
6728
+ this._symlinkPaths.clear();
6729
+ this._throttled.clear();
6730
+ this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve();
6731
+ return this._closePromise;
6732
+ }
6733
+ /**
6734
+ * Expose list of watched paths
6735
+ * @returns for chaining
6736
+ */
6737
+ getWatched() {
6738
+ const watchList = {};
6739
+ this._watched.forEach((entry, dir) => {
6740
+ const key = this.options.cwd ? sp2.relative(this.options.cwd, dir) : dir;
6741
+ const index = key || ONE_DOT;
6742
+ watchList[index] = entry.getChildren().sort();
6743
+ });
6744
+ return watchList;
6745
+ }
6746
+ emitWithAll(event, args) {
6747
+ this.emit(event, ...args);
6748
+ if (event !== EVENTS.ERROR)
6749
+ this.emit(EVENTS.ALL, event, ...args);
6750
+ }
6751
+ // Common helpers
6752
+ // --------------
6753
+ /**
6754
+ * Normalize and emit events.
6755
+ * Calling _emit DOES NOT MEAN emit() would be called!
6756
+ * @param event Type of event
6757
+ * @param path File or directory path
6758
+ * @param stats arguments to be passed with event
6759
+ * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
6760
+ */
6761
+ async _emit(event, path15, stats) {
6762
+ if (this.closed)
6763
+ return;
6764
+ const opts = this.options;
6765
+ if (isWindows)
6766
+ path15 = sp2.normalize(path15);
6767
+ if (opts.cwd)
6768
+ path15 = sp2.relative(opts.cwd, path15);
6769
+ const args = [path15];
6770
+ if (stats != null)
6771
+ args.push(stats);
6772
+ const awf = opts.awaitWriteFinish;
6773
+ let pw;
6774
+ if (awf && (pw = this._pendingWrites.get(path15))) {
6775
+ pw.lastChange = /* @__PURE__ */ new Date();
6776
+ return this;
6777
+ }
6778
+ if (opts.atomic) {
6779
+ if (event === EVENTS.UNLINK) {
6780
+ this._pendingUnlinks.set(path15, [event, ...args]);
6781
+ setTimeout(() => {
6782
+ this._pendingUnlinks.forEach((entry, path16) => {
6783
+ this.emit(...entry);
6784
+ this.emit(EVENTS.ALL, ...entry);
6785
+ this._pendingUnlinks.delete(path16);
6786
+ });
6787
+ }, typeof opts.atomic === "number" ? opts.atomic : 100);
6788
+ return this;
6789
+ }
6790
+ if (event === EVENTS.ADD && this._pendingUnlinks.has(path15)) {
6791
+ event = EVENTS.CHANGE;
6792
+ this._pendingUnlinks.delete(path15);
6793
+ }
6794
+ }
6795
+ if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
6796
+ const awfEmit = (err, stats2) => {
6797
+ if (err) {
6798
+ event = EVENTS.ERROR;
6799
+ args[0] = err;
6800
+ this.emitWithAll(event, args);
6801
+ } else if (stats2) {
6802
+ if (args.length > 1) {
6803
+ args[1] = stats2;
6804
+ } else {
6805
+ args.push(stats2);
6806
+ }
6807
+ this.emitWithAll(event, args);
6808
+ }
6809
+ };
6810
+ this._awaitWriteFinish(path15, awf.stabilityThreshold, event, awfEmit);
6811
+ return this;
6812
+ }
6813
+ if (event === EVENTS.CHANGE) {
6814
+ const isThrottled = !this._throttle(EVENTS.CHANGE, path15, 50);
6815
+ if (isThrottled)
6816
+ return this;
6817
+ }
6818
+ if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
6819
+ const fullPath = opts.cwd ? sp2.join(opts.cwd, path15) : path15;
6820
+ let stats2;
6821
+ try {
6822
+ stats2 = await (0, import_promises3.stat)(fullPath);
6823
+ } catch (err) {
6824
+ }
6825
+ if (!stats2 || this.closed)
6826
+ return;
6827
+ args.push(stats2);
6828
+ }
6829
+ this.emitWithAll(event, args);
6830
+ return this;
6831
+ }
6832
+ /**
6833
+ * Common handler for errors
6834
+ * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
6835
+ */
6836
+ _handleError(error48) {
6837
+ const code = error48 && error48.code;
6838
+ if (error48 && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) {
6839
+ this.emit(EVENTS.ERROR, error48);
6840
+ }
6841
+ return error48 || this.closed;
6842
+ }
6843
+ /**
6844
+ * Helper utility for throttling
6845
+ * @param actionType type being throttled
6846
+ * @param path being acted upon
6847
+ * @param timeout duration of time to suppress duplicate actions
6848
+ * @returns tracking object or false if action should be suppressed
6849
+ */
6850
+ _throttle(actionType, path15, timeout) {
6851
+ if (!this._throttled.has(actionType)) {
6852
+ this._throttled.set(actionType, /* @__PURE__ */ new Map());
6853
+ }
6854
+ const action = this._throttled.get(actionType);
6855
+ if (!action)
6856
+ throw new Error("invalid throttle");
6857
+ const actionPath = action.get(path15);
6858
+ if (actionPath) {
6859
+ actionPath.count++;
6860
+ return false;
6861
+ }
6862
+ let timeoutObject;
6863
+ const clear = () => {
6864
+ const item = action.get(path15);
6865
+ const count = item ? item.count : 0;
6866
+ action.delete(path15);
6867
+ clearTimeout(timeoutObject);
6868
+ if (item)
6869
+ clearTimeout(item.timeoutObject);
6870
+ return count;
6871
+ };
6872
+ timeoutObject = setTimeout(clear, timeout);
6873
+ const thr = { timeoutObject, clear, count: 0 };
6874
+ action.set(path15, thr);
6875
+ return thr;
6876
+ }
6877
+ _incrReadyCount() {
6878
+ return this._readyCount++;
6879
+ }
6880
+ /**
6881
+ * Awaits write operation to finish.
6882
+ * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
6883
+ * @param path being acted upon
6884
+ * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
6885
+ * @param event
6886
+ * @param awfEmit Callback to be called when ready for event to be emitted.
6887
+ */
6888
+ _awaitWriteFinish(path15, threshold, event, awfEmit) {
6889
+ const awf = this.options.awaitWriteFinish;
6890
+ if (typeof awf !== "object")
6891
+ return;
6892
+ const pollInterval = awf.pollInterval;
6893
+ let timeoutHandler;
6894
+ let fullPath = path15;
6895
+ if (this.options.cwd && !sp2.isAbsolute(path15)) {
6896
+ fullPath = sp2.join(this.options.cwd, path15);
6897
+ }
6898
+ const now = /* @__PURE__ */ new Date();
6899
+ const writes = this._pendingWrites;
6900
+ function awaitWriteFinishFn(prevStat) {
6901
+ (0, import_node_fs2.stat)(fullPath, (err, curStat) => {
6902
+ if (err || !writes.has(path15)) {
6903
+ if (err && err.code !== "ENOENT")
6904
+ awfEmit(err);
6905
+ return;
6906
+ }
6907
+ const now2 = Number(/* @__PURE__ */ new Date());
6908
+ if (prevStat && curStat.size !== prevStat.size) {
6909
+ writes.get(path15).lastChange = now2;
6910
+ }
6911
+ const pw = writes.get(path15);
6912
+ const df = now2 - pw.lastChange;
6913
+ if (df >= threshold) {
6914
+ writes.delete(path15);
6915
+ awfEmit(void 0, curStat);
6916
+ } else {
6917
+ timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
6918
+ }
6919
+ });
6920
+ }
6921
+ if (!writes.has(path15)) {
6922
+ writes.set(path15, {
6923
+ lastChange: now,
6924
+ cancelWait: () => {
6925
+ writes.delete(path15);
6926
+ clearTimeout(timeoutHandler);
6927
+ return event;
6928
+ }
6929
+ });
6930
+ timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
6931
+ }
6932
+ }
6933
+ /**
6934
+ * Determines whether user has asked to ignore this path.
6935
+ */
6936
+ _isIgnored(path15, stats) {
6937
+ if (this.options.atomic && DOT_RE.test(path15))
6938
+ return true;
6939
+ if (!this._userIgnored) {
6940
+ const { cwd } = this.options;
6941
+ const ign = this.options.ignored;
6942
+ const ignored = (ign || []).map(normalizeIgnored(cwd));
6943
+ const ignoredPaths = [...this._ignoredPaths];
6944
+ const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];
6945
+ this._userIgnored = anymatch(list, void 0);
6946
+ }
6947
+ return this._userIgnored(path15, stats);
6948
+ }
6949
+ _isntIgnored(path15, stat4) {
6950
+ return !this._isIgnored(path15, stat4);
6951
+ }
6952
+ /**
6953
+ * Provides a set of common helpers and properties relating to symlink handling.
6954
+ * @param path file or directory pattern being watched
6955
+ */
6956
+ _getWatchHelpers(path15) {
6957
+ return new WatchHelper(path15, this.options.followSymlinks, this);
6958
+ }
6959
+ // Directory helpers
6960
+ // -----------------
6961
+ /**
6962
+ * Provides directory tracking objects
6963
+ * @param directory path of the directory
6964
+ */
6965
+ _getWatchedDir(directory) {
6966
+ const dir = sp2.resolve(directory);
6967
+ if (!this._watched.has(dir))
6968
+ this._watched.set(dir, new DirEntry(dir, this._boundRemove));
6969
+ return this._watched.get(dir);
6970
+ }
6971
+ // File helpers
6972
+ // ------------
6973
+ /**
6974
+ * Check for read permissions: https://stackoverflow.com/a/11781404/1358405
6975
+ */
6976
+ _hasReadPermissions(stats) {
6977
+ if (this.options.ignorePermissionErrors)
6978
+ return true;
6979
+ return Boolean(Number(stats.mode) & 256);
6980
+ }
6981
+ /**
6982
+ * Handles emitting unlink events for
6983
+ * files and directories, and via recursion, for
6984
+ * files and directories within directories that are unlinked
6985
+ * @param directory within which the following item is located
6986
+ * @param item base path of item/directory
6987
+ */
6988
+ _remove(directory, item, isDirectory) {
6989
+ const path15 = sp2.join(directory, item);
6990
+ const fullPath = sp2.resolve(path15);
6991
+ isDirectory = isDirectory != null ? isDirectory : this._watched.has(path15) || this._watched.has(fullPath);
6992
+ if (!this._throttle("remove", path15, 100))
6993
+ return;
6994
+ if (!isDirectory && this._watched.size === 1) {
6995
+ this.add(directory, item, true);
6996
+ }
6997
+ const wp = this._getWatchedDir(path15);
6998
+ const nestedDirectoryChildren = wp.getChildren();
6999
+ nestedDirectoryChildren.forEach((nested) => this._remove(path15, nested));
7000
+ const parent = this._getWatchedDir(directory);
7001
+ const wasTracked = parent.has(item);
7002
+ parent.remove(item);
7003
+ if (this._symlinkPaths.has(fullPath)) {
7004
+ this._symlinkPaths.delete(fullPath);
7005
+ }
7006
+ let relPath = path15;
7007
+ if (this.options.cwd)
7008
+ relPath = sp2.relative(this.options.cwd, path15);
7009
+ if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
7010
+ const event = this._pendingWrites.get(relPath).cancelWait();
7011
+ if (event === EVENTS.ADD)
7012
+ return;
7013
+ }
7014
+ this._watched.delete(path15);
7015
+ this._watched.delete(fullPath);
7016
+ const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
7017
+ if (wasTracked && !this._isIgnored(path15))
7018
+ this._emit(eventName, path15);
7019
+ this._closePath(path15);
7020
+ }
7021
+ /**
7022
+ * Closes all watchers for a path
7023
+ */
7024
+ _closePath(path15) {
7025
+ this._closeFile(path15);
7026
+ const dir = sp2.dirname(path15);
7027
+ this._getWatchedDir(dir).remove(sp2.basename(path15));
7028
+ }
7029
+ /**
7030
+ * Closes only file-specific watchers
7031
+ */
7032
+ _closeFile(path15) {
7033
+ const closers = this._closers.get(path15);
7034
+ if (!closers)
7035
+ return;
7036
+ closers.forEach((closer) => closer());
7037
+ this._closers.delete(path15);
7038
+ }
7039
+ _addPathCloser(path15, closer) {
7040
+ if (!closer)
7041
+ return;
7042
+ let list = this._closers.get(path15);
7043
+ if (!list) {
7044
+ list = [];
7045
+ this._closers.set(path15, list);
7046
+ }
7047
+ list.push(closer);
7048
+ }
7049
+ _readdirp(root, opts) {
7050
+ if (this.closed)
7051
+ return;
7052
+ const options = { type: EVENTS.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };
7053
+ let stream = readdirp(root, options);
7054
+ this._streams.add(stream);
7055
+ stream.once(STR_CLOSE, () => {
7056
+ stream = void 0;
7057
+ });
7058
+ stream.once(STR_END, () => {
7059
+ if (stream) {
7060
+ this._streams.delete(stream);
7061
+ stream = void 0;
7062
+ }
7063
+ });
7064
+ return stream;
7065
+ }
7066
+ };
7067
+ }
7068
+ });
7069
+
5304
7070
  // ../../oss/packages/daemon-core/src/providers/provider-loader.ts
5305
7071
  var fs5, path6, os7, ProviderLoader;
5306
7072
  var init_provider_loader = __esm({
@@ -5309,11 +7075,11 @@ var init_provider_loader = __esm({
5309
7075
  fs5 = __toESM(require("fs"));
5310
7076
  path6 = __toESM(require("path"));
5311
7077
  os7 = __toESM(require("os"));
7078
+ init_chokidar();
5312
7079
  init_ide_detector();
5313
7080
  init_logger();
5314
7081
  ProviderLoader = class _ProviderLoader {
5315
7082
  providers = /* @__PURE__ */ new Map();
5316
- builtinDirs;
5317
7083
  userDir;
5318
7084
  upstreamDir;
5319
7085
  disableUpstream;
@@ -5328,36 +7094,31 @@ var init_provider_loader = __esm({
5328
7094
  static GITHUB_TARBALL_URL = "https://github.com/vilmire/adhdev-providers/archive/refs/heads/main.tar.gz";
5329
7095
  static META_FILE = ".meta.json";
5330
7096
  constructor(options) {
5331
- if (options?.builtinDir) {
5332
- this.builtinDirs = Array.isArray(options.builtinDir) ? options.builtinDir : [options.builtinDir];
7097
+ this.logFn = options?.logFn || LOG.forComponent("Provider").asLogFn();
7098
+ const defaultProvidersDir = path6.join(os7.homedir(), ".adhdev", "providers");
7099
+ if (options?.userDir) {
7100
+ this.userDir = options.userDir;
7101
+ this.log(`Config 'providerDir' applied: ${this.userDir}`);
5333
7102
  } else {
5334
- this.builtinDirs = [];
7103
+ const localRepoPath = path6.resolve(__dirname, "../../../../../adhdev-providers");
7104
+ if (fs5.existsSync(localRepoPath)) {
7105
+ this.userDir = localRepoPath;
7106
+ this.log(`Auto-detected local public repository: ${this.userDir} (Dev workspace speedup)`);
7107
+ } else {
7108
+ this.userDir = defaultProvidersDir;
7109
+ this.log(`Using default user providers directory: ${this.userDir}`);
7110
+ }
5335
7111
  }
5336
- const defaultProvidersDir = path6.join(os7.homedir(), ".adhdev", "providers");
5337
- this.userDir = options?.userDir || defaultProvidersDir;
5338
7112
  this.upstreamDir = path6.join(defaultProvidersDir, ".upstream");
5339
7113
  this.disableUpstream = options?.disableUpstream ?? false;
5340
- this.logFn = options?.logFn || LOG.forComponent("Provider").asLogFn();
5341
7114
  }
5342
7115
  log(msg) {
5343
7116
  this.logFn(`[ProviderLoader] ${msg}`);
5344
7117
  }
5345
7118
  // ─── Public API ────────────────────────────────
5346
7119
  /**
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
- */
7120
+ * User override root (~/.adhdev/providers by default).
7121
+ */
5361
7122
  getUserDir() {
5362
7123
  return this.userDir;
5363
7124
  }
@@ -5368,11 +7129,11 @@ var init_provider_loader = __esm({
5368
7129
  return this.upstreamDir;
5369
7130
  }
5370
7131
  /**
5371
- * Provider search order for on-disk lookups.
5372
- * Highest-priority editable overrides come first.
5373
- */
7132
+ * Provider search order for on-disk lookups.
7133
+ * Highest-priority editable overrides come first.
7134
+ */
5374
7135
  getProviderRoots() {
5375
- return [this.userDir, this.upstreamDir, ...this.builtinDirs];
7136
+ return [this.userDir, this.upstreamDir];
5376
7137
  }
5377
7138
  /**
5378
7139
  * Canonical provider directory shape for a given root.
@@ -5393,16 +7154,9 @@ var init_provider_loader = __esm({
5393
7154
  return this.getProviderDir(this.upstreamDir, category, type);
5394
7155
  }
5395
7156
  /**
5396
- * Canonical builtin directory for a provider.
7157
+ * Find the on-disk directory for a provider by type.
7158
+ * Search order: user override → upstream.
5397
7159
  */
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
7160
  findProviderDir(type) {
5407
7161
  return this.findProviderDirInternal(type);
5408
7162
  }
@@ -5499,12 +7253,15 @@ var init_provider_loader = __esm({
5499
7253
  const result = [];
5500
7254
  for (const p of this.providers.values()) {
5501
7255
  if ((p.category === "cli" || p.category === "acp") && p.spawn?.command) {
7256
+ const verCmdConfig = p.versionCommand;
7257
+ const versionCommand = typeof verCmdConfig === "object" && verCmdConfig !== null ? verCmdConfig[process.platform] : verCmdConfig;
5502
7258
  result.push({
5503
7259
  id: p.type,
5504
7260
  displayName: p.displayName || p.name,
5505
7261
  icon: p.icon || "\u{1F527}",
5506
7262
  command: p.spawn.command,
5507
- category: p.category
7263
+ category: p.category,
7264
+ ...typeof versionCommand === "string" && versionCommand.trim() ? { versionCommand: versionCommand.trim() } : {}
5508
7265
  });
5509
7266
  }
5510
7267
  }
@@ -5767,13 +7524,12 @@ var init_provider_loader = __esm({
5767
7524
  }
5768
7525
  }
5769
7526
  const result = this.buildScriptWrappersFromDir(dir);
5770
- this.log(` [loadScriptsFromDir] ${type}: built wrappers from ${dir} (${Object.keys(result).length} scripts)`);
5771
7527
  this.scriptsCache.set(dir, result);
5772
7528
  return result;
5773
7529
  }
5774
7530
  /**
5775
- * Hot-reload: start watching for file changes
5776
- */
7531
+ * Hot-reload: start watching for file changes
7532
+ */
5777
7533
  watch() {
5778
7534
  this.stopWatch();
5779
7535
  const watchDir = (dir) => {
@@ -5785,18 +7541,27 @@ var init_provider_loader = __esm({
5785
7541
  }
5786
7542
  }
5787
7543
  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
- }
7544
+ const watcher = watch(dir, {
7545
+ ignored: /(^|[\/\\])\.\./,
7546
+ // ignore dotfiles
7547
+ persistent: true,
7548
+ ignoreInitial: true,
7549
+ awaitWriteFinish: { stabilityThreshold: 200, pollInterval: 50 }
5793
7550
  });
7551
+ const handleChange = (filePath) => {
7552
+ if (filePath.endsWith(".js") || filePath.endsWith(".json")) {
7553
+ this.log(`File changed: ${path6.basename(filePath)}, reloading...`);
7554
+ this.reload();
7555
+ }
7556
+ };
7557
+ watcher.on("add", handleChange).on("change", handleChange).on("unlink", handleChange);
7558
+ watcher.on("error", (err) => this.log(`Watch error: ${err.message}`));
5794
7559
  this.watchers.push(watcher);
7560
+ this.log(`Hot-reload watcher active: ${dir}`);
5795
7561
  } catch (e) {
5796
7562
  this.log(`Watch failed for ${dir}: ${e.message}`);
5797
7563
  }
5798
7564
  };
5799
- this.builtinDirs.forEach((dir) => watchDir(dir));
5800
7565
  watchDir(this.userDir);
5801
7566
  }
5802
7567
  /**
@@ -5857,7 +7622,7 @@ var init_provider_loader = __esm({
5857
7622
  return { updated: false };
5858
7623
  }
5859
7624
  try {
5860
- const etag = await new Promise((resolve7, reject) => {
7625
+ const etag = await new Promise((resolve10, reject) => {
5861
7626
  const options = {
5862
7627
  method: "HEAD",
5863
7628
  hostname: "github.com",
@@ -5875,7 +7640,7 @@ var init_provider_loader = __esm({
5875
7640
  headers: { "User-Agent": "adhdev-launcher" },
5876
7641
  timeout: 1e4
5877
7642
  }, (res2) => {
5878
- resolve7(res2.headers.etag || res2.headers["last-modified"] || "");
7643
+ resolve10(res2.headers.etag || res2.headers["last-modified"] || "");
5879
7644
  });
5880
7645
  req2.on("error", reject);
5881
7646
  req2.on("timeout", () => {
@@ -5884,7 +7649,7 @@ var init_provider_loader = __esm({
5884
7649
  });
5885
7650
  req2.end();
5886
7651
  } else {
5887
- resolve7(res.headers.etag || res.headers["last-modified"] || "");
7652
+ resolve10(res.headers.etag || res.headers["last-modified"] || "");
5888
7653
  }
5889
7654
  });
5890
7655
  req.on("error", reject);
@@ -5948,7 +7713,7 @@ var init_provider_loader = __esm({
5948
7713
  downloadFile(url2, destPath) {
5949
7714
  const https = require("https");
5950
7715
  const http3 = require("http");
5951
- return new Promise((resolve7, reject) => {
7716
+ return new Promise((resolve10, reject) => {
5952
7717
  const doRequest = (reqUrl, redirectCount = 0) => {
5953
7718
  if (redirectCount > 5) {
5954
7719
  reject(new Error("Too many redirects"));
@@ -5968,7 +7733,7 @@ var init_provider_loader = __esm({
5968
7733
  res.pipe(ws2);
5969
7734
  ws2.on("finish", () => {
5970
7735
  ws2.close();
5971
- resolve7();
7736
+ resolve10();
5972
7737
  });
5973
7738
  ws2.on("error", reject);
5974
7739
  });
@@ -6240,8 +8005,8 @@ var init_provider_loader = __esm({
6240
8005
  const existed = this.providers.has(mod.type);
6241
8006
  this.providers.set(mod.type, mod);
6242
8007
  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" : "";
8008
+ const source = d.startsWith(this.userDir) && !d.includes(".upstream") ? "user" : "upstream";
8009
+ const overrideWarning = existed && source === "user" ? " \u26A0 OVERRIDES upstream" : "";
6245
8010
  this.log(` ${existed ? "\u{1F504}" : "\u2705"} ${mod.type} (${mod.category}) \u2014 ${mod.name} [${source}]${overrideWarning}`);
6246
8011
  }
6247
8012
  } catch (e) {
@@ -6288,9 +8053,9 @@ var init_provider_loader = __esm({
6288
8053
  }
6289
8054
  }
6290
8055
  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);
8056
+ const normalize3 = (v2) => v2.split(/[-_+]/)[0].split(".").map((x) => parseInt(x, 10) || 0);
8057
+ const pa2 = normalize3(a);
8058
+ const pb = normalize3(b2);
6294
8059
  for (let i = 0; i < Math.max(pa2.length, pb.length); i++) {
6295
8060
  const va2 = pa2[i] || 0;
6296
8061
  const vb = pb[i] || 0;
@@ -6334,17 +8099,17 @@ async function findFreePort(ports) {
6334
8099
  throw new Error("No free port found");
6335
8100
  }
6336
8101
  function checkPortFree(port) {
6337
- return new Promise((resolve7) => {
8102
+ return new Promise((resolve10) => {
6338
8103
  const server = net.createServer();
6339
8104
  server.unref();
6340
- server.on("error", () => resolve7(false));
8105
+ server.on("error", () => resolve10(false));
6341
8106
  server.listen(port, "127.0.0.1", () => {
6342
- server.close(() => resolve7(true));
8107
+ server.close(() => resolve10(true));
6343
8108
  });
6344
8109
  });
6345
8110
  }
6346
8111
  async function isCdpActive(port) {
6347
- return new Promise((resolve7) => {
8112
+ return new Promise((resolve10) => {
6348
8113
  const req = require("http").get(`http://127.0.0.1:${port}/json/version`, {
6349
8114
  timeout: 2e3
6350
8115
  }, (res) => {
@@ -6353,16 +8118,16 @@ async function isCdpActive(port) {
6353
8118
  res.on("end", () => {
6354
8119
  try {
6355
8120
  const info = JSON.parse(data);
6356
- resolve7(!!info["WebKit-Version"] || !!info["Browser"]);
8121
+ resolve10(!!info["WebKit-Version"] || !!info["Browser"]);
6357
8122
  } catch {
6358
- resolve7(false);
8123
+ resolve10(false);
6359
8124
  }
6360
8125
  });
6361
8126
  });
6362
- req.on("error", () => resolve7(false));
8127
+ req.on("error", () => resolve10(false));
6363
8128
  req.on("timeout", () => {
6364
8129
  req.destroy();
6365
- resolve7(false);
8130
+ resolve10(false);
6366
8131
  });
6367
8132
  });
6368
8133
  }
@@ -6710,8 +8475,8 @@ function cleanOldFiles() {
6710
8475
  }
6711
8476
  function checkSize() {
6712
8477
  try {
6713
- const stat = fs6.statSync(currentFile);
6714
- if (stat.size > MAX_FILE_SIZE) {
8478
+ const stat4 = fs6.statSync(currentFile);
8479
+ if (stat4.size > MAX_FILE_SIZE) {
6715
8480
  const backup = currentFile.replace(".jsonl", ".1.jsonl");
6716
8481
  try {
6717
8482
  fs6.unlinkSync(backup);
@@ -16564,6 +18329,12 @@ __export(provider_cli_adapter_exports, {
16564
18329
  function stripAnsi(str) {
16565
18330
  return str.replace(/\x1B\[\d*[A-HJKSTfG]/g, " ").replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, "").replace(/\x1B\][^\x07]*\x07/g, "").replace(/\x1B\][^\x1B]*\x1B\\/g, "").replace(/ +/g, " ");
16566
18331
  }
18332
+ function stripTerminalNoise(str) {
18333
+ return String(str || "").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/g, "").replace(/(^|[\s([])(?:\??\d{1,4}(?:;\d{1,4})*[A-Za-z])(?=$|[\s)\]])/g, "$1").replace(/(^|[\s([])(?:\[\??\d{1,4}(?:;\d{1,4})*[A-Za-z])(?=$|[\s)\]])/g, "$1").replace(/(^|[\s([])(?:\d{1,4};\?)(?=$|[\s)\]])/g, "$1").replace(/\r+/g, "\n").replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").replace(/ {2,}/g, " ");
18334
+ }
18335
+ function sanitizeTerminalText(str) {
18336
+ return stripTerminalNoise(stripAnsi(str));
18337
+ }
16567
18338
  function findBinary(name) {
16568
18339
  const isWin = os12.platform() === "win32";
16569
18340
  try {
@@ -16719,9 +18490,9 @@ var init_provider_cli_adapter = __esm({
16719
18490
  const platformArch = `${os12.platform()}-${os12.arch()}`;
16720
18491
  const helper = path9.join(ptyDir, "prebuilds", platformArch, "spawn-helper");
16721
18492
  if (fs13.existsSync(helper)) {
16722
- const stat = fs13.statSync(helper);
16723
- if (!(stat.mode & 73)) {
16724
- fs13.chmodSync(helper, stat.mode | 493);
18493
+ const stat4 = fs13.statSync(helper);
18494
+ if (!(stat4.mode & 73)) {
18495
+ fs13.chmodSync(helper, stat4.mode | 493);
16725
18496
  LOG.info("CLI", "[node-pty] Fixed spawn-helper permissions");
16726
18497
  }
16727
18498
  }
@@ -16784,6 +18555,8 @@ var init_provider_cli_adapter = __esm({
16784
18555
  spawnAt = 0;
16785
18556
  // PTY I/O
16786
18557
  onPtyDataCallback = null;
18558
+ pendingOutputParseBuffer = "";
18559
+ pendingOutputParseTimer = null;
16787
18560
  ptyOutputBuffer = "";
16788
18561
  ptyOutputFlushTimer = null;
16789
18562
  // Server log forwarding
@@ -16794,6 +18567,9 @@ var init_provider_cli_adapter = __esm({
16794
18567
  // Approval state machine
16795
18568
  approvalTransitionBuffer = "";
16796
18569
  approvalExitTimeout = null;
18570
+ pendingScriptStatus = null;
18571
+ pendingScriptStatusSince = 0;
18572
+ pendingScriptStatusTimer = null;
16797
18573
  // Output settle debounce — fires after PTY output goes quiet
16798
18574
  settleTimer = null;
16799
18575
  settledBuffer = "";
@@ -16859,6 +18635,7 @@ var init_provider_cli_adapter = __esm({
16859
18635
  sendDelayMs;
16860
18636
  sendKey;
16861
18637
  submitStrategy;
18638
+ static SCRIPT_STATUS_DEBOUNCE_MS = 1e3;
16862
18639
  /** Inject CLI scripts after construction (e.g. when resolved by ProviderLoader) */
16863
18640
  setCliScripts(scripts) {
16864
18641
  this.cliScripts = scripts;
@@ -16879,6 +18656,16 @@ var init_provider_cli_adapter = __esm({
16879
18656
  setOnPtyData(callback) {
16880
18657
  this.onPtyDataCallback = callback;
16881
18658
  }
18659
+ flushPendingOutputParse() {
18660
+ if (this.pendingOutputParseTimer) {
18661
+ clearTimeout(this.pendingOutputParseTimer);
18662
+ this.pendingOutputParseTimer = null;
18663
+ }
18664
+ if (!this.pendingOutputParseBuffer) return;
18665
+ const rawData = this.pendingOutputParseBuffer;
18666
+ this.pendingOutputParseBuffer = "";
18667
+ this.handleOutput(rawData);
18668
+ }
16882
18669
  async spawn() {
16883
18670
  if (this.ptyProcess) return;
16884
18671
  if (!pty) throw new Error("node-pty is not installed");
@@ -16927,7 +18714,17 @@ var init_provider_cli_adapter = __esm({
16927
18714
  }
16928
18715
  }
16929
18716
  this.ptyProcess.onData((data) => {
16930
- this.handleOutput(data);
18717
+ if (Date.now() < this.resizeSuppressUntil) return;
18718
+ if (data.includes("\x1B[6n") || data.includes("\x1B[?6n")) {
18719
+ this.ptyProcess?.write("\x1B[1;1R");
18720
+ }
18721
+ this.pendingOutputParseBuffer += data;
18722
+ if (!this.pendingOutputParseTimer) {
18723
+ this.pendingOutputParseTimer = setTimeout(() => {
18724
+ this.pendingOutputParseTimer = null;
18725
+ this.flushPendingOutputParse();
18726
+ }, this.timeouts.ptyFlush);
18727
+ }
16931
18728
  if (this.onPtyDataCallback) {
16932
18729
  this.ptyOutputBuffer += data;
16933
18730
  if (!this.ptyOutputFlushTimer) {
@@ -16943,6 +18740,7 @@ var init_provider_cli_adapter = __esm({
16943
18740
  });
16944
18741
  this.ptyProcess.onExit(({ exitCode }) => {
16945
18742
  LOG.info("CLI", `[${this.cliType}] Exit code ${exitCode}`);
18743
+ this.flushPendingOutputParse();
16946
18744
  this.ptyProcess = null;
16947
18745
  this.setStatus("stopped", "pty_exit");
16948
18746
  this.ready = false;
@@ -16962,13 +18760,9 @@ var init_provider_cli_adapter = __esm({
16962
18760
  }
16963
18761
  // ─── Output Handling ────────────────────────────
16964
18762
  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
18763
  this.terminalScreen.write(rawData);
16970
18764
  this.terminalHistory = mergeTerminalHistory(this.terminalHistory, this.terminalScreen.getText());
16971
- const cleanData = stripAnsi(rawData);
18765
+ const cleanData = sanitizeTerminalText(rawData);
16972
18766
  if (this.isWaitingForResponse && cleanData) {
16973
18767
  this.responseBuffer = (this.responseBuffer + cleanData).slice(-8e3);
16974
18768
  }
@@ -17065,24 +18859,39 @@ var init_provider_cli_adapter = __esm({
17065
18859
  const scriptStatus = rawScriptStatus;
17066
18860
  if (!scriptStatus) return;
17067
18861
  const prevStatus = this.currentStatus;
17068
- if (scriptStatus === "waiting_approval") {
17069
- const modalMessage = modal?.message || "";
17070
- const screenText = this.terminalScreen.getText() || this.accumulatedBuffer;
17071
- const autoAcceptPatterns = [
17072
- /be able to read, edit, and execute/i,
17073
- /Security guide/i,
17074
- /Enter to confirm/i,
17075
- /Quick safety check/i,
17076
- /Do you trust the files/i,
17077
- /Is this a project/i
17078
- ];
17079
- if (autoAcceptPatterns.some((p) => p.test(modalMessage) || p.test(screenText))) {
17080
- LOG.info("CLI", `[${this.cliType}] Auto-accepting startup dialog: ${modalMessage.slice(0, 80)}`);
17081
- setTimeout(() => this.ptyProcess?.write("\r"), 200);
17082
- this.lastApprovalResolvedAt = Date.now();
17083
- this.activeModal = null;
18862
+ const clearPendingScriptStatus = () => {
18863
+ this.pendingScriptStatus = null;
18864
+ this.pendingScriptStatusSince = 0;
18865
+ if (this.pendingScriptStatusTimer) {
18866
+ clearTimeout(this.pendingScriptStatusTimer);
18867
+ this.pendingScriptStatusTimer = null;
18868
+ }
18869
+ };
18870
+ const armPendingScriptStatus = (delayMs) => {
18871
+ if (this.pendingScriptStatusTimer) clearTimeout(this.pendingScriptStatusTimer);
18872
+ this.pendingScriptStatusTimer = setTimeout(() => {
18873
+ this.pendingScriptStatusTimer = null;
18874
+ this.settledBuffer = this.recentOutputBuffer;
18875
+ this.evaluateSettled();
18876
+ }, delayMs);
18877
+ };
18878
+ const shouldDebouncePromotion = (status) => prevStatus === "idle" && !this.isWaitingForResponse && !this.currentTurnScope && (status === "generating" || status === "waiting_approval");
18879
+ if (shouldDebouncePromotion(scriptStatus)) {
18880
+ if (this.pendingScriptStatus !== scriptStatus) {
18881
+ this.pendingScriptStatus = scriptStatus;
18882
+ this.pendingScriptStatusSince = now;
18883
+ armPendingScriptStatus(_ProviderCliAdapter.SCRIPT_STATUS_DEBOUNCE_MS);
17084
18884
  return;
17085
18885
  }
18886
+ const elapsed = now - this.pendingScriptStatusSince;
18887
+ if (elapsed < _ProviderCliAdapter.SCRIPT_STATUS_DEBOUNCE_MS) {
18888
+ armPendingScriptStatus(_ProviderCliAdapter.SCRIPT_STATUS_DEBOUNCE_MS - elapsed);
18889
+ return;
18890
+ }
18891
+ } else {
18892
+ clearPendingScriptStatus();
18893
+ }
18894
+ if (scriptStatus === "waiting_approval") {
17086
18895
  const inCooldown = this.lastApprovalResolvedAt && Date.now() - this.lastApprovalResolvedAt < this.timeouts.approvalCooldown;
17087
18896
  if (!inCooldown) {
17088
18897
  this.isWaitingForResponse = true;
@@ -17095,6 +18904,12 @@ var init_provider_cli_adapter = __esm({
17095
18904
  }
17096
18905
  }
17097
18906
  if (scriptStatus === "generating") {
18907
+ const screenText = this.terminalScreen.getText() || this.accumulatedBuffer;
18908
+ const noActiveTurn = !this.currentTurnScope;
18909
+ const looksIdleChrome = /(^|\n)\s*[❯›>]\s*(?:\n|$)/m.test(screenText) || /accept edits on/i.test(screenText) && (/Update available!/i.test(screenText) || /\/effort/i.test(screenText) || /^.*➜\s+\S+/m.test(screenText));
18910
+ if (prevStatus === "idle" && !this.isWaitingForResponse && noActiveTurn && !modal && looksIdleChrome) {
18911
+ return;
18912
+ }
17098
18913
  if (prevStatus === "waiting_approval") {
17099
18914
  if (this.approvalExitTimeout) {
17100
18915
  clearTimeout(this.approvalExitTimeout);
@@ -17316,7 +19131,7 @@ ${data.message || ""}`.trim();
17316
19131
  if (this.startupParseGate) {
17317
19132
  const deadline = Date.now() + 1e4;
17318
19133
  while (this.startupParseGate && Date.now() < deadline) {
17319
- await new Promise((resolve7) => setTimeout(resolve7, 50));
19134
+ await new Promise((resolve10) => setTimeout(resolve10, 50));
17320
19135
  }
17321
19136
  }
17322
19137
  if (!this.ready) throw new Error(`${this.cliName} not ready (status: ${this.currentStatus})`);
@@ -17453,6 +19268,16 @@ ${data.message || ""}`.trim();
17453
19268
  clearTimeout(this.submitRetryTimer);
17454
19269
  this.submitRetryTimer = null;
17455
19270
  }
19271
+ if (this.pendingOutputParseTimer) {
19272
+ clearTimeout(this.pendingOutputParseTimer);
19273
+ this.pendingOutputParseTimer = null;
19274
+ }
19275
+ this.pendingOutputParseBuffer = "";
19276
+ if (this.ptyOutputFlushTimer) {
19277
+ clearTimeout(this.ptyOutputFlushTimer);
19278
+ this.ptyOutputFlushTimer = null;
19279
+ }
19280
+ this.ptyOutputBuffer = "";
17456
19281
  if (this.ptyProcess) {
17457
19282
  this.ptyProcess.write("");
17458
19283
  setTimeout(() => {
@@ -17478,6 +19303,16 @@ ${data.message || ""}`.trim();
17478
19303
  this.currentTurnScope = null;
17479
19304
  this.submitRetryUsed = false;
17480
19305
  this.submitRetryPromptSnippet = "";
19306
+ if (this.pendingOutputParseTimer) {
19307
+ clearTimeout(this.pendingOutputParseTimer);
19308
+ this.pendingOutputParseTimer = null;
19309
+ }
19310
+ this.pendingOutputParseBuffer = "";
19311
+ if (this.ptyOutputFlushTimer) {
19312
+ clearTimeout(this.ptyOutputFlushTimer);
19313
+ this.ptyOutputFlushTimer = null;
19314
+ }
19315
+ this.ptyOutputBuffer = "";
17481
19316
  this.terminalScreen.reset();
17482
19317
  this.onStatusChange?.();
17483
19318
  }
@@ -17532,7 +19367,7 @@ ${data.message || ""}`.trim();
17532
19367
  committedMessages: this.committedMessages.slice(-20),
17533
19368
  structuredMessages: this.structuredMessages.slice(-20),
17534
19369
  messageCount: this.committedMessages.length,
17535
- screenText: this.terminalScreen.getText().slice(-4e3),
19370
+ screenText: sanitizeTerminalText(this.terminalScreen.getText()).slice(-4e3),
17536
19371
  terminalHistory: this.terminalHistory.slice(-8e3),
17537
19372
  currentTurnScope: this.currentTurnScope,
17538
19373
  startupBuffer: this.startupBuffer.slice(-4e3),
@@ -17541,6 +19376,7 @@ ${data.message || ""}`.trim();
17541
19376
  accumulatedBufferLength: this.accumulatedBuffer.length,
17542
19377
  accumulatedRawBufferLength: this.accumulatedRawBuffer.length,
17543
19378
  rawBufferPreview: this.accumulatedRawBuffer.slice(-1e3),
19379
+ sanitizedRawPreview: sanitizeTerminalText(this.accumulatedRawBuffer).slice(-1e3),
17544
19380
  responseBuffer: this.responseBuffer.slice(-1e3),
17545
19381
  isWaitingForResponse: this.isWaitingForResponse,
17546
19382
  activeModal: this.activeModal,
@@ -17555,6 +19391,8 @@ ${data.message || ""}`.trim();
17555
19391
  scriptNames: Object.keys(this.cliScripts).filter((k) => typeof this.cliScripts[k] === "function"),
17556
19392
  statusHistory: this.statusHistory.slice(-30),
17557
19393
  timeouts: this.timeouts,
19394
+ pendingOutputParseBufferLength: this.pendingOutputParseBuffer.length,
19395
+ pendingOutputParseScheduled: !!this.pendingOutputParseTimer,
17558
19396
  ptyAlive: !!this.ptyProcess
17559
19397
  };
17560
19398
  }
@@ -17622,19 +19460,6 @@ var init_cli_provider_instance = __esm({
17622
19460
  getState() {
17623
19461
  const adapterStatus = this.adapter.getStatus();
17624
19462
  const dirName = this.workingDir.split("/").filter(Boolean).pop() || "session";
17625
- const recentMessages = adapterStatus.messages.slice(-50).map((m) => {
17626
- const content = typeof m.content === "string" && m.content.length > 8e3 ? m.content.slice(0, 8e3) + "\n... (truncated)" : m.content;
17627
- return { ...m, content };
17628
- });
17629
- if (recentMessages.length > 0) {
17630
- const dirName2 = this.workingDir.split("/").filter(Boolean).pop() || "session";
17631
- this.historyWriter.appendNewMessages(
17632
- this.type,
17633
- recentMessages,
17634
- `${this.provider.name} \xB7 ${dirName2}`,
17635
- this.instanceId
17636
- );
17637
- }
17638
19463
  if (adapterStatus.terminalHistory?.trim()) {
17639
19464
  this.historyWriter.appendTerminalHistory(
17640
19465
  this.type,
@@ -17648,12 +19473,12 @@ var init_cli_provider_instance = __esm({
17648
19473
  name: this.provider.name,
17649
19474
  category: "cli",
17650
19475
  status: adapterStatus.status,
17651
- mode: this.settings.mode || "terminal",
19476
+ mode: "terminal",
17652
19477
  activeChat: {
17653
19478
  id: `${this.type}_${this.workingDir}`,
17654
19479
  title: `${this.provider.name} \xB7 ${dirName}`,
17655
19480
  status: adapterStatus.status,
17656
- messages: recentMessages,
19481
+ messages: [],
17657
19482
  activeModal: adapterStatus.activeModal,
17658
19483
  terminalHistory: adapterStatus.terminalHistory,
17659
19484
  inputContent: ""
@@ -17667,11 +19492,15 @@ var init_cli_provider_instance = __esm({
17667
19492
  }
17668
19493
  onEvent(event, data) {
17669
19494
  if (event === "send_message" && data?.text) {
17670
- this.adapter.sendMessage(data.text);
19495
+ void this.adapter.sendMessage(data.text).catch((e) => {
19496
+ LOG.warn("CLI", `[${this.type}] send_message failed: ${e?.message || e}`);
19497
+ });
17671
19498
  } else if (event === "server_connected" && data?.serverConn) {
17672
19499
  this.adapter.setServerConn(data.serverConn);
17673
19500
  } else if (event === "resolve_action" && data) {
17674
- this.adapter.resolveAction(data);
19501
+ void this.adapter.resolveAction(data).catch((e) => {
19502
+ LOG.warn("CLI", `[${this.type}] resolve_action failed: ${e?.message || e}`);
19503
+ });
17675
19504
  }
17676
19505
  }
17677
19506
  dispose() {
@@ -33859,8 +35688,8 @@ var init_acp = __esm({
33859
35688
  this.#requestHandler = requestHandler;
33860
35689
  this.#notificationHandler = notificationHandler;
33861
35690
  this.#stream = stream;
33862
- this.#closedPromise = new Promise((resolve7) => {
33863
- this.#abortController.signal.addEventListener("abort", () => resolve7());
35691
+ this.#closedPromise = new Promise((resolve10) => {
35692
+ this.#abortController.signal.addEventListener("abort", () => resolve10());
33864
35693
  });
33865
35694
  this.#receive();
33866
35695
  }
@@ -34009,8 +35838,8 @@ var init_acp = __esm({
34009
35838
  }
34010
35839
  async sendRequest(method, params) {
34011
35840
  const id = this.#nextRequestId++;
34012
- const responsePromise = new Promise((resolve7, reject) => {
34013
- this.#pendingResponses.set(id, { resolve: resolve7, reject });
35841
+ const responsePromise = new Promise((resolve10, reject) => {
35842
+ this.#pendingResponses.set(id, { resolve: resolve10, reject });
34014
35843
  });
34015
35844
  await this.#sendMessage({ jsonrpc: "2.0", id, method, params });
34016
35845
  return responsePromise;
@@ -34542,13 +36371,13 @@ var init_acp_provider_instance = __esm({
34542
36371
  }
34543
36372
  this.currentStatus = "waiting_approval";
34544
36373
  this.detectStatusTransition();
34545
- const approved = await new Promise((resolve7) => {
34546
- this.permissionResolvers.push(resolve7);
36374
+ const approved = await new Promise((resolve10) => {
36375
+ this.permissionResolvers.push(resolve10);
34547
36376
  setTimeout(() => {
34548
- const idx = this.permissionResolvers.indexOf(resolve7);
36377
+ const idx = this.permissionResolvers.indexOf(resolve10);
34549
36378
  if (idx >= 0) {
34550
36379
  this.permissionResolvers.splice(idx, 1);
34551
- resolve7(false);
36380
+ resolve10(false);
34552
36381
  }
34553
36382
  }, 3e5);
34554
36383
  });
@@ -36113,18 +37942,18 @@ function findBinary2(name) {
36113
37942
  const result = runCommand(cmd, 5e3);
36114
37943
  return result ? result.split("\n")[0] : null;
36115
37944
  }
36116
- function parseVersion(raw) {
37945
+ function parseVersion2(raw) {
36117
37946
  const match = raw.match(/v?(\d+\.\d+(?:\.\d+)?(?:-[a-zA-Z0-9.]+)?)/);
36118
37947
  return match ? match[1] : raw.split("\n")[0].substring(0, 100);
36119
37948
  }
36120
37949
  function getVersion(binary, versionCommand) {
36121
37950
  if (versionCommand) {
36122
37951
  const raw = runCommand(versionCommand);
36123
- return raw ? parseVersion(raw) : null;
37952
+ return raw ? parseVersion2(raw) : null;
36124
37953
  }
36125
37954
  for (const flag of ["--version", "-V", "-v"]) {
36126
37955
  const raw = runCommand(`"${binary}" ${flag}`);
36127
- if (raw && raw.length < 500) return parseVersion(raw);
37956
+ if (raw && raw.length < 500) return parseVersion2(raw);
36128
37957
  }
36129
37958
  return null;
36130
37959
  }
@@ -36741,15 +38570,15 @@ var init_dev_server = __esm({
36741
38570
  this.json(res, 500, { error: e.message });
36742
38571
  }
36743
38572
  });
36744
- return new Promise((resolve7, reject) => {
38573
+ return new Promise((resolve10, reject) => {
36745
38574
  this.server.listen(port, "127.0.0.1", () => {
36746
38575
  this.log(`Dev server listening on http://127.0.0.1:${port}`);
36747
- resolve7();
38576
+ resolve10();
36748
38577
  });
36749
38578
  this.server.on("error", (e) => {
36750
38579
  if (e.code === "EADDRINUSE") {
36751
38580
  this.log(`Port ${port} in use, skipping dev server`);
36752
- resolve7();
38581
+ resolve10();
36753
38582
  } else {
36754
38583
  reject(e);
36755
38584
  }
@@ -36832,20 +38661,20 @@ var init_dev_server = __esm({
36832
38661
  child.stderr?.on("data", (d) => {
36833
38662
  stderr += d.toString().slice(0, 2e3);
36834
38663
  });
36835
- await new Promise((resolve7) => {
38664
+ await new Promise((resolve10) => {
36836
38665
  const timer = setTimeout(() => {
36837
38666
  child.kill();
36838
- resolve7();
38667
+ resolve10();
36839
38668
  }, 3e3);
36840
38669
  child.on("exit", () => {
36841
38670
  clearTimeout(timer);
36842
- resolve7();
38671
+ resolve10();
36843
38672
  });
36844
38673
  child.stdout?.once("data", () => {
36845
38674
  setTimeout(() => {
36846
38675
  child.kill();
36847
38676
  clearTimeout(timer);
36848
- resolve7();
38677
+ resolve10();
36849
38678
  }, 500);
36850
38679
  });
36851
38680
  });
@@ -37272,8 +39101,8 @@ var init_dev_server = __esm({
37272
39101
  files.push({ path: rel, size: 0, type: "dir" });
37273
39102
  scan(path12.join(d, entry.name), rel);
37274
39103
  } else {
37275
- const stat = fs10.statSync(path12.join(d, entry.name));
37276
- files.push({ path: rel, size: stat.size, type: "file" });
39104
+ const stat4 = fs10.statSync(path12.join(d, entry.name));
39105
+ files.push({ path: rel, size: stat4.size, type: "file" });
37277
39106
  }
37278
39107
  }
37279
39108
  } catch {
@@ -37589,14 +39418,14 @@ var init_dev_server = __esm({
37589
39418
  child.stderr?.on("data", (d) => {
37590
39419
  stderr += d.toString();
37591
39420
  });
37592
- await new Promise((resolve7) => {
39421
+ await new Promise((resolve10) => {
37593
39422
  const timer = setTimeout(() => {
37594
39423
  child.kill();
37595
- resolve7();
39424
+ resolve10();
37596
39425
  }, timeout);
37597
39426
  child.on("exit", () => {
37598
39427
  clearTimeout(timer);
37599
- resolve7();
39428
+ resolve10();
37600
39429
  });
37601
39430
  });
37602
39431
  const elapsed = Date.now() - start;
@@ -38440,25 +40269,66 @@ var init_dev_server = __esm({
38440
40269
  const ref = this.providerLoader.resolve(desired) || this.providerLoader.getMeta(desired);
38441
40270
  if (ref?.category === category) return desired;
38442
40271
  const all = this.providerLoader.getAll();
38443
- const fallback = all.find((p) => p.category === category && p.type !== targetType);
40272
+ 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
40273
  return fallback?.type || null;
38445
40274
  }
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;
40275
+ getLatestScriptVersionDir(scriptsDir) {
40276
+ if (!fs10.existsSync(scriptsDir)) return null;
38453
40277
  const versions = fs10.readdirSync(scriptsDir).filter((d) => {
38454
40278
  try {
38455
40279
  return fs10.statSync(path12.join(scriptsDir, d)).isDirectory();
38456
40280
  } catch {
38457
40281
  return false;
38458
40282
  }
38459
- }).sort().reverse();
38460
- if (versions.length === 0) return referenceScripts;
38461
- const latestDir = path12.join(scriptsDir, versions[0]);
40283
+ }).sort((a, b2) => b2.localeCompare(a, void 0, { numeric: true, sensitivity: "base" }));
40284
+ if (versions.length === 0) return null;
40285
+ return path12.join(scriptsDir, versions[0]);
40286
+ }
40287
+ resolveAutoImplWritableProviderDir(category, type, requestedDir) {
40288
+ const canonicalUserDir = path12.resolve(this.providerLoader.getUserProviderDir(category, type));
40289
+ const desiredDir = requestedDir ? path12.resolve(requestedDir) : canonicalUserDir;
40290
+ const upstreamRoot = path12.resolve(this.providerLoader.getUpstreamDir());
40291
+ if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path12.sep}`)) {
40292
+ return { dir: null, reason: `Refusing to write into upstream provider directory: ${desiredDir}` };
40293
+ }
40294
+ if (path12.basename(desiredDir) !== type) {
40295
+ return { dir: null, reason: `Requested writable provider directory must end with '${type}': ${desiredDir}` };
40296
+ }
40297
+ const sourceDir = this.findProviderDir(type);
40298
+ if (!sourceDir) {
40299
+ return { dir: null, reason: `Provider source directory not found for '${type}'` };
40300
+ }
40301
+ if (!fs10.existsSync(desiredDir)) {
40302
+ fs10.mkdirSync(path12.dirname(desiredDir), { recursive: true });
40303
+ fs10.cpSync(sourceDir, desiredDir, { recursive: true });
40304
+ this.log(`Auto-implement writable copy created: ${desiredDir}`);
40305
+ }
40306
+ const providerJson = path12.join(desiredDir, "provider.json");
40307
+ if (!fs10.existsSync(providerJson)) {
40308
+ return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
40309
+ }
40310
+ try {
40311
+ const providerData = JSON.parse(fs10.readFileSync(providerJson, "utf-8"));
40312
+ if (providerData.disableUpstream !== true) {
40313
+ providerData.disableUpstream = true;
40314
+ fs10.writeFileSync(providerJson, JSON.stringify(providerData, null, 2));
40315
+ }
40316
+ } catch (error48) {
40317
+ return {
40318
+ dir: null,
40319
+ reason: `Failed to update provider.json in writable provider directory: ${error48.message}`
40320
+ };
40321
+ }
40322
+ return { dir: desiredDir };
40323
+ }
40324
+ loadAutoImplReferenceScripts(referenceType) {
40325
+ if (!referenceType) return {};
40326
+ const refDir = this.findProviderDir(referenceType);
40327
+ if (!refDir || !fs10.existsSync(refDir)) return {};
40328
+ const referenceScripts = {};
40329
+ const scriptsDir = path12.join(refDir, "scripts");
40330
+ const latestDir = this.getLatestScriptVersionDir(scriptsDir);
40331
+ if (!latestDir) return referenceScripts;
38462
40332
  for (const file2 of fs10.readdirSync(latestDir)) {
38463
40333
  if (!file2.endsWith(".js")) continue;
38464
40334
  try {
@@ -38470,7 +40340,7 @@ var init_dev_server = __esm({
38470
40340
  }
38471
40341
  async handleAutoImplement(type, req, res) {
38472
40342
  const body = await this.readBody(req);
38473
- const { agent = "claude-cli", functions, reference = "antigravity", model, comment } = body;
40343
+ const { agent = "claude-cli", functions, reference, model, comment, providerDir: requestedProviderDir } = body;
38474
40344
  if (!functions || !Array.isArray(functions) || functions.length === 0) {
38475
40345
  this.json(res, 400, { error: 'functions[] is required (e.g. ["readChat", "sendMessage"])' });
38476
40346
  return;
@@ -38484,11 +40354,14 @@ var init_dev_server = __esm({
38484
40354
  this.json(res, 404, { error: `Provider not found: ${type}` });
38485
40355
  return;
38486
40356
  }
38487
- const providerDir = this.findProviderDir(type);
38488
- if (!providerDir) {
38489
- this.json(res, 404, { error: `Provider directory not found: ${type}` });
40357
+ const writableProvider = this.resolveAutoImplWritableProviderDir(provider.category, type, requestedProviderDir);
40358
+ if (!writableProvider.dir) {
40359
+ this.json(res, 409, {
40360
+ error: writableProvider.reason || `Auto-implement only writes to the canonical user provider directory for '${type}'.`
40361
+ });
38490
40362
  return;
38491
40363
  }
40364
+ const providerDir = writableProvider.dir;
38492
40365
  try {
38493
40366
  const resolvedReference = this.resolveAutoImplReference(provider.category, reference, type);
38494
40367
  this.sendAutoImplSSE({
@@ -38508,7 +40381,7 @@ var init_dev_server = __esm({
38508
40381
  message: `Loading reference script (${resolvedReference || "none"})...`
38509
40382
  }
38510
40383
  });
38511
- const referenceScripts = this.loadAutoImplReferenceScripts(provider.category, resolvedReference);
40384
+ const referenceScripts = this.loadAutoImplReferenceScripts(resolvedReference);
38512
40385
  const prompt = this.buildAutoImplPrompt(type, provider, providerDir, functions, domContext, referenceScripts, comment, resolvedReference);
38513
40386
  const tmpDir = path12.join(os15.tmpdir(), "adhdev-autoimpl");
38514
40387
  if (!fs10.existsSync(tmpDir)) fs10.mkdirSync(tmpDir, { recursive: true });
@@ -38530,7 +40403,7 @@ var init_dev_server = __esm({
38530
40403
  this.sendAutoImplSSE({ event: "progress", data: { function: "_init", status: "spawning", message: `Spawning ACP agent: ${spawn3.command} ${(spawn3.args || []).join(" ")}` } });
38531
40404
  this.autoImplStatus = { running: true, type, progress: [] };
38532
40405
  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");
40406
+ const { Readable: Readable3, Writable: Writable2 } = await import("stream");
38534
40407
  const { spawn: spawnFn2 } = await import("child_process");
38535
40408
  const acpArgs = [...spawn3.args || []];
38536
40409
  if (model) {
@@ -38549,7 +40422,7 @@ var init_dev_server = __esm({
38549
40422
  this.sendAutoImplSSE({ event: "output", data: { chunk, stream: "stderr" } });
38550
40423
  });
38551
40424
  const webStdin = Writable2.toWeb(child2.stdin);
38552
- const webStdout = Readable2.toWeb(child2.stdout);
40425
+ const webStdout = Readable3.toWeb(child2.stdout);
38553
40426
  const stream = ndJsonStream2(webStdin, webStdout);
38554
40427
  const connection = new ClientSideConnection2((_agent) => ({
38555
40428
  // Auto-approve all tool calls for auto-implement
@@ -38864,29 +40737,20 @@ var init_dev_server = __esm({
38864
40737
  lines.push("These are the files you need to EDIT. They contain TODO stubs \u2014 replace them with working implementations.");
38865
40738
  lines.push("");
38866
40739
  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
- }
40740
+ const latestScriptsDir = this.getLatestScriptVersionDir(scriptsDir);
40741
+ if (latestScriptsDir) {
40742
+ lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
40743
+ lines.push("");
40744
+ for (const file2 of fs10.readdirSync(latestScriptsDir)) {
40745
+ if (file2.endsWith(".js")) {
40746
+ try {
40747
+ const content = fs10.readFileSync(path12.join(latestScriptsDir, file2), "utf-8");
40748
+ lines.push(`### \`${file2}\``);
40749
+ lines.push("```javascript");
40750
+ lines.push(content);
40751
+ lines.push("```");
40752
+ lines.push("");
40753
+ } catch {
38890
40754
  }
38891
40755
  }
38892
40756
  }
@@ -38967,7 +40831,7 @@ var init_dev_server = __esm({
38967
40831
  lines.push("## Rules");
38968
40832
  lines.push("1. **Scripts WITHOUT params** \u2192 IIFE: `(() => { ... })()`");
38969
40833
  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");
40834
+ lines.push("3. If live DOM analysis is included above, use it. Otherwise, discover selectors yourself via CDP before coding.");
38971
40835
  lines.push("4. Always wrap in try-catch, return `JSON.stringify(result)`");
38972
40836
  lines.push("5. Do NOT modify `scripts.js` router \u2014 only edit individual `*.js` files");
38973
40837
  lines.push("6. All scripts run in the browser (CDP evaluate) \u2014 use DOM APIs only");
@@ -39016,8 +40880,12 @@ var init_dev_server = __esm({
39016
40880
  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
40881
  lines.push(" - `switchSession`: Prove your switch was successful by subsequently calling `readChat` and explicitly checking that the chat context has actually changed.");
39018
40882
  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!");
40883
+ lines.push("## DOM Exploration");
40884
+ if (domContext) {
40885
+ lines.push("A lightweight DOM snapshot is included above, but you MUST still verify selectors yourself before finalizing the scripts.");
40886
+ } else {
40887
+ lines.push("No DOM snapshot is included here. You MUST use your command-line tools to discover the IDE structure dynamically.");
40888
+ }
39021
40889
  lines.push("");
39022
40890
  lines.push("### 1. Evaluate JS to explore IDE DOM");
39023
40891
  lines.push("Use cURL to run JavaScript inside the IDE:");
@@ -39104,29 +40972,20 @@ var init_dev_server = __esm({
39104
40972
  lines.push("These are the files you need to edit. Replace TODO or heuristic-only logic with working PTY-aware implementations.");
39105
40973
  lines.push("");
39106
40974
  const scriptsDir = path12.join(providerDir, "scripts");
39107
- if (fs10.existsSync(scriptsDir)) {
39108
- const versions = fs10.readdirSync(scriptsDir).filter((d) => {
40975
+ const latestScriptsDir = this.getLatestScriptVersionDir(scriptsDir);
40976
+ if (latestScriptsDir) {
40977
+ lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
40978
+ lines.push("");
40979
+ for (const file2 of fs10.readdirSync(latestScriptsDir)) {
40980
+ if (!file2.endsWith(".js")) continue;
39109
40981
  try {
39110
- return fs10.statSync(path12.join(scriptsDir, d)).isDirectory();
40982
+ const content = fs10.readFileSync(path12.join(latestScriptsDir, file2), "utf-8");
40983
+ lines.push(`### \`${file2}\``);
40984
+ lines.push("```javascript");
40985
+ lines.push(content);
40986
+ lines.push("```");
40987
+ lines.push("");
39111
40988
  } 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
40989
  }
39131
40990
  }
39132
40991
  }
@@ -39195,6 +41054,9 @@ var init_dev_server = __esm({
39195
41054
  lines.push("8. Keep exports compatible with the existing `scripts.js` router (`module.exports = function ...`).");
39196
41055
  lines.push("9. Do not rewrite unrelated provider config. Only touch the scripts needed for this task unless a tiny supporting change is required.");
39197
41056
  lines.push("10. When the verification API returns `instanceId`, keep using that exact instance for follow-up `send`, `resolve`, `raw`, and `stop` calls. Do not assume type-only routing is safe if multiple sessions exist.");
41057
+ lines.push("11. Do NOT repeatedly dump the same target files. Read the target scripts once, reproduce the bug, then move directly to patching.");
41058
+ lines.push("12. If the user instructions include concrete screen text, raw PTY snippets, or a specific repro, treat that as the primary acceptance criteria.");
41059
+ lines.push("13. After the first successful live repro, stop broad diagnosis. Edit the scripts, reload, and verify. Do not burn tokens on repeated re-inspection without code changes.");
39198
41060
  lines.push("");
39199
41061
  lines.push("## Task");
39200
41062
  lines.push(`Edit files in \`${providerDir}\` to implement: **${functions.join(", ")}**`);
@@ -39236,6 +41098,9 @@ var init_dev_server = __esm({
39236
41098
  lines.push("");
39237
41099
  lines.push("Use `resolve` when the parsed modal buttons are correct. Use `raw` when the CLI expects a literal keystroke like `1`, `y`, or Enter. Repeat until idle.");
39238
41100
  lines.push("");
41101
+ lines.push("### Patch Discipline");
41102
+ lines.push("Once the repro is confirmed, immediately edit the target files. Avoid loops where you keep re-reading long files or re-running the same debug commands without changing code.");
41103
+ lines.push("");
39239
41104
  lines.push("### 5. Verify the side effects outside the CLI");
39240
41105
  lines.push("```bash");
39241
41106
  lines.push("test -f tmp/adhdev_provider_fix_test.py");
@@ -39340,14 +41205,14 @@ data: ${JSON.stringify(msg.data)}
39340
41205
  res.end(JSON.stringify(data, null, 2));
39341
41206
  }
39342
41207
  async readBody(req) {
39343
- return new Promise((resolve7) => {
41208
+ return new Promise((resolve10) => {
39344
41209
  let body = "";
39345
41210
  req.on("data", (chunk) => body += chunk);
39346
41211
  req.on("end", () => {
39347
41212
  try {
39348
- resolve7(JSON.parse(body));
41213
+ resolve10(JSON.parse(body));
39349
41214
  } catch {
39350
- resolve7({});
41215
+ resolve10({});
39351
41216
  }
39352
41217
  });
39353
41218
  });
@@ -39652,10 +41517,10 @@ async function installExtension(ide, extension) {
39652
41517
  const buffer = Buffer.from(await res.arrayBuffer());
39653
41518
  const fs13 = await import("fs");
39654
41519
  fs13.writeFileSync(vsixPath, buffer);
39655
- return new Promise((resolve7) => {
41520
+ return new Promise((resolve10) => {
39656
41521
  const cmd = `"${ide.cliCommand}" --install-extension "${vsixPath}" --force`;
39657
41522
  (0, import_child_process8.exec)(cmd, { timeout: 6e4 }, (error48, _stdout, stderr) => {
39658
- resolve7({
41523
+ resolve10({
39659
41524
  extensionId: extension.id,
39660
41525
  marketplaceId: extension.marketplaceId,
39661
41526
  success: !error48,
@@ -39668,11 +41533,11 @@ async function installExtension(ide, extension) {
39668
41533
  } catch (e) {
39669
41534
  }
39670
41535
  }
39671
- return new Promise((resolve7) => {
41536
+ return new Promise((resolve10) => {
39672
41537
  const cmd = `"${ide.cliCommand}" --install-extension ${extension.marketplaceId} --force`;
39673
41538
  (0, import_child_process8.exec)(cmd, { timeout: 6e4 }, (error48, stdout, stderr) => {
39674
41539
  if (error48) {
39675
- resolve7({
41540
+ resolve10({
39676
41541
  extensionId: extension.id,
39677
41542
  marketplaceId: extension.marketplaceId,
39678
41543
  success: false,
@@ -39680,7 +41545,7 @@ async function installExtension(ide, extension) {
39680
41545
  error: stderr || error48.message
39681
41546
  });
39682
41547
  } else {
39683
- resolve7({
41548
+ resolve10({
39684
41549
  extensionId: extension.id,
39685
41550
  marketplaceId: extension.marketplaceId,
39686
41551
  success: true,
@@ -39913,6 +41778,18 @@ async function initDaemonComponents(config2) {
39913
41778
  detectedIdes: detectedIdesRef
39914
41779
  };
39915
41780
  }
41781
+ async function startDaemonDevSupport(options) {
41782
+ const devServer = new DevServer({
41783
+ providerLoader: options.components.providerLoader,
41784
+ cdpManagers: options.components.cdpManagers,
41785
+ instanceManager: options.components.instanceManager,
41786
+ cliManager: options.components.cliManager,
41787
+ logFn: options.logFn
41788
+ });
41789
+ await devServer.start();
41790
+ options.components.providerLoader.watch();
41791
+ return devServer;
41792
+ }
39916
41793
  async function shutdownDaemonComponents(components) {
39917
41794
  const {
39918
41795
  poller,
@@ -39961,6 +41838,7 @@ var init_daemon_lifecycle = __esm({
39961
41838
  init_provider_loader();
39962
41839
  init_version_archive();
39963
41840
  init_provider_instance_manager();
41841
+ init_dev_server();
39964
41842
  init_ide_detector();
39965
41843
  init_logger();
39966
41844
  init_config();
@@ -40033,6 +41911,7 @@ __export(src_exports, {
40033
41911
  setLogLevel: () => setLogLevel,
40034
41912
  setupIdeInstance: () => setupIdeInstance,
40035
41913
  shutdownDaemonComponents: () => shutdownDaemonComponents,
41914
+ startDaemonDevSupport: () => startDaemonDevSupport,
40036
41915
  updateConfig: () => updateConfig
40037
41916
  });
40038
41917
  var init_src = __esm({
@@ -40521,13 +42400,13 @@ ${e?.stack || ""}`);
40521
42400
  } catch {
40522
42401
  }
40523
42402
  const http3 = esmRequire("https");
40524
- const data = await new Promise((resolve7, reject) => {
42403
+ const data = await new Promise((resolve10, reject) => {
40525
42404
  const req = http3.get(`${serverUrl}/api/v1/turn/credentials`, {
40526
42405
  headers: { "Authorization": `Bearer ${token}` }
40527
42406
  }, (res) => {
40528
42407
  let d = "";
40529
42408
  res.on("data", (c) => d += c);
40530
- res.on("end", () => resolve7(d));
42409
+ res.on("end", () => resolve10(d));
40531
42410
  });
40532
42411
  req.on("error", reject);
40533
42412
  req.setTimeout(5e3, () => {
@@ -41383,7 +43262,7 @@ var init_adhdev_daemon = __esm({
41383
43262
  fs12 = __toESM(require("fs"));
41384
43263
  path14 = __toESM(require("path"));
41385
43264
  import_chalk2 = __toESM(require("chalk"));
41386
- pkgVersion = "0.6.72";
43265
+ pkgVersion = "0.6.76";
41387
43266
  if (pkgVersion === "unknown") {
41388
43267
  try {
41389
43268
  const possiblePaths = [
@@ -41608,7 +43487,7 @@ ${err?.stack || ""}`);
41608
43487
  this.running = true;
41609
43488
  process.on("SIGINT", () => this.stop());
41610
43489
  process.on("SIGTERM", () => this.stop());
41611
- if (options.dev) {
43490
+ if (options.dev && this.components) {
41612
43491
  const devServer = new DevServer({
41613
43492
  providerLoader: this.components.providerLoader,
41614
43493
  cdpManagers: this.components.cdpManagers,
@@ -42194,7 +44073,7 @@ __export(cdp_utils_exports, {
42194
44073
  async function sendDaemonCommand(cmd, args = {}, port = 19222) {
42195
44074
  const WebSocket3 = (await import("ws")).default;
42196
44075
  const { DAEMON_WS_PATH: DAEMON_WS_PATH2 } = await Promise.resolve().then(() => (init_src(), src_exports));
42197
- return new Promise((resolve7, reject) => {
44076
+ return new Promise((resolve10, reject) => {
42198
44077
  const wsUrl = `ws://127.0.0.1:${port}${DAEMON_WS_PATH2 || "/daemon"}`;
42199
44078
  const ws2 = new WebSocket3(wsUrl);
42200
44079
  const timeout = setTimeout(() => {
@@ -42225,7 +44104,7 @@ async function sendDaemonCommand(cmd, args = {}, port = 19222) {
42225
44104
  if (msg.type === "daemon:command_result" || msg.type === "command_result") {
42226
44105
  clearTimeout(timeout);
42227
44106
  ws2.close();
42228
- resolve7(msg.payload?.result || msg.payload || msg);
44107
+ resolve10(msg.payload?.result || msg.payload || msg);
42229
44108
  }
42230
44109
  } catch {
42231
44110
  }
@@ -42242,13 +44121,13 @@ Is 'adhdev daemon' running?`));
42242
44121
  }
42243
44122
  async function directCdpEval(expression, port = 9222) {
42244
44123
  const http3 = await import("http");
42245
- const targets = await new Promise((resolve7, reject) => {
44124
+ const targets = await new Promise((resolve10, reject) => {
42246
44125
  http3.get(`http://127.0.0.1:${port}/json`, (res) => {
42247
44126
  let data = "";
42248
44127
  res.on("data", (c) => data += c);
42249
44128
  res.on("end", () => {
42250
44129
  try {
42251
- resolve7(JSON.parse(data));
44130
+ resolve10(JSON.parse(data));
42252
44131
  } catch {
42253
44132
  reject(new Error("Invalid JSON"));
42254
44133
  }
@@ -42261,7 +44140,7 @@ async function directCdpEval(expression, port = 9222) {
42261
44140
  const target = (mainPages.length > 0 ? mainPages[0] : pages[0]) || targets[0];
42262
44141
  if (!target?.webSocketDebuggerUrl) throw new Error("No CDP target found");
42263
44142
  const WebSocket3 = (await import("ws")).default;
42264
- return new Promise((resolve7, reject) => {
44143
+ return new Promise((resolve10, reject) => {
42265
44144
  const ws2 = new WebSocket3(target.webSocketDebuggerUrl);
42266
44145
  const timeout = setTimeout(() => {
42267
44146
  ws2.close();
@@ -42283,11 +44162,11 @@ async function directCdpEval(expression, port = 9222) {
42283
44162
  clearTimeout(timeout);
42284
44163
  ws2.close();
42285
44164
  if (msg.result?.result?.value !== void 0) {
42286
- resolve7(msg.result.result.value);
44165
+ resolve10(msg.result.result.value);
42287
44166
  } else if (msg.result?.exceptionDetails) {
42288
44167
  reject(new Error(msg.result.exceptionDetails.text));
42289
44168
  } else {
42290
- resolve7(msg.result);
44169
+ resolve10(msg.result);
42291
44170
  }
42292
44171
  }
42293
44172
  });
@@ -42872,13 +44751,21 @@ function hideCommand2(command) {
42872
44751
  command.hideHelp?.();
42873
44752
  return command;
42874
44753
  }
44754
+ async function createConfiguredProviderLoader() {
44755
+ const { ProviderLoader: ProviderLoader2, loadConfig: loadConfig2 } = await Promise.resolve().then(() => (init_src(), src_exports));
44756
+ const config2 = loadConfig2();
44757
+ const loader = new ProviderLoader2({
44758
+ userDir: config2.providerDir,
44759
+ disableUpstream: config2.disableUpstream
44760
+ });
44761
+ loader.loadAll();
44762
+ return loader;
44763
+ }
42875
44764
  function registerProviderCommands(program2) {
42876
44765
  const provider = hideCommand2(program2.command("provider").description("\u{1F50C} Provider management \u2014 list, test, reload providers"));
42877
44766
  provider.command("list").description("List all loaded providers").option("-j, --json", "Output raw JSON").action(async (options) => {
42878
44767
  try {
42879
- const { ProviderLoader: ProviderLoader2 } = await Promise.resolve().then(() => (init_src(), src_exports));
42880
- const loader = new ProviderLoader2();
42881
- loader.loadAll();
44768
+ const loader = await createConfiguredProviderLoader();
42882
44769
  const providers = loader.getAll();
42883
44770
  if (options.json) {
42884
44771
  console.log(JSON.stringify(providers.map((p) => ({
@@ -42930,7 +44817,7 @@ function registerProviderCommands(program2) {
42930
44817
  } catch {
42931
44818
  try {
42932
44819
  const http3 = await import("http");
42933
- const result = await new Promise((resolve7, reject) => {
44820
+ const result = await new Promise((resolve10, reject) => {
42934
44821
  const req = http3.request({
42935
44822
  hostname: "127.0.0.1",
42936
44823
  port: 19280,
@@ -42942,9 +44829,9 @@ function registerProviderCommands(program2) {
42942
44829
  res.on("data", (c) => data += c);
42943
44830
  res.on("end", () => {
42944
44831
  try {
42945
- resolve7(JSON.parse(data));
44832
+ resolve10(JSON.parse(data));
42946
44833
  } catch {
42947
- resolve7({ raw: data });
44834
+ resolve10({ raw: data });
42948
44835
  }
42949
44836
  });
42950
44837
  });
@@ -43047,12 +44934,12 @@ function registerProviderCommands(program2) {
43047
44934
  console.log(import_chalk6.default.yellow("Invalid port number."));
43048
44935
  continue;
43049
44936
  }
43050
- const isFree = await new Promise((resolve7) => {
44937
+ const isFree = await new Promise((resolve10) => {
43051
44938
  const server = net2.createServer();
43052
44939
  server.unref();
43053
- server.on("error", () => resolve7(false));
44940
+ server.on("error", () => resolve10(false));
43054
44941
  server.listen(port, "127.0.0.1", () => {
43055
- server.close(() => resolve7(true));
44942
+ server.close(() => resolve10(true));
43056
44943
  });
43057
44944
  });
43058
44945
  if (!isFree) {
@@ -43067,7 +44954,7 @@ function registerProviderCommands(program2) {
43067
44954
  rl.close();
43068
44955
  const location = options.builtin ? "builtin" : "user";
43069
44956
  const http3 = await import("http");
43070
- const result = await new Promise((resolve7, reject) => {
44957
+ const result = await new Promise((resolve10, reject) => {
43071
44958
  const postData = JSON.stringify({ type, name, category, location, cdpPorts, osPaths, processNames });
43072
44959
  const req = http3.request({
43073
44960
  hostname: "127.0.0.1",
@@ -43080,9 +44967,9 @@ function registerProviderCommands(program2) {
43080
44967
  res.on("data", (c) => data += c);
43081
44968
  res.on("end", () => {
43082
44969
  try {
43083
- resolve7(JSON.parse(data));
44970
+ resolve10(JSON.parse(data));
43084
44971
  } catch {
43085
- resolve7({ raw: data });
44972
+ resolve10({ raw: data });
43086
44973
  }
43087
44974
  });
43088
44975
  });
@@ -43092,9 +44979,8 @@ function registerProviderCommands(program2) {
43092
44979
  }).catch(async () => {
43093
44980
  const pathMod = await import("path");
43094
44981
  const fsMod = await import("fs");
43095
- const { ProviderLoader: ProviderLoader2 } = await Promise.resolve().then(() => (init_src(), src_exports));
43096
- const loader = new ProviderLoader2();
43097
- let targetDir = location === "builtin" ? loader.getBuiltinProviderDir(category, type) : loader.getUserProviderDir(category, type);
44982
+ const loader = await createConfiguredProviderLoader();
44983
+ let targetDir = location === "builtin" ? loader.getUpstreamProviderDir(category, type) : loader.getUserProviderDir(category, type);
43098
44984
  if (fsMod.existsSync(targetDir)) return { error: `Provider already exists at ${targetDir}` };
43099
44985
  const isExt = category === "extension";
43100
44986
  const isIde = category === "ide";
@@ -43146,9 +45032,7 @@ function registerProviderCommands(program2) {
43146
45032
  try {
43147
45033
  const http3 = await import("http");
43148
45034
  const inquirer2 = (await import("inquirer")).default;
43149
- const { ProviderLoader: ProviderLoader2 } = await Promise.resolve().then(() => (init_src(), src_exports));
43150
- const loader = new ProviderLoader2();
43151
- loader.loadAll();
45035
+ const loader = await createConfiguredProviderLoader();
43152
45036
  const allProviders = loader.getAll();
43153
45037
  const fsMod = await import("fs");
43154
45038
  const isUserProvider = (p) => {
@@ -43193,60 +45077,23 @@ function registerProviderCommands(program2) {
43193
45077
  if (providerToFix && !isUserProvider(providerToFix)) {
43194
45078
  console.log(import_chalk6.default.yellow(`
43195
45079
  \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
- }
45080
+ console.log(import_chalk6.default.gray(` Preparing a writable local copy in the user providers directory and disabling upstream updates for this provider.`));
43212
45081
  const pathMod = await import("path");
43213
45082
  const fsMod2 = await import("fs");
43214
- const builtinSrc = loader.getBuiltinProviderDir(providerToFix.category, type);
43215
45083
  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.`));
45084
+ const sourceDir = downloadedSrc;
45085
+ const targetDir2 = loader.getUserProviderDir(providerToFix.category, type);
45086
+ if (!fsMod2.existsSync(targetDir2)) {
45087
+ fsMod2.cpSync(sourceDir, targetDir2, { recursive: true });
45088
+ }
45089
+ const pJsonPath = pathMod.join(targetDir2, "provider.json");
45090
+ if (fsMod2.existsSync(pJsonPath)) {
45091
+ const pJson = JSON.parse(fsMod2.readFileSync(pJsonPath, "utf8"));
45092
+ pJson.disableUpstream = true;
45093
+ fsMod2.writeFileSync(pJsonPath, JSON.stringify(pJson, null, 2));
43249
45094
  }
45095
+ console.log(import_chalk6.default.green(`
45096
+ \u2713 Writable local copy ready at [${targetDir2}]`));
43250
45097
  }
43251
45098
  let agentName = options.agent || "codex-cli";
43252
45099
  const modelName = options.model;
@@ -43306,6 +45153,7 @@ function registerProviderCommands(program2) {
43306
45153
  userComment = commentAnswer.comment || "";
43307
45154
  }
43308
45155
  let consecutiveFailures = 0;
45156
+ const targetDir = loader.getUserProviderDir(providerToFix.category, type);
43309
45157
  console.log(import_chalk6.default.bold(`
43310
45158
  \u25B6\uFE0F Generating [${functionsToFix.length}] function(s) natively via autonomous agent for ${type}...`));
43311
45159
  if (userComment) {
@@ -43315,11 +45163,12 @@ function registerProviderCommands(program2) {
43315
45163
  const postData = JSON.stringify({
43316
45164
  functions: functionsToFix,
43317
45165
  agent: agentName,
45166
+ providerDir: targetDir,
43318
45167
  ...modelName ? { model: modelName } : {},
43319
45168
  ...userComment ? { comment: userComment } : {},
43320
45169
  reference
43321
45170
  });
43322
- const startResult = await new Promise((resolve7, reject) => {
45171
+ const startResult = await new Promise((resolve10, reject) => {
43323
45172
  const req = http3.request({
43324
45173
  hostname: "127.0.0.1",
43325
45174
  port: 19280,
@@ -43331,9 +45180,9 @@ function registerProviderCommands(program2) {
43331
45180
  res.on("data", (c) => data += c);
43332
45181
  res.on("end", () => {
43333
45182
  try {
43334
- resolve7(JSON.parse(data));
45183
+ resolve10(JSON.parse(data));
43335
45184
  } catch {
43336
- resolve7({ raw: data });
45185
+ resolve10({ raw: data });
43337
45186
  }
43338
45187
  });
43339
45188
  });
@@ -43352,18 +45201,14 @@ function registerProviderCommands(program2) {
43352
45201
  throw new Error(`Unexpected response: ${JSON.stringify(startResult)}`);
43353
45202
  }
43354
45203
  const pathMod = await import("path");
43355
- const { ProviderLoader: ProviderLoader3 } = await Promise.resolve().then(() => (init_src(), src_exports));
43356
- const loader2 = new ProviderLoader3();
43357
- loader2.loadAll();
43358
- const providerMeta = loader2.getMeta(type);
45204
+ const providerMeta = loader.getMeta(type);
43359
45205
  if (!providerMeta) throw new Error(`Unknown provider: ${type}`);
43360
- const targetDir = loader2.getUserProviderDir(providerMeta.category, type);
43361
45206
  const fsMock = await import("fs");
43362
45207
  const logFile2 = pathMod.join(targetDir, `auto-impl.log`);
43363
45208
  fsMock.writeFileSync(logFile2, `=== Auto-Impl Started ===
43364
45209
  `);
43365
45210
  console.log(import_chalk6.default.gray(` Agent logs: ${logFile2}`));
43366
- await new Promise((resolve7, reject) => {
45211
+ await new Promise((resolve10, reject) => {
43367
45212
  http3.get(`http://127.0.0.1:19280${startResult.sseUrl}`, (res) => {
43368
45213
  let buffer = "";
43369
45214
  res.on("data", (chunk) => {
@@ -43400,7 +45245,7 @@ function registerProviderCommands(program2) {
43400
45245
  if (currentData.success === false) {
43401
45246
  reject(new Error(`Agent failed to implement scripts properly (exit: ${currentData.exitCode})`));
43402
45247
  } else {
43403
- resolve7();
45248
+ resolve10();
43404
45249
  }
43405
45250
  } else if (currentEvent === "error") {
43406
45251
  fsMock.appendFileSync(logFile2, `
@@ -43411,7 +45256,7 @@ function registerProviderCommands(program2) {
43411
45256
  }
43412
45257
  }
43413
45258
  });
43414
- res.on("end", resolve7);
45259
+ res.on("end", resolve10);
43415
45260
  }).on("error", reject);
43416
45261
  });
43417
45262
  console.log(import_chalk6.default.green(`
@@ -43470,7 +45315,7 @@ function registerProviderCommands(program2) {
43470
45315
  ideType: type,
43471
45316
  params: options.param ? { text: options.param, sessionId: options.param, buttonText: options.param } : {}
43472
45317
  });
43473
- const result = await new Promise((resolve7, reject) => {
45318
+ const result = await new Promise((resolve10, reject) => {
43474
45319
  const req = http3.request({
43475
45320
  hostname: "127.0.0.1",
43476
45321
  port: 19280,
@@ -43482,9 +45327,9 @@ function registerProviderCommands(program2) {
43482
45327
  res.on("data", (c) => data += c);
43483
45328
  res.on("end", () => {
43484
45329
  try {
43485
- resolve7(JSON.parse(data));
45330
+ resolve10(JSON.parse(data));
43486
45331
  } catch {
43487
- resolve7({ raw: data });
45332
+ resolve10({ raw: data });
43488
45333
  }
43489
45334
  });
43490
45335
  });
@@ -43520,15 +45365,15 @@ function registerProviderCommands(program2) {
43520
45365
  provider.command("source <type>").description("View source code of a provider").action(async (type) => {
43521
45366
  try {
43522
45367
  const http3 = await import("http");
43523
- const result = await new Promise((resolve7, reject) => {
45368
+ const result = await new Promise((resolve10, reject) => {
43524
45369
  http3.get(`http://127.0.0.1:19280/api/providers/${type}/source`, (res) => {
43525
45370
  let data = "";
43526
45371
  res.on("data", (c) => data += c);
43527
45372
  res.on("end", () => {
43528
45373
  try {
43529
- resolve7(JSON.parse(data));
45374
+ resolve10(JSON.parse(data));
43530
45375
  } catch {
43531
- resolve7({ raw: data });
45376
+ resolve10({ raw: data });
43532
45377
  }
43533
45378
  });
43534
45379
  }).on("error", () => {
@@ -43537,17 +45382,14 @@ function registerProviderCommands(program2) {
43537
45382
  }).catch(async () => {
43538
45383
  const pathMod = await import("path");
43539
45384
  const fsMod = await import("fs");
43540
- const { ProviderLoader: ProviderLoader2 } = await Promise.resolve().then(() => (init_src(), src_exports));
43541
- const loader = new ProviderLoader2();
43542
- loader.loadAll();
45385
+ const loader = await createConfiguredProviderLoader();
43543
45386
  const providerMeta = loader.getMeta(type);
43544
45387
  if (!providerMeta) {
43545
45388
  return { error: `Provider '${type}' not found` };
43546
45389
  }
43547
45390
  const possiblePaths = [
43548
45391
  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")
45392
+ pathMod.join(loader.getUpstreamProviderDir(providerMeta.category, type), "provider.js")
43551
45393
  ];
43552
45394
  for (const p of possiblePaths) {
43553
45395
  if (fsMod.existsSync(p)) {
@@ -43577,7 +45419,7 @@ function registerProviderCommands(program2) {
43577
45419
  try {
43578
45420
  const http3 = await import("http");
43579
45421
  const postData = JSON.stringify({ script: "readChat", params: {} });
43580
- const result = await new Promise((resolve7, reject) => {
45422
+ const result = await new Promise((resolve10, reject) => {
43581
45423
  const req = http3.request({
43582
45424
  hostname: "127.0.0.1",
43583
45425
  port: 19280,
@@ -43589,9 +45431,9 @@ function registerProviderCommands(program2) {
43589
45431
  res2.on("data", (c) => data += c);
43590
45432
  res2.on("end", () => {
43591
45433
  try {
43592
- resolve7(JSON.parse(data));
45434
+ resolve10(JSON.parse(data));
43593
45435
  } catch {
43594
- resolve7({ raw: data });
45436
+ resolve10({ raw: data });
43595
45437
  }
43596
45438
  });
43597
45439
  });
@@ -43832,13 +45674,13 @@ function registerCdpCommands(program2) {
43832
45674
  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
45675
  try {
43834
45676
  const http3 = await import("http");
43835
- const targets = await new Promise((resolve7, reject) => {
45677
+ const targets = await new Promise((resolve10, reject) => {
43836
45678
  http3.get(`http://127.0.0.1:${options.port}/json`, (res) => {
43837
45679
  let data = "";
43838
45680
  res.on("data", (c) => data += c);
43839
45681
  res.on("end", () => {
43840
45682
  try {
43841
- resolve7(JSON.parse(data));
45683
+ resolve10(JSON.parse(data));
43842
45684
  } catch {
43843
45685
  reject(new Error("Invalid JSON"));
43844
45686
  }
@@ -43852,7 +45694,7 @@ function registerCdpCommands(program2) {
43852
45694
  if (!target?.webSocketDebuggerUrl) throw new Error("No CDP target");
43853
45695
  const WebSocket3 = (await import("ws")).default;
43854
45696
  const ws2 = new WebSocket3(target.webSocketDebuggerUrl);
43855
- await new Promise((resolve7, reject) => {
45697
+ await new Promise((resolve10, reject) => {
43856
45698
  ws2.on("open", () => {
43857
45699
  ws2.send(JSON.stringify({ id: 1, method: "Page.captureScreenshot", params: { format: "jpeg", quality: 50 } }));
43858
45700
  });
@@ -43865,7 +45707,7 @@ function registerCdpCommands(program2) {
43865
45707
  \u2713 Screenshot saved to ${options.output}
43866
45708
  `));
43867
45709
  ws2.close();
43868
- resolve7();
45710
+ resolve10();
43869
45711
  }
43870
45712
  });
43871
45713
  ws2.on("error", (e) => reject(e));
@@ -43934,6 +45776,9 @@ if (process.argv.length <= 2) {
43934
45776
  }
43935
45777
  /*! Bundled license information:
43936
45778
 
45779
+ chokidar/index.js:
45780
+ (*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) *)
45781
+
43937
45782
  @xterm/xterm/lib/xterm.mjs:
43938
45783
  (**
43939
45784
  * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.