@probelabs/probe 0.6.0-rc131 → 0.6.0-rc132

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.
@@ -2074,7 +2074,7 @@ var require_dist_cjs15 = __commonJS({
2074
2074
  const registerTimeout = (offset) => {
2075
2075
  const timeoutId = timing.setTimeout(() => {
2076
2076
  request.destroy();
2077
- reject2(Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), {
2077
+ 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.`), {
2078
2078
  name: "TimeoutError"
2079
2079
  }));
2080
2080
  }, timeoutInMs - offset);
@@ -2099,6 +2099,25 @@ var require_dist_cjs15 = __commonJS({
2099
2099
  }
2100
2100
  return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME$2), DEFER_EVENT_LISTENER_TIME$2);
2101
2101
  };
2102
+ var setRequestTimeout = (req, reject2, timeoutInMs = 0, throwOnRequestTimeout, logger2) => {
2103
+ if (timeoutInMs) {
2104
+ return timing.setTimeout(() => {
2105
+ let msg = `@smithy/node-http-handler - [${throwOnRequestTimeout ? "ERROR" : "WARN"}] a request has exceeded the configured ${timeoutInMs} ms requestTimeout.`;
2106
+ if (throwOnRequestTimeout) {
2107
+ const error2 = Object.assign(new Error(msg), {
2108
+ name: "TimeoutError",
2109
+ code: "ETIMEDOUT"
2110
+ });
2111
+ req.destroy(error2);
2112
+ reject2(error2);
2113
+ } else {
2114
+ msg += ` Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.`;
2115
+ logger2?.warn?.(msg);
2116
+ }
2117
+ }, timeoutInMs);
2118
+ }
2119
+ return -1;
2120
+ };
2102
2121
  var DEFER_EVENT_LISTENER_TIME$1 = 3e3;
2103
2122
  var setSocketKeepAlive = (request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME$1) => {
2104
2123
  if (keepAlive !== true) {
@@ -2120,12 +2139,12 @@ var require_dist_cjs15 = __commonJS({
2120
2139
  return timing.setTimeout(registerListener, deferTimeMs);
2121
2140
  };
2122
2141
  var DEFER_EVENT_LISTENER_TIME = 3e3;
2123
- var setSocketTimeout = (request, reject2, timeoutInMs = DEFAULT_REQUEST_TIMEOUT) => {
2142
+ var setSocketTimeout = (request, reject2, timeoutInMs = 0) => {
2124
2143
  const registerTimeout = (offset) => {
2125
2144
  const timeout = timeoutInMs - offset;
2126
2145
  const onTimeout = () => {
2127
2146
  request.destroy();
2128
- reject2(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" }));
2147
+ 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" }));
2129
2148
  };
2130
2149
  if (request.socket) {
2131
2150
  request.socket.setTimeout(timeout, onTimeout);
@@ -2238,13 +2257,15 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2238
2257
  });
2239
2258
  }
2240
2259
  resolveDefaultConfig(options) {
2241
- const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent } = options || {};
2260
+ const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent, throwOnRequestTimeout } = options || {};
2242
2261
  const keepAlive = true;
2243
2262
  const maxSockets = 50;
2244
2263
  return {
2245
2264
  connectionTimeout,
2246
- requestTimeout: requestTimeout ?? socketTimeout,
2265
+ requestTimeout,
2266
+ socketTimeout,
2247
2267
  socketAcquisitionWarningTimeout,
2268
+ throwOnRequestTimeout,
2248
2269
  httpAgent: (() => {
2249
2270
  if (httpAgent instanceof http.Agent || typeof httpAgent?.destroy === "function") {
2250
2271
  return httpAgent;
@@ -2358,7 +2379,8 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
2358
2379
  }
2359
2380
  const effectiveRequestTimeout = requestTimeout ?? this.config.requestTimeout;
2360
2381
  timeouts.push(setConnectionTimeout(req, reject2, this.config.connectionTimeout));
2361
- timeouts.push(setSocketTimeout(req, reject2, effectiveRequestTimeout));
2382
+ timeouts.push(setRequestTimeout(req, reject2, effectiveRequestTimeout, this.config.throwOnRequestTimeout, this.config.logger ?? console));
2383
+ timeouts.push(setSocketTimeout(req, reject2, this.config.socketTimeout));
2362
2384
  const httpAgent = nodeHttpsOptions.agent;
2363
2385
  if (typeof httpAgent === "object" && "keepAlive" in httpAgent) {
2364
2386
  timeouts.push(setSocketKeepAlive(req, {
@@ -3283,120 +3305,6 @@ var init_deref = __esm({
3283
3305
  }
3284
3306
  });
3285
3307
 
3286
- // node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js
3287
- var import_protocol_http2, import_util_middleware3, schemaDeserializationMiddleware, findHeader;
3288
- var init_schemaDeserializationMiddleware = __esm({
3289
- "node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js"() {
3290
- import_protocol_http2 = __toESM(require_dist_cjs2());
3291
- import_util_middleware3 = __toESM(require_dist_cjs7());
3292
- schemaDeserializationMiddleware = (config) => (next, context) => async (args) => {
3293
- const { response } = await next(args);
3294
- const { operationSchema } = (0, import_util_middleware3.getSmithyContext)(context);
3295
- try {
3296
- const parsed = await config.protocol.deserializeResponse(operationSchema, {
3297
- ...config,
3298
- ...context
3299
- }, response);
3300
- return {
3301
- response,
3302
- output: parsed
3303
- };
3304
- } catch (error2) {
3305
- Object.defineProperty(error2, "$response", {
3306
- value: response
3307
- });
3308
- if (!("$metadata" in error2)) {
3309
- const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`;
3310
- try {
3311
- error2.message += "\n " + hint;
3312
- } catch (e3) {
3313
- if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") {
3314
- console.warn(hint);
3315
- } else {
3316
- context.logger?.warn?.(hint);
3317
- }
3318
- }
3319
- if (typeof error2.$responseBodyText !== "undefined") {
3320
- if (error2.$response) {
3321
- error2.$response.body = error2.$responseBodyText;
3322
- }
3323
- }
3324
- try {
3325
- if (import_protocol_http2.HttpResponse.isInstance(response)) {
3326
- const { headers = {} } = response;
3327
- const headerEntries = Object.entries(headers);
3328
- error2.$metadata = {
3329
- httpStatusCode: response.statusCode,
3330
- requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries),
3331
- extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries),
3332
- cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries)
3333
- };
3334
- }
3335
- } catch (e3) {
3336
- }
3337
- }
3338
- throw error2;
3339
- }
3340
- };
3341
- findHeader = (pattern, headers) => {
3342
- return (headers.find(([k3]) => {
3343
- return k3.match(pattern);
3344
- }) || [void 0, void 0])[1];
3345
- };
3346
- }
3347
- });
3348
-
3349
- // node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js
3350
- var import_util_middleware4, schemaSerializationMiddleware;
3351
- var init_schemaSerializationMiddleware = __esm({
3352
- "node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js"() {
3353
- import_util_middleware4 = __toESM(require_dist_cjs7());
3354
- schemaSerializationMiddleware = (config) => (next, context) => async (args) => {
3355
- const { operationSchema } = (0, import_util_middleware4.getSmithyContext)(context);
3356
- const endpoint = context.endpointV2?.url && config.urlParser ? async () => config.urlParser(context.endpointV2.url) : config.endpoint;
3357
- const request = await config.protocol.serializeRequest(operationSchema, args.input, {
3358
- ...config,
3359
- ...context,
3360
- endpoint
3361
- });
3362
- return next({
3363
- ...args,
3364
- request
3365
- });
3366
- };
3367
- }
3368
- });
3369
-
3370
- // node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js
3371
- function getSchemaSerdePlugin(config) {
3372
- return {
3373
- applyToStack: (commandStack) => {
3374
- commandStack.add(schemaSerializationMiddleware(config), serializerMiddlewareOption2);
3375
- commandStack.add(schemaDeserializationMiddleware(config), deserializerMiddlewareOption);
3376
- config.protocol.setSerdeContext(config);
3377
- }
3378
- };
3379
- }
3380
- var deserializerMiddlewareOption, serializerMiddlewareOption2;
3381
- var init_getSchemaSerdePlugin = __esm({
3382
- "node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js"() {
3383
- init_schemaDeserializationMiddleware();
3384
- init_schemaSerializationMiddleware();
3385
- deserializerMiddlewareOption = {
3386
- name: "deserializerMiddleware",
3387
- step: "deserialize",
3388
- tags: ["DESERIALIZER"],
3389
- override: true
3390
- };
3391
- serializerMiddlewareOption2 = {
3392
- name: "serializerMiddleware",
3393
- step: "serialize",
3394
- tags: ["SERIALIZER"],
3395
- override: true
3396
- };
3397
- }
3398
- });
3399
-
3400
3308
  // node_modules/@smithy/core/dist-es/submodules/schema/TypeRegistry.js
3401
3309
  var TypeRegistry;
