@probelabs/probe 0.6.0-rc131 → 0.6.0-rc133

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
@@ -9774,7 +9774,7 @@ var require_dist_cjs15 = __commonJS({
9774
9774
  const registerTimeout = (offset) => {
9775
9775
  const timeoutId = timing.setTimeout(() => {
9776
9776
  request.destroy();
9777
- reject2(Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), {
9777
+ reject2(Object.assign(new Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${timeoutInMs} ms.`), {
9778
9778
  name: "TimeoutError"
9779
9779
  }));
9780
9780
  }, timeoutInMs - offset);
@@ -9799,6 +9799,25 @@ var require_dist_cjs15 = __commonJS({
9799
9799
  }
9800
9800
  return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME$2), DEFER_EVENT_LISTENER_TIME$2);
9801
9801
  };
9802
+ var setRequestTimeout = (req, reject2, timeoutInMs = 0, throwOnRequestTimeout, logger2) => {
9803
+ if (timeoutInMs) {
9804
+ return timing.setTimeout(() => {
9805
+ let msg = `@smithy/node-http-handler - [${throwOnRequestTimeout ? "ERROR" : "WARN"}] a request has exceeded the configured ${timeoutInMs} ms requestTimeout.`;
9806
+ if (throwOnRequestTimeout) {
9807
+ const error2 = Object.assign(new Error(msg), {
9808
+ name: "TimeoutError",
9809
+ code: "ETIMEDOUT"
9810
+ });
9811
+ req.destroy(error2);
9812
+ reject2(error2);
9813
+ } else {
9814
+ msg += ` Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.`;
9815
+ logger2?.warn?.(msg);
9816
+ }
9817
+ }, timeoutInMs);
9818
+ }
9819
+ return -1;
9820
+ };
9802
9821
  var DEFER_EVENT_LISTENER_TIME$1 = 3e3;
9803
9822
  var setSocketKeepAlive = (request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME$1) => {
9804
9823
  if (keepAlive !== true) {
@@ -9820,12 +9839,12 @@ var require_dist_cjs15 = __commonJS({
9820
9839
  return timing.setTimeout(registerListener, deferTimeMs);
9821
9840
  };
9822
9841
  var DEFER_EVENT_LISTENER_TIME = 3e3;
9823
- var setSocketTimeout = (request, reject2, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => {
9842
+ var setSocketTimeout = (request, reject2, timeoutInMs = 0) => {
9824
9843
  const registerTimeout = (offset) => {
9825
9844
  const timeout = timeoutInMs - offset;
9826
9845
  const onTimeout = () => {
9827
9846
  request.destroy();
9828
- reject2(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" }));
9847
+ reject2(Object.assign(new Error(`@smithy/node-http-handler - the request socket timed out after ${timeoutInMs} ms of inactivity (configured by client requestHandler).`), { name: "TimeoutError" }));
9829
9848
  };
9830
9849
  if (request.socket) {
9831
9850
  request.socket.setTimeout(timeout, onTimeout);
@@ -9938,13 +9957,15 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
9938
9957
  });
9939
9958
  }
9940
9959
  resolveDefaultConfig(options) {
9941
- const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {};
9960
+ const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent, throwOnRequestTimeout } = options || {};
9942
9961
  const keepAlive = true;
9943
9962
  const maxSockets = 50;
9944
9963
  return {
9945
9964
  connectionTimeout,
9946
- requestTimeout: requestTimeout ?? socketTimeout,
9965
+ requestTimeout,
9966
+ socketTimeout,
9947
9967
  socketAcquisitionWarningTimeout,
9968
+ throwOnRequestTimeout,
9948
9969
  httpAgent: (() => {
9949
9970
  if (httpAgent instanceof http.Agent || typeof httpAgent?.destroy === "function") {
9950
9971
  return httpAgent;
@@ -10058,7 +10079,8 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
10058
10079
  }
10059
10080
  const effectiveRequestTimeout = requestTimeout ?? this.config.requestTimeout;
10060
10081
  timeouts.push(setConnectionTimeout(req, reject2, this.config.connectionTimeout));
10061
- timeouts.push(setSocketTimeout(req, reject2, effectiveRequestTimeout));
10082
+ timeouts.push(setRequestTimeout(req, reject2, effectiveRequestTimeout, this.config.throwOnRequestTimeout, this.config.logger ?? console));
10083
+ timeouts.push(setSocketTimeout(req, reject2, this.config.socketTimeout));
10062
10084
  const httpAgent = nodeHttpsOptions.agent;
10063
10085
  if (typeof httpAgent === "object" && "keepAlive" in httpAgent) {
10064
10086
  timeouts.push(setSocketKeepAlive(req, {
@@ -10983,120 +11005,6 @@ var init_deref = __esm({
10983
11005
  }
10984
11006
  });
10985
11007
 
10986
- // node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js
10987
- var import_protocol_http2, import_util_middleware3, schemaDeserializationMiddleware, findHeader;
10988
- var init_schemaDeserializationMiddleware = __esm({
10989
- "node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js"() {
10990
- import_protocol_http2 = __toESM(require_dist_cjs2());
10991
- import_util_middleware3 = __toESM(require_dist_cjs7());
10992
- schemaDeserializationMiddleware = (config) => (next, context) => async (args) => {
10993
- const { response } = await next(args);
10994
- const { operationSchema } = (0, import_util_middleware3.getSmithyContext)(context);
10995
- try {
10996
- const parsed = await config.protocol.deserializeResponse(operationSchema, {
10997
- ...config,
10998
- ...context
10999
- }, response);
11000
- return {
11001
- response,
11002
- output: parsed
11003
- };
11004
- } catch (error2) {
11005
- Object.defineProperty(error2, "$response", {
11006
- value: response
11007
- });
11008
- if (!("$metadata" in error2)) {
11009
- const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`;
11010
- try {
11011
- error2.message += "\n " + hint;
11012
- } catch (e3) {
11013
- if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") {
11014
- console.warn(hint);
11015
- } else {
11016
- context.logger?.warn?.(hint);
11017
- }
11018
- }
11019
- if (typeof error2.$responseBodyText !== "undefined") {
11020
- if (error2.$response) {
11021
- error2.$response.body = error2.$responseBodyText;
11022
- }
11023
- }
11024
- try {
11025
- if (import_protocol_http2.HttpResponse.isInstance(response)) {
11026
- const { headers = {} } = response;
11027
- const headerEntries = Object.entries(headers);
11028
- error2.$metadata = {
11029
- httpStatusCode: response.statusCode,
11030
- requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries),
11031
- extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries),
11032
- cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries)
11033
- };
11034
- }
11035
- } catch (e3) {
11036
- }
11037
- }
11038
- throw error2;
11039
- }
11040
- };
11041
- findHeader = (pattern, headers) => {
11042
- return (headers.find(([k3]) => {
11043
- return k3.match(pattern);
11044
- }) || [void 0, void 0])[1];
11045
- };
11046
- }
11047
- });
11048
-
11049
- // node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js
11050
- var import_util_middleware4, schemaSerializationMiddleware;
11051
- var init_schemaSerializationMiddleware = __esm({
11052
- "node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js"() {
11053
- import_util_middleware4 = __toESM(require_dist_cjs7());
11054
- schemaSerializationMiddleware = (config) => (next, context) => async (args) => {
11055
- const { operationSchema } = (0, import_util_middleware4.getSmithyContext)(context);
11056
- const endpoint = context.endpointV2?.url && config.urlParser ? async () => config.urlParser(context.endpointV2.url) : config.endpoint;
11057
- const request = await config.protocol.serializeRequest(operationSchema, args.input, {
11058
- ...config,
11059
- ...context,
11060
- endpoint
11061
- });
11062
- return next({
11063
- ...args,
11064
- request
11065
- });
11066
- };
11067
- }
11068
- });
11069
-
11070
- // node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js
11071
- function getSchemaSerdePlugin(config) {
11072
- return {
11073
- applyToStack: (commandStack) => {
11074
- commandStack.add(schemaSerializationMiddleware(config), serializerMiddlewareOption2);
11075
- commandStack.add(schemaDeserializationMiddleware(config), deserializerMiddlewareOption);
11076
- config.protocol.setSerdeContext(config);
11077
- }
11078
- };
11079
- }
11080
- var deserializerMiddlewareOption, serializerMiddlewareOption2;
11081
- var init_getSchemaSerdePlugin = __esm({
11082
- "node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js"() {
11083
- init_schemaDeserializationMiddleware();
11084
- init_schemaSerializationMiddleware();
11085
- deserializerMiddlewareOption = {
11086
- name: "deserializerMiddleware",
11087
- step: "deserialize",
11088
- tags: ["DESERIALIZER"],
11089
- override: true
11090
- };
11091
- serializerMiddlewareOption2 = {
11092
- name: "serializerMiddleware",
11093
- step: "serialize",
11094
- tags: ["SERIALIZER"],
11095
- override: true
11096
- };
11097
- }
11098
- });
11099
-
11100
11008
  // node_modules/@smithy/core/dist-es/submodules/schema/TypeRegistry.js
11101
11009
  var TypeRegistry;
