@probelabs/probe 0.6.0-rc159 → 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 (36) 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 +7 -1
  5. package/build/agent/ProbeAgent.js +199 -7
  6. package/build/agent/RetryManager.d.ts +157 -0
  7. package/build/agent/RetryManager.js +334 -0
  8. package/build/agent/acp/tools.js +6 -2
  9. package/build/agent/index.js +1379 -168
  10. package/build/agent/probeTool.js +20 -2
  11. package/build/agent/tools.js +16 -0
  12. package/build/index.js +13 -0
  13. package/build/tools/common.js +5 -3
  14. package/build/tools/edit.js +409 -0
  15. package/build/tools/index.js +11 -0
  16. package/cjs/agent/ProbeAgent.cjs +1822 -497
  17. package/cjs/index.cjs +1784 -454
  18. package/package.json +2 -2
  19. package/src/agent/FallbackManager.d.ts +176 -0
  20. package/src/agent/FallbackManager.js +545 -0
  21. package/src/agent/ProbeAgent.d.ts +7 -1
  22. package/src/agent/ProbeAgent.js +199 -7
  23. package/src/agent/RetryManager.d.ts +157 -0
  24. package/src/agent/RetryManager.js +334 -0
  25. package/src/agent/acp/tools.js +6 -2
  26. package/src/agent/probeTool.js +20 -2
  27. package/src/agent/tools.js +16 -0
  28. package/src/index.js +13 -0
  29. package/src/tools/common.js +5 -3
  30. package/src/tools/edit.js +409 -0
  31. package/src/tools/index.js +11 -0
  32. package/bin/binaries/probe-v0.6.0-rc159-aarch64-apple-darwin.tar.gz +0 -0
  33. package/bin/binaries/probe-v0.6.0-rc159-aarch64-unknown-linux-musl.tar.gz +0 -0
  34. package/bin/binaries/probe-v0.6.0-rc159-x86_64-apple-darwin.tar.gz +0 -0
  35. package/bin/binaries/probe-v0.6.0-rc159-x86_64-pc-windows-msvc.zip +0 -0
  36. package/bin/binaries/probe-v0.6.0-rc159-x86_64-unknown-linux-musl.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
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 });
@@ -2571,7 +2553,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2571
2553
  const config = this.config;
2572
2554
  let writeRequestBodyPromise = void 0;
2573
2555
  const timeouts = [];
2574
- const resolve4 = async (arg) => {
2556
+ const resolve5 = async (arg) => {
2575
2557
  await writeRequestBodyPromise;
2576
2558
  timeouts.forEach(timing.clearTimeout);
2577
2559
  _resolve(arg);
@@ -2591,7 +2573,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2591
2573
  const headers = request.headers ?? {};
2592
2574
  const expectContinue = (headers.Expect ?? headers.expect) === "100-continue";
2593
2575
  let agent = isSSL ? config.httpsAgent : config.httpAgent;
2594
- if (expectContinue) {
2576
+ if (expectContinue && !this.externalAgent) {
2595
2577
  agent = new (isSSL ? https.Agent : http.Agent)({
2596
2578
  keepAlive: false,
2597
2579
  maxSockets: Infinity
@@ -2637,7 +2619,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2637
2619
  headers: getTransformedHeaders(res.headers),
2638
2620
  body: res
2639
2621
  });
2640
- resolve4({ response: httpResponse });
2622
+ resolve5({ response: httpResponse });
2641
2623
  });
2642
2624
  req.on("error", (err) => {
2643
2625
  if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) {
@@ -2672,7 +2654,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2672
2654
  keepAliveMsecs: httpAgent.keepAliveMsecs
2673
2655
  }));
2674
2656
  }
2675
- writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout).catch((e3) => {
2657
+ writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout, this.externalAgent).catch((e3) => {
2676
2658
  timeouts.forEach(timing.clearTimeout);
2677
2659
  return _reject(e3);
2678
2660
  });
@@ -2817,13 +2799,13 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2817
2799
  return new _NodeHttp2Handler(instanceOrOptions);
2818
2800
  }
