@probelabs/probe 0.6.0-rc154 → 0.6.0-rc161

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.
Files changed (49) hide show
  1. package/README.md +80 -1
  2. package/build/agent/FallbackManager.d.ts +176 -0
  3. package/build/agent/FallbackManager.js +545 -0
  4. package/build/agent/ProbeAgent.d.ts +9 -1
  5. package/build/agent/ProbeAgent.js +218 -10
  6. package/build/agent/RetryManager.d.ts +157 -0
  7. package/build/agent/RetryManager.js +334 -0
  8. package/build/agent/acp/server.js +1 -0
  9. package/build/agent/acp/tools.js +6 -2
  10. package/build/agent/index.js +1814 -355
  11. package/build/agent/probeTool.js +20 -2
  12. package/build/agent/tools.js +16 -0
  13. package/build/delegate.js +326 -201
  14. package/build/downloader.js +46 -17
  15. package/build/extractor.js +12 -12
  16. package/build/index.js +13 -0
  17. package/build/tools/common.js +5 -3
  18. package/build/tools/edit.js +409 -0
  19. package/build/tools/index.js +11 -0
  20. package/build/tools/vercel.js +55 -14
  21. package/build/utils.js +18 -9
  22. package/cjs/agent/ProbeAgent.cjs +2268 -699
  23. package/cjs/index.cjs +75902 -74348
  24. package/package.json +2 -2
  25. package/src/agent/FallbackManager.d.ts +176 -0
  26. package/src/agent/FallbackManager.js +545 -0
  27. package/src/agent/ProbeAgent.d.ts +9 -1
  28. package/src/agent/ProbeAgent.js +218 -10
  29. package/src/agent/RetryManager.d.ts +157 -0
  30. package/src/agent/RetryManager.js +334 -0
  31. package/src/agent/acp/server.js +1 -0
  32. package/src/agent/acp/tools.js +6 -2
  33. package/src/agent/index.js +8 -0
  34. package/src/agent/probeTool.js +20 -2
  35. package/src/agent/tools.js +16 -0
  36. package/src/delegate.js +326 -201
  37. package/src/downloader.js +46 -17
  38. package/src/extractor.js +12 -12
  39. package/src/index.js +13 -0
  40. package/src/tools/common.js +5 -3
  41. package/src/tools/edit.js +409 -0
  42. package/src/tools/index.js +11 -0
  43. package/src/tools/vercel.js +55 -14
  44. package/src/utils.js +18 -9
  45. package/bin/binaries/probe-v0.6.0-rc154-aarch64-apple-darwin.tar.gz +0 -0
  46. package/bin/binaries/probe-v0.6.0-rc154-aarch64-unknown-linux-gnu.tar.gz +0 -0
  47. package/bin/binaries/probe-v0.6.0-rc154-x86_64-apple-darwin.tar.gz +0 -0
  48. package/bin/binaries/probe-v0.6.0-rc154-x86_64-pc-windows-msvc.zip +0 -0
  49. package/bin/binaries/probe-v0.6.0-rc154-x86_64-unknown-linux-gnu.tar.gz +0 -0