11102
11010
  var init_TypeRegistry = __esm({
@@ -11128,11 +11036,11 @@ var init_TypeRegistry = __esm({
11128
11036
  }
11129
11037
  return this.schemas.get(id);
11130
11038
  }
11131
- registerError(errorSchema, ctor) {
11132
- this.exceptions.set(errorSchema, ctor);
11039
+ registerError(es, ctor) {
11040
+ this.exceptions.set(es, ctor);
11133
11041
  }
11134
- getErrorCtor(errorSchema) {
11135
- return this.exceptions.get(errorSchema);
11042
+ getErrorCtor(es) {
11043
+ return this.exceptions.get(es);
11136
11044
  }
11137
11045
  getBaseException() {
11138
11046
  for (const [id, schema] of this.schemas.entries()) {
@@ -11191,6 +11099,51 @@ var init_Schema = __esm({
11191
11099
  }
11192
11100
  });
11193
11101
 
11102
+ // node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js
11103
+ var StructureSchema, struct;
11104
+ var init_StructureSchema = __esm({
11105
+ "node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js"() {
11106
+ init_Schema();
11107
+ StructureSchema = class _StructureSchema extends Schema {
11108
+ static symbol = Symbol.for("@smithy/str");
11109
+ name;
11110
+ traits;
11111
+ memberNames;
11112
+ memberList;
11113
+ symbol = _StructureSchema.symbol;
11114
+ };
11115
+ struct = (namespace, name14, traits, memberNames, memberList) => Schema.assign(new StructureSchema(), {
11116
+ name: name14,
11117
+ namespace,
11118
+ traits,
11119
+ memberNames,
11120
+ memberList
11121
+ });
11122
+ }
11123
+ });
11124
+
11125
+ // node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js
11126
+ var ErrorSchema, error;
11127
+ var init_ErrorSchema = __esm({
11128
+ "node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js"() {
11129
+ init_Schema();
11130
+ init_StructureSchema();
11131
+ ErrorSchema = class _ErrorSchema extends StructureSchema {
11132
+ static symbol = Symbol.for("@smithy/err");
11133
+ ctor;
11134
+ symbol = _ErrorSchema.symbol;
11135
+ };
11136
+ error = (namespace, name14, traits, memberNames, memberList, ctor) => Schema.assign(new ErrorSchema(), {
11137
+ name: name14,
11138
+ namespace,
11139
+ traits,
11140
+ memberNames,
11141
+ memberList,
11142
+ ctor: null
11143
+ });
11144
+ }
11145
+ });
11146
+
11194
11147
  // node_modules/@smithy/core/dist-es/submodules/schema/schemas/ListSchema.js
11195
11148
  var ListSchema, list;
11196
11149
  var init_ListSchema = __esm({
@@ -11258,47 +11211,23 @@ var init_OperationSchema = __esm({
11258
11211
  }
11259
11212
  });
11260
11213
 
11261
- // node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js
11262
- var StructureSchema, struct;
11263
- var init_StructureSchema = __esm({
11264
- "node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js"() {
11214
+ // node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js
11215
+ var SimpleSchema, sim;
11216
+ var init_SimpleSchema = __esm({
11217
+ "node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js"() {
11265
11218
  init_Schema();
11266
- StructureSchema = class _StructureSchema extends Schema {
11267
- static symbol = Symbol.for("@smithy/str");
11219
+ SimpleSchema = class _SimpleSchema extends Schema {
11220
+ static symbol = Symbol.for("@smithy/sim");
11268
11221
  name;
11222
+ schemaRef;
11269
11223
  traits;
11270
- memberNames;
11271
- memberList;
11272
- symbol = _StructureSchema.symbol;
11273
- };
11274
- struct = (namespace, name14, traits, memberNames, memberList) => Schema.assign(new StructureSchema(), {
11275
- name: name14,
11276
- namespace,
11277
- traits,
11278
- memberNames,
11279
- memberList
11280
- });
11281
- }
11282
- });
11283
-
11284
- // node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js
11285
- var ErrorSchema, error;
11286
- var init_ErrorSchema = __esm({
11287
- "node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js"() {
11288
- init_Schema();
11289
- init_StructureSchema();
11290
- ErrorSchema = class _ErrorSchema extends StructureSchema {
11291
- static symbol = Symbol.for("@smithy/err");
11292
- ctor;
11293
- symbol = _ErrorSchema.symbol;
11224
+ symbol = _SimpleSchema.symbol;
11294
11225
  };
11295
- error = (namespace, name14, traits, memberNames, memberList, ctor) => Schema.assign(new ErrorSchema(), {
11226
+ sim = (namespace, name14, schemaRef, traits) => Schema.assign(new SimpleSchema(), {
11296
11227
  name: name14,
11297
11228
  namespace,
11298
11229
  traits,
11299
- memberNames,
11300
- memberList,
11301
- ctor: null
11230
+ schemaRef
11302
11231
  });
11303
11232
  }
11304
11233
  });
@@ -11342,13 +11271,27 @@ function member(memberSchema, memberName) {
11342
11271
  const internalCtorAccess = NormalizedSchema;
11343
11272
  return new internalCtorAccess(memberSchema, memberName);
11344
11273
  }
11345
- var NormalizedSchema;
11274
+ function hydrate(ss) {
11275
+ const [id, ...rest] = ss;
11276
+ return {
11277
+ [0]: sim,
11278
+ [1]: list,
11279
+ [2]: map,
11280
+ [3]: struct,
11281
+ [-3]: error,
11282
+ [9]: op
11283
+ }[id].call(null, ...rest);
11284
+ }
11285
+ var NormalizedSchema, isMemberSchema, isStaticSchema;
11346
11286
  var init_NormalizedSchema = __esm({
11347
11287
  "node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js"() {
11348
11288
  init_deref();
11289
+ init_ErrorSchema();
11349
11290
  init_ListSchema();
11350
11291
  init_MapSchema();
11292
+ init_OperationSchema();
11351
11293
  init_Schema();
11294
+ init_SimpleSchema();
11352
11295
  init_StructureSchema();
11353
11296
  init_translateTraits();
11354
11297
  NormalizedSchema = class _NormalizedSchema {
@@ -11369,12 +11312,14 @@ var init_NormalizedSchema = __esm({
11369
11312
  let _ref = ref;
11370
11313
  let schema = ref;
11371
11314
  this._isMemberSchema = false;
11372
- while (Array.isArray(_ref)) {
11315
+ while (isMemberSchema(_ref)) {
11373
11316
  traitStack.push(_ref[1]);
11374
11317
  _ref = _ref[0];
11375
11318
  schema = deref(_ref);
11376
11319
  this._isMemberSchema = true;
11377
11320
  }
11321
+ if (isStaticSchema(schema))
11322
+ schema = hydrate(schema);
11378
11323
  if (traitStack.length > 0) {
11379
11324
  this.memberTraits = {};
11380
11325
  for (let i3 = traitStack.length - 1; i3 >= 0; --i3) {
@@ -11411,7 +11356,7 @@ var init_NormalizedSchema = __esm({
11411
11356
  if (sc instanceof _NormalizedSchema) {
11412
11357
  return sc;
11413
11358
  }
11414
- if (Array.isArray(sc)) {
11359
+ if (isMemberSchema(sc)) {
11415
11360
  const [ns, traits] = sc;
11416
11361
  if (ns instanceof _NormalizedSchema) {
11417
11362
  Object.assign(ns.getMergedTraits(), translateTraits(traits));
@@ -11520,7 +11465,7 @@ var init_NormalizedSchema = __esm({
11520
11465
  if (this.isStructSchema() && struct2.memberNames.includes(memberName)) {
11521
11466
  const i3 = struct2.memberNames.indexOf(memberName);
11522
11467
  const memberSchema = struct2.memberList[i3];
11523
- return member(Array.isArray(memberSchema) ? memberSchema : [memberSchema, 0], memberName);
11468
+ return member(isMemberSchema(memberSchema) ? memberSchema : [memberSchema, 0], memberName);
11524
11469
  }
11525
11470
  if (this.isDocumentSchema()) {
11526
11471
  return member([15, 0], memberName);
@@ -11560,27 +11505,130 @@ var init_NormalizedSchema = __esm({
11560
11505
  }
11561
11506
  }
11562
11507
  };
11508
+ isMemberSchema = (sc) => Array.isArray(sc) && sc.length === 2;
11509
+ isStaticSchema = (sc) => Array.isArray(sc) && sc.length >= 5;
11563
11510
  }
11564
11511
  });
11565
11512
 
11566
- // node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js
11567
- var SimpleSchema, sim;
11568
- var init_SimpleSchema = __esm({
11569
- "node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js"() {
11570
- init_Schema();
11571
- SimpleSchema = class _SimpleSchema extends Schema {
11572
- static symbol = Symbol.for("@smithy/sim");
11573
- name;
11574
- schemaRef;
11575
- traits;
11576
- symbol = _SimpleSchema.symbol;
11513
+ // node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js
11514
+ var import_protocol_http2, import_util_middleware3, schemaDeserializationMiddleware, findHeader;
11515
+ var init_schemaDeserializationMiddleware = __esm({
11516
+ "node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js"() {
11517
+ import_protocol_http2 = __toESM(require_dist_cjs2());
11518
+ import_util_middleware3 = __toESM(require_dist_cjs7());
11519
+ init_NormalizedSchema();
11520
+ schemaDeserializationMiddleware = (config) => (next, context) => async (args) => {
11521
+ const { response } = await next(args);
11522
+ let { operationSchema } = (0, import_util_middleware3.getSmithyContext)(context);
11523
+ if (isStaticSchema(operationSchema)) {
11524
+ operationSchema = hydrate(operationSchema);
11525
+ }
11526
+ try {
11527
+ const parsed = await config.protocol.deserializeResponse(operationSchema, {
11528
+ ...config,
11529
+ ...context
11530
+ }, response);
11531
+ return {
11532
+ response,
11533
+ output: parsed
11534
+ };
11535
+ } catch (error2) {
11536
+ Object.defineProperty(error2, "$response", {
11537
+ value: response
11538
+ });
11539
+ if (!("$metadata" in error2)) {
11540
+ const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`;
11541
+ try {
11542
+ error2.message += "\n " + hint;
11543
+ } catch (e3) {
11544
+ if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") {
11545
+ console.warn(hint);
11546
+ } else {
11547
+ context.logger?.warn?.(hint);
11548
+ }
11549
+ }
11550
+ if (typeof error2.$responseBodyText !== "undefined") {
11551
+ if (error2.$response) {
11552
+ error2.$response.body = error2.$responseBodyText;
11553
+ }
11554
+ }
11555
+ try {
11556
+ if (import_protocol_http2.HttpResponse.isInstance(response)) {
11557
+ const { headers = {} } = response;
11558
+ const headerEntries = Object.entries(headers);
11559
+ error2.$metadata = {
11560
+ httpStatusCode: response.statusCode,
11561
+ requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries),
11562
+ extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries),
11563
+ cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries)
11564
+ };
11565
+ }
11566
+ } catch (e3) {
11567
+ }
11568
+ }
11569
+ throw error2;
11570
+ }
11571
+ };
11572
+ findHeader = (pattern, headers) => {
11573
+ return (headers.find(([k3]) => {
11574
+ return k3.match(pattern);
11575
+ }) || [void 0, void 0])[1];
11576
+ };
11577
+ }
11578
+ });
11579
+
11580
+ // node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js
11581
+ var import_util_middleware4, schemaSerializationMiddleware;
11582
+ var init_schemaSerializationMiddleware = __esm({
11583
+ "node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js"() {
11584
+ import_util_middleware4 = __toESM(require_dist_cjs7());
11585
+ init_NormalizedSchema();
11586
+ schemaSerializationMiddleware = (config) => (next, context) => async (args) => {
11587
+ let { operationSchema } = (0, import_util_middleware4.getSmithyContext)(context);
11588
+ if (isStaticSchema(operationSchema)) {
11589
+ operationSchema = hydrate(operationSchema);
11590
+ }
11591
+ const endpoint = context.endpointV2?.url && config.urlParser ? async () => config.urlParser(context.endpointV2.url) : config.endpoint;
11592
+ const request = await config.protocol.serializeRequest(operationSchema, args.input, {
11593
+ ...config,
11594
+ ...context,
11595
+ endpoint
11596
+ });
11597
+ return next({
11598
+ ...args,
11599
+ request
11600
+ });
11601
+ };
11602
+ }
11603
+ });
11604
+
11605
+ // node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js
11606
+ function getSchemaSerdePlugin(config) {
11607
+ return {
11608
+ applyToStack: (commandStack) => {
11609
+ commandStack.add(schemaSerializationMiddleware(config), serializerMiddlewareOption2);
11610
+ commandStack.add(schemaDeserializationMiddleware(config), deserializerMiddlewareOption);
11611
+ config.protocol.setSerdeContext(config);
11612
+ }
11613
+ };
11614
+ }
11615
+ var deserializerMiddlewareOption, serializerMiddlewareOption2;
11616
+ var init_getSchemaSerdePlugin = __esm({
11617
+ "node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js"() {
11618
+ init_schemaDeserializationMiddleware();
11619
+ init_schemaSerializationMiddleware();
11620
+ deserializerMiddlewareOption = {
11621
+ name: "deserializerMiddleware",
11622
+ step: "deserialize",
11623
+ tags: ["DESERIALIZER"],
11624
+ override: true
11625
+ };
11626
+ serializerMiddlewareOption2 = {
11627
+ name: "serializerMiddleware",
11628
+ step: "serialize",
11629
+ tags: ["SERIALIZER"],
11630
+ override: true
11577
11631
  };
11578
- sim = (namespace, name14, schemaRef, traits) => Schema.assign(new SimpleSchema(), {
11579
- name: name14,
11580
- namespace,
11581
- traits,
11582
- schemaRef
11583
- });
11584
11632
  }
11585
11633
  });
11586
11634
 
@@ -11624,6 +11672,8 @@ __export(schema_exports, {
11624
11672
  deserializerMiddlewareOption: () => deserializerMiddlewareOption,
11625
11673
  error: () => error,
11626
11674
  getSchemaSerdePlugin: () => getSchemaSerdePlugin,
11675
+ hydrate: () => hydrate,
11676
+ isStaticSchema: () => isStaticSchema,
11627
11677
  list: () => list,
11628
11678
  map: () => map,
11629
11679
  op: () => op,
@@ -12970,6 +13020,19 @@ var init_serde = __esm({
12970
13020
  }
12971
13021
  });
12972
13022
 
13023
+ // node_modules/@smithy/core/dist-es/submodules/protocols/SerdeContext.js
13024
+ var SerdeContext;
13025
+ var init_SerdeContext = __esm({
13026
+ "node_modules/@smithy/core/dist-es/submodules/protocols/SerdeContext.js"() {
13027
+ SerdeContext = class {
13028
+ serdeContext;
13029
+ setSerdeContext(serdeContext) {
13030
+ this.serdeContext = serdeContext;
13031
+ }
13032
+ };
13033
+ }
13034
+ });
13035
+
12973
13036
  // node_modules/@smithy/core/dist-es/submodules/event-streams/EventStreamSerde.js
12974
13037
  var import_util_utf8, EventStreamSerde;
12975
13038
  var init_EventStreamSerde = __esm({
@@ -13188,10 +13251,11 @@ var init_HttpProtocol = __esm({
13188
13251
  "node_modules/@smithy/core/dist-es/submodules/protocols/HttpProtocol.js"() {
13189
13252
  init_schema();
13190
13253
  import_protocol_http3 = __toESM(require_dist_cjs2());
13191
- HttpProtocol = class {
13254
+ init_SerdeContext();
13255
+ HttpProtocol = class extends SerdeContext {
13192
13256
  options;
13193
- serdeContext;
13194
13257
  constructor(options) {
13258
+ super();
13195
13259
  this.options = options;
13196
13260
  }
13197
13261
  getRequestType() {
@@ -13775,16 +13839,14 @@ var init_FromStringShapeDeserializer = __esm({
13775
13839
  init_serde();
13776
13840
  import_util_base64 = __toESM(require_dist_cjs12());
13777
13841
  import_util_utf82 = __toESM(require_dist_cjs11());
13842
+ init_SerdeContext();
13778
13843
  init_determineTimestampFormat();
13779
- FromStringShapeDeserializer = class {
13844
+ FromStringShapeDeserializer = class extends SerdeContext {
13780
13845
  settings;
13781
- serdeContext;
13782
13846
  constructor(settings) {
13847
+ super();
13783
13848
  this.settings = settings;
13784
13849
  }
13785
- setSerdeContext(serdeContext) {
13786
- this.serdeContext = serdeContext;
13787
- }
13788
13850
  read(_schema, data2) {
13789
13851
  const ns = NormalizedSchema.of(_schema);
13790
13852
  if (ns.isListSchema()) {
@@ -13848,12 +13910,13 @@ var init_HttpInterceptingShapeDeserializer = __esm({
13848
13910
  "node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeDeserializer.js"() {
13849
13911
  init_schema();
13850
13912
  import_util_utf83 = __toESM(require_dist_cjs11());
13913
+ init_SerdeContext();
13851
13914
  init_FromStringShapeDeserializer();
13852
- HttpInterceptingShapeDeserializer = class {
13915
+ HttpInterceptingShapeDeserializer = class extends SerdeContext {
13853
13916
  codecDeserializer;
13854
13917
  stringDeserializer;
13855
- serdeContext;
13856
13918
  constructor(codecDeserializer, codecSettings) {
13919
+ super();
13857
13920
  this.codecDeserializer = codecDeserializer;
13858
13921
  this.stringDeserializer = new FromStringShapeDeserializer(codecSettings);
13859
13922
  }
@@ -13896,17 +13959,15 @@ var init_ToStringShapeSerializer = __esm({
13896
13959
  init_schema();
13897
13960
  init_serde();
13898
13961
  import_util_base642 = __toESM(require_dist_cjs12());
13962
+ init_SerdeContext();
13899
13963
  init_determineTimestampFormat();
13900
- ToStringShapeSerializer = class {
13964
+ ToStringShapeSerializer = class extends SerdeContext {
13901
13965
  settings;
13902
13966
  stringBuffer = "";
13903
- serdeContext = void 0;
13904
13967
  constructor(settings) {
13968
+ super();
13905
13969
  this.settings = settings;
13906
13970
  }
13907
- setSerdeContext(serdeContext) {
13908
- this.serdeContext = serdeContext;
13909
- }
13910
13971
  write(schema, value) {
13911
13972
  const ns = NormalizedSchema.of(schema);
13912
13973
  switch (typeof value) {
@@ -14034,6 +14095,7 @@ __export(protocols_exports, {
14034
14095
  HttpProtocol: () => HttpProtocol,
14035
14096
  RequestBuilder: () => RequestBuilder,
14036
14097
  RpcProtocol: () => RpcProtocol,
14098
+ SerdeContext: () => SerdeContext,
14037
14099
  ToStringShapeSerializer: () => ToStringShapeSerializer,
14038
14100
  collectBody: () => collectBody,
14039
14101
  determineTimestampFormat: () => determineTimestampFormat,
@@ -14055,12 +14117,13 @@ var init_protocols = __esm({
14055
14117
  init_HttpInterceptingShapeSerializer();
14056
14118
  init_ToStringShapeSerializer();
14057
14119
  init_determineTimestampFormat();
14120
+ init_SerdeContext();
14058
14121
  }
14059
14122
  });
14060
14123
 
14061
- // node_modules/@smithy/core/dist-es/protocols/requestBuilder.js
14124
+ // node_modules/@smithy/core/dist-es/request-builder/requestBuilder.js
14062
14125
  var init_requestBuilder2 = __esm({
14063
- "node_modules/@smithy/core/dist-es/protocols/requestBuilder.js"() {
14126
+ "node_modules/@smithy/core/dist-es/request-builder/requestBuilder.js"() {
14064
14127
  init_protocols();
14065
14128
  }
14066
14129
  });
@@ -17015,13 +17078,13 @@ var init_parseCborBody = __esm({
17015
17078
  var import_util_base643, CborCodec, CborShapeSerializer, CborShapeDeserializer;
17016
17079
  var init_CborCodec = __esm({
17017
17080
  "node_modules/@smithy/core/dist-es/submodules/cbor/CborCodec.js"() {
17081
+ init_protocols();
17018
17082
  init_schema();
17019
17083
  init_serde();
17020
17084
  import_util_base643 = __toESM(require_dist_cjs12());
17021
17085
  init_cbor();
17022
17086
  init_parseCborBody();
17023
- CborCodec = class {
17024
- serdeContext;
17087
+ CborCodec = class extends SerdeContext {
17025
17088
  createSerializer() {
17026
17089
  const serializer = new CborShapeSerializer();
17027
17090
  serializer.setSerdeContext(this.serdeContext);
@@ -17032,16 +17095,9 @@ var init_CborCodec = __esm({
17032
17095
  deserializer.setSerdeContext(this.serdeContext);
17033
17096
  return deserializer;
17034
17097
  }
17035
- setSerdeContext(serdeContext) {
17036
- this.serdeContext = serdeContext;
17037
- }
17038
17098
  };
17039
- CborShapeSerializer = class {
17040
- serdeContext;
17099
+ CborShapeSerializer = class extends SerdeContext {
17041
17100
  value;
17042
- setSerdeContext(serdeContext) {
17043
- this.serdeContext = serdeContext;
17044
- }
17045
17101
  write(schema, value) {
17046
17102
  this.value = this.serialize(schema, value);
17047
17103
  }
@@ -17113,11 +17169,7 @@ var init_CborCodec = __esm({
17113
17169
  return buffer;
17114
17170
  }
17115
17171
  };
17116
- CborShapeDeserializer = class {
17117
- serdeContext;
17118
- setSerdeContext(serdeContext) {
17119
- this.serdeContext = serdeContext;
17120
- }
17172
+ CborShapeDeserializer = class extends SerdeContext {
17121
17173
  read(schema, bytes) {
17122
17174
  const data2 = cbor.deserialize(bytes);
17123
17175
  return this.readValue(schema, data2);
@@ -17982,13 +18034,16 @@ var require_dist_cjs27 = __commonJS({
17982
18034
  this.schema = closure._operationSchema;
17983
18035
  }
17984
18036
  resolveMiddleware(stack, configuration, options) {
18037
+ const op2 = closure._operationSchema;
18038
+ const input = op2?.[4] ?? op2?.input;
18039
+ const output = op2?.[5] ?? op2?.output;
17985
18040
  return this.resolveMiddlewareWithContext(stack, configuration, options, {
17986
18041
  CommandCtor: CommandRef,
17987
18042
  middlewareFn: closure._middlewareFn,
17988
18043
  clientName: closure._clientName,
17989
18044
  commandName: closure._commandName,
17990
- inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (closure._operationSchema ? schemaLogFilter.bind(null, closure._operationSchema.input) : (_2) => _2),
17991
- outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (closure._operationSchema ? schemaLogFilter.bind(null, closure._operationSchema.output) : (_2) => _2),
18045
+ inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op2 ? schemaLogFilter.bind(null, input) : (_2) => _2),
18046
+ outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op2 ? schemaLogFilter.bind(null, output) : (_2) => _2),
17992
18047
  smithyContext: closure._smithyContext,
17993
18048
  additionalContext: closure._additionalContext
17994
18049
  });
@@ -71941,6 +71996,28 @@ var init_out = __esm({
71941
71996
  });
71942
71997
 
71943
71998
  // src/agent/schemaUtils.js
71999
+ var schemaUtils_exports = {};
72000
+ __export(schemaUtils_exports, {
72001
+ JsonFixingAgent: () => JsonFixingAgent,
72002
+ MermaidFixingAgent: () => MermaidFixingAgent,
72003
+ cleanSchemaResponse: () => cleanSchemaResponse,
72004
+ createJsonCorrectionPrompt: () => createJsonCorrectionPrompt,
72005
+ createMermaidCorrectionPrompt: () => createMermaidCorrectionPrompt,
72006
+ createSchemaDefinitionCorrectionPrompt: () => createSchemaDefinitionCorrectionPrompt,
72007
+ decodeHtmlEntities: () => decodeHtmlEntities,
72008
+ extractMermaidFromMarkdown: () => extractMermaidFromMarkdown,
72009
+ isJsonSchema: () => isJsonSchema,
72010
+ isJsonSchemaDefinition: () => isJsonSchemaDefinition,
72011
+ isMermaidSchema: () => isMermaidSchema,
72012
+ processSchemaResponse: () => processSchemaResponse,
72013
+ replaceMermaidDiagramsInMarkdown: () => replaceMermaidDiagramsInMarkdown,
72014
+ tryMaidAutoFix: () => tryMaidAutoFix,
72015
+ validateAndFixMermaidResponse: () => validateAndFixMermaidResponse,
72016
+ validateJsonResponse: () => validateJsonResponse,
72017
+ validateMermaidDiagram: () => validateMermaidDiagram,
72018
+ validateMermaidResponse: () => validateMermaidResponse,
72019
+ validateXmlResponse: () => validateXmlResponse
72020
+ });
71944
72021
  function decodeHtmlEntities(text) {
71945
72022
  if (!text || typeof text !== "string") {
71946
72023
  return text;
@@ -71996,19 +72073,16 @@ function cleanSchemaResponse(response) {
71996
72073
  return trimmed.substring(startIndex, endIndex);
71997
72074
  }
71998
72075
  }
71999
- const firstBracket = Math.min(
72000
- trimmed.indexOf("{") >= 0 ? trimmed.indexOf("{") : Infinity,
72001
- trimmed.indexOf("[") >= 0 ? trimmed.indexOf("[") : Infinity
72002
- );
72003
- const lastBracket = Math.max(
72004
- trimmed.lastIndexOf("}"),
72005
- trimmed.lastIndexOf("]")
72006
- );
72007
- if (firstBracket < Infinity && lastBracket >= 0 && firstBracket < lastBracket) {
72008
- const beforeFirstBracket = trimmed.substring(0, firstBracket).trim();
72009
- if (beforeFirstBracket === "" || beforeFirstBracket.match(/^```\w*$/) || beforeFirstBracket.split("\n").length <= 2) {
72010
- return trimmed.substring(firstBracket, lastBracket + 1);
72011
- }
72076
+ let cleaned = trimmed;
72077
+ cleaned = cleaned.replace(/^```(?:json)?\s*\n?/i, "");
72078
+ cleaned = cleaned.replace(/\n?```\s*$/, "");
72079
+ cleaned = cleaned.trim();
72080
+ const firstChar = cleaned[0];
72081
+ const lastChar = cleaned[cleaned.length - 1];
72082
+ const isJsonObject = firstChar === "{" && lastChar === "}";
72083
+ const isJsonArray = firstChar === "[" && lastChar === "]";
72084
+ if (isJsonObject || isJsonArray) {
72085
+ return cleaned;
72012
72086
  }
72013
72087
  return response;
72014
72088
  }
@@ -72029,9 +72103,49 @@ function validateJsonResponse(response, options = {}) {
72029
72103
  }
72030
72104
  return { isValid: true, parsed };
72031
72105
  } catch (error2) {
72106
+ const positionMatch = error2.message.match(/position (\d+)/);
72107
+ let errorPosition = positionMatch ? parseInt(positionMatch[1], 10) : null;
72108
+ if (errorPosition === null) {
72109
+ const tokenMatch = error2.message.match(/Unexpected token '(.)', /);
72110
+ if (tokenMatch && tokenMatch[1]) {
72111
+ const problematicToken = tokenMatch[1];
72112
+ errorPosition = response.indexOf(problematicToken);
72113
+ }
72114
+ }
72115
+ let enhancedError = error2.message;
72116
+ let errorContext = null;
72117
+ if (errorPosition !== null && errorPosition >= 0 && response && response.length > 0) {
72118
+ const contextRadius = 50;
72119
+ const startPos = Math.max(0, errorPosition - contextRadius);
72120
+ const endPos = Math.min(response.length, errorPosition + contextRadius);
72121
+ const beforeError = response.substring(startPos, errorPosition);
72122
+ const atError = response[errorPosition] || "";
72123
+ const afterError = response.substring(errorPosition + 1, endPos);
72124
+ const snippet = beforeError + atError + afterError;
72125
+ const pointerOffset = beforeError.length;
72126
+ const pointer = " ".repeat(pointerOffset) + "^";
72127
+ errorContext = {
72128
+ position: errorPosition,
72129
+ snippet,
72130
+ pointer,
72131
+ beforeError,
72132
+ atError,
72133
+ afterError
72134
+ };
72135
+ enhancedError = `${error2.message}
72136
+
72137
+ Error location (position ${errorPosition}):
72138
+ ${snippet}
72139
+ ${pointer} here`;
72140
+ }
72032
72141
  if (debug) {
72033
72142
  console.log(`[DEBUG] JSON validation: Parse failed with error: ${error2.message}`);
72034
- console.log(`[DEBUG] JSON validation: Error at position: ${error2.message.match(/position (\d+)/) ? error2.message.match(/position (\d+)/)[1] : "unknown"}`);
72143
+ console.log(`[DEBUG] JSON validation: Error at position: ${errorPosition !== null ? errorPosition : "unknown"}`);
72144
+ if (errorContext) {
72145
+ console.log(`[DEBUG] JSON validation: Error context:
72146
+ ${errorContext.snippet}
72147
+ ${errorContext.pointer}`);
72148
+ }
72035
72149
  if (error2.message.includes("Unexpected token")) {
72036
72150
  console.log(`[DEBUG] JSON validation: Likely syntax error - unexpected character`);
72037
72151
  } else if (error2.message.includes("Unexpected end")) {
@@ -72040,8 +72154,72 @@ function validateJsonResponse(response, options = {}) {
72040
72154
  console.log(`[DEBUG] JSON validation: Likely unquoted property names`);
72041
72155
  }
72042
72156
  }
72043
- return { isValid: false, error: error2.message };
72157
+ return {
72158
+ isValid: false,
72159
+ error: error2.message,
72160
+ enhancedError,
72161
+ errorContext
72162
+ };
72163
+ }
72164
+ }
72165
+ function validateXmlResponse(response) {
72166
+ const xmlPattern = /<\/?[\w\s="'.-]+>/g;
72167
+ const tags = response.match(xmlPattern);
72168
+ if (!tags) {
72169
+ return { isValid: false, error: "No XML tags found" };
72044
72170
  }
72171
+ if (response.includes("<") && response.includes(">")) {
72172
+ return { isValid: true };
72173
+ }
72174
+ return { isValid: false, error: "Invalid XML structure" };
72175
+ }
72176
+ function processSchemaResponse(response, schema, options = {}) {
72177
+ const { validateJson = false, validateXml = false, debug = false } = options;
72178
+ if (debug) {
72179
+ console.log(`[DEBUG] Schema processing: Starting with response length ${response.length}`);
72180
+ console.log(`[DEBUG] Schema processing: Schema type detection...`);
72181
+ if (isJsonSchema(schema)) {
72182
+ console.log(`[DEBUG] Schema processing: Detected JSON schema`);
72183
+ } else {
72184
+ console.log(`[DEBUG] Schema processing: Non-JSON schema detected`);
72185
+ }
72186
+ }
72187
+ const cleanStart = Date.now();
72188
+ const cleaned = cleanSchemaResponse(response);
72189
+ const cleanTime = Date.now() - cleanStart;
72190
+ const result = { cleaned };
72191
+ if (debug) {
72192
+ console.log(`[DEBUG] Schema processing: Cleaning completed in ${cleanTime}ms`);
72193
+ result.debug = {
72194
+ originalLength: response.length,
72195
+ cleanedLength: cleaned.length,
72196
+ wasModified: response !== cleaned,
72197
+ cleaningTimeMs: cleanTime,
72198
+ removedContent: response !== cleaned ? {
72199
+ before: response.substring(0, 100) + (response.length > 100 ? "..." : ""),
72200
+ after: cleaned.substring(0, 100) + (cleaned.length > 100 ? "..." : "")
72201
+ } : null
72202
+ };
72203
+ if (response !== cleaned) {
72204
+ console.log(`[DEBUG] Schema processing: Response was modified during cleaning`);
72205
+ console.log(`[DEBUG] Schema processing: Original length: ${response.length}, cleaned length: ${cleaned.length}`);
72206
+ } else {
72207
+ console.log(`[DEBUG] Schema processing: Response unchanged during cleaning`);
72208
+ }
72209
+ }
72210
+ if (validateJson) {
72211
+ if (debug) {
72212
+ console.log(`[DEBUG] Schema processing: Running JSON validation...`);
72213
+ }
72214
+ result.jsonValidation = validateJsonResponse(cleaned, { debug });
72215
+ }
72216
+ if (validateXml) {
72217
+ if (debug) {
72218
+ console.log(`[DEBUG] Schema processing: Running XML validation...`);
72219
+ }
72220
+ result.xmlValidation = validateXmlResponse(cleaned);
72221
+ }
72222
+ return result;
72045
72223
  }
72046
72224
  function isJsonSchema(schema) {
72047
72225
  if (!schema || typeof schema !== "string") {
@@ -72101,7 +72279,16 @@ function isJsonSchemaDefinition(jsonString, options = {}) {
72101
72279
  return false;
72102
72280
  }
72103
72281
  }
72104
- function createJsonCorrectionPrompt(invalidResponse, schema, error2, retryCount = 0) {
72282
+ function createJsonCorrectionPrompt(invalidResponse, schema, errorOrValidation, retryCount = 0) {
72283
+ let errorMessage;
72284
+ let enhancedError;
72285
+ if (typeof errorOrValidation === "object" && errorOrValidation !== null) {
72286
+ errorMessage = errorOrValidation.error;
72287
+ enhancedError = errorOrValidation.enhancedError || errorMessage;
72288
+ } else {
72289
+ errorMessage = errorOrValidation;
72290
+ enhancedError = errorMessage;
72291
+ }
72105
72292
  const strengthLevels = [
72106
72293
  {
72107
72294
  prefix: "CRITICAL JSON ERROR:",
@@ -72125,7 +72312,7 @@ function createJsonCorrectionPrompt(invalidResponse, schema, error2, retryCount
72125
72312
 
72126
72313
  ${invalidResponse.substring(0, 500)}${invalidResponse.length > 500 ? "..." : ""}
72127
72314
 
72128
- Error: ${error2}
72315
+ Error: ${enhancedError}
72129
72316
 
72130
72317
  ${currentLevel.instruction}
72131
72318
 
@@ -72170,6 +72357,28 @@ ${currentLevel.example}
72170
72357
  Return ONLY the JSON data object/array that follows the schema structure. NO schema definitions, NO explanations, NO markdown formatting.`;
72171
72358
  return prompt;
72172
72359
  }
72360
+ function isMermaidSchema(schema) {
72361
+ if (!schema || typeof schema !== "string") {
72362
+ return false;
72363
+ }
72364
+ const trimmedSchema = schema.trim().toLowerCase();
72365
+ const mermaidIndicators = [
72366
+ trimmedSchema.includes("mermaid"),
72367
+ trimmedSchema.includes("diagram"),
72368
+ trimmedSchema.includes("flowchart"),
72369
+ trimmedSchema.includes("sequence"),
72370
+ trimmedSchema.includes("gantt"),
72371
+ trimmedSchema.includes("pie chart"),
72372
+ trimmedSchema.includes("state diagram"),
72373
+ trimmedSchema.includes("class diagram"),
72374
+ trimmedSchema.includes("entity relationship"),
72375
+ trimmedSchema.includes("user journey"),
72376
+ trimmedSchema.includes("git graph"),
72377
+ trimmedSchema.includes("requirement diagram"),
72378
+ trimmedSchema.includes("c4 context")
72379
+ ];
72380
+ return mermaidIndicators.some((indicator) => indicator);
72381
+ }
72173
72382
  function extractMermaidFromMarkdown(response) {
72174
72383
  if (!response || typeof response !== "string") {
72175
72384
  return { diagrams: [], cleanedResponse: response };
@@ -72190,6 +72399,24 @@ function extractMermaidFromMarkdown(response) {
72190
72399
  }
72191
72400
  return { diagrams, cleanedResponse: response };
72192
72401
  }
72402
+ function replaceMermaidDiagramsInMarkdown(originalResponse, correctedDiagrams) {
72403
+ if (!originalResponse || typeof originalResponse !== "string") {
72404
+ return originalResponse;
72405
+ }
72406
+ if (!correctedDiagrams || correctedDiagrams.length === 0) {
72407
+ return originalResponse;
72408
+ }
72409
+ let modifiedResponse = originalResponse;
72410
+ const sortedDiagrams = [...correctedDiagrams].sort((a3, b3) => b3.startIndex - a3.startIndex);
72411
+ for (const diagram of sortedDiagrams) {
72412
+ const attributesStr = diagram.attributes ? ` ${diagram.attributes}` : "";
72413
+ const newCodeBlock = `\`\`\`mermaid${attributesStr}
72414
+ ${diagram.content}
72415
+ \`\`\``;
72416
+ modifiedResponse = modifiedResponse.slice(0, diagram.startIndex) + newCodeBlock + modifiedResponse.slice(diagram.endIndex);
72417
+ }
72418
+ return modifiedResponse;
72419
+ }
72193
72420
  async function validateMermaidDiagram(diagram) {
72194
72421
  if (!diagram || typeof diagram !== "string") {
72195
72422
  return { isValid: false, error: "Empty or invalid diagram input" };
@@ -72256,6 +72483,45 @@ async function validateMermaidResponse(response) {
72256
72483
  errors: errors.length > 0 ? errors : void 0
72257
72484
  };
72258
72485
  }
72486
+ function createMermaidCorrectionPrompt(invalidResponse, schema, errors, diagrams) {
72487
+ let prompt = `Your previous response contains invalid Mermaid diagrams that cannot be parsed. Here's what you returned:
72488
+
72489
+ ${invalidResponse}
72490
+
72491
+ Validation Errors:`;
72492
+ errors.forEach((error2, index) => {
72493
+ prompt += `
72494
+ ${index + 1}. ${error2}`;
72495
+ });
72496
+ if (diagrams && diagrams.length > 0) {
72497
+ prompt += `
72498
+
72499
+ Diagram Details:`;
72500
+ diagrams.forEach((diagramResult, index) => {
72501
+ if (!diagramResult.isValid) {
72502
+ prompt += `
72503
+
72504
+ Diagram ${index + 1}:`;
72505
+ const diagramContent = diagramResult.content || diagramResult.diagram || "";
72506
+ prompt += `
72507
+ - Content: ${diagramContent.substring(0, 100)}${diagramContent.length > 100 ? "..." : ""}`;
72508
+ prompt += `
72509
+ - Error: ${diagramResult.error}`;
72510
+ if (diagramResult.detailedError && diagramResult.detailedError !== diagramResult.error) {
72511
+ prompt += `
72512
+ - Details: ${diagramResult.detailedError}`;
72513
+ }
72514
+ }
72515
+ });
72516
+ }
72517
+ prompt += `
72518
+
72519
+ Please correct your response to include valid Mermaid diagrams that match this schema:
72520
+ ${schema}
72521
+
72522
+ Ensure all Mermaid diagrams are properly formatted within \`\`\`mermaid code blocks and follow correct Mermaid syntax.`;
72523
+ return prompt;
72524
+ }
72259
72525
  async function tryMaidAutoFix(diagramContent, options = {}) {
72260
72526
  const { debug = false } = options;
72261
72527
  try {
@@ -72565,7 +72831,7 @@ ${fixedContent}
72565
72831
  };
72566
72832
  }
72567
72833
  }
72568
- var HTML_ENTITY_MAP, MermaidFixingAgent;
72834
+ var HTML_ENTITY_MAP, JsonFixingAgent, MermaidFixingAgent;
72569
72835
  var init_schemaUtils = __esm({
72570
72836
  "src/agent/schemaUtils.js"() {
72571
72837
  "use strict";
@@ -72581,6 +72847,156 @@ var init_schemaUtils = __esm({
72581
72847
  // Also handle XML/HTML5 apostrophe entity
72582
72848
  "&nbsp;": " "
72583
72849
  };
72850
+ JsonFixingAgent = class {
72851
+ constructor(options = {}) {
72852
+ this.ProbeAgent = null;
72853
+ this.options = {
72854
+ sessionId: options.sessionId || `json-fixer-${Date.now()}`,
72855
+ path: options.path || process.cwd(),
72856
+ provider: options.provider,
72857
+ model: options.model,
72858
+ debug: options.debug,
72859
+ tracer: options.tracer,
72860
+ // Set to false since we're only fixing JSON syntax, not implementing code
72861
+ allowEdit: false
72862
+ };
72863
+ }
72864
+ /**
72865
+ * Get the specialized prompt for JSON fixing
72866
+ */
72867
+ getJsonFixingPrompt() {
72868
+ return `You are a world-class JSON syntax correction specialist. Your expertise lies in analyzing and fixing JSON syntax errors while preserving the original data structure and intent.
72869
+
72870
+ CORE RESPONSIBILITIES:
72871
+ - Analyze JSON for syntax errors and structural issues
72872
+ - Fix syntax errors while maintaining the original data's semantic meaning
72873
+ - Ensure JSON follows proper RFC 8259 specification
72874
+ - Handle all JSON structures: objects, arrays, primitives, nested structures
72875
+
72876
+ JSON SYNTAX RULES:
72877
+ 1. **Property names**: Must be enclosed in double quotes
72878
+ 2. **String values**: Must use double quotes (not single quotes)
72879
+ 3. **Numbers**: Can be integers or decimals, no quotes needed
72880
+ 4. **Booleans**: true or false (lowercase, no quotes)
72881
+ 5. **Null**: null (lowercase, no quotes)
72882
+ 6. **Arrays**: Comma-separated values in square brackets [...]
72883
+ 7. **Objects**: Comma-separated key-value pairs in curly braces {...}
72884
+ 8. **No trailing commas**: Last item in array/object must not have a trailing comma
72885
+ 9. **Escape sequences**: Special characters must be escaped (\\n, \\t, \\", \\\\, etc.)
72886
+
72887
+ COMMON ERRORS TO FIX:
72888
+ 1. **Unquoted property names**: {name: "value"} \u2192 {"name": "value"}
72889
+ 2. **Single quotes**: {'key': 'value'} \u2192 {"key": "value"}
72890
+ 3. **Trailing commas**: {"a": 1,} \u2192 {"a": 1}
72891
+ 4. **Unquoted strings**: {key: value} \u2192 {"key": "value"}
72892
+ 5. **Missing commas**: {"a": 1 "b": 2} \u2192 {"a": 1, "b": 2}
72893
+ 6. **Extra commas**: {"a": 1,, "b": 2} \u2192 {"a": 1, "b": 2}
72894
+ 7. **Unclosed brackets/braces**: {"key": "value" \u2192 {"key": "value"}
72895
+ 8. **Invalid escape sequences**: Fix or remove
72896
+ 9. **Comments**: Remove // or /* */ comments (not allowed in JSON)
72897
+ 10. **Undefined values**: Replace undefined with null
72898
+
72899
+ FIXING METHODOLOGY:
72900
+ 1. **Identify the error location** from the error message
72901
+ 2. **Analyze the context** around the error
72902
+ 3. **Apply the appropriate fix** based on JSON syntax rules
72903
+ 4. **Preserve data intent** - never change the meaning of the data
72904
+ 5. **Validate the result** - ensure it's parseable JSON
72905
+
72906
+ CRITICAL RULES:
72907
+ - ALWAYS output only the corrected JSON
72908
+ - NEVER add explanations, comments, or additional text
72909
+ - NEVER wrap in markdown code blocks (no \`\`\`json)
72910
+ - PRESERVE the original data structure and values
72911
+ - FIX only syntax errors, don't modify the data itself
72912
+ - ENSURE the output is valid, parseable JSON
72913
+
72914
+ When presented with broken JSON, analyze it thoroughly and provide the corrected version that maintains the original intent while fixing all syntax issues.`;
72915
+ }
72916
+ /**
72917
+ * Initialize the ProbeAgent if not already done
72918
+ */
72919
+ async initializeAgent() {
72920
+ if (!this.ProbeAgent) {
72921
+ const { ProbeAgent: ProbeAgent2 } = await Promise.resolve().then(() => (init_ProbeAgent(), ProbeAgent_exports));
72922
+ this.ProbeAgent = ProbeAgent2;
72923
+ }
72924
+ if (!this.agent) {
72925
+ this.agent = new this.ProbeAgent({
72926
+ sessionId: this.options.sessionId,
72927
+ customPrompt: this.getJsonFixingPrompt(),
72928
+ path: this.options.path,
72929
+ provider: this.options.provider,
72930
+ model: this.options.model,
72931
+ debug: this.options.debug,
72932
+ tracer: this.options.tracer,
72933
+ allowEdit: this.options.allowEdit,
72934
+ maxIterations: 5,
72935
+ // Allow multiple iterations for JSON fixing
72936
+ disableJsonValidation: true
72937
+ // CRITICAL: Disable JSON validation in nested agent to prevent infinite recursion
72938
+ });
72939
+ }
72940
+ return this.agent;
72941
+ }
72942
+ /**
72943
+ * Fix invalid JSON using the specialized agent
72944
+ * @param {string} invalidJson - The broken JSON string
72945
+ * @param {string} schema - The original schema for context
72946
+ * @param {Object} validationResult - Validation result with error details
72947
+ * @param {number} attemptNumber - Current attempt number (for logging)
72948
+ * @returns {Promise<string>} - The corrected JSON
72949
+ */
72950
+ async fixJson(invalidJson, schema, validationResult, attemptNumber = 1) {
72951
+ await this.initializeAgent();
72952
+ let errorContext = validationResult.error;
72953
+ if (validationResult.enhancedError) {
72954
+ errorContext = validationResult.enhancedError;
72955
+ }
72956
+ const prompt = `Fix the following invalid JSON.
72957
+
72958
+ Error: ${errorContext}
72959
+
72960
+ Invalid JSON:
72961
+ ${invalidJson}
72962
+
72963
+ Expected schema structure:
72964
+ ${schema}
72965
+
72966
+ Provide only the corrected JSON without any markdown formatting or explanations.`;
72967
+ try {
72968
+ if (this.options.debug) {
72969
+ console.log(`[DEBUG] JSON fixing: Attempt ${attemptNumber} to fix JSON with separate agent`);
72970
+ }
72971
+ const result = await this.agent.answer(prompt, []);
72972
+ const cleaned = cleanSchemaResponse(result);
72973
+ if (this.options.debug) {
72974
+ console.log(`[DEBUG] JSON fixing: Agent returned ${cleaned.length} chars`);
72975
+ }
72976
+ return cleaned;
72977
+ } catch (error2) {
72978
+ if (this.options.debug) {
72979
+ console.error(`[DEBUG] JSON fixing failed: ${error2.message}`);
72980
+ }
72981
+ throw new Error(`Failed to fix JSON: ${error2.message}`);
72982
+ }
72983
+ }
72984
+ /**
72985
+ * Get token usage information from the specialized agent
72986
+ * @returns {Object} - Token usage statistics
72987
+ */
72988
+ getTokenUsage() {
72989
+ return this.agent ? this.agent.getTokenUsage() : null;
72990
+ }
72991
+ /**
72992
+ * Cancel any ongoing operations
72993
+ */
72994
+ cancel() {
72995
+ if (this.agent) {
72996
+ this.agent.cancel();
72997
+ }
72998
+ }
72999
+ };
72584
73000
  MermaidFixingAgent = class {
72585
73001
  constructor(options = {}) {
72586
73002
  this.ProbeAgent = null;
@@ -73573,6 +73989,7 @@ var init_ProbeAgent = __esm({
73573
73989
  * @param {number} [options.maxResponseTokens] - Maximum tokens for AI responses
73574
73990
  * @param {number} [options.maxIterations] - Maximum tool iterations (overrides MAX_TOOL_ITERATIONS env var)
73575
73991
  * @param {boolean} [options.disableMermaidValidation=false] - Disable automatic mermaid diagram validation and fixing
73992
+ * @param {boolean} [options.disableJsonValidation=false] - Disable automatic JSON validation and fixing (prevents infinite recursion in JsonFixingAgent)
73576
73993
  * @param {boolean} [options.enableMcp=false] - Enable MCP tool integration
73577
73994
  * @param {string} [options.mcpConfigPath] - Path to MCP configuration file
73578
73995
  * @param {Object} [options.mcpConfig] - MCP configuration object (overrides mcpConfigPath)
@@ -73592,6 +74009,7 @@ var init_ProbeAgent = __esm({
73592
74009
  this.maxResponseTokens = options.maxResponseTokens || parseInt(process.env.MAX_RESPONSE_TOKENS || "0", 10) || null;
73593
74010
  this.maxIterations = options.maxIterations || null;
73594
74011
  this.disableMermaidValidation = !!options.disableMermaidValidation;
74012
+ this.disableJsonValidation = !!options.disableJsonValidation;
73595
74013
  this.storageAdapter = options.storageAdapter || new InMemoryStorageAdapter();
73596
74014
  this.hooks = new HookManager();
73597
74015
  if (options.hooks) {
@@ -74806,15 +75224,16 @@ Remember: Use proper XML format with BOTH opening and closing tags:
74806
75224
  <parameter>value</parameter>
74807
75225
  </tool_name>
74808
75226
 
74809
- IMPORTANT: A schema was provided. You MUST respond with data that matches this schema.
74810
- Use attempt_completion with your response directly inside the tags:
75227
+ IMPORTANT: A schema was provided for the final output format. You have two options:
74811
75228
 
75229
+ Option 1 - Use attempt_completion with your complete answer:
74812
75230
  <attempt_completion>
74813
- [Your response content matching the provided schema format]
75231
+ [Your complete answer here - will be automatically formatted to match the schema]
74814
75232
  </attempt_completion>
74815
75233
 
74816
- Your response must conform to this schema:
74817
- ${options.schema}`;
75234
+ Option 2 - Provide a natural response without any tool, and it will be automatically formatted.
75235
+
75236
+ Do NOT try to format your response as JSON yourself - this will be done automatically.`;
74818
75237
  } else {
74819
75238
  reminderContent = `Please use one of the available tools to help answer the question, or use attempt_completion if you have enough information to provide a final answer.
74820
75239
 
@@ -74961,6 +75380,10 @@ Convert your previous response content into actual JSON data that follows this s
74961
75380
  console.log(`[DEBUG] JSON validation: Starting validation process for schema response`);
74962
75381
  console.log(`[DEBUG] JSON validation: Response length: ${finalResult.length} chars`);
74963
75382
  }
75383
+ finalResult = cleanSchemaResponse(finalResult);
75384
+ if (this.debug) {
75385
+ console.log(`[DEBUG] JSON validation: After cleaning, length: ${finalResult.length} chars`);
75386
+ }
74964
75387
  if (this.tracer) {
74965
75388
  this.tracer.recordJsonValidationEvent("started", {
74966
75389
  "json_validation.response_length": finalResult.length,
@@ -74972,75 +75395,66 @@ Convert your previous response content into actual JSON data that follows this s
74972
75395
  const maxRetries = 3;
74973
75396
  if (validation.isValid && isJsonSchemaDefinition(finalResult, { debug: this.debug })) {
74974
75397
  if (this.debug) {
74975
- console.log(`[DEBUG] JSON validation: Response is a JSON schema definition instead of data, correcting...`);
75398
+ console.log(`[DEBUG] JSON validation: Response is a JSON schema definition instead of data, needs correction...`);
74976
75399
  }
74977
- const schemaDefinitionPrompt = createSchemaDefinitionCorrectionPrompt(
74978
- finalResult,
74979
- options.schema,
74980
- 0
74981
- );
74982
- finalResult = await this.answer(schemaDefinitionPrompt, [], {
74983
- ...options,
74984
- _schemaFormatted: true
74985
- });
74986
- finalResult = cleanSchemaResponse(finalResult);
74987
- validation = validateJsonResponse(finalResult);
74988
- retryCount = 1;
75400
+ validation = {
75401
+ isValid: false,
75402
+ error: "Response is a JSON schema definition instead of actual data",
75403
+ enhancedError: "Response is a JSON schema definition instead of actual data. Please return data that conforms to the schema, not the schema itself."
75404
+ };
74989
75405
  }
74990
- while (!validation.isValid && retryCount < maxRetries) {
75406
+ if (!validation.isValid) {
74991
75407
  if (this.debug) {
74992
- console.log(`[DEBUG] JSON validation: Validation failed (attempt ${retryCount + 1}/${maxRetries}):`, validation.error);
74993
- console.log(`[DEBUG] JSON validation: Invalid response sample: ${finalResult.substring(0, 300)}${finalResult.length > 300 ? "..." : ""}`);
75408
+ console.log(`[DEBUG] JSON validation: Starting separate JsonFixingAgent session...`);
74994
75409
  }
74995
- let correctionPrompt;
74996
- try {
74997
- if (isJsonSchemaDefinition(finalResult, { debug: this.debug })) {
74998
- if (this.debug) {
74999
- console.log(`[DEBUG] JSON validation: Response is still a schema definition, using specialized correction`);
75000
- }
75001
- correctionPrompt = createSchemaDefinitionCorrectionPrompt(
75002
- finalResult,
75003
- options.schema,
75004
- retryCount
75005
- );
75006
- } else {
75007
- correctionPrompt = createJsonCorrectionPrompt(
75008
- finalResult,
75410
+ const { JsonFixingAgent: JsonFixingAgent2 } = await Promise.resolve().then(() => (init_schemaUtils(), schemaUtils_exports));
75411
+ const jsonFixer = new JsonFixingAgent2({
75412
+ path: this.allowedFolders[0],
75413
+ provider: this.clientApiProvider,
75414
+ model: this.model,
75415
+ debug: this.debug,
75416
+ tracer: this.tracer
75417
+ });
75418
+ let currentResult = finalResult;
75419
+ let currentValidation = validation;
75420
+ while (!currentValidation.isValid && retryCount < maxRetries) {
75421
+ if (this.debug) {
75422
+ console.log(`[DEBUG] JSON validation: Validation failed (attempt ${retryCount + 1}/${maxRetries}):`, currentValidation.error);
75423
+ console.log(`[DEBUG] JSON validation: Invalid response sample: ${currentResult.substring(0, 300)}${currentResult.length > 300 ? "..." : ""}`);
75424
+ }
75425
+ try {
75426
+ currentResult = await jsonFixer.fixJson(
75427
+ currentResult,
75009
75428
  options.schema,
75010
- validation.error,
75011
- retryCount
75429
+ currentValidation,
75430
+ retryCount + 1
75012
75431
  );
75432
+ currentValidation = validateJsonResponse(currentResult, { debug: this.debug });
75433
+ retryCount++;
75434
+ if (this.debug) {
75435
+ if (!currentValidation.isValid && retryCount < maxRetries) {
75436
+ console.log(`[DEBUG] JSON validation: Still invalid after correction ${retryCount}, retrying...`);
75437
+ console.log(`[DEBUG] JSON validation: Corrected response sample: ${currentResult.substring(0, 300)}${currentResult.length > 300 ? "..." : ""}`);
75438
+ } else if (currentValidation.isValid) {
75439
+ console.log(`[DEBUG] JSON validation: Successfully corrected after ${retryCount} attempts with JsonFixingAgent`);
75440
+ }
75441
+ }
75442
+ } catch (error2) {
75443
+ if (this.debug) {
75444
+ console.error(`[DEBUG] JSON validation: JsonFixingAgent error on attempt ${retryCount + 1}:`, error2.message);
75445
+ }
75446
+ break;
75013
75447
  }
75014
- } catch (error2) {
75015
- correctionPrompt = createJsonCorrectionPrompt(
75016
- finalResult,
75017
- options.schema,
75018
- validation.error,
75019
- retryCount
75020
- );
75021
75448
  }
75022
- finalResult = await this.answer(correctionPrompt, [], {
75023
- ...options,
75024
- _schemaFormatted: true
75025
- });
75026
- finalResult = cleanSchemaResponse(finalResult);
75027
- validation = validateJsonResponse(finalResult, { debug: this.debug });
75028
- retryCount++;
75029
- if (this.debug) {
75030
- if (!validation.isValid && retryCount < maxRetries) {
75031
- console.log(`[DEBUG] JSON validation: Still invalid after correction ${retryCount}, retrying...`);
75032
- console.log(`[DEBUG] JSON validation: Corrected response sample: ${finalResult.substring(0, 300)}${finalResult.length > 300 ? "..." : ""}`);
75033
- } else if (validation.isValid) {
75034
- console.log(`[DEBUG] JSON validation: Successfully corrected after ${retryCount} attempts`);
75035
- }
75449
+ finalResult = currentResult;
75450
+ validation = currentValidation;
75451
+ if (!validation.isValid && this.debug) {
75452
+ console.log(`[DEBUG] JSON validation: Still invalid after ${maxRetries} correction attempts with JsonFixingAgent:`, validation.error);
75453
+ console.log(`[DEBUG] JSON validation: Final invalid response: ${finalResult.substring(0, 500)}${finalResult.length > 500 ? "..." : ""}`);
75454
+ } else if (validation.isValid && this.debug) {
75455
+ console.log(`[DEBUG] JSON validation: Final validation successful`);
75036
75456
  }
75037
75457
  }
75038
- if (!validation.isValid && this.debug) {
75039
- console.log(`[DEBUG] JSON validation: Still invalid after ${maxRetries} correction attempts:`, validation.error);
75040
- console.log(`[DEBUG] JSON validation: Final invalid response: ${finalResult.substring(0, 500)}${finalResult.length > 500 ? "..." : ""}`);
75041
- } else if (validation.isValid && this.debug) {
75042
- console.log(`[DEBUG] JSON validation: Final validation successful`);
75043
- }
75044
75458
  if (this.tracer) {
75045
75459
  this.tracer.recordJsonValidationEvent("completed", {
75046
75460
  "json_validation.success": validation.isValid,
@@ -75288,6 +75702,7 @@ Convert your previous response content into actual JSON data that follows this s
75288
75702
  maxResponseTokens: this.maxResponseTokens,
75289
75703
  maxIterations: this.maxIterations,
75290
75704
  disableMermaidValidation: this.disableMermaidValidation,
75705
+ disableJsonValidation: this.disableJsonValidation,
75291
75706
  enableMcp: !!this.mcpBridge,
75292
75707
  mcpConfig: this.mcpConfig,
75293
75708
  enableBash: this.enableBash,
@@ -75306,11 +75721,44 @@ Convert your previous response content into actual JSON data that follows this s
75306
75721
  }
75307
75722
  /**
75308
75723
  * Internal method to strip internal/temporary messages from history
75309
- * Removes: schema reminders, mermaid fix prompts, tool use reminders, etc.
75310
- * Keeps: system message, user messages, assistant responses, tool results
75724
+ * Strategy: Find the FIRST schema-related message and truncate everything from that point onwards.
75725
+ * This ensures that all schema formatting iterations (IMPORTANT, CRITICAL, corrections, etc.) are removed.
75726
+ * Keeps: system message, user messages, assistant responses, tool results up to the first schema message
75311
75727
  * @private
75312
75728
  */
75313
75729
  _stripInternalMessages(history, keepSystemMessage = true) {
75730
+ let firstSchemaMessageIndex = -1;
75731
+ for (let i3 = 0; i3 < history.length; i3++) {
75732
+ const message = history[i3];
75733
+ if (message.role === "system") {
75734
+ continue;
75735
+ }
75736
+ if (this._isSchemaMessage(message)) {
75737
+ firstSchemaMessageIndex = i3;
75738
+ if (this.debug) {
75739
+ console.log(`[DEBUG] Found first schema message at index ${i3}, truncating from here`);
75740
+ }
75741
+ break;
75742
+ }
75743
+ }
75744
+ if (firstSchemaMessageIndex === -1) {
75745
+ return this._stripNonSchemaInternalMessages(history, keepSystemMessage);
75746
+ }
75747
+ const truncated = history.slice(0, firstSchemaMessageIndex);
75748
+ const filtered = this._stripNonSchemaInternalMessages(truncated, keepSystemMessage);
75749
+ if (this.debug) {
75750
+ const removedCount = history.length - filtered.length;
75751
+ console.log(`[DEBUG] Truncated at schema message (index ${firstSchemaMessageIndex}) and filtered non-schema internal messages`);
75752
+ console.log(`[DEBUG] Removed ${removedCount} messages total (${history.length} \u2192 ${filtered.length})`);
75753
+ }
75754
+ return filtered;
75755
+ }
75756
+ /**
75757
+ * Strip non-schema internal messages (mermaid fixes, tool reminders, etc.) individually
75758
+ * Used when no schema messages are present in history
75759
+ * @private
75760
+ */
75761
+ _stripNonSchemaInternalMessages(history, keepSystemMessage = true) {
75314
75762
  const filtered = [];
75315
75763
  for (let i3 = 0; i3 < history.length; i3++) {
75316
75764
  const message = history[i3];
@@ -75322,9 +75770,9 @@ Convert your previous response content into actual JSON data that follows this s
75322
75770
  }
75323
75771
  continue;
75324
75772
  }
75325
- if (this._isInternalMessage(message, i3, history)) {
75773
+ if (this._isNonSchemaInternalMessage(message)) {
75326
75774
  if (this.debug) {
75327
- console.log(`[DEBUG] Stripping internal message at index ${i3}: ${message.role}`);
75775
+ console.log(`[DEBUG] Stripping non-schema internal message at index ${i3}: ${message.role}`);
75328
75776
  }
75329
75777
  continue;
75330
75778
  }
@@ -75333,20 +75781,50 @@ Convert your previous response content into actual JSON data that follows this s
75333
75781
  return filtered;
75334
75782
  }
75335
75783
  /**
75336
- * Determine if a message is an internal/temporary message
75784
+ * Check if a message is schema-related (IMPORTANT, CRITICAL, etc.)
75337
75785
  * @private
75338
75786
  */
75339
- _isInternalMessage(message, index, history) {
75787
+ _isSchemaMessage(message) {
75340
75788
  if (message.role !== "user") {
75341
75789
  return false;
75342
75790
  }
75343
75791
  if (!message.content) {
75344
75792
  return false;
75345
75793
  }
75346
- const content = typeof message.content === "string" ? message.content : JSON.stringify(message.content);
75347
- if (content.includes("IMPORTANT: A schema was provided") || content.includes("You MUST respond with data that matches this schema") || content.includes("Your response must conform to this schema:")) {
75794
+ let content;
75795
+ try {
75796
+ content = typeof message.content === "string" ? message.content : JSON.stringify(message.content);
75797
+ } catch (error2) {
75798
+ if (this.debug) {
75799
+ console.log(`[DEBUG] Could not stringify message content in _isSchemaMessage: ${error2.message}`);
75800
+ }
75801
+ return false;
75802
+ }
75803
+ if (content.includes("IMPORTANT: A schema was provided") || content.includes("You MUST respond with data that matches this schema") || content.includes("Your response must conform to this schema:") || content.includes("CRITICAL: You MUST respond with ONLY valid JSON DATA") || content.includes("Schema to follow (this is just the structure")) {
75348
75804
  return true;
75349
75805
  }
75806
+ return false;
75807
+ }
75808
+ /**
75809
+ * Check if a message is a non-schema internal message (mermaid, tool reminders, JSON corrections)
75810
+ * @private
75811
+ */
75812
+ _isNonSchemaInternalMessage(message) {
75813
+ if (message.role !== "user") {
75814
+ return false;
75815
+ }
75816
+ if (!message.content) {
75817
+ return false;
75818
+ }
75819
+ let content;
75820
+ try {
75821
+ content = typeof message.content === "string" ? message.content : JSON.stringify(message.content);
75822
+ } catch (error2) {
75823
+ if (this.debug) {
75824
+ console.log(`[DEBUG] Could not stringify message content in _isNonSchemaInternalMessage: ${error2.message}`);
75825
+ }
75826
+ return false;
75827
+ }
75350
75828
  if (content.includes("Please use one of the available tools") && content.includes("or use attempt_completion") && content.includes("Remember: Use proper XML format")) {
75351
75829
  return true;
75352
75830
  }