@probelabs/probe 0.6.0-rc226 → 0.6.0-rc227

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cjs/index.cjs CHANGED
@@ -16079,8 +16079,45 @@ var require_dist_cjs29 = __commonJS({
16079
16079
  }
16080
16080
  });
16081
16081
 
16082
- // node_modules/@aws-crypto/util/node_modules/@smithy/is-array-buffer/dist-cjs/index.js
16082
+ // node_modules/@aws-sdk/util-format-url/dist-cjs/index.js
16083
16083
  var require_dist_cjs30 = __commonJS({
16084
+ "node_modules/@aws-sdk/util-format-url/dist-cjs/index.js"(exports2) {
16085
+ "use strict";
16086
+ var querystringBuilder = require_dist_cjs14();
16087
+ function formatUrl(request) {
16088
+ const { port, query: query2 } = request;
16089
+ let { protocol, path: path9, hostname } = request;
16090
+ if (protocol && protocol.slice(-1) !== ":") {
16091
+ protocol += ":";
16092
+ }
16093
+ if (port) {
16094
+ hostname += `:${port}`;
16095
+ }
16096
+ if (path9 && path9.charAt(0) !== "/") {
16097
+ path9 = `/${path9}`;
16098
+ }
16099
+ let queryString = query2 ? querystringBuilder.buildQueryString(query2) : "";
16100
+ if (queryString && queryString[0] !== "?") {
16101
+ queryString = `?${queryString}`;
16102
+ }
16103
+ let auth = "";
16104
+ if (request.username != null || request.password != null) {
16105
+ const username = request.username ?? "";
16106
+ const password = request.password ?? "";
16107
+ auth = `${username}:${password}@`;
16108
+ }
16109
+ let fragment = "";
16110
+ if (request.fragment) {
16111
+ fragment = `#${request.fragment}`;
16112
+ }
16113
+ return `${protocol}//${auth}${hostname}${path9}${queryString}${fragment}`;
16114
+ }
16115
+ exports2.formatUrl = formatUrl;
16116
+ }
16117
+ });
16118
+
16119
+ // node_modules/@aws-crypto/util/node_modules/@smithy/is-array-buffer/dist-cjs/index.js
16120
+ var require_dist_cjs31 = __commonJS({
16084
16121
  "node_modules/@aws-crypto/util/node_modules/@smithy/is-array-buffer/dist-cjs/index.js"(exports2, module2) {
16085
16122
  var __defProp2 = Object.defineProperty;
16086
16123
  var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
@@ -16110,7 +16147,7 @@ var require_dist_cjs30 = __commonJS({
16110
16147
  });
16111
16148
 
16112
16149
  // node_modules/@aws-crypto/util/node_modules/@smithy/util-buffer-from/dist-cjs/index.js
16113
- var require_dist_cjs31 = __commonJS({
16150
+ var require_dist_cjs32 = __commonJS({
16114
16151
  "node_modules/@aws-crypto/util/node_modules/@smithy/util-buffer-from/dist-cjs/index.js"(exports2, module2) {
16115
16152
  var __defProp2 = Object.defineProperty;
16116
16153
  var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
@@ -16136,7 +16173,7 @@ var require_dist_cjs31 = __commonJS({
16136
16173
  fromString: () => fromString
16137
16174
  });
16138
16175
  module2.exports = __toCommonJS2(src_exports);
16139
- var import_is_array_buffer = require_dist_cjs30();
16176
+ var import_is_array_buffer = require_dist_cjs31();
16140
16177
  var import_buffer = require("buffer");
16141
16178
  var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => {
16142
16179
  if (!(0, import_is_array_buffer.isArrayBuffer)(input)) {
@@ -16154,7 +16191,7 @@ var require_dist_cjs31 = __commonJS({
16154
16191
  });
16155
16192
 
16156
16193
  // node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-cjs/index.js
16157
- var require_dist_cjs32 = __commonJS({
16194
+ var require_dist_cjs33 = __commonJS({
16158
16195
  "node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-cjs/index.js"(exports2, module2) {
16159
16196
  var __defProp2 = Object.defineProperty;
16160
16197
  var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
@@ -16181,7 +16218,7 @@ var require_dist_cjs32 = __commonJS({
16181
16218
  toUtf8: () => toUtf811
16182
16219
  });
16183
16220
  module2.exports = __toCommonJS2(src_exports);
16184
- var import_util_buffer_from = require_dist_cjs31();
16221
+ var import_util_buffer_from = require_dist_cjs32();
16185
16222
  var fromUtf88 = /* @__PURE__ */ __name((input) => {
16186
16223
  const buf = (0, import_util_buffer_from.fromString)(input, "utf8");
16187
16224
  return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT);
@@ -16213,7 +16250,7 @@ var require_convertToBuffer = __commonJS({
16213
16250
  "use strict";
16214
16251
  Object.defineProperty(exports2, "__esModule", { value: true });
16215
16252
  exports2.convertToBuffer = void 0;
16216
- var util_utf8_1 = require_dist_cjs32();
16253
+ var util_utf8_1 = require_dist_cjs33();
16217
16254
  var fromUtf88 = typeof Buffer !== "undefined" && Buffer.from ? function(input) {
16218
16255
  return Buffer.from(input, "utf8");
16219
16256
  } : util_utf8_1.fromUtf8;
@@ -16660,7 +16697,7 @@ var require_main3 = __commonJS({
16660
16697
  });
16661
16698
 
16662
16699
  // node_modules/@smithy/eventstream-codec/dist-cjs/index.js
16663
- var require_dist_cjs33 = __commonJS({
16700
+ var require_dist_cjs34 = __commonJS({
16664
16701
  "node_modules/@smithy/eventstream-codec/dist-cjs/index.js"(exports2) {
16665
16702
  "use strict";
16666
16703
  var crc32 = require_main3();
@@ -17043,48 +17080,11 @@ var require_dist_cjs33 = __commonJS({
17043
17080
  }
17044
17081
  });
17045
17082
 
17046
- // node_modules/@aws-sdk/util-format-url/dist-cjs/index.js
17047
- var require_dist_cjs34 = __commonJS({
17048
- "node_modules/@aws-sdk/util-format-url/dist-cjs/index.js"(exports2) {
17049
- "use strict";
17050
- var querystringBuilder = require_dist_cjs14();
17051
- function formatUrl(request) {
17052
- const { port, query: query2 } = request;
17053
- let { protocol, path: path9, hostname } = request;
17054
- if (protocol && protocol.slice(-1) !== ":") {
17055
- protocol += ":";
17056
- }
17057
- if (port) {
17058
- hostname += `:${port}`;
17059
- }
17060
- if (path9 && path9.charAt(0) !== "/") {
17061
- path9 = `/${path9}`;
17062
- }
17063
- let queryString = query2 ? querystringBuilder.buildQueryString(query2) : "";
17064
- if (queryString && queryString[0] !== "?") {
17065
- queryString = `?${queryString}`;
17066
- }
17067
- let auth = "";
17068
- if (request.username != null || request.password != null) {
17069
- const username = request.username ?? "";
17070
- const password = request.password ?? "";
17071
- auth = `${username}:${password}@`;
17072
- }
17073
- let fragment = "";
17074
- if (request.fragment) {
17075
- fragment = `#${request.fragment}`;
17076
- }
17077
- return `${protocol}//${auth}${hostname}${path9}${queryString}${fragment}`;
17078
- }
17079
- exports2.formatUrl = formatUrl;
17080
- }
17081
- });
17082
-
17083
17083
  // node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js
17084
17084
  var require_dist_cjs35 = __commonJS({
17085
17085
  "node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js"(exports2) {
17086
17086
  "use strict";
17087
- var eventstreamCodec = require_dist_cjs33();
17087
+ var eventstreamCodec = require_dist_cjs34();
17088
17088
  function getChunkedStream(source) {
17089
17089
  let currentMessageTotalLength = 0;
17090
17090
  let currentMessagePendingLength = 0;
@@ -17269,183 +17269,20 @@ var require_dist_cjs36 = __commonJS({
17269
17269
  var require_dist_cjs37 = __commonJS({
17270
17270
  "node_modules/@aws-sdk/middleware-websocket/dist-cjs/index.js"(exports2) {
17271
17271
  "use strict";
17272
- var eventstreamCodec = require_dist_cjs33();
17273
- var utilHexEncoding = require_dist_cjs17();
17274
- var protocolHttp = require_dist_cjs2();
17275
- var utilFormatUrl = require_dist_cjs34();
17272
+ var utilFormatUrl = require_dist_cjs30();
17276
17273
  var eventstreamSerdeBrowser = require_dist_cjs36();
17277
17274
  var fetchHttpHandler = require_dist_cjs16();
17278
- var getEventSigningTransformStream = (initialSignature, messageSigner, eventStreamCodec, systemClockOffsetProvider) => {
17279
- let priorSignature = initialSignature;
17280
- const transformer = {
17281
- start() {
17282
- },
17283
- async transform(chunk, controller) {
17284
- try {
17285
- const now = new Date(Date.now() + await systemClockOffsetProvider());
17286
- const dateHeader = {
17287
- ":date": { type: "timestamp", value: now }
17288
- };
17289
- const signedMessage = await messageSigner.sign({
17290
- message: {
17291
- body: chunk,
17292
- headers: dateHeader
17293
- },
17294
- priorSignature
17295
- }, {
17296
- signingDate: now
17297
- });
17298
- priorSignature = signedMessage.signature;
17299
- const serializedSigned = eventStreamCodec.encode({
17300
- headers: {
17301
- ...dateHeader,
17302
- ":chunk-signature": {
17303
- type: "binary",
17304
- value: utilHexEncoding.fromHex(signedMessage.signature)
17305
- }
17306
- },
17307
- body: chunk
17308
- });
17309
- controller.enqueue(serializedSigned);
17310
- } catch (error2) {
17311
- controller.error(error2);
17312
- }
17313
- }
17314
- };
17315
- return new TransformStream({ ...transformer });
17316
- };
17317
- var EventStreamPayloadHandler = class {
17318
- messageSigner;
17319
- eventStreamCodec;
17320
- systemClockOffsetProvider;
17321
- constructor(options) {
17322
- this.messageSigner = options.messageSigner;
17323
- this.eventStreamCodec = new eventstreamCodec.EventStreamCodec(options.utf8Encoder, options.utf8Decoder);
17324
- this.systemClockOffsetProvider = async () => options.systemClockOffset ?? 0;
17325
- }
17326
- async handle(next, args, context = {}) {
17327
- const request = args.request;
17328
- const { body: payload2, headers, query: query2 } = request;
17329
- if (!(payload2 instanceof ReadableStream)) {
17330
- throw new Error("Eventstream payload must be a ReadableStream.");
17331
- }
17332
- const placeHolderStream = new TransformStream();
17333
- request.body = placeHolderStream.readable;
17334
- const match2 = (headers?.authorization ?? "").match(/Signature=(\w+)$/);
17335
- const priorSignature = (match2 ?? [])[1] ?? (query2 && query2["X-Amz-Signature"]) ?? "";
17336
- const signingStream = getEventSigningTransformStream(priorSignature, await this.messageSigner(), this.eventStreamCodec, this.systemClockOffsetProvider);
17337
- payload2.pipeThrough(signingStream).pipeThrough(placeHolderStream);
17338
- let result;
17339
- try {
17340
- result = await next(args);
17341
- } catch (e5) {
17342
- const p5 = payload2.cancel?.();
17343
- if (p5 instanceof Promise) {
17344
- p5.catch(() => {
17345
- });
17346
- }
17347
- throw e5;
17348
- }
17349
- return result;
17350
- }
17351
- };
17352
- var eventStreamPayloadHandlerProvider = (options) => new EventStreamPayloadHandler(options);
17353
- var injectSessionIdMiddleware = () => (next) => async (args) => {
17354
- const requestParams = {
17355
- ...args.input
17356
- };
17357
- const response = await next(args);
17358
- const output = response.output;
17359
- if (requestParams.SessionId && output.SessionId == null) {
17360
- output.SessionId = requestParams.SessionId;
17361
- }
17362
- return response;
17363
- };
17364
- var injectSessionIdMiddlewareOptions = {
17365
- step: "initialize",
17366
- name: "injectSessionIdMiddleware",
17367
- tags: ["WEBSOCKET", "EVENT_STREAM"],
17368
- override: true
17369
- };
17370
- var websocketEndpointMiddleware = (config, options) => (next) => (args) => {
17371
- const { request } = args;
17372
- if (protocolHttp.HttpRequest.isInstance(request) && config.requestHandler.metadata?.handlerProtocol?.toLowerCase().includes("websocket")) {
17373
- request.protocol = "wss:";
17374
- request.method = "GET";
17375
- request.path = `${request.path}-websocket`;
17376
- const { headers } = request;
17377
- delete headers["content-type"];
17378
- delete headers["x-amz-content-sha256"];
17379
- for (const name14 of Object.keys(headers)) {
17380
- if (name14.indexOf(options.headerPrefix) === 0) {
17381
- const chunkedName = name14.replace(options.headerPrefix, "");
17382
- request.query[chunkedName] = headers[name14];
17383
- }
17384
- }
17385
- if (headers["x-amz-user-agent"]) {
17386
- request.query["user-agent"] = headers["x-amz-user-agent"];
17387
- }
17388
- request.headers = { host: headers.host ?? request.hostname };
17389
- }
17390
- return next(args);
17391
- };
17392
- var websocketEndpointMiddlewareOptions = {
17393
- name: "websocketEndpointMiddleware",
17394
- tags: ["WEBSOCKET", "EVENT_STREAM"],
17395
- relation: "after",
17396
- toMiddleware: "eventStreamHeaderMiddleware",
17397
- override: true
17398
- };
17399
- var getWebSocketPlugin = (config, options) => ({
17400
- applyToStack: (clientStack) => {
17401
- clientStack.addRelativeTo(websocketEndpointMiddleware(config, options), websocketEndpointMiddlewareOptions);
17402
- clientStack.add(injectSessionIdMiddleware(), injectSessionIdMiddlewareOptions);
17403
- }
17404
- });
17275
+ var protocolHttp = require_dist_cjs2();
17276
+ var utilBase64 = require_dist_cjs12();
17277
+ var eventstreamCodec = require_dist_cjs34();
17278
+ var utilHexEncoding = require_dist_cjs17();
17405
17279
  var isWebSocketRequest = (request) => request.protocol === "ws:" || request.protocol === "wss:";
17406
- var WebsocketSignatureV4 = class {
17407
- signer;
17408
- constructor(options) {
17409
- this.signer = options.signer;
17410
- }
17411
- presign(originalRequest, options = {}) {
17412
- return this.signer.presign(originalRequest, options);
17413
- }
17414
- async sign(toSign, options) {
17415
- if (protocolHttp.HttpRequest.isInstance(toSign) && isWebSocketRequest(toSign)) {
17416
- const signedRequest = await this.signer.presign({ ...toSign, body: "" }, {
17417
- ...options,
17418
- expiresIn: 60,
17419
- unsignableHeaders: new Set(Object.keys(toSign.headers).filter((header) => header !== "host"))
17420
- });
17421
- return {
17422
- ...signedRequest,
17423
- body: toSign.body
17424
- };
17425
- } else {
17426
- return this.signer.sign(toSign, options);
17427
- }
17428
- }
17429
- };
17430
- var resolveWebSocketConfig = (input) => {
17431
- const { signer } = input;
17432
- return Object.assign(input, {
17433
- signer: async (authScheme) => {
17434
- const signerObj = await signer(authScheme);
17435
- if (validateSigner(signerObj)) {
17436
- return new WebsocketSignatureV4({ signer: signerObj });
17437
- }
17438
- throw new Error("Expected WebsocketSignatureV4 signer, please check the client constructor.");
17439
- }
17440
- });
17441
- };
17442
- var validateSigner = (signer) => !!signer;
17443
- var DEFAULT_WS_CONNECTION_TIMEOUT_MS = 2e3;
17280
+ var DEFAULT_WS_CONNECTION_TIMEOUT_MS = 3e3;
17444
17281
  var WebSocketFetchHandler = class _WebSocketFetchHandler {
17445
17282
  metadata = {
17446
17283
  handlerProtocol: "websocket/h1.1"
17447
17284
  };
17448
- config;
17285
+ config = {};
17449
17286
  configPromise;
17450
17287
  httpHandler;
17451
17288
  sockets = {};
@@ -17457,12 +17294,19 @@ var require_dist_cjs37 = __commonJS({
17457
17294
  }
17458
17295
  constructor(options, httpHandler = new fetchHttpHandler.FetchHttpHandler()) {
17459
17296
  this.httpHandler = httpHandler;
17297
+ const setConfig = (opts) => {
17298
+ this.config = {
17299
+ ...opts ?? {}
17300
+ };
17301
+ return this.config;
17302
+ };
17460
17303
  if (typeof options === "function") {
17461
17304
  this.config = {};
17462
- this.configPromise = options().then((opts) => this.config = opts ?? {});
17305
+ this.configPromise = options().then((opts) => {
17306
+ return setConfig(opts);
17307
+ });
17463
17308
  } else {
17464
- this.config = options ?? {};
17465
- this.configPromise = Promise.resolve(this.config);
17309
+ this.configPromise = Promise.resolve(setConfig(options));
17466
17310
  }
17467
17311
  }
17468
17312
  destroy() {
@@ -17474,17 +17318,20 @@ var require_dist_cjs37 = __commonJS({
17474
17318
  }
17475
17319
  }
17476
17320
  async handle(request) {
17321
+ this.config = await this.configPromise;
17322
+ const { logger: logger2 } = this.config;
17477
17323
  if (!isWebSocketRequest(request)) {
17324
+ logger2?.debug?.(`@aws-sdk - ws fetching ${request.protocol}${request.hostname}${request.path}`);
17478
17325
  return this.httpHandler.handle(request);
17479
17326
  }
17480
17327
  const url = utilFormatUrl.formatUrl(request);
17328
+ logger2?.debug?.(`@aws-sdk - ws connecting ${url.split("?")[0]}`);
17481
17329
  const socket = new WebSocket(url);
17482
17330
  if (!this.sockets[url]) {
17483
17331
  this.sockets[url] = [];
17484
17332
  }
17485
17333
  this.sockets[url].push(socket);
17486
17334
  socket.binaryType = "arraybuffer";
17487
- this.config = await this.configPromise;
17488
17335
  const { connectionTimeout = DEFAULT_WS_CONNECTION_TIMEOUT_MS } = this.config;
17489
17336
  await this.waitForReady(socket, connectionTimeout);
17490
17337
  const { body } = request;
@@ -17516,7 +17363,8 @@ var require_dist_cjs37 = __commonJS({
17516
17363
  this.removeNotUsableSockets(socket.url);
17517
17364
  reject2({
17518
17365
  $metadata: {
17519
- httpStatusCode: 500
17366
+ httpStatusCode: 500,
17367
+ websocketSynthetic500Error: true
17520
17368
  }
17521
17369
  });
17522
17370
  }, connectionTimeout);
@@ -17527,42 +17375,57 @@ var require_dist_cjs37 = __commonJS({
17527
17375
  });
17528
17376
  }
17529
17377
  connect(socket, data2) {
17530
- let streamError = void 0;
17531
- let socketErrorOccurred = false;
17532
- let reject2 = () => {
17533
- };
17534
- let resolve7 = () => {
17378
+ const messageQueue = [];
17379
+ let pendingResolve = null;
17380
+ let pendingReject = null;
17381
+ const push = (item) => {
17382
+ if (pendingResolve) {
17383
+ if (item.error) {
17384
+ pendingReject(item.error);
17385
+ } else {
17386
+ pendingResolve({ done: item.done, value: item.value });
17387
+ }
17388
+ pendingResolve = null;
17389
+ pendingReject = null;
17390
+ } else {
17391
+ messageQueue.push(item);
17392
+ }
17535
17393
  };
17536
17394
  socket.onmessage = (event) => {
17537
- resolve7({
17538
- done: false,
17539
- value: new Uint8Array(event.data)
17540
- });
17395
+ const { data: data3 } = event;
17396
+ if (typeof data3 === "string") {
17397
+ push({
17398
+ done: false,
17399
+ value: utilBase64.fromBase64(data3)
17400
+ });
17401
+ } else {
17402
+ push({
17403
+ done: false,
17404
+ value: new Uint8Array(data3)
17405
+ });
17406
+ }
17541
17407
  };
17542
- socket.onerror = (error2) => {
17543
- socketErrorOccurred = true;
17408
+ socket.onerror = (event) => {
17544
17409
  socket.close();
17545
- reject2(error2);
17410
+ push({ done: true, error: event });
17546
17411
  };
17547
17412
  socket.onclose = () => {
17548
17413
  this.removeNotUsableSockets(socket.url);
17549
- if (socketErrorOccurred)
17550
- return;
17551
- if (streamError) {
17552
- reject2(streamError);
17553
- } else {
17554
- resolve7({
17555
- done: true,
17556
- value: void 0
17557
- });
17558
- }
17414
+ push({ done: true });
17559
17415
  };
17560
17416
  const outputStream = {
17561
17417
  [Symbol.asyncIterator]: () => ({
17562
- next: () => {
17563
- return new Promise((_resolve, _reject) => {
17564
- resolve7 = _resolve;
17565
- reject2 = _reject;
17418
+ async next() {
17419
+ if (messageQueue.length > 0) {
17420
+ const item = messageQueue.shift();
17421
+ if (item.error) {
17422
+ throw item.error;
17423
+ }
17424
+ return { done: item.done, value: item.value };
17425
+ }
17426
+ return new Promise((resolve7, reject2) => {
17427
+ pendingResolve = resolve7;
17428
+ pendingReject = reject2;
17566
17429
  });
17567
17430
  }
17568
17431
  })
@@ -17577,7 +17440,10 @@ var require_dist_cjs37 = __commonJS({
17577
17440
  }
17578
17441
  }
17579
17442
  } catch (err) {
17580
- streamError = err;
17443
+ push({
17444
+ done: true,
17445
+ error: err
17446
+ });
17581
17447
  } finally {
17582
17448
  socket.close(1e3);
17583
17449
  }
@@ -17601,6 +17467,174 @@ var require_dist_cjs37 = __commonJS({
17601
17467
  };
17602
17468
  var toReadableStream = (asyncIterable) => typeof ReadableStream === "function" ? eventstreamSerdeBrowser.iterableToReadableStream(asyncIterable) : asyncIterable;
17603
17469
  var isReadableStream = (payload2) => typeof ReadableStream === "function" && payload2 instanceof ReadableStream;
17470
+ var websocketEndpointMiddleware = (config, options) => (next) => (args) => {
17471
+ const { request } = args;
17472
+ if (protocolHttp.HttpRequest.isInstance(request) && config.requestHandler.metadata?.handlerProtocol?.toLowerCase().includes("websocket")) {
17473
+ request.protocol = "wss:";
17474
+ request.method = "GET";
17475
+ request.path = `${request.path}-websocket`;
17476
+ const { headers } = request;
17477
+ delete headers["content-type"];
17478
+ delete headers["x-amz-content-sha256"];
17479
+ for (const name14 of Object.keys(headers)) {
17480
+ if (name14.indexOf(options.headerPrefix) === 0) {
17481
+ const chunkedName = name14.replace(options.headerPrefix, "");
17482
+ request.query[chunkedName] = headers[name14];
17483
+ }
17484
+ }
17485
+ if (headers["x-amz-user-agent"]) {
17486
+ request.query["user-agent"] = headers["x-amz-user-agent"];
17487
+ }
17488
+ request.headers = { host: headers.host ?? request.hostname };
17489
+ }
17490
+ return next(args);
17491
+ };
17492
+ var websocketEndpointMiddlewareOptions = {
17493
+ name: "websocketEndpointMiddleware",
17494
+ tags: ["WEBSOCKET", "EVENT_STREAM"],
17495
+ relation: "after",
17496
+ toMiddleware: "eventStreamHeaderMiddleware",
17497
+ override: true
17498
+ };
17499
+ var injectSessionIdMiddleware = () => (next) => async (args) => {
17500
+ const requestParams = {
17501
+ ...args.input
17502
+ };
17503
+ const response = await next(args);
17504
+ const output = response.output;
17505
+ if (requestParams.SessionId && output.SessionId == null) {
17506
+ output.SessionId = requestParams.SessionId;
17507
+ }
17508
+ return response;
17509
+ };
17510
+ var injectSessionIdMiddlewareOptions = {
17511
+ step: "initialize",
17512
+ name: "injectSessionIdMiddleware",
17513
+ tags: ["WEBSOCKET", "EVENT_STREAM"],
17514
+ override: true
17515
+ };
17516
+ var getWebSocketPlugin = (config, options) => ({
17517
+ applyToStack: (clientStack) => {
17518
+ clientStack.addRelativeTo(websocketEndpointMiddleware(config, options), websocketEndpointMiddlewareOptions);
17519
+ clientStack.add(injectSessionIdMiddleware(), injectSessionIdMiddlewareOptions);
17520
+ }
17521
+ });
17522
+ var WebsocketSignatureV4 = class {
17523
+ signer;
17524
+ constructor(options) {
17525
+ this.signer = options.signer;
17526
+ }
17527
+ presign(originalRequest, options = {}) {
17528
+ return this.signer.presign(originalRequest, options);
17529
+ }
17530
+ async sign(toSign, options) {
17531
+ if (protocolHttp.HttpRequest.isInstance(toSign) && isWebSocketRequest(toSign)) {
17532
+ const signedRequest = await this.signer.presign({ ...toSign, body: "" }, {
17533
+ ...options,
17534
+ expiresIn: 60,
17535
+ unsignableHeaders: new Set(Object.keys(toSign.headers).filter((header) => header !== "host"))
17536
+ });
17537
+ return {
17538
+ ...signedRequest,
17539
+ body: toSign.body
17540
+ };
17541
+ } else {
17542
+ return this.signer.sign(toSign, options);
17543
+ }
17544
+ }
17545
+ signMessage(message, args) {
17546
+ return this.signer.signMessage(message, args);
17547
+ }
17548
+ };
17549
+ var resolveWebSocketConfig = (input) => {
17550
+ const { signer } = input;
17551
+ return Object.assign(input, {
17552
+ signer: async (authScheme) => {
17553
+ const signerObj = await signer(authScheme);
17554
+ if (validateSigner(signerObj)) {
17555
+ return new WebsocketSignatureV4({ signer: signerObj });
17556
+ }
17557
+ throw new Error("Expected WebsocketSignatureV4 signer, please check the client constructor.");
17558
+ }
17559
+ });
17560
+ };
17561
+ var validateSigner = (signer) => !!signer;
17562
+ var EventSigningTransformStream = class extends TransformStream {
17563
+ constructor(initialSignature, messageSigner, eventStreamCodec, systemClockOffsetProvider) {
17564
+ let priorSignature = initialSignature;
17565
+ super({
17566
+ start() {
17567
+ },
17568
+ async transform(chunk, controller) {
17569
+ try {
17570
+ const now = new Date(Date.now() + await systemClockOffsetProvider());
17571
+ const dateHeader = {
17572
+ ":date": { type: "timestamp", value: now }
17573
+ };
17574
+ const signedMessage = await messageSigner.sign({
17575
+ message: {
17576
+ body: chunk,
17577
+ headers: dateHeader
17578
+ },
17579
+ priorSignature
17580
+ }, {
17581
+ signingDate: now
17582
+ });
17583
+ priorSignature = signedMessage.signature;
17584
+ const serializedSigned = eventStreamCodec.encode({
17585
+ headers: {
17586
+ ...dateHeader,
17587
+ ":chunk-signature": {
17588
+ type: "binary",
17589
+ value: utilHexEncoding.fromHex(signedMessage.signature)
17590
+ }
17591
+ },
17592
+ body: chunk
17593
+ });
17594
+ controller.enqueue(serializedSigned);
17595
+ } catch (error2) {
17596
+ controller.error(error2);
17597
+ }
17598
+ }
17599
+ });
17600
+ }
17601
+ };
17602
+ var EventStreamPayloadHandler = class {
17603
+ messageSigner;
17604
+ eventStreamCodec;
17605
+ systemClockOffsetProvider;
17606
+ constructor(options) {
17607
+ this.messageSigner = options.messageSigner;
17608
+ this.eventStreamCodec = new eventstreamCodec.EventStreamCodec(options.utf8Encoder, options.utf8Decoder);
17609
+ this.systemClockOffsetProvider = async () => options.systemClockOffset ?? 0;
17610
+ }
17611
+ async handle(next, args, context = {}) {
17612
+ const request = args.request;
17613
+ const { body: payload2, headers, query: query2 } = request;
17614
+ if (!(payload2 instanceof ReadableStream)) {
17615
+ throw new Error("Eventstream payload must be a ReadableStream.");
17616
+ }
17617
+ const placeHolderStream = new TransformStream();
17618
+ request.body = placeHolderStream.readable;
17619
+ const match2 = (headers?.authorization ?? "").match(/Signature=(\w+)$/);
17620
+ const priorSignature = (match2 ?? [])[1] ?? (query2 && query2["X-Amz-Signature"]) ?? "";
17621
+ const signingStream = new EventSigningTransformStream(priorSignature, await this.messageSigner(), this.eventStreamCodec, this.systemClockOffsetProvider);
17622
+ payload2.pipeThrough(signingStream).pipeThrough(placeHolderStream);
17623
+ let result;
17624
+ try {
17625
+ result = await next(args);
17626
+ } catch (e5) {
17627
+ const p5 = payload2.cancel?.();
17628
+ if (p5 instanceof Promise) {
17629
+ p5.catch(() => {
17630
+ });
17631
+ }
17632
+ throw e5;
17633
+ }
17634
+ return result;
17635
+ }
17636
+ };
17637
+ var eventStreamPayloadHandlerProvider = (options) => new EventStreamPayloadHandler(options);
17604
17638
  exports2.WebSocketFetchHandler = WebSocketFetchHandler;
17605
17639
  exports2.eventStreamPayloadHandlerProvider = eventStreamPayloadHandlerProvider;
17606
17640
  exports2.getWebSocketPlugin = getWebSocketPlugin;
@@ -19248,7 +19282,7 @@ var require_package2 = __commonJS({
19248
19282
  module2.exports = {
19249
19283
  name: "@aws-sdk/client-bedrock-runtime",
19250
19284
  description: "AWS SDK for JavaScript Bedrock Runtime Client for Node.js, Browser and React Native",
19251
- version: "3.983.0",
19285
+ version: "3.984.0",
19252
19286
  scripts: {
19253
19287
  build: "concurrently 'yarn:build:types' 'yarn:build:es' && yarn build:cjs",
19254
19288
  "build:cjs": "node ../../scripts/compilation/inline client-bedrock-runtime",
@@ -19270,17 +19304,17 @@ var require_package2 = __commonJS({
19270
19304
  "@aws-crypto/sha256-js": "5.2.0",
19271
19305
  "@aws-sdk/core": "^3.973.6",
19272
19306
  "@aws-sdk/credential-provider-node": "^3.972.5",
19273
- "@aws-sdk/eventstream-handler-node": "^3.972.4",
19307
+ "@aws-sdk/eventstream-handler-node": "^3.972.5",
19274
19308
  "@aws-sdk/middleware-eventstream": "^3.972.3",
19275
19309
  "@aws-sdk/middleware-host-header": "^3.972.3",
19276
19310
  "@aws-sdk/middleware-logger": "^3.972.3",
19277
19311
  "@aws-sdk/middleware-recursion-detection": "^3.972.3",
19278
19312
  "@aws-sdk/middleware-user-agent": "^3.972.6",
19279
- "@aws-sdk/middleware-websocket": "^3.972.4",
19313
+ "@aws-sdk/middleware-websocket": "^3.972.5",
19280
19314
  "@aws-sdk/region-config-resolver": "^3.972.3",
19281
- "@aws-sdk/token-providers": "3.983.0",
19315
+ "@aws-sdk/token-providers": "3.984.0",
19282
19316
  "@aws-sdk/types": "^3.973.1",
19283
- "@aws-sdk/util-endpoints": "3.983.0",
19317
+ "@aws-sdk/util-endpoints": "3.984.0",
19284
19318
  "@aws-sdk/util-user-agent-browser": "^3.972.3",
19285
19319
  "@aws-sdk/util-user-agent-node": "^3.972.4",
19286
19320
  "@smithy/config-resolver": "^4.4.6",
@@ -25592,9 +25626,9 @@ var require_dist_cjs65 = __commonJS({
25592
25626
  var require_dist_cjs66 = __commonJS({
25593
25627
  "node_modules/@aws-sdk/eventstream-handler-node/dist-cjs/index.js"(exports2) {
25594
25628
  "use strict";
25595
- var eventstreamCodec = require_dist_cjs33();
25596
- var stream2 = require("stream");
25597
- var EventSigningStream = class extends stream2.Transform {
25629
+ var eventstreamCodec = require_dist_cjs34();
25630
+ var node_stream = require("node:stream");
25631
+ var EventSigningTransformStream = class extends node_stream.Transform {
25598
25632
  priorSignature;
25599
25633
  messageSigner;
25600
25634
  eventStreamCodec;
@@ -25660,16 +25694,16 @@ var require_dist_cjs66 = __commonJS({
25660
25694
  async handle(next, args, context = {}) {
25661
25695
  const request = args.request;
25662
25696
  const { body: payload2, query: query2 } = request;
25663
- if (!(payload2 instanceof stream2.Readable)) {
25697
+ if (!(payload2 instanceof node_stream.Readable)) {
25664
25698
  throw new Error("Eventstream payload must be a Readable stream.");
25665
25699
  }
25666
25700
  const payloadStream = payload2;
25667
- request.body = new stream2.PassThrough({
25701
+ request.body = new node_stream.PassThrough({
25668
25702
  objectMode: true
25669
25703
  });
25670
25704
  const match2 = request.headers?.authorization?.match(/Signature=([\w]+)$/);
25671
25705
  const priorSignature = match2?.[1] ?? query2?.["X-Amz-Signature"] ?? "";
25672
- const signingStream = new EventSigningStream({
25706
+ const signingStream = new EventSigningTransformStream({
25673
25707
  priorSignature,
25674
25708
  eventStreamCodec: this.eventStreamCodec,
25675
25709
  messageSigner: await this.messageSigner(),
@@ -25678,7 +25712,7 @@ var require_dist_cjs66 = __commonJS({
25678
25712
  let resolvePipeline;
25679
25713
  const pipelineError = new Promise((resolve7, reject2) => {
25680
25714
  resolvePipeline = () => resolve7(void 0);
25681
- stream2.pipeline(payloadStream, signingStream, request.body, (err) => {
25715
+ node_stream.pipeline(payloadStream, signingStream, request.body, (err) => {
25682
25716
  if (err) {
25683
25717
  reject2(new Error(`Pipeline error in @aws-sdk/eventstream-handler-node: ${err.message}`, { cause: err }));
25684
25718
  }
@@ -25783,7 +25817,7 @@ var init_package2 = __esm({
25783
25817
  "node_modules/@aws-sdk/token-providers/node_modules/@aws-sdk/nested-clients/package.json"() {
25784
25818
  package_default2 = {
25785
25819
  name: "@aws-sdk/nested-clients",
25786
- version: "3.983.0",
25820
+ version: "3.984.0",
25787
25821
  description: "Nested clients for AWS SDK packages.",
25788
25822
  main: "./dist-cjs/index.js",
25789
25823
  module: "./dist-es/index.js",
@@ -25819,7 +25853,7 @@ var init_package2 = __esm({
25819
25853
  "@aws-sdk/middleware-user-agent": "^3.972.6",
25820
25854
  "@aws-sdk/region-config-resolver": "^3.972.3",
25821
25855
  "@aws-sdk/types": "^3.973.1",
25822
- "@aws-sdk/util-endpoints": "3.983.0",
25856
+ "@aws-sdk/util-endpoints": "3.984.0",
25823
25857
  "@aws-sdk/util-user-agent-browser": "^3.972.3",
25824
25858
  "@aws-sdk/util-user-agent-node": "^3.972.4",
25825
25859
  "@smithy/config-resolver": "^4.4.6",
@@ -95131,7 +95165,7 @@ __export(enhanced_claude_code_exports, {
95131
95165
  createEnhancedClaudeCLIEngine: () => createEnhancedClaudeCLIEngine
95132
95166
  });
95133
95167
  async function createEnhancedClaudeCLIEngine(options = {}) {
95134
- const { agent, systemPrompt, customPrompt, debug, sessionId, allowedTools } = options;
95168
+ const { agent, systemPrompt, customPrompt, debug, sessionId, allowedTools, timeout = 12e4 } = options;
95135
95169
  const session = new Session(
95136
95170
  sessionId || (0, import_crypto6.randomBytes)(8).toString("hex"),
95137
95171
  debug
@@ -95230,6 +95264,30 @@ ${opts.schema}`;
95230
95264
  stdio: ["ignore", "pipe", "pipe"]
95231
95265
  // Ignore stdin since echo handles it
95232
95266
  });
95267
+ let killed = false;
95268
+ let timeoutHandle;
95269
+ let sigkillHandle;
95270
+ if (timeout > 0) {
95271
+ timeoutHandle = setTimeout(() => {
95272
+ if (!killed) {
95273
+ killed = true;
95274
+ processEnded = true;
95275
+ proc2.kill("SIGTERM");
95276
+ if (debug) {
95277
+ console.log(`[DEBUG] Process timed out after ${timeout}ms, sending SIGTERM`);
95278
+ }
95279
+ sigkillHandle = setTimeout(() => {
95280
+ if (proc2.exitCode === null) {
95281
+ proc2.kill("SIGKILL");
95282
+ if (debug) {
95283
+ console.log("[DEBUG] Process did not exit, sending SIGKILL");
95284
+ }
95285
+ }
95286
+ }, 5e3);
95287
+ emitter.emit("error", new Error(`Claude CLI process timed out after ${timeout}ms`));
95288
+ }
95289
+ }, timeout);
95290
+ }
95233
95291
  proc2.stdout.on("data", (data2) => {
95234
95292
  buffer += data2.toString();
95235
95293
  processJsonBuffer(buffer, emitter, session, debug, toolCollector);
@@ -95246,10 +95304,20 @@ ${opts.schema}`;
95246
95304
  }
95247
95305
  });
95248
95306
  proc2.on("close", (code) => {
95307
+ if (timeoutHandle) {
95308
+ clearTimeout(timeoutHandle);
95309
+ }
95310
+ if (sigkillHandle) {
95311
+ clearTimeout(sigkillHandle);
95312
+ }
95249
95313
  processEnded = true;
95250
95314
  if (code !== 0 && debug) {
95251
95315
  console.log(`[DEBUG] Process exited with code ${code}`);
95252
95316
  }
95317
+ if (killed) {
95318
+ emitter.emit("end");
95319
+ return;
95320
+ }
95253
95321
  if (buffer.trim()) {
95254
95322
  processJsonBuffer(buffer, emitter, session, debug, toolCollector);
95255
95323
  }
@@ -95265,6 +95333,13 @@ ${opts.schema}`;
95265
95333
  emitter.emit("end");
95266
95334
  });
95267
95335
  proc2.on("error", (error2) => {
95336
+ if (timeoutHandle) {
95337
+ clearTimeout(timeoutHandle);
95338
+ }
95339
+ if (sigkillHandle) {
95340
+ clearTimeout(sigkillHandle);
95341
+ }
95342
+ processEnded = true;
95268
95343
  emitter.emit("error", error2);
95269
95344
  });
95270
95345
  const messageQueue = [];
@@ -95310,7 +95385,22 @@ ${opts.schema}`;
95310
95385
  \u{1F527} Using ${msg.name}: ${JSON.stringify(msg.input)}
95311
95386
  `
95312
95387
  };
95313
- const result = await executeProbleTool(agent, msg.name, msg.input);
95388
+ const toolTimeout = 3e4;
95389
+ let toolTimeoutId;
95390
+ const timeoutPromise = new Promise((_, reject2) => {
95391
+ toolTimeoutId = setTimeout(() => reject2(new Error(`Tool ${msg.name} timed out after ${toolTimeout}ms`)), toolTimeout);
95392
+ });
95393
+ let result;
95394
+ try {
95395
+ result = await Promise.race([
95396
+ executeProbleTool(agent, msg.name, msg.input),
95397
+ timeoutPromise
95398
+ ]);
95399
+ } catch (error2) {
95400
+ result = `Tool error: ${error2.message}`;
95401
+ } finally {
95402
+ clearTimeout(toolTimeoutId);
95403
+ }
95314
95404
  yield { type: "text", content: `${result}
95315
95405
  ` };
95316
95406
  } else if (msg.type === "toolBatch") {
@@ -95886,6 +95976,9 @@ var init_enhanced_vercel = __esm({
95886
95976
  // src/agent/ProbeAgent.js
95887
95977
  var ProbeAgent_exports = {};
95888
95978
  __export(ProbeAgent_exports, {
95979
+ ENGINE_ACTIVITY_TIMEOUT_DEFAULT: () => ENGINE_ACTIVITY_TIMEOUT_DEFAULT,
95980
+ ENGINE_ACTIVITY_TIMEOUT_MAX: () => ENGINE_ACTIVITY_TIMEOUT_MAX,
95981
+ ENGINE_ACTIVITY_TIMEOUT_MIN: () => ENGINE_ACTIVITY_TIMEOUT_MIN,
95889
95982
  ProbeAgent: () => ProbeAgent
95890
95983
  });
95891
95984
  function extractWrappedToolName(wrappedToolError) {
@@ -95909,7 +96002,7 @@ Your content here
95909
96002
 
95910
96003
  Do NOT wrap in other tags like <api_call>, <tool_name>, <function>, etc.`;
95911
96004
  }
95912
- var import_dotenv, import_anthropic2, import_openai2, import_google2, import_ai3, import_crypto8, import_events4, import_fs11, import_promises6, import_path13, MAX_TOOL_ITERATIONS, MAX_HISTORY_MESSAGES, MAX_IMAGE_FILE_SIZE, ProbeAgent;
96005
+ var import_dotenv, import_anthropic2, import_openai2, import_google2, import_ai3, import_crypto8, import_events4, import_fs11, import_promises6, import_path13, ENGINE_ACTIVITY_TIMEOUT_DEFAULT, ENGINE_ACTIVITY_TIMEOUT_MIN, ENGINE_ACTIVITY_TIMEOUT_MAX, MAX_TOOL_ITERATIONS, MAX_HISTORY_MESSAGES, MAX_IMAGE_FILE_SIZE, ProbeAgent;
95913
96006
  var init_ProbeAgent = __esm({
95914
96007
  "src/agent/ProbeAgent.js"() {
95915
96008
  "use strict";
@@ -95949,6 +96042,9 @@ var init_ProbeAgent = __esm({
95949
96042
  init_delegate();
95950
96043
  init_tasks();
95951
96044
  import_dotenv.default.config();
96045
+ ENGINE_ACTIVITY_TIMEOUT_DEFAULT = 18e4;
96046
+ ENGINE_ACTIVITY_TIMEOUT_MIN = 5e3;
96047
+ ENGINE_ACTIVITY_TIMEOUT_MAX = 6e5;
95952
96048
  MAX_TOOL_ITERATIONS = (() => {
95953
96049
  const val = parseInt(process.env.MAX_TOOL_ITERATIONS || "30", 10);
95954
96050
  if (isNaN(val) || val < 1 || val > 200) {
@@ -96007,6 +96103,8 @@ var init_ProbeAgent = __esm({
96007
96103
  * @param {number} [options.fallback.maxTotalAttempts=10] - Maximum total attempts across all providers
96008
96104
  * @param {string} [options.completionPrompt] - Custom prompt to run after attempt_completion for validation/review (runs before mermaid/JSON validation)
96009
96105
  * @param {number} [options.maxOutputTokens] - Maximum tokens for tool output before truncation (default: 20000, can also be set via PROBE_MAX_OUTPUT_TOKENS env var)
96106
+ * @param {number} [options.requestTimeout] - Timeout in ms for AI requests (default: 120000 or REQUEST_TIMEOUT env var). Used to abort hung requests.
96107
+ * @param {number} [options.maxOperationTimeout] - Maximum timeout in ms for the entire operation including all retries and fallbacks (default: 300000 or MAX_OPERATION_TIMEOUT env var). This is the absolute maximum time for streamTextWithRetryAndFallback.
96010
96108
  */
96011
96109
  constructor(options = {}) {
96012
96110
  this.sessionId = options.sessionId || (0, import_crypto8.randomUUID)();
@@ -96092,6 +96190,32 @@ var init_ProbeAgent = __esm({
96092
96190
  this.enableTasks = !!options.enableTasks;
96093
96191
  this.taskManager = null;
96094
96192
  this.delegationManager = new DelegationManager();
96193
+ this.requestTimeout = options.requestTimeout ?? (() => {
96194
+ if (process.env.REQUEST_TIMEOUT) {
96195
+ const parsed = parseInt(process.env.REQUEST_TIMEOUT, 10);
96196
+ if (isNaN(parsed) || parsed < 1e3 || parsed > 36e5) {
96197
+ return 12e4;
96198
+ }
96199
+ return parsed;
96200
+ }
96201
+ return 12e4;
96202
+ })();
96203
+ if (this.debug) {
96204
+ console.log(`[DEBUG] Request timeout: ${this.requestTimeout}ms`);
96205
+ }
96206
+ this.maxOperationTimeout = options.maxOperationTimeout ?? (() => {
96207
+ if (process.env.MAX_OPERATION_TIMEOUT) {
96208
+ const parsed = parseInt(process.env.MAX_OPERATION_TIMEOUT, 10);
96209
+ if (isNaN(parsed) || parsed < 1e3 || parsed > 72e5) {
96210
+ return 3e5;
96211
+ }
96212
+ return parsed;
96213
+ }
96214
+ return 3e5;
96215
+ })();
96216
+ if (this.debug) {
96217
+ console.log(`[DEBUG] Max operation timeout: ${this.maxOperationTimeout}ms`);
96218
+ }
96095
96219
  this.retryConfig = options.retry || {};
96096
96220
  this.retryManager = null;
96097
96221
  this.fallbackConfig = options.fallback || null;
@@ -96711,88 +96835,98 @@ var init_ProbeAgent = __esm({
96711
96835
  }
96712
96836
  }
96713
96837
  /**
96714
- * Execute streamText with retry and fallback support
96715
- * @param {Object} options - streamText options
96716
- * @returns {Promise<Object>} - streamText result
96838
+ * Create a streamText-compatible result from an engine stream with timeout handling
96839
+ * @param {AsyncGenerator} engineStream - The engine's query result
96840
+ * @param {AbortSignal} abortSignal - Signal for aborting the operation
96841
+ * @param {number} requestTimeout - Per-request timeout in ms
96842
+ * @param {Object} timeoutState - Object with timeoutId property (mutable for cleanup)
96843
+ * @returns {Object} - streamText-compatible result with textStream
96717
96844
  * @private
96718
96845
  */
96719
- async streamTextWithRetryAndFallback(options) {
96720
- if (this.clientApiProvider === "claude-code" || process.env.USE_CLAUDE_CODE === "true") {
96846
+ _createEngineTextStreamResult(engineStream, abortSignal, requestTimeout, timeoutState) {
96847
+ const activityTimeout = (() => {
96848
+ const parsed = parseInt(process.env.ENGINE_ACTIVITY_TIMEOUT, 10);
96849
+ return isNaN(parsed) || parsed < ENGINE_ACTIVITY_TIMEOUT_MIN || parsed > ENGINE_ACTIVITY_TIMEOUT_MAX ? ENGINE_ACTIVITY_TIMEOUT_DEFAULT : parsed;
96850
+ })();
96851
+ const startTime = Date.now();
96852
+ async function* createTextStream() {
96853
+ let lastActivity = Date.now();
96721
96854
  try {
96722
- const engine = await this.getEngine();
96723
- if (engine && engine.query) {
96724
- const userMessages = options.messages.filter(
96725
- (m5) => m5.role === "user" && !m5.content.includes("WARNING: You have reached the maximum tool iterations limit")
96726
- );
96727
- const lastUserMessage = userMessages[userMessages.length - 1];
96728
- const prompt = lastUserMessage ? lastUserMessage.content : "";
96729
- const engineOptions = {
96730
- maxTokens: options.maxTokens,
96731
- temperature: options.temperature,
96732
- messages: options.messages,
96733
- systemPrompt: options.messages.find((m5) => m5.role === "system")?.content
96734
- };
96735
- const engineStream = engine.query(prompt, engineOptions);
96736
- async function* createTextStream() {
96737
- for await (const message of engineStream) {
96738
- if (message.type === "text" && message.content) {
96739
- yield message.content;
96740
- } else if (typeof message === "string") {
96741
- yield message;
96742
- }
96743
- }
96855
+ for await (const message of engineStream) {
96856
+ if (abortSignal.aborted) {
96857
+ const abortError = new Error("Operation aborted");
96858
+ abortError.name = "AbortError";
96859
+ throw abortError;
96744
96860
  }
96745
- return {
96746
- textStream: createTextStream(),
96747
- usage: Promise.resolve({})
96748
- // Engine should handle its own usage tracking
96749
- // Add other streamText-compatible properties as needed
96750
- };
96751
- }
96752
- } catch (error2) {
96753
- if (this.debug) {
96754
- console.log(`[DEBUG] Failed to use Claude Code engine, falling back to Vercel:`, error2.message);
96755
- }
96756
- }
96757
- }
96758
- if (this.clientApiProvider === "codex" || process.env.USE_CODEX === "true") {
96759
- try {
96760
- const engine = await this.getEngine();
96761
- if (engine && engine.query) {
96762
- const userMessages = options.messages.filter(
96763
- (m5) => m5.role === "user" && !m5.content.includes("WARNING: You have reached the maximum tool iterations limit")
96764
- );
96765
- const lastUserMessage = userMessages[userMessages.length - 1];
96766
- const prompt = lastUserMessage ? lastUserMessage.content : "";
96767
- const engineOptions = {
96768
- maxTokens: options.maxTokens,
96769
- temperature: options.temperature,
96770
- messages: options.messages,
96771
- systemPrompt: options.messages.find((m5) => m5.role === "system")?.content
96772
- };
96773
- const engineStream = engine.query(prompt, engineOptions);
96774
- async function* createTextStream() {
96775
- for await (const message of engineStream) {
96776
- if (message.type === "text" && message.content) {
96777
- yield message.content;
96778
- } else if (typeof message === "string") {
96779
- yield message;
96780
- }
96781
- }
96861
+ const now = Date.now();
96862
+ if (now - lastActivity > activityTimeout) {
96863
+ throw new Error(`Engine stream timeout - no activity for ${activityTimeout}ms`);
96864
+ }
96865
+ if (requestTimeout > 0 && now - startTime > requestTimeout) {
96866
+ throw new Error(`Engine stream timeout - request exceeded ${requestTimeout}ms`);
96867
+ }
96868
+ lastActivity = now;
96869
+ if (message.type === "text" && message.content) {
96870
+ yield message.content;
96871
+ } else if (typeof message === "string") {
96872
+ yield message;
96782
96873
  }
96783
- return {
96784
- textStream: createTextStream(),
96785
- usage: Promise.resolve({})
96786
- // Engine should handle its own usage tracking
96787
- // Add other streamText-compatible properties as needed
96788
- };
96789
96874
  }
96790
- } catch (error2) {
96791
- if (this.debug) {
96792
- console.log(`[DEBUG] Failed to use Codex engine, falling back to Vercel:`, error2.message);
96875
+ } finally {
96876
+ if (timeoutState.timeoutId) {
96877
+ clearTimeout(timeoutState.timeoutId);
96878
+ timeoutState.timeoutId = null;
96793
96879
  }
96794
96880
  }
96795
96881
  }
96882
+ return {
96883
+ textStream: createTextStream(),
96884
+ usage: Promise.resolve({})
96885
+ // Engine should handle its own usage tracking
96886
+ // Add other streamText-compatible properties as needed
96887
+ };
96888
+ }
96889
+ /**
96890
+ * Try to use an engine (claude-code or codex) for streaming
96891
+ * @param {Object} options - streamText options
96892
+ * @param {AbortController} controller - Abort controller for the operation
96893
+ * @param {Object} timeoutState - Mutable timeout state for cleanup
96894
+ * @returns {Promise<Object|null>} - Stream result or null if engine unavailable
96895
+ * @private
96896
+ */
96897
+ async _tryEngineStreamPath(options, controller, timeoutState) {
96898
+ const engine = await this.getEngine();
96899
+ if (!engine || !engine.query) {
96900
+ return null;
96901
+ }
96902
+ const userMessages = options.messages.filter(
96903
+ (m5) => m5.role === "user" && !m5.content.includes("WARNING: You have reached the maximum tool iterations limit")
96904
+ );
96905
+ const lastUserMessage = userMessages[userMessages.length - 1];
96906
+ const prompt = lastUserMessage ? lastUserMessage.content : "";
96907
+ const engineOptions = {
96908
+ maxTokens: options.maxTokens,
96909
+ temperature: options.temperature,
96910
+ messages: options.messages,
96911
+ systemPrompt: options.messages.find((m5) => m5.role === "system")?.content,
96912
+ abortSignal: controller.signal
96913
+ };
96914
+ const engineStream = engine.query(prompt, engineOptions);
96915
+ return this._createEngineTextStreamResult(
96916
+ engineStream,
96917
+ controller.signal,
96918
+ this.requestTimeout,
96919
+ timeoutState
96920
+ );
96921
+ }
96922
+ /**
96923
+ * Execute streamText with Vercel AI SDK using retry/fallback logic
96924
+ * @param {Object} options - streamText options
96925
+ * @param {AbortController} controller - Abort controller for the operation
96926
+ * @returns {Promise<Object>} - Stream result
96927
+ * @private
96928
+ */
96929
+ async _executeWithVercelProvider(options, controller) {
96796
96930
  if (!this.retryManager) {
96797
96931
  this.retryManager = new RetryManager({
96798
96932
  maxRetries: this.retryConfig.maxRetries ?? 3,
@@ -96805,10 +96939,11 @@ var init_ProbeAgent = __esm({
96805
96939
  }
96806
96940
  if (!this.fallbackManager) {
96807
96941
  return await this.retryManager.executeWithRetry(
96808
- () => (0, import_ai3.streamText)(options),
96942
+ () => (0, import_ai3.streamText)({ ...options, abortSignal: controller.signal }),
96809
96943
  {
96810
96944
  provider: this.apiType,
96811
- model: this.model
96945
+ model: this.model,
96946
+ signal: controller.signal
96812
96947
  }
96813
96948
  );
96814
96949
  }
@@ -96816,7 +96951,8 @@ var init_ProbeAgent = __esm({
96816
96951
  async (provider, model, config) => {
96817
96952
  const fallbackOptions = {
96818
96953
  ...options,
96819
- model: provider(model)
96954
+ model: provider(model),
96955
+ abortSignal: controller.signal
96820
96956
  };
96821
96957
  const providerRetryManager = new RetryManager({
96822
96958
  maxRetries: config.maxRetries ?? this.retryConfig.maxRetries ?? 3,
@@ -96830,12 +96966,54 @@ var init_ProbeAgent = __esm({
96830
96966
  () => (0, import_ai3.streamText)(fallbackOptions),
96831
96967
  {
96832
96968
  provider: config.provider,
96833
- model
96969
+ model,
96970
+ signal: controller.signal
96834
96971
  }
96835
96972
  );
96836
96973
  }
96837
96974
  );
96838
96975
  }
96976
+ /**
96977
+ * Execute streamText with retry and fallback support
96978
+ * @param {Object} options - streamText options
96979
+ * @returns {Promise<Object>} - streamText result
96980
+ * @private
96981
+ */
96982
+ async streamTextWithRetryAndFallback(options) {
96983
+ const controller = new AbortController();
96984
+ const timeoutState = { timeoutId: null };
96985
+ if (this.maxOperationTimeout && this.maxOperationTimeout > 0) {
96986
+ timeoutState.timeoutId = setTimeout(() => {
96987
+ controller.abort();
96988
+ if (this.debug) {
96989
+ console.log(`[DEBUG] Operation timed out after ${this.maxOperationTimeout}ms (max operation timeout)`);
96990
+ }
96991
+ }, this.maxOperationTimeout);
96992
+ }
96993
+ try {
96994
+ const useClaudeCode = this.clientApiProvider === "claude-code" || process.env.USE_CLAUDE_CODE === "true";
96995
+ const useCodex = this.clientApiProvider === "codex" || process.env.USE_CODEX === "true";
96996
+ if (useClaudeCode || useCodex) {
96997
+ try {
96998
+ const result = await this._tryEngineStreamPath(options, controller, timeoutState);
96999
+ if (result) {
97000
+ return result;
97001
+ }
97002
+ } catch (error2) {
97003
+ if (this.debug) {
97004
+ const engineType = useClaudeCode ? "Claude Code" : "Codex";
97005
+ console.log(`[DEBUG] Failed to use ${engineType} engine, falling back to Vercel:`, error2.message);
97006
+ }
97007
+ }
97008
+ }
97009
+ return await this._executeWithVercelProvider(options, controller);
97010
+ } finally {
97011
+ if (timeoutState.timeoutId) {
97012
+ clearTimeout(timeoutState.timeoutId);
97013
+ timeoutState.timeoutId = null;
97014
+ }
97015
+ }
97016
+ }
96839
97017
  /**
96840
97018
  * Initialize Anthropic model
96841
97019
  */