@@ -104,7 +104,7 @@ var require_package = __commonJS({
104
104
  // node_modules/dotenv/lib/main.js
105
105
  var require_main = __commonJS({
106
106
  "node_modules/dotenv/lib/main.js"(exports2, module2) {
107
- var fs6 = require("fs");
107
+ var fs7 = require("fs");
108
108
  var path7 = require("path");
109
109
  var os3 = require("os");
110
110
  var crypto2 = require("crypto");
@@ -213,7 +213,7 @@ var require_main = __commonJS({
213
213
  if (options && options.path && options.path.length > 0) {
214
214
  if (Array.isArray(options.path)) {
215
215
  for (const filepath of options.path) {
216
- if (fs6.existsSync(filepath)) {
216
+ if (fs7.existsSync(filepath)) {
217
217
  possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
218
218
  }
219
219
  }
@@ -223,7 +223,7 @@ var require_main = __commonJS({
223
223
  } else {
224
224
  possibleVaultPath = path7.resolve(process.cwd(), ".env.vault");
225
225
  }
226
- if (fs6.existsSync(possibleVaultPath)) {
226
+ if (fs7.existsSync(possibleVaultPath)) {
227
227
  return possibleVaultPath;
228
228
  }
229
229
  return null;
@@ -272,7 +272,7 @@ var require_main = __commonJS({
272
272
  const parsedAll = {};
273
273
  for (const path8 of optionPaths) {
274
274
  try {
275
- const parsed = DotenvModule.parse(fs6.readFileSync(path8, { encoding }));
275
+ const parsed = DotenvModule.parse(fs7.readFileSync(path8, { encoding }));
276
276
  DotenvModule.populate(parsedAll, parsed, options);
277
277
  } catch (e3) {
278
278
  if (debug) {
@@ -1128,48 +1128,37 @@ var require_dist_cjs5 = __commonJS({
1128
1128
  }
1129
1129
  });
1130
1130
 
1131
- // node_modules/@aws/lambda-invoke-store/dist/invoke-store.js
1132
- var require_invoke_store = __commonJS({
1133
- "node_modules/@aws/lambda-invoke-store/dist/invoke-store.js"(exports2) {
1134
- "use strict";
1135
- Object.defineProperty(exports2, "__esModule", { value: true });
1136
- exports2.InvokeStore = void 0;
1137
- var async_hooks_1 = require("async_hooks");
1138
- var noGlobalAwsLambda = process.env["AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA"] === "1" || process.env["AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA"] === "true";
1131
+ // node_modules/@aws/lambda-invoke-store/dist-es/invoke-store.js
1132
+ var invoke_store_exports = {};
1133
+ __export(invoke_store_exports, {
1134
+ InvokeStore: () => InvokeStore
1135
+ });
1136
+ var import_async_hooks, noGlobalAwsLambda, PROTECTED_KEYS, InvokeStoreImpl, instance, InvokeStore;
1137
+ var init_invoke_store = __esm({
1138
+ "node_modules/@aws/lambda-invoke-store/dist-es/invoke-store.js"() {
1139
+ import_async_hooks = require("async_hooks");
1140
+ noGlobalAwsLambda = process.env["AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA"] === "1" || process.env["AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA"] === "true";
1139
1141
  if (!noGlobalAwsLambda) {
1140
1142
  globalThis.awslambda = globalThis.awslambda || {};
1141
1143
  }
1142
- var PROTECTED_KEYS = {
1144
+ PROTECTED_KEYS = {
1143
1145
  REQUEST_ID: Symbol("_AWS_LAMBDA_REQUEST_ID"),
1144
- X_RAY_TRACE_ID: Symbol("_AWS_LAMBDA_X_RAY_TRACE_ID")
1146
+ X_RAY_TRACE_ID: Symbol("_AWS_LAMBDA_X_RAY_TRACE_ID"),
1147
+ TENANT_ID: Symbol("_AWS_LAMBDA_TENANT_ID")
1145
1148
  };
1146
- var InvokeStoreImpl = class {
1147
- static storage = new async_hooks_1.AsyncLocalStorage();
1148
- // Protected keys for Lambda context fields
1149
+ InvokeStoreImpl = class {
1150
+ static storage = new import_async_hooks.AsyncLocalStorage();
1149
1151
  static PROTECTED_KEYS = PROTECTED_KEYS;
1150
- /**
1151
- * Initialize and run code within an invoke context
1152
- */
1153
1152
  static run(context, fn) {
1154
1153
  return this.storage.run({ ...context }, fn);
1155
1154
  }
1156
- /**
1157
- * Get the complete current context
1158
- */
1159
1155
  static getContext() {
1160
1156
  return this.storage.getStore();
1161
1157
  }
1162
- /**
1163
- * Get a specific value from the context by key
1164
- */
1165
1158
  static get(key) {
1166
1159
  const context = this.storage.getStore();
1167
1160
  return context?.[key];
1168
1161
  }
1169
- /**
1170
- * Set a custom value in the current context
1171
- * Protected Lambda context fields cannot be overwritten
1172
- */
1173
1162
  static set(key, value) {
1174
1163
  if (this.isProtectedKey(key)) {
1175
1164
  throw new Error(`Cannot modify protected Lambda context field`);
@@ -1179,32 +1168,22 @@ var require_invoke_store = __commonJS({
1179
1168
  context[key] = value;
1180
1169
  }
1181
1170
  }
1182
- /**
1183
- * Get the current request ID
1184
- */
1185
1171
  static getRequestId() {
1186
1172
  return this.get(this.PROTECTED_KEYS.REQUEST_ID) ?? "-";
1187
1173
  }
1188
- /**
1189
- * Get the current X-ray trace ID
1190
- */
1191
1174
  static getXRayTraceId() {
1192
1175
  return this.get(this.PROTECTED_KEYS.X_RAY_TRACE_ID);
1193
1176
  }
1194
- /**
1195
- * Check if we're currently within an invoke context
1196
- */
1177
+ static getTenantId() {
1178
+ return this.get(this.PROTECTED_KEYS.TENANT_ID);
1179
+ }
1197
1180
  static hasContext() {
1198
1181
  return this.storage.getStore() !== void 0;
1199
1182
  }
1200
- /**
1201
- * Check if a key is protected (readonly Lambda context field)
1202
- */
1203
1183
  static isProtectedKey(key) {
1204
1184
  return key === this.PROTECTED_KEYS.REQUEST_ID || key === this.PROTECTED_KEYS.X_RAY_TRACE_ID;
1205
1185
  }
1206
1186
  };
1207
- var instance;
1208
1187
  if (!noGlobalAwsLambda && globalThis.awslambda?.InvokeStore) {
1209
1188
  instance = globalThis.awslambda.InvokeStore;
1210
1189
  } else {
@@ -1213,7 +1192,7 @@ var require_invoke_store = __commonJS({
1213
1192
  globalThis.awslambda.InvokeStore = instance;
1214
1193
  }
1215
1194
  }
1216
- exports2.InvokeStore = instance;
1195
+ InvokeStore = instance;
1217
1196
  }
1218
1197
  });
1219
1198
 
@@ -1223,7 +1202,7 @@ var require_recursionDetectionMiddleware = __commonJS({
1223
1202
  "use strict";
1224
1203
  Object.defineProperty(exports2, "__esModule", { value: true });
1225
1204
  exports2.recursionDetectionMiddleware = void 0;
1226
- var lambda_invoke_store_1 = require_invoke_store();
1205
+ var lambda_invoke_store_1 = (init_invoke_store(), __toCommonJS(invoke_store_exports));
1227
1206
  var protocol_http_1 = require_dist_cjs2();
1228
1207
  var TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id";
1229
1208
  var ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME";
@@ -2246,7 +2225,7 @@ var require_headStream = __commonJS({
2246
2225
  if ((0, stream_type_check_1.isReadableStream)(stream2)) {
2247
2226
  return (0, headStream_browser_1.headStream)(stream2, bytes);
2248
2227
  }
2249
- return new Promise((resolve4, reject2) => {
2228
+ return new Promise((resolve5, reject2) => {
2250
2229
  const collector = new Collector();
2251
2230
  collector.limit = bytes;
2252
2231
  stream2.pipe(collector);
@@ -2257,7 +2236,7 @@ var require_headStream = __commonJS({
2257
2236
  collector.on("error", reject2);
2258
2237
  collector.on("finish", function() {
2259
2238
  const bytes2 = new Uint8Array(Buffer.concat(this.buffers));
2260
- resolve4(bytes2);
2239
+ resolve5(bytes2);
2261
2240
  });
2262
2241
  });
2263
2242
  };
@@ -2438,28 +2417,28 @@ var require_dist_cjs15 = __commonJS({
2438
2417
  return timing.setTimeout(registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME);
2439
2418
  };
2440
2419
  var MIN_WAIT_TIME = 6e3;
2441
- async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) {
2420
+ async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME, externalAgent = false) {
2442
2421
  const headers = request.headers ?? {};
2443
- const expect = headers["Expect"] || headers["expect"];
2422
+ const expect = headers.Expect || headers.expect;
2444
2423
  let timeoutId = -1;
2445
2424
  let sendBody = true;
2446
- if (expect === "100-continue") {
2425
+ if (!externalAgent && expect === "100-continue") {
2447
2426
  sendBody = await Promise.race([
2448
- new Promise((resolve4) => {
2449
- timeoutId = Number(timing.setTimeout(() => resolve4(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs)));
2427
+ new Promise((resolve5) => {
2428
+ timeoutId = Number(timing.setTimeout(() => resolve5(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs)));
2450
2429
  }),
2451
- new Promise((resolve4) => {
2430
+ new Promise((resolve5) => {
2452
2431
  httpRequest.on("continue", () => {
2453
2432
  timing.clearTimeout(timeoutId);
2454
- resolve4(true);
2433
+ resolve5(true);
2455
2434
  });
2456
2435
  httpRequest.on("response", () => {
2457
2436
  timing.clearTimeout(timeoutId);
2458
- resolve4(false);
2437
+ resolve5(false);
2459
2438
  });
2460
2439
  httpRequest.on("error", () => {
2461
2440
  timing.clearTimeout(timeoutId);
2462
- resolve4(false);
2441
+ resolve5(false);
2463
2442
  });
2464
2443
  })
2465
2444
  ]);
@@ -2493,6 +2472,7 @@ var require_dist_cjs15 = __commonJS({
2493
2472
  config;
2494
2473
  configProvider;
2495
2474
  socketWarningTimestamp = 0;
2475
+ externalAgent = false;
2496
2476
  metadata = { handlerProtocol: "http/1.1" };
2497
2477
  static create(instanceOrOptions) {
2498
2478
  if (typeof instanceOrOptions?.handle === "function") {
@@ -2524,13 +2504,13 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2524
2504
  return socketWarningTimestamp;
2525
2505
  }
2526
2506
  constructor(options) {
2527
- this.configProvider = new Promise((resolve4, reject2) => {
2507
+ this.configProvider = new Promise((resolve5, reject2) => {
2528
2508
  if (typeof options === "function") {
2529
2509
  options().then((_options) => {
2530
- resolve4(this.resolveDefaultConfig(_options));
2510
+ resolve5(this.resolveDefaultConfig(_options));
2531
2511
  }).catch(reject2);
2532
2512
  } else {
2533
- resolve4(this.resolveDefaultConfig(options));
2513
+ resolve5(this.resolveDefaultConfig(options));
2534
2514
  }
2535
2515
  });
2536
2516
  }
@@ -2546,12 +2526,14 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2546
2526
  throwOnRequestTimeout,
2547
2527
  httpAgent: (() => {
2548
2528
  if (httpAgent instanceof http.Agent || typeof httpAgent?.destroy === "function") {
2529
+ this.externalAgent = true;
2549
2530
  return httpAgent;
2550
2531
  }
2551
2532
  return new http.Agent({ keepAlive, maxSockets, ...httpAgent });
2552
2533
  })(),
2553
2534
  httpsAgent: (() => {
2554
2535
  if (httpsAgent instanceof https.Agent || typeof httpsAgent?.destroy === "function") {
2536
+ this.externalAgent = true;
2555
2537
  return httpsAgent;
2556
2538
  }
2557
2539
  return new https.Agent({ keepAlive, maxSockets, ...httpsAgent });
@@ -2568,9 +2550,10 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2568
2550
  this.config = await this.configProvider;
2569
2551
  }
2570
2552
  return new Promise((_resolve, _reject) => {
2553
+ const config = this.config;
2571
2554
  let writeRequestBodyPromise = void 0;
2572
2555
  const timeouts = [];
2573
- const resolve4 = async (arg) => {
2556
+ const resolve5 = async (arg) => {
2574
2557
  await writeRequestBodyPromise;
2575
2558
  timeouts.forEach(timing.clearTimeout);
2576
2559
  _resolve(arg);
@@ -2580,9 +2563,6 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2580
2563
  timeouts.forEach(timing.clearTimeout);
2581
2564
  _reject(arg);
2582
2565
  };
2583
- if (!this.config) {
2584
- throw new Error("Node HTTP request handler config is not resolved");
2585
- }
2586
2566
  if (abortSignal?.aborted) {
2587
2567
  const abortError = new Error("Request aborted");
2588
2568
  abortError.name = "AbortError";
@@ -2590,10 +2570,18 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2590
2570
  return;
2591
2571
  }
2592
2572
  const isSSL = request.protocol === "https:";
2593
- const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent;
2573
+ const headers = request.headers ?? {};
2574
+ const expectContinue = (headers.Expect ?? headers.expect) === "100-continue";
2575
+ let agent = isSSL ? config.httpsAgent : config.httpAgent;
2576
+ if (expectContinue && !this.externalAgent) {
2577
+ agent = new (isSSL ? https.Agent : http.Agent)({
2578
+ keepAlive: false,
2579
+ maxSockets: Infinity
2580
+ });
2581
+ }
2594
2582
  timeouts.push(timing.setTimeout(() => {
2595
- this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp, this.config.logger);
2596
- }, this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3)));
2583
+ this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp, config.logger);
2584
+ }, config.socketAcquisitionWarningTimeout ?? (config.requestTimeout ?? 2e3) + (config.connectionTimeout ?? 1e3)));
2597
2585
  const queryString = querystringBuilder.buildQueryString(request.query || {});
2598
2586
  let auth = void 0;
2599
2587
  if (request.username != null || request.password != null) {
@@ -2631,7 +2619,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2631
2619
  headers: getTransformedHeaders(res.headers),
2632
2620
  body: res
2633
2621
  });
2634
- resolve4({ response: httpResponse });
2622
+ resolve5({ response: httpResponse });
2635
2623
  });
2636
2624
  req.on("error", (err) => {
2637
2625
  if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) {
@@ -2655,10 +2643,10 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2655
2643
  abortSignal.onabort = onAbort;
2656
2644
  }
2657
2645
  }
2658
- const effectiveRequestTimeout = requestTimeout ?? this.config.requestTimeout;
2659
- timeouts.push(setConnectionTimeout(req, reject2, this.config.connectionTimeout));
2660
- timeouts.push(setRequestTimeout(req, reject2, effectiveRequestTimeout, this.config.throwOnRequestTimeout, this.config.logger ?? console));
2661
- timeouts.push(setSocketTimeout(req, reject2, this.config.socketTimeout));
2646
+ const effectiveRequestTimeout = requestTimeout ?? config.requestTimeout;
2647
+ timeouts.push(setConnectionTimeout(req, reject2, config.connectionTimeout));
2648
+ timeouts.push(setRequestTimeout(req, reject2, effectiveRequestTimeout, config.throwOnRequestTimeout, config.logger ?? console));
2649
+ timeouts.push(setSocketTimeout(req, reject2, config.socketTimeout));
2662
2650
  const httpAgent = nodeHttpsOptions.agent;
2663
2651
  if (typeof httpAgent === "object" && "keepAlive" in httpAgent) {
2664
2652
  timeouts.push(setSocketKeepAlive(req, {
@@ -2666,7 +2654,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2666
2654
  keepAliveMsecs: httpAgent.keepAliveMsecs
2667
2655
  }));
2668
2656
  }
2669
- writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout).catch((e3) => {
2657
+ writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout, this.externalAgent).catch((e3) => {
2670
2658
  timeouts.forEach(timing.clearTimeout);
2671
2659
  return _reject(e3);
2672
2660
  });
@@ -2811,13 +2799,13 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2811
2799
  return new _NodeHttp2Handler(instanceOrOptions);
2812
2800
  }
2813
2801
  constructor(options) {
2814
- this.configProvider = new Promise((resolve4, reject2) => {
2802
+ this.configProvider = new Promise((resolve5, reject2) => {
2815
2803
  if (typeof options === "function") {
2816
2804
  options().then((opts) => {
2817
- resolve4(opts || {});
2805
+ resolve5(opts || {});
2818
2806
  }).catch(reject2);
2819
2807
  } else {
2820
- resolve4(options || {});
2808
+ resolve5(options || {});
2821
2809
  }
2822
2810
  });
2823
2811
  }
@@ -2837,7 +2825,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2837
2825
  return new Promise((_resolve, _reject) => {
2838
2826
  let fulfilled = false;
2839
2827
  let writeRequestBodyPromise = void 0;
2840
- const resolve4 = async (arg) => {
2828
+ const resolve5 = async (arg) => {
2841
2829
  await writeRequestBodyPromise;
2842
2830
  _resolve(arg);
2843
2831
  };
@@ -2893,7 +2881,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2893
2881
  body: req
2894
2882
  });
2895
2883
  fulfilled = true;
2896
- resolve4({ response: httpResponse });
2884
+ resolve5({ response: httpResponse });
2897
2885
  if (disableConcurrentStreams) {
2898
2886
  session.close();
2899
2887
  this.connectionManager.deleteSession(authority, session);
@@ -2970,7 +2958,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2970
2958
  if (isReadableStreamInstance(stream3)) {
2971
2959
  return collectReadableStream(stream3);
2972
2960
  }
2973
- return new Promise((resolve4, reject2) => {
2961
+ return new Promise((resolve5, reject2) => {
2974
2962
  const collector = new Collector();
2975
2963
  stream3.pipe(collector);
2976
2964
  stream3.on("error", (err) => {
@@ -2980,7 +2968,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2980
2968
  collector.on("error", reject2);
2981
2969
  collector.on("finish", function() {
2982
2970
  const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes));
2983
- resolve4(bytes);
2971
+ resolve5(bytes);
2984
2972
  });
2985
2973
  });
2986
2974
  };
@@ -3024,7 +3012,7 @@ var require_dist_cjs16 = __commonJS({
3024
3012
  return new Request(url, requestOptions);
3025
3013
  }
3026
3014
  function requestTimeout(timeoutInMs = 0) {
3027
- return new Promise((resolve4, reject2) => {
3015
+ return new Promise((resolve5, reject2) => {
3028
3016
  if (timeoutInMs) {
3029
3017
  setTimeout(() => {
3030
3018
  const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`);
@@ -3142,7 +3130,7 @@ var require_dist_cjs16 = __commonJS({
3142
3130
  requestTimeout(requestTimeoutInMs)
3143
3131
  ];
3144
3132
  if (abortSignal) {
3145
- raceOfPromises.push(new Promise((resolve4, reject2) => {
3133
+ raceOfPromises.push(new Promise((resolve5, reject2) => {
3146
3134
  const onAbort = () => {
3147
3135
  const abortError = new Error("Request aborted");
3148
3136
  abortError.name = "AbortError";
@@ -3206,7 +3194,7 @@ var require_dist_cjs16 = __commonJS({
3206
3194
  return collected;
3207
3195
  }
3208
3196
  function readToBase64(blob) {
3209
- return new Promise((resolve4, reject2) => {
3197
+ return new Promise((resolve5, reject2) => {
3210
3198
  const reader = new FileReader();
3211
3199
  reader.onloadend = () => {
3212
3200
  if (reader.readyState !== 2) {
@@ -3215,7 +3203,7 @@ var require_dist_cjs16 = __commonJS({
3215
3203
  const result = reader.result ?? "";
3216
3204
  const commaIndex = result.indexOf(",");
3217
3205
  const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length;
3218
- resolve4(result.substring(dataOffset));
3206
+ resolve5(result.substring(dataOffset));
3219
3207
  };
3220
3208
  reader.onabort = () => reject2(new Error("Read aborted"));
3221
3209
  reader.onerror = () => reject2(reader.error);
@@ -3717,8 +3705,8 @@ var init_Schema = __esm({
3717
3705
  name;
3718
3706
  namespace;
3719
3707
  traits;
3720
- static assign(instance, values2) {
3721
- const schema = Object.assign(instance, values2);
3708
+ static assign(instance2, values2) {
3709
+ const schema = Object.assign(instance2, values2);
3722
3710
  return schema;
3723
3711
  }
3724
3712
  static [Symbol.hasInstance](lhs) {
@@ -4835,11 +4823,11 @@ function __metadata(metadataKey, metadataValue) {
4835
4823
  }
4836
4824
  function __awaiter(thisArg, _arguments, P, generator) {
4837
4825
  function adopt(value) {
4838
- return value instanceof P ? value : new P(function(resolve4) {
4839
- resolve4(value);
4826
+ return value instanceof P ? value : new P(function(resolve5) {
4827
+ resolve5(value);
4840
4828
  });
4841
4829
  }
4842
- return new (P || (P = Promise))(function(resolve4, reject2) {
4830
+ return new (P || (P = Promise))(function(resolve5, reject2) {
4843
4831
  function fulfilled(value) {
4844
4832
  try {
4845
4833
  step(generator.next(value));
@@ -4855,7 +4843,7 @@ function __awaiter(thisArg, _arguments, P, generator) {
4855
4843
  }
4856
4844
  }
4857
4845
  function step(result) {
4858
- result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected);
4846
+ result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected);
4859
4847
  }
4860
4848
  step((generator = generator.apply(thisArg, _arguments || [])).next());
4861
4849
  });
@@ -5046,14 +5034,14 @@ function __asyncValues(o3) {
5046
5034
  }, i3);
5047
5035
  function verb(n3) {
5048
5036
  i3[n3] = o3[n3] && function(v3) {
5049
- return new Promise(function(resolve4, reject2) {
5050
- v3 = o3[n3](v3), settle(resolve4, reject2, v3.done, v3.value);
5037
+ return new Promise(function(resolve5, reject2) {
5038
+ v3 = o3[n3](v3), settle(resolve5, reject2, v3.done, v3.value);
5051
5039
  });
5052
5040
  };
5053
5041
  }
5054
- function settle(resolve4, reject2, d3, v3) {
5042
+ function settle(resolve5, reject2, d3, v3) {
5055
5043
  Promise.resolve(v3).then(function(v4) {
5056
- resolve4({ value: v4, done: d3 });
5044
+ resolve5({ value: v4, done: d3 });
5057
5045
  }, reject2);
5058
5046
  }
5059
5047
  }
@@ -5380,12 +5368,8 @@ var init_schema_date_utils = __esm({
5380
5368
  range(hours, 0, 23);
5381
5369
  range(minutes, 0, 59);
5382
5370
  range(seconds, 0, 60);
5383
- const date2 = /* @__PURE__ */ new Date();
5384
- date2.setUTCFullYear(Number(yearStr), Number(monthStr) - 1, Number(dayStr));
5385
- date2.setUTCHours(Number(hours));
5386
- date2.setUTCMinutes(Number(minutes));
5387
- date2.setUTCSeconds(Number(seconds));
5388
- date2.setUTCMilliseconds(Number(ms) ? Math.round(parseFloat(`0.${ms}`) * 1e3) : 0);
5371
+ const date2 = new Date(Date.UTC(Number(yearStr), Number(monthStr) - 1, Number(dayStr), Number(hours), Number(minutes), Number(seconds), Number(ms) ? Math.round(parseFloat(`0.${ms}`) * 1e3) : 0));
5372
+ date2.setUTCFullYear(Number(yearStr));
5389
5373
  if (offsetStr.toUpperCase() != "Z") {
5390
5374
  const [, sign, offsetH, offsetM] = /([+-])(\d\d):(\d\d)/.exec(offsetStr) || [void 0, "+", 0, 0];
5391
5375
  const scalar = sign === "-" ? 1 : -1;
@@ -5417,18 +5401,13 @@ var init_schema_date_utils = __esm({
5417
5401
  [, month, day, hour, minute, second, fraction, year2] = matches;
5418
5402
  }
5419
5403
  if (year2 && second) {
5420
- const date2 = /* @__PURE__ */ new Date();
5421
- date2.setUTCFullYear(Number(year2));
5422
- date2.setUTCMonth(months.indexOf(month));
5404
+ const timestamp = Date.UTC(Number(year2), months.indexOf(month), Number(day), Number(hour), Number(minute), Number(second), fraction ? Math.round(parseFloat(`0.${fraction}`) * 1e3) : 0);
5423
5405
  range(day, 1, 31);
5424
- date2.setUTCDate(Number(day));
5425
5406
  range(hour, 0, 23);
5426
- date2.setUTCHours(Number(hour));
5427
5407
  range(minute, 0, 59);
5428
- date2.setUTCMinutes(Number(minute));
5429
5408
  range(second, 0, 60);
5430
- date2.setUTCSeconds(Number(second));
5431
- date2.setUTCMilliseconds(fraction ? Math.round(parseFloat(`0.${fraction}`) * 1e3) : 0);
5409
+ const date2 = new Date(timestamp);
5410
+ date2.setUTCFullYear(Number(year2));
5432
5411
  return date2;
5433
5412
  }
5434
5413
  throw new TypeError(`Invalid RFC7231 date-time value ${value}.`);
@@ -7662,6 +7641,9 @@ var require_dist_cjs23 = __commonJS({
7662
7641
  },
7663
7642
  "us-isob-east-1": {
7664
7643
  description: "US ISOB East (Ohio)"
7644
+ },
7645
+ "us-isob-west-1": {
7646
+ description: "US ISOB West"
7665
7647
  }
7666
7648
  }
7667
7649
  },
@@ -10666,18 +10648,18 @@ var require_dist_cjs27 = __commonJS({
10666
10648
  const candidate = value;
10667
10649
  return _ServiceException.prototype.isPrototypeOf(candidate) || Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server");
10668
10650
  }
10669
- static [Symbol.hasInstance](instance) {
10670
- if (!instance)
10651
+ static [Symbol.hasInstance](instance2) {
10652
+ if (!instance2)
10671
10653
  return false;
10672
- const candidate = instance;
10654
+ const candidate = instance2;
10673
10655
  if (this === _ServiceException) {
10674
- return _ServiceException.isInstance(instance);
10656
+ return _ServiceException.isInstance(instance2);
10675
10657
  }
10676
- if (_ServiceException.isInstance(instance)) {
10658
+ if (_ServiceException.isInstance(instance2)) {
10677
10659
  if (candidate.name && this.name) {
10678
- return this.prototype.isPrototypeOf(instance) || candidate.name === this.name;
10660
+ return this.prototype.isPrototypeOf(instance2) || candidate.name === this.name;
10679
10661
  }
10680
- return this.prototype.isPrototypeOf(instance);
10662
+ return this.prototype.isPrototypeOf(instance2);
10681
10663
  }
10682
10664
  return false;
10683
10665
  }
@@ -13603,8 +13585,8 @@ var require_dist_cjs29 = __commonJS({
13603
13585
  var X_AMZ_USER_AGENT = "x-amz-user-agent";
13604
13586
  var SPACE = " ";
13605
13587
  var UA_NAME_SEPARATOR = "/";
13606
- var UA_NAME_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g;
13607
- var UA_VALUE_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g;
13588
+ var UA_NAME_ESCAPE_REGEX = /[^!$%&'*+\-.^_`|~\w]/g;
13589
+ var UA_VALUE_ESCAPE_REGEX = /[^!$%&'*+\-.^_`|~\w#]/g;
13608
13590
  var UA_ESCAPE_CHAR = "-";
13609
13591
  var BYTE_LIMIT = 1024;
13610
13592
  function encodeFeatures(features) {
@@ -13637,7 +13619,7 @@ var require_dist_cjs29 = __commonJS({
13637
13619
  const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || [];
13638
13620
  const appId = await options.userAgentAppId();
13639
13621
  if (appId) {
13640
- defaultUserAgent.push(escapeUserAgent([`app/${appId}`]));
13622
+ defaultUserAgent.push(escapeUserAgent([`app`, `${appId}`]));
13641
13623
  }
13642
13624
  const prefix = utilEndpoints.getUserAgentPrefix();
13643
13625
  const sdkUserAgentValue = (prefix ? [prefix] : []).concat([...defaultUserAgent, ...userAgent, ...customUserAgent]).join(SPACE);
@@ -15127,7 +15109,7 @@ var require_dist_cjs37 = __commonJS({
15127
15109
  this.sockets[url] = (this.sockets[url] ?? []).filter((socket) => ![WebSocket.CLOSING, WebSocket.CLOSED].includes(socket.readyState));
15128
15110
  }
15129
15111
  waitForReady(socket, connectionTimeout) {
15130
- return new Promise((resolve4, reject2) => {
15112
+ return new Promise((resolve5, reject2) => {
15131
15113
  const timeout = setTimeout(() => {
15132
15114
  this.removeNotUsableSockets(socket.url);
15133
15115
  reject2({
@@ -15138,7 +15120,7 @@ var require_dist_cjs37 = __commonJS({
15138
15120
  }, connectionTimeout);
15139
15121
  socket.onopen = () => {
15140
15122
  clearTimeout(timeout);
15141
- resolve4();
15123
+ resolve5();
15142
15124
  };
15143
15125
  });
15144
15126
  }
@@ -15147,10 +15129,10 @@ var require_dist_cjs37 = __commonJS({
15147
15129
  let socketErrorOccurred = false;
15148
15130
  let reject2 = () => {
15149
15131
  };
15150
- let resolve4 = () => {
15132
+ let resolve5 = () => {
15151
15133
  };
15152
15134
  socket.onmessage = (event) => {
15153
- resolve4({
15135
+ resolve5({
15154
15136
  done: false,
15155
15137
  value: new Uint8Array(event.data)
15156
15138
  });
@@ -15167,7 +15149,7 @@ var require_dist_cjs37 = __commonJS({
15167
15149
  if (streamError) {
15168
15150
  reject2(streamError);
15169
15151
  } else {
15170
- resolve4({
15152
+ resolve5({
15171
15153
  done: true,
15172
15154
  value: void 0
15173
15155
  });
@@ -15177,7 +15159,7 @@ var require_dist_cjs37 = __commonJS({
15177
15159
  [Symbol.asyncIterator]: () => ({
15178
15160
  next: () => {
15179
15161
  return new Promise((_resolve, _reject) => {
15180
- resolve4 = _resolve;
15162
+ resolve5 = _resolve;
15181
15163
  reject2 = _reject;
15182
15164
  });
15183
15165
  }
@@ -16200,7 +16182,7 @@ var require_dist_cjs46 = __commonJS({
16200
16182
  this.refillTokenBucket();
16201
16183
  if (amount > this.currentCapacity) {
16202
16184
  const delay = (amount - this.currentCapacity) / this.fillRate * 1e3;
16203
- await new Promise((resolve4) => _DefaultRateLimiter.setTimeoutFn(resolve4, delay));
16185
+ await new Promise((resolve5) => _DefaultRateLimiter.setTimeoutFn(resolve5, delay));
16204
16186
  }
16205
16187
  this.currentCapacity = this.currentCapacity - amount;
16206
16188
  }
@@ -16535,7 +16517,7 @@ var require_dist_cjs47 = __commonJS({
16535
16517
  const delayFromResponse = getDelayFromRetryAfterHeader(err.$response);
16536
16518
  const delay = Math.max(delayFromResponse || 0, delayFromDecider);
16537
16519
  totalDelay += delay;
16538
- await new Promise((resolve4) => setTimeout(resolve4, delay));
16520
+ await new Promise((resolve5) => setTimeout(resolve5, delay));
16539
16521
  continue;
16540
16522
  }
16541
16523
  if (!err.$metadata) {
@@ -16693,7 +16675,7 @@ var require_dist_cjs47 = __commonJS({
16693
16675
  attempts = retryToken.getRetryCount();
16694
16676
  const delay = retryToken.getRetryDelay();
16695
16677
  totalRetryDelay += delay;
16696
- await new Promise((resolve4) => setTimeout(resolve4, delay));
16678
+ await new Promise((resolve5) => setTimeout(resolve5, delay));
16697
16679
  }
16698
16680
  }
16699
16681
  } else {
@@ -16845,7 +16827,7 @@ var require_package2 = __commonJS({
16845
16827
  module2.exports = {
16846
16828
  name: "@aws-sdk/client-bedrock-runtime",
16847
16829
  description: "AWS SDK for JavaScript Bedrock Runtime Client for Node.js, Browser and React Native",
16848
- version: "3.914.0",
16830
+ version: "3.922.0",
16849
16831
  scripts: {
16850
16832
  build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
16851
16833
  "build:cjs": "node ../../scripts/compilation/inline client-bedrock-runtime",
@@ -16864,49 +16846,49 @@ var require_package2 = __commonJS({
16864
16846
  dependencies: {
16865
16847
  "@aws-crypto/sha256-browser": "5.2.0",
16866
16848
  "@aws-crypto/sha256-js": "5.2.0",
16867
- "@aws-sdk/core": "3.914.0",
16868
- "@aws-sdk/credential-provider-node": "3.914.0",
16869
- "@aws-sdk/eventstream-handler-node": "3.914.0",
16870
- "@aws-sdk/middleware-eventstream": "3.914.0",
16871
- "@aws-sdk/middleware-host-header": "3.914.0",
16872
- "@aws-sdk/middleware-logger": "3.914.0",
16873
- "@aws-sdk/middleware-recursion-detection": "3.914.0",
16874
- "@aws-sdk/middleware-user-agent": "3.914.0",
16875
- "@aws-sdk/middleware-websocket": "3.914.0",
16876
- "@aws-sdk/region-config-resolver": "3.914.0",
16877
- "@aws-sdk/token-providers": "3.914.0",
16878
- "@aws-sdk/types": "3.914.0",
16879
- "@aws-sdk/util-endpoints": "3.914.0",
16880
- "@aws-sdk/util-user-agent-browser": "3.914.0",
16881
- "@aws-sdk/util-user-agent-node": "3.914.0",
16882
- "@smithy/config-resolver": "^4.4.0",
16883
- "@smithy/core": "^3.17.0",
16884
- "@smithy/eventstream-serde-browser": "^4.2.3",
16885
- "@smithy/eventstream-serde-config-resolver": "^4.3.3",
16886
- "@smithy/eventstream-serde-node": "^4.2.3",
16887
- "@smithy/fetch-http-handler": "^5.3.4",
16888
- "@smithy/hash-node": "^4.2.3",
16889
- "@smithy/invalid-dependency": "^4.2.3",
16890
- "@smithy/middleware-content-length": "^4.2.3",
16891
- "@smithy/middleware-endpoint": "^4.3.4",
16892
- "@smithy/middleware-retry": "^4.4.4",
16893
- "@smithy/middleware-serde": "^4.2.3",
16894
- "@smithy/middleware-stack": "^4.2.3",
16895
- "@smithy/node-config-provider": "^4.3.3",
16896
- "@smithy/node-http-handler": "^4.4.2",
16897
- "@smithy/protocol-http": "^5.3.3",
16898
- "@smithy/smithy-client": "^4.9.0",
16899
- "@smithy/types": "^4.8.0",
16900
- "@smithy/url-parser": "^4.2.3",
16849
+ "@aws-sdk/core": "3.922.0",
16850
+ "@aws-sdk/credential-provider-node": "3.922.0",
16851
+ "@aws-sdk/eventstream-handler-node": "3.922.0",
16852
+ "@aws-sdk/middleware-eventstream": "3.922.0",
16853
+ "@aws-sdk/middleware-host-header": "3.922.0",
16854
+ "@aws-sdk/middleware-logger": "3.922.0",
16855
+ "@aws-sdk/middleware-recursion-detection": "3.922.0",
16856
+ "@aws-sdk/middleware-user-agent": "3.922.0",
16857
+ "@aws-sdk/middleware-websocket": "3.922.0",
16858
+ "@aws-sdk/region-config-resolver": "3.922.0",
16859
+ "@aws-sdk/token-providers": "3.922.0",
16860
+ "@aws-sdk/types": "3.922.0",
16861
+ "@aws-sdk/util-endpoints": "3.922.0",
16862
+ "@aws-sdk/util-user-agent-browser": "3.922.0",
16863
+ "@aws-sdk/util-user-agent-node": "3.922.0",
16864
+ "@smithy/config-resolver": "^4.4.1",
16865
+ "@smithy/core": "^3.17.2",
16866
+ "@smithy/eventstream-serde-browser": "^4.2.4",
16867
+ "@smithy/eventstream-serde-config-resolver": "^4.3.4",
16868
+ "@smithy/eventstream-serde-node": "^4.2.4",
16869
+ "@smithy/fetch-http-handler": "^5.3.5",
16870
+ "@smithy/hash-node": "^4.2.4",
16871
+ "@smithy/invalid-dependency": "^4.2.4",
16872
+ "@smithy/middleware-content-length": "^4.2.4",
16873
+ "@smithy/middleware-endpoint": "^4.3.6",
16874
+ "@smithy/middleware-retry": "^4.4.6",
16875
+ "@smithy/middleware-serde": "^4.2.4",
16876
+ "@smithy/middleware-stack": "^4.2.4",
16877
+ "@smithy/node-config-provider": "^4.3.4",
16878
+ "@smithy/node-http-handler": "^4.4.4",
16879
+ "@smithy/protocol-http": "^5.3.4",
16880
+ "@smithy/smithy-client": "^4.9.2",
16881
+ "@smithy/types": "^4.8.1",
16882
+ "@smithy/url-parser": "^4.2.4",
16901
16883
  "@smithy/util-base64": "^4.3.0",
16902
16884
  "@smithy/util-body-length-browser": "^4.2.0",
16903
16885
  "@smithy/util-body-length-node": "^4.2.1",
16904
- "@smithy/util-defaults-mode-browser": "^4.3.3",
16905
- "@smithy/util-defaults-mode-node": "^4.2.5",
16906
- "@smithy/util-endpoints": "^3.2.3",
16907
- "@smithy/util-middleware": "^4.2.3",
16908
- "@smithy/util-retry": "^4.2.3",
16909
- "@smithy/util-stream": "^4.5.3",
16886
+ "@smithy/util-defaults-mode-browser": "^4.3.5",
16887
+ "@smithy/util-defaults-mode-node": "^4.2.7",
16888
+ "@smithy/util-endpoints": "^3.2.4",
16889
+ "@smithy/util-middleware": "^4.2.4",
16890
+ "@smithy/util-retry": "^4.2.4",
16891
+ "@smithy/util-stream": "^4.5.5",
16910
16892
  "@smithy/util-utf8": "^4.2.0",
16911
16893
  "@smithy/uuid": "^1.1.0",
16912
16894
  tslib: "^2.6.2"
@@ -17008,7 +16990,7 @@ var require_dist_cjs49 = __commonJS({
17008
16990
  var nodeConfigProvider = require_dist_cjs43();
17009
16991
  var urlParser = require_dist_cjs22();
17010
16992
  function httpRequest(options) {
17011
- return new Promise((resolve4, reject2) => {
16993
+ return new Promise((resolve5, reject2) => {
17012
16994
  const req = http.request({
17013
16995
  method: "GET",
17014
16996
  ...options,
@@ -17033,7 +17015,7 @@ var require_dist_cjs49 = __commonJS({
17033
17015
  chunks.push(chunk);
17034
17016
  });
17035
17017
  res.on("end", () => {
17036
- resolve4(buffer.Buffer.concat(chunks));
17018
+ resolve5(buffer.Buffer.concat(chunks));
17037
17019
  req.destroy();
17038
17020
  });
17039
17021
  });
@@ -17453,7 +17435,7 @@ var require_retry_wrapper = __commonJS({
17453
17435
  try {
17454
17436
  return await toRetry();
17455
17437
  } catch (e3) {
17456
- await new Promise((resolve4) => setTimeout(resolve4, delayMs));
17438
+ await new Promise((resolve5) => setTimeout(resolve5, delayMs));
17457
17439
  }
17458
17440
  }
17459
17441
  return await toRetry();
@@ -17626,7 +17608,7 @@ var init_package = __esm({
17626
17608
  "node_modules/@aws-sdk/nested-clients/package.json"() {
17627
17609
  package_default = {
17628
17610
  name: "@aws-sdk/nested-clients",
17629
- version: "3.914.0",
17611
+ version: "3.922.0",
17630
17612
  description: "Nested clients for AWS SDK packages.",
17631
17613
  main: "./dist-cjs/index.js",
17632
17614
  module: "./dist-es/index.js",
@@ -17655,40 +17637,40 @@ var init_package = __esm({
17655
17637
  dependencies: {
17656
17638
  "@aws-crypto/sha256-browser": "5.2.0",
17657
17639
  "@aws-crypto/sha256-js": "5.2.0",
17658
- "@aws-sdk/core": "3.914.0",
17659
- "@aws-sdk/middleware-host-header": "3.914.0",
17660
- "@aws-sdk/middleware-logger": "3.914.0",
17661
- "@aws-sdk/middleware-recursion-detection": "3.914.0",
17662
- "@aws-sdk/middleware-user-agent": "3.914.0",
17663
- "@aws-sdk/region-config-resolver": "3.914.0",
17664
- "@aws-sdk/types": "3.914.0",
17665
- "@aws-sdk/util-endpoints": "3.914.0",
17666
- "@aws-sdk/util-user-agent-browser": "3.914.0",
17667
- "@aws-sdk/util-user-agent-node": "3.914.0",
17668
- "@smithy/config-resolver": "^4.4.0",
17669
- "@smithy/core": "^3.17.0",
17670
- "@smithy/fetch-http-handler": "^5.3.4",
17671
- "@smithy/hash-node": "^4.2.3",
17672
- "@smithy/invalid-dependency": "^4.2.3",
17673
- "@smithy/middleware-content-length": "^4.2.3",
17674
- "@smithy/middleware-endpoint": "^4.3.4",
17675
- "@smithy/middleware-retry": "^4.4.4",
17676
- "@smithy/middleware-serde": "^4.2.3",
17677
- "@smithy/middleware-stack": "^4.2.3",
17678
- "@smithy/node-config-provider": "^4.3.3",
17679
- "@smithy/node-http-handler": "^4.4.2",
17680
- "@smithy/protocol-http": "^5.3.3",
17681
- "@smithy/smithy-client": "^4.9.0",
17682
- "@smithy/types": "^4.8.0",
17683
- "@smithy/url-parser": "^4.2.3",
17640
+ "@aws-sdk/core": "3.922.0",
17641
+ "@aws-sdk/middleware-host-header": "3.922.0",
17642
+ "@aws-sdk/middleware-logger": "3.922.0",
17643
+ "@aws-sdk/middleware-recursion-detection": "3.922.0",
17644
+ "@aws-sdk/middleware-user-agent": "3.922.0",
17645
+ "@aws-sdk/region-config-resolver": "3.922.0",
17646
+ "@aws-sdk/types": "3.922.0",
17647
+ "@aws-sdk/util-endpoints": "3.922.0",
17648
+ "@aws-sdk/util-user-agent-browser": "3.922.0",
17649
+ "@aws-sdk/util-user-agent-node": "3.922.0",
17650
+ "@smithy/config-resolver": "^4.4.1",
17651
+ "@smithy/core": "^3.17.2",
17652
+ "@smithy/fetch-http-handler": "^5.3.5",
17653
+ "@smithy/hash-node": "^4.2.4",
17654
+ "@smithy/invalid-dependency": "^4.2.4",
17655
+ "@smithy/middleware-content-length": "^4.2.4",
17656
+ "@smithy/middleware-endpoint": "^4.3.6",
17657
+ "@smithy/middleware-retry": "^4.4.6",
17658
+ "@smithy/middleware-serde": "^4.2.4",
17659
+ "@smithy/middleware-stack": "^4.2.4",
17660
+ "@smithy/node-config-provider": "^4.3.4",
17661
+ "@smithy/node-http-handler": "^4.4.4",
17662
+ "@smithy/protocol-http": "^5.3.4",
17663
+ "@smithy/smithy-client": "^4.9.2",
17664
+ "@smithy/types": "^4.8.1",
17665
+ "@smithy/url-parser": "^4.2.4",
17684
17666
  "@smithy/util-base64": "^4.3.0",
17685
17667
  "@smithy/util-body-length-browser": "^4.2.0",
17686
17668
  "@smithy/util-body-length-node": "^4.2.1",
17687
- "@smithy/util-defaults-mode-browser": "^4.3.3",
17688
- "@smithy/util-defaults-mode-node": "^4.2.5",
17689
- "@smithy/util-endpoints": "^3.2.3",
17690
- "@smithy/util-middleware": "^4.2.3",
17691
- "@smithy/util-retry": "^4.2.3",
17669
+ "@smithy/util-defaults-mode-browser": "^4.3.5",
17670
+ "@smithy/util-defaults-mode-node": "^4.2.7",
17671
+ "@smithy/util-endpoints": "^3.2.4",
17672
+ "@smithy/util-middleware": "^4.2.4",
17673
+ "@smithy/util-retry": "^4.2.4",
17692
17674
  "@smithy/util-utf8": "^4.2.0",
17693
17675
  tslib: "^2.6.2"
17694
17676
  },
@@ -17890,8 +17872,8 @@ var init_ruleset = __esm({
17890
17872
  f = "tree";
17891
17873
  g = "PartitionResult";
17892
17874
  h = "getAttr";
17893
- i = { [u]: false, "type": "String" };
17894
- j = { [u]: true, "default": false, "type": "Boolean" };
17875
+ i = { [u]: false, "type": "string" };
17876
+ j = { [u]: true, "default": false, "type": "boolean" };
17895
17877
  k = { [x]: "Endpoint" };
17896
17878
  l = { [v]: c, [w]: [{ [x]: "UseFIPS" }, true] };
17897
17879
  m = { [v]: c, [w]: [{ [x]: "UseDualStack" }, true] };
@@ -18097,11 +18079,38 @@ var init_runtimeConfig = __esm({
18097
18079
  }
18098
18080
  });
18099
18081
 
18082
+ // node_modules/@aws-sdk/region-config-resolver/dist-cjs/regionConfig/stsRegionDefaultResolver.js
18083
+ var require_stsRegionDefaultResolver = __commonJS({
18084
+ "node_modules/@aws-sdk/region-config-resolver/dist-cjs/regionConfig/stsRegionDefaultResolver.js"(exports2) {
18085
+ "use strict";
18086
+ Object.defineProperty(exports2, "__esModule", { value: true });
18087
+ exports2.warning = void 0;
18088
+ exports2.stsRegionDefaultResolver = stsRegionDefaultResolver2;
18089
+ var config_resolver_1 = require_dist_cjs39();
18090
+ var node_config_provider_1 = require_dist_cjs43();
18091
+ function stsRegionDefaultResolver2(loaderConfig = {}) {
18092
+ return (0, node_config_provider_1.loadConfig)({
18093
+ ...config_resolver_1.NODE_REGION_CONFIG_OPTIONS,
18094
+ async default() {
18095
+ if (!exports2.warning.silence) {
18096
+ console.warn("@aws-sdk - WARN - default STS region of us-east-1 used. See @aws-sdk/credential-providers README and set a region explicitly.");
18097
+ }
18098
+ return "us-east-1";
18099
+ }
18100
+ }, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig });
18101
+ }
18102
+ exports2.warning = {
18103
+ silence: false
18104
+ };
18105
+ }
18106
+ });
18107
+
18100
18108
  // node_modules/@aws-sdk/region-config-resolver/dist-cjs/index.js
18101
18109
  var require_dist_cjs55 = __commonJS({
18102
18110
  "node_modules/@aws-sdk/region-config-resolver/dist-cjs/index.js"(exports2) {
18103
18111
  "use strict";
18104
18112
  var configResolver = require_dist_cjs39();
18113
+ var stsRegionDefaultResolver2 = require_stsRegionDefaultResolver();
18105
18114
  var getAwsRegionExtensionConfiguration3 = (runtimeConfig) => {
18106
18115
  return {
18107
18116
  setRegion(region) {
@@ -18149,6 +18158,14 @@ var require_dist_cjs55 = __commonJS({
18149
18158
  });
18150
18159
  exports2.getAwsRegionExtensionConfiguration = getAwsRegionExtensionConfiguration3;
18151
18160
  exports2.resolveAwsRegionExtensionConfiguration = resolveAwsRegionExtensionConfiguration3;
18161
+ Object.keys(stsRegionDefaultResolver2).forEach(function(k3) {
18162
+ if (k3 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, k3)) Object.defineProperty(exports2, k3, {
18163
+ enumerable: true,
18164
+ get: function() {
18165
+ return stsRegionDefaultResolver2[k3];
18166
+ }
18167
+ });
18168
+ });
18152
18169
  }
18153
18170
  });
18154
18171
 
@@ -18846,7 +18863,7 @@ var require_dist_cjs56 = __commonJS({
18846
18863
  var httpAuthSchemes = (init_httpAuthSchemes2(), __toCommonJS(httpAuthSchemes_exports));
18847
18864
  var propertyProvider = require_dist_cjs24();
18848
18865
  var sharedIniFileLoader = require_dist_cjs42();
18849
- var fs6 = require("fs");
18866
+ var fs7 = require("fs");
18850
18867
  var fromEnvSigningName = ({ logger: logger2, signingName } = {}) => async () => {
18851
18868
  logger2?.debug?.("@aws-sdk/token-providers - fromEnvSigningName");
18852
18869
  if (!signingName) {
@@ -18864,9 +18881,11 @@ var require_dist_cjs56 = __commonJS({
18864
18881
  var REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`;
18865
18882
  var getSsoOidcClient = async (ssoRegion, init = {}) => {
18866
18883
  const { SSOOIDCClient: SSOOIDCClient2 } = await Promise.resolve().then(() => (init_sso_oidc(), sso_oidc_exports));
18884
+ const coalesce = (prop) => init.clientConfig?.[prop] ?? init.parentClientConfig?.[prop];
18867
18885
  const ssoOidcClient = new SSOOIDCClient2(Object.assign({}, init.clientConfig ?? {}, {
18868
18886
  region: ssoRegion ?? init.clientConfig?.region,
18869
- logger: init.clientConfig?.logger ?? init.parentClientConfig?.logger
18887
+ logger: coalesce("logger"),
18888
+ userAgentAppId: coalesce("userAgentAppId")
18870
18889
  }));
18871
18890
  return ssoOidcClient;
18872
18891
  };
@@ -18890,7 +18909,7 @@ var require_dist_cjs56 = __commonJS({
18890
18909
  throw new propertyProvider.TokenProviderError(`Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`, false);
18891
18910
  }
18892
18911
  };
18893
- var { writeFile } = fs6.promises;
18912
+ var { writeFile } = fs7.promises;
18894
18913
  var writeSSOTokenToFile = (id, ssoToken) => {
18895
18914
  const tokenFilepath = sharedIniFileLoader.getSSOTokenFilepath(id);
18896
18915
  const tokenString = JSON.stringify(ssoToken, null, 2);
@@ -19069,7 +19088,7 @@ var require_package3 = __commonJS({
19069
19088
  module2.exports = {
19070
19089
  name: "@aws-sdk/client-sso",
19071
19090
  description: "AWS SDK for JavaScript Sso Client for Node.js, Browser and React Native",
19072
- version: "3.914.0",
19091
+ version: "3.922.0",
19073
19092
  scripts: {
19074
19093
  build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
19075
19094
  "build:cjs": "node ../../scripts/compilation/inline client-sso",
@@ -19088,40 +19107,40 @@ var require_package3 = __commonJS({
19088
19107
  dependencies: {
19089
19108
  "@aws-crypto/sha256-browser": "5.2.0",
19090
19109
  "@aws-crypto/sha256-js": "5.2.0",
19091
- "@aws-sdk/core": "3.914.0",
19092
- "@aws-sdk/middleware-host-header": "3.914.0",
19093
- "@aws-sdk/middleware-logger": "3.914.0",
19094
- "@aws-sdk/middleware-recursion-detection": "3.914.0",
19095
- "@aws-sdk/middleware-user-agent": "3.914.0",
19096
- "@aws-sdk/region-config-resolver": "3.914.0",
19097
- "@aws-sdk/types": "3.914.0",
19098
- "@aws-sdk/util-endpoints": "3.914.0",
19099
- "@aws-sdk/util-user-agent-browser": "3.914.0",
19100
- "@aws-sdk/util-user-agent-node": "3.914.0",
19101
- "@smithy/config-resolver": "^4.4.0",
19102
- "@smithy/core": "^3.17.0",
19103
- "@smithy/fetch-http-handler": "^5.3.4",
19104
- "@smithy/hash-node": "^4.2.3",
19105
- "@smithy/invalid-dependency": "^4.2.3",
19106
- "@smithy/middleware-content-length": "^4.2.3",
19107
- "@smithy/middleware-endpoint": "^4.3.4",
19108
- "@smithy/middleware-retry": "^4.4.4",
19109
- "@smithy/middleware-serde": "^4.2.3",
19110
- "@smithy/middleware-stack": "^4.2.3",
19111
- "@smithy/node-config-provider": "^4.3.3",
19112
- "@smithy/node-http-handler": "^4.4.2",
19113
- "@smithy/protocol-http": "^5.3.3",
19114
- "@smithy/smithy-client": "^4.9.0",
19115
- "@smithy/types": "^4.8.0",
19116
- "@smithy/url-parser": "^4.2.3",
19110
+ "@aws-sdk/core": "3.922.0",
19111
+ "@aws-sdk/middleware-host-header": "3.922.0",
19112
+ "@aws-sdk/middleware-logger": "3.922.0",
19113
+ "@aws-sdk/middleware-recursion-detection": "3.922.0",
19114
+ "@aws-sdk/middleware-user-agent": "3.922.0",
19115
+ "@aws-sdk/region-config-resolver": "3.922.0",
19116
+ "@aws-sdk/types": "3.922.0",
19117
+ "@aws-sdk/util-endpoints": "3.922.0",
19118
+ "@aws-sdk/util-user-agent-browser": "3.922.0",
19119
+ "@aws-sdk/util-user-agent-node": "3.922.0",
19120
+ "@smithy/config-resolver": "^4.4.1",
19121
+ "@smithy/core": "^3.17.2",
19122
+ "@smithy/fetch-http-handler": "^5.3.5",
19123
+ "@smithy/hash-node": "^4.2.4",
19124
+ "@smithy/invalid-dependency": "^4.2.4",
19125
+ "@smithy/middleware-content-length": "^4.2.4",
19126
+ "@smithy/middleware-endpoint": "^4.3.6",
19127
+ "@smithy/middleware-retry": "^4.4.6",
19128
+ "@smithy/middleware-serde": "^4.2.4",
19129
+ "@smithy/middleware-stack": "^4.2.4",
19130
+ "@smithy/node-config-provider": "^4.3.4",
19131
+ "@smithy/node-http-handler": "^4.4.4",
19132
+ "@smithy/protocol-http": "^5.3.4",
19133
+ "@smithy/smithy-client": "^4.9.2",
19134
+ "@smithy/types": "^4.8.1",
19135
+ "@smithy/url-parser": "^4.2.4",
19117
19136
  "@smithy/util-base64": "^4.3.0",
19118
19137
  "@smithy/util-body-length-browser": "^4.2.0",
19119
19138
  "@smithy/util-body-length-node": "^4.2.1",
19120
- "@smithy/util-defaults-mode-browser": "^4.3.3",
19121
- "@smithy/util-defaults-mode-node": "^4.2.5",
19122
- "@smithy/util-endpoints": "^3.2.3",
19123
- "@smithy/util-middleware": "^4.2.3",
19124
- "@smithy/util-retry": "^4.2.3",
19139
+ "@smithy/util-defaults-mode-browser": "^4.3.5",
19140
+ "@smithy/util-defaults-mode-node": "^4.2.7",
19141
+ "@smithy/util-endpoints": "^3.2.4",
19142
+ "@smithy/util-middleware": "^4.2.4",
19143
+ "@smithy/util-retry": "^4.2.4",
19125
19144
  "@smithy/util-utf8": "^4.2.0",
19126
19145
  tslib: "^2.6.2"
19127
19146
  },
@@ -19185,8 +19204,8 @@ var require_ruleset = __commonJS({
19185
19204
  var f3 = "tree";
19186
19205
  var g3 = "PartitionResult";
19187
19206
  var h3 = "getAttr";
19188
- var i3 = { [u3]: false, "type": "String" };
19189
- var j3 = { [u3]: true, "default": false, "type": "Boolean" };
19207
+ var i3 = { [u3]: false, "type": "string" };
19208
+ var j3 = { [u3]: true, "default": false, "type": "boolean" };
19190
19209
  var k3 = { [x3]: "Endpoint" };
19191
19210
  var l3 = { [v3]: c3, [w3]: [{ [x3]: "UseFIPS" }, true] };
19192
19211
  var m3 = { [v3]: c3, [w3]: [{ [x3]: "UseDualStack" }, true] };
@@ -19866,7 +19885,8 @@ var require_dist_cjs58 = __commonJS({
19866
19885
  });
19867
19886
  const sso = ssoClient || new SSOClient(Object.assign({}, clientConfig ?? {}, {
19868
19887
  logger: clientConfig?.logger ?? parentClientConfig?.logger,
19869
- region: clientConfig?.region ?? ssoRegion
19888
+ region: clientConfig?.region ?? ssoRegion,
19889
+ userAgentAppId: clientConfig?.userAgentAppId ?? parentClientConfig?.userAgentAppId
19870
19890
  }));
19871
19891
  let ssoResp;
19872
19892
  try {
@@ -20094,8 +20114,8 @@ var init_ruleset2 = __esm({
20094
20114
  j2 = "tree";
20095
20115
  k2 = "error";
20096
20116
  l2 = "getAttr";
20097
- m2 = { [F]: false, [G]: "String" };
20098
- n2 = { [F]: true, "default": false, [G]: "Boolean" };
20117
+ m2 = { [F]: false, [G]: "string" };
20118
+ n2 = { [F]: true, "default": false, [G]: "boolean" };
20099
20119
  o2 = { [J]: "Endpoint" };
20100
20120
  p2 = { [H]: "isSet", [I]: [{ [J]: "Region" }] };
20101
20121
  q2 = { [J]: "Region" };
@@ -21091,13 +21111,13 @@ var init_models2 = __esm({
21091
21111
  });
21092
21112
 
21093
21113
  // node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultStsRoleAssumers.js
21094
- var ASSUME_ROLE_DEFAULT_REGION, getAccountIdFromAssumedRoleUser, resolveRegion, getDefaultRoleAssumer, getDefaultRoleAssumerWithWebIdentity, isH2;
21114
+ var import_region_config_resolver3, getAccountIdFromAssumedRoleUser, resolveRegion, getDefaultRoleAssumer, getDefaultRoleAssumerWithWebIdentity, isH2;
21095
21115
  var init_defaultStsRoleAssumers = __esm({
21096
21116
  "node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultStsRoleAssumers.js"() {
21097
21117
  init_client();
21118
+ import_region_config_resolver3 = __toESM(require_dist_cjs55());
21098
21119
  init_AssumeRoleCommand();
21099
21120
  init_AssumeRoleWithWebIdentityCommand();
21100
- ASSUME_ROLE_DEFAULT_REGION = "us-east-1";
21101
21121
  getAccountIdFromAssumedRoleUser = (assumedRoleUser) => {
21102
21122
  if (typeof assumedRoleUser?.Arn === "string") {
21103
21123
  const arnComponents = assumedRoleUser.Arn.split(":");
@@ -21107,11 +21127,12 @@ var init_defaultStsRoleAssumers = __esm({
21107
21127
  }
21108
21128
  return void 0;
21109
21129
  };
21110
- resolveRegion = async (_region, _parentRegion, credentialProviderLogger) => {
21130
+ resolveRegion = async (_region, _parentRegion, credentialProviderLogger, loaderConfig = {}) => {
21111
21131
  const region = typeof _region === "function" ? await _region() : _region;
21112
21132
  const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion;
21113
- credentialProviderLogger?.debug?.("@aws-sdk/client-sts::resolveRegion", "accepting first of:", `${region} (provider)`, `${parentRegion} (parent client)`, `${ASSUME_ROLE_DEFAULT_REGION} (STS default)`);
21114
- return region ?? parentRegion ?? ASSUME_ROLE_DEFAULT_REGION;
21133
+ const stsDefaultRegion = await (0, import_region_config_resolver3.stsRegionDefaultResolver)(loaderConfig)();
21134
+ credentialProviderLogger?.debug?.("@aws-sdk/client-sts::resolveRegion", "accepting first of:", `${region} (credential provider clientConfig)`, `${parentRegion} (contextual client)`, `${stsDefaultRegion} (STS default: AWS_REGION, profile region, or us-east-1)`);
21135
+ return region ?? parentRegion ?? stsDefaultRegion;
21115
21136
  };
21116
21137
  getDefaultRoleAssumer = (stsOptions, STSClient2) => {
21117
21138
  let stsClient;
@@ -21119,11 +21140,15 @@ var init_defaultStsRoleAssumers = __esm({
21119
21140
  return async (sourceCreds, params) => {
21120
21141
  closureSourceCreds = sourceCreds;
21121
21142
  if (!stsClient) {
21122
- const { logger: logger2 = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger } = stsOptions;
21123
- const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger);
21143
+ const { logger: logger2 = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId } = stsOptions;
21144
+ const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, {
21145
+ logger: logger2,
21146
+ profile
21147
+ });
21124
21148
  const isCompatibleRequestHandler = !isH2(requestHandler);
21125
21149
  stsClient = new STSClient2({
21126
21150
  ...stsOptions,
21151
+ userAgentAppId,
21127
21152
  profile,
21128
21153
  credentialDefaultProvider: () => async () => closureSourceCreds,
21129
21154
  region: resolvedRegion,
@@ -21152,11 +21177,15 @@ var init_defaultStsRoleAssumers = __esm({
21152
21177
  let stsClient;
21153
21178
  return async (params) => {
21154
21179
  if (!stsClient) {
21155
- const { logger: logger2 = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger } = stsOptions;
21156
- const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger);
21180
+ const { logger: logger2 = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId } = stsOptions;
21181
+ const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, {
21182
+ logger: logger2,
21183
+ profile
21184
+ });
21157
21185
  const isCompatibleRequestHandler = !isH2(requestHandler);
21158
21186
  stsClient = new STSClient2({
21159
21187
  ...stsOptions,
21188
+ userAgentAppId,
21160
21189
  profile,
21161
21190
  region: resolvedRegion,
21162
21191
  requestHandler: isCompatibleRequestHandler ? requestHandler : void 0,
@@ -21415,7 +21444,7 @@ var require_fromTokenFile = __commonJS({
21415
21444
  var ENV_TOKEN_FILE = "AWS_WEB_IDENTITY_TOKEN_FILE";
21416
21445
  var ENV_ROLE_ARN = "AWS_ROLE_ARN";
21417
21446
  var ENV_ROLE_SESSION_NAME = "AWS_ROLE_SESSION_NAME";
21418
- var fromTokenFile = (init = {}) => async () => {
21447
+ var fromTokenFile = (init = {}) => async (awsIdentityProperties) => {
21419
21448
  init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile");
21420
21449
  const webIdentityTokenFile = init?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE];
21421
21450
  const roleArn = init?.roleArn ?? process.env[ENV_ROLE_ARN];
@@ -21430,7 +21459,7 @@ var require_fromTokenFile = __commonJS({
21430
21459
  webIdentityToken: shared_ini_file_loader_1.externalDataInterceptor?.getTokenRecord?.()[webIdentityTokenFile] ?? (0, fs_1.readFileSync)(webIdentityTokenFile, { encoding: "ascii" }),
21431
21460
  roleArn,
21432
21461
  roleSessionName
21433
- })();
21462
+ })(awsIdentityProperties);
21434
21463
  if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) {
21435
21464
  (0, client_1.setCredentialFeature)(credentials, "CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN", "h");
21436
21465
  }
@@ -21667,15 +21696,67 @@ var require_dist_cjs62 = __commonJS({
21667
21696
  init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata");
21668
21697
  return fromInstanceMetadata(init);
21669
21698
  };
21699
+ function memoizeChain(providers, treatAsExpired) {
21700
+ const chain = internalCreateChain(providers);
21701
+ let activeLock;
21702
+ let passiveLock;
21703
+ let credentials;
21704
+ const provider = async (options) => {
21705
+ if (options?.forceRefresh) {
21706
+ return await chain(options);
21707
+ }
21708
+ if (credentials?.expiration) {
21709
+ if (credentials?.expiration?.getTime() < Date.now()) {
21710
+ credentials = void 0;
21711
+ }
21712
+ }
21713
+ if (activeLock) {
21714
+ await activeLock;
21715
+ } else if (!credentials || treatAsExpired?.(credentials)) {
21716
+ if (credentials) {
21717
+ if (!passiveLock) {
21718
+ passiveLock = chain(options).then((c3) => {
21719
+ credentials = c3;
21720
+ passiveLock = void 0;
21721
+ });
21722
+ }
21723
+ } else {
21724
+ activeLock = chain(options).then((c3) => {
21725
+ credentials = c3;
21726
+ activeLock = void 0;
21727
+ });
21728
+ return provider(options);
21729
+ }
21730
+ }
21731
+ return credentials;
21732
+ };
21733
+ return provider;
21734
+ }
21735
+ var internalCreateChain = (providers) => async (awsIdentityProperties) => {
21736
+ let lastProviderError;
21737
+ for (const provider of providers) {
21738
+ try {
21739
+ return await provider(awsIdentityProperties);
21740
+ } catch (err) {
21741
+ lastProviderError = err;
21742
+ if (err?.tryNextLink) {
21743
+ continue;
21744
+ }
21745
+ throw err;
21746
+ }
21747
+ }
21748
+ throw lastProviderError;
21749
+ };
21670
21750
  var multipleCredentialSourceWarningEmitted = false;
21671
- var defaultProvider = (init = {}) => propertyProvider.memoize(propertyProvider.chain(async () => {
21672
- const profile = init.profile ?? process.env[sharedIniFileLoader.ENV_PROFILE];
21673
- if (profile) {
21674
- const envStaticCredentialsAreSet = process.env[credentialProviderEnv.ENV_KEY] && process.env[credentialProviderEnv.ENV_SECRET];
21675
- if (envStaticCredentialsAreSet) {
21676
- if (!multipleCredentialSourceWarningEmitted) {
21677
- const warnFn = init.logger?.warn && init.logger?.constructor?.name !== "NoOpLogger" ? init.logger.warn.bind(init.logger) : console.warn;
21678
- warnFn(`@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING:
21751
+ var defaultProvider = (init = {}) => memoizeChain([
21752
+ async () => {
21753
+ const profile = init.profile ?? process.env[sharedIniFileLoader.ENV_PROFILE];
21754
+ if (profile) {
21755
+ const envStaticCredentialsAreSet = process.env[credentialProviderEnv.ENV_KEY] && process.env[credentialProviderEnv.ENV_SECRET];
21756
+ if (envStaticCredentialsAreSet) {
21757
+ if (!multipleCredentialSourceWarningEmitted) {
21758
+ const warnFn = init.logger?.warn && init.logger?.constructor?.name !== "NoOpLogger" ? init.logger.warn.bind(init.logger) : console.warn;
21759
+ warnFn(`@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING:
21679
21760
  Multiple credential sources detected:
21680
21761
  Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set.
21681
21762
  This SDK will proceed with the AWS_PROFILE value.
@@ -21684,45 +21765,52 @@ var require_dist_cjs62 = __commonJS({
21684
21765
  Please ensure that your environment only sets either the AWS_PROFILE or the
21685
21766
  AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair.
21686
21767
  `);
21687
- multipleCredentialSourceWarningEmitted = true;
21768
+ multipleCredentialSourceWarningEmitted = true;
21769
+ }
21688
21770
  }
21771
+ throw new propertyProvider.CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", {
21772
+ logger: init.logger,
21773
+ tryNextLink: true
21774
+ });
21689
21775
  }
21690
- throw new propertyProvider.CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", {
21691
- logger: init.logger,
21692
- tryNextLink: true
21776
+ init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv");
21777
+ return credentialProviderEnv.fromEnv(init)();
21778
+ },
21779
+ async (awsIdentityProperties) => {
21780
+ init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO");
21781
+ const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init;
21782
+ if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {
21783
+ throw new propertyProvider.CredentialsProviderError("Skipping SSO provider in default chain (inputs do not include SSO fields).", { logger: init.logger });
21784
+ }
21785
+ const { fromSSO } = await Promise.resolve().then(() => __toESM(require_dist_cjs58()));
21786
+ return fromSSO(init)(awsIdentityProperties);
21787
+ },
21788
+ async (awsIdentityProperties) => {
21789
+ init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni");
21790
+ const { fromIni } = await Promise.resolve().then(() => __toESM(require_dist_cjs61()));
21791
+ return fromIni(init)(awsIdentityProperties);
21792
+ },
21793
+ async (awsIdentityProperties) => {
21794
+ init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess");
21795
+ const { fromProcess } = await Promise.resolve().then(() => __toESM(require_dist_cjs59()));
21796
+ return fromProcess(init)(awsIdentityProperties);
21797
+ },
21798
+ async (awsIdentityProperties) => {
21799
+ init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile");
21800
+ const { fromTokenFile } = await Promise.resolve().then(() => __toESM(require_dist_cjs60()));
21801
+ return fromTokenFile(init)(awsIdentityProperties);
21802
+ },
21803
+ async () => {
21804
+ init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider");
21805
+ return (await remoteProvider(init))();
21806
+ },
21807
+ async () => {
21808
+ throw new propertyProvider.CredentialsProviderError("Could not load credentials from any providers", {
21809
+ tryNextLink: false,
21810
+ logger: init.logger
21693
21811
  });
21694
21812
  }
21695
- init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv");
21696
- return credentialProviderEnv.fromEnv(init)();
21697
- }, async () => {
21698
- init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO");
21699
- const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init;
21700
- if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {
21701
- throw new propertyProvider.CredentialsProviderError("Skipping SSO provider in default chain (inputs do not include SSO fields).", { logger: init.logger });
21702
- }
21703
- const { fromSSO } = await Promise.resolve().then(() => __toESM(require_dist_cjs58()));
21704
- return fromSSO(init)();
21705
- }, async () => {
21706
- init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni");
21707
- const { fromIni } = await Promise.resolve().then(() => __toESM(require_dist_cjs61()));
21708
- return fromIni(init)();
21709
- }, async () => {
21710
- init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess");
21711
- const { fromProcess } = await Promise.resolve().then(() => __toESM(require_dist_cjs59()));
21712
- return fromProcess(init)();
21713
- }, async () => {
21714
- init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile");
21715
- const { fromTokenFile } = await Promise.resolve().then(() => __toESM(require_dist_cjs60()));
21716
- return fromTokenFile(init)();
21717
- }, async () => {
21718
- init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider");
21719
- return (await remoteProvider(init))();
21720
- }, async () => {
21721
- throw new propertyProvider.CredentialsProviderError("Could not load credentials from any providers", {
21722
- tryNextLink: false,
21723
- logger: init.logger
21724
- });
21725
- }), credentialsTreatedAsExpired, credentialsWillNeedRefresh);
21813
+ ], credentialsTreatedAsExpired);
21726
21814
  var credentialsWillNeedRefresh = (credentials) => credentials?.expiration !== void 0;
21727
21815
  var credentialsTreatedAsExpired = (credentials) => credentials?.expiration !== void 0 && credentials.expiration.getTime() - Date.now() < 3e5;
21728
21816
  exports2.credentialsTreatedAsExpired = credentialsTreatedAsExpired;
@@ -21863,7 +21951,7 @@ var require_dist_cjs64 = __commonJS({
21863
21951
  streamEnded = true;
21864
21952
  });
21865
21953
  while (!generationEnded) {
21866
- const value = await new Promise((resolve4) => setTimeout(() => resolve4(records.shift()), 0));
21954
+ const value = await new Promise((resolve5) => setTimeout(() => resolve5(records.shift()), 0));
21867
21955
  if (value) {
21868
21956
  yield value;
21869
21957
  }
@@ -21909,8 +21997,8 @@ var require_ruleset2 = __commonJS({
21909
21997
  var e3 = "endpoint";
21910
21998
  var f3 = "tree";
21911
21999
  var g3 = "PartitionResult";
21912
- var h3 = { [s3]: false, "type": "String" };
21913
- var i3 = { [s3]: true, "default": false, "type": "Boolean" };
22000
+ var h3 = { [s3]: false, "type": "string" };
22001
+ var i3 = { [s3]: true, "default": false, "type": "boolean" };
21914
22002
  var j3 = { [v3]: "Endpoint" };
21915
22003
  var k3 = { [t3]: c3, [u3]: [{ [v3]: "UseFIPS" }, true] };
21916
22004
  var l3 = { [t3]: c3, [u3]: [{ [v3]: "UseDualStack" }, true] };
@@ -22483,6 +22571,8 @@ var require_dist_cjs65 = __commonJS({
22483
22571
  exports2.CitationLocation = void 0;
22484
22572
  (function(CitationLocation) {
22485
22573
  CitationLocation.visit = (value, visitor) => {
22574
+ if (value.web !== void 0)
22575
+ return visitor.web(value.web);
22486
22576
  if (value.documentChar !== void 0)
22487
22577
  return visitor.documentChar(value.documentChar);
22488
22578
  if (value.documentPage !== void 0)
@@ -22635,6 +22725,9 @@ var require_dist_cjs65 = __commonJS({
22635
22725
  ERROR: "error",
22636
22726
  SUCCESS: "success"
22637
22727
  };
22728
+ var ToolUseType = {
22729
+ SERVER_TOOL_USE: "server_tool_use"
22730
+ };
22638
22731
  exports2.ContentBlock = void 0;
22639
22732
  (function(ContentBlock) {
22640
22733
  ContentBlock.visit = (value, visitor) => {
@@ -22714,6 +22807,8 @@ var require_dist_cjs65 = __commonJS({
22714
22807
  Tool.visit = (value, visitor) => {
22715
22808
  if (value.toolSpec !== void 0)
22716
22809
  return visitor.toolSpec(value.toolSpec);
22810
+ if (value.systemTool !== void 0)
22811
+ return visitor.systemTool(value.systemTool);
22717
22812
  if (value.cachePoint !== void 0)
22718
22813
  return visitor.cachePoint(value.cachePoint);
22719
22814
  return visitor._(value.$unknown[0], value.$unknown[1]);
@@ -22793,6 +22888,14 @@ var require_dist_cjs65 = __commonJS({
22793
22888
  return visitor._(value.$unknown[0], value.$unknown[1]);
22794
22889
  };
22795
22890
  })(exports2.ReasoningContentBlockDelta || (exports2.ReasoningContentBlockDelta = {}));
22891
+ exports2.ToolResultBlockDelta = void 0;
22892
+ (function(ToolResultBlockDelta) {
22893
+ ToolResultBlockDelta.visit = (value, visitor) => {
22894
+ if (value.text !== void 0)
22895
+ return visitor.text(value.text);
22896
+ return visitor._(value.$unknown[0], value.$unknown[1]);
22897
+ };
22898
+ })(exports2.ToolResultBlockDelta || (exports2.ToolResultBlockDelta = {}));
22796
22899
  exports2.ContentBlockDelta = void 0;
22797
22900
  (function(ContentBlockDelta) {
22798
22901
  ContentBlockDelta.visit = (value, visitor) => {
@@ -22800,6 +22903,8 @@ var require_dist_cjs65 = __commonJS({
22800
22903
  return visitor.text(value.text);
22801
22904
  if (value.toolUse !== void 0)
22802
22905
  return visitor.toolUse(value.toolUse);
22906
+ if (value.toolResult !== void 0)
22907
+ return visitor.toolResult(value.toolResult);
22803
22908
  if (value.reasoningContent !== void 0)
22804
22909
  return visitor.reasoningContent(value.reasoningContent);
22805
22910
  if (value.citation !== void 0)
@@ -22812,6 +22917,8 @@ var require_dist_cjs65 = __commonJS({
22812
22917
  ContentBlockStart.visit = (value, visitor) => {
22813
22918
  if (value.toolUse !== void 0)
22814
22919
  return visitor.toolUse(value.toolUse);
22920
+ if (value.toolResult !== void 0)
22921
+ return visitor.toolResult(value.toolResult);
22815
22922
  return visitor._(value.$unknown[0], value.$unknown[1]);
22816
22923
  };
22817
22924
  })(exports2.ContentBlockStart || (exports2.ContentBlockStart = {}));
@@ -23201,6 +23308,8 @@ var require_dist_cjs65 = __commonJS({
23201
23308
  return { text: obj.text };
23202
23309
  if (obj.toolUse !== void 0)
23203
23310
  return { toolUse: obj.toolUse };
23311
+ if (obj.toolResult !== void 0)
23312
+ return { toolResult: obj.toolResult.map((item) => item) };
23204
23313
  if (obj.reasoningContent !== void 0)
23205
23314
  return { reasoningContent: smithyClient.SENSITIVE_STRING };
23206
23315
  if (obj.citation !== void 0)
@@ -24296,6 +24405,7 @@ var require_dist_cjs65 = __commonJS({
24296
24405
  var se_Tool = (input, context) => {
24297
24406
  return exports2.Tool.visit(input, {
24298
24407
  cachePoint: (value) => ({ cachePoint: smithyClient._json(value) }),
24408
+ systemTool: (value) => ({ systemTool: smithyClient._json(value) }),
24299
24409
  toolSpec: (value) => ({ toolSpec: se_ToolSpecification(value) }),
24300
24410
  _: (name14, value) => ({ [name14]: value })
24301
24411
  });
@@ -24316,7 +24426,8 @@ var require_dist_cjs65 = __commonJS({
24316
24426
  return smithyClient.take(input, {
24317
24427
  content: (_2) => se_ToolResultContentBlocks(_2, context),
24318
24428
  status: [],
24319
- toolUseId: []
24429
+ toolUseId: [],
24430
+ type: []
24320
24431
  });
24321
24432
  };
24322
24433
  var se_ToolResultContentBlock = (input, context) => {
@@ -24350,7 +24461,8 @@ var require_dist_cjs65 = __commonJS({
24350
24461
  return smithyClient.take(input, {
24351
24462
  input: (_2) => se_Document(_2),
24352
24463
  name: [],
24353
- toolUseId: []
24464
+ toolUseId: [],
24465
+ type: []
24354
24466
  });
24355
24467
  };
24356
24468
  var se_VideoBlock = (input, context) => {
@@ -24458,6 +24570,11 @@ var require_dist_cjs65 = __commonJS({
24458
24570
  if (smithyClient.expectString(output.text) !== void 0) {
24459
24571
  return { text: smithyClient.expectString(output.text) };
24460
24572
  }
24573
+ if (output.toolResult != null) {
24574
+ return {
24575
+ toolResult: smithyClient._json(output.toolResult)
24576
+ };
24577
+ }
24461
24578
  if (output.toolUse != null) {
24462
24579
  return {
24463
24580
  toolUse: smithyClient._json(output.toolUse)
@@ -24803,7 +24920,8 @@ var require_dist_cjs65 = __commonJS({
24803
24920
  return smithyClient.take(output, {
24804
24921
  content: (_2) => de_ToolResultContentBlocks(_2, context),
24805
24922
  status: smithyClient.expectString,
24806
- toolUseId: smithyClient.expectString
24923
+ toolUseId: smithyClient.expectString,
24924
+ type: smithyClient.expectString
24807
24925
  });
24808
24926
  };
24809
24927
  var de_ToolResultContentBlock = (output, context) => {
@@ -24842,7 +24960,8 @@ var require_dist_cjs65 = __commonJS({
24842
24960
  return smithyClient.take(output, {
24843
24961
  input: (_2) => de_Document(_2),
24844
24962
  name: smithyClient.expectString,
24845
- toolUseId: smithyClient.expectString
24963
+ toolUseId: smithyClient.expectString,
24964
+ type: smithyClient.expectString
24846
24965
  });
24847
24966
  };
24848
24967
  var de_VideoBlock = (output, context) => {
@@ -25124,6 +25243,7 @@ var require_dist_cjs65 = __commonJS({
25124
25243
  exports2.SystemContentBlockFilterSensitiveLog = SystemContentBlockFilterSensitiveLog;
25125
25244
  exports2.ThrottlingException = ThrottlingException;
25126
25245
  exports2.ToolResultStatus = ToolResultStatus;
25246
+ exports2.ToolUseType = ToolUseType;
25127
25247
  exports2.Trace = Trace;
25128
25248
  exports2.ValidationException = ValidationException;
25129
25249
  exports2.VideoFormat = VideoFormat;
@@ -25143,16 +25263,16 @@ function prepareTools(mode) {
25143
25263
  }
25144
25264
  const toolWarnings = [];
25145
25265
  const bedrockTools = [];
25146
- for (const tool3 of tools2) {
25147
- if (tool3.type === "provider-defined") {
25148
- toolWarnings.push({ type: "unsupported-tool", tool: tool3 });
25266
+ for (const tool4 of tools2) {
25267
+ if (tool4.type === "provider-defined") {
25268
+ toolWarnings.push({ type: "unsupported-tool", tool: tool4 });
25149
25269
  } else {
25150
25270
  bedrockTools.push({
25151
25271
  toolSpec: {
25152
- name: tool3.name,
25153
- description: tool3.description,
25272
+ name: tool4.name,
25273
+ description: tool4.description,
25154
25274
  inputSchema: {
25155
- json: tool3.parameters
25275
+ json: tool4.parameters
25156
25276
  }
25157
25277
  }
25158
25278
  });
@@ -27643,6 +27763,28 @@ var init_directory_resolver = __esm({
27643
27763
  });
27644
27764
 
27645
27765
  // src/downloader.js
27766
+ function sanitizeError(err) {
27767
+ try {
27768
+ const status = err?.response?.status;
27769
+ const statusText = err?.response?.statusText;
27770
+ const url = err?.config?.url || err?.response?.config?.url;
27771
+ const code = err?.code;
27772
+ const serverMsg = typeof err?.response?.data === "string" ? err.response.data.slice(0, 500) : typeof err?.response?.data?.message === "string" ? err.response.data.message : void 0;
27773
+ const base = err?.message || String(err);
27774
+ const parts = [base];
27775
+ if (status || statusText) parts.push(`[${status ?? ""} ${statusText ?? ""}]`.trim());
27776
+ if (code) parts.push(`code=${code}`);
27777
+ if (url) parts.push(`url=${url}`);
27778
+ if (serverMsg) parts.push(`server="${String(serverMsg).replace(/\s+/g, " ").trim()}"`);
27779
+ const e3 = new Error(parts.filter(Boolean).join(" "));
27780
+ if (status) e3.status = status;
27781
+ if (code) e3.code = code;
27782
+ if (url) e3.url = url;
27783
+ return e3;
27784
+ } catch (_2) {
27785
+ return new Error(err?.message || String(err));
27786
+ }
27787
+ }
27646
27788
  async function acquireFileLock(lockPath, version) {
27647
27789
  const lockData = {
27648
27790
  version,
@@ -27735,7 +27877,7 @@ async function waitForFileLock(lockPath, binaryPath) {
27735
27877
  }
27736
27878
  } catch {
27737
27879
  }
27738
- await new Promise((resolve4) => setTimeout(resolve4, LOCK_POLL_INTERVAL_MS));
27880
+ await new Promise((resolve5) => setTimeout(resolve5, LOCK_POLL_INTERVAL_MS));
27739
27881
  }
27740
27882
  if (process.env.DEBUG === "1" || process.env.VERBOSE === "1") {
27741
27883
  console.log(`Timeout waiting for file lock`);
@@ -27791,7 +27933,7 @@ function detectOsArch() {
27791
27933
  case "linux":
27792
27934
  osInfo = {
27793
27935
  type: "linux",
27794
- keywords: ["linux", "Linux", "gnu"]
27936
+ keywords: ["linux", "Linux", "musl", "gnu"]
27795
27937
  };
27796
27938
  break;
27797
27939
  case "darwin":
@@ -27835,7 +27977,7 @@ function constructAssetInfo(version, osInfo, archInfo) {
27835
27977
  let extension;
27836
27978
  switch (osInfo.type) {
27837
27979
  case "linux":
27838
- platform = `${archInfo.type}-unknown-linux-gnu`;
27980
+ platform = `${archInfo.type}-unknown-linux-musl`;
27839
27981
  extension = "tar.gz";
27840
27982
  break;
27841
27983
  case "darwin":
@@ -27952,7 +28094,7 @@ async function getLatestRelease(version) {
27952
28094
  }
27953
28095
  return { tag: tag2, assets };
27954
28096
  }
27955
- throw error2;
28097
+ throw sanitizeError(error2);
27956
28098
  }
27957
28099
  }
27958
28100
  function findBestAsset(assets, osInfo, archInfo) {
@@ -28166,7 +28308,7 @@ async function extractBinary(assetPath, outputDir) {
28166
28308
  return binaryPath;
28167
28309
  } catch (error2) {
28168
28310
  console.error(`Error extracting binary: ${error2 instanceof Error ? error2.message : String(error2)}`);
28169
- throw error2;
28311
+ throw sanitizeError(error2);
28170
28312
  }
28171
28313
  }
28172
28314
  async function getVersionInfo(binDir) {
@@ -28331,8 +28473,8 @@ async function downloadProbeBinary(version) {
28331
28473
  }
28332
28474
  return await withDownloadLock(version, () => doDownload(version));
28333
28475
  } catch (error2) {
28334
- console.error("Error downloading probe binary:", error2);
28335
- throw error2;
28476
+ console.error("Error downloading probe binary:", error2?.message || String(error2));
28477
+ throw sanitizeError(error2);
28336
28478
  }
28337
28479
  }
28338
28480
  var import_axios, import_fs_extra2, import_path2, import_crypto, import_util3, import_child_process, import_tar, import_os2, import_url2, exec, REPO_OWNER, REPO_NAME, BINARY_NAME, __filename2, __dirname2, downloadLocks, LOCK_TIMEOUT_MS, LOCK_POLL_INTERVAL_MS, MAX_LOCK_WAIT_MS;
@@ -28375,9 +28517,15 @@ async function getBinaryPath(options = {}) {
28375
28517
  probeBinaryPath = await downloadProbeBinary(version);
28376
28518
  return probeBinaryPath;
28377
28519
  }
28378
- const binDir = await getPackageBinDir();
28379
28520
  const isWindows = process.platform === "win32";
28380
28521
  const binaryName = isWindows ? "probe.exe" : "probe-binary";
28522
+ const localPackageBin = import_path3.default.resolve(__dirname3, "..", "bin");
28523
+ const localBinaryPath = import_path3.default.join(localPackageBin, binaryName);
28524
+ if (import_fs_extra3.default.existsSync(localBinaryPath) && !forceDownload) {
28525
+ probeBinaryPath = localBinaryPath;
28526
+ return probeBinaryPath;
28527
+ }
28528
+ const binDir = await getPackageBinDir();
28381
28529
  const binaryPath = import_path3.default.join(binDir, binaryName);
28382
28530
  if (import_fs_extra3.default.existsSync(binaryPath) && !forceDownload) {
28383
28531
  probeBinaryPath = binaryPath;
@@ -28707,7 +28855,7 @@ Command: ${command}`;
28707
28855
  }
28708
28856
  }
28709
28857
  function extractWithStdin(binaryPath, cliArgs, content, options) {
28710
- return new Promise((resolve4, reject2) => {
28858
+ return new Promise((resolve5, reject2) => {
28711
28859
  const childProcess = (0, import_child_process4.spawn)(binaryPath, ["extract", ...cliArgs], {
28712
28860
  stdio: ["pipe", "pipe", "pipe"]
28713
28861
  });
@@ -28729,7 +28877,7 @@ function extractWithStdin(binaryPath, cliArgs, content, options) {
28729
28877
  }
28730
28878
  try {
28731
28879
  const result = processExtractOutput(stdout, options);
28732
- resolve4(result);
28880
+ resolve5(result);
28733
28881
  } catch (error2) {
28734
28882
  reject2(error2);
28735
28883
  }
@@ -28822,6 +28970,262 @@ var init_grep = __esm({
28822
28970
  }
28823
28971
  });
28824
28972
 
28973
+ // src/delegate.js
28974
+ async function delegate({
28975
+ task,
28976
+ timeout = 300,
28977
+ debug = false,
28978
+ currentIteration = 0,
28979
+ maxIterations = 30,
28980
+ tracer = null,
28981
+ parentSessionId = null,
28982
+ path: path7 = null,
28983
+ provider = null,
28984
+ model = null
28985
+ }) {
28986
+ if (!task || typeof task !== "string") {
28987
+ throw new Error("Task parameter is required and must be a string");
28988
+ }
28989
+ const sessionId = (0, import_crypto2.randomUUID)();
28990
+ const startTime = Date.now();
28991
+ const remainingIterations = Math.max(1, maxIterations - currentIteration);
28992
+ const delegationSpan = tracer ? tracer.createDelegationSpan(sessionId, task) : null;
28993
+ let timeoutId = null;
28994
+ let acquired = false;
28995
+ try {
28996
+ delegationManager.tryAcquire(parentSessionId);
28997
+ acquired = true;
28998
+ if (debug) {
28999
+ const stats = delegationManager.getStats();
29000
+ console.error(`[DELEGATE] Starting delegation session ${sessionId}`);
29001
+ console.error(`[DELEGATE] Parent session: ${parentSessionId || "none"}`);
29002
+ console.error(`[DELEGATE] Task: ${task}`);
29003
+ console.error(`[DELEGATE] Current iteration: ${currentIteration}/${maxIterations}`);
29004
+ console.error(`[DELEGATE] Remaining iterations for subagent: ${remainingIterations}`);
29005
+ console.error(`[DELEGATE] Timeout configured: ${timeout} seconds`);
29006
+ console.error(`[DELEGATE] Global active delegations: ${stats.globalActive}/${stats.maxConcurrent}`);
29007
+ console.error(`[DELEGATE] Using ProbeAgent SDK with code-researcher prompt`);
29008
+ }
29009
+ const subagent = new ProbeAgent({
29010
+ sessionId,
29011
+ promptType: "code-researcher",
29012
+ // Clean prompt, not inherited from parent
29013
+ enableDelegate: false,
29014
+ // Explicitly disable delegation to prevent recursion
29015
+ disableMermaidValidation: true,
29016
+ // Faster processing
29017
+ disableJsonValidation: true,
29018
+ // Simpler responses
29019
+ maxIterations: remainingIterations,
29020
+ debug,
29021
+ tracer,
29022
+ path: path7,
29023
+ // Inherit from parent
29024
+ provider,
29025
+ // Inherit from parent
29026
+ model
29027
+ // Inherit from parent
29028
+ });
29029
+ if (debug) {
29030
+ console.error(`[DELEGATE] Created subagent with session ${sessionId}`);
29031
+ console.error(`[DELEGATE] Subagent config: promptType=code-researcher, enableDelegate=false, maxIterations=${remainingIterations}`);
29032
+ }
29033
+ const timeoutPromise = new Promise((_2, reject2) => {
29034
+ timeoutId = setTimeout(() => {
29035
+ reject2(new Error(`Delegation timed out after ${timeout} seconds`));
29036
+ }, timeout * 1e3);
29037
+ });
29038
+ const answerPromise = subagent.answer(task);
29039
+ const response = await Promise.race([answerPromise, timeoutPromise]);
29040
+ if (timeoutId !== null) {
29041
+ clearTimeout(timeoutId);
29042
+ timeoutId = null;
29043
+ }
29044
+ const duration = Date.now() - startTime;
29045
+ if (typeof response !== "string") {
29046
+ throw new Error("Delegate agent returned invalid response (not a string)");
29047
+ }
29048
+ const trimmedResponse = response.trim();
29049
+ if (trimmedResponse.length === 0) {
29050
+ throw new Error("Delegate agent returned empty or whitespace-only response");
29051
+ }
29052
+ if (trimmedResponse.includes("\0")) {
29053
+ throw new Error("Delegate agent returned response containing null bytes");
29054
+ }
29055
+ if (debug) {
29056
+ console.error(`[DELEGATE] Task completed successfully for session ${sessionId}`);
29057
+ console.error(`[DELEGATE] Duration: ${(duration / 1e3).toFixed(2)}s`);
29058
+ console.error(`[DELEGATE] Response length: ${response.length} chars`);
29059
+ }
29060
+ if (tracer) {
29061
+ tracer.recordDelegationEvent("completed", {
29062
+ "delegation.session_id": sessionId,
29063
+ "delegation.parent_session_id": parentSessionId,
29064
+ "delegation.duration_ms": duration,
29065
+ "delegation.response_length": response.length,
29066
+ "delegation.success": true
29067
+ });
29068
+ if (delegationSpan) {
29069
+ delegationSpan.setAttributes({
29070
+ "delegation.result.success": true,
29071
+ "delegation.result.response_length": response.length,
29072
+ "delegation.result.duration_ms": duration
29073
+ });
29074
+ delegationSpan.setStatus({ code: 1 });
29075
+ delegationSpan.end();
29076
+ }
29077
+ }
29078
+ if (acquired) {
29079
+ delegationManager.release(parentSessionId, debug);
29080
+ }
29081
+ return response;
29082
+ } catch (error2) {
29083
+ if (timeoutId !== null) {
29084
+ clearTimeout(timeoutId);
29085
+ timeoutId = null;
29086
+ }
29087
+ const duration = Date.now() - startTime;
29088
+ if (acquired) {
29089
+ delegationManager.release(parentSessionId, debug);
29090
+ }
29091
+ if (debug) {
29092
+ console.error(`[DELEGATE] Task failed for session ${sessionId} after ${duration}ms`);
29093
+ console.error(`[DELEGATE] Error: ${error2.message}`);
29094
+ console.error(`[DELEGATE] Stack: ${error2.stack}`);
29095
+ }
29096
+ if (tracer) {
29097
+ tracer.recordDelegationEvent("failed", {
29098
+ "delegation.session_id": sessionId,
29099
+ "delegation.parent_session_id": parentSessionId,
29100
+ "delegation.duration_ms": duration,
29101
+ "delegation.error_message": error2.message,
29102
+ "delegation.success": false
29103
+ });
29104
+ if (delegationSpan) {
29105
+ delegationSpan.setAttributes({
29106
+ "delegation.result.success": false,
29107
+ "delegation.result.error": error2.message,
29108
+ "delegation.result.duration_ms": duration
29109
+ });
29110
+ delegationSpan.setStatus({ code: 2, message: error2.message });
29111
+ delegationSpan.end();
29112
+ }
29113
+ }
29114
+ throw new Error(`Delegation failed: ${error2.message}`);
29115
+ }
29116
+ }
29117
+ var import_crypto2, DelegationManager, delegationManager;
29118
+ var init_delegate = __esm({
29119
+ "src/delegate.js"() {
29120
+ "use strict";
29121
+ import_crypto2 = require("crypto");
29122
+ init_ProbeAgent();
29123
+ DelegationManager = class {
29124
+ constructor() {
29125
+ this.maxConcurrent = parseInt(process.env.MAX_CONCURRENT_DELEGATIONS || "3", 10);
29126
+ this.maxPerSession = parseInt(process.env.MAX_DELEGATIONS_PER_SESSION || "10", 10);
29127
+ this.sessionDelegations = /* @__PURE__ */ new Map();
29128
+ this.globalActive = 0;
29129
+ this.cleanupInterval = setInterval(() => {
29130
+ try {
29131
+ this.cleanupStaleSessions();
29132
+ } catch (error2) {
29133
+ console.error("[DelegationManager] Error during cleanup:", error2);
29134
+ }
29135
+ }, 5 * 60 * 1e3);
29136
+ if (this.cleanupInterval.unref) {
29137
+ this.cleanupInterval.unref();
29138
+ }
29139
+ }
29140
+ /**
29141
+ * Check limits and increment counters (synchronous, atomic in Node.js event loop)
29142
+ * @param {string|null|undefined} parentSessionId - Parent session ID for tracking
29143
+ */
29144
+ tryAcquire(parentSessionId) {
29145
+ if (parentSessionId !== null && parentSessionId !== void 0 && typeof parentSessionId !== "string") {
29146
+ throw new TypeError("parentSessionId must be a string, null, or undefined");
29147
+ }
29148
+ if (this.globalActive >= this.maxConcurrent) {
29149
+ throw new Error(`Maximum concurrent delegations (${this.maxConcurrent}) reached. Please wait for some delegations to complete.`);
29150
+ }
29151
+ if (parentSessionId) {
29152
+ const sessionData = this.sessionDelegations.get(parentSessionId);
29153
+ const sessionCount = sessionData?.count || 0;
29154
+ if (sessionCount >= this.maxPerSession) {
29155
+ throw new Error(`Maximum delegations per session (${this.maxPerSession}) reached for session ${parentSessionId}`);
29156
+ }
29157
+ }
29158
+ this.globalActive++;
29159
+ if (parentSessionId) {
29160
+ const sessionData = this.sessionDelegations.get(parentSessionId);
29161
+ if (sessionData) {
29162
+ sessionData.count++;
29163
+ sessionData.lastUpdated = Date.now();
29164
+ } else {
29165
+ this.sessionDelegations.set(parentSessionId, {
29166
+ count: 1,
29167
+ lastUpdated: Date.now()
29168
+ });
29169
+ }
29170
+ }
29171
+ return true;
29172
+ }
29173
+ /**
29174
+ * Decrement counters (synchronous, atomic in Node.js event loop)
29175
+ */
29176
+ release(parentSessionId, debug = false) {
29177
+ this.globalActive = Math.max(0, this.globalActive - 1);
29178
+ if (parentSessionId) {
29179
+ const sessionData = this.sessionDelegations.get(parentSessionId);
29180
+ if (sessionData) {
29181
+ sessionData.count = Math.max(0, sessionData.count - 1);
29182
+ if (sessionData.count === 0) {
29183
+ this.sessionDelegations.delete(parentSessionId);
29184
+ }
29185
+ }
29186
+ }
29187
+ if (debug) {
29188
+ console.error(`[DELEGATE] Released. Global active: ${this.globalActive}`);
29189
+ }
29190
+ }
29191
+ /**
29192
+ * Get current stats for monitoring
29193
+ */
29194
+ getStats() {
29195
+ return {
29196
+ globalActive: this.globalActive,
29197
+ maxConcurrent: this.maxConcurrent,
29198
+ maxPerSession: this.maxPerSession,
29199
+ sessionCount: this.sessionDelegations.size
29200
+ };
29201
+ }
29202
+ /**
29203
+ * Clean up stale sessions (sessions with count=0 that haven't been updated in 1 hour)
29204
+ */
29205
+ cleanupStaleSessions() {
29206
+ const oneHourAgo = Date.now() - 60 * 60 * 1e3;
29207
+ for (const [sessionId, data2] of this.sessionDelegations.entries()) {
29208
+ if (data2.count === 0 && data2.lastUpdated < oneHourAgo) {
29209
+ this.sessionDelegations.delete(sessionId);
29210
+ }
29211
+ }
29212
+ }
29213
+ /**
29214
+ * Cleanup all resources (for testing or shutdown)
29215
+ */
29216
+ cleanup() {
29217
+ if (this.cleanupInterval) {
29218
+ clearInterval(this.cleanupInterval);
29219
+ this.cleanupInterval = null;
29220
+ }
29221
+ this.sessionDelegations.clear();
29222
+ this.globalActive = 0;
29223
+ }
29224
+ };
29225
+ delegationManager = new DelegationManager();
29226
+ }
29227
+ });
29228
+
28825
29229
  // node_modules/zod/v3/helpers/util.js
28826
29230
  var util, objectUtil, ZodParsedType, getParsedType;
28827
29231
  var init_util2 = __esm({
@@ -33035,7 +33439,7 @@ function parseTargets(targets) {
33035
33439
  }
33036
33440
  return targets.split(/\s+/).filter((f3) => f3.length > 0);
33037
33441
  }
33038
- var searchSchema, querySchema, extractSchema, delegateSchema, bashSchema, attemptCompletionSchema, searchToolDefinition, queryToolDefinition, extractToolDefinition, attemptCompletionToolDefinition, searchDescription, queryDescription, extractDescription, delegateDescription, DEFAULT_VALID_TOOLS;
33442
+ var searchSchema, querySchema, extractSchema, delegateSchema, bashSchema, attemptCompletionSchema, searchToolDefinition, queryToolDefinition, extractToolDefinition, delegateToolDefinition, attemptCompletionToolDefinition, bashToolDefinition, searchDescription, queryDescription, extractDescription, delegateDescription, DEFAULT_VALID_TOOLS;
33039
33443
  var init_common2 = __esm({
33040
33444
  "src/tools/common.js"() {
33041
33445
  "use strict";
@@ -33048,11 +33452,12 @@ var init_common2 = __esm({
33048
33452
  pattern: external_exports.string().describe("AST pattern to search for. Use $NAME for variable names, $$$PARAMS for parameter lists, etc."),
33049
33453
  path: external_exports.string().optional().default(".").describe("Path to search in"),
33050
33454
  language: external_exports.string().optional().default("rust").describe("Programming language to use for parsing"),
33051
- allow_tests: external_exports.boolean().optional().default(false).describe("Allow test files in search results")
33455
+ allow_tests: external_exports.boolean().optional().default(true).describe("Allow test files in search results")
33052
33456
  });
33053
33457
  extractSchema = external_exports.object({
33054
33458
  targets: external_exports.string().optional().describe('File paths or symbols to extract from. Formats: "file.js" (whole file), "file.js:42" (line 42), "file.js:10-20" (lines 10-20), "file.js#funcName" (symbol). Multiple targets separated by spaces.'),
33055
- input_content: external_exports.string().optional().describe("Text content to extract file paths from (alternative to targets)")
33459
+ input_content: external_exports.string().optional().describe("Text content to extract file paths from (alternative to targets)"),
33460
+ allow_tests: external_exports.boolean().optional().default(true).describe("Include test files in extraction results")
33056
33461
  });
33057
33462
  delegateSchema = external_exports.object({
33058
33463
  task: external_exports.string().describe("The task to delegate to a subagent. Be specific about what needs to be accomplished.")
@@ -33179,7 +33584,7 @@ Parameters:
33179
33584
  - pattern: (required) AST pattern to search for. Use $NAME for variable names, $$$PARAMS for parameter lists, etc.
33180
33585
  - path: (optional, default: '.') Path to search in.
33181
33586
  - language: (optional, default: 'rust') Programming language to use for parsing.
33182
- - allow_tests: (optional, default: false) Allow test files in search results (true/false).
33587
+ - allow_tests: (optional, default: true) Allow test files in search results (true/false).
33183
33588
  Usage Example:
33184
33589
 
33185
33590
  <examples>
@@ -33204,6 +33609,7 @@ Full file extraction should be the LAST RESORT! Always prefer search.
33204
33609
  Parameters:
33205
33610
  - targets: (required) File paths or symbols to extract from. Formats: "file.js" (whole file), "file.js:42" (code block at line 42), "file.js:10-20" (lines 10-20), "file.js#funcName" (specific symbol). Multiple targets separated by spaces.
33206
33611
  - input_content: (optional) Text content to extract file paths from (alternative to targets for processing diffs/logs).
33612
+ - allow_tests: (optional, default: true) Include test files in extraction results.
33207
33613
 
33208
33614
  Usage Example:
33209
33615
 
@@ -33240,6 +33646,26 @@ User: Read file inside the dependency
33240
33646
  </extract>
33241
33647
 
33242
33648
  </examples>
33649
+ `;
33650
+ delegateToolDefinition = `
33651
+ ## delegate
33652
+ Description: Automatically delegate big distinct tasks to specialized probe subagents within the agentic loop. Use this when you recognize that a user's request involves multiple large, distinct components that would benefit from parallel processing or specialized focus. The AI agent should automatically identify opportunities for task separation and use delegation without explicit user instruction.
33653
+
33654
+ Parameters:
33655
+ - task: (required) A complete, self-contained task that can be executed independently by a subagent. Should be specific and focused on one area of expertise.
33656
+
33657
+ Usage Pattern:
33658
+ When the AI agent encounters complex multi-part requests, it should automatically break them down and delegate:
33659
+
33660
+ <delegate>
33661
+ <task>Analyze all authentication and authorization code in the codebase for security vulnerabilities and provide specific remediation recommendations</task>
33662
+ </delegate>
33663
+
33664
+ <delegate>
33665
+ <task>Review database queries and API endpoints for performance bottlenecks and suggest optimization strategies</task>
33666
+ </delegate>
33667
+
33668
+ The agent uses this tool automatically when it identifies that work can be separated into distinct, parallel tasks for more efficient processing.
33243
33669
  `;
33244
33670
  attemptCompletionToolDefinition = `
33245
33671
  ## attempt_completion
@@ -33250,6 +33676,61 @@ Usage Example:
33250
33676
  <attempt_completion>
33251
33677
  I have refactored the search module according to the requirements and verified the tests pass. The module now uses the new BM25 ranking algorithm and has improved error handling.
33252
33678
  </attempt_completion>
33679
+ `;
33680
+ bashToolDefinition = `
33681
+ ## bash
33682
+ Description: Execute bash commands for system exploration and development tasks. This tool has built-in security with allow/deny lists. By default, only safe read-only commands are allowed for code exploration.
33683
+
33684
+ Parameters:
33685
+ - command: (required) The bash command to execute
33686
+ - workingDirectory: (optional) Directory to execute the command in
33687
+ - timeout: (optional) Command timeout in milliseconds
33688
+ - env: (optional) Additional environment variables as an object
33689
+
33690
+ Security: Commands are filtered through allow/deny lists for safety:
33691
+ - Allowed by default: ls, cat, git status, npm list, find, grep, etc.
33692
+ - Denied by default: rm -rf, sudo, npm install, dangerous system commands
33693
+
33694
+ Usage Examples:
33695
+
33696
+ <examples>
33697
+
33698
+ User: What files are in the src directory?
33699
+ <bash>
33700
+ <command>ls -la src/</command>
33701
+ </bash>
33702
+
33703
+ User: Show me the git status
33704
+ <bash>
33705
+ <command>git status</command>
33706
+ </bash>
33707
+
33708
+ User: Find all TypeScript files
33709
+ <bash>
33710
+ <command>find . -name "*.ts" -type f</command>
33711
+ </bash>
33712
+
33713
+ User: Check installed npm packages
33714
+ <bash>
33715
+ <command>npm list --depth=0</command>
33716
+ </bash>
33717
+
33718
+ User: Search for TODO comments in code
33719
+ <bash>
33720
+ <command>grep -r "TODO" src/</command>
33721
+ </bash>
33722
+
33723
+ User: Show recent git commits
33724
+ <bash>
33725
+ <command>git log --oneline -10</command>
33726
+ </bash>
33727
+
33728
+ User: Check system info
33729
+ <bash>
33730
+ <command>uname -a</command>
33731
+ </bash>
33732
+
33733
+ </examples>
33253
33734
  `;
33254
33735
  searchDescription = "Search code in the repository using Elasticsearch-like query syntax. Use this tool first for any code-related questions.";
33255
33736
  queryDescription = "Search code using ast-grep structural pattern matching. Use this tool to find specific code structures like functions, classes, or methods.";
@@ -33268,194 +33749,6 @@ I have refactored the search module according to the requirements and verified t
33268
33749
  }
33269
33750
  });
33270
33751
 
33271
- // src/delegate.js
33272
- async function delegate({ task, timeout = 300, debug = false, currentIteration = 0, maxIterations = 30, tracer = null }) {
33273
- if (!task || typeof task !== "string") {
33274
- throw new Error("Task parameter is required and must be a string");
33275
- }
33276
- const sessionId = (0, import_crypto2.randomUUID)();
33277
- const startTime = Date.now();
33278
- const remainingIterations = Math.max(1, maxIterations - currentIteration);
33279
- if (debug) {
33280
- console.error(`[DELEGATE] Starting delegation session ${sessionId}`);
33281
- console.error(`[DELEGATE] Task: ${task}`);
33282
- console.error(`[DELEGATE] Current iteration: ${currentIteration}/${maxIterations}`);
33283
- console.error(`[DELEGATE] Remaining iterations for subagent: ${remainingIterations}`);
33284
- console.error(`[DELEGATE] Timeout configured: ${timeout} seconds`);
33285
- console.error(`[DELEGATE] Using clean agent environment with code-researcher prompt`);
33286
- }
33287
- try {
33288
- const binaryPath = await getBinaryPath();
33289
- const args = [
33290
- "agent",
33291
- "--task",
33292
- task,
33293
- "--session-id",
33294
- sessionId,
33295
- "--prompt-type",
33296
- "code-researcher",
33297
- // Automatically use default code researcher prompt
33298
- "--no-schema-validation",
33299
- // Automatically disable schema validation
33300
- "--no-mermaid-validation",
33301
- // Automatically disable mermaid validation
33302
- "--max-iterations",
33303
- remainingIterations.toString()
33304
- // Automatically limit to remaining iterations
33305
- ];
33306
- if (debug) {
33307
- args.push("--debug");
33308
- console.error(`[DELEGATE] Using binary at: ${binaryPath}`);
33309
- console.error(`[DELEGATE] Command args: ${args.join(" ")}`);
33310
- }
33311
- return new Promise((resolve4, reject2) => {
33312
- const delegationSpan = tracer ? tracer.createDelegationSpan(sessionId, task) : null;
33313
- const process2 = (0, import_child_process6.spawn)(binaryPath, args, {
33314
- stdio: ["pipe", "pipe", "pipe"],
33315
- timeout: timeout * 1e3
33316
- });
33317
- let stdout = "";
33318
- let stderr = "";
33319
- let isResolved = false;
33320
- process2.stdout.on("data", (data2) => {
33321
- const chunk = data2.toString();
33322
- stdout += chunk;
33323
- if (debug) {
33324
- const preview = createMessagePreview(chunk);
33325
- console.error(`[DELEGATE] stdout chunk received (${chunk.length} chars): ${preview}`);
33326
- }
33327
- });
33328
- process2.stderr.on("data", (data2) => {
33329
- const chunk = data2.toString();
33330
- stderr += chunk;
33331
- if (debug) {
33332
- const preview = createMessagePreview(chunk);
33333
- console.error(`[DELEGATE] stderr chunk received (${chunk.length} chars): ${preview}`);
33334
- }
33335
- });
33336
- process2.on("close", (code) => {
33337
- if (isResolved) return;
33338
- isResolved = true;
33339
- const duration = Date.now() - startTime;
33340
- if (debug) {
33341
- console.error(`[DELEGATE] Process completed with code ${code} in ${duration}ms`);
33342
- console.error(`[DELEGATE] Duration: ${(duration / 1e3).toFixed(2)}s`);
33343
- console.error(`[DELEGATE] Total stdout: ${stdout.length} chars`);
33344
- console.error(`[DELEGATE] Total stderr: ${stderr.length} chars`);
33345
- }
33346
- if (code === 0) {
33347
- const response = stdout.trim();
33348
- if (!response) {
33349
- if (debug) {
33350
- console.error(`[DELEGATE] Task completed but returned empty response for session ${sessionId}`);
33351
- }
33352
- reject2(new Error("Delegate agent returned empty response"));
33353
- return;
33354
- }
33355
- if (debug) {
33356
- console.error(`[DELEGATE] Task completed successfully for session ${sessionId}`);
33357
- console.error(`[DELEGATE] Response length: ${response.length} chars`);
33358
- }
33359
- if (tracer) {
33360
- tracer.recordDelegationEvent("completed", {
33361
- "delegation.session_id": sessionId,
33362
- "delegation.duration_ms": duration,
33363
- "delegation.response_length": response.length,
33364
- "delegation.success": true
33365
- });
33366
- if (delegationSpan) {
33367
- delegationSpan.setAttributes({
33368
- "delegation.result.success": true,
33369
- "delegation.result.response_length": response.length,
33370
- "delegation.result.duration_ms": duration
33371
- });
33372
- delegationSpan.setStatus({ code: 1 });
33373
- delegationSpan.end();
33374
- }
33375
- }
33376
- resolve4(response);
33377
- } else {
33378
- const errorMessage = stderr.trim() || `Delegate process failed with exit code ${code}`;
33379
- if (debug) {
33380
- console.error(`[DELEGATE] Task failed for session ${sessionId} with code ${code}`);
33381
- console.error(`[DELEGATE] Error message: ${errorMessage}`);
33382
- }
33383
- if (tracer) {
33384
- tracer.recordDelegationEvent("failed", {
33385
- "delegation.session_id": sessionId,
33386
- "delegation.duration_ms": duration,
33387
- "delegation.exit_code": code,
33388
- "delegation.error_message": errorMessage,
33389
- "delegation.success": false
33390
- });
33391
- if (delegationSpan) {
33392
- delegationSpan.setAttributes({
33393
- "delegation.result.success": false,
33394
- "delegation.result.exit_code": code,
33395
- "delegation.result.error": errorMessage,
33396
- "delegation.result.duration_ms": duration
33397
- });
33398
- delegationSpan.setStatus({ code: 2, message: errorMessage });
33399
- delegationSpan.end();
33400
- }
33401
- }
33402
- reject2(new Error(`Delegation failed: ${errorMessage}`));
33403
- }
33404
- });
33405
- process2.on("error", (error2) => {
33406
- if (isResolved) return;
33407
- isResolved = true;
33408
- const duration = Date.now() - startTime;
33409
- if (debug) {
33410
- console.error(`[DELEGATE] Process spawn error after ${duration}ms:`, error2);
33411
- console.error(`[DELEGATE] Session ${sessionId} failed during process creation`);
33412
- console.error(`[DELEGATE] Error type: ${error2.code || "unknown"}`);
33413
- }
33414
- reject2(new Error(`Failed to start delegate process: ${error2.message}`));
33415
- });
33416
- setTimeout(() => {
33417
- if (isResolved) return;
33418
- isResolved = true;
33419
- const duration = Date.now() - startTime;
33420
- if (debug) {
33421
- console.error(`[DELEGATE] Process timeout after ${(duration / 1e3).toFixed(2)}s (limit: ${timeout}s)`);
33422
- console.error(`[DELEGATE] Terminating session ${sessionId} due to timeout`);
33423
- console.error(`[DELEGATE] Partial stdout: ${stdout.substring(0, 500)}${stdout.length > 500 ? "..." : ""}`);
33424
- console.error(`[DELEGATE] Partial stderr: ${stderr.substring(0, 500)}${stderr.length > 500 ? "..." : ""}`);
33425
- }
33426
- process2.kill("SIGTERM");
33427
- setTimeout(() => {
33428
- if (!process2.killed) {
33429
- if (debug) {
33430
- console.error(`[DELEGATE] Force killing process ${sessionId} after graceful timeout`);
33431
- }
33432
- process2.kill("SIGKILL");
33433
- }
33434
- }, 5e3);
33435
- reject2(new Error(`Delegation timed out after ${timeout} seconds`));
33436
- }, timeout * 1e3);
33437
- });
33438
- } catch (error2) {
33439
- const duration = Date.now() - startTime;
33440
- if (debug) {
33441
- console.error(`[DELEGATE] Error in delegate function after ${duration}ms:`, error2);
33442
- console.error(`[DELEGATE] Session ${sessionId} failed during setup`);
33443
- console.error(`[DELEGATE] Error stack: ${error2.stack}`);
33444
- }
33445
- throw new Error(`Delegation setup failed: ${error2.message}`);
33446
- }
33447
- }
33448
- var import_child_process6, import_crypto2;
33449
- var init_delegate = __esm({
33450
- "src/delegate.js"() {
33451
- "use strict";
33452
- import_child_process6 = require("child_process");
33453
- import_crypto2 = require("crypto");
33454
- init_utils2();
33455
- init_common2();
33456
- }
33457
- });
33458
-
33459
33752
  // src/tools/vercel.js
33460
33753
  var import_ai, searchTool, queryTool, extractTool, delegateTool;
33461
33754
  var init_vercel = __esm({
@@ -33628,21 +33921,50 @@ var init_vercel = __esm({
33628
33921
  name: "delegate",
33629
33922
  description: delegateDescription,
33630
33923
  inputSchema: delegateSchema,
33631
- execute: async ({ task }) => {
33632
- try {
33633
- if (debug) {
33634
- console.error(`Executing delegate with task: "${task}"`);
33635
- }
33636
- const result = await delegate({
33637
- task,
33638
- timeout,
33639
- debug
33640
- });
33641
- return result;
33642
- } catch (error2) {
33643
- console.error("Error executing delegate command:", error2);
33644
- return `Error executing delegate command: ${error2.message}`;
33924
+ execute: async ({ task, currentIteration, maxIterations, parentSessionId, path: path7, provider, model, tracer }) => {
33925
+ if (!task || typeof task !== "string") {
33926
+ throw new Error("Task parameter is required and must be a non-empty string");
33927
+ }
33928
+ if (task.trim().length === 0) {
33929
+ throw new Error("Task parameter cannot be empty or whitespace only");
33930
+ }
33931
+ if (currentIteration !== void 0 && (typeof currentIteration !== "number" || currentIteration < 0)) {
33932
+ throw new Error("currentIteration must be a non-negative number");
33933
+ }
33934
+ if (maxIterations !== void 0 && (typeof maxIterations !== "number" || maxIterations < 1)) {
33935
+ throw new Error("maxIterations must be a positive number");
33936
+ }
33937
+ if (parentSessionId !== void 0 && parentSessionId !== null && typeof parentSessionId !== "string") {
33938
+ throw new TypeError("parentSessionId must be a string, null, or undefined");
33645
33939
  }
33940
+ if (path7 !== void 0 && path7 !== null && typeof path7 !== "string") {
33941
+ throw new TypeError("path must be a string, null, or undefined");
33942
+ }
33943
+ if (provider !== void 0 && provider !== null && typeof provider !== "string") {
33944
+ throw new TypeError("provider must be a string, null, or undefined");
33945
+ }
33946
+ if (model !== void 0 && model !== null && typeof model !== "string") {
33947
+ throw new TypeError("model must be a string, null, or undefined");
33948
+ }
33949
+ if (debug) {
33950
+ console.error(`Executing delegate with task: "${task.substring(0, 100)}${task.length > 100 ? "..." : ""}"`);
33951
+ if (parentSessionId) {
33952
+ console.error(`Parent session: ${parentSessionId}`);
33953
+ }
33954
+ }
33955
+ const result = await delegate({
33956
+ task,
33957
+ timeout,
33958
+ debug,
33959
+ currentIteration: currentIteration || 0,
33960
+ maxIterations: maxIterations || 30,
33961
+ parentSessionId,
33962
+ path: path7,
33963
+ provider,
33964
+ model,
33965
+ tracer
33966
+ });
33967
+ return result;
33646
33968
  }
33647
33969
  });
33648
33970
  };
@@ -34505,14 +34827,14 @@ async function executeBashCommand(command, options = {}) {
34505
34827
  console.log(`[BashExecutor] Working directory: "${cwd}"`);
34506
34828
  console.log(`[BashExecutor] Timeout: ${timeout}ms`);
34507
34829
  }
34508
- return new Promise((resolve4, reject2) => {
34830
+ return new Promise((resolve5, reject2) => {
34509
34831
  const processEnv = {
34510
34832
  ...process.env,
34511
34833
  ...env
34512
34834
  };
34513
34835
  const args = parseCommandForExecution(command);
34514
34836
  if (!args || args.length === 0) {
34515
- resolve4({
34837
+ resolve5({
34516
34838
  success: false,
34517
34839
  error: "Failed to parse command",
34518
34840
  stdout: "",
@@ -34525,7 +34847,7 @@ async function executeBashCommand(command, options = {}) {
34525
34847
  return;
34526
34848
  }
34527
34849
  const [cmd, ...cmdArgs] = args;
34528
- const child = (0, import_child_process7.spawn)(cmd, cmdArgs, {
34850
+ const child = (0, import_child_process6.spawn)(cmd, cmdArgs, {
34529
34851
  cwd,
34530
34852
  env: processEnv,
34531
34853
  stdio: ["ignore", "pipe", "pipe"],
@@ -34595,7 +34917,7 @@ async function executeBashCommand(command, options = {}) {
34595
34917
  success = false;
34596
34918
  error2 = `Command exited with code ${code}`;
34597
34919
  }
34598
- resolve4({
34920
+ resolve5({
34599
34921
  success,
34600
34922
  error: error2,
34601
34923
  stdout: stdout.trim(),
@@ -34615,7 +34937,7 @@ async function executeBashCommand(command, options = {}) {
34615
34937
  if (debug) {
34616
34938
  console.log(`[BashExecutor] Spawn error:`, error2);
34617
34939
  }
34618
- resolve4({
34940
+ resolve5({
34619
34941
  success: false,
34620
34942
  error: `Failed to execute command: ${error2.message}`,
34621
34943
  stdout: "",
@@ -34709,11 +35031,11 @@ function validateExecutionOptions(options = {}) {
34709
35031
  warnings
34710
35032
  };
34711
35033
  }
34712
- var import_child_process7, import_path4, import_fs;
35034
+ var import_child_process6, import_path4, import_fs;
34713
35035
  var init_bashExecutor = __esm({
34714
35036
  "src/agent/bashExecutor.js"() {
34715
35037
  "use strict";
34716
- import_child_process7 = require("child_process");
35038
+ import_child_process6 = require("child_process");
34717
35039
  import_path4 = require("path");
34718
35040
  import_fs = require("fs");
34719
35041
  init_bashCommandUtils();
@@ -34891,6 +35213,283 @@ Command failed with exit code ${result.exitCode}`;
34891
35213
  }
34892
35214
  });
34893
35215
 
35216
+ // src/tools/edit.js
35217
+ function isPathAllowed(filePath, allowedFolders) {
35218
+ if (!allowedFolders || allowedFolders.length === 0) {
35219
+ const resolvedPath3 = (0, import_path6.resolve)(filePath);
35220
+ const cwd = (0, import_path6.resolve)(process.cwd());
35221
+ return resolvedPath3 === cwd || resolvedPath3.startsWith(cwd + import_path6.sep);
35222
+ }
35223
+ const resolvedPath2 = (0, import_path6.resolve)(filePath);
35224
+ return allowedFolders.some((folder) => {
35225
+ const allowedPath = (0, import_path6.resolve)(folder);
35226
+ return resolvedPath2 === allowedPath || resolvedPath2.startsWith(allowedPath + import_path6.sep);
35227
+ });
35228
+ }
35229
+ function parseFileToolOptions(options = {}) {
35230
+ return {
35231
+ debug: options.debug || false,
35232
+ allowedFolders: options.allowedFolders || [],
35233
+ defaultPath: options.defaultPath
35234
+ };
35235
+ }
35236
+ var import_ai3, import_fs2, import_path6, import_fs3, editTool, createTool, editDescription, createDescription, editToolDefinition, createToolDefinition;
35237
+ var init_edit = __esm({
35238
+ "src/tools/edit.js"() {
35239
+ "use strict";
35240
+ import_ai3 = require("ai");
35241
+ import_fs2 = require("fs");
35242
+ import_path6 = require("path");
35243
+ import_fs3 = require("fs");
35244
+ editTool = (options = {}) => {
35245
+ const { debug, allowedFolders, defaultPath } = parseFileToolOptions(options);
35246
+ return (0, import_ai3.tool)({
35247
+ name: "edit",
35248
+ description: `Edit files using exact string replacement (Claude Code style).
35249
+
35250
+ This tool performs exact string replacements in files. It requires the old_string to match exactly what's in the file, including all whitespace and indentation.
35251
+
35252
+ Parameters:
35253
+ - file_path: Path to the file to edit (absolute or relative)
35254
+ - old_string: Exact text to find and replace (must be unique in the file unless replace_all is true)
35255
+ - new_string: Text to replace with
35256
+ - replace_all: (optional) Replace all occurrences instead of requiring uniqueness
35257
+
35258
+ Important:
35259
+ - The old_string must match EXACTLY including whitespace
35260
+ - If old_string appears multiple times and replace_all is false, the edit will fail
35261
+ - Use larger context around the string to ensure uniqueness when needed`,
35262
+ inputSchema: {
35263
+ type: "object",
35264
+ properties: {
35265
+ file_path: {
35266
+ type: "string",
35267
+ description: "Path to the file to edit"
35268
+ },
35269
+ old_string: {
35270
+ type: "string",
35271
+ description: "Exact text to find and replace"
35272
+ },
35273
+ new_string: {
35274
+ type: "string",
35275
+ description: "Text to replace with"
35276
+ },
35277
+ replace_all: {
35278
+ type: "boolean",
35279
+ description: "Replace all occurrences (default: false)",
35280
+ default: false
35281
+ }
35282
+ },
35283
+ required: ["file_path", "old_string", "new_string"]
35284
+ },
35285
+ execute: async ({ file_path, old_string, new_string, replace_all = false }) => {
35286
+ try {
35287
+ if (!file_path || typeof file_path !== "string" || file_path.trim() === "") {
35288
+ return `Error editing file: Invalid file_path - must be a non-empty string`;
35289
+ }
35290
+ if (old_string === void 0 || old_string === null || typeof old_string !== "string") {
35291
+ return `Error editing file: Invalid old_string - must be a string`;
35292
+ }
35293
+ if (new_string === void 0 || new_string === null || typeof new_string !== "string") {
35294
+ return `Error editing file: Invalid new_string - must be a string`;
35295
+ }
35296
+ const resolvedPath2 = (0, import_path6.isAbsolute)(file_path) ? file_path : (0, import_path6.resolve)(defaultPath || process.cwd(), file_path);
35297
+ if (debug) {
35298
+ console.error(`[Edit] Attempting to edit file: ${resolvedPath2}`);
35299
+ }
35300
+ if (!isPathAllowed(resolvedPath2, allowedFolders)) {
35301
+ return `Error editing file: Permission denied - ${file_path} is outside allowed directories`;
35302
+ }
35303
+ if (!(0, import_fs3.existsSync)(resolvedPath2)) {
35304
+ return `Error editing file: File not found - ${file_path}`;
35305
+ }
35306
+ const content = await import_fs2.promises.readFile(resolvedPath2, "utf-8");
35307
+ if (!content.includes(old_string)) {
35308
+ return `Error editing file: String not found - the specified old_string was not found in ${file_path}`;
35309
+ }
35310
+ const occurrences = content.split(old_string).length - 1;
35311
+ if (!replace_all && occurrences > 1) {
35312
+ return `Error editing file: Multiple occurrences found - the old_string appears ${occurrences} times. Use replace_all: true to replace all occurrences, or provide more context to make the string unique.`;
35313
+ }
35314
+ let newContent;
35315
+ if (replace_all) {
35316
+ newContent = content.replaceAll(old_string, new_string);
35317
+ } else {
35318
+ newContent = content.replace(old_string, new_string);
35319
+ }
35320
+ if (newContent === content) {
35321
+ return `Error editing file: No changes made - old_string and new_string might be the same`;
35322
+ }
35323
+ await import_fs2.promises.writeFile(resolvedPath2, newContent, "utf-8");
35324
+ const replacedCount = replace_all ? occurrences : 1;
35325
+ if (debug) {
35326
+ console.error(`[Edit] Successfully edited ${resolvedPath2}, replaced ${replacedCount} occurrence(s)`);
35327
+ }
35328
+ return `Successfully edited ${file_path} (${replacedCount} replacement${replacedCount !== 1 ? "s" : ""})`;
35329
+ } catch (error2) {
35330
+ console.error("[Edit] Error:", error2);
35331
+ return `Error editing file: ${error2.message}`;
35332
+ }
35333
+ }
35334
+ });
35335
+ };
35336
+ createTool = (options = {}) => {
35337
+ const { debug, allowedFolders, defaultPath } = parseFileToolOptions(options);
35338
+ return (0, import_ai3.tool)({
35339
+ name: "create",
35340
+ description: `Create new files with specified content.
35341
+
35342
+ This tool creates new files in the filesystem. It will create parent directories if they don't exist.
35343
+
35344
+ Parameters:
35345
+ - file_path: Path where the file should be created (absolute or relative)
35346
+ - content: Content to write to the file
35347
+ - overwrite: (optional) Whether to overwrite if file exists (default: false)
35348
+
35349
+ Important:
35350
+ - By default, will fail if the file already exists
35351
+ - Set overwrite: true to replace existing files
35352
+ - Parent directories will be created automatically if needed`,
35353
+ inputSchema: {
35354
+ type: "object",
35355
+ properties: {
35356
+ file_path: {
35357
+ type: "string",
35358
+ description: "Path where the file should be created"
35359
+ },
35360
+ content: {
35361
+ type: "string",
35362
+ description: "Content to write to the file"
35363
+ },
35364
+ overwrite: {
35365
+ type: "boolean",
35366
+ description: "Overwrite if file exists (default: false)",
35367
+ default: false
35368
+ }
35369
+ },
35370
+ required: ["file_path", "content"]
35371
+ },
35372
+ execute: async ({ file_path, content, overwrite = false }) => {
35373
+ try {
35374
+ if (!file_path || typeof file_path !== "string" || file_path.trim() === "") {
35375
+ return `Error creating file: Invalid file_path - must be a non-empty string`;
35376
+ }
35377
+ if (content === void 0 || content === null || typeof content !== "string") {
35378
+ return `Error creating file: Invalid content - must be a string`;
35379
+ }
35380
+ const resolvedPath2 = (0, import_path6.isAbsolute)(file_path) ? file_path : (0, import_path6.resolve)(defaultPath || process.cwd(), file_path);
35381
+ if (debug) {
35382
+ console.error(`[Create] Attempting to create file: ${resolvedPath2}`);
35383
+ }
35384
+ if (!isPathAllowed(resolvedPath2, allowedFolders)) {
35385
+ return `Error creating file: Permission denied - ${file_path} is outside allowed directories`;
35386
+ }
35387
+ if ((0, import_fs3.existsSync)(resolvedPath2) && !overwrite) {
35388
+ return `Error creating file: File already exists - ${file_path}. Use overwrite: true to replace it.`;
35389
+ }
35390
+ const dir = (0, import_path6.dirname)(resolvedPath2);
35391
+ await import_fs2.promises.mkdir(dir, { recursive: true });
35392
+ await import_fs2.promises.writeFile(resolvedPath2, content, "utf-8");
35393
+ const action = (0, import_fs3.existsSync)(resolvedPath2) && overwrite ? "overwrote" : "created";
35394
+ const bytes = Buffer.byteLength(content, "utf-8");
35395
+ if (debug) {
35396
+ console.error(`[Create] Successfully ${action} ${resolvedPath2}`);
35397
+ }
35398
+ return `Successfully ${action} ${file_path} (${bytes} bytes)`;
35399
+ } catch (error2) {
35400
+ console.error("[Create] Error:", error2);
35401
+ return `Error creating file: ${error2.message}`;
35402
+ }
35403
+ }
35404
+ });
35405
+ };
35406
+ editDescription = "Edit files using exact string replacement. Requires exact match including whitespace.";
35407
+ createDescription = "Create new files with specified content. Will create parent directories if needed.";
35408
+ editToolDefinition = `
35409
+ ## edit
35410
+ Description: ${editDescription}
35411
+
35412
+ When to use:
35413
+ - For precise, surgical edits to existing files
35414
+ - When you need to change specific lines or blocks of code
35415
+ - For renaming functions, variables, or updating configuration values
35416
+ - When the exact text to replace is known and unique (or use replace_all for multiple occurrences)
35417
+
35418
+ When NOT to use:
35419
+ - For creating new files (use 'create' tool instead)
35420
+ - When you cannot determine the exact text to replace
35421
+ - When changes span multiple locations that would be better handled together
35422
+
35423
+ Parameters:
35424
+ - file_path: (required) Path to the file to edit
35425
+ - old_string: (required) Exact text to find and replace (must match including whitespace, newlines, and indentation)
35426
+ - new_string: (required) Text to replace with
35427
+ - replace_all: (optional, default: false) Replace all occurrences if the string appears multiple times
35428
+
35429
+ Important notes:
35430
+ - The old_string MUST match EXACTLY, including all whitespace, indentation, and line breaks
35431
+ - If old_string appears multiple times and replace_all is false, the tool will fail
35432
+ - Always verify the exact formatting of the text you want to replace
35433
+
35434
+ Examples:
35435
+ <edit>
35436
+ <file_path>src/main.js</file_path>
35437
+ <old_string>function oldName() {
35438
+ return 42;
35439
+ }</old_string>
35440
+ <new_string>function newName() {
35441
+ return 42;
35442
+ }</new_string>
35443
+ </edit>
35444
+
35445
+ <edit>
35446
+ <file_path>config.json</file_path>
35447
+ <old_string>"debug": false</old_string>
35448
+ <new_string>"debug": true</new_string>
35449
+ <replace_all>true</replace_all>
35450
+ </edit>`;
35451
+ createToolDefinition = `
35452
+ ## create
35453
+ Description: ${createDescription}
35454
+
35455
+ When to use:
35456
+ - For creating brand new files from scratch
35457
+ - When you need to add configuration files, documentation, or new modules
35458
+ - For generating boilerplate code or templates
35459
+ - When you have the complete content ready to write
35460
+
35461
+ When NOT to use:
35462
+ - For editing existing files (use 'edit' tool instead)
35463
+ - When a file already exists unless you explicitly want to overwrite it
35464
+
35465
+ Parameters:
35466
+ - file_path: (required) Path where the file should be created
35467
+ - content: (required) Complete content to write to the file
35468
+ - overwrite: (optional, default: false) Whether to overwrite if file already exists
35469
+
35470
+ Important notes:
35471
+ - Parent directories will be created automatically if they don't exist
35472
+ - The tool will fail if the file already exists and overwrite is false
35473
+ - Be careful with the overwrite option as it completely replaces existing files
35474
+
35475
+ Examples:
35476
+ <create>
35477
+ <file_path>src/newFile.js</file_path>
35478
+ <content>export function hello() {
35479
+ return "Hello, world!";
35480
+ }</content>
35481
+ </create>
35482
+
35483
+ <create>
35484
+ <file_path>README.md</file_path>
35485
+ <content># My Project
35486
+
35487
+ This is a new project.</content>
35488
+ <overwrite>true</overwrite>
35489
+ </create>`;
35490
+ }
35491
+ });
35492
+
34894
35493
  // src/tools/langchain.js
34895
35494
  var init_langchain = __esm({
34896
35495
  "src/tools/langchain.js"() {
@@ -35040,8 +35639,10 @@ var init_tools = __esm({
35040
35639
  "use strict";
35041
35640
  init_vercel();
35042
35641
  init_bash();
35642
+ init_edit();
35043
35643
  init_langchain();
35044
35644
  init_common2();
35645
+ init_edit();
35045
35646
  init_system_message();
35046
35647
  init_vercel();
35047
35648
  init_bash();
@@ -35064,10 +35665,10 @@ async function listFilesByLevel(options) {
35064
35665
  maxFiles = 100,
35065
35666
  respectGitignore = true
35066
35667
  } = options;
35067
- if (!import_fs2.default.existsSync(directory)) {
35668
+ if (!import_fs4.default.existsSync(directory)) {
35068
35669
  throw new Error(`Directory does not exist: ${directory}`);
35069
35670
  }
35070
- const gitDirExists = import_fs2.default.existsSync(import_path6.default.join(directory, ".git"));
35671
+ const gitDirExists = import_fs4.default.existsSync(import_path7.default.join(directory, ".git"));
35071
35672
  if (gitDirExists && respectGitignore) {
35072
35673
  try {
35073
35674
  return await listFilesUsingGit(directory, maxFiles);
@@ -35082,8 +35683,8 @@ async function listFilesUsingGit(directory, maxFiles) {
35082
35683
  const { stdout } = await execAsync3("git ls-files", { cwd: directory });
35083
35684
  const files = stdout.split("\n").filter(Boolean);
35084
35685
  const sortedFiles = files.sort((a3, b3) => {
35085
- const depthA = a3.split(import_path6.default.sep).length;
35086
- const depthB = b3.split(import_path6.default.sep).length;
35686
+ const depthA = a3.split(import_path7.default.sep).length;
35687
+ const depthB = b3.split(import_path7.default.sep).length;
35087
35688
  return depthA - depthB;
35088
35689
  });
35089
35690
  return sortedFiles.slice(0, maxFiles);
@@ -35098,19 +35699,19 @@ async function listFilesByLevelManually(directory, maxFiles, respectGitignore) {
35098
35699
  while (queue.length > 0 && result.length < maxFiles) {
35099
35700
  const { dir, level } = queue.shift();
35100
35701
  try {
35101
- const entries = import_fs2.default.readdirSync(dir, { withFileTypes: true });
35702
+ const entries = import_fs4.default.readdirSync(dir, { withFileTypes: true });
35102
35703
  const files = entries.filter((entry) => entry.isFile());
35103
35704
  for (const file of files) {
35104
35705
  if (result.length >= maxFiles) break;
35105
- const filePath = import_path6.default.join(dir, file.name);
35106
- const relativePath = import_path6.default.relative(directory, filePath);
35706
+ const filePath = import_path7.default.join(dir, file.name);
35707
+ const relativePath = import_path7.default.relative(directory, filePath);
35107
35708
  if (shouldIgnore(relativePath, ignorePatterns)) continue;
35108
35709
  result.push(relativePath);
35109
35710
  }
35110
35711
  const dirs = entries.filter((entry) => entry.isDirectory());
35111
35712
  for (const subdir of dirs) {
35112
- const subdirPath = import_path6.default.join(dir, subdir.name);
35113
- const relativeSubdirPath = import_path6.default.relative(directory, subdirPath);
35713
+ const subdirPath = import_path7.default.join(dir, subdir.name);
35714
+ const relativeSubdirPath = import_path7.default.relative(directory, subdirPath);
35114
35715
  if (shouldIgnore(relativeSubdirPath, ignorePatterns)) continue;
35115
35716
  if (subdir.name === "node_modules" || subdir.name === ".git") continue;
35116
35717
  queue.push({ dir: subdirPath, level: level + 1 });
@@ -35122,12 +35723,12 @@ async function listFilesByLevelManually(directory, maxFiles, respectGitignore) {
35122
35723
  return result;
35123
35724
  }
35124
35725
  function loadGitignorePatterns(directory) {
35125
- const gitignorePath = import_path6.default.join(directory, ".gitignore");
35126
- if (!import_fs2.default.existsSync(gitignorePath)) {
35726
+ const gitignorePath = import_path7.default.join(directory, ".gitignore");
35727
+ if (!import_fs4.default.existsSync(gitignorePath)) {
35127
35728
  return [];
35128
35729
  }
35129
35730
  try {
35130
- const content = import_fs2.default.readFileSync(gitignorePath, "utf8");
35731
+ const content = import_fs4.default.readFileSync(gitignorePath, "utf8");
35131
35732
  return content.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
35132
35733
  } catch (error2) {
35133
35734
  console.error(`Warning: Could not read .gitignore: ${error2.message}`);
@@ -35145,25 +35746,25 @@ function shouldIgnore(filePath, ignorePatterns) {
35145
35746
  }
35146
35747
  return false;
35147
35748
  }
35148
- var import_fs2, import_path6, import_util11, import_child_process8, execAsync3;
35749
+ var import_fs4, import_path7, import_util11, import_child_process7, execAsync3;
35149
35750
  var init_file_lister = __esm({
35150
35751
  "src/utils/file-lister.js"() {
35151
35752
  "use strict";
35152
- import_fs2 = __toESM(require("fs"), 1);
35153
- import_path6 = __toESM(require("path"), 1);
35753
+ import_fs4 = __toESM(require("fs"), 1);
35754
+ import_path7 = __toESM(require("path"), 1);
35154
35755
  import_util11 = require("util");
35155
- import_child_process8 = require("child_process");
35156
- execAsync3 = (0, import_util11.promisify)(import_child_process8.exec);
35756
+ import_child_process7 = require("child_process");
35757
+ execAsync3 = (0, import_util11.promisify)(import_child_process7.exec);
35157
35758
  }
35158
35759
  });
35159
35760
 
35160
35761
  // src/agent/simpleTelemetry.js
35161
- var import_fs3, import_path7;
35762
+ var import_fs5, import_path8;
35162
35763
  var init_simpleTelemetry = __esm({
35163
35764
  "src/agent/simpleTelemetry.js"() {
35164
35765
  "use strict";
35165
- import_fs3 = require("fs");
35166
- import_path7 = require("path");
35766
+ import_fs5 = require("fs");
35767
+ import_path8 = require("path");
35167
35768
  }
35168
35769
  });
35169
35770
 
@@ -36012,7 +36613,7 @@ var init_escape = __esm({
36012
36613
  });
36013
36614
 
36014
36615
  // node_modules/minimatch/dist/esm/index.js
36015
- var import_brace_expansion, minimatch, starDotExtRE, starDotExtTest, starDotExtTestDot, starDotExtTestNocase, starDotExtTestNocaseDot, starDotStarRE, starDotStarTest, starDotStarTestDot, dotStarRE, dotStarTest, starRE, starTest, starTestDot, qmarksRE, qmarksTestNocase, qmarksTestNocaseDot, qmarksTestDot, qmarksTest, qmarksTestNoExt, qmarksTestNoExtDot, defaultPlatform, path5, sep, GLOBSTAR, qmark2, star2, twoStarDot, twoStarNoDot, filter, ext, defaults, braceExpand, makeRe, match, globMagic, regExpEscape2, Minimatch;
36616
+ var import_brace_expansion, minimatch, starDotExtRE, starDotExtTest, starDotExtTestDot, starDotExtTestNocase, starDotExtTestNocaseDot, starDotStarRE, starDotStarTest, starDotStarTestDot, dotStarRE, dotStarTest, starRE, starTest, starTestDot, qmarksRE, qmarksTestNocase, qmarksTestNocaseDot, qmarksTestDot, qmarksTest, qmarksTestNoExt, qmarksTestNoExtDot, defaultPlatform, path5, sep2, GLOBSTAR, qmark2, star2, twoStarDot, twoStarNoDot, filter, ext, defaults, braceExpand, makeRe, match, globMagic, regExpEscape2, Minimatch;
36016
36617
  var init_esm = __esm({
36017
36618
  "node_modules/minimatch/dist/esm/index.js"() {
36018
36619
  import_brace_expansion = __toESM(require_brace_expansion(), 1);
@@ -36085,8 +36686,8 @@ var init_esm = __esm({
36085
36686
  win32: { sep: "\\" },
36086
36687
  posix: { sep: "/" }
36087
36688
  };
36088
- sep = defaultPlatform === "win32" ? path5.win32.sep : path5.posix.sep;
36089
- minimatch.sep = sep;
36689
+ sep2 = defaultPlatform === "win32" ? path5.win32.sep : path5.posix.sep;
36690
+ minimatch.sep = sep2;
36090
36691
  GLOBSTAR = Symbol("globstar **");
36091
36692
  minimatch.GLOBSTAR = GLOBSTAR;
36092
36693
  qmark2 = "[^/]";
@@ -38848,10 +39449,10 @@ var init_esm3 = __esm({
38848
39449
  * Return a void Promise that resolves once the stream ends.
38849
39450
  */
38850
39451
  async promise() {
38851
- return new Promise((resolve4, reject2) => {
39452
+ return new Promise((resolve5, reject2) => {
38852
39453
  this.on(DESTROYED, () => reject2(new Error("stream destroyed")));
38853
39454
  this.on("error", (er) => reject2(er));
38854
- this.on("end", () => resolve4());
39455
+ this.on("end", () => resolve5());
38855
39456
  });
38856
39457
  }
38857
39458
  /**
@@ -38875,7 +39476,7 @@ var init_esm3 = __esm({
38875
39476
  return Promise.resolve({ done: false, value: res });
38876
39477
  if (this[EOF])
38877
39478
  return stop();
38878
- let resolve4;
39479
+ let resolve5;
38879
39480
  let reject2;
38880
39481
  const onerr = (er) => {
38881
39482
  this.off("data", ondata);
@@ -38889,19 +39490,19 @@ var init_esm3 = __esm({
38889
39490
  this.off("end", onend);
38890
39491
  this.off(DESTROYED, ondestroy);
38891
39492
  this.pause();
38892
- resolve4({ value, done: !!this[EOF] });
39493
+ resolve5({ value, done: !!this[EOF] });
38893
39494
  };
38894
39495
  const onend = () => {
38895
39496
  this.off("error", onerr);
38896
39497
  this.off("data", ondata);
38897
39498
  this.off(DESTROYED, ondestroy);
38898
39499
  stop();
38899
- resolve4({ done: true, value: void 0 });
39500
+ resolve5({ done: true, value: void 0 });
38900
39501
  };
38901
39502
  const ondestroy = () => onerr(new Error("stream destroyed"));
38902
39503
  return new Promise((res2, rej) => {
38903
39504
  reject2 = rej;
38904
- resolve4 = res2;
39505
+ resolve5 = res2;
38905
39506
  this.once(DESTROYED, ondestroy);
38906
39507
  this.once("error", onerr);
38907
39508
  this.once("end", onend);
@@ -39000,22 +39601,22 @@ var init_esm3 = __esm({
39000
39601
  });
39001
39602
 
39002
39603
  // node_modules/path-scurry/dist/esm/index.js
39003
- var import_node_path, import_node_url, import_fs4, actualFS, import_promises, realpathSync, defaultFS, fsFromOption, uncDriveRegexp, uncToDrive, eitherSep, UNKNOWN, IFIFO, IFCHR, IFDIR, IFBLK, IFREG, IFLNK, IFSOCK, IFMT, IFMT_UNKNOWN, READDIR_CALLED, LSTAT_CALLED, ENOTDIR, ENOENT, ENOREADLINK, ENOREALPATH, ENOCHILD, TYPEMASK, entToType, normalizeCache, normalize, normalizeNocaseCache, normalizeNocase, ResolveCache, ChildrenCache, setAsCwd, PathBase, PathWin32, PathPosix, PathScurryBase, PathScurryWin32, PathScurryPosix, PathScurryDarwin, Path, PathScurry;
39604
+ var import_node_path, import_node_url, import_fs6, actualFS, import_promises, realpathSync, defaultFS, fsFromOption, uncDriveRegexp, uncToDrive, eitherSep, UNKNOWN, IFIFO, IFCHR, IFDIR, IFBLK, IFREG, IFLNK, IFSOCK, IFMT, IFMT_UNKNOWN, READDIR_CALLED, LSTAT_CALLED, ENOTDIR, ENOENT, ENOREADLINK, ENOREALPATH, ENOCHILD, TYPEMASK, entToType, normalizeCache, normalize, normalizeNocaseCache, normalizeNocase, ResolveCache, ChildrenCache, setAsCwd, PathBase, PathWin32, PathPosix, PathScurryBase, PathScurryWin32, PathScurryPosix, PathScurryDarwin, Path, PathScurry;
39004
39605
  var init_esm4 = __esm({
39005
39606
  "node_modules/path-scurry/dist/esm/index.js"() {
39006
39607
  init_esm2();
39007
39608
  import_node_path = require("node:path");
39008
39609
  import_node_url = require("node:url");
39009
- import_fs4 = require("fs");
39610
+ import_fs6 = require("fs");
39010
39611
  actualFS = __toESM(require("node:fs"), 1);
39011
39612
  import_promises = require("node:fs/promises");
39012
39613
  init_esm3();
39013
- realpathSync = import_fs4.realpathSync.native;
39614
+ realpathSync = import_fs6.realpathSync.native;
39014
39615
  defaultFS = {
39015
- lstatSync: import_fs4.lstatSync,
39016
- readdir: import_fs4.readdir,
39017
- readdirSync: import_fs4.readdirSync,
39018
- readlinkSync: import_fs4.readlinkSync,
39616
+ lstatSync: import_fs6.lstatSync,
39617
+ readdir: import_fs6.readdir,
39618
+ readdirSync: import_fs6.readdirSync,
39619
+ readlinkSync: import_fs6.readlinkSync,
39019
39620
  realpathSync,
39020
39621
  promises: {
39021
39622
  lstat: import_promises.lstat,
@@ -39881,9 +40482,9 @@ var init_esm4 = __esm({
39881
40482
  if (this.#asyncReaddirInFlight) {
39882
40483
  await this.#asyncReaddirInFlight;
39883
40484
  } else {
39884
- let resolve4 = () => {
40485
+ let resolve5 = () => {
39885
40486
  };
39886
- this.#asyncReaddirInFlight = new Promise((res) => resolve4 = res);
40487
+ this.#asyncReaddirInFlight = new Promise((res) => resolve5 = res);
39887
40488
  try {
39888
40489
  for (const e3 of await this.#fs.promises.readdir(fullpath, {
39889
40490
  withFileTypes: true
@@ -39896,7 +40497,7 @@ var init_esm4 = __esm({
39896
40497
  children.provisional = 0;
39897
40498
  }
39898
40499
  this.#asyncReaddirInFlight = void 0;
39899
- resolve4();
40500
+ resolve5();
39900
40501
  }
39901
40502
  return children.slice(0, children.provisional);
39902
40503
  }
@@ -40126,8 +40727,8 @@ var init_esm4 = __esm({
40126
40727
  *
40127
40728
  * @internal
40128
40729
  */
40129
- constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs6 = defaultFS } = {}) {
40130
- this.#fs = fsFromOption(fs6);
40730
+ constructor(cwd = process.cwd(), pathImpl, sep3, { nocase, childrenCacheSize = 16 * 1024, fs: fs7 = defaultFS } = {}) {
40731
+ this.#fs = fsFromOption(fs7);
40131
40732
  if (cwd instanceof URL || cwd.startsWith("file://")) {
40132
40733
  cwd = (0, import_node_url.fileURLToPath)(cwd);
40133
40734
  }
@@ -40137,7 +40738,7 @@ var init_esm4 = __esm({
40137
40738
  this.#resolveCache = new ResolveCache();
40138
40739
  this.#resolvePosixCache = new ResolveCache();
40139
40740
  this.#children = new ChildrenCache(childrenCacheSize);
40140
- const split = cwdPath.substring(this.rootPath.length).split(sep2);
40741
+ const split = cwdPath.substring(this.rootPath.length).split(sep3);
40141
40742
  if (split.length === 1 && !split[0]) {
40142
40743
  split.pop();
40143
40744
  }
@@ -40685,8 +41286,8 @@ var init_esm4 = __esm({
40685
41286
  /**
40686
41287
  * @internal
40687
41288
  */
40688
- newRoot(fs6) {
40689
- return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs6 });
41289
+ newRoot(fs7) {
41290
+ return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs7 });
40690
41291
  }
40691
41292
  /**
40692
41293
  * Return true if the provided path string is an absolute path
@@ -40714,8 +41315,8 @@ var init_esm4 = __esm({
40714
41315
  /**
40715
41316
  * @internal
40716
41317
  */
40717
- newRoot(fs6) {
40718
- return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs6 });
41318
+ newRoot(fs7) {
41319
+ return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs7 });
40719
41320
  }
40720
41321
  /**
40721
41322
  * Return true if the provided path string is an absolute path
@@ -41908,26 +42509,40 @@ function createWrappedTools(baseTools) {
41908
42509
  baseTools.bashTool.execute
41909
42510
  );
41910
42511
  }
42512
+ if (baseTools.editTool) {
42513
+ wrappedTools.editToolInstance = wrapToolWithEmitter(
42514
+ baseTools.editTool,
42515
+ "edit",
42516
+ baseTools.editTool.execute
42517
+ );
42518
+ }
42519
+ if (baseTools.createTool) {
42520
+ wrappedTools.createToolInstance = wrapToolWithEmitter(
42521
+ baseTools.createTool,
42522
+ "create",
42523
+ baseTools.createTool.execute
42524
+ );
42525
+ }
41911
42526
  return wrappedTools;
41912
42527
  }
41913
- var import_child_process9, import_util12, import_crypto3, import_events, import_fs5, import_fs6, import_path8, toolCallEmitter, activeToolExecutions, wrapToolWithEmitter, listFilesTool, searchFilesTool, listFilesToolInstance, searchFilesToolInstance;
42528
+ var import_child_process8, import_util12, import_crypto3, import_events, import_fs7, import_fs8, import_path9, toolCallEmitter, activeToolExecutions, wrapToolWithEmitter, listFilesTool, searchFilesTool, listFilesToolInstance, searchFilesToolInstance;
41914
42529
  var init_probeTool = __esm({
41915
42530
  "src/agent/probeTool.js"() {
41916
42531
  "use strict";
41917
42532
  init_index();
41918
- import_child_process9 = require("child_process");
42533
+ import_child_process8 = require("child_process");
41919
42534
  import_util12 = require("util");
41920
42535
  import_crypto3 = require("crypto");
41921
42536
  import_events = require("events");
41922
- import_fs5 = __toESM(require("fs"), 1);
41923
- import_fs6 = require("fs");
41924
- import_path8 = __toESM(require("path"), 1);
42537
+ import_fs7 = __toESM(require("fs"), 1);
42538
+ import_fs8 = require("fs");
42539
+ import_path9 = __toESM(require("path"), 1);
41925
42540
  init_esm5();
41926
42541
  toolCallEmitter = new import_events.EventEmitter();
41927
42542
  activeToolExecutions = /* @__PURE__ */ new Map();
41928
- wrapToolWithEmitter = (tool3, toolName, baseExecute) => {
42543
+ wrapToolWithEmitter = (tool4, toolName, baseExecute) => {
41929
42544
  return {
41930
- ...tool3,
42545
+ ...tool4,
41931
42546
  // Spread schema, description etc.
41932
42547
  execute: async (params) => {
41933
42548
  const debug = process.env.DEBUG === "1";
@@ -42009,17 +42624,17 @@ var init_probeTool = __esm({
42009
42624
  execute: async (params) => {
42010
42625
  const { directory = ".", workingDirectory } = params;
42011
42626
  const baseCwd = workingDirectory || process.cwd();
42012
- const secureBaseDir = import_path8.default.resolve(baseCwd);
42627
+ const secureBaseDir = import_path9.default.resolve(baseCwd);
42013
42628
  const isDependencyPath = directory.startsWith("/dep/") || directory.startsWith("go:") || directory.startsWith("js:") || directory.startsWith("rust:");
42014
42629
  let targetDir;
42015
- if (import_path8.default.isAbsolute(directory)) {
42016
- targetDir = import_path8.default.resolve(directory);
42017
- if (!isDependencyPath && !targetDir.startsWith(secureBaseDir + import_path8.default.sep) && targetDir !== secureBaseDir) {
42630
+ if (import_path9.default.isAbsolute(directory)) {
42631
+ targetDir = import_path9.default.resolve(directory);
42632
+ if (!isDependencyPath && !targetDir.startsWith(secureBaseDir + import_path9.default.sep) && targetDir !== secureBaseDir) {
42018
42633
  throw new Error(`Path traversal attempt detected. Cannot access directory outside workspace: ${directory}`);
42019
42634
  }
42020
42635
  } else {
42021
- targetDir = import_path8.default.resolve(secureBaseDir, directory);
42022
- if (!isDependencyPath && !targetDir.startsWith(secureBaseDir + import_path8.default.sep) && targetDir !== secureBaseDir) {
42636
+ targetDir = import_path9.default.resolve(secureBaseDir, directory);
42637
+ if (!isDependencyPath && !targetDir.startsWith(secureBaseDir + import_path9.default.sep) && targetDir !== secureBaseDir) {
42023
42638
  throw new Error(`Path traversal attempt detected. Access denied: ${directory}`);
42024
42639
  }
42025
42640
  }
@@ -42028,7 +42643,7 @@ var init_probeTool = __esm({
42028
42643
  console.log(`[DEBUG] Listing files in directory: ${targetDir}`);
42029
42644
  }
42030
42645
  try {
42031
- const files = await import_fs6.promises.readdir(targetDir, { withFileTypes: true });
42646
+ const files = await import_fs8.promises.readdir(targetDir, { withFileTypes: true });
42032
42647
  const formatSize = (size) => {
42033
42648
  if (size < 1024) return `${size}B`;
42034
42649
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)}K`;
@@ -42037,10 +42652,10 @@ var init_probeTool = __esm({
42037
42652
  };
42038
42653
  const entries = await Promise.all(files.map(async (file) => {
42039
42654
  const isDirectory = file.isDirectory();
42040
- const fullPath = import_path8.default.join(targetDir, file.name);
42655
+ const fullPath = import_path9.default.join(targetDir, file.name);
42041
42656
  let size = 0;
42042
42657
  try {
42043
- const stats = await import_fs6.promises.stat(fullPath);
42658
+ const stats = await import_fs8.promises.stat(fullPath);
42044
42659
  size = stats.size;
42045
42660
  } catch (statError) {
42046
42661
  if (debug) {
@@ -42082,17 +42697,17 @@ var init_probeTool = __esm({
42082
42697
  throw new Error("Pattern is required for file search");
42083
42698
  }
42084
42699
  const baseCwd = workingDirectory || process.cwd();
42085
- const secureBaseDir = import_path8.default.resolve(baseCwd);
42700
+ const secureBaseDir = import_path9.default.resolve(baseCwd);
42086
42701
  const isDependencyPath = directory.startsWith("/dep/") || directory.startsWith("go:") || directory.startsWith("js:") || directory.startsWith("rust:");
42087
42702
  let targetDir;
42088
- if (import_path8.default.isAbsolute(directory)) {
42089
- targetDir = import_path8.default.resolve(directory);
42090
- if (!isDependencyPath && !targetDir.startsWith(secureBaseDir + import_path8.default.sep) && targetDir !== secureBaseDir) {
42703
+ if (import_path9.default.isAbsolute(directory)) {
42704
+ targetDir = import_path9.default.resolve(directory);
42705
+ if (!isDependencyPath && !targetDir.startsWith(secureBaseDir + import_path9.default.sep) && targetDir !== secureBaseDir) {
42091
42706
  throw new Error(`Path traversal attempt detected. Cannot access directory outside workspace: ${directory}`);
42092
42707
  }
42093
42708
  } else {
42094
- targetDir = import_path8.default.resolve(secureBaseDir, directory);
42095
- if (!isDependencyPath && !targetDir.startsWith(secureBaseDir + import_path8.default.sep) && targetDir !== secureBaseDir) {
42709
+ targetDir = import_path9.default.resolve(secureBaseDir, directory);
42710
+ if (!isDependencyPath && !targetDir.startsWith(secureBaseDir + import_path9.default.sep) && targetDir !== secureBaseDir) {
42096
42711
  throw new Error(`Path traversal attempt detected. Access denied: ${directory}`);
42097
42712
  }
42098
42713
  }
@@ -42163,8 +42778,10 @@ var init_index = __esm({
42163
42778
  init_file_lister();
42164
42779
  init_system_message();
42165
42780
  init_common2();
42781
+ init_edit();
42166
42782
  init_vercel();
42167
42783
  init_bash();
42784
+ init_edit();
42168
42785
  init_ProbeAgent();
42169
42786
  init_simpleTelemetry();
42170
42787
  init_probeTool();
@@ -42246,8 +42863,8 @@ function checkAttemptCompleteRecovery(cleanedXmlString, validTools = []) {
42246
42863
  function hasOtherToolTags(xmlString, validTools = []) {
42247
42864
  const defaultTools = ["search", "query", "extract", "listFiles", "searchFiles", "implement", "attempt_completion"];
42248
42865
  const toolsToCheck = validTools.length > 0 ? validTools : defaultTools;
42249
- for (const tool3 of toolsToCheck) {
42250
- if (tool3 !== "attempt_completion" && xmlString.includes(`<${tool3}`)) {
42866
+ for (const tool4 of toolsToCheck) {
42867
+ if (tool4 !== "attempt_completion" && xmlString.includes(`<${tool4}`)) {
42251
42868
  return true;
42252
42869
  }
42253
42870
  }
@@ -42284,6 +42901,10 @@ function createTools(configOptions) {
42284
42901
  if (configOptions.enableBash) {
42285
42902
  tools2.bashTool = bashTool(configOptions);
42286
42903
  }
42904
+ if (configOptions.allowEdit) {
42905
+ tools2.editTool = editTool(configOptions);
42906
+ tools2.createTool = createTool(configOptions);
42907
+ }
42287
42908
  return tools2;
42288
42909
  }
42289
42910
  function parseXmlToolCallWithThinking(xmlString, validTools) {
@@ -42385,7 +43006,7 @@ function createMockProvider() {
42385
43006
  provider: "mock",
42386
43007
  // Mock the doGenerate method used by Vercel AI SDK
42387
43008
  doGenerate: async ({ messages, tools: tools2 }) => {
42388
- await new Promise((resolve4) => setTimeout(resolve4, 10));
43009
+ await new Promise((resolve5) => setTimeout(resolve5, 10));
42389
43010
  return {
42390
43011
  text: "This is a mock response for testing",
42391
43012
  toolCalls: [],
@@ -54372,16 +54993,6 @@ var init_parser2 = __esm({
54372
54993
  this.subgraph = this.RULE("subgraph", () => {
54373
54994
  this.CONSUME(SubgraphKeyword);
54374
54995
  this.OR([
54375
- {
54376
- ALT: () => {
54377
- this.CONSUME(Identifier, { LABEL: "subgraphId" });
54378
- this.OPTION(() => {
54379
- this.CONSUME1(SquareOpen);
54380
- this.SUBRULE(this.nodeContent);
54381
- this.CONSUME1(SquareClose);
54382
- });
54383
- }
54384
- },
54385
54996
  {
54386
54997
  ALT: () => {
54387
54998
  this.CONSUME(QuotedString, { LABEL: "subgraphTitleQ" });
@@ -54393,6 +55004,33 @@ var init_parser2 = __esm({
54393
55004
  this.SUBRULE2(this.nodeContent);
54394
55005
  this.CONSUME2(SquareClose);
54395
55006
  }
55007
+ },
55008
+ {
55009
+ ALT: () => {
55010
+ this.CONSUME1(Identifier, { LABEL: "subgraphIdOrFirstWord" });
55011
+ this.OPTION(() => {
55012
+ this.OR1([
55013
+ {
55014
+ ALT: () => {
55015
+ this.CONSUME1(SquareOpen);
55016
+ this.SUBRULE(this.nodeContent);
55017
+ this.CONSUME1(SquareClose);
55018
+ }
55019
+ },
55020
+ {
55021
+ ALT: () => {
55022
+ this.AT_LEAST_ONE(() => {
55023
+ this.OR2([
55024
+ { ALT: () => this.CONSUME2(Identifier) },
55025
+ { ALT: () => this.CONSUME(Text) },
55026
+ { ALT: () => this.CONSUME(NumberLiteral) }
55027
+ ]);
55028
+ });
55029
+ }
55030
+ }
55031
+ ]);
55032
+ });
55033
+ }
54396
55034
  }
54397
55035
  ]);
54398
55036
  this.CONSUME(Newline);
@@ -54996,7 +55634,6 @@ var init_semantics = __esm({
54996
55634
  const last2 = allChildren[allChildren.length - 1];
54997
55635
  const isSlash = (t3) => t3.image === "/" || t3.image === "\\";
54998
55636
  if (isSlash(first2) && isSlash(last2)) {
54999
- continue;
55000
55637
  }
55001
55638
  }
55002
55639
  const opens = ch.RoundOpen || [];
@@ -55476,13 +56113,24 @@ function mapFlowchartParserError(err, text) {
55476
56113
  length: len
55477
56114
  };
55478
56115
  }
55479
- if (tokType === "QuotedString") {
56116
+ if (tokType === "QuotedString" || tokType === "SquareOpen" || tokType === "SquareClose") {
55480
56117
  const context = err?.context;
55481
56118
  const inLinkRule = context?.ruleStack?.includes("linkTextInline") || context?.ruleStack?.includes("link") || false;
55482
56119
  const lineContent = allLines[Math.max(0, line - 1)] || "";
55483
56120
  const beforeQuote = lineContent.slice(0, Math.max(0, column - 1));
55484
56121
  const hasLinkBefore = beforeQuote.match(/--\s*$|==\s*$|-\.\s*$|-\.-\s*$|\[\s*$/);
55485
56122
  if (inLinkRule || hasLinkBefore) {
56123
+ if (tokType === "SquareOpen" || tokType === "SquareClose") {
56124
+ return {
56125
+ line,
56126
+ column,
56127
+ severity: "error",
56128
+ code: "FL-EDGE-LABEL-BRACKET",
56129
+ message: "Square brackets [ ] are not supported inside inline edge labels.",
56130
+ hint: "Use HTML entities &#91; and &#93; inside |...|, e.g., --|run: &#91;aggregate&#93;|-->",
56131
+ length: len
56132
+ };
56133
+ }
55486
56134
  const quotedText = found.startsWith('"') ? found.slice(1, -1) : found;
55487
56135
  return {
55488
56136
  line,
@@ -55576,7 +56224,7 @@ function mapFlowchartParserError(err, text) {
55576
56224
  }
55577
56225
  }
55578
56226
  }
55579
- if (tokType === "QuotedString") {
56227
+ if (tokType === "QuotedString" || tokType === "SquareOpen" || tokType === "SquareClose") {
55580
56228
  return {
55581
56229
  line,
55582
56230
  column,
@@ -55597,7 +56245,7 @@ function mapFlowchartParserError(err, text) {
55597
56245
  return { line, column, severity: "error", code: "FL-NODE-UNCLOSED-BRACKET", message: "Unclosed '['. Add a matching ']' before the arrow or newline.", hint: "Example: A[Label] --> B", length: 1 };
55598
56246
  }
55599
56247
  if (expecting(err, "RoundClose")) {
55600
- if (tokType === "QuotedString") {
56248
+ if (tokType === "QuotedString" || tokType === "SquareOpen" || tokType === "SquareClose") {
55601
56249
  return {
55602
56250
  line,
55603
56251
  column,
@@ -55636,7 +56284,7 @@ function mapFlowchartParserError(err, text) {
55636
56284
  return { line, column, severity: "error", code: "FL-NODE-UNCLOSED-BRACKET", message: "Unclosed '('. Add a matching ')'.", hint: "Example: B(Label)", length: 1 };
55637
56285
  }
55638
56286
  if (expecting(err, "DiamondClose")) {
55639
- if (tokType === "QuotedString") {
56287
+ if (tokType === "QuotedString" || tokType === "SquareOpen" || tokType === "SquareClose") {
55640
56288
  return {
55641
56289
  line,
55642
56290
  column,
@@ -55779,16 +56427,19 @@ function mapFlowchartParserError(err, text) {
55779
56427
  const subgraphIdx = lineStr.indexOf("subgraph");
55780
56428
  if (subgraphIdx !== -1) {
55781
56429
  const afterSubgraph = lineStr.slice(subgraphIdx + 8).trim();
55782
- if (afterSubgraph && !afterSubgraph.startsWith('"') && !afterSubgraph.startsWith("'") && afterSubgraph.includes(" ")) {
55783
- return {
55784
- line,
55785
- column,
55786
- severity: "error",
55787
- code: "FL-SUBGRAPH-UNQUOTED-TITLE",
55788
- message: "Subgraph titles with spaces must be quoted.",
55789
- hint: 'Example: subgraph "Existing Logic Path" or use underscores: subgraph Existing_Logic_Path',
55790
- length: afterSubgraph.length
55791
- };
56430
+ if (afterSubgraph && !afterSubgraph.startsWith('"') && !afterSubgraph.startsWith("'")) {
56431
+ const hasHazard = /[\[\](){}/:|"'\\]/.test(afterSubgraph);
56432
+ if (hasHazard) {
56433
+ return {
56434
+ line,
56435
+ column,
56436
+ severity: "error",
56437
+ code: "FL-SUBGRAPH-UNQUOTED-TITLE",
56438
+ message: "Subgraph title contains special characters; wrap it in quotes.",
56439
+ hint: 'Example: subgraph "Streams (inside Gateway)"',
56440
+ length: afterSubgraph.length
56441
+ };
56442
+ }
55792
56443
  }
55793
56444
  }
55794
56445
  }
@@ -56482,6 +57133,111 @@ function validateFlowchart(text, options = {}) {
56482
57133
  }
56483
57134
  }
56484
57135
  }
57136
+ {
57137
+ const byLine = /* @__PURE__ */ new Map();
57138
+ const collect = (arr) => {
57139
+ for (const e3 of arr || []) {
57140
+ if (e3 && (e3.code === "FL-LABEL-PARENS-UNQUOTED" || e3.code === "FL-LABEL-AT-IN-UNQUOTED")) {
57141
+ const ln = e3.line ?? 0;
57142
+ const col = e3.column ?? 1;
57143
+ const list2 = byLine.get(ln) || [];
57144
+ list2.push({ start: col, end: col });
57145
+ byLine.set(ln, list2);
57146
+ }
57147
+ }
57148
+ };
57149
+ collect(prevErrors);
57150
+ collect(errs);
57151
+ const lines2 = text2.split(/\r?\n/);
57152
+ for (let ii = 0; ii < lines2.length; ii++) {
57153
+ const raw = lines2[ii] || "";
57154
+ if (!raw.includes("[") || !raw.includes("]"))
57155
+ continue;
57156
+ let i3 = 0;
57157
+ const n3 = raw.length;
57158
+ let inQuote = false;
57159
+ let esc = false;
57160
+ while (i3 < n3) {
57161
+ const ch = raw[i3];
57162
+ if (inQuote) {
57163
+ if (esc) {
57164
+ esc = false;
57165
+ } else if (ch === "\\") {
57166
+ esc = true;
57167
+ } else if (ch === '"') {
57168
+ inQuote = false;
57169
+ }
57170
+ i3++;
57171
+ continue;
57172
+ }
57173
+ if (ch === '"') {
57174
+ inQuote = true;
57175
+ i3++;
57176
+ continue;
57177
+ }
57178
+ if (ch === "[") {
57179
+ let j3 = i3 + 1;
57180
+ let inQ = false;
57181
+ let esc2 = false;
57182
+ let depth = 1;
57183
+ while (j3 < n3 && depth > 0) {
57184
+ const cj = raw[j3];
57185
+ if (inQ) {
57186
+ if (esc2) {
57187
+ esc2 = false;
57188
+ } else if (cj === "\\") {
57189
+ esc2 = true;
57190
+ } else if (cj === '"') {
57191
+ inQ = false;
57192
+ }
57193
+ j3++;
57194
+ continue;
57195
+ }
57196
+ if (cj === '"') {
57197
+ inQ = true;
57198
+ j3++;
57199
+ continue;
57200
+ }
57201
+ if (cj === "[")
57202
+ depth++;
57203
+ else if (cj === "]")
57204
+ depth--;
57205
+ j3++;
57206
+ }
57207
+ if (depth === 0) {
57208
+ const startCol = i3 + 2;
57209
+ const endCol = j3;
57210
+ const seg = raw.slice(i3 + 1, j3 - 1);
57211
+ const trimmed = seg.trim();
57212
+ const ln = ii + 1;
57213
+ const lsp = trimmed.slice(0, 1), rsp = trimmed.slice(-1);
57214
+ const isSlashPair = (lsp === "/" || lsp === "\\") && (rsp === "/" || rsp === "\\");
57215
+ const isParenWrapped = lsp === "(" && rsp === ")";
57216
+ const isQuoted = /^"[\s\S]*"$/.test(trimmed);
57217
+ const existing = byLine.get(ln) || [];
57218
+ const covered = existing.some((r3) => !(endCol < r3.start || startCol > r3.end));
57219
+ const hasParens = seg.includes("(") || seg.includes(")");
57220
+ const hasAt = seg.includes("@");
57221
+ if (!covered && !isQuoted && !isParenWrapped && hasParens) {
57222
+ errs.push({ line: ln, column: startCol, severity: "error", code: "FL-LABEL-PARENS-UNQUOTED", message: "Parentheses inside an unquoted label are not supported by Mermaid.", hint: 'Wrap the label in quotes, e.g., A["Mark (X)"] \u2014 or replace ( and ) with HTML entities: &#40; and &#41;.' });
57223
+ existing.push({ start: startCol, end: endCol });
57224
+ byLine.set(ln, existing);
57225
+ }
57226
+ if (!covered && !isQuoted && !isSlashPair && hasAt) {
57227
+ errs.push({ line: ln, column: startCol, severity: "error", code: "FL-LABEL-AT-IN-UNQUOTED", message: "'@' inside an unquoted label can be misparsed by Mermaid.", hint: 'Wrap the label in quotes, e.g., B["@probelabs/probe v0.6.0-rc149"]' });
57228
+ existing.push({ start: startCol, end: endCol });
57229
+ byLine.set(ln, existing);
57230
+ }
57231
+ i3 = j3;
57232
+ continue;
57233
+ } else {
57234
+ break;
57235
+ }
57236
+ }
57237
+ i3++;
57238
+ }
57239
+ }
57240
+ }
56485
57241
  const dblEsc = (text2.match(/\\\"/g) || []).length;
56486
57242
  const dq = (text2.match(/\"/g) || []).length - dblEsc;
56487
57243
  const sq = (text2.match(/'/g) || []).length;
@@ -58826,6 +59582,21 @@ function computeFixes(text, errors, level = "safe") {
58826
59582
  }
58827
59583
  continue;
58828
59584
  }
59585
+ if (is("FL-EDGE-LABEL-BRACKET", e3)) {
59586
+ const lineText = lineTextAt(text, e3.line);
59587
+ const firstBar = lineText.indexOf("|");
59588
+ const secondBar = firstBar >= 0 ? lineText.indexOf("|", firstBar + 1) : -1;
59589
+ if (firstBar >= 0 && secondBar > firstBar) {
59590
+ const before = lineText.slice(0, firstBar + 1);
59591
+ const label = lineText.slice(firstBar + 1, secondBar);
59592
+ const after = lineText.slice(secondBar);
59593
+ const fixedLabel = label.replace(/\[/g, "&#91;").replace(/\]/g, "&#93;");
59594
+ const fixedLine = before + fixedLabel + after;
59595
+ const finalLine = fixedLine.replace(/\[([^\]]*)\]/g, (m3, seg) => "[" + String(seg).replace(/`/g, "") + "]");
59596
+ edits.push({ start: { line: e3.line, column: 1 }, end: { line: e3.line, column: lineText.length + 1 }, newText: finalLine });
59597
+ }
59598
+ continue;
59599
+ }
58829
59600
  if (is("FL-EDGE-LABEL-BACKTICK", e3)) {
58830
59601
  const lineText = lineTextAt(text, e3.line);
58831
59602
  const re = /^(.*?--)\s*([^|>]+?)\s*(-->|==>|\.->|->)(.*)$/;
@@ -67949,7 +68720,7 @@ var require_bk = __commonJS({
67949
68720
  return xs;
67950
68721
  }
67951
68722
  function buildBlockGraph(g3, layering, root2, reverseSep) {
67952
- var blockGraph = new Graph(), graphLabel = g3.graph(), sepFn = sep2(graphLabel.nodesep, graphLabel.edgesep, reverseSep);
68723
+ var blockGraph = new Graph(), graphLabel = g3.graph(), sepFn = sep3(graphLabel.nodesep, graphLabel.edgesep, reverseSep);
67953
68724
  _2.forEach(layering, function(layer) {
67954
68725
  var u3;
67955
68726
  _2.forEach(layer, function(v3) {
@@ -68039,7 +68810,7 @@ var require_bk = __commonJS({
68039
68810
  alignCoordinates(xss, smallestWidth);
68040
68811
  return balance(xss, g3.graph().align);
68041
68812
  }
68042
- function sep2(nodeSep, edgeSep, reverseSep) {
68813
+ function sep3(nodeSep, edgeSep, reverseSep) {
68043
68814
  return function(g3, v3, w3) {
68044
68815
  var vLabel = g3.node(v3);
68045
68816
  var wLabel = g3.node(w3);
@@ -75333,7 +76104,7 @@ var require_compile = __commonJS({
75333
76104
  const schOrFunc = root2.refs[ref];
75334
76105
  if (schOrFunc)
75335
76106
  return schOrFunc;
75336
- let _sch = resolve4.call(this, root2, ref);
76107
+ let _sch = resolve5.call(this, root2, ref);
75337
76108
  if (_sch === void 0) {
75338
76109
  const schema = (_a16 = root2.localRefs) === null || _a16 === void 0 ? void 0 : _a16[ref];
75339
76110
  const { schemaId } = this.opts;
@@ -75360,7 +76131,7 @@ var require_compile = __commonJS({
75360
76131
  function sameSchemaEnv(s1, s22) {
75361
76132
  return s1.schema === s22.schema && s1.root === s22.root && s1.baseId === s22.baseId;
75362
76133
  }
75363
- function resolve4(root2, ref) {
76134
+ function resolve5(root2, ref) {
75364
76135
  let sch;
75365
76136
  while (typeof (sch = this.refs[ref]) == "string")
75366
76137
  ref = sch;
@@ -75935,7 +76706,7 @@ var require_fast_uri = __commonJS({
75935
76706
  }
75936
76707
  return uri;
75937
76708
  }
75938
- function resolve4(baseURI, relativeURI, options) {
76709
+ function resolve5(baseURI, relativeURI, options) {
75939
76710
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
75940
76711
  const resolved = resolveComponent(parse6(baseURI, schemelessOptions), parse6(relativeURI, schemelessOptions), schemelessOptions, true);
75941
76712
  schemelessOptions.skipEscape = true;
@@ -76162,7 +76933,7 @@ var require_fast_uri = __commonJS({
76162
76933
  var fastUri = {
76163
76934
  SCHEMES,
76164
76935
  normalize: normalize2,
76165
- resolve: resolve4,
76936
+ resolve: resolve5,
76166
76937
  resolveComponent,
76167
76938
  equal,
76168
76939
  serialize,
@@ -80184,11 +80955,11 @@ function loadMCPConfigurationFromPath(configPath) {
80184
80955
  if (!configPath) {
80185
80956
  throw new Error("Config path is required");
80186
80957
  }
80187
- if (!(0, import_fs7.existsSync)(configPath)) {
80958
+ if (!(0, import_fs9.existsSync)(configPath)) {
80188
80959
  throw new Error(`MCP configuration file not found: ${configPath}`);
80189
80960
  }
80190
80961
  try {
80191
- const content = (0, import_fs7.readFileSync)(configPath, "utf8");
80962
+ const content = (0, import_fs9.readFileSync)(configPath, "utf8");
80192
80963
  const config = JSON.parse(content);
80193
80964
  if (process.env.DEBUG === "1" || process.env.DEBUG_MCP === "1") {
80194
80965
  console.error(`[MCP DEBUG] Loaded configuration from: ${configPath}`);
@@ -80203,19 +80974,19 @@ function loadMCPConfiguration() {
80203
80974
  // Environment variable path
80204
80975
  process.env.MCP_CONFIG_PATH,
80205
80976
  // Local project paths
80206
- (0, import_path9.join)(process.cwd(), ".mcp", "config.json"),
80207
- (0, import_path9.join)(process.cwd(), "mcp.config.json"),
80977
+ (0, import_path10.join)(process.cwd(), ".mcp", "config.json"),
80978
+ (0, import_path10.join)(process.cwd(), "mcp.config.json"),
80208
80979
  // Home directory paths
80209
- (0, import_path9.join)((0, import_os3.homedir)(), ".config", "probe", "mcp.json"),
80210
- (0, import_path9.join)((0, import_os3.homedir)(), ".mcp", "config.json"),
80980
+ (0, import_path10.join)((0, import_os3.homedir)(), ".config", "probe", "mcp.json"),
80981
+ (0, import_path10.join)((0, import_os3.homedir)(), ".mcp", "config.json"),
80211
80982
  // Claude-style config location
80212
- (0, import_path9.join)((0, import_os3.homedir)(), "Library", "Application Support", "Claude", "mcp_config.json")
80983
+ (0, import_path10.join)((0, import_os3.homedir)(), "Library", "Application Support", "Claude", "mcp_config.json")
80213
80984
  ].filter(Boolean);
80214
80985
  let config = null;
80215
80986
  for (const configPath of configPaths) {
80216
- if ((0, import_fs7.existsSync)(configPath)) {
80987
+ if ((0, import_fs9.existsSync)(configPath)) {
80217
80988
  try {
80218
- const content = (0, import_fs7.readFileSync)(configPath, "utf8");
80989
+ const content = (0, import_fs9.readFileSync)(configPath, "utf8");
80219
80990
  config = JSON.parse(content);
80220
80991
  if (process.env.DEBUG === "1" || process.env.DEBUG_MCP === "1") {
80221
80992
  console.error(`[MCP DEBUG] Loaded configuration from: ${configPath}`);
@@ -80311,22 +81082,22 @@ function parseEnabledServers(config) {
80311
81082
  }
80312
81083
  return servers;
80313
81084
  }
80314
- var import_fs7, import_path9, import_os3, import_url4, __filename4, __dirname4, DEFAULT_CONFIG;
81085
+ var import_fs9, import_path10, import_os3, import_url4, __filename4, __dirname4, DEFAULT_CONFIG;
80315
81086
  var init_config = __esm({
80316
81087
  "src/agent/mcp/config.js"() {
80317
81088
  "use strict";
80318
- import_fs7 = require("fs");
80319
- import_path9 = require("path");
81089
+ import_fs9 = require("fs");
81090
+ import_path10 = require("path");
80320
81091
  import_os3 = require("os");
80321
81092
  import_url4 = require("url");
80322
81093
  __filename4 = (0, import_url4.fileURLToPath)("file:///");
80323
- __dirname4 = (0, import_path9.dirname)(__filename4);
81094
+ __dirname4 = (0, import_path10.dirname)(__filename4);
80324
81095
  DEFAULT_CONFIG = {
80325
81096
  mcpServers: {
80326
81097
  // Example probe server configuration
80327
81098
  "probe-local": {
80328
81099
  command: "node",
80329
- args: [(0, import_path9.join)(__dirname4, "../../../examples/chat/mcpServer.js")],
81100
+ args: [(0, import_path10.join)(__dirname4, "../../../examples/chat/mcpServer.js")],
80330
81101
  transport: "stdio",
80331
81102
  enabled: false
80332
81103
  },
@@ -80509,12 +81280,12 @@ var init_client2 = __esm({
80509
81280
  const toolsResponse = await client.listTools();
80510
81281
  const toolCount = toolsResponse?.tools?.length || 0;
80511
81282
  if (toolsResponse && toolsResponse.tools) {
80512
- for (const tool3 of toolsResponse.tools) {
80513
- const qualifiedName = `${name14}_${tool3.name}`;
81283
+ for (const tool4 of toolsResponse.tools) {
81284
+ const qualifiedName = `${name14}_${tool4.name}`;
80514
81285
  this.tools.set(qualifiedName, {
80515
- ...tool3,
81286
+ ...tool4,
80516
81287
  serverName: name14,
80517
- originalName: tool3.name
81288
+ originalName: tool4.name
80518
81289
  });
80519
81290
  if (this.debug) {
80520
81291
  console.error(`[MCP DEBUG] Registered tool: ${qualifiedName}`);
@@ -80537,13 +81308,13 @@ var init_client2 = __esm({
80537
81308
  * @param {Object} args - Tool arguments
80538
81309
  */
80539
81310
  async callTool(toolName, args) {
80540
- const tool3 = this.tools.get(toolName);
80541
- if (!tool3) {
81311
+ const tool4 = this.tools.get(toolName);
81312
+ if (!tool4) {
80542
81313
  throw new Error(`Unknown tool: ${toolName}`);
80543
81314
  }
80544
- const clientInfo = this.clients.get(tool3.serverName);
81315
+ const clientInfo = this.clients.get(tool4.serverName);
80545
81316
  if (!clientInfo) {
80546
- throw new Error(`Server ${tool3.serverName} not connected`);
81317
+ throw new Error(`Server ${tool4.serverName} not connected`);
80547
81318
  }
80548
81319
  try {
80549
81320
  if (this.debug) {
@@ -80557,7 +81328,7 @@ var init_client2 = __esm({
80557
81328
  });
80558
81329
  const result = await Promise.race([
80559
81330
  clientInfo.client.callTool({
80560
- name: tool3.originalName,
81331
+ name: tool4.originalName,
80561
81332
  arguments: args
80562
81333
  }),
80563
81334
  timeoutPromise
@@ -80580,11 +81351,11 @@ var init_client2 = __esm({
80580
81351
  */
80581
81352
  getTools() {
80582
81353
  const tools2 = {};
80583
- for (const [name14, tool3] of this.tools.entries()) {
81354
+ for (const [name14, tool4] of this.tools.entries()) {
80584
81355
  tools2[name14] = {
80585
- description: tool3.description,
80586
- inputSchema: tool3.inputSchema,
80587
- serverName: tool3.serverName
81356
+ description: tool4.description,
81357
+ inputSchema: tool4.inputSchema,
81358
+ serverName: tool4.serverName
80588
81359
  };
80589
81360
  }
80590
81361
  return tools2;
@@ -80595,10 +81366,10 @@ var init_client2 = __esm({
80595
81366
  */
80596
81367
  getVercelTools() {
80597
81368
  const tools2 = {};
80598
- for (const [name14, tool3] of this.tools.entries()) {
81369
+ for (const [name14, tool4] of this.tools.entries()) {
80599
81370
  tools2[name14] = {
80600
- description: tool3.description,
80601
- inputSchema: tool3.inputSchema,
81371
+ description: tool4.description,
81372
+ inputSchema: tool4.inputSchema,
80602
81373
  execute: async (args) => {
80603
81374
  const result = await this.callTool(name14, args);
80604
81375
  if (result.content && result.content[0]) {
@@ -80647,9 +81418,9 @@ var init_client2 = __esm({
80647
81418
  });
80648
81419
 
80649
81420
  // src/agent/mcp/xmlBridge.js
80650
- function mcpToolToXmlDefinition(name14, tool3) {
80651
- const description = tool3.description || "MCP tool";
80652
- const inputSchema = tool3.inputSchema || tool3.parameters || {};
81421
+ function mcpToolToXmlDefinition(name14, tool4) {
81422
+ const description = tool4.description || "MCP tool";
81423
+ const inputSchema = tool4.inputSchema || tool4.parameters || {};
80653
81424
  let paramDocs = "";
80654
81425
  if (inputSchema.properties) {
80655
81426
  paramDocs = "\n\nParameters (provide as JSON object):";
@@ -80828,8 +81599,8 @@ var init_xmlBridge = __esm({
80828
81599
  const vercelTools = this.mcpManager.getVercelTools();
80829
81600
  this.mcpTools = vercelTools;
80830
81601
  const toolCount = Object.keys(vercelTools).length;
80831
- for (const [name14, tool3] of Object.entries(vercelTools)) {
80832
- this.xmlDefinitions[name14] = mcpToolToXmlDefinition(name14, tool3);
81602
+ for (const [name14, tool4] of Object.entries(vercelTools)) {
81603
+ this.xmlDefinitions[name14] = mcpToolToXmlDefinition(name14, tool4);
80833
81604
  }
80834
81605
  if (toolCount === 0) {
80835
81606
  console.error("[MCP INFO] MCP initialization complete: 0 tools loaded");
@@ -80876,14 +81647,14 @@ var init_xmlBridge = __esm({
80876
81647
  console.error(`[MCP DEBUG] Executing MCP tool: ${toolName}`);
80877
81648
  console.error(`[MCP DEBUG] Parameters:`, JSON.stringify(params, null, 2));
80878
81649
  }
80879
- const tool3 = this.mcpTools[toolName];
80880
- if (!tool3) {
81650
+ const tool4 = this.mcpTools[toolName];
81651
+ if (!tool4) {
80881
81652
  console.error(`[MCP ERROR] Unknown MCP tool: ${toolName}`);
80882
81653
  console.error(`[MCP ERROR] Available tools: ${this.getToolNames().join(", ")}`);
80883
81654
  throw new Error(`Unknown MCP tool: ${toolName}`);
80884
81655
  }
80885
81656
  try {
80886
- const result = await tool3.execute(params);
81657
+ const result = await tool4.execute(params);
80887
81658
  if (this.debug) {
80888
81659
  console.error(`[MCP DEBUG] Tool ${toolName} executed successfully`);
80889
81660
  }
@@ -80937,26 +81708,640 @@ var init_mcp = __esm({
80937
81708
  }
80938
81709
  });
80939
81710
 
81711
+ // src/agent/RetryManager.js
81712
+ function isRetryableError(error2, retryableErrors = DEFAULT_RETRYABLE_ERRORS) {
81713
+ if (!error2) return false;
81714
+ const errorString = error2.toString().toLowerCase();
81715
+ const errorMessage = (error2.message || "").toLowerCase();
81716
+ const errorCode = (error2.code || "").toLowerCase();
81717
+ const errorType = (error2.type || "").toLowerCase();
81718
+ const statusCode = error2.statusCode || error2.status;
81719
+ for (const pattern of retryableErrors) {
81720
+ const lowerPattern = pattern.toLowerCase();
81721
+ if (errorString.includes(lowerPattern) || errorMessage.includes(lowerPattern) || errorCode.includes(lowerPattern) || errorType.includes(lowerPattern) || statusCode?.toString() === pattern) {
81722
+ return true;
81723
+ }
81724
+ }
81725
+ return false;
81726
+ }
81727
+ function extractErrorInfo(error2) {
81728
+ return {
81729
+ message: error2.message || error2.toString(),
81730
+ type: error2.type || error2.constructor.name,
81731
+ code: error2.code,
81732
+ statusCode: error2.statusCode || error2.status,
81733
+ provider: error2.provider,
81734
+ isRetryable: isRetryableError(error2)
81735
+ };
81736
+ }
81737
+ function sleep(ms) {
81738
+ return new Promise((resolve5) => setTimeout(resolve5, ms));
81739
+ }
81740
+ var DEFAULT_RETRYABLE_ERRORS, RetryManager;
81741
+ var init_RetryManager = __esm({
81742
+ "src/agent/RetryManager.js"() {
81743
+ "use strict";
81744
+ DEFAULT_RETRYABLE_ERRORS = [
81745
+ "Overloaded",
81746
+ "overloaded",
81747
+ "rate_limit",
81748
+ "rate limit",
81749
+ "429",
81750
+ "500",
81751
+ "502",
81752
+ "503",
81753
+ "504",
81754
+ "timeout",
81755
+ "ECONNRESET",
81756
+ "ETIMEDOUT",
81757
+ "ENOTFOUND",
81758
+ "api_error"
81759
+ ];
81760
+ RetryManager = class {
81761
+ /**
81762
+ * Create a new RetryManager
81763
+ * @param {Object} options - Configuration options
81764
+ * @param {number} [options.maxRetries=3] - Maximum retry attempts
81765
+ * @param {number} [options.initialDelay=1000] - Initial delay in ms (1 second)
81766
+ * @param {number} [options.maxDelay=30000] - Maximum delay in ms (30 seconds)
81767
+ * @param {number} [options.backoffFactor=2] - Exponential backoff multiplier
81768
+ * @param {Array<string>} [options.retryableErrors] - List of retryable error patterns
81769
+ * @param {boolean} [options.debug=false] - Enable debug logging
81770
+ */
81771
+ constructor(options = {}) {
81772
+ this.maxRetries = this._validateNumber(options.maxRetries, 3, "maxRetries", 0, 100);
81773
+ this.initialDelay = this._validateNumber(options.initialDelay, 1e3, "initialDelay", 0, 6e4);
81774
+ this.maxDelay = this._validateNumber(options.maxDelay, 3e4, "maxDelay", 0, 3e5);
81775
+ this.backoffFactor = this._validateNumber(options.backoffFactor, 2, "backoffFactor", 1, 10);
81776
+ this.retryableErrors = options.retryableErrors || DEFAULT_RETRYABLE_ERRORS;
81777
+ this.debug = options.debug ?? false;
81778
+ this.jitter = options.jitter ?? true;
81779
+ if (this.maxDelay < this.initialDelay) {
81780
+ throw new Error("maxDelay must be greater than or equal to initialDelay");
81781
+ }
81782
+ this.stats = {
81783
+ totalAttempts: 0,
81784
+ totalRetries: 0,
81785
+ successfulRetries: 0,
81786
+ failedRetries: 0
81787
+ };
81788
+ }
81789
+ /**
81790
+ * Validate a numeric parameter
81791
+ * @param {*} value - Value to validate
81792
+ * @param {number} defaultValue - Default if undefined
81793
+ * @param {string} name - Parameter name for error messages
81794
+ * @param {number} min - Minimum allowed value
81795
+ * @param {number} max - Maximum allowed value
81796
+ * @returns {number} - Validated number
81797
+ * @private
81798
+ */
81799
+ _validateNumber(value, defaultValue, name14, min, max) {
81800
+ if (value === void 0 || value === null) {
81801
+ return defaultValue;
81802
+ }
81803
+ const num = Number(value);
81804
+ if (isNaN(num)) {
81805
+ throw new Error(`${name14} must be a number, got: ${value}`);
81806
+ }
81807
+ if (num < min || num > max) {
81808
+ throw new Error(`${name14} must be between ${min} and ${max}, got: ${num}`);
81809
+ }
81810
+ return num;
81811
+ }
81812
+ /**
81813
+ * Execute a function with retry logic
81814
+ * @param {Function} fn - Async function to execute
81815
+ * @param {Object} [context={}] - Context information for logging
81816
+ * @param {AbortSignal} [context.signal] - Optional abort signal for cancellation
81817
+ * @returns {Promise<*>} - Result from the function
81818
+ * @throws {Error} - If all retries are exhausted or operation is aborted
81819
+ */
81820
+ async executeWithRetry(fn, context = {}) {
81821
+ let lastError = null;
81822
+ let currentDelay = this.initialDelay;
81823
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
81824
+ if (context.signal?.aborted) {
81825
+ const abortError = new Error("Operation aborted");
81826
+ abortError.name = "AbortError";
81827
+ throw abortError;
81828
+ }
81829
+ this.stats.totalAttempts++;
81830
+ try {
81831
+ if (this.debug && attempt > 0) {
81832
+ console.log(`[RetryManager] Retry attempt ${attempt}/${this.maxRetries}`, context);
81833
+ }
81834
+ const result = await fn();
81835
+ if (attempt > 0) {
81836
+ this.stats.successfulRetries++;
81837
+ if (this.debug) {
81838
+ console.log(`[RetryManager] \u2705 Retry successful on attempt ${attempt + 1}`, context);
81839
+ }
81840
+ }
81841
+ return result;
81842
+ } catch (error2) {
81843
+ lastError = error2;
81844
+ const errorInfo = extractErrorInfo(error2);
81845
+ const shouldRetry = isRetryableError(error2, this.retryableErrors);
81846
+ const hasRetriesLeft = attempt < this.maxRetries;
81847
+ if (this.debug) {
81848
+ console.log(`[RetryManager] \u274C Attempt ${attempt + 1}/${this.maxRetries + 1} failed:`, {
81849
+ ...context,
81850
+ error: errorInfo,
81851
+ shouldRetry,
81852
+ hasRetriesLeft
81853
+ });
81854
+ }
81855
+ if (!shouldRetry) {
81856
+ if (this.debug) {
81857
+ console.log(`[RetryManager] Error is not retryable, failing immediately`, errorInfo);
81858
+ }
81859
+ throw error2;
81860
+ }
81861
+ if (!hasRetriesLeft) {
81862
+ this.stats.failedRetries++;
81863
+ if (this.debug) {
81864
+ console.log(`[RetryManager] Max retries (${this.maxRetries}) exhausted`, context);
81865
+ }
81866
+ throw error2;
81867
+ }
81868
+ this.stats.totalRetries++;
81869
+ let delayWithJitter = currentDelay;
81870
+ if (this.jitter) {
81871
+ const jitterAmount = currentDelay * 0.25;
81872
+ delayWithJitter = currentDelay + (Math.random() * jitterAmount * 2 - jitterAmount);
81873
+ }
81874
+ if (this.debug) {
81875
+ console.log(`[RetryManager] Waiting ${Math.round(delayWithJitter)}ms before retry...`);
81876
+ }
81877
+ await sleep(delayWithJitter);
81878
+ currentDelay = Math.min(currentDelay * this.backoffFactor, this.maxDelay);
81879
+ }
81880
+ }
81881
+ throw lastError;
81882
+ }
81883
+ /**
81884
+ * Check if an error is retryable
81885
+ * @param {Error} error - The error to check
81886
+ * @returns {boolean} - True if error should be retried
81887
+ */
81888
+ isRetryable(error2) {
81889
+ return isRetryableError(error2, this.retryableErrors);
81890
+ }
81891
+ /**
81892
+ * Get retry statistics
81893
+ * @returns {Object} - Statistics object
81894
+ */
81895
+ getStats() {
81896
+ return { ...this.stats };
81897
+ }
81898
+ /**
81899
+ * Reset statistics
81900
+ */
81901
+ resetStats() {
81902
+ this.stats = {
81903
+ totalAttempts: 0,
81904
+ totalRetries: 0,
81905
+ successfulRetries: 0,
81906
+ failedRetries: 0
81907
+ };
81908
+ }
81909
+ };
81910
+ }
81911
+ });
81912
+
81913
+ // src/agent/FallbackManager.js
81914
+ function createFallbackManagerFromEnv(debug = false) {
81915
+ const fallbackProvidersEnv = process.env.FALLBACK_PROVIDERS;
81916
+ const fallbackModelsEnv = process.env.FALLBACK_MODELS;
81917
+ if (!fallbackProvidersEnv && !fallbackModelsEnv) {
81918
+ return null;
81919
+ }
81920
+ let providers = [];
81921
+ let models = [];
81922
+ let strategy = FALLBACK_STRATEGIES.ANY;
81923
+ if (fallbackProvidersEnv) {
81924
+ try {
81925
+ if (typeof fallbackProvidersEnv !== "string" || fallbackProvidersEnv.length > 1e4) {
81926
+ console.error("[FallbackManager] FALLBACK_PROVIDERS must be a valid JSON string under 10KB");
81927
+ return null;
81928
+ }
81929
+ const parsed = JSON.parse(fallbackProvidersEnv);
81930
+ if (!Array.isArray(parsed)) {
81931
+ console.error("[FallbackManager] FALLBACK_PROVIDERS must be a JSON array");
81932
+ return null;
81933
+ }
81934
+ providers = parsed;
81935
+ strategy = FALLBACK_STRATEGIES.CUSTOM;
81936
+ } catch (error2) {
81937
+ console.error("[FallbackManager] Failed to parse FALLBACK_PROVIDERS:", error2.message);
81938
+ return null;
81939
+ }
81940
+ }
81941
+ if (fallbackModelsEnv) {
81942
+ try {
81943
+ if (typeof fallbackModelsEnv !== "string" || fallbackModelsEnv.length > 1e4) {
81944
+ console.error("[FallbackManager] FALLBACK_MODELS must be a valid JSON string under 10KB");
81945
+ return null;
81946
+ }
81947
+ const parsed = JSON.parse(fallbackModelsEnv);
81948
+ if (!Array.isArray(parsed)) {
81949
+ console.error("[FallbackManager] FALLBACK_MODELS must be a JSON array");
81950
+ return null;
81951
+ }
81952
+ models = parsed;
81953
+ strategy = FALLBACK_STRATEGIES.SAME_PROVIDER;
81954
+ } catch (error2) {
81955
+ console.error("[FallbackManager] Failed to parse FALLBACK_MODELS:", error2.message);
81956
+ return null;
81957
+ }
81958
+ }
81959
+ const maxTotalAttempts = process.env.FALLBACK_MAX_TOTAL_ATTEMPTS ? (() => {
81960
+ const val = parseInt(process.env.FALLBACK_MAX_TOTAL_ATTEMPTS, 10);
81961
+ if (isNaN(val) || val < 1 || val > 100) {
81962
+ console.warn("[FallbackManager] FALLBACK_MAX_TOTAL_ATTEMPTS must be between 1 and 100, using default: 10");
81963
+ return 10;
81964
+ }
81965
+ return val;
81966
+ })() : 10;
81967
+ return new FallbackManager({
81968
+ strategy,
81969
+ providers,
81970
+ models,
81971
+ maxTotalAttempts,
81972
+ debug
81973
+ });
81974
+ }
81975
+ function buildFallbackProvidersFromEnv(options = {}) {
81976
+ const providers = [];
81977
+ const anthropicApiKey = process.env.ANTHROPIC_API_KEY || process.env.ANTHROPIC_AUTH_TOKEN;
81978
+ const openaiApiKey = process.env.OPENAI_API_KEY;
81979
+ const googleApiKey = process.env.GOOGLE_GENERATIVE_AI_API_KEY || process.env.GOOGLE_API_KEY;
81980
+ const awsAccessKeyId = process.env.AWS_ACCESS_KEY_ID;
81981
+ const awsSecretAccessKey = process.env.AWS_SECRET_ACCESS_KEY;
81982
+ const awsRegion = process.env.AWS_REGION;
81983
+ const awsApiKey = process.env.AWS_BEDROCK_API_KEY;
81984
+ const llmBaseUrl = process.env.LLM_BASE_URL;
81985
+ const anthropicApiUrl = process.env.ANTHROPIC_API_URL || process.env.ANTHROPIC_BASE_URL || llmBaseUrl;
81986
+ const openaiApiUrl = process.env.OPENAI_API_URL || llmBaseUrl;
81987
+ const googleApiUrl = process.env.GOOGLE_API_URL || llmBaseUrl;
81988
+ const awsBedrockBaseUrl = process.env.AWS_BEDROCK_BASE_URL || llmBaseUrl;
81989
+ const primaryProvider = options.primaryProvider?.toLowerCase();
81990
+ const primaryModel = options.primaryModel;
81991
+ if (primaryProvider === "anthropic" && anthropicApiKey) {
81992
+ providers.push({
81993
+ provider: "anthropic",
81994
+ apiKey: anthropicApiKey,
81995
+ ...anthropicApiUrl && { baseURL: anthropicApiUrl },
81996
+ ...primaryModel && { model: primaryModel }
81997
+ });
81998
+ } else if (primaryProvider === "openai" && openaiApiKey) {
81999
+ providers.push({
82000
+ provider: "openai",
82001
+ apiKey: openaiApiKey,
82002
+ ...openaiApiUrl && { baseURL: openaiApiUrl },
82003
+ ...primaryModel && { model: primaryModel }
82004
+ });
82005
+ } else if (primaryProvider === "google" && googleApiKey) {
82006
+ providers.push({
82007
+ provider: "google",
82008
+ apiKey: googleApiKey,
82009
+ ...googleApiUrl && { baseURL: googleApiUrl },
82010
+ ...primaryModel && { model: primaryModel }
82011
+ });
82012
+ } else if (primaryProvider === "bedrock" && (awsAccessKeyId && awsSecretAccessKey && awsRegion || awsApiKey)) {
82013
+ const config = { provider: "bedrock" };
82014
+ if (awsApiKey) {
82015
+ config.apiKey = awsApiKey;
82016
+ } else {
82017
+ config.accessKeyId = awsAccessKeyId;
82018
+ config.secretAccessKey = awsSecretAccessKey;
82019
+ config.region = awsRegion;
82020
+ if (process.env.AWS_SESSION_TOKEN) {
82021
+ config.sessionToken = process.env.AWS_SESSION_TOKEN;
82022
+ }
82023
+ }
82024
+ if (awsBedrockBaseUrl) config.baseURL = awsBedrockBaseUrl;
82025
+ if (primaryModel) config.model = primaryModel;
82026
+ providers.push(config);
82027
+ }
82028
+ if (anthropicApiKey && primaryProvider !== "anthropic") {
82029
+ providers.push({
82030
+ provider: "anthropic",
82031
+ apiKey: anthropicApiKey,
82032
+ ...anthropicApiUrl && { baseURL: anthropicApiUrl }
82033
+ });
82034
+ }
82035
+ if (openaiApiKey && primaryProvider !== "openai") {
82036
+ providers.push({
82037
+ provider: "openai",
82038
+ apiKey: openaiApiKey,
82039
+ ...openaiApiUrl && { baseURL: openaiApiUrl }
82040
+ });
82041
+ }
82042
+ if (googleApiKey && primaryProvider !== "google") {
82043
+ providers.push({
82044
+ provider: "google",
82045
+ apiKey: googleApiKey,
82046
+ ...googleApiUrl && { baseURL: googleApiUrl }
82047
+ });
82048
+ }
82049
+ if ((awsAccessKeyId && awsSecretAccessKey && awsRegion || awsApiKey) && primaryProvider !== "bedrock") {
82050
+ const config = { provider: "bedrock" };
82051
+ if (awsApiKey) {
82052
+ config.apiKey = awsApiKey;
82053
+ } else {
82054
+ config.accessKeyId = awsAccessKeyId;
82055
+ config.secretAccessKey = awsSecretAccessKey;
82056
+ config.region = awsRegion;
82057
+ if (process.env.AWS_SESSION_TOKEN) {
82058
+ config.sessionToken = process.env.AWS_SESSION_TOKEN;
82059
+ }
82060
+ }
82061
+ if (awsBedrockBaseUrl) config.baseURL = awsBedrockBaseUrl;
82062
+ providers.push(config);
82063
+ }
82064
+ return providers;
82065
+ }
82066
+ var import_anthropic, import_openai, import_google, FALLBACK_STRATEGIES, DEFAULT_MODELS, FallbackManager;
82067
+ var init_FallbackManager = __esm({
82068
+ "src/agent/FallbackManager.js"() {
82069
+ "use strict";
82070
+ import_anthropic = require("@ai-sdk/anthropic");
82071
+ import_openai = require("@ai-sdk/openai");
82072
+ import_google = require("@ai-sdk/google");
82073
+ init_dist3();
82074
+ FALLBACK_STRATEGIES = {
82075
+ SAME_MODEL: "same-model",
82076
+ // Try same model on different providers
82077
+ SAME_PROVIDER: "same-provider",
82078
+ // Try different models on same provider
82079
+ ANY: "any",
82080
+ // Try any available provider/model
82081
+ CUSTOM: "custom"
82082
+ // Use custom provider list
82083
+ };
82084
+ DEFAULT_MODELS = {
82085
+ anthropic: "claude-sonnet-4-5-20250929",
82086
+ openai: "gpt-4o",
82087
+ google: "gemini-2.0-flash-exp",
82088
+ bedrock: "anthropic.claude-sonnet-4-20250514-v1:0"
82089
+ };
82090
+ FallbackManager = class {
82091
+ /**
82092
+ * Create a new FallbackManager
82093
+ * @param {Object} options - Configuration options
82094
+ * @param {string} [options.strategy='any'] - Fallback strategy
82095
+ * @param {Array<string>} [options.models] - List of models for same-provider fallback
82096
+ * @param {Array<ProviderConfig>} [options.providers] - List of provider configurations
82097
+ * @param {boolean} [options.stopOnSuccess=true] - Stop on first success
82098
+ * @param {boolean} [options.continueOnNonRetryableError=false] - Continue to fallback on non-retryable errors
82099
+ * @param {number} [options.maxTotalAttempts=10] - Maximum total attempts across all providers
82100
+ * @param {boolean} [options.debug=false] - Enable debug logging
82101
+ */
82102
+ constructor(options = {}) {
82103
+ this.strategy = options.strategy || FALLBACK_STRATEGIES.ANY;
82104
+ this.models = Array.isArray(options.models) ? options.models : [];
82105
+ this.providers = Array.isArray(options.providers) ? options.providers : [];
82106
+ this.stopOnSuccess = options.stopOnSuccess ?? true;
82107
+ this.continueOnNonRetryableError = options.continueOnNonRetryableError ?? false;
82108
+ this.debug = options.debug ?? false;
82109
+ const maxAttempts = options.maxTotalAttempts ?? 10;
82110
+ if (typeof maxAttempts !== "number" || isNaN(maxAttempts) || maxAttempts < 1 || maxAttempts > 100) {
82111
+ throw new Error(`FallbackManager: maxTotalAttempts must be a number between 1 and 100, got: ${maxAttempts}`);
82112
+ }
82113
+ this.maxTotalAttempts = maxAttempts;
82114
+ this.stats = {
82115
+ totalAttempts: 0,
82116
+ providerAttempts: {},
82117
+ successfulProvider: null,
82118
+ failedProviders: []
82119
+ };
82120
+ this._validateConfiguration();
82121
+ }
82122
+ /**
82123
+ * Validate the fallback configuration
82124
+ * @private
82125
+ */
82126
+ _validateConfiguration() {
82127
+ if (this.strategy === FALLBACK_STRATEGIES.SAME_PROVIDER && this.models.length === 0) {
82128
+ throw new Error('FallbackManager: strategy "same-provider" requires models list');
82129
+ }
82130
+ if (this.strategy === FALLBACK_STRATEGIES.CUSTOM && this.providers.length === 0) {
82131
+ throw new Error('FallbackManager: strategy "custom" requires providers list');
82132
+ }
82133
+ for (const config of this.providers) {
82134
+ if (!config.provider) {
82135
+ throw new Error('FallbackManager: Each provider config must have a "provider" field');
82136
+ }
82137
+ if (!["anthropic", "openai", "google", "bedrock"].includes(config.provider)) {
82138
+ throw new Error(`FallbackManager: Invalid provider "${config.provider}". Must be: anthropic, openai, google, or bedrock`);
82139
+ }
82140
+ if (config.provider === "bedrock") {
82141
+ const hasCredentials = config.accessKeyId && config.secretAccessKey && config.region;
82142
+ const hasApiKey = config.apiKey;
82143
+ if (!hasCredentials && !hasApiKey) {
82144
+ throw new Error("FallbackManager: Bedrock provider requires either (accessKeyId, secretAccessKey, region) or apiKey");
82145
+ }
82146
+ } else {
82147
+ if (!config.apiKey) {
82148
+ throw new Error(`FallbackManager: Provider "${config.provider}" requires apiKey`);
82149
+ }
82150
+ }
82151
+ }
82152
+ }
82153
+ /**
82154
+ * Create a provider instance from configuration
82155
+ * @param {ProviderConfig} config - Provider configuration
82156
+ * @returns {Object} - Provider instance
82157
+ * @throws {Error} - If provider creation fails
82158
+ * @private
82159
+ */
82160
+ _createProviderInstance(config) {
82161
+ try {
82162
+ switch (config.provider) {
82163
+ case "anthropic":
82164
+ return (0, import_anthropic.createAnthropic)({
82165
+ apiKey: config.apiKey,
82166
+ ...config.baseURL && { baseURL: config.baseURL }
82167
+ });
82168
+ case "openai":
82169
+ return (0, import_openai.createOpenAI)({
82170
+ compatibility: "strict",
82171
+ apiKey: config.apiKey,
82172
+ ...config.baseURL && { baseURL: config.baseURL }
82173
+ });
82174
+ case "google":
82175
+ return (0, import_google.createGoogleGenerativeAI)({
82176
+ apiKey: config.apiKey,
82177
+ ...config.baseURL && { baseURL: config.baseURL }
82178
+ });
82179
+ case "bedrock": {
82180
+ const bedrockConfig = {};
82181
+ if (config.apiKey) {
82182
+ bedrockConfig.apiKey = config.apiKey;
82183
+ } else if (config.accessKeyId && config.secretAccessKey) {
82184
+ bedrockConfig.accessKeyId = config.accessKeyId;
82185
+ bedrockConfig.secretAccessKey = config.secretAccessKey;
82186
+ if (config.sessionToken) {
82187
+ bedrockConfig.sessionToken = config.sessionToken;
82188
+ }
82189
+ }
82190
+ if (config.region) {
82191
+ bedrockConfig.region = config.region;
82192
+ }
82193
+ if (config.baseURL) {
82194
+ bedrockConfig.baseURL = config.baseURL;
82195
+ }
82196
+ return createAmazonBedrock(bedrockConfig);
82197
+ }
82198
+ default:
82199
+ throw new Error(`FallbackManager: Unknown provider "${config.provider}"`);
82200
+ }
82201
+ } catch (error2) {
82202
+ const providerName = this._getProviderDisplayName(config);
82203
+ throw new Error(`Failed to create provider instance for ${providerName}: ${error2.message}`);
82204
+ }
82205
+ }
82206
+ /**
82207
+ * Get the model name for a provider configuration
82208
+ * @param {ProviderConfig} config - Provider configuration
82209
+ * @returns {string} - Model name
82210
+ * @private
82211
+ */
82212
+ _getModelName(config) {
82213
+ return config.model || DEFAULT_MODELS[config.provider];
82214
+ }
82215
+ /**
82216
+ * Get provider display name for logging
82217
+ * @param {ProviderConfig} config - Provider configuration
82218
+ * @returns {string} - Display name
82219
+ * @private
82220
+ */
82221
+ _getProviderDisplayName(config) {
82222
+ const model = this._getModelName(config);
82223
+ const provider = config.provider;
82224
+ const url = config.baseURL ? ` (${config.baseURL})` : "";
82225
+ return `${provider}/${model}${url}`;
82226
+ }
82227
+ /**
82228
+ * Execute a function with fallback support
82229
+ * @param {Function} fn - Function that takes (provider, model, config) and returns a Promise
82230
+ * @returns {Promise<*>} - Result from the function
82231
+ * @throws {Error} - If all fallbacks are exhausted
82232
+ */
82233
+ async executeWithFallback(fn) {
82234
+ if (this.providers.length === 0) {
82235
+ throw new Error("FallbackManager: No providers configured for fallback");
82236
+ }
82237
+ let lastError = null;
82238
+ let totalAttempts = 0;
82239
+ for (const config of this.providers) {
82240
+ if (totalAttempts >= this.maxTotalAttempts) {
82241
+ if (this.debug) {
82242
+ console.log(`[FallbackManager] \u26A0\uFE0F Max total attempts (${this.maxTotalAttempts}) reached`);
82243
+ }
82244
+ break;
82245
+ }
82246
+ totalAttempts++;
82247
+ this.stats.totalAttempts++;
82248
+ const providerName = this._getProviderDisplayName(config);
82249
+ this.stats.providerAttempts[providerName] = (this.stats.providerAttempts[providerName] || 0) + 1;
82250
+ try {
82251
+ if (this.debug) {
82252
+ console.log(`[FallbackManager] Attempting provider: ${providerName} (attempt ${totalAttempts}/${this.maxTotalAttempts})`);
82253
+ }
82254
+ const provider = this._createProviderInstance(config);
82255
+ const model = this._getModelName(config);
82256
+ const result = await fn(provider, model, config);
82257
+ this.stats.successfulProvider = providerName;
82258
+ if (this.debug) {
82259
+ console.log(`[FallbackManager] \u2705 Success with provider: ${providerName}`);
82260
+ }
82261
+ return result;
82262
+ } catch (error2) {
82263
+ lastError = error2;
82264
+ const errorInfo = {
82265
+ message: error2.message || error2.toString(),
82266
+ type: error2.type || error2.constructor.name,
82267
+ statusCode: error2.statusCode || error2.status
82268
+ };
82269
+ this.stats.failedProviders.push({
82270
+ provider: providerName,
82271
+ error: errorInfo
82272
+ });
82273
+ if (this.debug) {
82274
+ console.log(`[FallbackManager] \u274C Failed with provider: ${providerName}`, errorInfo);
82275
+ }
82276
+ if (!this.continueOnNonRetryableError && error2.nonRetryable) {
82277
+ if (this.debug) {
82278
+ console.log(`[FallbackManager] Non-retryable error, stopping fallback chain`);
82279
+ }
82280
+ throw error2;
82281
+ }
82282
+ if (this.debug) {
82283
+ const remaining = this.providers.length - (this.providers.indexOf(config) + 1);
82284
+ console.log(`[FallbackManager] Trying next provider (${remaining} remaining)...`);
82285
+ }
82286
+ }
82287
+ }
82288
+ if (this.debug) {
82289
+ console.log(`[FallbackManager] \u274C All providers exhausted. Total attempts: ${totalAttempts}`);
82290
+ }
82291
+ const fallbackError = new Error(
82292
+ `All provider fallbacks exhausted after ${totalAttempts} attempts. Last error: ${lastError?.message || "Unknown error"}`
82293
+ );
82294
+ fallbackError.cause = lastError;
82295
+ fallbackError.stats = this.getStats();
82296
+ fallbackError.allProvidersFailed = true;
82297
+ throw fallbackError;
82298
+ }
82299
+ /**
82300
+ * Get fallback statistics
82301
+ * @returns {Object} - Statistics object
82302
+ */
82303
+ getStats() {
82304
+ return {
82305
+ ...this.stats,
82306
+ providerAttempts: { ...this.stats.providerAttempts },
82307
+ failedProviders: [...this.stats.failedProviders]
82308
+ };
82309
+ }
82310
+ /**
82311
+ * Reset statistics
82312
+ */
82313
+ resetStats() {
82314
+ this.stats = {
82315
+ totalAttempts: 0,
82316
+ providerAttempts: {},
82317
+ successfulProvider: null,
82318
+ failedProviders: []
82319
+ };
82320
+ }
82321
+ };
82322
+ }
82323
+ });
82324
+
80940
82325
  // src/agent/ProbeAgent.js
80941
82326
  var ProbeAgent_exports = {};
80942
82327
  __export(ProbeAgent_exports, {
80943
82328
  ProbeAgent: () => ProbeAgent
80944
82329
  });
80945
82330
  module.exports = __toCommonJS(ProbeAgent_exports);
80946
- var import_dotenv2, import_anthropic, import_openai, import_google, import_ai3, import_crypto5, import_events2, import_fs8, import_promises2, import_path10, MAX_TOOL_ITERATIONS, MAX_HISTORY_MESSAGES, MAX_IMAGE_FILE_SIZE, ProbeAgent;
82331
+ var import_dotenv2, import_anthropic2, import_openai2, import_google2, import_ai4, import_crypto5, import_events2, import_fs10, import_promises2, import_path11, MAX_TOOL_ITERATIONS, MAX_HISTORY_MESSAGES, MAX_IMAGE_FILE_SIZE, ProbeAgent;
80947
82332
  var init_ProbeAgent = __esm({
80948
82333
  "src/agent/ProbeAgent.js"() {
80949
82334
  import_dotenv2 = __toESM(require_main(), 1);
80950
- import_anthropic = require("@ai-sdk/anthropic");
80951
- import_openai = require("@ai-sdk/openai");
80952
- import_google = require("@ai-sdk/google");
82335
+ import_anthropic2 = require("@ai-sdk/anthropic");
82336
+ import_openai2 = require("@ai-sdk/openai");
82337
+ import_google2 = require("@ai-sdk/google");
80953
82338
  init_dist3();
80954
- import_ai3 = require("ai");
82339
+ import_ai4 = require("ai");
80955
82340
  import_crypto5 = require("crypto");
80956
82341
  import_events2 = require("events");
80957
- import_fs8 = require("fs");
82342
+ import_fs10 = require("fs");
80958
82343
  import_promises2 = require("fs/promises");
80959
- import_path10 = require("path");
82344
+ import_path11 = require("path");
80960
82345
  init_tokenCounter();
80961
82346
  init_InMemoryStorageAdapter();
80962
82347
  init_HookManager();
@@ -80969,8 +82354,17 @@ var init_ProbeAgent = __esm({
80969
82354
  init_schemaUtils();
80970
82355
  init_xmlParsingUtils();
80971
82356
  init_mcp();
82357
+ init_RetryManager();
82358
+ init_FallbackManager();
80972
82359
  import_dotenv2.default.config();
80973
- MAX_TOOL_ITERATIONS = parseInt(process.env.MAX_TOOL_ITERATIONS || "30", 10);
82360
+ MAX_TOOL_ITERATIONS = (() => {
82361
+ const val = parseInt(process.env.MAX_TOOL_ITERATIONS || "30", 10);
82362
+ if (isNaN(val) || val < 1 || val > 200) {
82363
+ console.warn("[ProbeAgent] MAX_TOOL_ITERATIONS must be between 1 and 200, using default: 30");
82364
+ return 30;
82365
+ }
82366
+ return val;
82367
+ })();
80974
82368
  MAX_HISTORY_MESSAGES = 100;
80975
82369
  MAX_IMAGE_FILE_SIZE = 20 * 1024 * 1024;
80976
82370
  ProbeAgent = class _ProbeAgent {
@@ -80981,6 +82375,7 @@ var init_ProbeAgent = __esm({
80981
82375
  * @param {string} [options.customPrompt] - Custom prompt to replace the default system message
80982
82376
  * @param {string} [options.promptType] - Predefined prompt type (architect, code-review, support)
80983
82377
  * @param {boolean} [options.allowEdit=false] - Allow the use of the 'implement' tool
82378
+ * @param {boolean} [options.enableDelegate=false] - Enable the delegate tool for task distribution to subagents
80984
82379
  * @param {string} [options.path] - Search directory path
80985
82380
  * @param {string} [options.provider] - Force specific AI provider
80986
82381
  * @param {string} [options.model] - Override model name
@@ -80996,17 +82391,36 @@ var init_ProbeAgent = __esm({
80996
82391
  * @param {Array} [options.mcpServers] - Deprecated, use mcpConfig instead
80997
82392
  * @param {Object} [options.storageAdapter] - Custom storage adapter for history management
80998
82393
  * @param {Object} [options.hooks] - Hook callbacks for events (e.g., {'tool:start': callback})
82394
+ * @param {Object} [options.retry] - Retry configuration
82395
+ * @param {number} [options.retry.maxRetries=3] - Maximum retry attempts per provider
82396
+ * @param {number} [options.retry.initialDelay=1000] - Initial delay in ms
82397
+ * @param {number} [options.retry.maxDelay=30000] - Maximum delay in ms
82398
+ * @param {number} [options.retry.backoffFactor=2] - Exponential backoff multiplier
82399
+ * @param {Array<string>} [options.retry.retryableErrors] - List of retryable error patterns
82400
+ * @param {Object} [options.fallback] - Fallback configuration
82401
+ * @param {string} [options.fallback.strategy] - Fallback strategy: 'same-model', 'same-provider', 'any', 'custom'
82402
+ * @param {Array<string>} [options.fallback.models] - List of models for same-provider fallback
82403
+ * @param {Array<Object>} [options.fallback.providers] - List of provider configurations for custom fallback
82404
+ * @param {boolean} [options.fallback.stopOnSuccess=true] - Stop on first success
82405
+ * @param {number} [options.fallback.maxTotalAttempts=10] - Maximum total attempts across all providers
80999
82406
  */
81000
82407
  constructor(options = {}) {
81001
82408
  this.sessionId = options.sessionId || (0, import_crypto5.randomUUID)();
81002
82409
  this.customPrompt = options.customPrompt || null;
81003
82410
  this.promptType = options.promptType || "code-explorer";
81004
82411
  this.allowEdit = !!options.allowEdit;
82412
+ this.enableDelegate = !!options.enableDelegate;
81005
82413
  this.debug = options.debug || process.env.DEBUG === "1";
81006
82414
  this.cancelled = false;
81007
82415
  this.tracer = options.tracer || null;
81008
82416
  this.outline = !!options.outline;
81009
- this.maxResponseTokens = options.maxResponseTokens || parseInt(process.env.MAX_RESPONSE_TOKENS || "0", 10) || null;
82417
+ this.maxResponseTokens = options.maxResponseTokens || (() => {
82418
+ const val = parseInt(process.env.MAX_RESPONSE_TOKENS || "0", 10);
82419
+ if (isNaN(val) || val < 0 || val > 2e5) {
82420
+ return null;
82421
+ }
82422
+ return val || null;
82423
+ })();
81010
82424
  this.maxIterations = options.maxIterations || null;
81011
82425
  this.disableMermaidValidation = !!options.disableMermaidValidation;
81012
82426
  this.disableJsonValidation = !!options.disableJsonValidation;
@@ -81047,6 +82461,10 @@ var init_ProbeAgent = __esm({
81047
82461
  this.mcpServers = options.mcpServers || null;
81048
82462
  this.mcpBridge = null;
81049
82463
  this._mcpInitialized = false;
82464
+ this.retryConfig = options.retry || {};
82465
+ this.retryManager = null;
82466
+ this.fallbackConfig = options.fallback || null;
82467
+ this.fallbackManager = null;
81050
82468
  this.initializeModel();
81051
82469
  }
81052
82470
  /**
@@ -81131,6 +82549,14 @@ var init_ProbeAgent = __esm({
81131
82549
  if (this.enableBash && wrappedTools.bashToolInstance) {
81132
82550
  this.toolImplementations.bash = wrappedTools.bashToolInstance;
81133
82551
  }
82552
+ if (this.allowEdit) {
82553
+ if (wrappedTools.editToolInstance) {
82554
+ this.toolImplementations.edit = wrappedTools.editToolInstance;
82555
+ }
82556
+ if (wrappedTools.createToolInstance) {
82557
+ this.toolImplementations.create = wrappedTools.createToolInstance;
82558
+ }
82559
+ }
81134
82560
  this.wrappedTools = wrappedTools;
81135
82561
  if (this.debug) {
81136
82562
  console.error("\n[DEBUG] ========================================");
@@ -81181,36 +82607,147 @@ var init_ProbeAgent = __esm({
81181
82607
  if (forceProvider) {
81182
82608
  if (forceProvider === "anthropic" && anthropicApiKey) {
81183
82609
  this.initializeAnthropicModel(anthropicApiKey, anthropicApiUrl, modelName);
82610
+ this.initializeFallbackManager(forceProvider, modelName);
81184
82611
  return;
81185
82612
  } else if (forceProvider === "openai" && openaiApiKey) {
81186
82613
  this.initializeOpenAIModel(openaiApiKey, openaiApiUrl, modelName);
82614
+ this.initializeFallbackManager(forceProvider, modelName);
81187
82615
  return;
81188
82616
  } else if (forceProvider === "google" && googleApiKey) {
81189
82617
  this.initializeGoogleModel(googleApiKey, googleApiUrl, modelName);
82618
+ this.initializeFallbackManager(forceProvider, modelName);
81190
82619
  return;
81191
82620
  } else if (forceProvider === "bedrock" && (awsAccessKeyId && awsSecretAccessKey && awsRegion || awsApiKey)) {
81192
82621
  this.initializeBedrockModel(awsAccessKeyId, awsSecretAccessKey, awsRegion, awsSessionToken, awsApiKey, awsBedrockBaseUrl, modelName);
82622
+ this.initializeFallbackManager(forceProvider, modelName);
81193
82623
  return;
81194
82624
  }
81195
82625
  console.warn(`WARNING: Forced provider "${forceProvider}" selected but required API key is missing or invalid! Falling back to auto-detection.`);
81196
82626
  }
81197
82627
  if (anthropicApiKey) {
81198
82628
  this.initializeAnthropicModel(anthropicApiKey, anthropicApiUrl, modelName);
82629
+ this.initializeFallbackManager("anthropic", modelName);
81199
82630
  } else if (openaiApiKey) {
81200
82631
  this.initializeOpenAIModel(openaiApiKey, openaiApiUrl, modelName);
82632
+ this.initializeFallbackManager("openai", modelName);
81201
82633
  } else if (googleApiKey) {
81202
82634
  this.initializeGoogleModel(googleApiKey, googleApiUrl, modelName);
82635
+ this.initializeFallbackManager("google", modelName);
81203
82636
  } else if (awsAccessKeyId && awsSecretAccessKey && awsRegion || awsApiKey) {
81204
82637
  this.initializeBedrockModel(awsAccessKeyId, awsSecretAccessKey, awsRegion, awsSessionToken, awsApiKey, awsBedrockBaseUrl, modelName);
82638
+ this.initializeFallbackManager("bedrock", modelName);
81205
82639
  } else {
81206
82640
  throw new Error("No API key provided. Please set ANTHROPIC_API_KEY (or ANTHROPIC_AUTH_TOKEN), OPENAI_API_KEY, GOOGLE_GENERATIVE_AI_API_KEY (or GOOGLE_API_KEY), AWS credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION), or AWS_BEDROCK_API_KEY environment variables.");
81207
82641
  }
81208
82642
  }
82643
+ /**
82644
+ * Initialize fallback manager based on configuration
82645
+ * @param {string} primaryProvider - The primary provider being used
82646
+ * @param {string} primaryModel - The primary model being used
82647
+ * @private
82648
+ */
82649
+ initializeFallbackManager(primaryProvider, primaryModel) {
82650
+ if (this.fallbackConfig === false || process.env.DISABLE_FALLBACK === "1") {
82651
+ return;
82652
+ }
82653
+ if (this.fallbackConfig && this.fallbackConfig.providers) {
82654
+ try {
82655
+ this.fallbackManager = new FallbackManager({
82656
+ ...this.fallbackConfig,
82657
+ debug: this.debug
82658
+ });
82659
+ if (this.debug) {
82660
+ console.log(`[DEBUG] Fallback manager initialized with ${this.fallbackManager.providers.length} providers`);
82661
+ }
82662
+ } catch (error2) {
82663
+ console.error("[WARNING] Failed to initialize fallback manager:", error2.message);
82664
+ }
82665
+ return;
82666
+ }
82667
+ const envFallbackManager = createFallbackManagerFromEnv(this.debug);
82668
+ if (envFallbackManager) {
82669
+ this.fallbackManager = envFallbackManager;
82670
+ if (this.debug) {
82671
+ console.log(`[DEBUG] Fallback manager initialized from environment variables`);
82672
+ }
82673
+ return;
82674
+ }
82675
+ if (process.env.AUTO_FALLBACK === "1" || this.fallbackConfig?.auto) {
82676
+ const providers = buildFallbackProvidersFromEnv({
82677
+ primaryProvider,
82678
+ primaryModel
82679
+ });
82680
+ if (providers.length > 1) {
82681
+ try {
82682
+ this.fallbackManager = new FallbackManager({
82683
+ strategy: "custom",
82684
+ providers,
82685
+ debug: this.debug
82686
+ });
82687
+ if (this.debug) {
82688
+ console.log(`[DEBUG] Auto-fallback enabled with ${providers.length} providers`);
82689
+ }
82690
+ } catch (error2) {
82691
+ console.error("[WARNING] Failed to initialize auto-fallback:", error2.message);
82692
+ }
82693
+ }
82694
+ }
82695
+ }
82696
+ /**
82697
+ * Execute streamText with retry and fallback support
82698
+ * @param {Object} options - streamText options
82699
+ * @returns {Promise<Object>} - streamText result
82700
+ * @private
82701
+ */
82702
+ async streamTextWithRetryAndFallback(options) {
82703
+ if (!this.retryManager) {
82704
+ this.retryManager = new RetryManager({
82705
+ maxRetries: this.retryConfig.maxRetries ?? 3,
82706
+ initialDelay: this.retryConfig.initialDelay ?? 1e3,
82707
+ maxDelay: this.retryConfig.maxDelay ?? 3e4,
82708
+ backoffFactor: this.retryConfig.backoffFactor ?? 2,
82709
+ retryableErrors: this.retryConfig.retryableErrors,
82710
+ debug: this.debug
82711
+ });
82712
+ }
82713
+ if (!this.fallbackManager) {
82714
+ return await this.retryManager.executeWithRetry(
82715
+ () => (0, import_ai4.streamText)(options),
82716
+ {
82717
+ provider: this.apiType,
82718
+ model: this.model
82719
+ }
82720
+ );
82721
+ }
82722
+ return await this.fallbackManager.executeWithFallback(
82723
+ async (provider, model, config) => {
82724
+ const fallbackOptions = {
82725
+ ...options,
82726
+ model: provider(model)
82727
+ };
82728
+ const providerRetryManager = new RetryManager({
82729
+ maxRetries: config.maxRetries ?? this.retryConfig.maxRetries ?? 3,
82730
+ initialDelay: this.retryConfig.initialDelay ?? 1e3,
82731
+ maxDelay: this.retryConfig.maxDelay ?? 3e4,
82732
+ backoffFactor: this.retryConfig.backoffFactor ?? 2,
82733
+ retryableErrors: this.retryConfig.retryableErrors,
82734
+ debug: this.debug
82735
+ });
82736
+ return await providerRetryManager.executeWithRetry(
82737
+ () => (0, import_ai4.streamText)(fallbackOptions),
82738
+ {
82739
+ provider: config.provider,
82740
+ model
82741
+ }
82742
+ );
82743
+ }
82744
+ );
82745
+ }
81209
82746
  /**
81210
82747
  * Initialize Anthropic model
81211
82748
  */
81212
82749
  initializeAnthropicModel(apiKey, apiUrl, modelName) {
81213
- this.provider = (0, import_anthropic.createAnthropic)({
82750
+ this.provider = (0, import_anthropic2.createAnthropic)({
81214
82751
  apiKey,
81215
82752
  ...apiUrl && { baseURL: apiUrl }
81216
82753
  });
@@ -81224,7 +82761,7 @@ var init_ProbeAgent = __esm({
81224
82761
  * Initialize OpenAI model
81225
82762
  */
81226
82763
  initializeOpenAIModel(apiKey, apiUrl, modelName) {
81227
- this.provider = (0, import_openai.createOpenAI)({
82764
+ this.provider = (0, import_openai2.createOpenAI)({
81228
82765
  compatibility: "strict",
81229
82766
  apiKey,
81230
82767
  ...apiUrl && { baseURL: apiUrl }
@@ -81239,7 +82776,7 @@ var init_ProbeAgent = __esm({
81239
82776
  * Initialize Google model
81240
82777
  */
81241
82778
  initializeGoogleModel(apiKey, apiUrl, modelName) {
81242
- this.provider = (0, import_google.createGoogleGenerativeAI)({
82779
+ this.provider = (0, import_google2.createGoogleGenerativeAI)({
81243
82780
  apiKey,
81244
82781
  ...apiUrl && { baseURL: apiUrl }
81245
82782
  });
@@ -81314,7 +82851,7 @@ var init_ProbeAgent = __esm({
81314
82851
  let resolvedPath2 = imagePath;
81315
82852
  if (!imagePath.includes("/") && !imagePath.includes("\\")) {
81316
82853
  for (const dir of listFilesDirectories) {
81317
- const potentialPath = (0, import_path10.resolve)(dir, imagePath);
82854
+ const potentialPath = (0, import_path11.resolve)(dir, imagePath);
81318
82855
  const loaded = await this.loadImageIfValid(potentialPath);
81319
82856
  if (loaded) {
81320
82857
  if (this.debug) {
@@ -81339,7 +82876,7 @@ var init_ProbeAgent = __esm({
81339
82876
  let match2;
81340
82877
  while ((match2 = fileHeaderPattern.exec(content)) !== null) {
81341
82878
  const filePath = match2[1].trim();
81342
- const dir = (0, import_path10.dirname)(filePath);
82879
+ const dir = (0, import_path11.dirname)(filePath);
81343
82880
  if (dir && dir !== ".") {
81344
82881
  directories.push(dir);
81345
82882
  if (this.debug) {
@@ -81383,21 +82920,21 @@ var init_ProbeAgent = __esm({
81383
82920
  }
81384
82921
  const allowedDirs = this.allowedFolders && this.allowedFolders.length > 0 ? this.allowedFolders : [process.cwd()];
81385
82922
  let absolutePath;
81386
- let isPathAllowed = false;
81387
- if ((0, import_path10.isAbsolute)(imagePath)) {
82923
+ let isPathAllowed2 = false;
82924
+ if ((0, import_path11.isAbsolute)(imagePath)) {
81388
82925
  absolutePath = imagePath;
81389
- isPathAllowed = allowedDirs.some((dir) => absolutePath.startsWith((0, import_path10.resolve)(dir)));
82926
+ isPathAllowed2 = allowedDirs.some((dir) => absolutePath.startsWith((0, import_path11.resolve)(dir)));
81390
82927
  } else {
81391
82928
  for (const dir of allowedDirs) {
81392
- const resolvedPath2 = (0, import_path10.resolve)(dir, imagePath);
81393
- if (resolvedPath2.startsWith((0, import_path10.resolve)(dir))) {
82929
+ const resolvedPath2 = (0, import_path11.resolve)(dir, imagePath);
82930
+ if (resolvedPath2.startsWith((0, import_path11.resolve)(dir))) {
81394
82931
  absolutePath = resolvedPath2;
81395
- isPathAllowed = true;
82932
+ isPathAllowed2 = true;
81396
82933
  break;
81397
82934
  }
81398
82935
  }
81399
82936
  }
81400
- if (!isPathAllowed) {
82937
+ if (!isPathAllowed2) {
81401
82938
  if (this.debug) {
81402
82939
  console.log(`[DEBUG] Image path outside allowed directories: ${imagePath}`);
81403
82940
  }
@@ -81596,6 +83133,18 @@ ${attemptCompletionToolDefinition}
81596
83133
  `;
81597
83134
  if (this.allowEdit) {
81598
83135
  toolDefinitions += `${implementToolDefinition}
83136
+ `;
83137
+ toolDefinitions += `${editToolDefinition}
83138
+ `;
83139
+ toolDefinitions += `${createToolDefinition}
83140
+ `;
83141
+ }
83142
+ if (this.enableBash) {
83143
+ toolDefinitions += `${bashToolDefinition}
83144
+ `;
83145
+ }
83146
+ if (this.enableDelegate) {
83147
+ toolDefinitions += `${delegateToolDefinition}
81599
83148
  `;
81600
83149
  }
81601
83150
  let xmlToolGuidelines = `
@@ -81659,7 +83208,7 @@ Available Tools:
81659
83208
  - extract: Extract specific code blocks or lines from files.
81660
83209
  - listFiles: List files and directories in a specified location.
81661
83210
  - searchFiles: Find files matching a glob pattern with recursive search capability.
81662
- ${this.allowEdit ? "- implement: Implement a feature or fix a bug using aider.\n" : ""}
83211
+ ${this.allowEdit ? "- implement: Implement a feature or fix a bug using aider.\n- edit: Edit files using exact string replacement.\n- create: Create new files with specified content.\n" : ""}${this.enableDelegate ? "- delegate: Delegate big distinct tasks to specialized probe subagents.\n" : ""}${this.enableBash ? "- bash: Execute bash commands for system operations.\n" : ""}
81663
83212
  - attempt_completion: Finalize the task and provide the result to the user.
81664
83213
  - attempt_complete: Quick completion using previous response (shorthand).
81665
83214
  `;
@@ -81673,7 +83222,10 @@ Follow these instructions carefully:
81673
83222
  6. You MUST respond with exactly ONE tool call per message, using the specified XML format, until the task is complete.
81674
83223
  7. Wait for the tool execution result (provided in the next user message in a <tool_result> block) before proceeding to the next step.
81675
83224
  8. Once the task is fully completed, use the '<attempt_completion>' tool to provide the final result. This is the ONLY way to signal completion.
81676
- 9. Prefer concise and focused search queries. Use specific keywords and phrases to narrow down results.
83225
+ 9. Prefer concise and focused search queries. Use specific keywords and phrases to narrow down results.${this.allowEdit ? `
83226
+ 10. When modifying files, choose the appropriate tool:
83227
+ - Use 'edit' for precise changes to existing files (requires exact string match)
83228
+ - Use 'create' for new files or complete file rewrites` : ""}
81677
83229
  </instructions>
81678
83230
  `;
81679
83231
  const predefinedPrompts = {
@@ -81925,7 +83477,7 @@ You are working with a repository located at: ${searchDirectory}
81925
83477
  try {
81926
83478
  const executeAIRequest = async () => {
81927
83479
  const messagesForAI = this.prepareMessagesWithImages(currentMessages);
81928
- const result = await (0, import_ai3.streamText)({
83480
+ const result = await this.streamTextWithRetryAndFallback({
81929
83481
  model: this.provider(this.model),
81930
83482
  messages: messagesForAI,
81931
83483
  maxTokens: maxResponseTokens,
@@ -81977,7 +83529,13 @@ You are working with a repository located at: ${searchDirectory}
81977
83529
  "attempt_completion"
81978
83530
  ];
81979
83531
  if (this.allowEdit) {
81980
- validTools.push("implement");
83532
+ validTools.push("implement", "edit", "create");
83533
+ }
83534
+ if (this.enableBash) {
83535
+ validTools.push("bash");
83536
+ }
83537
+ if (this.enableDelegate) {
83538
+ validTools.push("delegate");
81981
83539
  }
81982
83540
  const nativeTools = validTools;
81983
83541
  const parsedTool = this.mcpBridge ? parseHybridXmlToolCall(assistantResponseContent, nativeTools, this.mcpBridge) : parseXmlToolCallWithThinking(assistantResponseContent, validTools);
@@ -82092,11 +83650,21 @@ ${toolResultContent}
82092
83650
  ...toolParams,
82093
83651
  currentIteration,
82094
83652
  maxIterations,
83653
+ parentSessionId: this.sessionId,
83654
+ // Pass parent session ID for tracking
83655
+ path: this.searchPath,
83656
+ // Inherit search path
83657
+ provider: this.provider,
83658
+ // Inherit AI provider
83659
+ model: this.model,
83660
+ // Inherit model
82095
83661
  debug: this.debug,
82096
83662
  tracer: this.tracer
82097
83663
  };
82098
83664
  if (this.debug) {
82099
83665
  console.log(`[DEBUG] Executing delegate tool at iteration ${currentIteration}/${maxIterations}`);
83666
+ console.log(`[DEBUG] Parent session: ${this.sessionId}`);
83667
+ console.log(`[DEBUG] Inherited config: path=${this.searchPath}, provider=${this.provider}, model=${this.model}`);
82100
83668
  console.log(`[DEBUG] Delegate task: ${toolParams.task?.substring(0, 100)}...`);
82101
83669
  }
82102
83670
  if (this.tracer) {
@@ -82687,6 +84255,7 @@ Convert your previous response content into actual JSON data that follows this s
82687
84255
  customPrompt: this.customPrompt,
82688
84256
  promptType: this.promptType,
82689
84257
  allowEdit: this.allowEdit,
84258
+ enableDelegate: this.enableDelegate,
82690
84259
  path: this.allowedFolders[0],
82691
84260
  // Use first allowed folder as primary path
82692
84261
  allowedFolders: [...this.allowedFolders],