3402
3310
  var init_TypeRegistry = __esm({
@@ -3428,11 +3336,11 @@ var init_TypeRegistry = __esm({
3428
3336
  }
3429
3337
  return this.schemas.get(id);
3430
3338
  }
3431
- registerError(errorSchema, ctor) {
3432
- this.exceptions.set(errorSchema, ctor);
3339
+ registerError(es, ctor) {
3340
+ this.exceptions.set(es, ctor);
3433
3341
  }
3434
- getErrorCtor(errorSchema) {
3435
- return this.exceptions.get(errorSchema);
3342
+ getErrorCtor(es) {
3343
+ return this.exceptions.get(es);
3436
3344
  }
3437
3345
  getBaseException() {
3438
3346
  for (const [id, schema] of this.schemas.entries()) {
@@ -3491,6 +3399,51 @@ var init_Schema = __esm({
3491
3399
  }
3492
3400
  });
3493
3401
 
3402
+ // node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js
3403
+ var StructureSchema, struct;
3404
+ var init_StructureSchema = __esm({
3405
+ "node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js"() {
3406
+ init_Schema();
3407
+ StructureSchema = class _StructureSchema extends Schema {
3408
+ static symbol = Symbol.for("@smithy/str");
3409
+ name;
3410
+ traits;
3411
+ memberNames;
3412
+ memberList;
3413
+ symbol = _StructureSchema.symbol;
3414
+ };
3415
+ struct = (namespace, name14, traits, memberNames, memberList) => Schema.assign(new StructureSchema(), {
3416
+ name: name14,
3417
+ namespace,
3418
+ traits,
3419
+ memberNames,
3420
+ memberList
3421
+ });
3422
+ }
3423
+ });
3424
+
3425
+ // node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js
3426
+ var ErrorSchema, error;
3427
+ var init_ErrorSchema = __esm({
3428
+ "node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js"() {
3429
+ init_Schema();
3430
+ init_StructureSchema();
3431
+ ErrorSchema = class _ErrorSchema extends StructureSchema {
3432
+ static symbol = Symbol.for("@smithy/err");
3433
+ ctor;
3434
+ symbol = _ErrorSchema.symbol;
3435
+ };
3436
+ error = (namespace, name14, traits, memberNames, memberList, ctor) => Schema.assign(new ErrorSchema(), {
3437
+ name: name14,
3438
+ namespace,
3439
+ traits,
3440
+ memberNames,
3441
+ memberList,
3442
+ ctor: null
3443
+ });
3444
+ }
3445
+ });
3446
+
3494
3447
  // node_modules/@smithy/core/dist-es/submodules/schema/schemas/ListSchema.js
3495
3448
  var ListSchema, list;
3496
3449
  var init_ListSchema = __esm({
@@ -3558,47 +3511,23 @@ var init_OperationSchema = __esm({
3558
3511
  }
3559
3512
  });
3560
3513
 
3561
- // node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js
3562
- var StructureSchema, struct;
3563
- var init_StructureSchema = __esm({
3564
- "node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js"() {
3514
+ // node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js
3515
+ var SimpleSchema, sim;
3516
+ var init_SimpleSchema = __esm({
3517
+ "node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js"() {
3565
3518
  init_Schema();
3566
- StructureSchema = class _StructureSchema extends Schema {
3567
- static symbol = Symbol.for("@smithy/str");
3519
+ SimpleSchema = class _SimpleSchema extends Schema {
3520
+ static symbol = Symbol.for("@smithy/sim");
3568
3521
  name;
3522
+ schemaRef;
3569
3523
  traits;
3570
- memberNames;
3571
- memberList;
3572
- symbol = _StructureSchema.symbol;
3573
- };
3574
- struct = (namespace, name14, traits, memberNames, memberList) => Schema.assign(new StructureSchema(), {
3575
- name: name14,
3576
- namespace,
3577
- traits,
3578
- memberNames,
3579
- memberList
3580
- });
3581
- }
3582
- });
3583
-
3584
- // node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js
3585
- var ErrorSchema, error;
3586
- var init_ErrorSchema = __esm({
3587
- "node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js"() {
3588
- init_Schema();
3589
- init_StructureSchema();
3590
- ErrorSchema = class _ErrorSchema extends StructureSchema {
3591
- static symbol = Symbol.for("@smithy/err");
3592
- ctor;
3593
- symbol = _ErrorSchema.symbol;
3524
+ symbol = _SimpleSchema.symbol;
3594
3525
  };
3595
- error = (namespace, name14, traits, memberNames, memberList, ctor) => Schema.assign(new ErrorSchema(), {
3526
+ sim = (namespace, name14, schemaRef, traits) => Schema.assign(new SimpleSchema(), {
3596
3527
  name: name14,
3597
3528
  namespace,
3598
3529
  traits,
3599
- memberNames,
3600
- memberList,
3601
- ctor: null
3530
+ schemaRef
3602
3531
  });
3603
3532
  }
3604
3533
  });
@@ -3642,13 +3571,27 @@ function member(memberSchema, memberName) {
3642
3571
  const internalCtorAccess = NormalizedSchema;
3643
3572
  return new internalCtorAccess(memberSchema, memberName);
3644
3573
  }
3645
- var NormalizedSchema;
3574
+ function hydrate(ss) {
3575
+ const [id, ...rest] = ss;
3576
+ return {
3577
+ [0]: sim,
3578
+ [1]: list,
3579
+ [2]: map,
3580
+ [3]: struct,
3581
+ [-3]: error,
3582
+ [9]: op
3583
+ }[id].call(null, ...rest);
3584
+ }
3585
+ var NormalizedSchema, isMemberSchema, isStaticSchema;
3646
3586
  var init_NormalizedSchema = __esm({
3647
3587
  "node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js"() {
3648
3588
  init_deref();
3589
+ init_ErrorSchema();
3649
3590
  init_ListSchema();
3650
3591
  init_MapSchema();
3592
+ init_OperationSchema();
3651
3593
  init_Schema();
3594
+ init_SimpleSchema();
3652
3595
  init_StructureSchema();
3653
3596
  init_translateTraits();
3654
3597
  NormalizedSchema = class _NormalizedSchema {
@@ -3669,12 +3612,14 @@ var init_NormalizedSchema = __esm({
3669
3612
  let _ref = ref;
3670
3613
  let schema = ref;
3671
3614
  this._isMemberSchema = false;
3672
- while (Array.isArray(_ref)) {
3615
+ while (isMemberSchema(_ref)) {
3673
3616
  traitStack.push(_ref[1]);
3674
3617
  _ref = _ref[0];
3675
3618
  schema = deref(_ref);
3676
3619
  this._isMemberSchema = true;
3677
3620
  }
3621
+ if (isStaticSchema(schema))
3622
+ schema = hydrate(schema);
3678
3623
  if (traitStack.length > 0) {
3679
3624
  this.memberTraits = {};
3680
3625
  for (let i3 = traitStack.length - 1; i3 >= 0; --i3) {
@@ -3711,7 +3656,7 @@ var init_NormalizedSchema = __esm({
3711
3656
  if (sc instanceof _NormalizedSchema) {
3712
3657
  return sc;
3713
3658
  }
3714
- if (Array.isArray(sc)) {
3659
+ if (isMemberSchema(sc)) {
3715
3660
  const [ns, traits] = sc;
3716
3661
  if (ns instanceof _NormalizedSchema) {
3717
3662
  Object.assign(ns.getMergedTraits(), translateTraits(traits));
@@ -3820,7 +3765,7 @@ var init_NormalizedSchema = __esm({
3820
3765
  if (this.isStructSchema() && struct2.memberNames.includes(memberName)) {
3821
3766
  const i3 = struct2.memberNames.indexOf(memberName);
3822
3767
  const memberSchema = struct2.memberList[i3];
3823
- return member(Array.isArray(memberSchema) ? memberSchema : [memberSchema, 0], memberName);
3768
+ return member(isMemberSchema(memberSchema) ? memberSchema : [memberSchema, 0], memberName);
3824
3769
  }
3825
3770
  if (this.isDocumentSchema()) {
3826
3771
  return member([15, 0], memberName);
@@ -3860,27 +3805,130 @@ var init_NormalizedSchema = __esm({
3860
3805
  }
3861
3806
  }
3862
3807
  };
3808
+ isMemberSchema = (sc) => Array.isArray(sc) && sc.length === 2;
3809
+ isStaticSchema = (sc) => Array.isArray(sc) && sc.length >= 5;
3863
3810
  }
3864
3811
  });
3865
3812
 
3866
- // node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js
3867
- var SimpleSchema, sim;
3868
- var init_SimpleSchema = __esm({
3869
- "node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js"() {
3870
- init_Schema();
3871
- SimpleSchema = class _SimpleSchema extends Schema {
3872
- static symbol = Symbol.for("@smithy/sim");
3873
- name;
3874
- schemaRef;
3875
- traits;
3876
- symbol = _SimpleSchema.symbol;
3813
+ // node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js
3814
+ var import_protocol_http2, import_util_middleware3, schemaDeserializationMiddleware, findHeader;
3815
+ var init_schemaDeserializationMiddleware = __esm({
3816
+ "node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js"() {
3817
+ import_protocol_http2 = __toESM(require_dist_cjs2());
3818
+ import_util_middleware3 = __toESM(require_dist_cjs7());
3819
+ init_NormalizedSchema();
3820
+ schemaDeserializationMiddleware = (config) => (next, context) => async (args) => {
3821
+ const { response } = await next(args);
3822
+ let { operationSchema } = (0, import_util_middleware3.getSmithyContext)(context);
3823
+ if (isStaticSchema(operationSchema)) {
3824
+ operationSchema = hydrate(operationSchema);
3825
+ }
3826
+ try {
3827
+ const parsed = await config.protocol.deserializeResponse(operationSchema, {
3828
+ ...config,
3829
+ ...context
3830
+ }, response);
3831
+ return {
3832
+ response,
3833
+ output: parsed
3834
+ };
3835
+ } catch (error2) {
3836
+ Object.defineProperty(error2, "$response", {
3837
+ value: response
3838
+ });
3839
+ if (!("$metadata" in error2)) {
3840
+ const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`;
3841
+ try {
3842
+ error2.message += "\n " + hint;
3843
+ } catch (e3) {
3844
+ if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") {
3845
+ console.warn(hint);
3846
+ } else {
3847
+ context.logger?.warn?.(hint);
3848
+ }
3849
+ }
3850
+ if (typeof error2.$responseBodyText !== "undefined") {
3851
+ if (error2.$response) {
3852
+ error2.$response.body = error2.$responseBodyText;
3853
+ }
3854
+ }
3855
+ try {
3856
+ if (import_protocol_http2.HttpResponse.isInstance(response)) {
3857
+ const { headers = {} } = response;
3858
+ const headerEntries = Object.entries(headers);
3859
+ error2.$metadata = {
3860
+ httpStatusCode: response.statusCode,
3861
+ requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries),
3862
+ extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries),
3863
+ cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries)
3864
+ };
3865
+ }
3866
+ } catch (e3) {
3867
+ }
3868
+ }
3869
+ throw error2;
3870
+ }
3871
+ };
3872
+ findHeader = (pattern, headers) => {
3873
+ return (headers.find(([k3]) => {
3874
+ return k3.match(pattern);
3875
+ }) || [void 0, void 0])[1];
3876
+ };
3877
+ }
3878
+ });
3879
+
3880
+ // node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js
3881
+ var import_util_middleware4, schemaSerializationMiddleware;
3882
+ var init_schemaSerializationMiddleware = __esm({
3883
+ "node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js"() {
3884
+ import_util_middleware4 = __toESM(require_dist_cjs7());
3885
+ init_NormalizedSchema();
3886
+ schemaSerializationMiddleware = (config) => (next, context) => async (args) => {
3887
+ let { operationSchema } = (0, import_util_middleware4.getSmithyContext)(context);
3888
+ if (isStaticSchema(operationSchema)) {
3889
+ operationSchema = hydrate(operationSchema);
3890
+ }
3891
+ const endpoint = context.endpointV2?.url && config.urlParser ? async () => config.urlParser(context.endpointV2.url) : config.endpoint;
3892
+ const request = await config.protocol.serializeRequest(operationSchema, args.input, {
3893
+ ...config,
3894
+ ...context,
3895
+ endpoint
3896
+ });
3897
+ return next({
3898
+ ...args,
3899
+ request
3900
+ });
3901
+ };
3902
+ }
3903
+ });
3904
+
3905
+ // node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js
3906
+ function getSchemaSerdePlugin(config) {
3907
+ return {
3908
+ applyToStack: (commandStack) => {
3909
+ commandStack.add(schemaSerializationMiddleware(config), serializerMiddlewareOption2);
3910
+ commandStack.add(schemaDeserializationMiddleware(config), deserializerMiddlewareOption);
3911
+ config.protocol.setSerdeContext(config);
3912
+ }
3913
+ };
3914
+ }
3915
+ var deserializerMiddlewareOption, serializerMiddlewareOption2;
3916
+ var init_getSchemaSerdePlugin = __esm({
3917
+ "node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js"() {
3918
+ init_schemaDeserializationMiddleware();
3919
+ init_schemaSerializationMiddleware();
3920
+ deserializerMiddlewareOption = {
3921
+ name: "deserializerMiddleware",
3922
+ step: "deserialize",
3923
+ tags: ["DESERIALIZER"],
3924
+ override: true
3925
+ };
3926
+ serializerMiddlewareOption2 = {
3927
+ name: "serializerMiddleware",
3928
+ step: "serialize",
3929
+ tags: ["SERIALIZER"],
3930
+ override: true
3877
3931
  };
3878
- sim = (namespace, name14, schemaRef, traits) => Schema.assign(new SimpleSchema(), {
3879
- name: name14,
3880
- namespace,
3881
- traits,
3882
- schemaRef
3883
- });
3884
3932
  }
3885
3933
  });
3886
3934
 
@@ -3924,6 +3972,8 @@ __export(schema_exports, {
3924
3972
  deserializerMiddlewareOption: () => deserializerMiddlewareOption,
3925
3973
  error: () => error,
3926
3974
  getSchemaSerdePlugin: () => getSchemaSerdePlugin,
3975
+ hydrate: () => hydrate,
3976
+ isStaticSchema: () => isStaticSchema,
3927
3977
  list: () => list,
3928
3978
  map: () => map,
3929
3979
  op: () => op,
@@ -5270,6 +5320,19 @@ var init_serde = __esm({
5270
5320
  }
5271
5321
  });
5272
5322
 
5323
+ // node_modules/@smithy/core/dist-es/submodules/protocols/SerdeContext.js
5324
+ var SerdeContext;
5325
+ var init_SerdeContext = __esm({
5326
+ "node_modules/@smithy/core/dist-es/submodules/protocols/SerdeContext.js"() {
5327
+ SerdeContext = class {
5328
+ serdeContext;
5329
+ setSerdeContext(serdeContext) {
5330
+ this.serdeContext = serdeContext;
5331
+ }
5332
+ };
5333
+ }
5334
+ });
5335
+
5273
5336
  // node_modules/@smithy/core/dist-es/submodules/event-streams/EventStreamSerde.js
5274
5337
  var import_util_utf8, EventStreamSerde;
5275
5338
  var init_EventStreamSerde = __esm({
@@ -5488,10 +5551,11 @@ var init_HttpProtocol = __esm({
5488
5551
  "node_modules/@smithy/core/dist-es/submodules/protocols/HttpProtocol.js"() {
5489
5552
  init_schema();
5490
5553
  import_protocol_http3 = __toESM(require_dist_cjs2());
5491
- HttpProtocol = class {
5554
+ init_SerdeContext();
5555
+ HttpProtocol = class extends SerdeContext {
5492
5556
  options;
5493
- serdeContext;
5494
5557
  constructor(options) {
5558
+ super();
5495
5559
  this.options = options;
5496
5560
  }
5497
5561
  getRequestType() {
@@ -6075,16 +6139,14 @@ var init_FromStringShapeDeserializer = __esm({
6075
6139
  init_serde();
6076
6140
  import_util_base64 = __toESM(require_dist_cjs12());
6077
6141
  import_util_utf82 = __toESM(require_dist_cjs11());
6142
+ init_SerdeContext();
6078
6143
  init_determineTimestampFormat();
6079
- FromStringShapeDeserializer = class {
6144
+ FromStringShapeDeserializer = class extends SerdeContext {
6080
6145
  settings;
6081
- serdeContext;
6082
6146
  constructor(settings) {
6147
+ super();
6083
6148
  this.settings = settings;
6084
6149
  }
6085
- setSerdeContext(serdeContext) {
6086
- this.serdeContext = serdeContext;
6087
- }
6088
6150
  read(_schema, data2) {
6089
6151
  const ns = NormalizedSchema.of(_schema);
6090
6152
  if (ns.isListSchema()) {
@@ -6148,12 +6210,13 @@ var init_HttpInterceptingShapeDeserializer = __esm({
6148
6210
  "node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeDeserializer.js"() {
6149
6211
  init_schema();
6150
6212
  import_util_utf83 = __toESM(require_dist_cjs11());
6213
+ init_SerdeContext();
6151
6214
  init_FromStringShapeDeserializer();
6152
- HttpInterceptingShapeDeserializer = class {
6215
+ HttpInterceptingShapeDeserializer = class extends SerdeContext {
6153
6216
  codecDeserializer;
6154
6217
  stringDeserializer;
6155
- serdeContext;
6156
6218
  constructor(codecDeserializer, codecSettings) {
6219
+ super();
6157
6220
  this.codecDeserializer = codecDeserializer;
6158
6221
  this.stringDeserializer = new FromStringShapeDeserializer(codecSettings);
6159
6222
  }
@@ -6196,17 +6259,15 @@ var init_ToStringShapeSerializer = __esm({
6196
6259
  init_schema();
6197
6260
  init_serde();
6198
6261
  import_util_base642 = __toESM(require_dist_cjs12());
6262
+ init_SerdeContext();
6199
6263
  init_determineTimestampFormat();
6200
- ToStringShapeSerializer = class {
6264
+ ToStringShapeSerializer = class extends SerdeContext {
6201
6265
  settings;
6202
6266
  stringBuffer = "";
6203
- serdeContext = void 0;
6204
6267
  constructor(settings) {
6268
+ super();
6205
6269
  this.settings = settings;
6206
6270
  }
6207
- setSerdeContext(serdeContext) {
6208
- this.serdeContext = serdeContext;
6209
- }
6210
6271
  write(schema, value) {
6211
6272
  const ns = NormalizedSchema.of(schema);
6212
6273
  switch (typeof value) {
@@ -6334,6 +6395,7 @@ __export(protocols_exports, {
6334
6395
  HttpProtocol: () => HttpProtocol,
6335
6396
  RequestBuilder: () => RequestBuilder,
6336
6397
  RpcProtocol: () => RpcProtocol,
6398
+ SerdeContext: () => SerdeContext,
6337
6399
  ToStringShapeSerializer: () => ToStringShapeSerializer,
6338
6400
  collectBody: () => collectBody,
6339
6401
  determineTimestampFormat: () => determineTimestampFormat,
@@ -6355,12 +6417,13 @@ var init_protocols = __esm({
6355
6417
  init_HttpInterceptingShapeSerializer();
6356
6418
  init_ToStringShapeSerializer();
6357
6419
  init_determineTimestampFormat();
6420
+ init_SerdeContext();
6358
6421
  }
6359
6422
  });
6360
6423
 
6361
- // node_modules/@smithy/core/dist-es/protocols/requestBuilder.js
6424
+ // node_modules/@smithy/core/dist-es/request-builder/requestBuilder.js
6362
6425
  var init_requestBuilder2 = __esm({
6363
- "node_modules/@smithy/core/dist-es/protocols/requestBuilder.js"() {
6426
+ "node_modules/@smithy/core/dist-es/request-builder/requestBuilder.js"() {
6364
6427
  init_protocols();
6365
6428
  }
6366
6429
  });
@@ -9315,13 +9378,13 @@ var init_parseCborBody = __esm({
9315
9378
  var import_util_base643, CborCodec, CborShapeSerializer, CborShapeDeserializer;
9316
9379
  var init_CborCodec = __esm({
9317
9380
  "node_modules/@smithy/core/dist-es/submodules/cbor/CborCodec.js"() {
9381
+ init_protocols();
9318
9382
  init_schema();
9319
9383
  init_serde();
9320
9384
  import_util_base643 = __toESM(require_dist_cjs12());
9321
9385
  init_cbor();
9322
9386
  init_parseCborBody();
9323
- CborCodec = class {
9324
- serdeContext;
9387
+ CborCodec = class extends SerdeContext {
9325
9388
  createSerializer() {
9326
9389
  const serializer = new CborShapeSerializer();
9327
9390
  serializer.setSerdeContext(this.serdeContext);
@@ -9332,16 +9395,9 @@ var init_CborCodec = __esm({
9332
9395
  deserializer.setSerdeContext(this.serdeContext);
9333
9396
  return deserializer;
9334
9397
  }
9335
- setSerdeContext(serdeContext) {
9336
- this.serdeContext = serdeContext;
9337
- }
9338
9398
  };
9339
- CborShapeSerializer = class {
9340
- serdeContext;
9399
+ CborShapeSerializer = class extends SerdeContext {
9341
9400
  value;
9342
- setSerdeContext(serdeContext) {
9343
- this.serdeContext = serdeContext;
9344
- }
9345
9401
  write(schema, value) {
9346
9402
  this.value = this.serialize(schema, value);
9347
9403
  }
@@ -9413,11 +9469,7 @@ var init_CborCodec = __esm({
9413
9469
  return buffer;
9414
9470
  }
9415
9471
  };
9416
- CborShapeDeserializer = class {
9417
- serdeContext;
9418
- setSerdeContext(serdeContext) {
9419
- this.serdeContext = serdeContext;
9420
- }
9472
+ CborShapeDeserializer = class extends SerdeContext {
9421
9473
  read(schema, bytes) {
9422
9474
  const data2 = cbor.deserialize(bytes);
9423
9475
  return this.readValue(schema, data2);
@@ -10282,13 +10334,16 @@ var require_dist_cjs27 = __commonJS({
10282
10334
  this.schema = closure._operationSchema;
10283
10335
  }
10284
10336
  resolveMiddleware(stack, configuration, options) {
10337
+ const op2 = closure._operationSchema;
10338
+ const input = op2?.[4] ?? op2?.input;
10339
+ const output = op2?.[5] ?? op2?.output;
10285
10340
  return this.resolveMiddlewareWithContext(stack, configuration, options, {
10286
10341
  CommandCtor: CommandRef,
10287
10342
  middlewareFn: closure._middlewareFn,
10288
10343
  clientName: closure._clientName,
10289
10344
  commandName: closure._commandName,
10290
- inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (closure._operationSchema ? schemaLogFilter.bind(null, closure._operationSchema.input) : (_2) => _2),
10291
- outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (closure._operationSchema ? schemaLogFilter.bind(null, closure._operationSchema.output) : (_2) => _2),
10345
+ inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (op2 ? schemaLogFilter.bind(null, input) : (_2) => _2),
10346
+ outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (op2 ? schemaLogFilter.bind(null, output) : (_2) => _2),
10292
10347
  smithyContext: closure._smithyContext,
10293
10348
  additionalContext: closure._additionalContext
10294
10349
  });
@@ -71761,6 +71816,28 @@ var init_out = __esm({
71761
71816
  });
71762
71817
 
71763
71818
  // src/agent/schemaUtils.js
71819
+ var schemaUtils_exports = {};
71820
+ __export(schemaUtils_exports, {
71821
+ JsonFixingAgent: () => JsonFixingAgent,
71822
+ MermaidFixingAgent: () => MermaidFixingAgent,
71823
+ cleanSchemaResponse: () => cleanSchemaResponse,
71824
+ createJsonCorrectionPrompt: () => createJsonCorrectionPrompt,
71825
+ createMermaidCorrectionPrompt: () => createMermaidCorrectionPrompt,
71826
+ createSchemaDefinitionCorrectionPrompt: () => createSchemaDefinitionCorrectionPrompt,
71827
+ decodeHtmlEntities: () => decodeHtmlEntities,
71828
+ extractMermaidFromMarkdown: () => extractMermaidFromMarkdown,
71829
+ isJsonSchema: () => isJsonSchema,
71830
+ isJsonSchemaDefinition: () => isJsonSchemaDefinition,
71831
+ isMermaidSchema: () => isMermaidSchema,
71832
+ processSchemaResponse: () => processSchemaResponse,
71833
+ replaceMermaidDiagramsInMarkdown: () => replaceMermaidDiagramsInMarkdown,
71834
+ tryMaidAutoFix: () => tryMaidAutoFix,
71835
+ validateAndFixMermaidResponse: () => validateAndFixMermaidResponse,
71836
+ validateJsonResponse: () => validateJsonResponse,
71837
+ validateMermaidDiagram: () => validateMermaidDiagram,
71838
+ validateMermaidResponse: () => validateMermaidResponse,
71839
+ validateXmlResponse: () => validateXmlResponse
71840
+ });
71764
71841
  function decodeHtmlEntities(text) {
71765
71842
  if (!text || typeof text !== "string") {
71766
71843
  return text;
@@ -71849,9 +71926,49 @@ function validateJsonResponse(response, options = {}) {
71849
71926
  }
71850
71927
  return { isValid: true, parsed };
71851
71928
  } catch (error2) {
71929
+ const positionMatch = error2.message.match(/position (\d+)/);
71930
+ let errorPosition = positionMatch ? parseInt(positionMatch[1], 10) : null;
71931
+ if (errorPosition === null) {
71932
+ const tokenMatch = error2.message.match(/Unexpected token '(.)', /);
71933
+ if (tokenMatch && tokenMatch[1]) {
71934
+ const problematicToken = tokenMatch[1];
71935
+ errorPosition = response.indexOf(problematicToken);
71936
+ }
71937
+ }
71938
+ let enhancedError = error2.message;
71939
+ let errorContext = null;
71940
+ if (errorPosition !== null && errorPosition >= 0 && response && response.length > 0) {
71941
+ const contextRadius = 50;
71942
+ const startPos = Math.max(0, errorPosition - contextRadius);
71943
+ const endPos = Math.min(response.length, errorPosition + contextRadius);
71944
+ const beforeError = response.substring(startPos, errorPosition);
71945
+ const atError = response[errorPosition] || "";
71946
+ const afterError = response.substring(errorPosition + 1, endPos);
71947
+ const snippet = beforeError + atError + afterError;
71948
+ const pointerOffset = beforeError.length;
71949
+ const pointer = " ".repeat(pointerOffset) + "^";
71950
+ errorContext = {
71951
+ position: errorPosition,
71952
+ snippet,
71953
+ pointer,
71954
+ beforeError,
71955
+ atError,
71956
+ afterError
71957
+ };
71958
+ enhancedError = `${error2.message}
71959
+
71960
+ Error location (position ${errorPosition}):
71961
+ ${snippet}
71962
+ ${pointer} here`;
71963
+ }
71852
71964
  if (debug) {
71853
71965
  console.log(`[DEBUG] JSON validation: Parse failed with error: ${error2.message}`);
71854
- console.log(`[DEBUG] JSON validation: Error at position: ${error2.message.match(/position (\d+)/) ? error2.message.match(/position (\d+)/)[1] : "unknown"}`);
71966
+ console.log(`[DEBUG] JSON validation: Error at position: ${errorPosition !== null ? errorPosition : "unknown"}`);
71967
+ if (errorContext) {
71968
+ console.log(`[DEBUG] JSON validation: Error context:
71969
+ ${errorContext.snippet}
71970
+ ${errorContext.pointer}`);
71971
+ }
71855
71972
  if (error2.message.includes("Unexpected token")) {
71856
71973
  console.log(`[DEBUG] JSON validation: Likely syntax error - unexpected character`);
71857
71974
  } else if (error2.message.includes("Unexpected end")) {
@@ -71860,8 +71977,72 @@ function validateJsonResponse(response, options = {}) {
71860
71977
  console.log(`[DEBUG] JSON validation: Likely unquoted property names`);
71861
71978
  }
71862
71979
  }
71863
- return { isValid: false, error: error2.message };
71980
+ return {
71981
+ isValid: false,
71982
+ error: error2.message,
71983
+ enhancedError,
71984
+ errorContext
71985
+ };
71986
+ }
71987
+ }
71988
+ function validateXmlResponse(response) {
71989
+ const xmlPattern = /<\/?[\w\s="'.-]+>/g;
71990
+ const tags = response.match(xmlPattern);
71991
+ if (!tags) {
71992
+ return { isValid: false, error: "No XML tags found" };
71993
+ }
71994
+ if (response.includes("<") && response.includes(">")) {
71995
+ return { isValid: true };
71864
71996
  }
71997
+ return { isValid: false, error: "Invalid XML structure" };
71998
+ }
71999
+ function processSchemaResponse(response, schema, options = {}) {
72000
+ const { validateJson = false, validateXml = false, debug = false } = options;
72001
+ if (debug) {
72002
+ console.log(`[DEBUG] Schema processing: Starting with response length ${response.length}`);
72003
+ console.log(`[DEBUG] Schema processing: Schema type detection...`);
72004
+ if (isJsonSchema(schema)) {
72005
+ console.log(`[DEBUG] Schema processing: Detected JSON schema`);
72006
+ } else {
72007
+ console.log(`[DEBUG] Schema processing: Non-JSON schema detected`);
72008
+ }
72009
+ }
72010
+ const cleanStart = Date.now();
72011
+ const cleaned = cleanSchemaResponse(response);
72012
+ const cleanTime = Date.now() - cleanStart;
72013
+ const result = { cleaned };
72014
+ if (debug) {
72015
+ console.log(`[DEBUG] Schema processing: Cleaning completed in ${cleanTime}ms`);
72016
+ result.debug = {
72017
+ originalLength: response.length,
72018
+ cleanedLength: cleaned.length,
72019
+ wasModified: response !== cleaned,
72020
+ cleaningTimeMs: cleanTime,
72021
+ removedContent: response !== cleaned ? {
72022
+ before: response.substring(0, 100) + (response.length > 100 ? "..." : ""),
72023
+ after: cleaned.substring(0, 100) + (cleaned.length > 100 ? "..." : "")
72024
+ } : null
72025
+ };
72026
+ if (response !== cleaned) {
72027
+ console.log(`[DEBUG] Schema processing: Response was modified during cleaning`);
72028
+ console.log(`[DEBUG] Schema processing: Original length: ${response.length}, cleaned length: ${cleaned.length}`);
72029
+ } else {
72030
+ console.log(`[DEBUG] Schema processing: Response unchanged during cleaning`);
72031
+ }
72032
+ }
72033
+ if (validateJson) {
72034
+ if (debug) {
72035
+ console.log(`[DEBUG] Schema processing: Running JSON validation...`);
72036
+ }
72037
+ result.jsonValidation = validateJsonResponse(cleaned, { debug });
72038
+ }
72039
+ if (validateXml) {
72040
+ if (debug) {
72041
+ console.log(`[DEBUG] Schema processing: Running XML validation...`);
72042
+ }
72043
+ result.xmlValidation = validateXmlResponse(cleaned);
72044
+ }
72045
+ return result;
71865
72046
  }
71866
72047
  function isJsonSchema(schema) {
71867
72048
  if (!schema || typeof schema !== "string") {
@@ -71921,7 +72102,16 @@ function isJsonSchemaDefinition(jsonString, options = {}) {
71921
72102
  return false;
71922
72103
  }
71923
72104
  }
71924
- function createJsonCorrectionPrompt(invalidResponse, schema, error2, retryCount = 0) {
72105
+ function createJsonCorrectionPrompt(invalidResponse, schema, errorOrValidation, retryCount = 0) {
72106
+ let errorMessage;
72107
+ let enhancedError;
72108
+ if (typeof errorOrValidation === "object" && errorOrValidation !== null) {
72109
+ errorMessage = errorOrValidation.error;
72110
+ enhancedError = errorOrValidation.enhancedError || errorMessage;
72111
+ } else {
72112
+ errorMessage = errorOrValidation;
72113
+ enhancedError = errorMessage;
72114
+ }
71925
72115
  const strengthLevels = [
71926
72116
  {
71927
72117
  prefix: "CRITICAL JSON ERROR:",
@@ -71945,7 +72135,7 @@ function createJsonCorrectionPrompt(invalidResponse, schema, error2, retryCount
71945
72135
 
71946
72136
  ${invalidResponse.substring(0, 500)}${invalidResponse.length > 500 ? "..." : ""}
71947
72137
 
71948
- Error: ${error2}
72138
+ Error: ${enhancedError}
71949
72139
 
71950
72140
  ${currentLevel.instruction}
71951
72141
 
@@ -71990,6 +72180,28 @@ ${currentLevel.example}
71990
72180
  Return ONLY the JSON data object/array that follows the schema structure. NO schema definitions, NO explanations, NO markdown formatting.`;
71991
72181
  return prompt;
71992
72182
  }
72183
+ function isMermaidSchema(schema) {
72184
+ if (!schema || typeof schema !== "string") {
72185
+ return false;
72186
+ }
72187
+ const trimmedSchema = schema.trim().toLowerCase();
72188
+ const mermaidIndicators = [
72189
+ trimmedSchema.includes("mermaid"),
72190
+ trimmedSchema.includes("diagram"),
72191
+ trimmedSchema.includes("flowchart"),
72192
+ trimmedSchema.includes("sequence"),
72193
+ trimmedSchema.includes("gantt"),
72194
+ trimmedSchema.includes("pie chart"),
72195
+ trimmedSchema.includes("state diagram"),
72196
+ trimmedSchema.includes("class diagram"),
72197
+ trimmedSchema.includes("entity relationship"),
72198
+ trimmedSchema.includes("user journey"),
72199
+ trimmedSchema.includes("git graph"),
72200
+ trimmedSchema.includes("requirement diagram"),
72201
+ trimmedSchema.includes("c4 context")
72202
+ ];
72203
+ return mermaidIndicators.some((indicator) => indicator);
72204
+ }
71993
72205
  function extractMermaidFromMarkdown(response) {
71994
72206
  if (!response || typeof response !== "string") {
71995
72207
  return { diagrams: [], cleanedResponse: response };
@@ -72010,6 +72222,24 @@ function extractMermaidFromMarkdown(response) {
72010
72222
  }
72011
72223
  return { diagrams, cleanedResponse: response };
72012
72224
  }
72225
+ function replaceMermaidDiagramsInMarkdown(originalResponse, correctedDiagrams) {
72226
+ if (!originalResponse || typeof originalResponse !== "string") {
72227
+ return originalResponse;
72228
+ }
72229
+ if (!correctedDiagrams || correctedDiagrams.length === 0) {
72230
+ return originalResponse;
72231
+ }
72232
+ let modifiedResponse = originalResponse;
72233
+ const sortedDiagrams = [...correctedDiagrams].sort((a3, b3) => b3.startIndex - a3.startIndex);
72234
+ for (const diagram of sortedDiagrams) {
72235
+ const attributesStr = diagram.attributes ? ` ${diagram.attributes}` : "";
72236
+ const newCodeBlock = `\`\`\`mermaid${attributesStr}
72237
+ ${diagram.content}
72238
+ \`\`\``;
72239
+ modifiedResponse = modifiedResponse.slice(0, diagram.startIndex) + newCodeBlock + modifiedResponse.slice(diagram.endIndex);
72240
+ }
72241
+ return modifiedResponse;
72242
+ }
72013
72243
  async function validateMermaidDiagram(diagram) {
72014
72244
  if (!diagram || typeof diagram !== "string") {
72015
72245
  return { isValid: false, error: "Empty or invalid diagram input" };
@@ -72076,6 +72306,45 @@ async function validateMermaidResponse(response) {
72076
72306
  errors: errors.length > 0 ? errors : void 0
72077
72307
  };
72078
72308
  }
72309
+ function createMermaidCorrectionPrompt(invalidResponse, schema, errors, diagrams) {
72310
+ let prompt = `Your previous response contains invalid Mermaid diagrams that cannot be parsed. Here's what you returned:
72311
+
72312
+ ${invalidResponse}
72313
+
72314
+ Validation Errors:`;
72315
+ errors.forEach((error2, index) => {
72316
+ prompt += `
72317
+ ${index + 1}. ${error2}`;
72318
+ });
72319
+ if (diagrams && diagrams.length > 0) {
72320
+ prompt += `
72321
+
72322
+ Diagram Details:`;
72323
+ diagrams.forEach((diagramResult, index) => {
72324
+ if (!diagramResult.isValid) {
72325
+ prompt += `
72326
+
72327
+ Diagram ${index + 1}:`;
72328
+ const diagramContent = diagramResult.content || diagramResult.diagram || "";
72329
+ prompt += `
72330
+ - Content: ${diagramContent.substring(0, 100)}${diagramContent.length > 100 ? "..." : ""}`;
72331
+ prompt += `
72332
+ - Error: ${diagramResult.error}`;
72333
+ if (diagramResult.detailedError && diagramResult.detailedError !== diagramResult.error) {
72334
+ prompt += `
72335
+ - Details: ${diagramResult.detailedError}`;
72336
+ }
72337
+ }
72338
+ });
72339
+ }
72340
+ prompt += `
72341
+
72342
+ Please correct your response to include valid Mermaid diagrams that match this schema:
72343
+ ${schema}
72344
+
72345
+ Ensure all Mermaid diagrams are properly formatted within \`\`\`mermaid code blocks and follow correct Mermaid syntax.`;
72346
+ return prompt;
72347
+ }
72079
72348
  async function tryMaidAutoFix(diagramContent, options = {}) {
72080
72349
  const { debug = false } = options;
72081
72350
  try {
@@ -72385,7 +72654,7 @@ ${fixedContent}
72385
72654
  };
72386
72655
  }
72387
72656
  }
72388
- var HTML_ENTITY_MAP, MermaidFixingAgent;
72657
+ var HTML_ENTITY_MAP, JsonFixingAgent, MermaidFixingAgent;
72389
72658
  var init_schemaUtils = __esm({
72390
72659
  "src/agent/schemaUtils.js"() {
72391
72660
  "use strict";
@@ -72401,6 +72670,156 @@ var init_schemaUtils = __esm({
72401
72670
  // Also handle XML/HTML5 apostrophe entity
72402
72671
  "&nbsp;": " "
72403
72672
  };
72673
+ JsonFixingAgent = class {
72674
+ constructor(options = {}) {
72675
+ this.ProbeAgent = null;
72676
+ this.options = {
72677
+ sessionId: options.sessionId || `json-fixer-${Date.now()}`,
72678
+ path: options.path || process.cwd(),
72679
+ provider: options.provider,
72680
+ model: options.model,
72681
+ debug: options.debug,
72682
+ tracer: options.tracer,
72683
+ // Set to false since we're only fixing JSON syntax, not implementing code
72684
+ allowEdit: false
72685
+ };
72686
+ }
72687
+ /**
72688
+ * Get the specialized prompt for JSON fixing
72689
+ */
72690
+ getJsonFixingPrompt() {
72691
+ 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.
72692
+
72693
+ CORE RESPONSIBILITIES:
72694
+ - Analyze JSON for syntax errors and structural issues
72695
+ - Fix syntax errors while maintaining the original data's semantic meaning
72696
+ - Ensure JSON follows proper RFC 8259 specification
72697
+ - Handle all JSON structures: objects, arrays, primitives, nested structures
72698
+
72699
+ JSON SYNTAX RULES:
72700
+ 1. **Property names**: Must be enclosed in double quotes
72701
+ 2. **String values**: Must use double quotes (not single quotes)
72702
+ 3. **Numbers**: Can be integers or decimals, no quotes needed
72703
+ 4. **Booleans**: true or false (lowercase, no quotes)
72704
+ 5. **Null**: null (lowercase, no quotes)
72705
+ 6. **Arrays**: Comma-separated values in square brackets [...]
72706
+ 7. **Objects**: Comma-separated key-value pairs in curly braces {...}
72707
+ 8. **No trailing commas**: Last item in array/object must not have a trailing comma
72708
+ 9. **Escape sequences**: Special characters must be escaped (\\n, \\t, \\", \\\\, etc.)
72709
+
72710
+ COMMON ERRORS TO FIX:
72711
+ 1. **Unquoted property names**: {name: "value"} \u2192 {"name": "value"}
72712
+ 2. **Single quotes**: {'key': 'value'} \u2192 {"key": "value"}
72713
+ 3. **Trailing commas**: {"a": 1,} \u2192 {"a": 1}
72714
+ 4. **Unquoted strings**: {key: value} \u2192 {"key": "value"}
72715
+ 5. **Missing commas**: {"a": 1 "b": 2} \u2192 {"a": 1, "b": 2}
72716
+ 6. **Extra commas**: {"a": 1,, "b": 2} \u2192 {"a": 1, "b": 2}
72717
+ 7. **Unclosed brackets/braces**: {"key": "value" \u2192 {"key": "value"}
72718
+ 8. **Invalid escape sequences**: Fix or remove
72719
+ 9. **Comments**: Remove // or /* */ comments (not allowed in JSON)
72720
+ 10. **Undefined values**: Replace undefined with null
72721
+
72722
+ FIXING METHODOLOGY:
72723
+ 1. **Identify the error location** from the error message
72724
+ 2. **Analyze the context** around the error
72725
+ 3. **Apply the appropriate fix** based on JSON syntax rules
72726
+ 4. **Preserve data intent** - never change the meaning of the data
72727
+ 5. **Validate the result** - ensure it's parseable JSON
72728
+
72729
+ CRITICAL RULES:
72730
+ - ALWAYS output only the corrected JSON
72731
+ - NEVER add explanations, comments, or additional text
72732
+ - NEVER wrap in markdown code blocks (no \`\`\`json)
72733
+ - PRESERVE the original data structure and values
72734
+ - FIX only syntax errors, don't modify the data itself
72735
+ - ENSURE the output is valid, parseable JSON
72736
+
72737
+ When presented with broken JSON, analyze it thoroughly and provide the corrected version that maintains the original intent while fixing all syntax issues.`;
72738
+ }
72739
+ /**
72740
+ * Initialize the ProbeAgent if not already done
72741
+ */
72742
+ async initializeAgent() {
72743
+ if (!this.ProbeAgent) {
72744
+ const { ProbeAgent: ProbeAgent2 } = await Promise.resolve().then(() => (init_ProbeAgent(), ProbeAgent_exports));
72745
+ this.ProbeAgent = ProbeAgent2;
72746
+ }
72747
+ if (!this.agent) {
72748
+ this.agent = new this.ProbeAgent({
72749
+ sessionId: this.options.sessionId,
72750
+ customPrompt: this.getJsonFixingPrompt(),
72751
+ path: this.options.path,
72752
+ provider: this.options.provider,
72753
+ model: this.options.model,
72754
+ debug: this.options.debug,
72755
+ tracer: this.options.tracer,
72756
+ allowEdit: this.options.allowEdit,
72757
+ maxIterations: 5,
72758
+ // Allow multiple iterations for JSON fixing
72759
+ disableJsonValidation: true
72760
+ // CRITICAL: Disable JSON validation in nested agent to prevent infinite recursion
72761
+ });
72762
+ }
72763
+ return this.agent;
72764
+ }
72765
+ /**
72766
+ * Fix invalid JSON using the specialized agent
72767
+ * @param {string} invalidJson - The broken JSON string
72768
+ * @param {string} schema - The original schema for context
72769
+ * @param {Object} validationResult - Validation result with error details
72770
+ * @param {number} attemptNumber - Current attempt number (for logging)
72771
+ * @returns {Promise<string>} - The corrected JSON
72772
+ */
72773
+ async fixJson(invalidJson, schema, validationResult, attemptNumber = 1) {
72774
+ await this.initializeAgent();
72775
+ let errorContext = validationResult.error;
72776
+ if (validationResult.enhancedError) {
72777
+ errorContext = validationResult.enhancedError;
72778
+ }
72779
+ const prompt = `Fix the following invalid JSON.
72780
+
72781
+ Error: ${errorContext}
72782
+
72783
+ Invalid JSON:
72784
+ ${invalidJson}
72785
+
72786
+ Expected schema structure:
72787
+ ${schema}
72788
+
72789
+ Provide only the corrected JSON without any markdown formatting or explanations.`;
72790
+ try {
72791
+ if (this.options.debug) {
72792
+ console.log(`[DEBUG] JSON fixing: Attempt ${attemptNumber} to fix JSON with separate agent`);
72793
+ }
72794
+ const result = await this.agent.answer(prompt, []);
72795
+ const cleaned = cleanSchemaResponse(result);
72796
+ if (this.options.debug) {
72797
+ console.log(`[DEBUG] JSON fixing: Agent returned ${cleaned.length} chars`);
72798
+ }
72799
+ return cleaned;
72800
+ } catch (error2) {
72801
+ if (this.options.debug) {
72802
+ console.error(`[DEBUG] JSON fixing failed: ${error2.message}`);
72803
+ }
72804
+ throw new Error(`Failed to fix JSON: ${error2.message}`);
72805
+ }
72806
+ }
72807
+ /**
72808
+ * Get token usage information from the specialized agent
72809
+ * @returns {Object} - Token usage statistics
72810
+ */
72811
+ getTokenUsage() {
72812
+ return this.agent ? this.agent.getTokenUsage() : null;
72813
+ }
72814
+ /**
72815
+ * Cancel any ongoing operations
72816
+ */
72817
+ cancel() {
72818
+ if (this.agent) {
72819
+ this.agent.cancel();
72820
+ }
72821
+ }
72822
+ };
72404
72823
  MermaidFixingAgent = class {
72405
72824
  constructor(options = {}) {
72406
72825
  this.ProbeAgent = null;
@@ -73393,6 +73812,7 @@ var init_ProbeAgent = __esm({
73393
73812
  * @param {number} [options.maxResponseTokens] - Maximum tokens for AI responses
73394
73813
  * @param {number} [options.maxIterations] - Maximum tool iterations (overrides MAX_TOOL_ITERATIONS env var)
73395
73814
  * @param {boolean} [options.disableMermaidValidation=false] - Disable automatic mermaid diagram validation and fixing
73815
+ * @param {boolean} [options.disableJsonValidation=false] - Disable automatic JSON validation and fixing (prevents infinite recursion in JsonFixingAgent)
73396
73816
  * @param {boolean} [options.enableMcp=false] - Enable MCP tool integration
73397
73817
  * @param {string} [options.mcpConfigPath] - Path to MCP configuration file
73398
73818
  * @param {Object} [options.mcpConfig] - MCP configuration object (overrides mcpConfigPath)
@@ -73412,6 +73832,7 @@ var init_ProbeAgent = __esm({
73412
73832
  this.maxResponseTokens = options.maxResponseTokens || parseInt(process.env.MAX_RESPONSE_TOKENS || "0", 10) || null;
73413
73833
  this.maxIterations = options.maxIterations || null;
73414
73834
  this.disableMermaidValidation = !!options.disableMermaidValidation;
73835
+ this.disableJsonValidation = !!options.disableJsonValidation;
73415
73836
  this.storageAdapter = options.storageAdapter || new InMemoryStorageAdapter();
73416
73837
  this.hooks = new HookManager();
73417
73838
  if (options.hooks) {
@@ -74626,15 +75047,16 @@ Remember: Use proper XML format with BOTH opening and closing tags:
74626
75047
  <parameter>value</parameter>
74627
75048
  </tool_name>
74628
75049
 
74629
- IMPORTANT: A schema was provided. You MUST respond with data that matches this schema.
74630
- Use attempt_completion with your response directly inside the tags:
75050
+ IMPORTANT: A schema was provided for the final output format. You have two options:
74631
75051
 
75052
+ Option 1 - Use attempt_completion with your complete answer:
74632
75053
  <attempt_completion>
74633
- [Your response content matching the provided schema format]
75054
+ [Your complete answer here - will be automatically formatted to match the schema]
74634
75055
  </attempt_completion>
74635
75056
 
74636
- Your response must conform to this schema:
74637
- ${options.schema}`;
75057
+ Option 2 - Provide a natural response without any tool, and it will be automatically formatted.
75058
+
75059
+ Do NOT try to format your response as JSON yourself - this will be done automatically.`;
74638
75060
  } else {
74639
75061
  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.
74640
75062
 
@@ -74781,6 +75203,10 @@ Convert your previous response content into actual JSON data that follows this s
74781
75203
  console.log(`[DEBUG] JSON validation: Starting validation process for schema response`);
74782
75204
  console.log(`[DEBUG] JSON validation: Response length: ${finalResult.length} chars`);
74783
75205
  }
75206
+ finalResult = cleanSchemaResponse(finalResult);
75207
+ if (this.debug) {
75208
+ console.log(`[DEBUG] JSON validation: After cleaning, length: ${finalResult.length} chars`);
75209
+ }
74784
75210
  if (this.tracer) {
74785
75211
  this.tracer.recordJsonValidationEvent("started", {
74786
75212
  "json_validation.response_length": finalResult.length,
@@ -74792,75 +75218,66 @@ Convert your previous response content into actual JSON data that follows this s
74792
75218
  const maxRetries = 3;
74793
75219
  if (validation.isValid && isJsonSchemaDefinition(finalResult, { debug: this.debug })) {
74794
75220
  if (this.debug) {
74795
- console.log(`[DEBUG] JSON validation: Response is a JSON schema definition instead of data, correcting...`);
75221
+ console.log(`[DEBUG] JSON validation: Response is a JSON schema definition instead of data, needs correction...`);
74796
75222
  }
74797
- const schemaDefinitionPrompt = createSchemaDefinitionCorrectionPrompt(
74798
- finalResult,
74799
- options.schema,
74800
- 0
74801
- );
74802
- finalResult = await this.answer(schemaDefinitionPrompt, [], {
74803
- ...options,
74804
- _schemaFormatted: true
74805
- });
74806
- finalResult = cleanSchemaResponse(finalResult);
74807
- validation = validateJsonResponse(finalResult);
74808
- retryCount = 1;
75223
+ validation = {
75224
+ isValid: false,
75225
+ error: "Response is a JSON schema definition instead of actual data",
75226
+ enhancedError: "Response is a JSON schema definition instead of actual data. Please return data that conforms to the schema, not the schema itself."
75227
+ };
74809
75228
  }
74810
- while (!validation.isValid && retryCount < maxRetries) {
75229
+ if (!validation.isValid) {
74811
75230
  if (this.debug) {
74812
- console.log(`[DEBUG] JSON validation: Validation failed (attempt ${retryCount + 1}/${maxRetries}):`, validation.error);
74813
- console.log(`[DEBUG] JSON validation: Invalid response sample: ${finalResult.substring(0, 300)}${finalResult.length > 300 ? "..." : ""}`);
75231
+ console.log(`[DEBUG] JSON validation: Starting separate JsonFixingAgent session...`);
74814
75232
  }
74815
- let correctionPrompt;
74816
- try {
74817
- if (isJsonSchemaDefinition(finalResult, { debug: this.debug })) {
74818
- if (this.debug) {
74819
- console.log(`[DEBUG] JSON validation: Response is still a schema definition, using specialized correction`);
74820
- }
74821
- correctionPrompt = createSchemaDefinitionCorrectionPrompt(
74822
- finalResult,
74823
- options.schema,
74824
- retryCount
74825
- );
74826
- } else {
74827
- correctionPrompt = createJsonCorrectionPrompt(
74828
- finalResult,
75233
+ const { JsonFixingAgent: JsonFixingAgent2 } = await Promise.resolve().then(() => (init_schemaUtils(), schemaUtils_exports));
75234
+ const jsonFixer = new JsonFixingAgent2({
75235
+ path: this.allowedFolders[0],
75236
+ provider: this.clientApiProvider,
75237
+ model: this.model,
75238
+ debug: this.debug,
75239
+ tracer: this.tracer
75240
+ });
75241
+ let currentResult = finalResult;
75242
+ let currentValidation = validation;
75243
+ while (!currentValidation.isValid && retryCount < maxRetries) {
75244
+ if (this.debug) {
75245
+ console.log(`[DEBUG] JSON validation: Validation failed (attempt ${retryCount + 1}/${maxRetries}):`, currentValidation.error);
75246
+ console.log(`[DEBUG] JSON validation: Invalid response sample: ${currentResult.substring(0, 300)}${currentResult.length > 300 ? "..." : ""}`);
75247
+ }
75248
+ try {
75249
+ currentResult = await jsonFixer.fixJson(
75250
+ currentResult,
74829
75251
  options.schema,
74830
- validation.error,
74831
- retryCount
75252
+ currentValidation,
75253
+ retryCount + 1
74832
75254
  );
75255
+ currentValidation = validateJsonResponse(currentResult, { debug: this.debug });
75256
+ retryCount++;
75257
+ if (this.debug) {
75258
+ if (!currentValidation.isValid && retryCount < maxRetries) {
75259
+ console.log(`[DEBUG] JSON validation: Still invalid after correction ${retryCount}, retrying...`);
75260
+ console.log(`[DEBUG] JSON validation: Corrected response sample: ${currentResult.substring(0, 300)}${currentResult.length > 300 ? "..." : ""}`);
75261
+ } else if (currentValidation.isValid) {
75262
+ console.log(`[DEBUG] JSON validation: Successfully corrected after ${retryCount} attempts with JsonFixingAgent`);
75263
+ }
75264
+ }
75265
+ } catch (error2) {
75266
+ if (this.debug) {
75267
+ console.error(`[DEBUG] JSON validation: JsonFixingAgent error on attempt ${retryCount + 1}:`, error2.message);
75268
+ }
75269
+ break;
74833
75270
  }
74834
- } catch (error2) {
74835
- correctionPrompt = createJsonCorrectionPrompt(
74836
- finalResult,
74837
- options.schema,
74838
- validation.error,
74839
- retryCount
74840
- );
74841
75271
  }
74842
- finalResult = await this.answer(correctionPrompt, [], {
74843
- ...options,
74844
- _schemaFormatted: true
74845
- });
74846
- finalResult = cleanSchemaResponse(finalResult);
74847
- validation = validateJsonResponse(finalResult, { debug: this.debug });
74848
- retryCount++;
74849
- if (this.debug) {
74850
- if (!validation.isValid && retryCount < maxRetries) {
74851
- console.log(`[DEBUG] JSON validation: Still invalid after correction ${retryCount}, retrying...`);
74852
- console.log(`[DEBUG] JSON validation: Corrected response sample: ${finalResult.substring(0, 300)}${finalResult.length > 300 ? "..." : ""}`);
74853
- } else if (validation.isValid) {
74854
- console.log(`[DEBUG] JSON validation: Successfully corrected after ${retryCount} attempts`);
74855
- }
75272
+ finalResult = currentResult;
75273
+ validation = currentValidation;
75274
+ if (!validation.isValid && this.debug) {
75275
+ console.log(`[DEBUG] JSON validation: Still invalid after ${maxRetries} correction attempts with JsonFixingAgent:`, validation.error);
75276
+ console.log(`[DEBUG] JSON validation: Final invalid response: ${finalResult.substring(0, 500)}${finalResult.length > 500 ? "..." : ""}`);
75277
+ } else if (validation.isValid && this.debug) {
75278
+ console.log(`[DEBUG] JSON validation: Final validation successful`);
74856
75279
  }
74857
75280
  }
74858
- if (!validation.isValid && this.debug) {
74859
- console.log(`[DEBUG] JSON validation: Still invalid after ${maxRetries} correction attempts:`, validation.error);
74860
- console.log(`[DEBUG] JSON validation: Final invalid response: ${finalResult.substring(0, 500)}${finalResult.length > 500 ? "..." : ""}`);
74861
- } else if (validation.isValid && this.debug) {
74862
- console.log(`[DEBUG] JSON validation: Final validation successful`);
74863
- }
74864
75281
  if (this.tracer) {
74865
75282
  this.tracer.recordJsonValidationEvent("completed", {
74866
75283
  "json_validation.success": validation.isValid,
@@ -75108,6 +75525,7 @@ Convert your previous response content into actual JSON data that follows this s
75108
75525
  maxResponseTokens: this.maxResponseTokens,
75109
75526
  maxIterations: this.maxIterations,
75110
75527
  disableMermaidValidation: this.disableMermaidValidation,
75528
+ disableJsonValidation: this.disableJsonValidation,
75111
75529
  enableMcp: !!this.mcpBridge,
75112
75530
  mcpConfig: this.mcpConfig,
75113
75531
  enableBash: this.enableBash,
@@ -75126,11 +75544,44 @@ Convert your previous response content into actual JSON data that follows this s
75126
75544
  }
75127
75545
  /**
75128
75546
  * Internal method to strip internal/temporary messages from history
75129
- * Removes: schema reminders, mermaid fix prompts, tool use reminders, etc.
75130
- * Keeps: system message, user messages, assistant responses, tool results
75547
+ * Strategy: Find the FIRST schema-related message and truncate everything from that point onwards.
75548
+ * This ensures that all schema formatting iterations (IMPORTANT, CRITICAL, corrections, etc.) are removed.
75549
+ * Keeps: system message, user messages, assistant responses, tool results up to the first schema message
75131
75550
  * @private
75132
75551
  */
75133
75552
  _stripInternalMessages(history, keepSystemMessage = true) {
75553
+ let firstSchemaMessageIndex = -1;
75554
+ for (let i3 = 0; i3 < history.length; i3++) {
75555
+ const message = history[i3];
75556
+ if (message.role === "system") {
75557
+ continue;
75558
+ }
75559
+ if (this._isSchemaMessage(message)) {
75560
+ firstSchemaMessageIndex = i3;
75561
+ if (this.debug) {
75562
+ console.log(`[DEBUG] Found first schema message at index ${i3}, truncating from here`);
75563
+ }
75564
+ break;
75565
+ }
75566
+ }
75567
+ if (firstSchemaMessageIndex === -1) {
75568
+ return this._stripNonSchemaInternalMessages(history, keepSystemMessage);
75569
+ }
75570
+ const truncated = history.slice(0, firstSchemaMessageIndex);
75571
+ const filtered = this._stripNonSchemaInternalMessages(truncated, keepSystemMessage);
75572
+ if (this.debug) {
75573
+ const removedCount = history.length - filtered.length;
75574
+ console.log(`[DEBUG] Truncated at schema message (index ${firstSchemaMessageIndex}) and filtered non-schema internal messages`);
75575
+ console.log(`[DEBUG] Removed ${removedCount} messages total (${history.length} \u2192 ${filtered.length})`);
75576
+ }
75577
+ return filtered;
75578
+ }
75579
+ /**
75580
+ * Strip non-schema internal messages (mermaid fixes, tool reminders, etc.) individually
75581
+ * Used when no schema messages are present in history
75582
+ * @private
75583
+ */
75584
+ _stripNonSchemaInternalMessages(history, keepSystemMessage = true) {
75134
75585
  const filtered = [];
75135
75586
  for (let i3 = 0; i3 < history.length; i3++) {
75136
75587
  const message = history[i3];
@@ -75142,9 +75593,9 @@ Convert your previous response content into actual JSON data that follows this s
75142
75593
  }
75143
75594
  continue;
75144
75595
  }
75145
- if (this._isInternalMessage(message, i3, history)) {
75596
+ if (this._isNonSchemaInternalMessage(message)) {
75146
75597
  if (this.debug) {
75147
- console.log(`[DEBUG] Stripping internal message at index ${i3}: ${message.role}`);
75598
+ console.log(`[DEBUG] Stripping non-schema internal message at index ${i3}: ${message.role}`);
75148
75599
  }
75149
75600
  continue;
75150
75601
  }
@@ -75153,20 +75604,50 @@ Convert your previous response content into actual JSON data that follows this s
75153
75604
  return filtered;
75154
75605
  }
75155
75606
  /**
75156
- * Determine if a message is an internal/temporary message
75607
+ * Check if a message is schema-related (IMPORTANT, CRITICAL, etc.)
75157
75608
  * @private
75158
75609
  */
75159
- _isInternalMessage(message, index, history) {
75610
+ _isSchemaMessage(message) {
75160
75611
  if (message.role !== "user") {
75161
75612
  return false;
75162
75613
  }
75163
75614
  if (!message.content) {
75164
75615
  return false;
75165
75616
  }
75166
- const content = typeof message.content === "string" ? message.content : JSON.stringify(message.content);
75167
- 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:")) {
75617
+ let content;
75618
+ try {
75619
+ content = typeof message.content === "string" ? message.content : JSON.stringify(message.content);
75620
+ } catch (error2) {
75621
+ if (this.debug) {
75622
+ console.log(`[DEBUG] Could not stringify message content in _isSchemaMessage: ${error2.message}`);
75623
+ }
75624
+ return false;
75625
+ }
75626
+ 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")) {
75168
75627
  return true;
75169
75628
  }
75629
+ return false;
75630
+ }
75631
+ /**
75632
+ * Check if a message is a non-schema internal message (mermaid, tool reminders, JSON corrections)
75633
+ * @private
75634
+ */
75635
+ _isNonSchemaInternalMessage(message) {
75636
+ if (message.role !== "user") {
75637
+ return false;
75638
+ }
75639
+ if (!message.content) {
75640
+ return false;
75641
+ }
75642
+ let content;
75643
+ try {
75644
+ content = typeof message.content === "string" ? message.content : JSON.stringify(message.content);
75645
+ } catch (error2) {
75646
+ if (this.debug) {
75647
+ console.log(`[DEBUG] Could not stringify message content in _isNonSchemaInternalMessage: ${error2.message}`);
75648
+ }
75649
+ return false;
75650
+ }
75170
75651
  if (content.includes("Please use one of the available tools") && content.includes("or use attempt_completion") && content.includes("Remember: Use proper XML format")) {
75171
75652
  return true;
75172
75653
  }