2819
2801
  constructor(options) {
2820
- this.configProvider = new Promise((resolve4, reject2) => {
2802
+ this.configProvider = new Promise((resolve5, reject2) => {
2821
2803
  if (typeof options === "function") {
2822
2804
  options().then((opts) => {
2823
- resolve4(opts || {});
2805
+ resolve5(opts || {});
2824
2806
  }).catch(reject2);
2825
2807
  } else {
2826
- resolve4(options || {});
2808
+ resolve5(options || {});
2827
2809
  }
2828
2810
  });
2829
2811
  }
@@ -2843,7 +2825,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2843
2825
  return new Promise((_resolve, _reject) => {
2844
2826
  let fulfilled = false;
2845
2827
  let writeRequestBodyPromise = void 0;
2846
- const resolve4 = async (arg) => {
2828
+ const resolve5 = async (arg) => {
2847
2829
  await writeRequestBodyPromise;
2848
2830
  _resolve(arg);
2849
2831
  };
@@ -2899,7 +2881,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2899
2881
  body: req
2900
2882
  });
2901
2883
  fulfilled = true;
2902
- resolve4({ response: httpResponse });
2884
+ resolve5({ response: httpResponse });
2903
2885
  if (disableConcurrentStreams) {
2904
2886
  session.close();
2905
2887
  this.connectionManager.deleteSession(authority, session);
@@ -2976,7 +2958,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2976
2958
  if (isReadableStreamInstance(stream3)) {
2977
2959
  return collectReadableStream(stream3);
2978
2960
  }
2979
- return new Promise((resolve4, reject2) => {
2961
+ return new Promise((resolve5, reject2) => {
2980
2962
  const collector = new Collector();
2981
2963
  stream3.pipe(collector);
2982
2964
  stream3.on("error", (err) => {
@@ -2986,7 +2968,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2986
2968
  collector.on("error", reject2);
2987
2969
  collector.on("finish", function() {
2988
2970
  const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes));
2989
- resolve4(bytes);
2971
+ resolve5(bytes);
2990
2972
  });
2991
2973
  });
2992
2974
  };
@@ -3030,7 +3012,7 @@ var require_dist_cjs16 = __commonJS({
3030
3012
  return new Request(url, requestOptions);
3031
3013
  }
3032
3014
  function requestTimeout(timeoutInMs = 0) {
3033
- return new Promise((resolve4, reject2) => {
3015
+ return new Promise((resolve5, reject2) => {
3034
3016
  if (timeoutInMs) {
3035
3017
  setTimeout(() => {
3036
3018
  const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`);
@@ -3148,7 +3130,7 @@ var require_dist_cjs16 = __commonJS({
3148
3130
  requestTimeout(requestTimeoutInMs)
3149
3131
  ];
3150
3132
  if (abortSignal) {
3151
- raceOfPromises.push(new Promise((resolve4, reject2) => {
3133
+ raceOfPromises.push(new Promise((resolve5, reject2) => {
3152
3134
  const onAbort = () => {
3153
3135
  const abortError = new Error("Request aborted");
3154
3136
  abortError.name = "AbortError";
@@ -3212,7 +3194,7 @@ var require_dist_cjs16 = __commonJS({
3212
3194
  return collected;
3213
3195
  }
3214
3196
  function readToBase64(blob) {
3215
- return new Promise((resolve4, reject2) => {
3197
+ return new Promise((resolve5, reject2) => {
3216
3198
  const reader = new FileReader();
3217
3199
  reader.onloadend = () => {
3218
3200
  if (reader.readyState !== 2) {
@@ -3221,7 +3203,7 @@ var require_dist_cjs16 = __commonJS({
3221
3203
  const result = reader.result ?? "";
3222
3204
  const commaIndex = result.indexOf(",");
3223
3205
  const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length;
3224
- resolve4(result.substring(dataOffset));
3206
+ resolve5(result.substring(dataOffset));
3225
3207
  };
3226
3208
  reader.onabort = () => reject2(new Error("Read aborted"));
3227
3209
  reader.onerror = () => reject2(reader.error);
@@ -3723,8 +3705,8 @@ var init_Schema = __esm({
3723
3705
  name;
3724
3706
  namespace;
3725
3707
  traits;
3726
- static assign(instance, values2) {
3727
- const schema = Object.assign(instance, values2);
3708
+ static assign(instance2, values2) {
3709
+ const schema = Object.assign(instance2, values2);
3728
3710
  return schema;
3729
3711
  }
3730
3712
  static [Symbol.hasInstance](lhs) {
@@ -4841,11 +4823,11 @@ function __metadata(metadataKey, metadataValue) {
4841
4823
  }
4842
4824
  function __awaiter(thisArg, _arguments, P, generator) {
4843
4825
  function adopt(value) {
4844
- return value instanceof P ? value : new P(function(resolve4) {
4845
- resolve4(value);
4826
+ return value instanceof P ? value : new P(function(resolve5) {
4827
+ resolve5(value);
4846
4828
  });
4847
4829
  }
4848
- return new (P || (P = Promise))(function(resolve4, reject2) {
4830
+ return new (P || (P = Promise))(function(resolve5, reject2) {
4849
4831
  function fulfilled(value) {
4850
4832
  try {
4851
4833
  step(generator.next(value));
@@ -4861,7 +4843,7 @@ function __awaiter(thisArg, _arguments, P, generator) {
4861
4843
  }
4862
4844
  }
4863
4845
  function step(result) {
4864
- result.done ? resolve4(result.value) : adopt(result.value).then(fulfilled, rejected);
4846
+ result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected);
4865
4847
  }
4866
4848
  step((generator = generator.apply(thisArg, _arguments || [])).next());
4867
4849
  });
@@ -5052,14 +5034,14 @@ function __asyncValues(o3) {
5052
5034
  }, i3);
5053
5035
  function verb(n3) {
5054
5036
  i3[n3] = o3[n3] && function(v3) {
5055
- return new Promise(function(resolve4, reject2) {
5056
- 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);
5057
5039
  });
5058
5040
  };
5059
5041
  }
5060
- function settle(resolve4, reject2, d3, v3) {
5042
+ function settle(resolve5, reject2, d3, v3) {
5061
5043
  Promise.resolve(v3).then(function(v4) {
5062
- resolve4({ value: v4, done: d3 });
5044
+ resolve5({ value: v4, done: d3 });
5063
5045
  }, reject2);
5064
5046
  }
5065
5047
  }
@@ -5386,12 +5368,8 @@ var init_schema_date_utils = __esm({
5386
5368
  range(hours, 0, 23);
5387
5369
  range(minutes, 0, 59);
5388
5370
  range(seconds, 0, 60);
5389
- const date2 = /* @__PURE__ */ new Date();
5390
- date2.setUTCFullYear(Number(yearStr), Number(monthStr) - 1, Number(dayStr));
5391
- date2.setUTCHours(Number(hours));
5392
- date2.setUTCMinutes(Number(minutes));
5393
- date2.setUTCSeconds(Number(seconds));
5394
- 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));
5395
5373
  if (offsetStr.toUpperCase() != "Z") {
5396
5374
  const [, sign, offsetH, offsetM] = /([+-])(\d\d):(\d\d)/.exec(offsetStr) || [void 0, "+", 0, 0];
5397
5375
  const scalar = sign === "-" ? 1 : -1;
@@ -5423,18 +5401,13 @@ var init_schema_date_utils = __esm({
5423
5401
  [, month, day, hour, minute, second, fraction, year2] = matches;
5424
5402
  }
5425
5403
  if (year2 && second) {
5426
- const date2 = /* @__PURE__ */ new Date();
5427
- date2.setUTCFullYear(Number(year2));
5428
- 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);
5429
5405
  range(day, 1, 31);
5430
- date2.setUTCDate(Number(day));
5431
5406
  range(hour, 0, 23);
5432
- date2.setUTCHours(Number(hour));
5433
5407
  range(minute, 0, 59);
5434
- date2.setUTCMinutes(Number(minute));
5435
5408
  range(second, 0, 60);
5436
- date2.setUTCSeconds(Number(second));
5437
- date2.setUTCMilliseconds(fraction ? Math.round(parseFloat(`0.${fraction}`) * 1e3) : 0);
5409
+ const date2 = new Date(timestamp);
5410
+ date2.setUTCFullYear(Number(year2));
5438
5411
  return date2;
5439
5412
  }
5440
5413
  throw new TypeError(`Invalid RFC7231 date-time value ${value}.`);
@@ -7668,6 +7641,9 @@ var require_dist_cjs23 = __commonJS({
7668
7641
  },
7669
7642
  "us-isob-east-1": {
7670
7643
  description: "US ISOB East (Ohio)"
7644
+ },
7645
+ "us-isob-west-1": {
7646
+ description: "US ISOB West"
7671
7647
  }
7672
7648
  }
7673
7649
  },
@@ -10672,18 +10648,18 @@ var require_dist_cjs27 = __commonJS({
10672
10648
  const candidate = value;
10673
10649
  return _ServiceException.prototype.isPrototypeOf(candidate) || Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server");
10674
10650
  }
10675
- static [Symbol.hasInstance](instance) {
10676
- if (!instance)
10651
+ static [Symbol.hasInstance](instance2) {
10652
+ if (!instance2)
10677
10653
  return false;
10678
- const candidate = instance;
10654
+ const candidate = instance2;
10679
10655
  if (this === _ServiceException) {
10680
- return _ServiceException.isInstance(instance);
10656
+ return _ServiceException.isInstance(instance2);
10681
10657
  }
10682
- if (_ServiceException.isInstance(instance)) {
10658
+ if (_ServiceException.isInstance(instance2)) {
10683
10659
  if (candidate.name && this.name) {
10684
- return this.prototype.isPrototypeOf(instance) || candidate.name === this.name;
10660
+ return this.prototype.isPrototypeOf(instance2) || candidate.name === this.name;
10685
10661
  }
10686
- return this.prototype.isPrototypeOf(instance);
10662
+ return this.prototype.isPrototypeOf(instance2);
10687
10663
  }
10688
10664
  return false;
10689
10665
  }
@@ -13609,8 +13585,8 @@ var require_dist_cjs29 = __commonJS({
13609
13585
  var X_AMZ_USER_AGENT = "x-amz-user-agent";
13610
13586
  var SPACE = " ";
13611
13587
  var UA_NAME_SEPARATOR = "/";
13612
- var UA_NAME_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g;
13613
- var UA_VALUE_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g;
13588
+ var UA_NAME_ESCAPE_REGEX = /[^!$%&'*+\-.^_`|~\w]/g;
13589
+ var UA_VALUE_ESCAPE_REGEX = /[^!$%&'*+\-.^_`|~\w#]/g;
13614
13590
  var UA_ESCAPE_CHAR = "-";
13615
13591
  var BYTE_LIMIT = 1024;
13616
13592
  function encodeFeatures(features) {
@@ -13643,7 +13619,7 @@ var require_dist_cjs29 = __commonJS({
13643
13619
  const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || [];
13644
13620
  const appId = await options.userAgentAppId();
13645
13621
  if (appId) {
13646
- defaultUserAgent.push(escapeUserAgent([`app/${appId}`]));
13622
+ defaultUserAgent.push(escapeUserAgent([`app`, `${appId}`]));
13647
13623
  }
13648
13624
  const prefix = utilEndpoints.getUserAgentPrefix();
13649
13625
  const sdkUserAgentValue = (prefix ? [prefix] : []).concat([...defaultUserAgent, ...userAgent, ...customUserAgent]).join(SPACE);
@@ -15133,7 +15109,7 @@ var require_dist_cjs37 = __commonJS({
15133
15109
  this.sockets[url] = (this.sockets[url] ?? []).filter((socket) => ![WebSocket.CLOSING, WebSocket.CLOSED].includes(socket.readyState));
15134
15110
  }
15135
15111
  waitForReady(socket, connectionTimeout) {
15136
- return new Promise((resolve4, reject2) => {
15112
+ return new Promise((resolve5, reject2) => {
15137
15113
  const timeout = setTimeout(() => {
15138
15114
  this.removeNotUsableSockets(socket.url);
15139
15115
  reject2({
@@ -15144,7 +15120,7 @@ var require_dist_cjs37 = __commonJS({
15144
15120
  }, connectionTimeout);
15145
15121
  socket.onopen = () => {
15146
15122
  clearTimeout(timeout);
15147
- resolve4();
15123
+ resolve5();
15148
15124
  };
15149
15125
  });
15150
15126
  }
@@ -15153,10 +15129,10 @@ var require_dist_cjs37 = __commonJS({
15153
15129
  let socketErrorOccurred = false;
15154
15130
  let reject2 = () => {
15155
15131
  };
15156
- let resolve4 = () => {
15132
+ let resolve5 = () => {
15157
15133
  };
15158
15134
  socket.onmessage = (event) => {
15159
- resolve4({
15135
+ resolve5({
15160
15136
  done: false,
15161
15137
  value: new Uint8Array(event.data)
15162
15138
  });
@@ -15173,7 +15149,7 @@ var require_dist_cjs37 = __commonJS({
15173
15149
  if (streamError) {
15174
15150
  reject2(streamError);
15175
15151
  } else {
15176
- resolve4({
15152
+ resolve5({
15177
15153
  done: true,
15178
15154
  value: void 0
15179
15155
  });
@@ -15183,7 +15159,7 @@ var require_dist_cjs37 = __commonJS({
15183
15159
  [Symbol.asyncIterator]: () => ({
15184
15160
  next: () => {
15185
15161
  return new Promise((_resolve, _reject) => {
15186
- resolve4 = _resolve;
15162
+ resolve5 = _resolve;
15187
15163
  reject2 = _reject;
15188
15164
  });
15189
15165
  }
@@ -16206,7 +16182,7 @@ var require_dist_cjs46 = __commonJS({
16206
16182
  this.refillTokenBucket();
16207
16183
  if (amount > this.currentCapacity) {
16208
16184
  const delay = (amount - this.currentCapacity) / this.fillRate * 1e3;
16209
- await new Promise((resolve4) => _DefaultRateLimiter.setTimeoutFn(resolve4, delay));
16185
+ await new Promise((resolve5) => _DefaultRateLimiter.setTimeoutFn(resolve5, delay));
16210
16186
  }
16211
16187
  this.currentCapacity = this.currentCapacity - amount;
16212
16188
  }
@@ -16541,7 +16517,7 @@ var require_dist_cjs47 = __commonJS({
16541
16517
  const delayFromResponse = getDelayFromRetryAfterHeader(err.$response);
16542
16518
  const delay = Math.max(delayFromResponse || 0, delayFromDecider);
16543
16519
  totalDelay += delay;
16544
- await new Promise((resolve4) => setTimeout(resolve4, delay));
16520
+ await new Promise((resolve5) => setTimeout(resolve5, delay));
16545
16521
  continue;
16546
16522
  }
16547
16523
  if (!err.$metadata) {
@@ -16699,7 +16675,7 @@ var require_dist_cjs47 = __commonJS({
16699
16675
  attempts = retryToken.getRetryCount();
16700
16676
  const delay = retryToken.getRetryDelay();
16701
16677
  totalRetryDelay += delay;
16702
- await new Promise((resolve4) => setTimeout(resolve4, delay));
16678
+ await new Promise((resolve5) => setTimeout(resolve5, delay));
16703
16679
  }
16704
16680
  }
16705
16681
  } else {
@@ -16851,7 +16827,7 @@ var require_package2 = __commonJS({
16851
16827
  module2.exports = {
16852
16828
  name: "@aws-sdk/client-bedrock-runtime",
16853
16829
  description: "AWS SDK for JavaScript Bedrock Runtime Client for Node.js, Browser and React Native",
16854
- version: "3.914.0",
16830
+ version: "3.922.0",
16855
16831
  scripts: {
16856
16832
  build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
16857
16833
  "build:cjs": "node ../../scripts/compilation/inline client-bedrock-runtime",
@@ -16870,49 +16846,49 @@ var require_package2 = __commonJS({
16870
16846
  dependencies: {
16871
16847
  "@aws-crypto/sha256-browser": "5.2.0",
16872
16848
  "@aws-crypto/sha256-js": "5.2.0",
16873
- "@aws-sdk/core": "3.914.0",
16874
- "@aws-sdk/credential-provider-node": "3.914.0",
16875
- "@aws-sdk/eventstream-handler-node": "3.914.0",
16876
- "@aws-sdk/middleware-eventstream": "3.914.0",
16877
- "@aws-sdk/middleware-host-header": "3.914.0",
16878
- "@aws-sdk/middleware-logger": "3.914.0",
16879
- "@aws-sdk/middleware-recursion-detection": "3.914.0",
16880
- "@aws-sdk/middleware-user-agent": "3.914.0",
16881
- "@aws-sdk/middleware-websocket": "3.914.0",
16882
- "@aws-sdk/region-config-resolver": "3.914.0",
16883
- "@aws-sdk/token-providers": "3.914.0",
16884
- "@aws-sdk/types": "3.914.0",
16885
- "@aws-sdk/util-endpoints": "3.914.0",
16886
- "@aws-sdk/util-user-agent-browser": "3.914.0",
16887
- "@aws-sdk/util-user-agent-node": "3.914.0",
16888
- "@smithy/config-resolver": "^4.4.0",
16889
- "@smithy/core": "^3.17.0",
16890
- "@smithy/eventstream-serde-browser": "^4.2.3",
16891
- "@smithy/eventstream-serde-config-resolver": "^4.3.3",
16892
- "@smithy/eventstream-serde-node": "^4.2.3",
16893
- "@smithy/fetch-http-handler": "^5.3.4",
16894
- "@smithy/hash-node": "^4.2.3",
16895
- "@smithy/invalid-dependency": "^4.2.3",
16896
- "@smithy/middleware-content-length": "^4.2.3",
16897
- "@smithy/middleware-endpoint": "^4.3.4",
16898
- "@smithy/middleware-retry": "^4.4.4",
16899
- "@smithy/middleware-serde": "^4.2.3",
16900
- "@smithy/middleware-stack": "^4.2.3",
16901
- "@smithy/node-config-provider": "^4.3.3",
16902
- "@smithy/node-http-handler": "^4.4.2",
16903
- "@smithy/protocol-http": "^5.3.3",
16904
- "@smithy/smithy-client": "^4.9.0",
16905
- "@smithy/types": "^4.8.0",
16906
- "@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",
16907
16883
  "@smithy/util-base64": "^4.3.0",
16908
16884
  "@smithy/util-body-length-browser": "^4.2.0",
16909
16885
  "@smithy/util-body-length-node": "^4.2.1",
16910
- "@smithy/util-defaults-mode-browser": "^4.3.3",
16911
- "@smithy/util-defaults-mode-node": "^4.2.5",
16912
- "@smithy/util-endpoints": "^3.2.3",
16913
- "@smithy/util-middleware": "^4.2.3",
16914
- "@smithy/util-retry": "^4.2.3",
16915
- "@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",
16916
16892
  "@smithy/util-utf8": "^4.2.0",
16917
16893
  "@smithy/uuid": "^1.1.0",
16918
16894
  tslib: "^2.6.2"
@@ -17014,7 +16990,7 @@ var require_dist_cjs49 = __commonJS({
17014
16990
  var nodeConfigProvider = require_dist_cjs43();
17015
16991
  var urlParser = require_dist_cjs22();
17016
16992
  function httpRequest(options) {
17017
- return new Promise((resolve4, reject2) => {
16993
+ return new Promise((resolve5, reject2) => {
17018
16994
  const req = http.request({
17019
16995
  method: "GET",
17020
16996
  ...options,
@@ -17039,7 +17015,7 @@ var require_dist_cjs49 = __commonJS({
17039
17015
  chunks.push(chunk);
17040
17016
  });
17041
17017
  res.on("end", () => {
17042
- resolve4(buffer.Buffer.concat(chunks));
17018
+ resolve5(buffer.Buffer.concat(chunks));
17043
17019
  req.destroy();
17044
17020
  });
17045
17021
  });
@@ -17459,7 +17435,7 @@ var require_retry_wrapper = __commonJS({
17459
17435
  try {
17460
17436
  return await toRetry();
17461
17437
  } catch (e3) {
17462
- await new Promise((resolve4) => setTimeout(resolve4, delayMs));
17438
+ await new Promise((resolve5) => setTimeout(resolve5, delayMs));
17463
17439
  }
17464
17440
  }
17465
17441
  return await toRetry();
@@ -17632,7 +17608,7 @@ var init_package = __esm({
17632
17608
  "node_modules/@aws-sdk/nested-clients/package.json"() {
17633
17609
  package_default = {
17634
17610
  name: "@aws-sdk/nested-clients",
17635
- version: "3.914.0",
17611
+ version: "3.922.0",
17636
17612
  description: "Nested clients for AWS SDK packages.",
17637
17613
  main: "./dist-cjs/index.js",
17638
17614
  module: "./dist-es/index.js",
@@ -17661,40 +17637,40 @@ var init_package = __esm({
17661
17637
  dependencies: {
17662
17638
  "@aws-crypto/sha256-browser": "5.2.0",
17663
17639
  "@aws-crypto/sha256-js": "5.2.0",
17664
- "@aws-sdk/core": "3.914.0",
17665
- "@aws-sdk/middleware-host-header": "3.914.0",
17666
- "@aws-sdk/middleware-logger": "3.914.0",
17667
- "@aws-sdk/middleware-recursion-detection": "3.914.0",
17668
- "@aws-sdk/middleware-user-agent": "3.914.0",
17669
- "@aws-sdk/region-config-resolver": "3.914.0",
17670
- "@aws-sdk/types": "3.914.0",
17671
- "@aws-sdk/util-endpoints": "3.914.0",
17672
- "@aws-sdk/util-user-agent-browser": "3.914.0",
17673
- "@aws-sdk/util-user-agent-node": "3.914.0",
17674
- "@smithy/config-resolver": "^4.4.0",
17675
- "@smithy/core": "^3.17.0",
17676
- "@smithy/fetch-http-handler": "^5.3.4",
17677
- "@smithy/hash-node": "^4.2.3",
17678
- "@smithy/invalid-dependency": "^4.2.3",
17679
- "@smithy/middleware-content-length": "^4.2.3",
17680
- "@smithy/middleware-endpoint": "^4.3.4",
17681
- "@smithy/middleware-retry": "^4.4.4",
17682
- "@smithy/middleware-serde": "^4.2.3",
17683
- "@smithy/middleware-stack": "^4.2.3",
17684
- "@smithy/node-config-provider": "^4.3.3",
17685
- "@smithy/node-http-handler": "^4.4.2",
17686
- "@smithy/protocol-http": "^5.3.3",
17687
- "@smithy/smithy-client": "^4.9.0",
17688
- "@smithy/types": "^4.8.0",
17689
- "@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",
17690
17666
  "@smithy/util-base64": "^4.3.0",
17691
17667
  "@smithy/util-body-length-browser": "^4.2.0",
17692
17668
  "@smithy/util-body-length-node": "^4.2.1",
17693
- "@smithy/util-defaults-mode-browser": "^4.3.3",
17694
- "@smithy/util-defaults-mode-node": "^4.2.5",
17695
- "@smithy/util-endpoints": "^3.2.3",
17696
- "@smithy/util-middleware": "^4.2.3",
17697
- "@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",
17698
17674
  "@smithy/util-utf8": "^4.2.0",
17699
17675
  tslib: "^2.6.2"
17700
17676
  },
@@ -17896,8 +17872,8 @@ var init_ruleset = __esm({
17896
17872
  f = "tree";
17897
17873
  g = "PartitionResult";
17898
17874
  h = "getAttr";
17899
- i = { [u]: false, "type": "String" };
17900
- j = { [u]: true, "default": false, "type": "Boolean" };
17875
+ i = { [u]: false, "type": "string" };
17876
+ j = { [u]: true, "default": false, "type": "boolean" };
17901
17877
  k = { [x]: "Endpoint" };
17902
17878
  l = { [v]: c, [w]: [{ [x]: "UseFIPS" }, true] };
17903
17879
  m = { [v]: c, [w]: [{ [x]: "UseDualStack" }, true] };
@@ -18103,11 +18079,38 @@ var init_runtimeConfig = __esm({
18103
18079
  }
18104
18080
  });
18105
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
+
18106
18108
  // node_modules/@aws-sdk/region-config-resolver/dist-cjs/index.js
18107
18109
  var require_dist_cjs55 = __commonJS({
18108
18110
  "node_modules/@aws-sdk/region-config-resolver/dist-cjs/index.js"(exports2) {
18109
18111
  "use strict";
18110
18112
  var configResolver = require_dist_cjs39();
18113
+ var stsRegionDefaultResolver2 = require_stsRegionDefaultResolver();
18111
18114
  var getAwsRegionExtensionConfiguration3 = (runtimeConfig) => {
18112
18115
  return {
18113
18116
  setRegion(region) {
@@ -18155,6 +18158,14 @@ var require_dist_cjs55 = __commonJS({
18155
18158
  });
18156
18159
  exports2.getAwsRegionExtensionConfiguration = getAwsRegionExtensionConfiguration3;
18157
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
+ });
18158
18169
  }
18159
18170
  });
18160
18171
 
@@ -18852,7 +18863,7 @@ var require_dist_cjs56 = __commonJS({
18852
18863
  var httpAuthSchemes = (init_httpAuthSchemes2(), __toCommonJS(httpAuthSchemes_exports));
18853
18864
  var propertyProvider = require_dist_cjs24();
18854
18865
  var sharedIniFileLoader = require_dist_cjs42();
18855
- var fs6 = require("fs");
18866
+ var fs7 = require("fs");
18856
18867
  var fromEnvSigningName = ({ logger: logger2, signingName } = {}) => async () => {
18857
18868
  logger2?.debug?.("@aws-sdk/token-providers - fromEnvSigningName");
18858
18869
  if (!signingName) {
@@ -18870,9 +18881,11 @@ var require_dist_cjs56 = __commonJS({
18870
18881
  var REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`;
18871
18882
  var getSsoOidcClient = async (ssoRegion, init = {}) => {
18872
18883
  const { SSOOIDCClient: SSOOIDCClient2 } = await Promise.resolve().then(() => (init_sso_oidc(), sso_oidc_exports));
18884
+ const coalesce = (prop) => init.clientConfig?.[prop] ?? init.parentClientConfig?.[prop];
18873
18885
  const ssoOidcClient = new SSOOIDCClient2(Object.assign({}, init.clientConfig ?? {}, {
18874
18886
  region: ssoRegion ?? init.clientConfig?.region,
18875
- logger: init.clientConfig?.logger ?? init.parentClientConfig?.logger
18887
+ logger: coalesce("logger"),
18888
+ userAgentAppId: coalesce("userAgentAppId")
18876
18889
  }));
18877
18890
  return ssoOidcClient;
18878
18891
  };
@@ -18896,7 +18909,7 @@ var require_dist_cjs56 = __commonJS({
18896
18909
  throw new propertyProvider.TokenProviderError(`Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`, false);
18897
18910
  }
18898
18911
  };
18899
- var { writeFile } = fs6.promises;
18912
+ var { writeFile } = fs7.promises;
18900
18913
  var writeSSOTokenToFile = (id, ssoToken) => {
18901
18914
  const tokenFilepath = sharedIniFileLoader.getSSOTokenFilepath(id);
18902
18915
  const tokenString = JSON.stringify(ssoToken, null, 2);
@@ -19075,7 +19088,7 @@ var require_package3 = __commonJS({
19075
19088
  module2.exports = {
19076
19089
  name: "@aws-sdk/client-sso",
19077
19090
  description: "AWS SDK for JavaScript Sso Client for Node.js, Browser and React Native",
19078
- version: "3.914.0",
19091
+ version: "3.922.0",
19079
19092
  scripts: {
19080
19093
  build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
19081
19094
  "build:cjs": "node ../../scripts/compilation/inline client-sso",
@@ -19094,40 +19107,40 @@ var require_package3 = __commonJS({
19094
19107
  dependencies: {
19095
19108
  "@aws-crypto/sha256-browser": "5.2.0",
19096
19109
  "@aws-crypto/sha256-js": "5.2.0",
19097
- "@aws-sdk/core": "3.914.0",
19098
- "@aws-sdk/middleware-host-header": "3.914.0",
19099
- "@aws-sdk/middleware-logger": "3.914.0",
19100
- "@aws-sdk/middleware-recursion-detection": "3.914.0",
19101
- "@aws-sdk/middleware-user-agent": "3.914.0",
19102
- "@aws-sdk/region-config-resolver": "3.914.0",
19103
- "@aws-sdk/types": "3.914.0",
19104
- "@aws-sdk/util-endpoints": "3.914.0",
19105
- "@aws-sdk/util-user-agent-browser": "3.914.0",
19106
- "@aws-sdk/util-user-agent-node": "3.914.0",
19107
- "@smithy/config-resolver": "^4.4.0",
19108
- "@smithy/core": "^3.17.0",
19109
- "@smithy/fetch-http-handler": "^5.3.4",
19110
- "@smithy/hash-node": "^4.2.3",
19111
- "@smithy/invalid-dependency": "^4.2.3",
19112
- "@smithy/middleware-content-length": "^4.2.3",
19113
- "@smithy/middleware-endpoint": "^4.3.4",
19114
- "@smithy/middleware-retry": "^4.4.4",
19115
- "@smithy/middleware-serde": "^4.2.3",
19116
- "@smithy/middleware-stack": "^4.2.3",
19117
- "@smithy/node-config-provider": "^4.3.3",
19118
- "@smithy/node-http-handler": "^4.4.2",
19119
- "@smithy/protocol-http": "^5.3.3",
19120
- "@smithy/smithy-client": "^4.9.0",
19121
- "@smithy/types": "^4.8.0",
19122
- "@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",
19123
19136
  "@smithy/util-base64": "^4.3.0",
19124
19137
  "@smithy/util-body-length-browser": "^4.2.0",
19125
19138
  "@smithy/util-body-length-node": "^4.2.1",
19126
- "@smithy/util-defaults-mode-browser": "^4.3.3",
19127
- "@smithy/util-defaults-mode-node": "^4.2.5",
19128
- "@smithy/util-endpoints": "^3.2.3",
19129
- "@smithy/util-middleware": "^4.2.3",
19130
- "@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",
19131
19144
  "@smithy/util-utf8": "^4.2.0",
19132
19145
  tslib: "^2.6.2"
19133
19146
  },
@@ -19191,8 +19204,8 @@ var require_ruleset = __commonJS({
19191
19204
  var f3 = "tree";
19192
19205
  var g3 = "PartitionResult";
19193
19206
  var h3 = "getAttr";
19194
- var i3 = { [u3]: false, "type": "String" };
19195
- var j3 = { [u3]: true, "default": false, "type": "Boolean" };
19207
+ var i3 = { [u3]: false, "type": "string" };
19208
+ var j3 = { [u3]: true, "default": false, "type": "boolean" };
19196
19209
  var k3 = { [x3]: "Endpoint" };
19197
19210
  var l3 = { [v3]: c3, [w3]: [{ [x3]: "UseFIPS" }, true] };
19198
19211
  var m3 = { [v3]: c3, [w3]: [{ [x3]: "UseDualStack" }, true] };
@@ -19872,7 +19885,8 @@ var require_dist_cjs58 = __commonJS({
19872
19885
  });
19873
19886
  const sso = ssoClient || new SSOClient(Object.assign({}, clientConfig ?? {}, {
19874
19887
  logger: clientConfig?.logger ?? parentClientConfig?.logger,
19875
- region: clientConfig?.region ?? ssoRegion
19888
+ region: clientConfig?.region ?? ssoRegion,
19889
+ userAgentAppId: clientConfig?.userAgentAppId ?? parentClientConfig?.userAgentAppId
19876
19890
  }));
19877
19891
  let ssoResp;
19878
19892
  try {
@@ -20100,8 +20114,8 @@ var init_ruleset2 = __esm({
20100
20114
  j2 = "tree";
20101
20115
  k2 = "error";
20102
20116
  l2 = "getAttr";
20103
- m2 = { [F]: false, [G]: "String" };
20104
- n2 = { [F]: true, "default": false, [G]: "Boolean" };
20117
+ m2 = { [F]: false, [G]: "string" };
20118
+ n2 = { [F]: true, "default": false, [G]: "boolean" };
20105
20119
  o2 = { [J]: "Endpoint" };
20106
20120
  p2 = { [H]: "isSet", [I]: [{ [J]: "Region" }] };
20107
20121
  q2 = { [J]: "Region" };
@@ -21097,13 +21111,13 @@ var init_models2 = __esm({
21097
21111
  });
21098
21112
 
21099
21113
  // node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultStsRoleAssumers.js
21100
- var ASSUME_ROLE_DEFAULT_REGION, getAccountIdFromAssumedRoleUser, resolveRegion, getDefaultRoleAssumer, getDefaultRoleAssumerWithWebIdentity, isH2;
21114
+ var import_region_config_resolver3, getAccountIdFromAssumedRoleUser, resolveRegion, getDefaultRoleAssumer, getDefaultRoleAssumerWithWebIdentity, isH2;
21101
21115
  var init_defaultStsRoleAssumers = __esm({
21102
21116
  "node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultStsRoleAssumers.js"() {
21103
21117
  init_client();
21118
+ import_region_config_resolver3 = __toESM(require_dist_cjs55());
21104
21119
  init_AssumeRoleCommand();
21105
21120
  init_AssumeRoleWithWebIdentityCommand();
21106
- ASSUME_ROLE_DEFAULT_REGION = "us-east-1";
21107
21121
  getAccountIdFromAssumedRoleUser = (assumedRoleUser) => {
21108
21122
  if (typeof assumedRoleUser?.Arn === "string") {
21109
21123
  const arnComponents = assumedRoleUser.Arn.split(":");
@@ -21113,11 +21127,12 @@ var init_defaultStsRoleAssumers = __esm({
21113
21127
  }
21114
21128
  return void 0;
21115
21129
  };
21116
- resolveRegion = async (_region, _parentRegion, credentialProviderLogger) => {
21130
+ resolveRegion = async (_region, _parentRegion, credentialProviderLogger, loaderConfig = {}) => {
21117
21131
  const region = typeof _region === "function" ? await _region() : _region;
21118
21132
  const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion;
21119
- credentialProviderLogger?.debug?.("@aws-sdk/client-sts::resolveRegion", "accepting first of:", `${region} (provider)`, `${parentRegion} (parent client)`, `${ASSUME_ROLE_DEFAULT_REGION} (STS default)`);
21120
- 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;
21121
21136
  };
21122
21137
  getDefaultRoleAssumer = (stsOptions, STSClient2) => {
21123
21138
  let stsClient;
@@ -21125,11 +21140,15 @@ var init_defaultStsRoleAssumers = __esm({
21125
21140
  return async (sourceCreds, params) => {
21126
21141
  closureSourceCreds = sourceCreds;
21127
21142
  if (!stsClient) {
21128
- const { logger: logger2 = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger } = stsOptions;
21129
- 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
+ });
21130
21148
  const isCompatibleRequestHandler = !isH2(requestHandler);
21131
21149
  stsClient = new STSClient2({
21132
21150
  ...stsOptions,
21151
+ userAgentAppId,
21133
21152
  profile,
21134
21153
  credentialDefaultProvider: () => async () => closureSourceCreds,
21135
21154
  region: resolvedRegion,
@@ -21158,11 +21177,15 @@ var init_defaultStsRoleAssumers = __esm({
21158
21177
  let stsClient;
21159
21178
  return async (params) => {
21160
21179
  if (!stsClient) {
21161
- const { logger: logger2 = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger } = stsOptions;
21162
- 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
+ });
21163
21185
  const isCompatibleRequestHandler = !isH2(requestHandler);
21164
21186
  stsClient = new STSClient2({
21165
21187
  ...stsOptions,
21188
+ userAgentAppId,
21166
21189
  profile,
21167
21190
  region: resolvedRegion,
21168
21191
  requestHandler: isCompatibleRequestHandler ? requestHandler : void 0,
@@ -21421,7 +21444,7 @@ var require_fromTokenFile = __commonJS({
21421
21444
  var ENV_TOKEN_FILE = "AWS_WEB_IDENTITY_TOKEN_FILE";
21422
21445
  var ENV_ROLE_ARN = "AWS_ROLE_ARN";
21423
21446
  var ENV_ROLE_SESSION_NAME = "AWS_ROLE_SESSION_NAME";
21424
- var fromTokenFile = (init = {}) => async () => {
21447
+ var fromTokenFile = (init = {}) => async (awsIdentityProperties) => {
21425
21448
  init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile");
21426
21449
  const webIdentityTokenFile = init?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE];
21427
21450
  const roleArn = init?.roleArn ?? process.env[ENV_ROLE_ARN];
@@ -21436,7 +21459,7 @@ var require_fromTokenFile = __commonJS({
21436
21459
  webIdentityToken: shared_ini_file_loader_1.externalDataInterceptor?.getTokenRecord?.()[webIdentityTokenFile] ?? (0, fs_1.readFileSync)(webIdentityTokenFile, { encoding: "ascii" }),
21437
21460
  roleArn,
21438
21461
  roleSessionName
21439
- })();
21462
+ })(awsIdentityProperties);
21440
21463
  if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) {
21441
21464
  (0, client_1.setCredentialFeature)(credentials, "CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN", "h");
21442
21465
  }
@@ -21673,15 +21696,67 @@ var require_dist_cjs62 = __commonJS({
21673
21696
  init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata");
21674
21697
  return fromInstanceMetadata(init);
21675
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
+ };
21676
21750
  var multipleCredentialSourceWarningEmitted = false;
21677
- var defaultProvider = (init = {}) => propertyProvider.memoize(propertyProvider.chain(async () => {
21678
- const profile = init.profile ?? process.env[sharedIniFileLoader.ENV_PROFILE];
21679
- if (profile) {
21680
- const envStaticCredentialsAreSet = process.env[credentialProviderEnv.ENV_KEY] && process.env[credentialProviderEnv.ENV_SECRET];
21681
- if (envStaticCredentialsAreSet) {
21682
- if (!multipleCredentialSourceWarningEmitted) {
21683
- const warnFn = init.logger?.warn && init.logger?.constructor?.name !== "NoOpLogger" ? init.logger.warn.bind(init.logger) : console.warn;
21684
- 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:
21685
21760
  Multiple credential sources detected:
21686
21761
  Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set.
21687
21762
  This SDK will proceed with the AWS_PROFILE value.
@@ -21690,45 +21765,52 @@ var require_dist_cjs62 = __commonJS({
21690
21765
  Please ensure that your environment only sets either the AWS_PROFILE or the
21691
21766
  AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair.
21692
21767
  `);
21693
- multipleCredentialSourceWarningEmitted = true;
21768
+ multipleCredentialSourceWarningEmitted = true;
21769
+ }
21694
21770
  }
21771
+ throw new propertyProvider.CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", {
21772
+ logger: init.logger,
21773
+ tryNextLink: true
21774
+ });
21695
21775
  }
21696
- throw new propertyProvider.CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", {
21697
- logger: init.logger,
21698
- 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
21699
21811
  });
21700
21812
  }
21701
- init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv");
21702
- return credentialProviderEnv.fromEnv(init)();
21703
- }, async () => {
21704
- init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO");
21705
- const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init;
21706
- if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) {
21707
- throw new propertyProvider.CredentialsProviderError("Skipping SSO provider in default chain (inputs do not include SSO fields).", { logger: init.logger });
21708
- }
21709
- const { fromSSO } = await Promise.resolve().then(() => __toESM(require_dist_cjs58()));
21710
- return fromSSO(init)();
21711
- }, async () => {
21712
- init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni");
21713
- const { fromIni } = await Promise.resolve().then(() => __toESM(require_dist_cjs61()));
21714
- return fromIni(init)();
21715
- }, async () => {
21716
- init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess");
21717
- const { fromProcess } = await Promise.resolve().then(() => __toESM(require_dist_cjs59()));
21718
- return fromProcess(init)();
21719
- }, async () => {
21720
- init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile");
21721
- const { fromTokenFile } = await Promise.resolve().then(() => __toESM(require_dist_cjs60()));
21722
- return fromTokenFile(init)();
21723
- }, async () => {
21724
- init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider");
21725
- return (await remoteProvider(init))();
21726
- }, async () => {
21727
- throw new propertyProvider.CredentialsProviderError("Could not load credentials from any providers", {
21728
- tryNextLink: false,
21729
- logger: init.logger
21730
- });
21731
- }), credentialsTreatedAsExpired, credentialsWillNeedRefresh);
21813
+ ], credentialsTreatedAsExpired);
21732
21814
  var credentialsWillNeedRefresh = (credentials) => credentials?.expiration !== void 0;
21733
21815
  var credentialsTreatedAsExpired = (credentials) => credentials?.expiration !== void 0 && credentials.expiration.getTime() - Date.now() < 3e5;
21734
21816
  exports2.credentialsTreatedAsExpired = credentialsTreatedAsExpired;
@@ -21869,7 +21951,7 @@ var require_dist_cjs64 = __commonJS({
21869
21951
  streamEnded = true;
21870
21952
  });
21871
21953
  while (!generationEnded) {
21872
- const value = await new Promise((resolve4) => setTimeout(() => resolve4(records.shift()), 0));
21954
+ const value = await new Promise((resolve5) => setTimeout(() => resolve5(records.shift()), 0));
21873
21955
  if (value) {
21874
21956
  yield value;
21875
21957
  }
@@ -21915,8 +21997,8 @@ var require_ruleset2 = __commonJS({
21915
21997
  var e3 = "endpoint";
21916
21998
  var f3 = "tree";
21917
21999
  var g3 = "PartitionResult";
21918
- var h3 = { [s3]: false, "type": "String" };
21919
- var i3 = { [s3]: true, "default": false, "type": "Boolean" };
22000
+ var h3 = { [s3]: false, "type": "string" };
22001
+ var i3 = { [s3]: true, "default": false, "type": "boolean" };
21920
22002
  var j3 = { [v3]: "Endpoint" };
21921
22003
  var k3 = { [t3]: c3, [u3]: [{ [v3]: "UseFIPS" }, true] };
21922
22004
  var l3 = { [t3]: c3, [u3]: [{ [v3]: "UseDualStack" }, true] };
@@ -22489,6 +22571,8 @@ var require_dist_cjs65 = __commonJS({
22489
22571
  exports2.CitationLocation = void 0;
22490
22572
  (function(CitationLocation) {
22491
22573
  CitationLocation.visit = (value, visitor) => {
22574
+ if (value.web !== void 0)
22575
+ return visitor.web(value.web);
22492
22576
  if (value.documentChar !== void 0)
22493
22577
  return visitor.documentChar(value.documentChar);
22494
22578
  if (value.documentPage !== void 0)
@@ -22641,6 +22725,9 @@ var require_dist_cjs65 = __commonJS({
22641
22725
  ERROR: "error",
22642
22726
  SUCCESS: "success"
22643
22727
  };
22728
+ var ToolUseType = {
22729
+ SERVER_TOOL_USE: "server_tool_use"
22730
+ };
22644
22731
  exports2.ContentBlock = void 0;
22645
22732
  (function(ContentBlock) {
22646
22733
  ContentBlock.visit = (value, visitor) => {
@@ -22720,6 +22807,8 @@ var require_dist_cjs65 = __commonJS({
22720
22807
  Tool.visit = (value, visitor) => {
22721
22808
  if (value.toolSpec !== void 0)
22722
22809
  return visitor.toolSpec(value.toolSpec);
22810
+ if (value.systemTool !== void 0)
22811
+ return visitor.systemTool(value.systemTool);
22723
22812
  if (value.cachePoint !== void 0)
22724
22813
  return visitor.cachePoint(value.cachePoint);
22725
22814
  return visitor._(value.$unknown[0], value.$unknown[1]);
@@ -22799,6 +22888,14 @@ var require_dist_cjs65 = __commonJS({
22799
22888
  return visitor._(value.$unknown[0], value.$unknown[1]);
22800
22889
  };
22801
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 = {}));
22802
22899
  exports2.ContentBlockDelta = void 0;
22803
22900
  (function(ContentBlockDelta) {
22804
22901
  ContentBlockDelta.visit = (value, visitor) => {
@@ -22806,6 +22903,8 @@ var require_dist_cjs65 = __commonJS({
22806
22903
  return visitor.text(value.text);
22807
22904
  if (value.toolUse !== void 0)
22808
22905
  return visitor.toolUse(value.toolUse);
22906
+ if (value.toolResult !== void 0)
22907
+ return visitor.toolResult(value.toolResult);
22809
22908
  if (value.reasoningContent !== void 0)
22810
22909
  return visitor.reasoningContent(value.reasoningContent);
22811
22910
  if (value.citation !== void 0)
@@ -22818,6 +22917,8 @@ var require_dist_cjs65 = __commonJS({
22818
22917
  ContentBlockStart.visit = (value, visitor) => {
22819
22918
  if (value.toolUse !== void 0)
22820
22919
  return visitor.toolUse(value.toolUse);
22920
+ if (value.toolResult !== void 0)
22921
+ return visitor.toolResult(value.toolResult);
22821
22922
  return visitor._(value.$unknown[0], value.$unknown[1]);
22822
22923
  };
22823
22924
  })(exports2.ContentBlockStart || (exports2.ContentBlockStart = {}));
@@ -23207,6 +23308,8 @@ var require_dist_cjs65 = __commonJS({
23207
23308
  return { text: obj.text };
23208
23309
  if (obj.toolUse !== void 0)
23209
23310
  return { toolUse: obj.toolUse };
23311
+ if (obj.toolResult !== void 0)
23312
+ return { toolResult: obj.toolResult.map((item) => item) };
23210
23313
  if (obj.reasoningContent !== void 0)
23211
23314
  return { reasoningContent: smithyClient.SENSITIVE_STRING };
23212
23315
  if (obj.citation !== void 0)
@@ -24302,6 +24405,7 @@ var require_dist_cjs65 = __commonJS({
24302
24405
  var se_Tool = (input, context) => {
24303
24406
  return exports2.Tool.visit(input, {
24304
24407
  cachePoint: (value) => ({ cachePoint: smithyClient._json(value) }),
24408
+ systemTool: (value) => ({ systemTool: smithyClient._json(value) }),
24305
24409
  toolSpec: (value) => ({ toolSpec: se_ToolSpecification(value) }),
24306
24410
  _: (name14, value) => ({ [name14]: value })
24307
24411
  });
@@ -24322,7 +24426,8 @@ var require_dist_cjs65 = __commonJS({
24322
24426
  return smithyClient.take(input, {
24323
24427
  content: (_2) => se_ToolResultContentBlocks(_2, context),
24324
24428
  status: [],
24325
- toolUseId: []
24429
+ toolUseId: [],
24430
+ type: []
24326
24431
  });
24327
24432
  };
24328
24433
  var se_ToolResultContentBlock = (input, context) => {
@@ -24356,7 +24461,8 @@ var require_dist_cjs65 = __commonJS({
24356
24461
  return smithyClient.take(input, {
24357
24462
  input: (_2) => se_Document(_2),
24358
24463
  name: [],
24359
- toolUseId: []
24464
+ toolUseId: [],
24465
+ type: []
24360
24466
  });
24361
24467
  };
24362
24468
  var se_VideoBlock = (input, context) => {
@@ -24464,6 +24570,11 @@ var require_dist_cjs65 = __commonJS({
24464
24570
  if (smithyClient.expectString(output.text) !== void 0) {
24465
24571
  return { text: smithyClient.expectString(output.text) };
24466
24572
  }
24573
+ if (output.toolResult != null) {
24574
+ return {
24575
+ toolResult: smithyClient._json(output.toolResult)
24576
+ };
24577
+ }
24467
24578
  if (output.toolUse != null) {
24468
24579
  return {
24469
24580
  toolUse: smithyClient._json(output.toolUse)
@@ -24809,7 +24920,8 @@ var require_dist_cjs65 = __commonJS({
24809
24920
  return smithyClient.take(output, {
24810
24921
  content: (_2) => de_ToolResultContentBlocks(_2, context),
24811
24922
  status: smithyClient.expectString,
24812
- toolUseId: smithyClient.expectString
24923
+ toolUseId: smithyClient.expectString,
24924
+ type: smithyClient.expectString
24813
24925
  });
24814
24926
  };
24815
24927
  var de_ToolResultContentBlock = (output, context) => {
@@ -24848,7 +24960,8 @@ var require_dist_cjs65 = __commonJS({
24848
24960
  return smithyClient.take(output, {
24849
24961
  input: (_2) => de_Document(_2),
24850
24962
  name: smithyClient.expectString,
24851
- toolUseId: smithyClient.expectString
24963
+ toolUseId: smithyClient.expectString,
24964
+ type: smithyClient.expectString
24852
24965
  });
24853
24966
  };
24854
24967
  var de_VideoBlock = (output, context) => {
@@ -25130,6 +25243,7 @@ var require_dist_cjs65 = __commonJS({
25130
25243
  exports2.SystemContentBlockFilterSensitiveLog = SystemContentBlockFilterSensitiveLog;
25131
25244
  exports2.ThrottlingException = ThrottlingException;
25132
25245
  exports2.ToolResultStatus = ToolResultStatus;
25246
+ exports2.ToolUseType = ToolUseType;
25133
25247
  exports2.Trace = Trace;
25134
25248
  exports2.ValidationException = ValidationException;
25135
25249
  exports2.VideoFormat = VideoFormat;
@@ -25149,16 +25263,16 @@ function prepareTools(mode) {
25149
25263
  }
25150
25264
  const toolWarnings = [];
25151
25265
  const bedrockTools = [];
25152
- for (const tool3 of tools2) {
25153
- if (tool3.type === "provider-defined") {
25154
- 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 });
25155
25269
  } else {
25156
25270
  bedrockTools.push({
25157
25271
  toolSpec: {
25158
- name: tool3.name,
25159
- description: tool3.description,
25272
+ name: tool4.name,
25273
+ description: tool4.description,
25160
25274
  inputSchema: {
25161
- json: tool3.parameters
25275
+ json: tool4.parameters
25162
25276
  }
25163
25277
  }
25164
25278
  });
@@ -27763,7 +27877,7 @@ async function waitForFileLock(lockPath, binaryPath) {
27763
27877
  }
27764
27878
  } catch {
27765
27879
  }
27766
- await new Promise((resolve4) => setTimeout(resolve4, LOCK_POLL_INTERVAL_MS));
27880
+ await new Promise((resolve5) => setTimeout(resolve5, LOCK_POLL_INTERVAL_MS));
27767
27881
  }
27768
27882
  if (process.env.DEBUG === "1" || process.env.VERBOSE === "1") {
27769
27883
  console.log(`Timeout waiting for file lock`);
@@ -28741,7 +28855,7 @@ Command: ${command}`;
28741
28855
  }
28742
28856
  }
28743
28857
  function extractWithStdin(binaryPath, cliArgs, content, options) {
28744
- return new Promise((resolve4, reject2) => {
28858
+ return new Promise((resolve5, reject2) => {
28745
28859
  const childProcess = (0, import_child_process4.spawn)(binaryPath, ["extract", ...cliArgs], {
28746
28860
  stdio: ["pipe", "pipe", "pipe"]
28747
28861
  });
@@ -28763,7 +28877,7 @@ function extractWithStdin(binaryPath, cliArgs, content, options) {
28763
28877
  }
28764
28878
  try {
28765
28879
  const result = processExtractOutput(stdout, options);
28766
- resolve4(result);
28880
+ resolve5(result);
28767
28881
  } catch (error2) {
28768
28882
  reject2(error2);
28769
28883
  }
@@ -33325,7 +33439,7 @@ function parseTargets(targets) {
33325
33439
  }
33326
33440
  return targets.split(/\s+/).filter((f3) => f3.length > 0);
33327
33441
  }
33328
- var searchSchema, querySchema, extractSchema, delegateSchema, bashSchema, attemptCompletionSchema, searchToolDefinition, queryToolDefinition, extractToolDefinition, delegateToolDefinition, 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;
33329
33443
  var init_common2 = __esm({
33330
33444
  "src/tools/common.js"() {
33331
33445
  "use strict";
@@ -33338,11 +33452,12 @@ var init_common2 = __esm({
33338
33452
  pattern: external_exports.string().describe("AST pattern to search for. Use $NAME for variable names, $$$PARAMS for parameter lists, etc."),
33339
33453
  path: external_exports.string().optional().default(".").describe("Path to search in"),
33340
33454
  language: external_exports.string().optional().default("rust").describe("Programming language to use for parsing"),
33341
- 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")
33342
33456
  });
33343
33457
  extractSchema = external_exports.object({
33344
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.'),
33345
- 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")
33346
33461
  });
33347
33462
  delegateSchema = external_exports.object({
33348
33463
  task: external_exports.string().describe("The task to delegate to a subagent. Be specific about what needs to be accomplished.")
@@ -33469,7 +33584,7 @@ Parameters:
33469
33584
  - pattern: (required) AST pattern to search for. Use $NAME for variable names, $$$PARAMS for parameter lists, etc.
33470
33585
  - path: (optional, default: '.') Path to search in.
33471
33586
  - language: (optional, default: 'rust') Programming language to use for parsing.
33472
- - 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).
33473
33588
  Usage Example:
33474
33589
 
33475
33590
  <examples>
@@ -33494,6 +33609,7 @@ Full file extraction should be the LAST RESORT! Always prefer search.
33494
33609
  Parameters:
33495
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.
33496
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.
33497
33613
 
33498
33614
  Usage Example:
33499
33615
 
@@ -33560,6 +33676,61 @@ Usage Example:
33560
33676
  <attempt_completion>
33561
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.
33562
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>
33563
33734
  `;
33564
33735
  searchDescription = "Search code in the repository using Elasticsearch-like query syntax. Use this tool first for any code-related questions.";
33565
33736
  queryDescription = "Search code using ast-grep structural pattern matching. Use this tool to find specific code structures like functions, classes, or methods.";
@@ -34656,14 +34827,14 @@ async function executeBashCommand(command, options = {}) {
34656
34827
  console.log(`[BashExecutor] Working directory: "${cwd}"`);
34657
34828
  console.log(`[BashExecutor] Timeout: ${timeout}ms`);
34658
34829
  }
34659
- return new Promise((resolve4, reject2) => {
34830
+ return new Promise((resolve5, reject2) => {
34660
34831
  const processEnv = {
34661
34832
  ...process.env,
34662
34833
  ...env
34663
34834
  };
34664
34835
  const args = parseCommandForExecution(command);
34665
34836
  if (!args || args.length === 0) {
34666
- resolve4({
34837
+ resolve5({
34667
34838
  success: false,
34668
34839
  error: "Failed to parse command",
34669
34840
  stdout: "",
@@ -34746,7 +34917,7 @@ async function executeBashCommand(command, options = {}) {
34746
34917
  success = false;
34747
34918
  error2 = `Command exited with code ${code}`;
34748
34919
  }
34749
- resolve4({
34920
+ resolve5({
34750
34921
  success,
34751
34922
  error: error2,
34752
34923
  stdout: stdout.trim(),
@@ -34766,7 +34937,7 @@ async function executeBashCommand(command, options = {}) {
34766
34937
  if (debug) {
34767
34938
  console.log(`[BashExecutor] Spawn error:`, error2);
34768
34939
  }
34769
- resolve4({
34940
+ resolve5({
34770
34941
  success: false,
34771
34942
  error: `Failed to execute command: ${error2.message}`,
34772
34943
  stdout: "",
@@ -35042,6 +35213,283 @@ Command failed with exit code ${result.exitCode}`;
35042
35213
  }
35043
35214
  });
35044
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
+
35045
35493
  // src/tools/langchain.js
35046
35494
  var init_langchain = __esm({
35047
35495
  "src/tools/langchain.js"() {
@@ -35191,8 +35639,10 @@ var init_tools = __esm({
35191
35639
  "use strict";
35192
35640
  init_vercel();
35193
35641
  init_bash();
35642
+ init_edit();
35194
35643
  init_langchain();
35195
35644
  init_common2();
35645
+ init_edit();
35196
35646
  init_system_message();
35197
35647
  init_vercel();
35198
35648
  init_bash();
@@ -35215,10 +35665,10 @@ async function listFilesByLevel(options) {
35215
35665
  maxFiles = 100,
35216
35666
  respectGitignore = true
35217
35667
  } = options;
35218
- if (!import_fs2.default.existsSync(directory)) {
35668
+ if (!import_fs4.default.existsSync(directory)) {
35219
35669
  throw new Error(`Directory does not exist: ${directory}`);
35220
35670
  }
35221
- 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"));
35222
35672
  if (gitDirExists && respectGitignore) {
35223
35673
  try {
35224
35674
  return await listFilesUsingGit(directory, maxFiles);
@@ -35233,8 +35683,8 @@ async function listFilesUsingGit(directory, maxFiles) {
35233
35683
  const { stdout } = await execAsync3("git ls-files", { cwd: directory });
35234
35684
  const files = stdout.split("\n").filter(Boolean);
35235
35685
  const sortedFiles = files.sort((a3, b3) => {
35236
- const depthA = a3.split(import_path6.default.sep).length;
35237
- 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;
35238
35688
  return depthA - depthB;
35239
35689
  });
35240
35690
  return sortedFiles.slice(0, maxFiles);
@@ -35249,19 +35699,19 @@ async function listFilesByLevelManually(directory, maxFiles, respectGitignore) {
35249
35699
  while (queue.length > 0 && result.length < maxFiles) {
35250
35700
  const { dir, level } = queue.shift();
35251
35701
  try {
35252
- const entries = import_fs2.default.readdirSync(dir, { withFileTypes: true });
35702
+ const entries = import_fs4.default.readdirSync(dir, { withFileTypes: true });
35253
35703
  const files = entries.filter((entry) => entry.isFile());
35254
35704
  for (const file of files) {
35255
35705
  if (result.length >= maxFiles) break;
35256
- const filePath = import_path6.default.join(dir, file.name);
35257
- 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);
35258
35708
  if (shouldIgnore(relativePath, ignorePatterns)) continue;
35259
35709
  result.push(relativePath);
35260
35710
  }
35261
35711
  const dirs = entries.filter((entry) => entry.isDirectory());
35262
35712
  for (const subdir of dirs) {
35263
- const subdirPath = import_path6.default.join(dir, subdir.name);
35264
- 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);
35265
35715
  if (shouldIgnore(relativeSubdirPath, ignorePatterns)) continue;
35266
35716
  if (subdir.name === "node_modules" || subdir.name === ".git") continue;
35267
35717
  queue.push({ dir: subdirPath, level: level + 1 });
@@ -35273,12 +35723,12 @@ async function listFilesByLevelManually(directory, maxFiles, respectGitignore) {
35273
35723
  return result;
35274
35724
  }
35275
35725
  function loadGitignorePatterns(directory) {
35276
- const gitignorePath = import_path6.default.join(directory, ".gitignore");
35277
- if (!import_fs2.default.existsSync(gitignorePath)) {
35726
+ const gitignorePath = import_path7.default.join(directory, ".gitignore");
35727
+ if (!import_fs4.default.existsSync(gitignorePath)) {
35278
35728
  return [];
35279
35729
  }
35280
35730
  try {
35281
- const content = import_fs2.default.readFileSync(gitignorePath, "utf8");
35731
+ const content = import_fs4.default.readFileSync(gitignorePath, "utf8");
35282
35732
  return content.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
35283
35733
  } catch (error2) {
35284
35734
  console.error(`Warning: Could not read .gitignore: ${error2.message}`);
@@ -35296,12 +35746,12 @@ function shouldIgnore(filePath, ignorePatterns) {
35296
35746
  }
35297
35747
  return false;
35298
35748
  }
35299
- var import_fs2, import_path6, import_util11, import_child_process7, execAsync3;
35749
+ var import_fs4, import_path7, import_util11, import_child_process7, execAsync3;
35300
35750
  var init_file_lister = __esm({
35301
35751
  "src/utils/file-lister.js"() {
35302
35752
  "use strict";
35303
- import_fs2 = __toESM(require("fs"), 1);
35304
- import_path6 = __toESM(require("path"), 1);
35753
+ import_fs4 = __toESM(require("fs"), 1);
35754
+ import_path7 = __toESM(require("path"), 1);
35305
35755
  import_util11 = require("util");
35306
35756
  import_child_process7 = require("child_process");
35307
35757
  execAsync3 = (0, import_util11.promisify)(import_child_process7.exec);
@@ -35309,12 +35759,12 @@ var init_file_lister = __esm({
35309
35759
  });
35310
35760
 
35311
35761
  // src/agent/simpleTelemetry.js
35312
- var import_fs3, import_path7;
35762
+ var import_fs5, import_path8;
35313
35763
  var init_simpleTelemetry = __esm({
35314
35764
  "src/agent/simpleTelemetry.js"() {
35315
35765
  "use strict";
35316
- import_fs3 = require("fs");
35317
- import_path7 = require("path");
35766
+ import_fs5 = require("fs");
35767
+ import_path8 = require("path");
35318
35768
  }
35319
35769
  });
35320
35770
 
@@ -36163,7 +36613,7 @@ var init_escape = __esm({
36163
36613
  });
36164
36614
 
36165
36615
  // node_modules/minimatch/dist/esm/index.js
36166
- 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;
36167
36617
  var init_esm = __esm({
36168
36618
  "node_modules/minimatch/dist/esm/index.js"() {
36169
36619
  import_brace_expansion = __toESM(require_brace_expansion(), 1);
@@ -36236,8 +36686,8 @@ var init_esm = __esm({
36236
36686
  win32: { sep: "\\" },
36237
36687
  posix: { sep: "/" }
36238
36688
  };
36239
- sep = defaultPlatform === "win32" ? path5.win32.sep : path5.posix.sep;
36240
- minimatch.sep = sep;
36689
+ sep2 = defaultPlatform === "win32" ? path5.win32.sep : path5.posix.sep;
36690
+ minimatch.sep = sep2;
36241
36691
  GLOBSTAR = Symbol("globstar **");
36242
36692
  minimatch.GLOBSTAR = GLOBSTAR;
36243
36693
  qmark2 = "[^/]";
@@ -38999,10 +39449,10 @@ var init_esm3 = __esm({
38999
39449
  * Return a void Promise that resolves once the stream ends.
39000
39450
  */
39001
39451
  async promise() {
39002
- return new Promise((resolve4, reject2) => {
39452
+ return new Promise((resolve5, reject2) => {
39003
39453
  this.on(DESTROYED, () => reject2(new Error("stream destroyed")));
39004
39454
  this.on("error", (er) => reject2(er));
39005
- this.on("end", () => resolve4());
39455
+ this.on("end", () => resolve5());
39006
39456
  });
39007
39457
  }
39008
39458
  /**
@@ -39026,7 +39476,7 @@ var init_esm3 = __esm({
39026
39476
  return Promise.resolve({ done: false, value: res });
39027
39477
  if (this[EOF])
39028
39478
  return stop();
39029
- let resolve4;
39479
+ let resolve5;
39030
39480
  let reject2;
39031
39481
  const onerr = (er) => {
39032
39482
  this.off("data", ondata);
@@ -39040,19 +39490,19 @@ var init_esm3 = __esm({
39040
39490
  this.off("end", onend);
39041
39491
  this.off(DESTROYED, ondestroy);
39042
39492
  this.pause();
39043
- resolve4({ value, done: !!this[EOF] });
39493
+ resolve5({ value, done: !!this[EOF] });
39044
39494
  };
39045
39495
  const onend = () => {
39046
39496
  this.off("error", onerr);
39047
39497
  this.off("data", ondata);
39048
39498
  this.off(DESTROYED, ondestroy);
39049
39499
  stop();
39050
- resolve4({ done: true, value: void 0 });
39500
+ resolve5({ done: true, value: void 0 });
39051
39501
  };
39052
39502
  const ondestroy = () => onerr(new Error("stream destroyed"));
39053
39503
  return new Promise((res2, rej) => {
39054
39504
  reject2 = rej;
39055
- resolve4 = res2;
39505
+ resolve5 = res2;
39056
39506
  this.once(DESTROYED, ondestroy);
39057
39507
  this.once("error", onerr);
39058
39508
  this.once("end", onend);
@@ -39151,22 +39601,22 @@ var init_esm3 = __esm({
39151
39601
  });
39152
39602
 
39153
39603
  // node_modules/path-scurry/dist/esm/index.js
39154
- 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;
39155
39605
  var init_esm4 = __esm({
39156
39606
  "node_modules/path-scurry/dist/esm/index.js"() {
39157
39607
  init_esm2();
39158
39608
  import_node_path = require("node:path");
39159
39609
  import_node_url = require("node:url");
39160
- import_fs4 = require("fs");
39610
+ import_fs6 = require("fs");
39161
39611
  actualFS = __toESM(require("node:fs"), 1);
39162
39612
  import_promises = require("node:fs/promises");
39163
39613
  init_esm3();
39164
- realpathSync = import_fs4.realpathSync.native;
39614
+ realpathSync = import_fs6.realpathSync.native;
39165
39615
  defaultFS = {
39166
- lstatSync: import_fs4.lstatSync,
39167
- readdir: import_fs4.readdir,
39168
- readdirSync: import_fs4.readdirSync,
39169
- readlinkSync: import_fs4.readlinkSync,
39616
+ lstatSync: import_fs6.lstatSync,
39617
+ readdir: import_fs6.readdir,
39618
+ readdirSync: import_fs6.readdirSync,
39619
+ readlinkSync: import_fs6.readlinkSync,
39170
39620
  realpathSync,
39171
39621
  promises: {
39172
39622
  lstat: import_promises.lstat,
@@ -40032,9 +40482,9 @@ var init_esm4 = __esm({
40032
40482
  if (this.#asyncReaddirInFlight) {
40033
40483
  await this.#asyncReaddirInFlight;
40034
40484
  } else {
40035
- let resolve4 = () => {
40485
+ let resolve5 = () => {
40036
40486
  };
40037
- this.#asyncReaddirInFlight = new Promise((res) => resolve4 = res);
40487
+ this.#asyncReaddirInFlight = new Promise((res) => resolve5 = res);
40038
40488
  try {
40039
40489
  for (const e3 of await this.#fs.promises.readdir(fullpath, {
40040
40490
  withFileTypes: true
@@ -40047,7 +40497,7 @@ var init_esm4 = __esm({
40047
40497
  children.provisional = 0;
40048
40498
  }
40049
40499
  this.#asyncReaddirInFlight = void 0;
40050
- resolve4();
40500
+ resolve5();
40051
40501
  }
40052
40502
  return children.slice(0, children.provisional);
40053
40503
  }
@@ -40277,8 +40727,8 @@ var init_esm4 = __esm({
40277
40727
  *
40278
40728
  * @internal
40279
40729
  */
40280
- constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs6 = defaultFS } = {}) {
40281
- this.#fs = fsFromOption(fs6);
40730
+ constructor(cwd = process.cwd(), pathImpl, sep3, { nocase, childrenCacheSize = 16 * 1024, fs: fs7 = defaultFS } = {}) {
40731
+ this.#fs = fsFromOption(fs7);
40282
40732
  if (cwd instanceof URL || cwd.startsWith("file://")) {
40283
40733
  cwd = (0, import_node_url.fileURLToPath)(cwd);
40284
40734
  }
@@ -40288,7 +40738,7 @@ var init_esm4 = __esm({
40288
40738
  this.#resolveCache = new ResolveCache();
40289
40739
  this.#resolvePosixCache = new ResolveCache();
40290
40740
  this.#children = new ChildrenCache(childrenCacheSize);
40291
- const split = cwdPath.substring(this.rootPath.length).split(sep2);
40741
+ const split = cwdPath.substring(this.rootPath.length).split(sep3);
40292
40742
  if (split.length === 1 && !split[0]) {
40293
40743
  split.pop();
40294
40744
  }
@@ -40836,8 +41286,8 @@ var init_esm4 = __esm({
40836
41286
  /**
40837
41287
  * @internal
40838
41288
  */
40839
- newRoot(fs6) {
40840
- 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 });
40841
41291
  }
40842
41292
  /**
40843
41293
  * Return true if the provided path string is an absolute path
@@ -40865,8 +41315,8 @@ var init_esm4 = __esm({
40865
41315
  /**
40866
41316
  * @internal
40867
41317
  */
40868
- newRoot(fs6) {
40869
- 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 });
40870
41320
  }
40871
41321
  /**
40872
41322
  * Return true if the provided path string is an absolute path
@@ -42059,9 +42509,23 @@ function createWrappedTools(baseTools) {
42059
42509
  baseTools.bashTool.execute
42060
42510
  );
42061
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
+ }
42062
42526
  return wrappedTools;
42063
42527
  }
42064
- var import_child_process8, 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;
42065
42529
  var init_probeTool = __esm({
42066
42530
  "src/agent/probeTool.js"() {
42067
42531
  "use strict";
@@ -42070,15 +42534,15 @@ var init_probeTool = __esm({
42070
42534
  import_util12 = require("util");
42071
42535
  import_crypto3 = require("crypto");
42072
42536
  import_events = require("events");
42073
- import_fs5 = __toESM(require("fs"), 1);
42074
- import_fs6 = require("fs");
42075
- 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);
42076
42540
  init_esm5();
42077
42541
  toolCallEmitter = new import_events.EventEmitter();
42078
42542
  activeToolExecutions = /* @__PURE__ */ new Map();
42079
- wrapToolWithEmitter = (tool3, toolName, baseExecute) => {
42543
+ wrapToolWithEmitter = (tool4, toolName, baseExecute) => {
42080
42544
  return {
42081
- ...tool3,
42545
+ ...tool4,
42082
42546
  // Spread schema, description etc.
42083
42547
  execute: async (params) => {
42084
42548
  const debug = process.env.DEBUG === "1";
@@ -42160,17 +42624,17 @@ var init_probeTool = __esm({
42160
42624
  execute: async (params) => {
42161
42625
  const { directory = ".", workingDirectory } = params;
42162
42626
  const baseCwd = workingDirectory || process.cwd();
42163
- const secureBaseDir = import_path8.default.resolve(baseCwd);
42627
+ const secureBaseDir = import_path9.default.resolve(baseCwd);
42164
42628
  const isDependencyPath = directory.startsWith("/dep/") || directory.startsWith("go:") || directory.startsWith("js:") || directory.startsWith("rust:");
42165
42629
  let targetDir;
42166
- if (import_path8.default.isAbsolute(directory)) {
42167
- targetDir = import_path8.default.resolve(directory);
42168
- 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) {
42169
42633
  throw new Error(`Path traversal attempt detected. Cannot access directory outside workspace: ${directory}`);
42170
42634
  }
42171
42635
  } else {
42172
- targetDir = import_path8.default.resolve(secureBaseDir, directory);
42173
- 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) {
42174
42638
  throw new Error(`Path traversal attempt detected. Access denied: ${directory}`);
42175
42639
  }
42176
42640
  }
@@ -42179,7 +42643,7 @@ var init_probeTool = __esm({
42179
42643
  console.log(`[DEBUG] Listing files in directory: ${targetDir}`);
42180
42644
  }
42181
42645
  try {
42182
- const files = await import_fs6.promises.readdir(targetDir, { withFileTypes: true });
42646
+ const files = await import_fs8.promises.readdir(targetDir, { withFileTypes: true });
42183
42647
  const formatSize = (size) => {
42184
42648
  if (size < 1024) return `${size}B`;
42185
42649
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)}K`;
@@ -42188,10 +42652,10 @@ var init_probeTool = __esm({
42188
42652
  };
42189
42653
  const entries = await Promise.all(files.map(async (file) => {
42190
42654
  const isDirectory = file.isDirectory();
42191
- const fullPath = import_path8.default.join(targetDir, file.name);
42655
+ const fullPath = import_path9.default.join(targetDir, file.name);
42192
42656
  let size = 0;
42193
42657
  try {
42194
- const stats = await import_fs6.promises.stat(fullPath);
42658
+ const stats = await import_fs8.promises.stat(fullPath);
42195
42659
  size = stats.size;
42196
42660
  } catch (statError) {
42197
42661
  if (debug) {
@@ -42233,17 +42697,17 @@ var init_probeTool = __esm({
42233
42697
  throw new Error("Pattern is required for file search");
42234
42698
  }
42235
42699
  const baseCwd = workingDirectory || process.cwd();
42236
- const secureBaseDir = import_path8.default.resolve(baseCwd);
42700
+ const secureBaseDir = import_path9.default.resolve(baseCwd);
42237
42701
  const isDependencyPath = directory.startsWith("/dep/") || directory.startsWith("go:") || directory.startsWith("js:") || directory.startsWith("rust:");
42238
42702
  let targetDir;
42239
- if (import_path8.default.isAbsolute(directory)) {
42240
- targetDir = import_path8.default.resolve(directory);
42241
- 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) {
42242
42706
  throw new Error(`Path traversal attempt detected. Cannot access directory outside workspace: ${directory}`);
42243
42707
  }
42244
42708
  } else {
42245
- targetDir = import_path8.default.resolve(secureBaseDir, directory);
42246
- 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) {
42247
42711
  throw new Error(`Path traversal attempt detected. Access denied: ${directory}`);
42248
42712
  }
42249
42713
  }
@@ -42314,8 +42778,10 @@ var init_index = __esm({
42314
42778
  init_file_lister();
42315
42779
  init_system_message();
42316
42780
  init_common2();
42781
+ init_edit();
42317
42782
  init_vercel();
42318
42783
  init_bash();
42784
+ init_edit();
42319
42785
  init_ProbeAgent();
42320
42786
  init_simpleTelemetry();
42321
42787
  init_probeTool();
@@ -42397,8 +42863,8 @@ function checkAttemptCompleteRecovery(cleanedXmlString, validTools = []) {
42397
42863
  function hasOtherToolTags(xmlString, validTools = []) {
42398
42864
  const defaultTools = ["search", "query", "extract", "listFiles", "searchFiles", "implement", "attempt_completion"];
42399
42865
  const toolsToCheck = validTools.length > 0 ? validTools : defaultTools;
42400
- for (const tool3 of toolsToCheck) {
42401
- if (tool3 !== "attempt_completion" && xmlString.includes(`<${tool3}`)) {
42866
+ for (const tool4 of toolsToCheck) {
42867
+ if (tool4 !== "attempt_completion" && xmlString.includes(`<${tool4}`)) {
42402
42868
  return true;
42403
42869
  }
42404
42870
  }
@@ -42435,6 +42901,10 @@ function createTools(configOptions) {
42435
42901
  if (configOptions.enableBash) {
42436
42902
  tools2.bashTool = bashTool(configOptions);
42437
42903
  }
42904
+ if (configOptions.allowEdit) {
42905
+ tools2.editTool = editTool(configOptions);
42906
+ tools2.createTool = createTool(configOptions);
42907
+ }
42438
42908
  return tools2;
42439
42909
  }
42440
42910
  function parseXmlToolCallWithThinking(xmlString, validTools) {
@@ -42536,7 +43006,7 @@ function createMockProvider() {
42536
43006
  provider: "mock",
42537
43007
  // Mock the doGenerate method used by Vercel AI SDK
42538
43008
  doGenerate: async ({ messages, tools: tools2 }) => {
42539
- await new Promise((resolve4) => setTimeout(resolve4, 10));
43009
+ await new Promise((resolve5) => setTimeout(resolve5, 10));
42540
43010
  return {
42541
43011
  text: "This is a mock response for testing",
42542
43012
  toolCalls: [],
@@ -54523,16 +54993,6 @@ var init_parser2 = __esm({
54523
54993
  this.subgraph = this.RULE("subgraph", () => {
54524
54994
  this.CONSUME(SubgraphKeyword);
54525
54995
  this.OR([
54526
- {
54527
- ALT: () => {
54528
- this.CONSUME(Identifier, { LABEL: "subgraphId" });
54529
- this.OPTION(() => {
54530
- this.CONSUME1(SquareOpen);
54531
- this.SUBRULE(this.nodeContent);
54532
- this.CONSUME1(SquareClose);
54533
- });
54534
- }
54535
- },
54536
54996
  {
54537
54997
  ALT: () => {
54538
54998
  this.CONSUME(QuotedString, { LABEL: "subgraphTitleQ" });
@@ -54544,6 +55004,33 @@ var init_parser2 = __esm({
54544
55004
  this.SUBRULE2(this.nodeContent);
54545
55005
  this.CONSUME2(SquareClose);
54546
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
+ }
54547
55034
  }
54548
55035
  ]);
54549
55036
  this.CONSUME(Newline);
@@ -55147,7 +55634,6 @@ var init_semantics = __esm({
55147
55634
  const last2 = allChildren[allChildren.length - 1];
55148
55635
  const isSlash = (t3) => t3.image === "/" || t3.image === "\\";
55149
55636
  if (isSlash(first2) && isSlash(last2)) {
55150
- continue;
55151
55637
  }
55152
55638
  }
55153
55639
  const opens = ch.RoundOpen || [];
@@ -55941,16 +56427,19 @@ function mapFlowchartParserError(err, text) {
55941
56427
  const subgraphIdx = lineStr.indexOf("subgraph");
55942
56428
  if (subgraphIdx !== -1) {
55943
56429
  const afterSubgraph = lineStr.slice(subgraphIdx + 8).trim();
55944
- if (afterSubgraph && !afterSubgraph.startsWith('"') && !afterSubgraph.startsWith("'") && afterSubgraph.includes(" ")) {
55945
- return {
55946
- line,
55947
- column,
55948
- severity: "error",
55949
- code: "FL-SUBGRAPH-UNQUOTED-TITLE",
55950
- message: "Subgraph titles with spaces must be quoted.",
55951
- hint: 'Example: subgraph "Existing Logic Path" or use underscores: subgraph Existing_Logic_Path',
55952
- length: afterSubgraph.length
55953
- };
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
+ }
55954
56443
  }
55955
56444
  }
55956
56445
  }
@@ -56648,11 +57137,11 @@ function validateFlowchart(text, options = {}) {
56648
57137
  const byLine = /* @__PURE__ */ new Map();
56649
57138
  const collect = (arr) => {
56650
57139
  for (const e3 of arr || []) {
56651
- if (e3 && e3.code === "FL-LABEL-PARENS-UNQUOTED") {
57140
+ if (e3 && (e3.code === "FL-LABEL-PARENS-UNQUOTED" || e3.code === "FL-LABEL-AT-IN-UNQUOTED")) {
56652
57141
  const ln = e3.line ?? 0;
56653
57142
  const col = e3.column ?? 1;
56654
57143
  const list2 = byLine.get(ln) || [];
56655
- list2.push(col);
57144
+ list2.push({ start: col, end: col });
56656
57145
  byLine.set(ln, list2);
56657
57146
  }
56658
57147
  }
@@ -56661,33 +57150,91 @@ function validateFlowchart(text, options = {}) {
56661
57150
  collect(errs);
56662
57151
  const lines2 = text2.split(/\r?\n/);
56663
57152
  for (let ii = 0; ii < lines2.length; ii++) {
56664
- const raw2 = lines2[ii] || "";
56665
- if (!raw2.includes("[") || !raw2.includes("]"))
57153
+ const raw = lines2[ii] || "";
57154
+ if (!raw.includes("[") || !raw.includes("]"))
56666
57155
  continue;
56667
- let search2 = 0;
56668
- while (true) {
56669
- const open2 = raw2.indexOf("[", search2);
56670
- if (open2 === -1)
56671
- break;
56672
- const close2 = raw2.indexOf("]", open2 + 1);
56673
- if (close2 === -1)
56674
- break;
56675
- const seg2 = raw2.slice(open2 + 1, close2);
56676
- const trimmed2 = seg2.trim();
56677
- const ln2 = ii + 1;
56678
- const lsp = trimmed2.slice(0, 1);
56679
- const rsp = trimmed2.slice(-1);
56680
- const isSlashPair = (lsp === "/" || lsp === "\\") && (rsp === "/" || rsp === "\\");
56681
- const isParenWrapped = lsp === "(" && rsp === ")";
56682
- const segStartCol = open2 + 2;
56683
- const segEndCol = close2 + 1;
56684
- const existing = byLine.get(ln2) || [];
56685
- const covered = existing.some((c3) => c3 >= segStartCol && c3 <= segEndCol);
56686
- if (!covered && !/^".*"$/.test(trimmed2) && (seg2.includes("(") || seg2.includes(")")) && !isSlashPair && !isParenWrapped) {
56687
- errs.push({ line: ln2, column: segStartCol, 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;.' });
56688
- byLine.set(ln2, existing.concat([segStartCol]));
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
+ }
56689
57236
  }
56690
- search2 = close2 + 1;
57237
+ i3++;
56691
57238
  }
56692
57239
  }
56693
57240
  }
@@ -68173,7 +68720,7 @@ var require_bk = __commonJS({
68173
68720
  return xs;
68174
68721
  }
68175
68722
  function buildBlockGraph(g3, layering, root2, reverseSep) {
68176
- 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);
68177
68724
  _2.forEach(layering, function(layer) {
68178
68725
  var u3;
68179
68726
  _2.forEach(layer, function(v3) {
@@ -68263,7 +68810,7 @@ var require_bk = __commonJS({
68263
68810
  alignCoordinates(xss, smallestWidth);
68264
68811
  return balance(xss, g3.graph().align);
68265
68812
  }
68266
- function sep2(nodeSep, edgeSep, reverseSep) {
68813
+ function sep3(nodeSep, edgeSep, reverseSep) {
68267
68814
  return function(g3, v3, w3) {
68268
68815
  var vLabel = g3.node(v3);
68269
68816
  var wLabel = g3.node(w3);
@@ -75557,7 +76104,7 @@ var require_compile = __commonJS({
75557
76104
  const schOrFunc = root2.refs[ref];
75558
76105
  if (schOrFunc)
75559
76106
  return schOrFunc;
75560
- let _sch = resolve4.call(this, root2, ref);
76107
+ let _sch = resolve5.call(this, root2, ref);
75561
76108
  if (_sch === void 0) {
75562
76109
  const schema = (_a16 = root2.localRefs) === null || _a16 === void 0 ? void 0 : _a16[ref];
75563
76110
  const { schemaId } = this.opts;
@@ -75584,7 +76131,7 @@ var require_compile = __commonJS({
75584
76131
  function sameSchemaEnv(s1, s22) {
75585
76132
  return s1.schema === s22.schema && s1.root === s22.root && s1.baseId === s22.baseId;
75586
76133
  }
75587
- function resolve4(root2, ref) {
76134
+ function resolve5(root2, ref) {
75588
76135
  let sch;
75589
76136
  while (typeof (sch = this.refs[ref]) == "string")
75590
76137
  ref = sch;
@@ -76159,7 +76706,7 @@ var require_fast_uri = __commonJS({
76159
76706
  }
76160
76707
  return uri;
76161
76708
  }
76162
- function resolve4(baseURI, relativeURI, options) {
76709
+ function resolve5(baseURI, relativeURI, options) {
76163
76710
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
76164
76711
  const resolved = resolveComponent(parse6(baseURI, schemelessOptions), parse6(relativeURI, schemelessOptions), schemelessOptions, true);
76165
76712
  schemelessOptions.skipEscape = true;
@@ -76386,7 +76933,7 @@ var require_fast_uri = __commonJS({
76386
76933
  var fastUri = {
76387
76934
  SCHEMES,
76388
76935
  normalize: normalize2,
76389
- resolve: resolve4,
76936
+ resolve: resolve5,
76390
76937
  resolveComponent,
76391
76938
  equal,
76392
76939
  serialize,
@@ -80408,11 +80955,11 @@ function loadMCPConfigurationFromPath(configPath) {
80408
80955
  if (!configPath) {
80409
80956
  throw new Error("Config path is required");
80410
80957
  }
80411
- if (!(0, import_fs7.existsSync)(configPath)) {
80958
+ if (!(0, import_fs9.existsSync)(configPath)) {
80412
80959
  throw new Error(`MCP configuration file not found: ${configPath}`);
80413
80960
  }
80414
80961
  try {
80415
- const content = (0, import_fs7.readFileSync)(configPath, "utf8");
80962
+ const content = (0, import_fs9.readFileSync)(configPath, "utf8");
80416
80963
  const config = JSON.parse(content);
80417
80964
  if (process.env.DEBUG === "1" || process.env.DEBUG_MCP === "1") {
80418
80965
  console.error(`[MCP DEBUG] Loaded configuration from: ${configPath}`);
@@ -80427,19 +80974,19 @@ function loadMCPConfiguration() {
80427
80974
  // Environment variable path
80428
80975
  process.env.MCP_CONFIG_PATH,
80429
80976
  // Local project paths
80430
- (0, import_path9.join)(process.cwd(), ".mcp", "config.json"),
80431
- (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"),
80432
80979
  // Home directory paths
80433
- (0, import_path9.join)((0, import_os3.homedir)(), ".config", "probe", "mcp.json"),
80434
- (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"),
80435
80982
  // Claude-style config location
80436
- (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")
80437
80984
  ].filter(Boolean);
80438
80985
  let config = null;
80439
80986
  for (const configPath of configPaths) {
80440
- if ((0, import_fs7.existsSync)(configPath)) {
80987
+ if ((0, import_fs9.existsSync)(configPath)) {
80441
80988
  try {
80442
- const content = (0, import_fs7.readFileSync)(configPath, "utf8");
80989
+ const content = (0, import_fs9.readFileSync)(configPath, "utf8");
80443
80990
  config = JSON.parse(content);
80444
80991
  if (process.env.DEBUG === "1" || process.env.DEBUG_MCP === "1") {
80445
80992
  console.error(`[MCP DEBUG] Loaded configuration from: ${configPath}`);
@@ -80535,22 +81082,22 @@ function parseEnabledServers(config) {
80535
81082
  }
80536
81083
  return servers;
80537
81084
  }
80538
- 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;
80539
81086
  var init_config = __esm({
80540
81087
  "src/agent/mcp/config.js"() {
80541
81088
  "use strict";
80542
- import_fs7 = require("fs");
80543
- import_path9 = require("path");
81089
+ import_fs9 = require("fs");
81090
+ import_path10 = require("path");
80544
81091
  import_os3 = require("os");
80545
81092
  import_url4 = require("url");
80546
81093
  __filename4 = (0, import_url4.fileURLToPath)("file:///");
80547
- __dirname4 = (0, import_path9.dirname)(__filename4);
81094
+ __dirname4 = (0, import_path10.dirname)(__filename4);
80548
81095
  DEFAULT_CONFIG = {
80549
81096
  mcpServers: {
80550
81097
  // Example probe server configuration
80551
81098
  "probe-local": {
80552
81099
  command: "node",
80553
- args: [(0, import_path9.join)(__dirname4, "../../../examples/chat/mcpServer.js")],
81100
+ args: [(0, import_path10.join)(__dirname4, "../../../examples/chat/mcpServer.js")],
80554
81101
  transport: "stdio",
80555
81102
  enabled: false
80556
81103
  },
@@ -80733,12 +81280,12 @@ var init_client2 = __esm({
80733
81280
  const toolsResponse = await client.listTools();
80734
81281
  const toolCount = toolsResponse?.tools?.length || 0;
80735
81282
  if (toolsResponse && toolsResponse.tools) {
80736
- for (const tool3 of toolsResponse.tools) {
80737
- const qualifiedName = `${name14}_${tool3.name}`;
81283
+ for (const tool4 of toolsResponse.tools) {
81284
+ const qualifiedName = `${name14}_${tool4.name}`;
80738
81285
  this.tools.set(qualifiedName, {
80739
- ...tool3,
81286
+ ...tool4,
80740
81287
  serverName: name14,
80741
- originalName: tool3.name
81288
+ originalName: tool4.name
80742
81289
  });
80743
81290
  if (this.debug) {
80744
81291
  console.error(`[MCP DEBUG] Registered tool: ${qualifiedName}`);
@@ -80761,13 +81308,13 @@ var init_client2 = __esm({
80761
81308
  * @param {Object} args - Tool arguments
80762
81309
  */
80763
81310
  async callTool(toolName, args) {
80764
- const tool3 = this.tools.get(toolName);
80765
- if (!tool3) {
81311
+ const tool4 = this.tools.get(toolName);
81312
+ if (!tool4) {
80766
81313
  throw new Error(`Unknown tool: ${toolName}`);
80767
81314
  }
80768
- const clientInfo = this.clients.get(tool3.serverName);
81315
+ const clientInfo = this.clients.get(tool4.serverName);
80769
81316
  if (!clientInfo) {
80770
- throw new Error(`Server ${tool3.serverName} not connected`);
81317
+ throw new Error(`Server ${tool4.serverName} not connected`);
80771
81318
  }
80772
81319
  try {
80773
81320
  if (this.debug) {
@@ -80781,7 +81328,7 @@ var init_client2 = __esm({
80781
81328
  });
80782
81329
  const result = await Promise.race([
80783
81330
  clientInfo.client.callTool({
80784
- name: tool3.originalName,
81331
+ name: tool4.originalName,
80785
81332
  arguments: args
80786
81333
  }),
80787
81334
  timeoutPromise
@@ -80804,11 +81351,11 @@ var init_client2 = __esm({
80804
81351
  */
80805
81352
  getTools() {
80806
81353
  const tools2 = {};
80807
- for (const [name14, tool3] of this.tools.entries()) {
81354
+ for (const [name14, tool4] of this.tools.entries()) {
80808
81355
  tools2[name14] = {
80809
- description: tool3.description,
80810
- inputSchema: tool3.inputSchema,
80811
- serverName: tool3.serverName
81356
+ description: tool4.description,
81357
+ inputSchema: tool4.inputSchema,
81358
+ serverName: tool4.serverName
80812
81359
  };
80813
81360
  }
80814
81361
  return tools2;
@@ -80819,10 +81366,10 @@ var init_client2 = __esm({
80819
81366
  */
80820
81367
  getVercelTools() {
80821
81368
  const tools2 = {};
80822
- for (const [name14, tool3] of this.tools.entries()) {
81369
+ for (const [name14, tool4] of this.tools.entries()) {
80823
81370
  tools2[name14] = {
80824
- description: tool3.description,
80825
- inputSchema: tool3.inputSchema,
81371
+ description: tool4.description,
81372
+ inputSchema: tool4.inputSchema,
80826
81373
  execute: async (args) => {
80827
81374
  const result = await this.callTool(name14, args);
80828
81375
  if (result.content && result.content[0]) {
@@ -80871,9 +81418,9 @@ var init_client2 = __esm({
80871
81418
  });
80872
81419
 
80873
81420
  // src/agent/mcp/xmlBridge.js
80874
- function mcpToolToXmlDefinition(name14, tool3) {
80875
- const description = tool3.description || "MCP tool";
80876
- 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 || {};
80877
81424
  let paramDocs = "";
80878
81425
  if (inputSchema.properties) {
80879
81426
  paramDocs = "\n\nParameters (provide as JSON object):";
@@ -81052,8 +81599,8 @@ var init_xmlBridge = __esm({
81052
81599
  const vercelTools = this.mcpManager.getVercelTools();
81053
81600
  this.mcpTools = vercelTools;
81054
81601
  const toolCount = Object.keys(vercelTools).length;
81055
- for (const [name14, tool3] of Object.entries(vercelTools)) {
81056
- this.xmlDefinitions[name14] = mcpToolToXmlDefinition(name14, tool3);
81602
+ for (const [name14, tool4] of Object.entries(vercelTools)) {
81603
+ this.xmlDefinitions[name14] = mcpToolToXmlDefinition(name14, tool4);
81057
81604
  }
81058
81605
  if (toolCount === 0) {
81059
81606
  console.error("[MCP INFO] MCP initialization complete: 0 tools loaded");
@@ -81100,14 +81647,14 @@ var init_xmlBridge = __esm({
81100
81647
  console.error(`[MCP DEBUG] Executing MCP tool: ${toolName}`);
81101
81648
  console.error(`[MCP DEBUG] Parameters:`, JSON.stringify(params, null, 2));
81102
81649
  }
81103
- const tool3 = this.mcpTools[toolName];
81104
- if (!tool3) {
81650
+ const tool4 = this.mcpTools[toolName];
81651
+ if (!tool4) {
81105
81652
  console.error(`[MCP ERROR] Unknown MCP tool: ${toolName}`);
81106
81653
  console.error(`[MCP ERROR] Available tools: ${this.getToolNames().join(", ")}`);
81107
81654
  throw new Error(`Unknown MCP tool: ${toolName}`);
81108
81655
  }
81109
81656
  try {
81110
- const result = await tool3.execute(params);
81657
+ const result = await tool4.execute(params);
81111
81658
  if (this.debug) {
81112
81659
  console.error(`[MCP DEBUG] Tool ${toolName} executed successfully`);
81113
81660
  }
@@ -81161,26 +81708,640 @@ var init_mcp = __esm({
81161
81708
  }
81162
81709
  });
81163
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
+
81164
82325
  // src/agent/ProbeAgent.js
81165
82326
  var ProbeAgent_exports = {};
81166
82327
  __export(ProbeAgent_exports, {
81167
82328
  ProbeAgent: () => ProbeAgent
81168
82329
  });
81169
82330
  module.exports = __toCommonJS(ProbeAgent_exports);
81170
- 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;
81171
82332
  var init_ProbeAgent = __esm({
81172
82333
  "src/agent/ProbeAgent.js"() {
81173
82334
  import_dotenv2 = __toESM(require_main(), 1);
81174
- import_anthropic = require("@ai-sdk/anthropic");
81175
- import_openai = require("@ai-sdk/openai");
81176
- 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");
81177
82338
  init_dist3();
81178
- import_ai3 = require("ai");
82339
+ import_ai4 = require("ai");
81179
82340
  import_crypto5 = require("crypto");
81180
82341
  import_events2 = require("events");
81181
- import_fs8 = require("fs");
82342
+ import_fs10 = require("fs");
81182
82343
  import_promises2 = require("fs/promises");
81183
- import_path10 = require("path");
82344
+ import_path11 = require("path");
81184
82345
  init_tokenCounter();
81185
82346
  init_InMemoryStorageAdapter();
81186
82347
  init_HookManager();
@@ -81193,8 +82354,17 @@ var init_ProbeAgent = __esm({
81193
82354
  init_schemaUtils();
81194
82355
  init_xmlParsingUtils();
81195
82356
  init_mcp();
82357
+ init_RetryManager();
82358
+ init_FallbackManager();
81196
82359
  import_dotenv2.default.config();
81197
- 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
+ })();
81198
82368
  MAX_HISTORY_MESSAGES = 100;
81199
82369
  MAX_IMAGE_FILE_SIZE = 20 * 1024 * 1024;
81200
82370
  ProbeAgent = class _ProbeAgent {
@@ -81221,6 +82391,18 @@ var init_ProbeAgent = __esm({
81221
82391
  * @param {Array} [options.mcpServers] - Deprecated, use mcpConfig instead
81222
82392
  * @param {Object} [options.storageAdapter] - Custom storage adapter for history management
81223
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
81224
82406
  */
81225
82407
  constructor(options = {}) {
81226
82408
  this.sessionId = options.sessionId || (0, import_crypto5.randomUUID)();
@@ -81232,7 +82414,13 @@ var init_ProbeAgent = __esm({
81232
82414
  this.cancelled = false;
81233
82415
  this.tracer = options.tracer || null;
81234
82416
  this.outline = !!options.outline;
81235
- 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
+ })();
81236
82424
  this.maxIterations = options.maxIterations || null;
81237
82425
  this.disableMermaidValidation = !!options.disableMermaidValidation;
81238
82426
  this.disableJsonValidation = !!options.disableJsonValidation;
@@ -81273,6 +82461,10 @@ var init_ProbeAgent = __esm({
81273
82461
  this.mcpServers = options.mcpServers || null;
81274
82462
  this.mcpBridge = null;
81275
82463
  this._mcpInitialized = false;
82464
+ this.retryConfig = options.retry || {};
82465
+ this.retryManager = null;
82466
+ this.fallbackConfig = options.fallback || null;
82467
+ this.fallbackManager = null;
81276
82468
  this.initializeModel();
81277
82469
  }
81278
82470
  /**
@@ -81357,6 +82549,14 @@ var init_ProbeAgent = __esm({
81357
82549
  if (this.enableBash && wrappedTools.bashToolInstance) {
81358
82550
  this.toolImplementations.bash = wrappedTools.bashToolInstance;
81359
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
+ }
81360
82560
  this.wrappedTools = wrappedTools;
81361
82561
  if (this.debug) {
81362
82562
  console.error("\n[DEBUG] ========================================");
@@ -81407,36 +82607,147 @@ var init_ProbeAgent = __esm({
81407
82607
  if (forceProvider) {
81408
82608
  if (forceProvider === "anthropic" && anthropicApiKey) {
81409
82609
  this.initializeAnthropicModel(anthropicApiKey, anthropicApiUrl, modelName);
82610
+ this.initializeFallbackManager(forceProvider, modelName);
81410
82611
  return;
81411
82612
  } else if (forceProvider === "openai" && openaiApiKey) {
81412
82613
  this.initializeOpenAIModel(openaiApiKey, openaiApiUrl, modelName);
82614
+ this.initializeFallbackManager(forceProvider, modelName);
81413
82615
  return;
81414
82616
  } else if (forceProvider === "google" && googleApiKey) {
81415
82617
  this.initializeGoogleModel(googleApiKey, googleApiUrl, modelName);
82618
+ this.initializeFallbackManager(forceProvider, modelName);
81416
82619
  return;
81417
82620
  } else if (forceProvider === "bedrock" && (awsAccessKeyId && awsSecretAccessKey && awsRegion || awsApiKey)) {
81418
82621
  this.initializeBedrockModel(awsAccessKeyId, awsSecretAccessKey, awsRegion, awsSessionToken, awsApiKey, awsBedrockBaseUrl, modelName);
82622
+ this.initializeFallbackManager(forceProvider, modelName);
81419
82623
  return;
81420
82624
  }
81421
82625
  console.warn(`WARNING: Forced provider "${forceProvider}" selected but required API key is missing or invalid! Falling back to auto-detection.`);
81422
82626
  }
81423
82627
  if (anthropicApiKey) {
81424
82628
  this.initializeAnthropicModel(anthropicApiKey, anthropicApiUrl, modelName);
82629
+ this.initializeFallbackManager("anthropic", modelName);
81425
82630
  } else if (openaiApiKey) {
81426
82631
  this.initializeOpenAIModel(openaiApiKey, openaiApiUrl, modelName);
82632
+ this.initializeFallbackManager("openai", modelName);
81427
82633
  } else if (googleApiKey) {
81428
82634
  this.initializeGoogleModel(googleApiKey, googleApiUrl, modelName);
82635
+ this.initializeFallbackManager("google", modelName);
81429
82636
  } else if (awsAccessKeyId && awsSecretAccessKey && awsRegion || awsApiKey) {
81430
82637
  this.initializeBedrockModel(awsAccessKeyId, awsSecretAccessKey, awsRegion, awsSessionToken, awsApiKey, awsBedrockBaseUrl, modelName);
82638
+ this.initializeFallbackManager("bedrock", modelName);
81431
82639
  } else {
81432
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.");
81433
82641
  }
81434
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
+ }
81435
82746
  /**
81436
82747
  * Initialize Anthropic model
81437
82748
  */
81438
82749
  initializeAnthropicModel(apiKey, apiUrl, modelName) {
81439
- this.provider = (0, import_anthropic.createAnthropic)({
82750
+ this.provider = (0, import_anthropic2.createAnthropic)({
81440
82751
  apiKey,
81441
82752
  ...apiUrl && { baseURL: apiUrl }
81442
82753
  });
@@ -81450,7 +82761,7 @@ var init_ProbeAgent = __esm({
81450
82761
  * Initialize OpenAI model
81451
82762
  */
81452
82763
  initializeOpenAIModel(apiKey, apiUrl, modelName) {
81453
- this.provider = (0, import_openai.createOpenAI)({
82764
+ this.provider = (0, import_openai2.createOpenAI)({
81454
82765
  compatibility: "strict",
81455
82766
  apiKey,
81456
82767
  ...apiUrl && { baseURL: apiUrl }
@@ -81465,7 +82776,7 @@ var init_ProbeAgent = __esm({
81465
82776
  * Initialize Google model
81466
82777
  */
81467
82778
  initializeGoogleModel(apiKey, apiUrl, modelName) {
81468
- this.provider = (0, import_google.createGoogleGenerativeAI)({
82779
+ this.provider = (0, import_google2.createGoogleGenerativeAI)({
81469
82780
  apiKey,
81470
82781
  ...apiUrl && { baseURL: apiUrl }
81471
82782
  });
@@ -81540,7 +82851,7 @@ var init_ProbeAgent = __esm({
81540
82851
  let resolvedPath2 = imagePath;
81541
82852
  if (!imagePath.includes("/") && !imagePath.includes("\\")) {
81542
82853
  for (const dir of listFilesDirectories) {
81543
- const potentialPath = (0, import_path10.resolve)(dir, imagePath);
82854
+ const potentialPath = (0, import_path11.resolve)(dir, imagePath);
81544
82855
  const loaded = await this.loadImageIfValid(potentialPath);
81545
82856
  if (loaded) {
81546
82857
  if (this.debug) {
@@ -81565,7 +82876,7 @@ var init_ProbeAgent = __esm({
81565
82876
  let match2;
81566
82877
  while ((match2 = fileHeaderPattern.exec(content)) !== null) {
81567
82878
  const filePath = match2[1].trim();
81568
- const dir = (0, import_path10.dirname)(filePath);
82879
+ const dir = (0, import_path11.dirname)(filePath);
81569
82880
  if (dir && dir !== ".") {
81570
82881
  directories.push(dir);
81571
82882
  if (this.debug) {
@@ -81609,21 +82920,21 @@ var init_ProbeAgent = __esm({
81609
82920
  }
81610
82921
  const allowedDirs = this.allowedFolders && this.allowedFolders.length > 0 ? this.allowedFolders : [process.cwd()];
81611
82922
  let absolutePath;
81612
- let isPathAllowed = false;
81613
- if ((0, import_path10.isAbsolute)(imagePath)) {
82923
+ let isPathAllowed2 = false;
82924
+ if ((0, import_path11.isAbsolute)(imagePath)) {
81614
82925
  absolutePath = imagePath;
81615
- isPathAllowed = allowedDirs.some((dir) => absolutePath.startsWith((0, import_path10.resolve)(dir)));
82926
+ isPathAllowed2 = allowedDirs.some((dir) => absolutePath.startsWith((0, import_path11.resolve)(dir)));
81616
82927
  } else {
81617
82928
  for (const dir of allowedDirs) {
81618
- const resolvedPath2 = (0, import_path10.resolve)(dir, imagePath);
81619
- 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))) {
81620
82931
  absolutePath = resolvedPath2;
81621
- isPathAllowed = true;
82932
+ isPathAllowed2 = true;
81622
82933
  break;
81623
82934
  }
81624
82935
  }
81625
82936
  }
81626
- if (!isPathAllowed) {
82937
+ if (!isPathAllowed2) {
81627
82938
  if (this.debug) {
81628
82939
  console.log(`[DEBUG] Image path outside allowed directories: ${imagePath}`);
81629
82940
  }
@@ -81822,6 +83133,14 @@ ${attemptCompletionToolDefinition}
81822
83133
  `;
81823
83134
  if (this.allowEdit) {
81824
83135
  toolDefinitions += `${implementToolDefinition}
83136
+ `;
83137
+ toolDefinitions += `${editToolDefinition}
83138
+ `;
83139
+ toolDefinitions += `${createToolDefinition}
83140
+ `;
83141
+ }
83142
+ if (this.enableBash) {
83143
+ toolDefinitions += `${bashToolDefinition}
81825
83144
  `;
81826
83145
  }
81827
83146
  if (this.enableDelegate) {
@@ -81889,7 +83208,7 @@ Available Tools:
81889
83208
  - extract: Extract specific code blocks or lines from files.
81890
83209
  - listFiles: List files and directories in a specified location.
81891
83210
  - searchFiles: Find files matching a glob pattern with recursive search capability.
81892
- ${this.allowEdit ? "- implement: Implement a feature or fix a bug using aider.\n" : ""}${this.enableDelegate ? "- delegate: Delegate big distinct tasks to specialized probe subagents.\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" : ""}
81893
83212
  - attempt_completion: Finalize the task and provide the result to the user.
81894
83213
  - attempt_complete: Quick completion using previous response (shorthand).
81895
83214
  `;
@@ -81903,7 +83222,10 @@ Follow these instructions carefully:
81903
83222
  6. You MUST respond with exactly ONE tool call per message, using the specified XML format, until the task is complete.
81904
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.
81905
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.
81906
- 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` : ""}
81907
83229
  </instructions>
81908
83230
  `;
81909
83231
  const predefinedPrompts = {
@@ -82155,7 +83477,7 @@ You are working with a repository located at: ${searchDirectory}
82155
83477
  try {
82156
83478
  const executeAIRequest = async () => {
82157
83479
  const messagesForAI = this.prepareMessagesWithImages(currentMessages);
82158
- const result = await (0, import_ai3.streamText)({
83480
+ const result = await this.streamTextWithRetryAndFallback({
82159
83481
  model: this.provider(this.model),
82160
83482
  messages: messagesForAI,
82161
83483
  maxTokens: maxResponseTokens,
@@ -82207,7 +83529,10 @@ You are working with a repository located at: ${searchDirectory}
82207
83529
  "attempt_completion"
82208
83530
  ];
82209
83531
  if (this.allowEdit) {
82210
- validTools.push("implement");
83532
+ validTools.push("implement", "edit", "create");
83533
+ }
83534
+ if (this.enableBash) {
83535
+ validTools.push("bash");
82211
83536
  }
82212
83537
  if (this.enableDelegate) {
82213
83538
  validTools.push("delegate");