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/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: dirname6 } = await import("path");
521
- const appDir = dirname6(appPath);
520
+ const { dirname: dirname8 } = await import("path");
521
+ const appDir = dirname8(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
  }
@@ -693,8 +705,8 @@ function cleanOldLogs() {
693
705
  }
694
706
  function rotateSizeIfNeeded() {
695
707
  try {
696
- const stat = fs2.statSync(currentLogFile);
697
- if (stat.size > MAX_LOG_SIZE) {
708
+ const stat4 = fs2.statSync(currentLogFile);
709
+ if (stat4.size > MAX_LOG_SIZE) {
698
710
  const backup = currentLogFile.replace(".log", ".1.log");
699
711
  try {
700
712
  fs2.unlinkSync(backup);
@@ -823,8 +835,8 @@ var init_logger = __esm({
823
835
  try {
824
836
  const oldLog = path3.join(LOG_DIR, "daemon.log");
825
837
  if (fs2.existsSync(oldLog)) {
826
- const stat = fs2.statSync(oldLog);
827
- const oldDate = stat.mtime.toISOString().slice(0, 10);
838
+ const stat4 = fs2.statSync(oldLog);
839
+ const oldDate = stat4.mtime.toISOString().slice(0, 10);
828
840
  fs2.renameSync(oldLog, path3.join(LOG_DIR, `daemon-${oldDate}.log`));
829
841
  }
830
842
  const oldLogBackup = path3.join(LOG_DIR, "daemon.log.old");
@@ -948,7 +960,7 @@ var init_manager = __esm({
948
960
  * Returns multiple entries if multiple IDE windows are open on same port
949
961
  */
950
962
  static listAllTargets(port) {
951
- return new Promise((resolve7) => {
963
+ return new Promise((resolve10) => {
952
964
  const req = http.get(`http://127.0.0.1:${port}/json`, (res) => {
953
965
  let data = "";
954
966
  res.on("data", (chunk) => data += chunk.toString());
@@ -964,16 +976,16 @@ var init_manager = __esm({
964
976
  (t) => !isNonMain(t.title || "") && t.url?.includes("workbench.html") && !t.url?.includes("agent")
965
977
  );
966
978
  const fallbackPages = pages.filter((t) => !isNonMain(t.title || ""));
967
- resolve7(mainPages.length > 0 ? mainPages : fallbackPages);
979
+ resolve10(mainPages.length > 0 ? mainPages : fallbackPages);
968
980
  } catch {
969
- resolve7([]);
981
+ resolve10([]);
970
982
  }
971
983
  });
972
984
  });
973
- req.on("error", () => resolve7([]));
985
+ req.on("error", () => resolve10([]));
974
986
  req.setTimeout(2e3, () => {
975
987
  req.destroy();
976
- resolve7([]);
988
+ resolve10([]);
977
989
  });
978
990
  });
979
991
  }
@@ -1013,7 +1025,7 @@ var init_manager = __esm({
1013
1025
  }
1014
1026
  }
1015
1027
  findTargetOnPort(port) {
1016
- return new Promise((resolve7) => {
1028
+ return new Promise((resolve10) => {
1017
1029
  const req = http.get(`http://127.0.0.1:${port}/json`, (res) => {
1018
1030
  let data = "";
1019
1031
  res.on("data", (chunk) => data += chunk.toString());
@@ -1024,7 +1036,7 @@ var init_manager = __esm({
1024
1036
  (t) => (t.type === "page" || t.type === "browser" || t.type === "Page") && t.webSocketDebuggerUrl
1025
1037
  );
1026
1038
  if (pages.length === 0) {
1027
- resolve7(targets.find((t) => t.webSocketDebuggerUrl) || null);
1039
+ resolve10(targets.find((t) => t.webSocketDebuggerUrl) || null);
1028
1040
  return;
1029
1041
  }
1030
1042
  const mainPages = pages.filter((t) => !this.isNonMainTitle(t.title || ""));
@@ -1034,24 +1046,24 @@ var init_manager = __esm({
1034
1046
  const specific = list.find((t) => t.id === this._targetId);
1035
1047
  if (specific) {
1036
1048
  this._pageTitle = specific.title || "";
1037
- resolve7(specific);
1049
+ resolve10(specific);
1038
1050
  } else {
1039
1051
  this.log(`[CDP] Target ${this._targetId} not found in page list`);
1040
- resolve7(null);
1052
+ resolve10(null);
1041
1053
  }
1042
1054
  return;
1043
1055
  }
1044
1056
  this._pageTitle = list[0]?.title || "";
1045
- resolve7(list[0]);
1057
+ resolve10(list[0]);
1046
1058
  } catch {
1047
- resolve7(null);
1059
+ resolve10(null);
1048
1060
  }
1049
1061
  });
1050
1062
  });
1051
- req.on("error", () => resolve7(null));
1063
+ req.on("error", () => resolve10(null));
1052
1064
  req.setTimeout(2e3, () => {
1053
1065
  req.destroy();
1054
- resolve7(null);
1066
+ resolve10(null);
1055
1067
  });
1056
1068
  });
1057
1069
  }
@@ -1062,7 +1074,7 @@ var init_manager = __esm({
1062
1074
  this.extensionProviders = providers;
1063
1075
  }
1064
1076
  connectToTarget(wsUrl) {
1065
- return new Promise((resolve7) => {
1077
+ return new Promise((resolve10) => {
1066
1078
  this.ws = new import_ws.default(wsUrl);
1067
1079
  this.ws.on("open", async () => {
1068
1080
  this._connected = true;
@@ -1072,17 +1084,17 @@ var init_manager = __esm({
1072
1084
  }
1073
1085
  this.connectBrowserWs().catch(() => {
1074
1086
  });
1075
- resolve7(true);
1087
+ resolve10(true);
1076
1088
  });
1077
1089
  this.ws.on("message", (data) => {
1078
1090
  try {
1079
1091
  const msg = JSON.parse(data.toString());
1080
1092
  if (msg.id && this.pending.has(msg.id)) {
1081
- const { resolve: resolve8, reject } = this.pending.get(msg.id);
1093
+ const { resolve: resolve11, reject } = this.pending.get(msg.id);
1082
1094
  this.pending.delete(msg.id);
1083
1095
  this.failureCount = 0;
1084
1096
  if (msg.error) reject(new Error(msg.error.message));
1085
- else resolve8(msg.result);
1097
+ else resolve11(msg.result);
1086
1098
  } else if (msg.method === "Runtime.executionContextCreated") {
1087
1099
  this.contexts.add(msg.params.context.id);
1088
1100
  } else if (msg.method === "Runtime.executionContextDestroyed") {
@@ -1105,7 +1117,7 @@ var init_manager = __esm({
1105
1117
  this.ws.on("error", (err) => {
1106
1118
  this.log(`[CDP] WebSocket error: ${err.message}`);
1107
1119
  this._connected = false;
1108
- resolve7(false);
1120
+ resolve10(false);
1109
1121
  });
1110
1122
  });
1111
1123
  }
@@ -1119,7 +1131,7 @@ var init_manager = __esm({
1119
1131
  return;
1120
1132
  }
1121
1133
  this.log(`[CDP] Connecting browser WS for target discovery...`);
1122
- await new Promise((resolve7, reject) => {
1134
+ await new Promise((resolve10, reject) => {
1123
1135
  this.browserWs = new import_ws.default(browserWsUrl);
1124
1136
  this.browserWs.on("open", async () => {
1125
1137
  this._browserConnected = true;
@@ -1129,16 +1141,16 @@ var init_manager = __esm({
1129
1141
  } catch (e) {
1130
1142
  this.log(`[CDP] setDiscoverTargets failed: ${e.message}`);
1131
1143
  }
1132
- resolve7();
1144
+ resolve10();
1133
1145
  });
1134
1146
  this.browserWs.on("message", (data) => {
1135
1147
  try {
1136
1148
  const msg = JSON.parse(data.toString());
1137
1149
  if (msg.id && this.browserPending.has(msg.id)) {
1138
- const { resolve: resolve8, reject: reject2 } = this.browserPending.get(msg.id);
1150
+ const { resolve: resolve11, reject: reject2 } = this.browserPending.get(msg.id);
1139
1151
  this.browserPending.delete(msg.id);
1140
1152
  if (msg.error) reject2(new Error(msg.error.message));
1141
- else resolve8(msg.result);
1153
+ else resolve11(msg.result);
1142
1154
  }
1143
1155
  } catch {
1144
1156
  }
@@ -1158,31 +1170,31 @@ var init_manager = __esm({
1158
1170
  }
1159
1171
  }
1160
1172
  getBrowserWsUrl() {
1161
- return new Promise((resolve7) => {
1173
+ return new Promise((resolve10) => {
1162
1174
  const req = http.get(`http://127.0.0.1:${this.port}/json/version`, (res) => {
1163
1175
  let data = "";
1164
1176
  res.on("data", (chunk) => data += chunk.toString());
1165
1177
  res.on("end", () => {
1166
1178
  try {
1167
1179
  const info = JSON.parse(data);
1168
- resolve7(info.webSocketDebuggerUrl || null);
1180
+ resolve10(info.webSocketDebuggerUrl || null);
1169
1181
  } catch {
1170
- resolve7(null);
1182
+ resolve10(null);
1171
1183
  }
1172
1184
  });
1173
1185
  });
1174
- req.on("error", () => resolve7(null));
1186
+ req.on("error", () => resolve10(null));
1175
1187
  req.setTimeout(3e3, () => {
1176
1188
  req.destroy();
1177
- resolve7(null);
1189
+ resolve10(null);
1178
1190
  });
1179
1191
  });
1180
1192
  }
1181
1193
  sendBrowser(method, params = {}, timeoutMs = 15e3) {
1182
- return new Promise((resolve7, reject) => {
1194
+ return new Promise((resolve10, reject) => {
1183
1195
  if (!this.browserWs || !this._browserConnected) return reject(new Error("Browser WS not connected"));
1184
1196
  const id = this.browserMsgId++;
1185
- this.browserPending.set(id, { resolve: resolve7, reject });
1197
+ this.browserPending.set(id, { resolve: resolve10, reject });
1186
1198
  this.browserWs.send(JSON.stringify({ id, method, params }));
1187
1199
  setTimeout(() => {
1188
1200
  if (this.browserPending.has(id)) {
@@ -1222,11 +1234,11 @@ var init_manager = __esm({
1222
1234
  }
1223
1235
  // ─── CDP Protocol ────────────────────────────────────────
1224
1236
  sendInternal(method, params = {}, timeoutMs = 15e3) {
1225
- return new Promise((resolve7, reject) => {
1237
+ return new Promise((resolve10, reject) => {
1226
1238
  if (!this.ws || !this._connected) return reject(new Error("CDP not connected"));
1227
1239
  if (this.ws.readyState !== import_ws.default.OPEN) return reject(new Error("WebSocket not open"));
1228
1240
  const id = this.msgId++;
1229
- this.pending.set(id, { resolve: resolve7, reject });
1241
+ this.pending.set(id, { resolve: resolve10, reject });
1230
1242
  this.ws.send(JSON.stringify({ id, method, params }));
1231
1243
  setTimeout(() => {
1232
1244
  if (this.pending.has(id)) {
@@ -1475,7 +1487,7 @@ var init_manager = __esm({
1475
1487
  const browserWs = this.browserWs;
1476
1488
  let msgId = this.browserMsgId;
1477
1489
  const sendWs = (method, params = {}, sessionId) => {
1478
- return new Promise((resolve7, reject) => {
1490
+ return new Promise((resolve10, reject) => {
1479
1491
  const mid = msgId++;
1480
1492
  this.browserMsgId = msgId;
1481
1493
  const handler = (raw) => {
@@ -1484,7 +1496,7 @@ var init_manager = __esm({
1484
1496
  if (msg.id === mid) {
1485
1497
  browserWs.removeListener("message", handler);
1486
1498
  if (msg.error) reject(new Error(msg.error.message || JSON.stringify(msg.error)));
1487
- else resolve7(msg.result);
1499
+ else resolve10(msg.result);
1488
1500
  }
1489
1501
  } catch {
1490
1502
  }
@@ -1666,14 +1678,14 @@ var init_manager = __esm({
1666
1678
  if (!ws2 || ws2.readyState !== import_ws.default.OPEN) {
1667
1679
  throw new Error("CDP not connected");
1668
1680
  }
1669
- return new Promise((resolve7, reject) => {
1681
+ return new Promise((resolve10, reject) => {
1670
1682
  const id = getNextId();
1671
1683
  pendingMap.set(id, {
1672
1684
  resolve: (result) => {
1673
1685
  if (result?.result?.subtype === "error") {
1674
1686
  reject(new Error(result.result.description));
1675
1687
  } else {
1676
- resolve7(result?.result?.value);
1688
+ resolve10(result?.result?.value);
1677
1689
  }
1678
1690
  },
1679
1691
  reject
@@ -1705,10 +1717,10 @@ var init_manager = __esm({
1705
1717
  throw new Error("CDP not connected");
1706
1718
  }
1707
1719
  const sendViaSession = (method, params = {}) => {
1708
- return new Promise((resolve7, reject) => {
1720
+ return new Promise((resolve10, reject) => {
1709
1721
  const pendingMap = this._browserConnected ? this.browserPending : this.pending;
1710
1722
  const id = this._browserConnected ? this.browserMsgId++ : this.msgId++;
1711
- pendingMap.set(id, { resolve: resolve7, reject });
1723
+ pendingMap.set(id, { resolve: resolve10, reject });
1712
1724
  ws2.send(JSON.stringify({ id, sessionId, method, params }));
1713
1725
  setTimeout(() => {
1714
1726
  if (pendingMap.has(id)) {
@@ -2524,8 +2536,8 @@ ${next}`;
2524
2536
  const files = fs3.readdirSync(dirPath).filter((f) => f.endsWith(".jsonl") || f.endsWith(".terminal.log"));
2525
2537
  for (const file2 of files) {
2526
2538
  const filePath = path4.join(dirPath, file2);
2527
- const stat = fs3.statSync(filePath);
2528
- if (stat.mtimeMs < cutoff) {
2539
+ const stat4 = fs3.statSync(filePath);
2540
+ if (stat4.mtimeMs < cutoff) {
2529
2541
  fs3.unlinkSync(filePath);
2530
2542
  }
2531
2543
  }
@@ -3210,7 +3222,7 @@ function buildManagedClis(cliStates) {
3210
3222
  cliType: s15.type,
3211
3223
  cliName: s15.name,
3212
3224
  status: s15.status,
3213
- mode: s15.mode,
3225
+ mode: "terminal",
3214
3226
  workspace: s15.workspace || "",
3215
3227
  activeChat: s15.activeChat
3216
3228
  }));
@@ -4804,8 +4816,13 @@ var init_handler = __esm({
4804
4816
  getCliAdapter(type) {
4805
4817
  const target = type || this._currentIdeType;
4806
4818
  if (!target || !this._ctx.adapters) return null;
4819
+ let normalizedTarget = target;
4820
+ const colonIdx = normalizedTarget.lastIndexOf(":");
4821
+ if (colonIdx >= 0) normalizedTarget = normalizedTarget.substring(colonIdx + 1);
4822
+ const direct = this._ctx.adapters.get(normalizedTarget);
4823
+ if (direct) return direct;
4807
4824
  for (const [key, adapter] of this._ctx.adapters.entries()) {
4808
- if (adapter.cliType === target || key.startsWith(target)) {
4825
+ if (adapter.cliType === target || adapter.cliType === normalizedTarget || key === normalizedTarget || key.startsWith(target) || key.startsWith(normalizedTarget)) {
4809
4826
  return adapter;
4810
4827
  }
4811
4828
  }
@@ -5048,7 +5065,7 @@ var init_handler = __esm({
5048
5065
  try {
5049
5066
  const http3 = await import("http");
5050
5067
  const postData = JSON.stringify(body);
5051
- const result = await new Promise((resolve7, reject) => {
5068
+ const result = await new Promise((resolve10, reject) => {
5052
5069
  const req = http3.request({
5053
5070
  hostname: "127.0.0.1",
5054
5071
  port: 19280,
@@ -5060,9 +5077,9 @@ var init_handler = __esm({
5060
5077
  res.on("data", (chunk) => data += chunk);
5061
5078
  res.on("end", () => {
5062
5079
  try {
5063
- resolve7(JSON.parse(data));
5080
+ resolve10(JSON.parse(data));
5064
5081
  } catch {
5065
- resolve7({ raw: data });
5082
+ resolve10({ raw: data });
5066
5083
  }
5067
5084
  });
5068
5085
  });
@@ -5080,15 +5097,15 @@ var init_handler = __esm({
5080
5097
  if (!providerType) return { success: false, error: "providerType required" };
5081
5098
  try {
5082
5099
  const http3 = await import("http");
5083
- const result = await new Promise((resolve7, reject) => {
5100
+ const result = await new Promise((resolve10, reject) => {
5084
5101
  http3.get(`http://127.0.0.1:19280/api/providers/${providerType}/${endpoint}`, (res) => {
5085
5102
  let data = "";
5086
5103
  res.on("data", (chunk) => data += chunk);
5087
5104
  res.on("end", () => {
5088
5105
  try {
5089
- resolve7(JSON.parse(data));
5106
+ resolve10(JSON.parse(data));
5090
5107
  } catch {
5091
- resolve7({ raw: data });
5108
+ resolve10({ raw: data });
5092
5109
  }
5093
5110
  });
5094
5111
  }).on("error", reject);
@@ -5102,7 +5119,7 @@ var init_handler = __esm({
5102
5119
  try {
5103
5120
  const http3 = await import("http");
5104
5121
  const postData = JSON.stringify(args || {});
5105
- const result = await new Promise((resolve7, reject) => {
5122
+ const result = await new Promise((resolve10, reject) => {
5106
5123
  const req = http3.request({
5107
5124
  hostname: "127.0.0.1",
5108
5125
  port: 19280,
@@ -5114,9 +5131,9 @@ var init_handler = __esm({
5114
5131
  res.on("data", (chunk) => data += chunk);
5115
5132
  res.on("end", () => {
5116
5133
  try {
5117
- resolve7(JSON.parse(data));
5134
+ resolve10(JSON.parse(data));
5118
5135
  } catch {
5119
- resolve7({ raw: data });
5136
+ resolve10({ raw: data });
5120
5137
  }
5121
5138
  });
5122
5139
  });
@@ -5133,6 +5150,1755 @@ var init_handler = __esm({
5133
5150
  }
5134
5151
  });
5135
5152
 
5153
+ // ../../oss/packages/daemon-core/node_modules/readdirp/index.js
5154
+ function readdirp(root, options = {}) {
5155
+ let type = options.entryType || options.type;
5156
+ if (type === "both")
5157
+ type = EntryTypes.FILE_DIR_TYPE;
5158
+ if (type)
5159
+ options.type = type;
5160
+ if (!root) {
5161
+ throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
5162
+ } else if (typeof root !== "string") {
5163
+ throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");
5164
+ } else if (type && !ALL_TYPES.includes(type)) {
5165
+ throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
5166
+ }
5167
+ options.root = root;
5168
+ return new ReaddirpStream(options);
5169
+ }
5170
+ 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;
5171
+ var init_readdirp = __esm({
5172
+ "../../oss/packages/daemon-core/node_modules/readdirp/index.js"() {
5173
+ "use strict";
5174
+ import_promises = require("fs/promises");
5175
+ import_node_path = require("path");
5176
+ import_node_stream = require("stream");
5177
+ EntryTypes = {
5178
+ FILE_TYPE: "files",
5179
+ DIR_TYPE: "directories",
5180
+ FILE_DIR_TYPE: "files_directories",
5181
+ EVERYTHING_TYPE: "all"
5182
+ };
5183
+ defaultOptions = {
5184
+ root: ".",
5185
+ fileFilter: (_entryInfo) => true,
5186
+ directoryFilter: (_entryInfo) => true,
5187
+ type: EntryTypes.FILE_TYPE,
5188
+ lstat: false,
5189
+ depth: 2147483648,
5190
+ alwaysStat: false,
5191
+ highWaterMark: 4096
5192
+ };
5193
+ Object.freeze(defaultOptions);
5194
+ RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR";
5195
+ NORMAL_FLOW_ERRORS = /* @__PURE__ */ new Set(["ENOENT", "EPERM", "EACCES", "ELOOP", RECURSIVE_ERROR_CODE]);
5196
+ ALL_TYPES = [
5197
+ EntryTypes.DIR_TYPE,
5198
+ EntryTypes.EVERYTHING_TYPE,
5199
+ EntryTypes.FILE_DIR_TYPE,
5200
+ EntryTypes.FILE_TYPE
5201
+ ];
5202
+ DIR_TYPES = /* @__PURE__ */ new Set([
5203
+ EntryTypes.DIR_TYPE,
5204
+ EntryTypes.EVERYTHING_TYPE,
5205
+ EntryTypes.FILE_DIR_TYPE
5206
+ ]);
5207
+ FILE_TYPES = /* @__PURE__ */ new Set([
5208
+ EntryTypes.EVERYTHING_TYPE,
5209
+ EntryTypes.FILE_DIR_TYPE,
5210
+ EntryTypes.FILE_TYPE
5211
+ ]);
5212
+ isNormalFlowError = (error48) => NORMAL_FLOW_ERRORS.has(error48.code);
5213
+ wantBigintFsStats = process.platform === "win32";
5214
+ emptyFn = (_entryInfo) => true;
5215
+ normalizeFilter = (filter) => {
5216
+ if (filter === void 0)
5217
+ return emptyFn;
5218
+ if (typeof filter === "function")
5219
+ return filter;
5220
+ if (typeof filter === "string") {
5221
+ const fl2 = filter.trim();
5222
+ return (entry) => entry.basename === fl2;
5223
+ }
5224
+ if (Array.isArray(filter)) {
5225
+ const trItems = filter.map((item) => item.trim());
5226
+ return (entry) => trItems.some((f) => entry.basename === f);
5227
+ }
5228
+ return emptyFn;
5229
+ };
5230
+ ReaddirpStream = class extends import_node_stream.Readable {
5231
+ parents;
5232
+ reading;
5233
+ parent;
5234
+ _stat;
5235
+ _maxDepth;
5236
+ _wantsDir;
5237
+ _wantsFile;
5238
+ _wantsEverything;
5239
+ _root;
5240
+ _isDirent;
5241
+ _statsProp;
5242
+ _rdOptions;
5243
+ _fileFilter;
5244
+ _directoryFilter;
5245
+ constructor(options = {}) {
5246
+ super({
5247
+ objectMode: true,
5248
+ autoDestroy: true,
5249
+ highWaterMark: options.highWaterMark
5250
+ });
5251
+ const opts = { ...defaultOptions, ...options };
5252
+ const { root, type } = opts;
5253
+ this._fileFilter = normalizeFilter(opts.fileFilter);
5254
+ this._directoryFilter = normalizeFilter(opts.directoryFilter);
5255
+ const statMethod = opts.lstat ? import_promises.lstat : import_promises.stat;
5256
+ if (wantBigintFsStats) {
5257
+ this._stat = (path15) => statMethod(path15, { bigint: true });
5258
+ } else {
5259
+ this._stat = statMethod;
5260
+ }
5261
+ this._maxDepth = opts.depth != null && Number.isSafeInteger(opts.depth) ? opts.depth : defaultOptions.depth;
5262
+ this._wantsDir = type ? DIR_TYPES.has(type) : false;
5263
+ this._wantsFile = type ? FILE_TYPES.has(type) : false;
5264
+ this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;
5265
+ this._root = (0, import_node_path.resolve)(root);
5266
+ this._isDirent = !opts.alwaysStat;
5267
+ this._statsProp = this._isDirent ? "dirent" : "stats";
5268
+ this._rdOptions = { encoding: "utf8", withFileTypes: this._isDirent };
5269
+ this.parents = [this._exploreDir(root, 1)];
5270
+ this.reading = false;
5271
+ this.parent = void 0;
5272
+ }
5273
+ async _read(batch) {
5274
+ if (this.reading)
5275
+ return;
5276
+ this.reading = true;
5277
+ try {
5278
+ while (!this.destroyed && batch > 0) {
5279
+ const par = this.parent;
5280
+ const fil = par && par.files;
5281
+ if (fil && fil.length > 0) {
5282
+ const { path: path15, depth } = par;
5283
+ const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path15));
5284
+ const awaited = await Promise.all(slice);
5285
+ for (const entry of awaited) {
5286
+ if (!entry)
5287
+ continue;
5288
+ if (this.destroyed)
5289
+ return;
5290
+ const entryType = await this._getEntryType(entry);
5291
+ if (entryType === "directory" && this._directoryFilter(entry)) {
5292
+ if (depth <= this._maxDepth) {
5293
+ this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
5294
+ }
5295
+ if (this._wantsDir) {
5296
+ this.push(entry);
5297
+ batch--;
5298
+ }
5299
+ } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) {
5300
+ if (this._wantsFile) {
5301
+ this.push(entry);
5302
+ batch--;
5303
+ }
5304
+ }
5305
+ }
5306
+ } else {
5307
+ const parent = this.parents.pop();
5308
+ if (!parent) {
5309
+ this.push(null);
5310
+ break;
5311
+ }
5312
+ this.parent = await parent;
5313
+ if (this.destroyed)
5314
+ return;
5315
+ }
5316
+ }
5317
+ } catch (error48) {
5318
+ this.destroy(error48);
5319
+ } finally {
5320
+ this.reading = false;
5321
+ }
5322
+ }
5323
+ async _exploreDir(path15, depth) {
5324
+ let files;
5325
+ try {
5326
+ files = await (0, import_promises.readdir)(path15, this._rdOptions);
5327
+ } catch (error48) {
5328
+ this._onError(error48);
5329
+ }
5330
+ return { files, depth, path: path15 };
5331
+ }
5332
+ async _formatEntry(dirent, path15) {
5333
+ let entry;
5334
+ const basename6 = this._isDirent ? dirent.name : dirent;
5335
+ try {
5336
+ const fullPath = (0, import_node_path.resolve)((0, import_node_path.join)(path15, basename6));
5337
+ entry = { path: (0, import_node_path.relative)(this._root, fullPath), fullPath, basename: basename6 };
5338
+ entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
5339
+ } catch (err) {
5340
+ this._onError(err);
5341
+ return;
5342
+ }
5343
+ return entry;
5344
+ }
5345
+ _onError(err) {
5346
+ if (isNormalFlowError(err) && !this.destroyed) {
5347
+ this.emit("warn", err);
5348
+ } else {
5349
+ this.destroy(err);
5350
+ }
5351
+ }
5352
+ async _getEntryType(entry) {
5353
+ if (!entry && this._statsProp in entry) {
5354
+ return "";
5355
+ }
5356
+ const stats = entry[this._statsProp];
5357
+ if (stats.isFile())
5358
+ return "file";
5359
+ if (stats.isDirectory())
5360
+ return "directory";
5361
+ if (stats && stats.isSymbolicLink()) {
5362
+ const full = entry.fullPath;
5363
+ try {
5364
+ const entryRealPath = await (0, import_promises.realpath)(full);
5365
+ const entryRealPathStats = await (0, import_promises.lstat)(entryRealPath);
5366
+ if (entryRealPathStats.isFile()) {
5367
+ return "file";
5368
+ }
5369
+ if (entryRealPathStats.isDirectory()) {
5370
+ const len = entryRealPath.length;
5371
+ if (full.startsWith(entryRealPath) && full.substr(len, 1) === import_node_path.sep) {
5372
+ const recursiveError = new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
5373
+ recursiveError.code = RECURSIVE_ERROR_CODE;
5374
+ return this._onError(recursiveError);
5375
+ }
5376
+ return "directory";
5377
+ }
5378
+ } catch (error48) {
5379
+ this._onError(error48);
5380
+ return "";
5381
+ }
5382
+ }
5383
+ }
5384
+ _includeAsFile(entry) {
5385
+ const stats = entry && entry[this._statsProp];
5386
+ return stats && this._wantsEverything && !stats.isDirectory();
5387
+ }
5388
+ };
5389
+ }
5390
+ });
5391
+
5392
+ // ../../oss/packages/daemon-core/node_modules/chokidar/handler.js
5393
+ function createFsWatchInstance(path15, options, listener, errHandler, emitRaw) {
5394
+ const handleEvent = (rawEvent, evPath) => {
5395
+ listener(path15);
5396
+ emitRaw(rawEvent, evPath, { watchedPath: path15 });
5397
+ if (evPath && path15 !== evPath) {
5398
+ fsWatchBroadcast(sp.resolve(path15, evPath), KEY_LISTENERS, sp.join(path15, evPath));
5399
+ }
5400
+ };
5401
+ try {
5402
+ return (0, import_node_fs.watch)(path15, {
5403
+ persistent: options.persistent
5404
+ }, handleEvent);
5405
+ } catch (error48) {
5406
+ errHandler(error48);
5407
+ return void 0;
5408
+ }
5409
+ }
5410
+ 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;
5411
+ var init_handler2 = __esm({
5412
+ "../../oss/packages/daemon-core/node_modules/chokidar/handler.js"() {
5413
+ "use strict";
5414
+ import_node_fs = require("fs");
5415
+ import_promises2 = require("fs/promises");
5416
+ import_node_os = require("os");
5417
+ sp = __toESM(require("path"), 1);
5418
+ STR_DATA = "data";
5419
+ STR_END = "end";
5420
+ STR_CLOSE = "close";
5421
+ EMPTY_FN = () => {
5422
+ };
5423
+ pl = process.platform;
5424
+ isWindows = pl === "win32";
5425
+ isMacos = pl === "darwin";
5426
+ isLinux = pl === "linux";
5427
+ isFreeBSD = pl === "freebsd";
5428
+ isIBMi = (0, import_node_os.type)() === "OS400";
5429
+ EVENTS = {
5430
+ ALL: "all",
5431
+ READY: "ready",
5432
+ ADD: "add",
5433
+ CHANGE: "change",
5434
+ ADD_DIR: "addDir",
5435
+ UNLINK: "unlink",
5436
+ UNLINK_DIR: "unlinkDir",
5437
+ RAW: "raw",
5438
+ ERROR: "error"
5439
+ };
5440
+ EV = EVENTS;
5441
+ THROTTLE_MODE_WATCH = "watch";
5442
+ statMethods = { lstat: import_promises2.lstat, stat: import_promises2.stat };
5443
+ KEY_LISTENERS = "listeners";
5444
+ KEY_ERR = "errHandlers";
5445
+ KEY_RAW = "rawEmitters";
5446
+ HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW];
5447
+ binaryExtensions = /* @__PURE__ */ new Set([
5448
+ "3dm",
5449
+ "3ds",
5450
+ "3g2",
5451
+ "3gp",
5452
+ "7z",
5453
+ "a",
5454
+ "aac",
5455
+ "adp",
5456
+ "afdesign",
5457
+ "afphoto",
5458
+ "afpub",
5459
+ "ai",
5460
+ "aif",
5461
+ "aiff",
5462
+ "alz",
5463
+ "ape",
5464
+ "apk",
5465
+ "appimage",
5466
+ "ar",
5467
+ "arj",
5468
+ "asf",
5469
+ "au",
5470
+ "avi",
5471
+ "bak",
5472
+ "baml",
5473
+ "bh",
5474
+ "bin",
5475
+ "bk",
5476
+ "bmp",
5477
+ "btif",
5478
+ "bz2",
5479
+ "bzip2",
5480
+ "cab",
5481
+ "caf",
5482
+ "cgm",
5483
+ "class",
5484
+ "cmx",
5485
+ "cpio",
5486
+ "cr2",
5487
+ "cur",
5488
+ "dat",
5489
+ "dcm",
5490
+ "deb",
5491
+ "dex",
5492
+ "djvu",
5493
+ "dll",
5494
+ "dmg",
5495
+ "dng",
5496
+ "doc",
5497
+ "docm",
5498
+ "docx",
5499
+ "dot",
5500
+ "dotm",
5501
+ "dra",
5502
+ "DS_Store",
5503
+ "dsk",
5504
+ "dts",
5505
+ "dtshd",
5506
+ "dvb",
5507
+ "dwg",
5508
+ "dxf",
5509
+ "ecelp4800",
5510
+ "ecelp7470",
5511
+ "ecelp9600",
5512
+ "egg",
5513
+ "eol",
5514
+ "eot",
5515
+ "epub",
5516
+ "exe",
5517
+ "f4v",
5518
+ "fbs",
5519
+ "fh",
5520
+ "fla",
5521
+ "flac",
5522
+ "flatpak",
5523
+ "fli",
5524
+ "flv",
5525
+ "fpx",
5526
+ "fst",
5527
+ "fvt",
5528
+ "g3",
5529
+ "gh",
5530
+ "gif",
5531
+ "graffle",
5532
+ "gz",
5533
+ "gzip",
5534
+ "h261",
5535
+ "h263",
5536
+ "h264",
5537
+ "icns",
5538
+ "ico",
5539
+ "ief",
5540
+ "img",
5541
+ "ipa",
5542
+ "iso",
5543
+ "jar",
5544
+ "jpeg",
5545
+ "jpg",
5546
+ "jpgv",
5547
+ "jpm",
5548
+ "jxr",
5549
+ "key",
5550
+ "ktx",
5551
+ "lha",
5552
+ "lib",
5553
+ "lvp",
5554
+ "lz",
5555
+ "lzh",
5556
+ "lzma",
5557
+ "lzo",
5558
+ "m3u",
5559
+ "m4a",
5560
+ "m4v",
5561
+ "mar",
5562
+ "mdi",
5563
+ "mht",
5564
+ "mid",
5565
+ "midi",
5566
+ "mj2",
5567
+ "mka",
5568
+ "mkv",
5569
+ "mmr",
5570
+ "mng",
5571
+ "mobi",
5572
+ "mov",
5573
+ "movie",
5574
+ "mp3",
5575
+ "mp4",
5576
+ "mp4a",
5577
+ "mpeg",
5578
+ "mpg",
5579
+ "mpga",
5580
+ "mxu",
5581
+ "nef",
5582
+ "npx",
5583
+ "numbers",
5584
+ "nupkg",
5585
+ "o",
5586
+ "odp",
5587
+ "ods",
5588
+ "odt",
5589
+ "oga",
5590
+ "ogg",
5591
+ "ogv",
5592
+ "otf",
5593
+ "ott",
5594
+ "pages",
5595
+ "pbm",
5596
+ "pcx",
5597
+ "pdb",
5598
+ "pdf",
5599
+ "pea",
5600
+ "pgm",
5601
+ "pic",
5602
+ "png",
5603
+ "pnm",
5604
+ "pot",
5605
+ "potm",
5606
+ "potx",
5607
+ "ppa",
5608
+ "ppam",
5609
+ "ppm",
5610
+ "pps",
5611
+ "ppsm",
5612
+ "ppsx",
5613
+ "ppt",
5614
+ "pptm",
5615
+ "pptx",
5616
+ "psd",
5617
+ "pya",
5618
+ "pyc",
5619
+ "pyo",
5620
+ "pyv",
5621
+ "qt",
5622
+ "rar",
5623
+ "ras",
5624
+ "raw",
5625
+ "resources",
5626
+ "rgb",
5627
+ "rip",
5628
+ "rlc",
5629
+ "rmf",
5630
+ "rmvb",
5631
+ "rpm",
5632
+ "rtf",
5633
+ "rz",
5634
+ "s3m",
5635
+ "s7z",
5636
+ "scpt",
5637
+ "sgi",
5638
+ "shar",
5639
+ "snap",
5640
+ "sil",
5641
+ "sketch",
5642
+ "slk",
5643
+ "smv",
5644
+ "snk",
5645
+ "so",
5646
+ "stl",
5647
+ "suo",
5648
+ "sub",
5649
+ "swf",
5650
+ "tar",
5651
+ "tbz",
5652
+ "tbz2",
5653
+ "tga",
5654
+ "tgz",
5655
+ "thmx",
5656
+ "tif",
5657
+ "tiff",
5658
+ "tlz",
5659
+ "ttc",
5660
+ "ttf",
5661
+ "txz",
5662
+ "udf",
5663
+ "uvh",
5664
+ "uvi",
5665
+ "uvm",
5666
+ "uvp",
5667
+ "uvs",
5668
+ "uvu",
5669
+ "viv",
5670
+ "vob",
5671
+ "war",
5672
+ "wav",
5673
+ "wax",
5674
+ "wbmp",
5675
+ "wdp",
5676
+ "weba",
5677
+ "webm",
5678
+ "webp",
5679
+ "whl",
5680
+ "wim",
5681
+ "wm",
5682
+ "wma",
5683
+ "wmv",
5684
+ "wmx",
5685
+ "woff",
5686
+ "woff2",
5687
+ "wrm",
5688
+ "wvx",
5689
+ "xbm",
5690
+ "xif",
5691
+ "xla",
5692
+ "xlam",
5693
+ "xls",
5694
+ "xlsb",
5695
+ "xlsm",
5696
+ "xlsx",
5697
+ "xlt",
5698
+ "xltm",
5699
+ "xltx",
5700
+ "xm",
5701
+ "xmind",
5702
+ "xpi",
5703
+ "xpm",
5704
+ "xwd",
5705
+ "xz",
5706
+ "z",
5707
+ "zip",
5708
+ "zipx"
5709
+ ]);
5710
+ isBinaryPath = (filePath) => binaryExtensions.has(sp.extname(filePath).slice(1).toLowerCase());
5711
+ foreach = (val, fn2) => {
5712
+ if (val instanceof Set) {
5713
+ val.forEach(fn2);
5714
+ } else {
5715
+ fn2(val);
5716
+ }
5717
+ };
5718
+ addAndConvert = (main, prop, item) => {
5719
+ let container = main[prop];
5720
+ if (!(container instanceof Set)) {
5721
+ main[prop] = container = /* @__PURE__ */ new Set([container]);
5722
+ }
5723
+ container.add(item);
5724
+ };
5725
+ clearItem = (cont) => (key) => {
5726
+ const set2 = cont[key];
5727
+ if (set2 instanceof Set) {
5728
+ set2.clear();
5729
+ } else {
5730
+ delete cont[key];
5731
+ }
5732
+ };
5733
+ delFromSet = (main, prop, item) => {
5734
+ const container = main[prop];
5735
+ if (container instanceof Set) {
5736
+ container.delete(item);
5737
+ } else if (container === item) {
5738
+ delete main[prop];
5739
+ }
5740
+ };
5741
+ isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
5742
+ FsWatchInstances = /* @__PURE__ */ new Map();
5743
+ fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
5744
+ const cont = FsWatchInstances.get(fullPath);
5745
+ if (!cont)
5746
+ return;
5747
+ foreach(cont[listenerType], (listener) => {
5748
+ listener(val1, val2, val3);
5749
+ });
5750
+ };
5751
+ setFsWatchListener = (path15, fullPath, options, handlers) => {
5752
+ const { listener, errHandler, rawEmitter } = handlers;
5753
+ let cont = FsWatchInstances.get(fullPath);
5754
+ let watcher;
5755
+ if (!options.persistent) {
5756
+ watcher = createFsWatchInstance(path15, options, listener, errHandler, rawEmitter);
5757
+ if (!watcher)
5758
+ return;
5759
+ return watcher.close.bind(watcher);
5760
+ }
5761
+ if (cont) {
5762
+ addAndConvert(cont, KEY_LISTENERS, listener);
5763
+ addAndConvert(cont, KEY_ERR, errHandler);
5764
+ addAndConvert(cont, KEY_RAW, rawEmitter);
5765
+ } else {
5766
+ watcher = createFsWatchInstance(
5767
+ path15,
5768
+ options,
5769
+ fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
5770
+ errHandler,
5771
+ // no need to use broadcast here
5772
+ fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
5773
+ );
5774
+ if (!watcher)
5775
+ return;
5776
+ watcher.on(EV.ERROR, async (error48) => {
5777
+ const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
5778
+ if (cont)
5779
+ cont.watcherUnusable = true;
5780
+ if (isWindows && error48.code === "EPERM") {
5781
+ try {
5782
+ const fd = await (0, import_promises2.open)(path15, "r");
5783
+ await fd.close();
5784
+ broadcastErr(error48);
5785
+ } catch (err) {
5786
+ }
5787
+ } else {
5788
+ broadcastErr(error48);
5789
+ }
5790
+ });
5791
+ cont = {
5792
+ listeners: listener,
5793
+ errHandlers: errHandler,
5794
+ rawEmitters: rawEmitter,
5795
+ watcher
5796
+ };
5797
+ FsWatchInstances.set(fullPath, cont);
5798
+ }
5799
+ return () => {
5800
+ delFromSet(cont, KEY_LISTENERS, listener);
5801
+ delFromSet(cont, KEY_ERR, errHandler);
5802
+ delFromSet(cont, KEY_RAW, rawEmitter);
5803
+ if (isEmptySet(cont.listeners)) {
5804
+ cont.watcher.close();
5805
+ FsWatchInstances.delete(fullPath);
5806
+ HANDLER_KEYS.forEach(clearItem(cont));
5807
+ cont.watcher = void 0;
5808
+ Object.freeze(cont);
5809
+ }
5810
+ };
5811
+ };
5812
+ FsWatchFileInstances = /* @__PURE__ */ new Map();
5813
+ setFsWatchFileListener = (path15, fullPath, options, handlers) => {
5814
+ const { listener, rawEmitter } = handlers;
5815
+ let cont = FsWatchFileInstances.get(fullPath);
5816
+ const copts = cont && cont.options;
5817
+ if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
5818
+ (0, import_node_fs.unwatchFile)(fullPath);
5819
+ cont = void 0;
5820
+ }
5821
+ if (cont) {
5822
+ addAndConvert(cont, KEY_LISTENERS, listener);
5823
+ addAndConvert(cont, KEY_RAW, rawEmitter);
5824
+ } else {
5825
+ cont = {
5826
+ listeners: listener,
5827
+ rawEmitters: rawEmitter,
5828
+ options,
5829
+ watcher: (0, import_node_fs.watchFile)(fullPath, options, (curr, prev) => {
5830
+ foreach(cont.rawEmitters, (rawEmitter2) => {
5831
+ rawEmitter2(EV.CHANGE, fullPath, { curr, prev });
5832
+ });
5833
+ const currmtime = curr.mtimeMs;
5834
+ if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
5835
+ foreach(cont.listeners, (listener2) => listener2(path15, curr));
5836
+ }
5837
+ })
5838
+ };
5839
+ FsWatchFileInstances.set(fullPath, cont);
5840
+ }
5841
+ return () => {
5842
+ delFromSet(cont, KEY_LISTENERS, listener);
5843
+ delFromSet(cont, KEY_RAW, rawEmitter);
5844
+ if (isEmptySet(cont.listeners)) {
5845
+ FsWatchFileInstances.delete(fullPath);
5846
+ (0, import_node_fs.unwatchFile)(fullPath);
5847
+ cont.options = cont.watcher = void 0;
5848
+ Object.freeze(cont);
5849
+ }
5850
+ };
5851
+ };
5852
+ NodeFsHandler = class {
5853
+ fsw;
5854
+ _boundHandleError;
5855
+ constructor(fsW) {
5856
+ this.fsw = fsW;
5857
+ this._boundHandleError = (error48) => fsW._handleError(error48);
5858
+ }
5859
+ /**
5860
+ * Watch file for changes with fs_watchFile or fs_watch.
5861
+ * @param path to file or dir
5862
+ * @param listener on fs change
5863
+ * @returns closer for the watcher instance
5864
+ */
5865
+ _watchWithNodeFs(path15, listener) {
5866
+ const opts = this.fsw.options;
5867
+ const directory = sp.dirname(path15);
5868
+ const basename6 = sp.basename(path15);
5869
+ const parent = this.fsw._getWatchedDir(directory);
5870
+ parent.add(basename6);
5871
+ const absolutePath = sp.resolve(path15);
5872
+ const options = {
5873
+ persistent: opts.persistent
5874
+ };
5875
+ if (!listener)
5876
+ listener = EMPTY_FN;
5877
+ let closer;
5878
+ if (opts.usePolling) {
5879
+ const enableBin = opts.interval !== opts.binaryInterval;
5880
+ options.interval = enableBin && isBinaryPath(basename6) ? opts.binaryInterval : opts.interval;
5881
+ closer = setFsWatchFileListener(path15, absolutePath, options, {
5882
+ listener,
5883
+ rawEmitter: this.fsw._emitRaw
5884
+ });
5885
+ } else {
5886
+ closer = setFsWatchListener(path15, absolutePath, options, {
5887
+ listener,
5888
+ errHandler: this._boundHandleError,
5889
+ rawEmitter: this.fsw._emitRaw
5890
+ });
5891
+ }
5892
+ return closer;
5893
+ }
5894
+ /**
5895
+ * Watch a file and emit add event if warranted.
5896
+ * @returns closer for the watcher instance
5897
+ */
5898
+ _handleFile(file2, stats, initialAdd) {
5899
+ if (this.fsw.closed) {
5900
+ return;
5901
+ }
5902
+ const dirname8 = sp.dirname(file2);
5903
+ const basename6 = sp.basename(file2);
5904
+ const parent = this.fsw._getWatchedDir(dirname8);
5905
+ let prevStats = stats;
5906
+ if (parent.has(basename6))
5907
+ return;
5908
+ const listener = async (path15, newStats) => {
5909
+ if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file2, 5))
5910
+ return;
5911
+ if (!newStats || newStats.mtimeMs === 0) {
5912
+ try {
5913
+ const newStats2 = await (0, import_promises2.stat)(file2);
5914
+ if (this.fsw.closed)
5915
+ return;
5916
+ const at2 = newStats2.atimeMs;
5917
+ const mt2 = newStats2.mtimeMs;
5918
+ if (!at2 || at2 <= mt2 || mt2 !== prevStats.mtimeMs) {
5919
+ this.fsw._emit(EV.CHANGE, file2, newStats2);
5920
+ }
5921
+ if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats2.ino) {
5922
+ this.fsw._closeFile(path15);
5923
+ prevStats = newStats2;
5924
+ const closer2 = this._watchWithNodeFs(file2, listener);
5925
+ if (closer2)
5926
+ this.fsw._addPathCloser(path15, closer2);
5927
+ } else {
5928
+ prevStats = newStats2;
5929
+ }
5930
+ } catch (error48) {
5931
+ this.fsw._remove(dirname8, basename6);
5932
+ }
5933
+ } else if (parent.has(basename6)) {
5934
+ const at2 = newStats.atimeMs;
5935
+ const mt2 = newStats.mtimeMs;
5936
+ if (!at2 || at2 <= mt2 || mt2 !== prevStats.mtimeMs) {
5937
+ this.fsw._emit(EV.CHANGE, file2, newStats);
5938
+ }
5939
+ prevStats = newStats;
5940
+ }
5941
+ };
5942
+ const closer = this._watchWithNodeFs(file2, listener);
5943
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file2)) {
5944
+ if (!this.fsw._throttle(EV.ADD, file2, 0))
5945
+ return;
5946
+ this.fsw._emit(EV.ADD, file2, stats);
5947
+ }
5948
+ return closer;
5949
+ }
5950
+ /**
5951
+ * Handle symlinks encountered while reading a dir.
5952
+ * @param entry returned by readdirp
5953
+ * @param directory path of dir being read
5954
+ * @param path of this item
5955
+ * @param item basename of this item
5956
+ * @returns true if no more processing is needed for this entry.
5957
+ */
5958
+ async _handleSymlink(entry, directory, path15, item) {
5959
+ if (this.fsw.closed) {
5960
+ return;
5961
+ }
5962
+ const full = entry.fullPath;
5963
+ const dir = this.fsw._getWatchedDir(directory);
5964
+ if (!this.fsw.options.followSymlinks) {
5965
+ this.fsw._incrReadyCount();
5966
+ let linkPath;
5967
+ try {
5968
+ linkPath = await (0, import_promises2.realpath)(path15);
5969
+ } catch (e) {
5970
+ this.fsw._emitReady();
5971
+ return true;
5972
+ }
5973
+ if (this.fsw.closed)
5974
+ return;
5975
+ if (dir.has(item)) {
5976
+ if (this.fsw._symlinkPaths.get(full) !== linkPath) {
5977
+ this.fsw._symlinkPaths.set(full, linkPath);
5978
+ this.fsw._emit(EV.CHANGE, path15, entry.stats);
5979
+ }
5980
+ } else {
5981
+ dir.add(item);
5982
+ this.fsw._symlinkPaths.set(full, linkPath);
5983
+ this.fsw._emit(EV.ADD, path15, entry.stats);
5984
+ }
5985
+ this.fsw._emitReady();
5986
+ return true;
5987
+ }
5988
+ if (this.fsw._symlinkPaths.has(full)) {
5989
+ return true;
5990
+ }
5991
+ this.fsw._symlinkPaths.set(full, true);
5992
+ }
5993
+ _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
5994
+ directory = sp.join(directory, "");
5995
+ const throttleKey = target ? `${directory}:${target}` : directory;
5996
+ throttler = this.fsw._throttle("readdir", throttleKey, 1e3);
5997
+ if (!throttler)
5998
+ return;
5999
+ const previous = this.fsw._getWatchedDir(wh.path);
6000
+ const current = /* @__PURE__ */ new Set();
6001
+ let stream = this.fsw._readdirp(directory, {
6002
+ fileFilter: (entry) => wh.filterPath(entry),
6003
+ directoryFilter: (entry) => wh.filterDir(entry)
6004
+ });
6005
+ if (!stream)
6006
+ return;
6007
+ stream.on(STR_DATA, async (entry) => {
6008
+ if (this.fsw.closed) {
6009
+ stream = void 0;
6010
+ return;
6011
+ }
6012
+ const item = entry.path;
6013
+ let path15 = sp.join(directory, item);
6014
+ current.add(item);
6015
+ if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path15, item)) {
6016
+ return;
6017
+ }
6018
+ if (this.fsw.closed) {
6019
+ stream = void 0;
6020
+ return;
6021
+ }
6022
+ if (item === target || !target && !previous.has(item)) {
6023
+ this.fsw._incrReadyCount();
6024
+ path15 = sp.join(dir, sp.relative(dir, path15));
6025
+ this._addToNodeFs(path15, initialAdd, wh, depth + 1);
6026
+ }
6027
+ }).on(EV.ERROR, this._boundHandleError);
6028
+ return new Promise((resolve10, reject) => {
6029
+ if (!stream)
6030
+ return reject();
6031
+ stream.once(STR_END, () => {
6032
+ if (this.fsw.closed) {
6033
+ stream = void 0;
6034
+ return;
6035
+ }
6036
+ const wasThrottled = throttler ? throttler.clear() : false;
6037
+ resolve10(void 0);
6038
+ previous.getChildren().filter((item) => {
6039
+ return item !== directory && !current.has(item);
6040
+ }).forEach((item) => {
6041
+ this.fsw._remove(directory, item);
6042
+ });
6043
+ stream = void 0;
6044
+ if (wasThrottled)
6045
+ this._handleRead(directory, false, wh, target, dir, depth, throttler);
6046
+ });
6047
+ });
6048
+ }
6049
+ /**
6050
+ * Read directory to add / remove files from `@watched` list and re-read it on change.
6051
+ * @param dir fs path
6052
+ * @param stats
6053
+ * @param initialAdd
6054
+ * @param depth relative to user-supplied path
6055
+ * @param target child path targeted for watch
6056
+ * @param wh Common watch helpers for this path
6057
+ * @param realpath
6058
+ * @returns closer for the watcher instance.
6059
+ */
6060
+ async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath2) {
6061
+ const parentDir = this.fsw._getWatchedDir(sp.dirname(dir));
6062
+ const tracked = parentDir.has(sp.basename(dir));
6063
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
6064
+ this.fsw._emit(EV.ADD_DIR, dir, stats);
6065
+ }
6066
+ parentDir.add(sp.basename(dir));
6067
+ this.fsw._getWatchedDir(dir);
6068
+ let throttler;
6069
+ let closer;
6070
+ const oDepth = this.fsw.options.depth;
6071
+ if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath2)) {
6072
+ if (!target) {
6073
+ await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
6074
+ if (this.fsw.closed)
6075
+ return;
6076
+ }
6077
+ closer = this._watchWithNodeFs(dir, (dirPath, stats2) => {
6078
+ if (stats2 && stats2.mtimeMs === 0)
6079
+ return;
6080
+ this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
6081
+ });
6082
+ }
6083
+ return closer;
6084
+ }
6085
+ /**
6086
+ * Handle added file, directory, or glob pattern.
6087
+ * Delegates call to _handleFile / _handleDir after checks.
6088
+ * @param path to file or ir
6089
+ * @param initialAdd was the file added at watch instantiation?
6090
+ * @param priorWh depth relative to user-supplied path
6091
+ * @param depth Child path actually targeted for watch
6092
+ * @param target Child path actually targeted for watch
6093
+ */
6094
+ async _addToNodeFs(path15, initialAdd, priorWh, depth, target) {
6095
+ const ready = this.fsw._emitReady;
6096
+ if (this.fsw._isIgnored(path15) || this.fsw.closed) {
6097
+ ready();
6098
+ return false;
6099
+ }
6100
+ const wh = this.fsw._getWatchHelpers(path15);
6101
+ if (priorWh) {
6102
+ wh.filterPath = (entry) => priorWh.filterPath(entry);
6103
+ wh.filterDir = (entry) => priorWh.filterDir(entry);
6104
+ }
6105
+ try {
6106
+ const stats = await statMethods[wh.statMethod](wh.watchPath);
6107
+ if (this.fsw.closed)
6108
+ return;
6109
+ if (this.fsw._isIgnored(wh.watchPath, stats)) {
6110
+ ready();
6111
+ return false;
6112
+ }
6113
+ const follow = this.fsw.options.followSymlinks;
6114
+ let closer;
6115
+ if (stats.isDirectory()) {
6116
+ const absPath = sp.resolve(path15);
6117
+ const targetPath = follow ? await (0, import_promises2.realpath)(path15) : path15;
6118
+ if (this.fsw.closed)
6119
+ return;
6120
+ closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
6121
+ if (this.fsw.closed)
6122
+ return;
6123
+ if (absPath !== targetPath && targetPath !== void 0) {
6124
+ this.fsw._symlinkPaths.set(absPath, targetPath);
6125
+ }
6126
+ } else if (stats.isSymbolicLink()) {
6127
+ const targetPath = follow ? await (0, import_promises2.realpath)(path15) : path15;
6128
+ if (this.fsw.closed)
6129
+ return;
6130
+ const parent = sp.dirname(wh.watchPath);
6131
+ this.fsw._getWatchedDir(parent).add(wh.watchPath);
6132
+ this.fsw._emit(EV.ADD, wh.watchPath, stats);
6133
+ closer = await this._handleDir(parent, stats, initialAdd, depth, path15, wh, targetPath);
6134
+ if (this.fsw.closed)
6135
+ return;
6136
+ if (targetPath !== void 0) {
6137
+ this.fsw._symlinkPaths.set(sp.resolve(path15), targetPath);
6138
+ }
6139
+ } else {
6140
+ closer = this._handleFile(wh.watchPath, stats, initialAdd);
6141
+ }
6142
+ ready();
6143
+ if (closer)
6144
+ this.fsw._addPathCloser(path15, closer);
6145
+ return false;
6146
+ } catch (error48) {
6147
+ if (this.fsw._handleError(error48)) {
6148
+ ready();
6149
+ return path15;
6150
+ }
6151
+ }
6152
+ }
6153
+ };
6154
+ }
6155
+ });
6156
+
6157
+ // ../../oss/packages/daemon-core/node_modules/chokidar/index.js
6158
+ function arrify(item) {
6159
+ return Array.isArray(item) ? item : [item];
6160
+ }
6161
+ function createPattern(matcher) {
6162
+ if (typeof matcher === "function")
6163
+ return matcher;
6164
+ if (typeof matcher === "string")
6165
+ return (string4) => matcher === string4;
6166
+ if (matcher instanceof RegExp)
6167
+ return (string4) => matcher.test(string4);
6168
+ if (typeof matcher === "object" && matcher !== null) {
6169
+ return (string4) => {
6170
+ if (matcher.path === string4)
6171
+ return true;
6172
+ if (matcher.recursive) {
6173
+ const relative3 = sp2.relative(matcher.path, string4);
6174
+ if (!relative3) {
6175
+ return false;
6176
+ }
6177
+ return !relative3.startsWith("..") && !sp2.isAbsolute(relative3);
6178
+ }
6179
+ return false;
6180
+ };
6181
+ }
6182
+ return () => false;
6183
+ }
6184
+ function normalizePath(path15) {
6185
+ if (typeof path15 !== "string")
6186
+ throw new Error("string expected");
6187
+ path15 = sp2.normalize(path15);
6188
+ path15 = path15.replace(/\\/g, "/");
6189
+ let prepend = false;
6190
+ if (path15.startsWith("//"))
6191
+ prepend = true;
6192
+ path15 = path15.replace(DOUBLE_SLASH_RE, "/");
6193
+ if (prepend)
6194
+ path15 = "/" + path15;
6195
+ return path15;
6196
+ }
6197
+ function matchPatterns(patterns, testString, stats) {
6198
+ const path15 = normalizePath(testString);
6199
+ for (let index = 0; index < patterns.length; index++) {
6200
+ const pattern = patterns[index];
6201
+ if (pattern(path15, stats)) {
6202
+ return true;
6203
+ }
6204
+ }
6205
+ return false;
6206
+ }
6207
+ function anymatch(matchers, testString) {
6208
+ if (matchers == null) {
6209
+ throw new TypeError("anymatch: specify first argument");
6210
+ }
6211
+ const matchersArray = arrify(matchers);
6212
+ const patterns = matchersArray.map((matcher) => createPattern(matcher));
6213
+ if (testString == null) {
6214
+ return (testString2, stats) => {
6215
+ return matchPatterns(patterns, testString2, stats);
6216
+ };
6217
+ }
6218
+ return matchPatterns(patterns, testString);
6219
+ }
6220
+ function watch(paths, options = {}) {
6221
+ const watcher = new FSWatcher(options);
6222
+ watcher.add(paths);
6223
+ return watcher;
6224
+ }
6225
+ 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;
6226
+ var init_chokidar = __esm({
6227
+ "../../oss/packages/daemon-core/node_modules/chokidar/index.js"() {
6228
+ "use strict";
6229
+ import_node_events = require("events");
6230
+ import_node_fs2 = require("fs");
6231
+ import_promises3 = require("fs/promises");
6232
+ sp2 = __toESM(require("path"), 1);
6233
+ init_readdirp();
6234
+ init_handler2();
6235
+ SLASH = "/";
6236
+ SLASH_SLASH = "//";
6237
+ ONE_DOT = ".";
6238
+ TWO_DOTS = "..";
6239
+ STRING_TYPE = "string";
6240
+ BACK_SLASH_RE = /\\/g;
6241
+ DOUBLE_SLASH_RE = /\/\//g;
6242
+ DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
6243
+ REPLACER_RE = /^\.[/\\]/;
6244
+ isMatcherObject = (matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp);
6245
+ unifyPaths = (paths_) => {
6246
+ const paths = arrify(paths_).flat();
6247
+ if (!paths.every((p) => typeof p === STRING_TYPE)) {
6248
+ throw new TypeError(`Non-string provided as watch path: ${paths}`);
6249
+ }
6250
+ return paths.map(normalizePathToUnix);
6251
+ };
6252
+ toUnix = (string4) => {
6253
+ let str = string4.replace(BACK_SLASH_RE, SLASH);
6254
+ let prepend = false;
6255
+ if (str.startsWith(SLASH_SLASH)) {
6256
+ prepend = true;
6257
+ }
6258
+ str = str.replace(DOUBLE_SLASH_RE, SLASH);
6259
+ if (prepend) {
6260
+ str = SLASH + str;
6261
+ }
6262
+ return str;
6263
+ };
6264
+ normalizePathToUnix = (path15) => toUnix(sp2.normalize(toUnix(path15)));
6265
+ normalizeIgnored = (cwd = "") => (path15) => {
6266
+ if (typeof path15 === "string") {
6267
+ return normalizePathToUnix(sp2.isAbsolute(path15) ? path15 : sp2.join(cwd, path15));
6268
+ } else {
6269
+ return path15;
6270
+ }
6271
+ };
6272
+ getAbsolutePath = (path15, cwd) => {
6273
+ if (sp2.isAbsolute(path15)) {
6274
+ return path15;
6275
+ }
6276
+ return sp2.join(cwd, path15);
6277
+ };
6278
+ EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set());
6279
+ DirEntry = class {
6280
+ path;
6281
+ _removeWatcher;
6282
+ items;
6283
+ constructor(dir, removeWatcher) {
6284
+ this.path = dir;
6285
+ this._removeWatcher = removeWatcher;
6286
+ this.items = /* @__PURE__ */ new Set();
6287
+ }
6288
+ add(item) {
6289
+ const { items } = this;
6290
+ if (!items)
6291
+ return;
6292
+ if (item !== ONE_DOT && item !== TWO_DOTS)
6293
+ items.add(item);
6294
+ }
6295
+ async remove(item) {
6296
+ const { items } = this;
6297
+ if (!items)
6298
+ return;
6299
+ items.delete(item);
6300
+ if (items.size > 0)
6301
+ return;
6302
+ const dir = this.path;
6303
+ try {
6304
+ await (0, import_promises3.readdir)(dir);
6305
+ } catch (err) {
6306
+ if (this._removeWatcher) {
6307
+ this._removeWatcher(sp2.dirname(dir), sp2.basename(dir));
6308
+ }
6309
+ }
6310
+ }
6311
+ has(item) {
6312
+ const { items } = this;
6313
+ if (!items)
6314
+ return;
6315
+ return items.has(item);
6316
+ }
6317
+ getChildren() {
6318
+ const { items } = this;
6319
+ if (!items)
6320
+ return [];
6321
+ return [...items.values()];
6322
+ }
6323
+ dispose() {
6324
+ this.items.clear();
6325
+ this.path = "";
6326
+ this._removeWatcher = EMPTY_FN;
6327
+ this.items = EMPTY_SET;
6328
+ Object.freeze(this);
6329
+ }
6330
+ };
6331
+ STAT_METHOD_F = "stat";
6332
+ STAT_METHOD_L = "lstat";
6333
+ WatchHelper = class {
6334
+ fsw;
6335
+ path;
6336
+ watchPath;
6337
+ fullWatchPath;
6338
+ dirParts;
6339
+ followSymlinks;
6340
+ statMethod;
6341
+ constructor(path15, follow, fsw) {
6342
+ this.fsw = fsw;
6343
+ const watchPath = path15;
6344
+ this.path = path15 = path15.replace(REPLACER_RE, "");
6345
+ this.watchPath = watchPath;
6346
+ this.fullWatchPath = sp2.resolve(watchPath);
6347
+ this.dirParts = [];
6348
+ this.dirParts.forEach((parts) => {
6349
+ if (parts.length > 1)
6350
+ parts.pop();
6351
+ });
6352
+ this.followSymlinks = follow;
6353
+ this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
6354
+ }
6355
+ entryPath(entry) {
6356
+ return sp2.join(this.watchPath, sp2.relative(this.watchPath, entry.fullPath));
6357
+ }
6358
+ filterPath(entry) {
6359
+ const { stats } = entry;
6360
+ if (stats && stats.isSymbolicLink())
6361
+ return this.filterDir(entry);
6362
+ const resolvedPath = this.entryPath(entry);
6363
+ return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
6364
+ }
6365
+ filterDir(entry) {
6366
+ return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
6367
+ }
6368
+ };
6369
+ FSWatcher = class extends import_node_events.EventEmitter {
6370
+ closed;
6371
+ options;
6372
+ _closers;
6373
+ _ignoredPaths;
6374
+ _throttled;
6375
+ _streams;
6376
+ _symlinkPaths;
6377
+ _watched;
6378
+ _pendingWrites;
6379
+ _pendingUnlinks;
6380
+ _readyCount;
6381
+ _emitReady;
6382
+ _closePromise;
6383
+ _userIgnored;
6384
+ _readyEmitted;
6385
+ _emitRaw;
6386
+ _boundRemove;
6387
+ _nodeFsHandler;
6388
+ // Not indenting methods for history sake; for now.
6389
+ constructor(_opts = {}) {
6390
+ super();
6391
+ this.closed = false;
6392
+ this._closers = /* @__PURE__ */ new Map();
6393
+ this._ignoredPaths = /* @__PURE__ */ new Set();
6394
+ this._throttled = /* @__PURE__ */ new Map();
6395
+ this._streams = /* @__PURE__ */ new Set();
6396
+ this._symlinkPaths = /* @__PURE__ */ new Map();
6397
+ this._watched = /* @__PURE__ */ new Map();
6398
+ this._pendingWrites = /* @__PURE__ */ new Map();
6399
+ this._pendingUnlinks = /* @__PURE__ */ new Map();
6400
+ this._readyCount = 0;
6401
+ this._readyEmitted = false;
6402
+ const awf = _opts.awaitWriteFinish;
6403
+ const DEF_AWF = { stabilityThreshold: 2e3, pollInterval: 100 };
6404
+ const opts = {
6405
+ // Defaults
6406
+ persistent: true,
6407
+ ignoreInitial: false,
6408
+ ignorePermissionErrors: false,
6409
+ interval: 100,
6410
+ binaryInterval: 300,
6411
+ followSymlinks: true,
6412
+ usePolling: false,
6413
+ // useAsync: false,
6414
+ atomic: true,
6415
+ // NOTE: overwritten later (depends on usePolling)
6416
+ ..._opts,
6417
+ // Change format
6418
+ ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
6419
+ awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? { ...DEF_AWF, ...awf } : false
6420
+ };
6421
+ if (isIBMi)
6422
+ opts.usePolling = true;
6423
+ if (opts.atomic === void 0)
6424
+ opts.atomic = !opts.usePolling;
6425
+ const envPoll = process.env.CHOKIDAR_USEPOLLING;
6426
+ if (envPoll !== void 0) {
6427
+ const envLower = envPoll.toLowerCase();
6428
+ if (envLower === "false" || envLower === "0")
6429
+ opts.usePolling = false;
6430
+ else if (envLower === "true" || envLower === "1")
6431
+ opts.usePolling = true;
6432
+ else
6433
+ opts.usePolling = !!envLower;
6434
+ }
6435
+ const envInterval = process.env.CHOKIDAR_INTERVAL;
6436
+ if (envInterval)
6437
+ opts.interval = Number.parseInt(envInterval, 10);
6438
+ let readyCalls = 0;
6439
+ this._emitReady = () => {
6440
+ readyCalls++;
6441
+ if (readyCalls >= this._readyCount) {
6442
+ this._emitReady = EMPTY_FN;
6443
+ this._readyEmitted = true;
6444
+ process.nextTick(() => this.emit(EVENTS.READY));
6445
+ }
6446
+ };
6447
+ this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args);
6448
+ this._boundRemove = this._remove.bind(this);
6449
+ this.options = opts;
6450
+ this._nodeFsHandler = new NodeFsHandler(this);
6451
+ Object.freeze(opts);
6452
+ }
6453
+ _addIgnoredPath(matcher) {
6454
+ if (isMatcherObject(matcher)) {
6455
+ for (const ignored of this._ignoredPaths) {
6456
+ if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) {
6457
+ return;
6458
+ }
6459
+ }
6460
+ }
6461
+ this._ignoredPaths.add(matcher);
6462
+ }
6463
+ _removeIgnoredPath(matcher) {
6464
+ this._ignoredPaths.delete(matcher);
6465
+ if (typeof matcher === "string") {
6466
+ for (const ignored of this._ignoredPaths) {
6467
+ if (isMatcherObject(ignored) && ignored.path === matcher) {
6468
+ this._ignoredPaths.delete(ignored);
6469
+ }
6470
+ }
6471
+ }
6472
+ }
6473
+ // Public methods
6474
+ /**
6475
+ * Adds paths to be watched on an existing FSWatcher instance.
6476
+ * @param paths_ file or file list. Other arguments are unused
6477
+ */
6478
+ add(paths_, _origAdd, _internal) {
6479
+ const { cwd } = this.options;
6480
+ this.closed = false;
6481
+ this._closePromise = void 0;
6482
+ let paths = unifyPaths(paths_);
6483
+ if (cwd) {
6484
+ paths = paths.map((path15) => {
6485
+ const absPath = getAbsolutePath(path15, cwd);
6486
+ return absPath;
6487
+ });
6488
+ }
6489
+ paths.forEach((path15) => {
6490
+ this._removeIgnoredPath(path15);
6491
+ });
6492
+ this._userIgnored = void 0;
6493
+ if (!this._readyCount)
6494
+ this._readyCount = 0;
6495
+ this._readyCount += paths.length;
6496
+ Promise.all(paths.map(async (path15) => {
6497
+ const res = await this._nodeFsHandler._addToNodeFs(path15, !_internal, void 0, 0, _origAdd);
6498
+ if (res)
6499
+ this._emitReady();
6500
+ return res;
6501
+ })).then((results) => {
6502
+ if (this.closed)
6503
+ return;
6504
+ results.forEach((item) => {
6505
+ if (item)
6506
+ this.add(sp2.dirname(item), sp2.basename(_origAdd || item));
6507
+ });
6508
+ });
6509
+ return this;
6510
+ }
6511
+ /**
6512
+ * Close watchers or start ignoring events from specified paths.
6513
+ */
6514
+ unwatch(paths_) {
6515
+ if (this.closed)
6516
+ return this;
6517
+ const paths = unifyPaths(paths_);
6518
+ const { cwd } = this.options;
6519
+ paths.forEach((path15) => {
6520
+ if (!sp2.isAbsolute(path15) && !this._closers.has(path15)) {
6521
+ if (cwd)
6522
+ path15 = sp2.join(cwd, path15);
6523
+ path15 = sp2.resolve(path15);
6524
+ }
6525
+ this._closePath(path15);
6526
+ this._addIgnoredPath(path15);
6527
+ if (this._watched.has(path15)) {
6528
+ this._addIgnoredPath({
6529
+ path: path15,
6530
+ recursive: true
6531
+ });
6532
+ }
6533
+ this._userIgnored = void 0;
6534
+ });
6535
+ return this;
6536
+ }
6537
+ /**
6538
+ * Close watchers and remove all listeners from watched paths.
6539
+ */
6540
+ close() {
6541
+ if (this._closePromise) {
6542
+ return this._closePromise;
6543
+ }
6544
+ this.closed = true;
6545
+ this.removeAllListeners();
6546
+ const closers = [];
6547
+ this._closers.forEach((closerList) => closerList.forEach((closer) => {
6548
+ const promise2 = closer();
6549
+ if (promise2 instanceof Promise)
6550
+ closers.push(promise2);
6551
+ }));
6552
+ this._streams.forEach((stream) => stream.destroy());
6553
+ this._userIgnored = void 0;
6554
+ this._readyCount = 0;
6555
+ this._readyEmitted = false;
6556
+ this._watched.forEach((dirent) => dirent.dispose());
6557
+ this._closers.clear();
6558
+ this._watched.clear();
6559
+ this._streams.clear();
6560
+ this._symlinkPaths.clear();
6561
+ this._throttled.clear();
6562
+ this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve();
6563
+ return this._closePromise;
6564
+ }
6565
+ /**
6566
+ * Expose list of watched paths
6567
+ * @returns for chaining
6568
+ */
6569
+ getWatched() {
6570
+ const watchList = {};
6571
+ this._watched.forEach((entry, dir) => {
6572
+ const key = this.options.cwd ? sp2.relative(this.options.cwd, dir) : dir;
6573
+ const index = key || ONE_DOT;
6574
+ watchList[index] = entry.getChildren().sort();
6575
+ });
6576
+ return watchList;
6577
+ }
6578
+ emitWithAll(event, args) {
6579
+ this.emit(event, ...args);
6580
+ if (event !== EVENTS.ERROR)
6581
+ this.emit(EVENTS.ALL, event, ...args);
6582
+ }
6583
+ // Common helpers
6584
+ // --------------
6585
+ /**
6586
+ * Normalize and emit events.
6587
+ * Calling _emit DOES NOT MEAN emit() would be called!
6588
+ * @param event Type of event
6589
+ * @param path File or directory path
6590
+ * @param stats arguments to be passed with event
6591
+ * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
6592
+ */
6593
+ async _emit(event, path15, stats) {
6594
+ if (this.closed)
6595
+ return;
6596
+ const opts = this.options;
6597
+ if (isWindows)
6598
+ path15 = sp2.normalize(path15);
6599
+ if (opts.cwd)
6600
+ path15 = sp2.relative(opts.cwd, path15);
6601
+ const args = [path15];
6602
+ if (stats != null)
6603
+ args.push(stats);
6604
+ const awf = opts.awaitWriteFinish;
6605
+ let pw;
6606
+ if (awf && (pw = this._pendingWrites.get(path15))) {
6607
+ pw.lastChange = /* @__PURE__ */ new Date();
6608
+ return this;
6609
+ }
6610
+ if (opts.atomic) {
6611
+ if (event === EVENTS.UNLINK) {
6612
+ this._pendingUnlinks.set(path15, [event, ...args]);
6613
+ setTimeout(() => {
6614
+ this._pendingUnlinks.forEach((entry, path16) => {
6615
+ this.emit(...entry);
6616
+ this.emit(EVENTS.ALL, ...entry);
6617
+ this._pendingUnlinks.delete(path16);
6618
+ });
6619
+ }, typeof opts.atomic === "number" ? opts.atomic : 100);
6620
+ return this;
6621
+ }
6622
+ if (event === EVENTS.ADD && this._pendingUnlinks.has(path15)) {
6623
+ event = EVENTS.CHANGE;
6624
+ this._pendingUnlinks.delete(path15);
6625
+ }
6626
+ }
6627
+ if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
6628
+ const awfEmit = (err, stats2) => {
6629
+ if (err) {
6630
+ event = EVENTS.ERROR;
6631
+ args[0] = err;
6632
+ this.emitWithAll(event, args);
6633
+ } else if (stats2) {
6634
+ if (args.length > 1) {
6635
+ args[1] = stats2;
6636
+ } else {
6637
+ args.push(stats2);
6638
+ }
6639
+ this.emitWithAll(event, args);
6640
+ }
6641
+ };
6642
+ this._awaitWriteFinish(path15, awf.stabilityThreshold, event, awfEmit);
6643
+ return this;
6644
+ }
6645
+ if (event === EVENTS.CHANGE) {
6646
+ const isThrottled = !this._throttle(EVENTS.CHANGE, path15, 50);
6647
+ if (isThrottled)
6648
+ return this;
6649
+ }
6650
+ if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
6651
+ const fullPath = opts.cwd ? sp2.join(opts.cwd, path15) : path15;
6652
+ let stats2;
6653
+ try {
6654
+ stats2 = await (0, import_promises3.stat)(fullPath);
6655
+ } catch (err) {
6656
+ }
6657
+ if (!stats2 || this.closed)
6658
+ return;
6659
+ args.push(stats2);
6660
+ }
6661
+ this.emitWithAll(event, args);
6662
+ return this;
6663
+ }
6664
+ /**
6665
+ * Common handler for errors
6666
+ * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
6667
+ */
6668
+ _handleError(error48) {
6669
+ const code = error48 && error48.code;
6670
+ if (error48 && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) {
6671
+ this.emit(EVENTS.ERROR, error48);
6672
+ }
6673
+ return error48 || this.closed;
6674
+ }
6675
+ /**
6676
+ * Helper utility for throttling
6677
+ * @param actionType type being throttled
6678
+ * @param path being acted upon
6679
+ * @param timeout duration of time to suppress duplicate actions
6680
+ * @returns tracking object or false if action should be suppressed
6681
+ */
6682
+ _throttle(actionType, path15, timeout) {
6683
+ if (!this._throttled.has(actionType)) {
6684
+ this._throttled.set(actionType, /* @__PURE__ */ new Map());
6685
+ }
6686
+ const action = this._throttled.get(actionType);
6687
+ if (!action)
6688
+ throw new Error("invalid throttle");
6689
+ const actionPath = action.get(path15);
6690
+ if (actionPath) {
6691
+ actionPath.count++;
6692
+ return false;
6693
+ }
6694
+ let timeoutObject;
6695
+ const clear = () => {
6696
+ const item = action.get(path15);
6697
+ const count = item ? item.count : 0;
6698
+ action.delete(path15);
6699
+ clearTimeout(timeoutObject);
6700
+ if (item)
6701
+ clearTimeout(item.timeoutObject);
6702
+ return count;
6703
+ };
6704
+ timeoutObject = setTimeout(clear, timeout);
6705
+ const thr = { timeoutObject, clear, count: 0 };
6706
+ action.set(path15, thr);
6707
+ return thr;
6708
+ }
6709
+ _incrReadyCount() {
6710
+ return this._readyCount++;
6711
+ }
6712
+ /**
6713
+ * Awaits write operation to finish.
6714
+ * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
6715
+ * @param path being acted upon
6716
+ * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
6717
+ * @param event
6718
+ * @param awfEmit Callback to be called when ready for event to be emitted.
6719
+ */
6720
+ _awaitWriteFinish(path15, threshold, event, awfEmit) {
6721
+ const awf = this.options.awaitWriteFinish;
6722
+ if (typeof awf !== "object")
6723
+ return;
6724
+ const pollInterval = awf.pollInterval;
6725
+ let timeoutHandler;
6726
+ let fullPath = path15;
6727
+ if (this.options.cwd && !sp2.isAbsolute(path15)) {
6728
+ fullPath = sp2.join(this.options.cwd, path15);
6729
+ }
6730
+ const now = /* @__PURE__ */ new Date();
6731
+ const writes = this._pendingWrites;
6732
+ function awaitWriteFinishFn(prevStat) {
6733
+ (0, import_node_fs2.stat)(fullPath, (err, curStat) => {
6734
+ if (err || !writes.has(path15)) {
6735
+ if (err && err.code !== "ENOENT")
6736
+ awfEmit(err);
6737
+ return;
6738
+ }
6739
+ const now2 = Number(/* @__PURE__ */ new Date());
6740
+ if (prevStat && curStat.size !== prevStat.size) {
6741
+ writes.get(path15).lastChange = now2;
6742
+ }
6743
+ const pw = writes.get(path15);
6744
+ const df = now2 - pw.lastChange;
6745
+ if (df >= threshold) {
6746
+ writes.delete(path15);
6747
+ awfEmit(void 0, curStat);
6748
+ } else {
6749
+ timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
6750
+ }
6751
+ });
6752
+ }
6753
+ if (!writes.has(path15)) {
6754
+ writes.set(path15, {
6755
+ lastChange: now,
6756
+ cancelWait: () => {
6757
+ writes.delete(path15);
6758
+ clearTimeout(timeoutHandler);
6759
+ return event;
6760
+ }
6761
+ });
6762
+ timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
6763
+ }
6764
+ }
6765
+ /**
6766
+ * Determines whether user has asked to ignore this path.
6767
+ */
6768
+ _isIgnored(path15, stats) {
6769
+ if (this.options.atomic && DOT_RE.test(path15))
6770
+ return true;
6771
+ if (!this._userIgnored) {
6772
+ const { cwd } = this.options;
6773
+ const ign = this.options.ignored;
6774
+ const ignored = (ign || []).map(normalizeIgnored(cwd));
6775
+ const ignoredPaths = [...this._ignoredPaths];
6776
+ const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];
6777
+ this._userIgnored = anymatch(list, void 0);
6778
+ }
6779
+ return this._userIgnored(path15, stats);
6780
+ }
6781
+ _isntIgnored(path15, stat4) {
6782
+ return !this._isIgnored(path15, stat4);
6783
+ }
6784
+ /**
6785
+ * Provides a set of common helpers and properties relating to symlink handling.
6786
+ * @param path file or directory pattern being watched
6787
+ */
6788
+ _getWatchHelpers(path15) {
6789
+ return new WatchHelper(path15, this.options.followSymlinks, this);
6790
+ }
6791
+ // Directory helpers
6792
+ // -----------------
6793
+ /**
6794
+ * Provides directory tracking objects
6795
+ * @param directory path of the directory
6796
+ */
6797
+ _getWatchedDir(directory) {
6798
+ const dir = sp2.resolve(directory);
6799
+ if (!this._watched.has(dir))
6800
+ this._watched.set(dir, new DirEntry(dir, this._boundRemove));
6801
+ return this._watched.get(dir);
6802
+ }
6803
+ // File helpers
6804
+ // ------------
6805
+ /**
6806
+ * Check for read permissions: https://stackoverflow.com/a/11781404/1358405
6807
+ */
6808
+ _hasReadPermissions(stats) {
6809
+ if (this.options.ignorePermissionErrors)
6810
+ return true;
6811
+ return Boolean(Number(stats.mode) & 256);
6812
+ }
6813
+ /**
6814
+ * Handles emitting unlink events for
6815
+ * files and directories, and via recursion, for
6816
+ * files and directories within directories that are unlinked
6817
+ * @param directory within which the following item is located
6818
+ * @param item base path of item/directory
6819
+ */
6820
+ _remove(directory, item, isDirectory) {
6821
+ const path15 = sp2.join(directory, item);
6822
+ const fullPath = sp2.resolve(path15);
6823
+ isDirectory = isDirectory != null ? isDirectory : this._watched.has(path15) || this._watched.has(fullPath);
6824
+ if (!this._throttle("remove", path15, 100))
6825
+ return;
6826
+ if (!isDirectory && this._watched.size === 1) {
6827
+ this.add(directory, item, true);
6828
+ }
6829
+ const wp = this._getWatchedDir(path15);
6830
+ const nestedDirectoryChildren = wp.getChildren();
6831
+ nestedDirectoryChildren.forEach((nested) => this._remove(path15, nested));
6832
+ const parent = this._getWatchedDir(directory);
6833
+ const wasTracked = parent.has(item);
6834
+ parent.remove(item);
6835
+ if (this._symlinkPaths.has(fullPath)) {
6836
+ this._symlinkPaths.delete(fullPath);
6837
+ }
6838
+ let relPath = path15;
6839
+ if (this.options.cwd)
6840
+ relPath = sp2.relative(this.options.cwd, path15);
6841
+ if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
6842
+ const event = this._pendingWrites.get(relPath).cancelWait();
6843
+ if (event === EVENTS.ADD)
6844
+ return;
6845
+ }
6846
+ this._watched.delete(path15);
6847
+ this._watched.delete(fullPath);
6848
+ const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
6849
+ if (wasTracked && !this._isIgnored(path15))
6850
+ this._emit(eventName, path15);
6851
+ this._closePath(path15);
6852
+ }
6853
+ /**
6854
+ * Closes all watchers for a path
6855
+ */
6856
+ _closePath(path15) {
6857
+ this._closeFile(path15);
6858
+ const dir = sp2.dirname(path15);
6859
+ this._getWatchedDir(dir).remove(sp2.basename(path15));
6860
+ }
6861
+ /**
6862
+ * Closes only file-specific watchers
6863
+ */
6864
+ _closeFile(path15) {
6865
+ const closers = this._closers.get(path15);
6866
+ if (!closers)
6867
+ return;
6868
+ closers.forEach((closer) => closer());
6869
+ this._closers.delete(path15);
6870
+ }
6871
+ _addPathCloser(path15, closer) {
6872
+ if (!closer)
6873
+ return;
6874
+ let list = this._closers.get(path15);
6875
+ if (!list) {
6876
+ list = [];
6877
+ this._closers.set(path15, list);
6878
+ }
6879
+ list.push(closer);
6880
+ }
6881
+ _readdirp(root, opts) {
6882
+ if (this.closed)
6883
+ return;
6884
+ const options = { type: EVENTS.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };
6885
+ let stream = readdirp(root, options);
6886
+ this._streams.add(stream);
6887
+ stream.once(STR_CLOSE, () => {
6888
+ stream = void 0;
6889
+ });
6890
+ stream.once(STR_END, () => {
6891
+ if (stream) {
6892
+ this._streams.delete(stream);
6893
+ stream = void 0;
6894
+ }
6895
+ });
6896
+ return stream;
6897
+ }
6898
+ };
6899
+ }
6900
+ });
6901
+
5136
6902
  // ../../oss/packages/daemon-core/src/providers/provider-loader.ts
5137
6903
  var fs5, path6, os7, ProviderLoader;
5138
6904
  var init_provider_loader = __esm({
@@ -5141,11 +6907,11 @@ var init_provider_loader = __esm({
5141
6907
  fs5 = __toESM(require("fs"));
5142
6908
  path6 = __toESM(require("path"));
5143
6909
  os7 = __toESM(require("os"));
6910
+ init_chokidar();
5144
6911
  init_ide_detector();
5145
6912
  init_logger();
5146
6913
  ProviderLoader = class _ProviderLoader {
5147
6914
  providers = /* @__PURE__ */ new Map();
5148
- builtinDirs;
5149
6915
  userDir;
5150
6916
  upstreamDir;
5151
6917
  disableUpstream;
@@ -5160,36 +6926,31 @@ var init_provider_loader = __esm({
5160
6926
  static GITHUB_TARBALL_URL = "https://github.com/vilmire/adhdev-providers/archive/refs/heads/main.tar.gz";
5161
6927
  static META_FILE = ".meta.json";
5162
6928
  constructor(options) {
5163
- if (options?.builtinDir) {
5164
- this.builtinDirs = Array.isArray(options.builtinDir) ? options.builtinDir : [options.builtinDir];
6929
+ this.logFn = options?.logFn || LOG.forComponent("Provider").asLogFn();
6930
+ const defaultProvidersDir = path6.join(os7.homedir(), ".adhdev", "providers");
6931
+ if (options?.userDir) {
6932
+ this.userDir = options.userDir;
6933
+ this.log(`Config 'providerDir' applied: ${this.userDir}`);
5165
6934
  } else {
5166
- this.builtinDirs = [];
6935
+ const localRepoPath = path6.resolve(__dirname, "../../../../../adhdev-providers");
6936
+ if (fs5.existsSync(localRepoPath)) {
6937
+ this.userDir = localRepoPath;
6938
+ this.log(`Auto-detected local public repository: ${this.userDir} (Dev workspace speedup)`);
6939
+ } else {
6940
+ this.userDir = defaultProvidersDir;
6941
+ this.log(`Using default user providers directory: ${this.userDir}`);
6942
+ }
5167
6943
  }
5168
- const defaultProvidersDir = path6.join(os7.homedir(), ".adhdev", "providers");
5169
- this.userDir = options?.userDir || defaultProvidersDir;
5170
6944
  this.upstreamDir = path6.join(defaultProvidersDir, ".upstream");
5171
6945
  this.disableUpstream = options?.disableUpstream ?? false;
5172
- this.logFn = options?.logFn || LOG.forComponent("Provider").asLogFn();
5173
6946
  }
5174
6947
  log(msg) {
5175
6948
  this.logFn(`[ProviderLoader] ${msg}`);
5176
6949
  }
5177
6950
  // ─── Public API ────────────────────────────────
5178
6951
  /**
5179
- * Ordered builtin roots used for local fallback/reference data.
5180
- */
5181
- getBuiltinDirs() {
5182
- return [...this.builtinDirs];
5183
- }
5184
- /**
5185
- * Primary builtin root used for local scaffolding/reference flows.
5186
- */
5187
- getPrimaryBuiltinDir() {
5188
- return this.builtinDirs[0];
5189
- }
5190
- /**
5191
- * User override root (~/.adhdev/providers by default).
5192
- */
6952
+ * User override root (~/.adhdev/providers by default).
6953
+ */
5193
6954
  getUserDir() {
5194
6955
  return this.userDir;
5195
6956
  }
@@ -5200,11 +6961,11 @@ var init_provider_loader = __esm({
5200
6961
  return this.upstreamDir;
5201
6962
  }
5202
6963
  /**
5203
- * Provider search order for on-disk lookups.
5204
- * Highest-priority editable overrides come first.
5205
- */
6964
+ * Provider search order for on-disk lookups.
6965
+ * Highest-priority editable overrides come first.
6966
+ */
5206
6967
  getProviderRoots() {
5207
- return [this.userDir, this.upstreamDir, ...this.builtinDirs];
6968
+ return [this.userDir, this.upstreamDir];
5208
6969
  }
5209
6970
  /**
5210
6971
  * Canonical provider directory shape for a given root.
@@ -5225,16 +6986,9 @@ var init_provider_loader = __esm({
5225
6986
  return this.getProviderDir(this.upstreamDir, category, type);
5226
6987
  }
5227
6988
  /**
5228
- * Canonical builtin directory for a provider.
6989
+ * Find the on-disk directory for a provider by type.
6990
+ * Search order: user override → upstream.
5229
6991
  */
5230
- getBuiltinProviderDir(category, type) {
5231
- const builtinRoot = this.getPrimaryBuiltinDir();
5232
- return builtinRoot ? this.getProviderDir(builtinRoot, category, type) : "";
5233
- }
5234
- /**
5235
- * Find the on-disk directory for a provider by type.
5236
- * Search order: user override → upstream → builtin fallback.
5237
- */
5238
6992
  findProviderDir(type) {
5239
6993
  return this.findProviderDirInternal(type);
5240
6994
  }
@@ -5331,12 +7085,15 @@ var init_provider_loader = __esm({
5331
7085
  const result = [];
5332
7086
  for (const p of this.providers.values()) {
5333
7087
  if ((p.category === "cli" || p.category === "acp") && p.spawn?.command) {
7088
+ const verCmdConfig = p.versionCommand;
7089
+ const versionCommand = typeof verCmdConfig === "object" && verCmdConfig !== null ? verCmdConfig[process.platform] : verCmdConfig;
5334
7090
  result.push({
5335
7091
  id: p.type,
5336
7092
  displayName: p.displayName || p.name,
5337
7093
  icon: p.icon || "\u{1F527}",
5338
7094
  command: p.spawn.command,
5339
- category: p.category
7095
+ category: p.category,
7096
+ ...typeof versionCommand === "string" && versionCommand.trim() ? { versionCommand: versionCommand.trim() } : {}
5340
7097
  });
5341
7098
  }
5342
7099
  }
@@ -5599,13 +7356,12 @@ var init_provider_loader = __esm({
5599
7356
  }
5600
7357
  }
5601
7358
  const result = this.buildScriptWrappersFromDir(dir);
5602
- this.log(` [loadScriptsFromDir] ${type}: built wrappers from ${dir} (${Object.keys(result).length} scripts)`);
5603
7359
  this.scriptsCache.set(dir, result);
5604
7360
  return result;
5605
7361
  }
5606
7362
  /**
5607
- * Hot-reload: start watching for file changes
5608
- */
7363
+ * Hot-reload: start watching for file changes
7364
+ */
5609
7365
  watch() {
5610
7366
  this.stopWatch();
5611
7367
  const watchDir = (dir) => {
@@ -5617,18 +7373,27 @@ var init_provider_loader = __esm({
5617
7373
  }
5618
7374
  }
5619
7375
  try {
5620
- const watcher = fs5.watch(dir, { recursive: true }, (event, filename) => {
5621
- if (filename?.endsWith(".js") || filename?.endsWith(".json")) {
5622
- this.log(`File changed: ${filename}, reloading...`);
5623
- this.loadAll();
5624
- }
7376
+ const watcher = watch(dir, {
7377
+ ignored: /(^|[\/\\])\.\./,
7378
+ // ignore dotfiles
7379
+ persistent: true,
7380
+ ignoreInitial: true,
7381
+ awaitWriteFinish: { stabilityThreshold: 200, pollInterval: 50 }
5625
7382
  });
7383
+ const handleChange = (filePath) => {
7384
+ if (filePath.endsWith(".js") || filePath.endsWith(".json")) {
7385
+ this.log(`File changed: ${path6.basename(filePath)}, reloading...`);
7386
+ this.reload();
7387
+ }
7388
+ };
7389
+ watcher.on("add", handleChange).on("change", handleChange).on("unlink", handleChange);
7390
+ watcher.on("error", (err) => this.log(`Watch error: ${err.message}`));
5626
7391
  this.watchers.push(watcher);
7392
+ this.log(`Hot-reload watcher active: ${dir}`);
5627
7393
  } catch (e) {
5628
7394
  this.log(`Watch failed for ${dir}: ${e.message}`);
5629
7395
  }
5630
7396
  };
5631
- this.builtinDirs.forEach((dir) => watchDir(dir));
5632
7397
  watchDir(this.userDir);
5633
7398
  }
5634
7399
  /**
@@ -5689,7 +7454,7 @@ var init_provider_loader = __esm({
5689
7454
  return { updated: false };
5690
7455
  }
5691
7456
  try {
5692
- const etag = await new Promise((resolve7, reject) => {
7457
+ const etag = await new Promise((resolve10, reject) => {
5693
7458
  const options = {
5694
7459
  method: "HEAD",
5695
7460
  hostname: "github.com",
@@ -5707,7 +7472,7 @@ var init_provider_loader = __esm({
5707
7472
  headers: { "User-Agent": "adhdev-launcher" },
5708
7473
  timeout: 1e4
5709
7474
  }, (res2) => {
5710
- resolve7(res2.headers.etag || res2.headers["last-modified"] || "");
7475
+ resolve10(res2.headers.etag || res2.headers["last-modified"] || "");
5711
7476
  });
5712
7477
  req2.on("error", reject);
5713
7478
  req2.on("timeout", () => {
@@ -5716,7 +7481,7 @@ var init_provider_loader = __esm({
5716
7481
  });
5717
7482
  req2.end();
5718
7483
  } else {
5719
- resolve7(res.headers.etag || res.headers["last-modified"] || "");
7484
+ resolve10(res.headers.etag || res.headers["last-modified"] || "");
5720
7485
  }
5721
7486
  });
5722
7487
  req.on("error", reject);
@@ -5780,7 +7545,7 @@ var init_provider_loader = __esm({
5780
7545
  downloadFile(url2, destPath) {
5781
7546
  const https = require("https");
5782
7547
  const http3 = require("http");
5783
- return new Promise((resolve7, reject) => {
7548
+ return new Promise((resolve10, reject) => {
5784
7549
  const doRequest = (reqUrl, redirectCount = 0) => {
5785
7550
  if (redirectCount > 5) {
5786
7551
  reject(new Error("Too many redirects"));
@@ -5800,7 +7565,7 @@ var init_provider_loader = __esm({
5800
7565
  res.pipe(ws2);
5801
7566
  ws2.on("finish", () => {
5802
7567
  ws2.close();
5803
- resolve7();
7568
+ resolve10();
5804
7569
  });
5805
7570
  ws2.on("error", reject);
5806
7571
  });
@@ -6072,8 +7837,8 @@ var init_provider_loader = __esm({
6072
7837
  const existed = this.providers.has(mod.type);
6073
7838
  this.providers.set(mod.type, mod);
6074
7839
  count++;
6075
- const source = d.startsWith(this.userDir) && !d.includes(".upstream") ? "user" : d.startsWith(this.upstreamDir) ? "upstream" : "builtin";
6076
- const overrideWarning = existed && source === "user" ? " \u26A0 OVERRIDES builtin/upstream" : "";
7840
+ const source = d.startsWith(this.userDir) && !d.includes(".upstream") ? "user" : "upstream";
7841
+ const overrideWarning = existed && source === "user" ? " \u26A0 OVERRIDES upstream" : "";
6077
7842
  this.log(` ${existed ? "\u{1F504}" : "\u2705"} ${mod.type} (${mod.category}) \u2014 ${mod.name} [${source}]${overrideWarning}`);
6078
7843
  }
6079
7844
  } catch (e) {
@@ -6120,9 +7885,9 @@ var init_provider_loader = __esm({
6120
7885
  }
6121
7886
  }
6122
7887
  compareVersions(a, b2) {
6123
- const normalize2 = (v2) => v2.split(/[-_+]/)[0].split(".").map((x) => parseInt(x, 10) || 0);
6124
- const pa2 = normalize2(a);
6125
- const pb = normalize2(b2);
7888
+ const normalize3 = (v2) => v2.split(/[-_+]/)[0].split(".").map((x) => parseInt(x, 10) || 0);
7889
+ const pa2 = normalize3(a);
7890
+ const pb = normalize3(b2);
6126
7891
  for (let i = 0; i < Math.max(pa2.length, pb.length); i++) {
6127
7892
  const va2 = pa2[i] || 0;
6128
7893
  const vb = pb[i] || 0;
@@ -6166,17 +7931,17 @@ async function findFreePort(ports) {
6166
7931
  throw new Error("No free port found");
6167
7932
  }
6168
7933
  function checkPortFree(port) {
6169
- return new Promise((resolve7) => {
7934
+ return new Promise((resolve10) => {
6170
7935
  const server = net.createServer();
6171
7936
  server.unref();
6172
- server.on("error", () => resolve7(false));
7937
+ server.on("error", () => resolve10(false));
6173
7938
  server.listen(port, "127.0.0.1", () => {
6174
- server.close(() => resolve7(true));
7939
+ server.close(() => resolve10(true));
6175
7940
  });
6176
7941
  });
6177
7942
  }
6178
7943
  async function isCdpActive(port) {
6179
- return new Promise((resolve7) => {
7944
+ return new Promise((resolve10) => {
6180
7945
  const req = require("http").get(`http://127.0.0.1:${port}/json/version`, {
6181
7946
  timeout: 2e3
6182
7947
  }, (res) => {
@@ -6185,16 +7950,16 @@ async function isCdpActive(port) {
6185
7950
  res.on("end", () => {
6186
7951
  try {
6187
7952
  const info = JSON.parse(data);
6188
- resolve7(!!info["WebKit-Version"] || !!info["Browser"]);
7953
+ resolve10(!!info["WebKit-Version"] || !!info["Browser"]);
6189
7954
  } catch {
6190
- resolve7(false);
7955
+ resolve10(false);
6191
7956
  }
6192
7957
  });
6193
7958
  });
6194
- req.on("error", () => resolve7(false));
7959
+ req.on("error", () => resolve10(false));
6195
7960
  req.on("timeout", () => {
6196
7961
  req.destroy();
6197
- resolve7(false);
7962
+ resolve10(false);
6198
7963
  });
6199
7964
  });
6200
7965
  }
@@ -6539,8 +8304,8 @@ function cleanOldFiles() {
6539
8304
  }
6540
8305
  function checkSize() {
6541
8306
  try {
6542
- const stat = fs6.statSync(currentFile);
6543
- if (stat.size > MAX_FILE_SIZE) {
8307
+ const stat4 = fs6.statSync(currentFile);
8308
+ if (stat4.size > MAX_FILE_SIZE) {
6544
8309
  const backup = currentFile.replace(".jsonl", ".1.jsonl");
6545
8310
  try {
6546
8311
  fs6.unlinkSync(backup);
@@ -16368,6 +18133,12 @@ __export(provider_cli_adapter_exports, {
16368
18133
  function stripAnsi(str) {
16369
18134
  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, " ");
16370
18135
  }
18136
+ function stripTerminalNoise(str) {
18137
+ 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, " ");
18138
+ }
18139
+ function sanitizeTerminalText(str) {
18140
+ return stripTerminalNoise(stripAnsi(str));
18141
+ }
16371
18142
  function findBinary(name) {
16372
18143
  const isWin = os12.platform() === "win32";
16373
18144
  try {
@@ -16523,9 +18294,9 @@ var init_provider_cli_adapter = __esm({
16523
18294
  const platformArch = `${os12.platform()}-${os12.arch()}`;
16524
18295
  const helper = path9.join(ptyDir, "prebuilds", platformArch, "spawn-helper");
16525
18296
  if (fs13.existsSync(helper)) {
16526
- const stat = fs13.statSync(helper);
16527
- if (!(stat.mode & 73)) {
16528
- fs13.chmodSync(helper, stat.mode | 493);
18297
+ const stat4 = fs13.statSync(helper);
18298
+ if (!(stat4.mode & 73)) {
18299
+ fs13.chmodSync(helper, stat4.mode | 493);
16529
18300
  LOG.info("CLI", "[node-pty] Fixed spawn-helper permissions");
16530
18301
  }
16531
18302
  }
@@ -16588,6 +18359,8 @@ var init_provider_cli_adapter = __esm({
16588
18359
  spawnAt = 0;
16589
18360
  // PTY I/O
16590
18361
  onPtyDataCallback = null;
18362
+ pendingOutputParseBuffer = "";
18363
+ pendingOutputParseTimer = null;
16591
18364
  ptyOutputBuffer = "";
16592
18365
  ptyOutputFlushTimer = null;
16593
18366
  // Server log forwarding
@@ -16598,6 +18371,9 @@ var init_provider_cli_adapter = __esm({
16598
18371
  // Approval state machine
16599
18372
  approvalTransitionBuffer = "";
16600
18373
  approvalExitTimeout = null;
18374
+ pendingScriptStatus = null;
18375
+ pendingScriptStatusSince = 0;
18376
+ pendingScriptStatusTimer = null;
16601
18377
  // Output settle debounce — fires after PTY output goes quiet
16602
18378
  settleTimer = null;
16603
18379
  settledBuffer = "";
@@ -16663,6 +18439,7 @@ var init_provider_cli_adapter = __esm({
16663
18439
  sendDelayMs;
16664
18440
  sendKey;
16665
18441
  submitStrategy;
18442
+ static SCRIPT_STATUS_DEBOUNCE_MS = 1e3;
16666
18443
  /** Inject CLI scripts after construction (e.g. when resolved by ProviderLoader) */
16667
18444
  setCliScripts(scripts) {
16668
18445
  this.cliScripts = scripts;
@@ -16683,6 +18460,16 @@ var init_provider_cli_adapter = __esm({
16683
18460
  setOnPtyData(callback) {
16684
18461
  this.onPtyDataCallback = callback;
16685
18462
  }
18463
+ flushPendingOutputParse() {
18464
+ if (this.pendingOutputParseTimer) {
18465
+ clearTimeout(this.pendingOutputParseTimer);
18466
+ this.pendingOutputParseTimer = null;
18467
+ }
18468
+ if (!this.pendingOutputParseBuffer) return;
18469
+ const rawData = this.pendingOutputParseBuffer;
18470
+ this.pendingOutputParseBuffer = "";
18471
+ this.handleOutput(rawData);
18472
+ }
16686
18473
  async spawn() {
16687
18474
  if (this.ptyProcess) return;
16688
18475
  if (!pty) throw new Error("node-pty is not installed");
@@ -16731,7 +18518,17 @@ var init_provider_cli_adapter = __esm({
16731
18518
  }
16732
18519
  }
16733
18520
  this.ptyProcess.onData((data) => {
16734
- this.handleOutput(data);
18521
+ if (Date.now() < this.resizeSuppressUntil) return;
18522
+ if (data.includes("\x1B[6n") || data.includes("\x1B[?6n")) {
18523
+ this.ptyProcess?.write("\x1B[1;1R");
18524
+ }
18525
+ this.pendingOutputParseBuffer += data;
18526
+ if (!this.pendingOutputParseTimer) {
18527
+ this.pendingOutputParseTimer = setTimeout(() => {
18528
+ this.pendingOutputParseTimer = null;
18529
+ this.flushPendingOutputParse();
18530
+ }, this.timeouts.ptyFlush);
18531
+ }
16735
18532
  if (this.onPtyDataCallback) {
16736
18533
  this.ptyOutputBuffer += data;
16737
18534
  if (!this.ptyOutputFlushTimer) {
@@ -16747,6 +18544,7 @@ var init_provider_cli_adapter = __esm({
16747
18544
  });
16748
18545
  this.ptyProcess.onExit(({ exitCode }) => {
16749
18546
  LOG.info("CLI", `[${this.cliType}] Exit code ${exitCode}`);
18547
+ this.flushPendingOutputParse();
16750
18548
  this.ptyProcess = null;
16751
18549
  this.setStatus("stopped", "pty_exit");
16752
18550
  this.ready = false;
@@ -16766,13 +18564,9 @@ var init_provider_cli_adapter = __esm({
16766
18564
  }
16767
18565
  // ─── Output Handling ────────────────────────────
16768
18566
  handleOutput(rawData) {
16769
- if (Date.now() < this.resizeSuppressUntil) return;
16770
- if (rawData.includes("\x1B[6n") || rawData.includes("\x1B[?6n")) {
16771
- this.ptyProcess?.write("\x1B[1;1R");
16772
- }
16773
18567
  this.terminalScreen.write(rawData);
16774
18568
  this.terminalHistory = mergeTerminalHistory(this.terminalHistory, this.terminalScreen.getText());
16775
- const cleanData = stripAnsi(rawData);
18569
+ const cleanData = sanitizeTerminalText(rawData);
16776
18570
  if (this.isWaitingForResponse && cleanData) {
16777
18571
  this.responseBuffer = (this.responseBuffer + cleanData).slice(-8e3);
16778
18572
  }
@@ -16869,24 +18663,39 @@ var init_provider_cli_adapter = __esm({
16869
18663
  const scriptStatus = rawScriptStatus;
16870
18664
  if (!scriptStatus) return;
16871
18665
  const prevStatus = this.currentStatus;
16872
- if (scriptStatus === "waiting_approval") {
16873
- const modalMessage = modal?.message || "";
16874
- const screenText = this.terminalScreen.getText() || this.accumulatedBuffer;
16875
- const autoAcceptPatterns = [
16876
- /be able to read, edit, and execute/i,
16877
- /Security guide/i,
16878
- /Enter to confirm/i,
16879
- /Quick safety check/i,
16880
- /Do you trust the files/i,
16881
- /Is this a project/i
16882
- ];
16883
- if (autoAcceptPatterns.some((p) => p.test(modalMessage) || p.test(screenText))) {
16884
- LOG.info("CLI", `[${this.cliType}] Auto-accepting startup dialog: ${modalMessage.slice(0, 80)}`);
16885
- setTimeout(() => this.ptyProcess?.write("\r"), 200);
16886
- this.lastApprovalResolvedAt = Date.now();
16887
- this.activeModal = null;
18666
+ const clearPendingScriptStatus = () => {
18667
+ this.pendingScriptStatus = null;
18668
+ this.pendingScriptStatusSince = 0;
18669
+ if (this.pendingScriptStatusTimer) {
18670
+ clearTimeout(this.pendingScriptStatusTimer);
18671
+ this.pendingScriptStatusTimer = null;
18672
+ }
18673
+ };
18674
+ const armPendingScriptStatus = (delayMs) => {
18675
+ if (this.pendingScriptStatusTimer) clearTimeout(this.pendingScriptStatusTimer);
18676
+ this.pendingScriptStatusTimer = setTimeout(() => {
18677
+ this.pendingScriptStatusTimer = null;
18678
+ this.settledBuffer = this.recentOutputBuffer;
18679
+ this.evaluateSettled();
18680
+ }, delayMs);
18681
+ };
18682
+ const shouldDebouncePromotion = (status) => prevStatus === "idle" && !this.isWaitingForResponse && !this.currentTurnScope && (status === "generating" || status === "waiting_approval");
18683
+ if (shouldDebouncePromotion(scriptStatus)) {
18684
+ if (this.pendingScriptStatus !== scriptStatus) {
18685
+ this.pendingScriptStatus = scriptStatus;
18686
+ this.pendingScriptStatusSince = now;
18687
+ armPendingScriptStatus(_ProviderCliAdapter.SCRIPT_STATUS_DEBOUNCE_MS);
16888
18688
  return;
16889
18689
  }
18690
+ const elapsed = now - this.pendingScriptStatusSince;
18691
+ if (elapsed < _ProviderCliAdapter.SCRIPT_STATUS_DEBOUNCE_MS) {
18692
+ armPendingScriptStatus(_ProviderCliAdapter.SCRIPT_STATUS_DEBOUNCE_MS - elapsed);
18693
+ return;
18694
+ }
18695
+ } else {
18696
+ clearPendingScriptStatus();
18697
+ }
18698
+ if (scriptStatus === "waiting_approval") {
16890
18699
  const inCooldown = this.lastApprovalResolvedAt && Date.now() - this.lastApprovalResolvedAt < this.timeouts.approvalCooldown;
16891
18700
  if (!inCooldown) {
16892
18701
  this.isWaitingForResponse = true;
@@ -16899,6 +18708,12 @@ var init_provider_cli_adapter = __esm({
16899
18708
  }
16900
18709
  }
16901
18710
  if (scriptStatus === "generating") {
18711
+ const screenText = this.terminalScreen.getText() || this.accumulatedBuffer;
18712
+ const noActiveTurn = !this.currentTurnScope;
18713
+ 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));
18714
+ if (prevStatus === "idle" && !this.isWaitingForResponse && noActiveTurn && !modal && looksIdleChrome) {
18715
+ return;
18716
+ }
16902
18717
  if (prevStatus === "waiting_approval") {
16903
18718
  if (this.approvalExitTimeout) {
16904
18719
  clearTimeout(this.approvalExitTimeout);
@@ -17120,7 +18935,7 @@ ${data.message || ""}`.trim();
17120
18935
  if (this.startupParseGate) {
17121
18936
  const deadline = Date.now() + 1e4;
17122
18937
  while (this.startupParseGate && Date.now() < deadline) {
17123
- await new Promise((resolve7) => setTimeout(resolve7, 50));
18938
+ await new Promise((resolve10) => setTimeout(resolve10, 50));
17124
18939
  }
17125
18940
  }
17126
18941
  if (!this.ready) throw new Error(`${this.cliName} not ready (status: ${this.currentStatus})`);
@@ -17257,6 +19072,16 @@ ${data.message || ""}`.trim();
17257
19072
  clearTimeout(this.submitRetryTimer);
17258
19073
  this.submitRetryTimer = null;
17259
19074
  }
19075
+ if (this.pendingOutputParseTimer) {
19076
+ clearTimeout(this.pendingOutputParseTimer);
19077
+ this.pendingOutputParseTimer = null;
19078
+ }
19079
+ this.pendingOutputParseBuffer = "";
19080
+ if (this.ptyOutputFlushTimer) {
19081
+ clearTimeout(this.ptyOutputFlushTimer);
19082
+ this.ptyOutputFlushTimer = null;
19083
+ }
19084
+ this.ptyOutputBuffer = "";
17260
19085
  if (this.ptyProcess) {
17261
19086
  this.ptyProcess.write("");
17262
19087
  setTimeout(() => {
@@ -17282,6 +19107,16 @@ ${data.message || ""}`.trim();
17282
19107
  this.currentTurnScope = null;
17283
19108
  this.submitRetryUsed = false;
17284
19109
  this.submitRetryPromptSnippet = "";
19110
+ if (this.pendingOutputParseTimer) {
19111
+ clearTimeout(this.pendingOutputParseTimer);
19112
+ this.pendingOutputParseTimer = null;
19113
+ }
19114
+ this.pendingOutputParseBuffer = "";
19115
+ if (this.ptyOutputFlushTimer) {
19116
+ clearTimeout(this.ptyOutputFlushTimer);
19117
+ this.ptyOutputFlushTimer = null;
19118
+ }
19119
+ this.ptyOutputBuffer = "";
17285
19120
  this.terminalScreen.reset();
17286
19121
  this.onStatusChange?.();
17287
19122
  }
@@ -17336,7 +19171,7 @@ ${data.message || ""}`.trim();
17336
19171
  committedMessages: this.committedMessages.slice(-20),
17337
19172
  structuredMessages: this.structuredMessages.slice(-20),
17338
19173
  messageCount: this.committedMessages.length,
17339
- screenText: this.terminalScreen.getText().slice(-4e3),
19174
+ screenText: sanitizeTerminalText(this.terminalScreen.getText()).slice(-4e3),
17340
19175
  terminalHistory: this.terminalHistory.slice(-8e3),
17341
19176
  currentTurnScope: this.currentTurnScope,
17342
19177
  startupBuffer: this.startupBuffer.slice(-4e3),
@@ -17345,6 +19180,7 @@ ${data.message || ""}`.trim();
17345
19180
  accumulatedBufferLength: this.accumulatedBuffer.length,
17346
19181
  accumulatedRawBufferLength: this.accumulatedRawBuffer.length,
17347
19182
  rawBufferPreview: this.accumulatedRawBuffer.slice(-1e3),
19183
+ sanitizedRawPreview: sanitizeTerminalText(this.accumulatedRawBuffer).slice(-1e3),
17348
19184
  responseBuffer: this.responseBuffer.slice(-1e3),
17349
19185
  isWaitingForResponse: this.isWaitingForResponse,
17350
19186
  activeModal: this.activeModal,
@@ -17359,6 +19195,8 @@ ${data.message || ""}`.trim();
17359
19195
  scriptNames: Object.keys(this.cliScripts).filter((k) => typeof this.cliScripts[k] === "function"),
17360
19196
  statusHistory: this.statusHistory.slice(-30),
17361
19197
  timeouts: this.timeouts,
19198
+ pendingOutputParseBufferLength: this.pendingOutputParseBuffer.length,
19199
+ pendingOutputParseScheduled: !!this.pendingOutputParseTimer,
17362
19200
  ptyAlive: !!this.ptyProcess
17363
19201
  };
17364
19202
  }
@@ -17426,19 +19264,6 @@ var init_cli_provider_instance = __esm({
17426
19264
  getState() {
17427
19265
  const adapterStatus = this.adapter.getStatus();
17428
19266
  const dirName = this.workingDir.split("/").filter(Boolean).pop() || "session";
17429
- const recentMessages = adapterStatus.messages.slice(-50).map((m) => {
17430
- const content = typeof m.content === "string" && m.content.length > 8e3 ? m.content.slice(0, 8e3) + "\n... (truncated)" : m.content;
17431
- return { ...m, content };
17432
- });
17433
- if (recentMessages.length > 0) {
17434
- const dirName2 = this.workingDir.split("/").filter(Boolean).pop() || "session";
17435
- this.historyWriter.appendNewMessages(
17436
- this.type,
17437
- recentMessages,
17438
- `${this.provider.name} \xB7 ${dirName2}`,
17439
- this.instanceId
17440
- );
17441
- }
17442
19267
  if (adapterStatus.terminalHistory?.trim()) {
17443
19268
  this.historyWriter.appendTerminalHistory(
17444
19269
  this.type,
@@ -17452,12 +19277,12 @@ var init_cli_provider_instance = __esm({
17452
19277
  name: this.provider.name,
17453
19278
  category: "cli",
17454
19279
  status: adapterStatus.status,
17455
- mode: this.settings.mode || "terminal",
19280
+ mode: "terminal",
17456
19281
  activeChat: {
17457
19282
  id: `${this.type}_${this.workingDir}`,
17458
19283
  title: `${this.provider.name} \xB7 ${dirName}`,
17459
19284
  status: adapterStatus.status,
17460
- messages: recentMessages,
19285
+ messages: [],
17461
19286
  activeModal: adapterStatus.activeModal,
17462
19287
  terminalHistory: adapterStatus.terminalHistory,
17463
19288
  inputContent: ""
@@ -17471,11 +19296,15 @@ var init_cli_provider_instance = __esm({
17471
19296
  }
17472
19297
  onEvent(event, data) {
17473
19298
  if (event === "send_message" && data?.text) {
17474
- this.adapter.sendMessage(data.text);
19299
+ void this.adapter.sendMessage(data.text).catch((e) => {
19300
+ LOG.warn("CLI", `[${this.type}] send_message failed: ${e?.message || e}`);
19301
+ });
17475
19302
  } else if (event === "server_connected" && data?.serverConn) {
17476
19303
  this.adapter.setServerConn(data.serverConn);
17477
19304
  } else if (event === "resolve_action" && data) {
17478
- this.adapter.resolveAction(data);
19305
+ void this.adapter.resolveAction(data).catch((e) => {
19306
+ LOG.warn("CLI", `[${this.type}] resolve_action failed: ${e?.message || e}`);
19307
+ });
17479
19308
  }
17480
19309
  }
17481
19310
  dispose() {
@@ -33663,8 +35492,8 @@ var init_acp = __esm({
33663
35492
  this.#requestHandler = requestHandler;
33664
35493
  this.#notificationHandler = notificationHandler;
33665
35494
  this.#stream = stream;
33666
- this.#closedPromise = new Promise((resolve7) => {
33667
- this.#abortController.signal.addEventListener("abort", () => resolve7());
35495
+ this.#closedPromise = new Promise((resolve10) => {
35496
+ this.#abortController.signal.addEventListener("abort", () => resolve10());
33668
35497
  });
33669
35498
  this.#receive();
33670
35499
  }
@@ -33813,8 +35642,8 @@ var init_acp = __esm({
33813
35642
  }
33814
35643
  async sendRequest(method, params) {
33815
35644
  const id = this.#nextRequestId++;
33816
- const responsePromise = new Promise((resolve7, reject) => {
33817
- this.#pendingResponses.set(id, { resolve: resolve7, reject });
35645
+ const responsePromise = new Promise((resolve10, reject) => {
35646
+ this.#pendingResponses.set(id, { resolve: resolve10, reject });
33818
35647
  });
33819
35648
  await this.#sendMessage({ jsonrpc: "2.0", id, method, params });
33820
35649
  return responsePromise;
@@ -34346,13 +36175,13 @@ var init_acp_provider_instance = __esm({
34346
36175
  }
34347
36176
  this.currentStatus = "waiting_approval";
34348
36177
  this.detectStatusTransition();
34349
- const approved = await new Promise((resolve7) => {
34350
- this.permissionResolvers.push(resolve7);
36178
+ const approved = await new Promise((resolve10) => {
36179
+ this.permissionResolvers.push(resolve10);
34351
36180
  setTimeout(() => {
34352
- const idx = this.permissionResolvers.indexOf(resolve7);
36181
+ const idx = this.permissionResolvers.indexOf(resolve10);
34353
36182
  if (idx >= 0) {
34354
36183
  this.permissionResolvers.splice(idx, 1);
34355
- resolve7(false);
36184
+ resolve10(false);
34356
36185
  }
34357
36186
  }, 3e5);
34358
36187
  });
@@ -35916,18 +37745,18 @@ function findBinary2(name) {
35916
37745
  const result = runCommand(cmd, 5e3);
35917
37746
  return result ? result.split("\n")[0] : null;
35918
37747
  }
35919
- function parseVersion(raw) {
37748
+ function parseVersion2(raw) {
35920
37749
  const match = raw.match(/v?(\d+\.\d+(?:\.\d+)?(?:-[a-zA-Z0-9.]+)?)/);
35921
37750
  return match ? match[1] : raw.split("\n")[0].substring(0, 100);
35922
37751
  }
35923
37752
  function getVersion(binary, versionCommand) {
35924
37753
  if (versionCommand) {
35925
37754
  const raw = runCommand(versionCommand);
35926
- return raw ? parseVersion(raw) : null;
37755
+ return raw ? parseVersion2(raw) : null;
35927
37756
  }
35928
37757
  for (const flag of ["--version", "-V", "-v"]) {
35929
37758
  const raw = runCommand(`"${binary}" ${flag}`);
35930
- if (raw && raw.length < 500) return parseVersion(raw);
37759
+ if (raw && raw.length < 500) return parseVersion2(raw);
35931
37760
  }
35932
37761
  return null;
35933
37762
  }
@@ -36544,15 +38373,15 @@ var init_dev_server = __esm({
36544
38373
  this.json(res, 500, { error: e.message });
36545
38374
  }
36546
38375
  });
36547
- return new Promise((resolve7, reject) => {
38376
+ return new Promise((resolve10, reject) => {
36548
38377
  this.server.listen(port, "127.0.0.1", () => {
36549
38378
  this.log(`Dev server listening on http://127.0.0.1:${port}`);
36550
- resolve7();
38379
+ resolve10();
36551
38380
  });
36552
38381
  this.server.on("error", (e) => {
36553
38382
  if (e.code === "EADDRINUSE") {
36554
38383
  this.log(`Port ${port} in use, skipping dev server`);
36555
- resolve7();
38384
+ resolve10();
36556
38385
  } else {
36557
38386
  reject(e);
36558
38387
  }
@@ -36635,20 +38464,20 @@ var init_dev_server = __esm({
36635
38464
  child.stderr?.on("data", (d) => {
36636
38465
  stderr += d.toString().slice(0, 2e3);
36637
38466
  });
36638
- await new Promise((resolve7) => {
38467
+ await new Promise((resolve10) => {
36639
38468
  const timer = setTimeout(() => {
36640
38469
  child.kill();
36641
- resolve7();
38470
+ resolve10();
36642
38471
  }, 3e3);
36643
38472
  child.on("exit", () => {
36644
38473
  clearTimeout(timer);
36645
- resolve7();
38474
+ resolve10();
36646
38475
  });
36647
38476
  child.stdout?.once("data", () => {
36648
38477
  setTimeout(() => {
36649
38478
  child.kill();
36650
38479
  clearTimeout(timer);
36651
- resolve7();
38480
+ resolve10();
36652
38481
  }, 500);
36653
38482
  });
36654
38483
  });
@@ -37075,8 +38904,8 @@ var init_dev_server = __esm({
37075
38904
  files.push({ path: rel, size: 0, type: "dir" });
37076
38905
  scan(path12.join(d, entry.name), rel);
37077
38906
  } else {
37078
- const stat = fs10.statSync(path12.join(d, entry.name));
37079
- files.push({ path: rel, size: stat.size, type: "file" });
38907
+ const stat4 = fs10.statSync(path12.join(d, entry.name));
38908
+ files.push({ path: rel, size: stat4.size, type: "file" });
37080
38909
  }
37081
38910
  }
37082
38911
  } catch {
@@ -37392,14 +39221,14 @@ var init_dev_server = __esm({
37392
39221
  child.stderr?.on("data", (d) => {
37393
39222
  stderr += d.toString();
37394
39223
  });
37395
- await new Promise((resolve7) => {
39224
+ await new Promise((resolve10) => {
37396
39225
  const timer = setTimeout(() => {
37397
39226
  child.kill();
37398
- resolve7();
39227
+ resolve10();
37399
39228
  }, timeout);
37400
39229
  child.on("exit", () => {
37401
39230
  clearTimeout(timer);
37402
- resolve7();
39231
+ resolve10();
37403
39232
  });
37404
39233
  });
37405
39234
  const elapsed = Date.now() - start;
@@ -38243,25 +40072,66 @@ var init_dev_server = __esm({
38243
40072
  const ref = this.providerLoader.resolve(desired) || this.providerLoader.getMeta(desired);
38244
40073
  if (ref?.category === category) return desired;
38245
40074
  const all = this.providerLoader.getAll();
38246
- const fallback = all.find((p) => p.category === category && p.type !== targetType);
40075
+ 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];
38247
40076
  return fallback?.type || null;
38248
40077
  }
38249
- loadAutoImplReferenceScripts(category, referenceType) {
38250
- if (!referenceType) return {};
38251
- const refDir = this.providerLoader.getUpstreamProviderDir(category, referenceType);
38252
- if (!fs10.existsSync(refDir)) return {};
38253
- const referenceScripts = {};
38254
- const scriptsDir = path12.join(refDir, "scripts");
38255
- if (!fs10.existsSync(scriptsDir)) return referenceScripts;
40078
+ getLatestScriptVersionDir(scriptsDir) {
40079
+ if (!fs10.existsSync(scriptsDir)) return null;
38256
40080
  const versions = fs10.readdirSync(scriptsDir).filter((d) => {
38257
40081
  try {
38258
40082
  return fs10.statSync(path12.join(scriptsDir, d)).isDirectory();
38259
40083
  } catch {
38260
40084
  return false;
38261
40085
  }
38262
- }).sort().reverse();
38263
- if (versions.length === 0) return referenceScripts;
38264
- const latestDir = path12.join(scriptsDir, versions[0]);
40086
+ }).sort((a, b2) => b2.localeCompare(a, void 0, { numeric: true, sensitivity: "base" }));
40087
+ if (versions.length === 0) return null;
40088
+ return path12.join(scriptsDir, versions[0]);
40089
+ }
40090
+ resolveAutoImplWritableProviderDir(category, type, requestedDir) {
40091
+ const canonicalUserDir = path12.resolve(this.providerLoader.getUserProviderDir(category, type));
40092
+ const desiredDir = requestedDir ? path12.resolve(requestedDir) : canonicalUserDir;
40093
+ const upstreamRoot = path12.resolve(this.providerLoader.getUpstreamDir());
40094
+ if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path12.sep}`)) {
40095
+ return { dir: null, reason: `Refusing to write into upstream provider directory: ${desiredDir}` };
40096
+ }
40097
+ if (path12.basename(desiredDir) !== type) {
40098
+ return { dir: null, reason: `Requested writable provider directory must end with '${type}': ${desiredDir}` };
40099
+ }
40100
+ const sourceDir = this.findProviderDir(type);
40101
+ if (!sourceDir) {
40102
+ return { dir: null, reason: `Provider source directory not found for '${type}'` };
40103
+ }
40104
+ if (!fs10.existsSync(desiredDir)) {
40105
+ fs10.mkdirSync(path12.dirname(desiredDir), { recursive: true });
40106
+ fs10.cpSync(sourceDir, desiredDir, { recursive: true });
40107
+ this.log(`Auto-implement writable copy created: ${desiredDir}`);
40108
+ }
40109
+ const providerJson = path12.join(desiredDir, "provider.json");
40110
+ if (!fs10.existsSync(providerJson)) {
40111
+ return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
40112
+ }
40113
+ try {
40114
+ const providerData = JSON.parse(fs10.readFileSync(providerJson, "utf-8"));
40115
+ if (providerData.disableUpstream !== true) {
40116
+ providerData.disableUpstream = true;
40117
+ fs10.writeFileSync(providerJson, JSON.stringify(providerData, null, 2));
40118
+ }
40119
+ } catch (error48) {
40120
+ return {
40121
+ dir: null,
40122
+ reason: `Failed to update provider.json in writable provider directory: ${error48.message}`
40123
+ };
40124
+ }
40125
+ return { dir: desiredDir };
40126
+ }
40127
+ loadAutoImplReferenceScripts(referenceType) {
40128
+ if (!referenceType) return {};
40129
+ const refDir = this.findProviderDir(referenceType);
40130
+ if (!refDir || !fs10.existsSync(refDir)) return {};
40131
+ const referenceScripts = {};
40132
+ const scriptsDir = path12.join(refDir, "scripts");
40133
+ const latestDir = this.getLatestScriptVersionDir(scriptsDir);
40134
+ if (!latestDir) return referenceScripts;
38265
40135
  for (const file2 of fs10.readdirSync(latestDir)) {
38266
40136
  if (!file2.endsWith(".js")) continue;
38267
40137
  try {
@@ -38273,7 +40143,7 @@ var init_dev_server = __esm({
38273
40143
  }
38274
40144
  async handleAutoImplement(type, req, res) {
38275
40145
  const body = await this.readBody(req);
38276
- const { agent = "claude-cli", functions, reference = "antigravity", model, comment } = body;
40146
+ const { agent = "claude-cli", functions, reference, model, comment, providerDir: requestedProviderDir } = body;
38277
40147
  if (!functions || !Array.isArray(functions) || functions.length === 0) {
38278
40148
  this.json(res, 400, { error: 'functions[] is required (e.g. ["readChat", "sendMessage"])' });
38279
40149
  return;
@@ -38287,11 +40157,14 @@ var init_dev_server = __esm({
38287
40157
  this.json(res, 404, { error: `Provider not found: ${type}` });
38288
40158
  return;
38289
40159
  }
38290
- const providerDir = this.findProviderDir(type);
38291
- if (!providerDir) {
38292
- this.json(res, 404, { error: `Provider directory not found: ${type}` });
40160
+ const writableProvider = this.resolveAutoImplWritableProviderDir(provider.category, type, requestedProviderDir);
40161
+ if (!writableProvider.dir) {
40162
+ this.json(res, 409, {
40163
+ error: writableProvider.reason || `Auto-implement only writes to the canonical user provider directory for '${type}'.`
40164
+ });
38293
40165
  return;
38294
40166
  }
40167
+ const providerDir = writableProvider.dir;
38295
40168
  try {
38296
40169
  const resolvedReference = this.resolveAutoImplReference(provider.category, reference, type);
38297
40170
  this.sendAutoImplSSE({
@@ -38311,7 +40184,7 @@ var init_dev_server = __esm({
38311
40184
  message: `Loading reference script (${resolvedReference || "none"})...`
38312
40185
  }
38313
40186
  });
38314
- const referenceScripts = this.loadAutoImplReferenceScripts(provider.category, resolvedReference);
40187
+ const referenceScripts = this.loadAutoImplReferenceScripts(resolvedReference);
38315
40188
  const prompt = this.buildAutoImplPrompt(type, provider, providerDir, functions, domContext, referenceScripts, comment, resolvedReference);
38316
40189
  const tmpDir = path12.join(os15.tmpdir(), "adhdev-autoimpl");
38317
40190
  if (!fs10.existsSync(tmpDir)) fs10.mkdirSync(tmpDir, { recursive: true });
@@ -38333,7 +40206,7 @@ var init_dev_server = __esm({
38333
40206
  this.sendAutoImplSSE({ event: "progress", data: { function: "_init", status: "spawning", message: `Spawning ACP agent: ${spawn3.command} ${(spawn3.args || []).join(" ")}` } });
38334
40207
  this.autoImplStatus = { running: true, type, progress: [] };
38335
40208
  const { ClientSideConnection: ClientSideConnection2, ndJsonStream: ndJsonStream2, PROTOCOL_VERSION: PROTOCOL_VERSION2 } = await Promise.resolve().then(() => (init_acp(), acp_exports));
38336
- const { Readable: Readable2, Writable: Writable2 } = await import("stream");
40209
+ const { Readable: Readable3, Writable: Writable2 } = await import("stream");
38337
40210
  const { spawn: spawnFn2 } = await import("child_process");
38338
40211
  const acpArgs = [...spawn3.args || []];
38339
40212
  if (model) {
@@ -38352,7 +40225,7 @@ var init_dev_server = __esm({
38352
40225
  this.sendAutoImplSSE({ event: "output", data: { chunk, stream: "stderr" } });
38353
40226
  });
38354
40227
  const webStdin = Writable2.toWeb(child2.stdin);
38355
- const webStdout = Readable2.toWeb(child2.stdout);
40228
+ const webStdout = Readable3.toWeb(child2.stdout);
38356
40229
  const stream = ndJsonStream2(webStdin, webStdout);
38357
40230
  const connection = new ClientSideConnection2((_agent) => ({
38358
40231
  // Auto-approve all tool calls for auto-implement
@@ -38667,29 +40540,20 @@ var init_dev_server = __esm({
38667
40540
  lines.push("These are the files you need to EDIT. They contain TODO stubs \u2014 replace them with working implementations.");
38668
40541
  lines.push("");
38669
40542
  const scriptsDir = path12.join(providerDir, "scripts");
38670
- if (fs10.existsSync(scriptsDir)) {
38671
- const versions = fs10.readdirSync(scriptsDir).filter((d) => {
38672
- try {
38673
- return fs10.statSync(path12.join(scriptsDir, d)).isDirectory();
38674
- } catch {
38675
- return false;
38676
- }
38677
- }).sort().reverse();
38678
- if (versions.length > 0) {
38679
- const vDir = path12.join(scriptsDir, versions[0]);
38680
- lines.push(`Scripts version directory: \`${vDir}\``);
38681
- lines.push("");
38682
- for (const file2 of fs10.readdirSync(vDir)) {
38683
- if (file2.endsWith(".js")) {
38684
- try {
38685
- const content = fs10.readFileSync(path12.join(vDir, file2), "utf-8");
38686
- lines.push(`### \`${file2}\``);
38687
- lines.push("```javascript");
38688
- lines.push(content);
38689
- lines.push("```");
38690
- lines.push("");
38691
- } catch {
38692
- }
40543
+ const latestScriptsDir = this.getLatestScriptVersionDir(scriptsDir);
40544
+ if (latestScriptsDir) {
40545
+ lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
40546
+ lines.push("");
40547
+ for (const file2 of fs10.readdirSync(latestScriptsDir)) {
40548
+ if (file2.endsWith(".js")) {
40549
+ try {
40550
+ const content = fs10.readFileSync(path12.join(latestScriptsDir, file2), "utf-8");
40551
+ lines.push(`### \`${file2}\``);
40552
+ lines.push("```javascript");
40553
+ lines.push(content);
40554
+ lines.push("```");
40555
+ lines.push("");
40556
+ } catch {
38693
40557
  }
38694
40558
  }
38695
40559
  }
@@ -38770,7 +40634,7 @@ var init_dev_server = __esm({
38770
40634
  lines.push("## Rules");
38771
40635
  lines.push("1. **Scripts WITHOUT params** \u2192 IIFE: `(() => { ... })()`");
38772
40636
  lines.push("2. **Scripts WITH params** \u2192 arrow: `(params) => { ... }` \u2014 router calls `(${script})(${JSON.stringify(params)})`");
38773
- lines.push("3. Use CSS selectors from the DOM analysis above");
40637
+ lines.push("3. If live DOM analysis is included above, use it. Otherwise, discover selectors yourself via CDP before coding.");
38774
40638
  lines.push("4. Always wrap in try-catch, return `JSON.stringify(result)`");
38775
40639
  lines.push("5. Do NOT modify `scripts.js` router \u2014 only edit individual `*.js` files");
38776
40640
  lines.push("6. All scripts run in the browser (CDP evaluate) \u2014 use DOM APIs only");
@@ -38819,8 +40683,12 @@ var init_dev_server = __esm({
38819
40683
  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.");
38820
40684
  lines.push(" - `switchSession`: Prove your switch was successful by subsequently calling `readChat` and explicitly checking that the chat context has actually changed.");
38821
40685
  lines.push("");
38822
- lines.push("## YOU MUST EXPLORE THE DOM YOURSELF!");
38823
- lines.push("I have NOT provided you with the DOM snapshot. You MUST use your command-line tools to discover the IDE structure dynamically!");
40686
+ lines.push("## DOM Exploration");
40687
+ if (domContext) {
40688
+ lines.push("A lightweight DOM snapshot is included above, but you MUST still verify selectors yourself before finalizing the scripts.");
40689
+ } else {
40690
+ lines.push("No DOM snapshot is included here. You MUST use your command-line tools to discover the IDE structure dynamically.");
40691
+ }
38824
40692
  lines.push("");
38825
40693
  lines.push("### 1. Evaluate JS to explore IDE DOM");
38826
40694
  lines.push("Use cURL to run JavaScript inside the IDE:");
@@ -38907,29 +40775,20 @@ var init_dev_server = __esm({
38907
40775
  lines.push("These are the files you need to edit. Replace TODO or heuristic-only logic with working PTY-aware implementations.");
38908
40776
  lines.push("");
38909
40777
  const scriptsDir = path12.join(providerDir, "scripts");
38910
- if (fs10.existsSync(scriptsDir)) {
38911
- const versions = fs10.readdirSync(scriptsDir).filter((d) => {
40778
+ const latestScriptsDir = this.getLatestScriptVersionDir(scriptsDir);
40779
+ if (latestScriptsDir) {
40780
+ lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
40781
+ lines.push("");
40782
+ for (const file2 of fs10.readdirSync(latestScriptsDir)) {
40783
+ if (!file2.endsWith(".js")) continue;
38912
40784
  try {
38913
- return fs10.statSync(path12.join(scriptsDir, d)).isDirectory();
40785
+ const content = fs10.readFileSync(path12.join(latestScriptsDir, file2), "utf-8");
40786
+ lines.push(`### \`${file2}\``);
40787
+ lines.push("```javascript");
40788
+ lines.push(content);
40789
+ lines.push("```");
40790
+ lines.push("");
38914
40791
  } catch {
38915
- return false;
38916
- }
38917
- }).sort().reverse();
38918
- if (versions.length > 0) {
38919
- const vDir = path12.join(scriptsDir, versions[0]);
38920
- lines.push(`Scripts version directory: \`${vDir}\``);
38921
- lines.push("");
38922
- for (const file2 of fs10.readdirSync(vDir)) {
38923
- if (!file2.endsWith(".js")) continue;
38924
- try {
38925
- const content = fs10.readFileSync(path12.join(vDir, file2), "utf-8");
38926
- lines.push(`### \`${file2}\``);
38927
- lines.push("```javascript");
38928
- lines.push(content);
38929
- lines.push("```");
38930
- lines.push("");
38931
- } catch {
38932
- }
38933
40792
  }
38934
40793
  }
38935
40794
  }
@@ -38998,6 +40857,9 @@ var init_dev_server = __esm({
38998
40857
  lines.push("8. Keep exports compatible with the existing `scripts.js` router (`module.exports = function ...`).");
38999
40858
  lines.push("9. Do not rewrite unrelated provider config. Only touch the scripts needed for this task unless a tiny supporting change is required.");
39000
40859
  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.");
40860
+ lines.push("11. Do NOT repeatedly dump the same target files. Read the target scripts once, reproduce the bug, then move directly to patching.");
40861
+ 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.");
40862
+ 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.");
39001
40863
  lines.push("");
39002
40864
  lines.push("## Task");
39003
40865
  lines.push(`Edit files in \`${providerDir}\` to implement: **${functions.join(", ")}**`);
@@ -39039,6 +40901,9 @@ var init_dev_server = __esm({
39039
40901
  lines.push("");
39040
40902
  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.");
39041
40903
  lines.push("");
40904
+ lines.push("### Patch Discipline");
40905
+ 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.");
40906
+ lines.push("");
39042
40907
  lines.push("### 5. Verify the side effects outside the CLI");
39043
40908
  lines.push("```bash");
39044
40909
  lines.push("test -f tmp/adhdev_provider_fix_test.py");
@@ -39143,14 +41008,14 @@ data: ${JSON.stringify(msg.data)}
39143
41008
  res.end(JSON.stringify(data, null, 2));
39144
41009
  }
39145
41010
  async readBody(req) {
39146
- return new Promise((resolve7) => {
41011
+ return new Promise((resolve10) => {
39147
41012
  let body = "";
39148
41013
  req.on("data", (chunk) => body += chunk);
39149
41014
  req.on("end", () => {
39150
41015
  try {
39151
- resolve7(JSON.parse(body));
41016
+ resolve10(JSON.parse(body));
39152
41017
  } catch {
39153
- resolve7({});
41018
+ resolve10({});
39154
41019
  }
39155
41020
  });
39156
41021
  });
@@ -39586,6 +41451,7 @@ var init_daemon_lifecycle = __esm({
39586
41451
  init_provider_loader();
39587
41452
  init_version_archive();
39588
41453
  init_provider_instance_manager();
41454
+ init_dev_server();
39589
41455
  init_ide_detector();
39590
41456
  init_logger();
39591
41457
  init_config();
@@ -40079,13 +41945,13 @@ ${e?.stack || ""}`);
40079
41945
  } catch {
40080
41946
  }
40081
41947
  const http3 = esmRequire("https");
40082
- const data = await new Promise((resolve7, reject) => {
41948
+ const data = await new Promise((resolve10, reject) => {
40083
41949
  const req = http3.get(`${serverUrl}/api/v1/turn/credentials`, {
40084
41950
  headers: { "Authorization": `Bearer ${token}` }
40085
41951
  }, (res) => {
40086
41952
  let d = "";
40087
41953
  res.on("data", (c) => d += c);
40088
- res.on("end", () => resolve7(d));
41954
+ res.on("end", () => resolve10(d));
40089
41955
  });
40090
41956
  req.on("error", reject);
40091
41957
  req.setTimeout(5e3, () => {
@@ -40941,7 +42807,7 @@ var init_adhdev_daemon = __esm({
40941
42807
  fs12 = __toESM(require("fs"));
40942
42808
  path14 = __toESM(require("path"));
40943
42809
  import_chalk2 = __toESM(require("chalk"));
40944
- pkgVersion = "0.6.72";
42810
+ pkgVersion = "0.6.76";
40945
42811
  if (pkgVersion === "unknown") {
40946
42812
  try {
40947
42813
  const possiblePaths = [
@@ -41166,7 +43032,7 @@ ${err?.stack || ""}`);
41166
43032
  this.running = true;
41167
43033
  process.on("SIGINT", () => this.stop());
41168
43034
  process.on("SIGTERM", () => this.stop());
41169
- if (options.dev) {
43035
+ if (options.dev && this.components) {
41170
43036
  const devServer = new DevServer({
41171
43037
  providerLoader: this.components.providerLoader,
41172
43038
  cdpManagers: this.components.cdpManagers,
@@ -41759,6 +43625,9 @@ async function installCliOnly() {
41759
43625
  });
41760
43626
  /*! Bundled license information:
41761
43627
 
43628
+ chokidar/index.js:
43629
+ (*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) *)
43630
+
41762
43631
  @xterm/xterm/lib/xterm.mjs:
41763
43632
  (**
41764
43633
  * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.