@hiper2d/ai-agents 0.29.0 → 0.30.0

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/dist/index.mjs CHANGED
@@ -589,6 +589,77 @@ function needsPromptBasedSchema(provider) {
589
589
  return provider === "anthropic";
590
590
  }
591
591
 
592
+ // src/errors.ts
593
+ var ModelError = class extends Error {
594
+ modelType;
595
+ constructor(message, modelType) {
596
+ super(message);
597
+ this.modelType = modelType;
598
+ }
599
+ };
600
+ var ModelOverloadError = class extends ModelError {
601
+ retryable;
602
+ constructor(message, modelType, retryable = true) {
603
+ super(message, modelType);
604
+ this.name = "ModelOverloadError";
605
+ this.retryable = retryable;
606
+ }
607
+ };
608
+ var ModelRateLimitError = class extends ModelError {
609
+ retryAfter;
610
+ // seconds to wait before retrying
611
+ constructor(message, modelType, retryAfter) {
612
+ super(message, modelType);
613
+ this.name = "ModelRateLimitError";
614
+ this.retryAfter = retryAfter;
615
+ }
616
+ };
617
+ var ModelUnavailableError = class extends ModelError {
618
+ reason;
619
+ constructor(message, modelType, reason = "unknown") {
620
+ super(message, modelType);
621
+ this.name = "ModelUnavailableError";
622
+ this.reason = reason;
623
+ }
624
+ };
625
+ var ModelAuthenticationError = class extends ModelError {
626
+ constructor(message, modelType) {
627
+ super(message, modelType);
628
+ this.name = "ModelAuthenticationError";
629
+ }
630
+ };
631
+ var ModelQuotaExceededError = class extends ModelError {
632
+ constructor(message, modelType) {
633
+ super(message, modelType);
634
+ this.name = "ModelQuotaExceededError";
635
+ }
636
+ };
637
+ var ModelInvalidResponseError = class extends ModelError {
638
+ truncated;
639
+ retries;
640
+ constructor(modelType, detail, truncated = false) {
641
+ super(`${modelType} failed to produce a valid response: ${detail}`, modelType);
642
+ this.name = "ModelInvalidResponseError";
643
+ this.truncated = truncated;
644
+ }
645
+ };
646
+ var ModelTimeoutError = class extends ModelError {
647
+ timeoutMs;
648
+ constructor(modelType, timeoutMs) {
649
+ super(`${modelType} did not respond within ${Math.round(timeoutMs / 1e3)}s`, modelType);
650
+ this.name = "ModelTimeoutError";
651
+ this.timeoutMs = timeoutMs;
652
+ }
653
+ };
654
+ var ModelRefusalError = class extends ModelError {
655
+ reason;
656
+ constructor(modelType, message = `${modelType} refused to answer (stop_reason: refusal)`, reason) {
657
+ super(message, modelType);
658
+ this.name = "ModelRefusalError";
659
+ this.reason = reason;
660
+ }
661
+ };
662
+
592
663
  // src/json-response-parser.ts
593
664
  function extractFirstJsonObject(text) {
594
665
  let searchFrom = 0;
@@ -633,7 +704,7 @@ function normalizeNestedReply(value, log) {
633
704
  return value;
634
705
  }
635
706
  function parseAndValidateLlmJson(rawReply, zodSchema, log = () => {
636
- }) {
707
+ }, model = "The model") {
637
708
  const cleaned = cleanResponse(rawReply);
638
709
  const candidates = [cleaned];
639
710
  if (cleaned.startsWith('"') && cleaned.endsWith('"')) {
@@ -690,81 +761,11 @@ function parseAndValidateLlmJson(rawReply, zodSchema, log = () => {
690
761
  }
691
762
  if (zodError !== null) {
692
763
  log(`Zod validation failed: ${JSON.stringify(zodError.errors)}`);
693
- throw new Error(`Response validation failed: ${zodError.message}`);
764
+ throw new ModelInvalidResponseError(model, `Response validation failed: ${zodError.message}`);
694
765
  }
695
- throw new Error(`Failed to parse JSON response: ${parseError}. First 200 chars: ${cleaned.slice(0, 200)}`);
766
+ throw new ModelInvalidResponseError(model, `Failed to parse JSON response: ${parseError}. First 200 chars: ${cleaned.slice(0, 200)}`);
696
767
  }
697
768
 
698
- // src/errors.ts
699
- var ModelError = class extends Error {
700
- modelType;
701
- constructor(message, modelType) {
702
- super(message);
703
- this.modelType = modelType;
704
- }
705
- };
706
- var ModelOverloadError = class extends ModelError {
707
- retryable;
708
- constructor(message, modelType, retryable = true) {
709
- super(message, modelType);
710
- this.name = "ModelOverloadError";
711
- this.retryable = retryable;
712
- }
713
- };
714
- var ModelRateLimitError = class extends ModelError {
715
- retryAfter;
716
- // seconds to wait before retrying
717
- constructor(message, modelType, retryAfter) {
718
- super(message, modelType);
719
- this.name = "ModelRateLimitError";
720
- this.retryAfter = retryAfter;
721
- }
722
- };
723
- var ModelUnavailableError = class extends ModelError {
724
- reason;
725
- constructor(message, modelType, reason = "unknown") {
726
- super(message, modelType);
727
- this.name = "ModelUnavailableError";
728
- this.reason = reason;
729
- }
730
- };
731
- var ModelAuthenticationError = class extends ModelError {
732
- constructor(message, modelType) {
733
- super(message, modelType);
734
- this.name = "ModelAuthenticationError";
735
- }
736
- };
737
- var ModelQuotaExceededError = class extends ModelError {
738
- constructor(message, modelType) {
739
- super(message, modelType);
740
- this.name = "ModelQuotaExceededError";
741
- }
742
- };
743
- var ModelInvalidResponseError = class extends ModelError {
744
- truncated;
745
- constructor(modelType, detail, truncated = false) {
746
- super(`${modelType} failed to produce a valid response: ${detail}`, modelType);
747
- this.name = "ModelInvalidResponseError";
748
- this.truncated = truncated;
749
- }
750
- };
751
- var ModelTimeoutError = class extends ModelError {
752
- timeoutMs;
753
- constructor(modelType, timeoutMs) {
754
- super(`${modelType} did not respond within ${Math.round(timeoutMs / 1e3)}s`, modelType);
755
- this.name = "ModelTimeoutError";
756
- this.timeoutMs = timeoutMs;
757
- }
758
- };
759
- var ModelRefusalError = class extends ModelError {
760
- reason;
761
- constructor(modelType, message = `${modelType} refused to answer (stop_reason: refusal)`, reason) {
762
- super(message, modelType);
763
- this.name = "ModelRefusalError";
764
- this.reason = reason;
765
- }
766
- };
767
-
768
769
  // src/thinking-utils.ts
769
770
  function stripInlineThinking(raw) {
770
771
  let thinking = "";
@@ -2363,6 +2364,10 @@ var beforeAskHook;
2363
2364
  function setBeforeAskHook(hook) {
2364
2365
  beforeAskHook = hook;
2365
2366
  }
2367
+ var retryHook;
2368
+ function setRetryHook(hook) {
2369
+ retryHook = hook;
2370
+ }
2366
2371
  var AbstractAgent = class {
2367
2372
  name;
2368
2373
  gameId;
@@ -2389,6 +2394,17 @@ var AbstractAgent = class {
2389
2394
  * instance for calls that legitimately run long, like maxOutputTokens.
2390
2395
  */
2391
2396
  requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS;
2397
+ /**
2398
+ * How many times one ask is re-sent after a ModelInvalidResponseError that is not a
2399
+ * cap hit: the model answered with nothing, or with text that is not the JSON the
2400
+ * schema asked for. Those are one-off generation failures the same prompt usually
2401
+ * gets right on the next try, unlike timeouts, refusals and transport errors, which
2402
+ * are never retried here. 0 (the default) hands every failure to the caller. A
2403
+ * truncated response is excluded because re-running it re-buys the whole output at
2404
+ * the cap. Each re-send runs the before-ask hook again (it is a new paid call) and
2405
+ * fires the retry hook; the error finally thrown carries `retries`.
2406
+ */
2407
+ invalidResponseRetries = 0;
2392
2408
  instruction;
2393
2409
  /**
2394
2410
  * The instruction split on CACHE_TIER_MARKER: [shared static tier, per-bot tier].
@@ -2415,26 +2431,83 @@ var AbstractAgent = class {
2415
2431
  this.thinkingBudgetTokens = modelConfig?.thinkingBudgetTokens;
2416
2432
  }
2417
2433
  /**
2418
- * Public ask API — template methods that time the provider call and stamp `durationMs`
2419
- * into the returned TokenUsage. Subclasses implement doAskWithZodSchema/doAskText and
2434
+ * Public ask API — template methods that run the before-ask hook, time the provider
2435
+ * call, stamp `durationMs` into the returned TokenUsage and apply the
2436
+ * invalidResponseRetries policy. Subclasses implement doAskWithZodSchema/doAskText and
2420
2437
  * must NOT override these.
2421
2438
  */
2422
2439
  async askWithZodSchema(zodSchema, messages) {
2423
- if (beforeAskHook) await beforeAskHook(this);
2424
- const startedAt = Date.now();
2440
+ return this.askWithRetries(() => this.doAskWithZodSchema(zodSchema, messages));
2441
+ }
2442
+ async askText(messages) {
2443
+ return this.askWithRetries(() => this.doAskText(messages));
2444
+ }
2445
+ /**
2446
+ * One attempt per loop; an empty or malformed answer (ModelInvalidResponseError, not
2447
+ * truncated) is re-sent up to invalidResponseRetries times, with the retry hook told
2448
+ * before each re-send. Anything else — a timeout, a refusal, a transport error, or the
2449
+ * last allowed attempt failing — is thrown as-is, stamped with the retry count. Every
2450
+ * settle function the hook returned runs once the ask is over, whichever way it ended.
2451
+ */
2452
+ async askWithRetries(call) {
2453
+ const settled = [];
2454
+ let retries = 0;
2425
2455
  try {
2426
- const [result, thinking, usage, signature] = await this.withTimeout(this.doAskWithZodSchema(zodSchema, messages));
2427
- return [result, thinking, this.stampDuration(usage, startedAt), signature];
2428
- } catch (error) {
2429
- this.stampErrorDuration(error, startedAt);
2430
- throw error;
2456
+ while (true) {
2457
+ try {
2458
+ return await this.attempt(call);
2459
+ } catch (error) {
2460
+ if (retries > 0 && error && typeof error === "object") {
2461
+ error.retries = retries;
2462
+ }
2463
+ if (!(error instanceof ModelInvalidResponseError) || error.truncated || retries >= this.invalidResponseRetries) {
2464
+ throw error;
2465
+ }
2466
+ retries++;
2467
+ logger.warn(`${this.name} (${this.model}): ${error.message} \u2014 asking again (retry ${retries} of ${this.invalidResponseRetries})`, {
2468
+ gameId: this.gameId,
2469
+ userId: this.userId,
2470
+ agentName: this.name,
2471
+ model: this.model,
2472
+ activity: "llm_retry",
2473
+ attempt: retries,
2474
+ error: error.message
2475
+ });
2476
+ if (retryHook) {
2477
+ try {
2478
+ const onSettled = await retryHook({ agent: this, model: this.model, error, attempt: retries });
2479
+ if (typeof onSettled === "function") settled.push(onSettled);
2480
+ } catch (hookError) {
2481
+ logger.warn(`${this.name} (${this.model}): retry hook failed, retrying anyway`, {
2482
+ gameId: this.gameId,
2483
+ agentName: this.name,
2484
+ model: this.model,
2485
+ error: hookError instanceof Error ? hookError.message : String(hookError)
2486
+ });
2487
+ }
2488
+ }
2489
+ }
2490
+ }
2491
+ } finally {
2492
+ for (const onSettled of settled) {
2493
+ try {
2494
+ await onSettled();
2495
+ } catch (hookError) {
2496
+ logger.warn(`${this.name} (${this.model}): retry settle hook failed`, {
2497
+ gameId: this.gameId,
2498
+ agentName: this.name,
2499
+ model: this.model,
2500
+ error: hookError instanceof Error ? hookError.message : String(hookError)
2501
+ });
2502
+ }
2503
+ }
2431
2504
  }
2432
2505
  }
2433
- async askText(messages) {
2506
+ async attempt(call) {
2434
2507
  if (beforeAskHook) await beforeAskHook(this);
2435
2508
  const startedAt = Date.now();
2436
2509
  try {
2437
- const [content, thinking, usage, signature] = await this.withTimeout(this.doAskText(messages));
2510
+ const [content, thinking, usage, signature] = await this.withTimeout(call());
2438
2511
  return [content, thinking, this.stampDuration(usage, startedAt), signature];
2439
2512
  } catch (error) {
2440
2513
  this.stampErrorDuration(error, startedAt);
@@ -2734,7 +2807,7 @@ ${instruction}`);
2734
2807
  reason === "max_output_tokens"
2735
2808
  );
2736
2809
  }
2737
- throw new Error(this.errorMessages.emptyResponse);
2810
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
2738
2811
  }
2739
2812
  let tokenUsage;
2740
2813
  if (response.usage) {
@@ -3015,7 +3088,7 @@ var ClaudeAgent = class extends AbstractAgent {
3015
3088
  throw new ModelRefusalError(this.model, void 0, "refusal");
3016
3089
  }
3017
3090
  if (!("content" in response) || !Array.isArray(response.content) || response.content.length === 0) {
3018
- throw new Error(this.errorMessages.emptyResponse);
3091
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3019
3092
  }
3020
3093
  let textContent = null;
3021
3094
  let thinkingContent = "";
@@ -3032,9 +3105,9 @@ var ClaudeAgent = class extends AbstractAgent {
3032
3105
  }
3033
3106
  }
3034
3107
  if (!textContent) {
3035
- throw new Error(this.errorMessages.invalidFormat);
3108
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.invalidFormat);
3036
3109
  }
3037
- const parsedData = parseAndValidateLlmJson(textContent, zodSchema, (m) => this.logger(m));
3110
+ const parsedData = parseAndValidateLlmJson(textContent, zodSchema, (m) => this.logger(m), this.model);
3038
3111
  this.logger(`\u2705 Response validated successfully with Zod schema`);
3039
3112
  let tokenUsage;
3040
3113
  if (response.usage) {
@@ -3113,7 +3186,7 @@ var ClaudeAgent = class extends AbstractAgent {
3113
3186
  throw new ModelRefusalError(this.model, void 0, "refusal");
3114
3187
  }
3115
3188
  if (!("content" in response) || !Array.isArray(response.content) || response.content.length === 0) {
3116
- throw new Error(this.errorMessages.emptyResponse);
3189
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3117
3190
  }
3118
3191
  const textParts = [];
3119
3192
  let thinkingContent = "";
@@ -3131,7 +3204,7 @@ var ClaudeAgent = class extends AbstractAgent {
3131
3204
  }
3132
3205
  const textContent = textParts.join("");
3133
3206
  if (!textContent) {
3134
- throw new Error(this.errorMessages.emptyResponse);
3207
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3135
3208
  }
3136
3209
  let tokenUsage;
3137
3210
  if (response.usage) {
@@ -3203,7 +3276,7 @@ function throwForEmptyGeminiResponse(model, response, fallback) {
3203
3276
  const bits = [`finishReason=${finishReason ?? "none"}`];
3204
3277
  if (!response?.candidates?.length) bits.push("no candidates");
3205
3278
  if (finishMessage) bits.push(`finishMessage="${finishMessage}"`);
3206
- throw new Error(`${fallback} (${bits.join(", ")})`);
3279
+ throw new ModelInvalidResponseError(model, `${fallback} (${bits.join(", ")})`);
3207
3280
  }
3208
3281
  var GoogleAgent = class extends AbstractAgent {
3209
3282
  client;
@@ -3399,7 +3472,7 @@ var GoogleAgent = class extends AbstractAgent {
3399
3472
  if (!response.text) {
3400
3473
  throwForEmptyGeminiResponse(this.model, response, this.errorMessages.emptyResponse);
3401
3474
  }
3402
- const parsedData = parseAndValidateLlmJson(response.text, zodSchema, (m) => this.logger(m));
3475
+ const parsedData = parseAndValidateLlmJson(response.text, zodSchema, (m) => this.logger(m), this.model);
3403
3476
  if (parsedData) {
3404
3477
  this.logReply(parsedData, thinkingContent || void 0, tokenUsage);
3405
3478
  }
@@ -3635,7 +3708,7 @@ ${instruction}`);
3635
3708
  processReply(response) {
3636
3709
  const message = response?.choices?.[0]?.message;
3637
3710
  if (!message || !message.content) {
3638
- throw new Error(this.errorMessages.emptyResponse);
3711
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3639
3712
  }
3640
3713
  let reply = message.content;
3641
3714
  if (Array.isArray(reply)) {
@@ -3740,12 +3813,12 @@ ${schemaDescription}`
3740
3813
  throw new Error(this.errorMessages.apiError(apiError));
3741
3814
  }
3742
3815
  if (!response || !response.choices || response.choices.length === 0) {
3743
- throw new Error(this.errorMessages.emptyResponse);
3816
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3744
3817
  }
3745
3818
  const choice = response.choices[0];
3746
3819
  const content = choice.message?.content;
3747
3820
  if (!content) {
3748
- throw new Error(this.errorMessages.invalidFormat);
3821
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.invalidFormat);
3749
3822
  }
3750
3823
  let responseText;
3751
3824
  let thinkingContent = "";
@@ -3758,7 +3831,7 @@ ${schemaDescription}`
3758
3831
  } else {
3759
3832
  responseText = JSON.stringify(content);
3760
3833
  }
3761
- const parsedData = parseAndValidateLlmJson(responseText, zodSchema, (m) => this.logger(m));
3834
+ const parsedData = parseAndValidateLlmJson(responseText, zodSchema, (m) => this.logger(m), this.model);
3762
3835
  this.logger(`\u2705 Response validated successfully with Zod schema`);
3763
3836
  const tokenUsage = this.extractTokenUsage(response);
3764
3837
  if (parsedData) {
@@ -3767,6 +3840,7 @@ ${schemaDescription}`
3767
3840
  return [parsedData, thinkingContent, tokenUsage];
3768
3841
  } catch (error) {
3769
3842
  this.logger(this.logTemplates.error(this.name, error));
3843
+ if (error instanceof ModelError) throw error;
3770
3844
  throw new Error(this.errorMessages.apiError(error));
3771
3845
  }
3772
3846
  }
@@ -3796,12 +3870,13 @@ ${schemaDescription}`
3796
3870
  }
3797
3871
  const [content, thinkingContent, tokenUsage] = this.processReply(response);
3798
3872
  if (!content) {
3799
- throw new Error(this.errorMessages.emptyResponse);
3873
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3800
3874
  }
3801
3875
  this.logReply(content, thinkingContent || void 0, tokenUsage);
3802
3876
  return [content, thinkingContent, tokenUsage];
3803
3877
  } catch (error) {
3804
3878
  this.logger(this.logTemplates.error(this.name, error));
3879
+ if (error instanceof ModelError) throw error;
3805
3880
  throw new Error(this.errorMessages.apiError(error));
3806
3881
  }
3807
3882
  }
@@ -3818,7 +3893,7 @@ var DeepSeekV2Agent = class extends AbstractAgent {
3818
3893
  };
3819
3894
  // Error message templates
3820
3895
  errorMessages = {
3821
- emptyResponse: "Empty or undefined response from DeepSeek API",
3896
+ emptyResponse: (finishReason) => `Empty or undefined response from DeepSeek API (finish_reason: ${finishReason ?? "unknown"})`,
3822
3897
  invalidFormat: "Invalid response format from DeepSeek API",
3823
3898
  apiError: (error) => `Failed to get response from DeepSeek API: ${error instanceof Error ? error.message : String(error)}`
3824
3899
  };
@@ -3923,14 +3998,14 @@ ${schemaDescription}`
3923
3998
  }
3924
3999
  const rawContent = response.choices[0]?.message?.content;
3925
4000
  if (!rawContent) {
3926
- throw new Error(this.errorMessages.emptyResponse);
4001
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(response.choices[0]?.finish_reason));
3927
4002
  }
3928
4003
  const { text: content, thinking: inlineThinking } = stripInlineThinking(rawContent);
3929
4004
  thinkingContent = mergeThinking(thinkingContent, inlineThinking);
3930
4005
  if (!content) {
3931
- throw new Error(this.errorMessages.emptyResponse);
4006
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(response.choices[0]?.finish_reason));
3932
4007
  }
3933
- const parsedData = parseAndValidateLlmJson(content, zodSchema, (m) => this.logger(m));
4008
+ const parsedData = parseAndValidateLlmJson(content, zodSchema, (m) => this.logger(m), this.model);
3934
4009
  this.logger(`\u2705 Response validated successfully with Zod schema`);
3935
4010
  const usageResult = extractUsageAndCalculateCost(this.model, response);
3936
4011
  let tokenUsage;
@@ -3951,6 +4026,7 @@ ${schemaDescription}`
3951
4026
  return [parsedData, thinkingContent, tokenUsage];
3952
4027
  } catch (error) {
3953
4028
  this.logger(this.logTemplates.error(this.name, error));
4029
+ if (error instanceof ModelError) throw error;
3954
4030
  throw new Error(this.errorMessages.apiError(error));
3955
4031
  }
3956
4032
  }
@@ -3986,12 +4062,12 @@ ${schemaDescription}`
3986
4062
  }
3987
4063
  const rawContent = response.choices[0]?.message?.content;
3988
4064
  if (!rawContent) {
3989
- throw new Error(this.errorMessages.emptyResponse);
4065
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(response.choices[0]?.finish_reason));
3990
4066
  }
3991
4067
  const { text: content, thinking: inlineThinking } = stripInlineThinking(rawContent);
3992
4068
  thinkingContent = mergeThinking(thinkingContent, inlineThinking);
3993
4069
  if (!content) {
3994
- throw new Error(this.errorMessages.emptyResponse);
4070
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(response.choices[0]?.finish_reason));
3995
4071
  }
3996
4072
  const usageResult = extractUsageAndCalculateCost(this.model, response);
3997
4073
  let tokenUsage;
@@ -4010,6 +4086,7 @@ ${schemaDescription}`
4010
4086
  return [content, thinkingContent, tokenUsage];
4011
4087
  } catch (error) {
4012
4088
  this.logger(this.logTemplates.error(this.name, error));
4089
+ if (error instanceof ModelError) throw error;
4013
4090
  throw new Error(this.errorMessages.apiError(error));
4014
4091
  }
4015
4092
  }
@@ -4060,10 +4137,10 @@ ${schemaDescription}`;
4060
4137
  const response = await this.createResponse(input, true);
4061
4138
  const { text, reasoningSummary, encryptedReasoning } = this.extractResponseParts(response);
4062
4139
  if (!text) {
4063
- throw new Error(this.errorMessages.emptyResponse);
4140
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4064
4141
  }
4065
4142
  this.logger(`Grok Agent - Found reasoning summary: ${!!reasoningSummary}, encrypted reasoning: ${!!encryptedReasoning}`);
4066
- const parsedData = parseAndValidateLlmJson(text, zodSchema, (m) => this.logger(m));
4143
+ const parsedData = parseAndValidateLlmJson(text, zodSchema, (m) => this.logger(m), this.model);
4067
4144
  this.logger(`\u2705 Response validated successfully with Zod schema`);
4068
4145
  const tokenUsage = this.extractTokenUsage(response);
4069
4146
  if (parsedData) {
@@ -4072,6 +4149,7 @@ ${schemaDescription}`;
4072
4149
  return [parsedData, reasoningSummary, tokenUsage, encryptedReasoning];
4073
4150
  } catch (error) {
4074
4151
  this.logger(this.logTemplates.error(this.name, error));
4152
+ if (error instanceof ModelError) throw error;
4075
4153
  throw new Error(this.errorMessages.apiError(error));
4076
4154
  }
4077
4155
  }
@@ -4087,13 +4165,14 @@ ${schemaDescription}`;
4087
4165
  const response = await this.createResponse(input, false);
4088
4166
  const { text, reasoningSummary, encryptedReasoning } = this.extractResponseParts(response);
4089
4167
  if (!text) {
4090
- throw new Error(this.errorMessages.emptyResponse);
4168
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4091
4169
  }
4092
4170
  const tokenUsage = this.extractTokenUsage(response);
4093
4171
  this.logReply(text, reasoningSummary, tokenUsage);
4094
4172
  return [text, reasoningSummary, tokenUsage, encryptedReasoning];
4095
4173
  } catch (error) {
4096
4174
  this.logger(this.logTemplates.error(this.name, error));
4175
+ if (error instanceof ModelError) throw error;
4097
4176
  throw new Error(this.errorMessages.apiError(error));
4098
4177
  }
4099
4178
  }
@@ -4333,13 +4412,13 @@ ${openAIMessages[0].content}`;
4333
4412
  }
4334
4413
  const rawReply = completion.choices[0]?.message?.content;
4335
4414
  if (!rawReply) {
4336
- throw new Error(this.errorMessages.emptyResponse);
4415
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4337
4416
  }
4338
4417
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4339
4418
  if (!reply) {
4340
- throw new Error(this.errorMessages.emptyResponse);
4419
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4341
4420
  }
4342
- const parsedData = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m));
4421
+ const parsedData = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m), this.model);
4343
4422
  this.logger(`\u2705 Response validated successfully with Zod schema (JSON mode)`);
4344
4423
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4345
4424
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4370,13 +4449,13 @@ ${schemaDescription}`;
4370
4449
  }
4371
4450
  const rawReply = completion.choices[0]?.message?.content;
4372
4451
  if (!rawReply) {
4373
- throw new Error(this.errorMessages.emptyResponse);
4452
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4374
4453
  }
4375
4454
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4376
4455
  if (!reply) {
4377
- throw new Error(this.errorMessages.emptyResponse);
4456
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4378
4457
  }
4379
- const parsedData = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m));
4458
+ const parsedData = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m), this.model);
4380
4459
  this.logger(`\u2705 Response validated successfully with Zod schema (prompt mode)`);
4381
4460
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4382
4461
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4387,6 +4466,7 @@ ${schemaDescription}`;
4387
4466
  }
4388
4467
  } catch (error) {
4389
4468
  this.logger(this.logTemplates.error(this.name, error));
4469
+ if (error instanceof ModelError) throw error;
4390
4470
  throw new Error(this.errorMessages.apiError(error));
4391
4471
  }
4392
4472
  }
@@ -4423,11 +4503,11 @@ ${openAIMessages[0].content}`;
4423
4503
  }
4424
4504
  const rawReply = completion.choices[0]?.message?.content;
4425
4505
  if (!rawReply) {
4426
- throw new Error(this.errorMessages.emptyResponse);
4506
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4427
4507
  }
4428
4508
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4429
4509
  if (!reply) {
4430
- throw new Error(this.errorMessages.emptyResponse);
4510
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4431
4511
  }
4432
4512
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4433
4513
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4435,6 +4515,7 @@ ${openAIMessages[0].content}`;
4435
4515
  return [reply, thinkingContent, tokenUsage];
4436
4516
  } catch (error) {
4437
4517
  this.logger(this.logTemplates.error(this.name, error));
4518
+ if (error instanceof ModelError) throw error;
4438
4519
  throw new Error(this.errorMessages.apiError(error));
4439
4520
  }
4440
4521
  }
@@ -4511,7 +4592,7 @@ var GlmAgent = class extends AbstractAgent {
4511
4592
  * Returns the validated value or throws.
4512
4593
  */
4513
4594
  parseAndValidate(rawReply, zodSchema) {
4514
- return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m));
4595
+ return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m), this.model);
4515
4596
  }
4516
4597
  async doAskWithZodSchema(zodSchema, messages) {
4517
4598
  try {
@@ -4551,11 +4632,11 @@ ${schemaDescription}`;
4551
4632
  }
4552
4633
  const rawReply = completion.choices[0]?.message?.content;
4553
4634
  if (!rawReply) {
4554
- throw new Error(this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4635
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4555
4636
  }
4556
4637
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4557
4638
  if (!reply) {
4558
- throw new Error(this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4639
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4559
4640
  }
4560
4641
  const validated = this.parseAndValidate(reply, zodSchema);
4561
4642
  this.logger(`\u2705 Response validated successfully with Zod schema`);
@@ -4567,6 +4648,7 @@ ${schemaDescription}`;
4567
4648
  return [validated, thinkingContent, tokenUsage];
4568
4649
  } catch (error) {
4569
4650
  this.logger(this.logTemplates.error(this.name, error));
4651
+ if (error instanceof ModelError) throw error;
4570
4652
  throw new Error(this.errorMessages.apiError(error));
4571
4653
  }
4572
4654
  }
@@ -4603,11 +4685,11 @@ ${openAIMessages[0].content}`;
4603
4685
  }
4604
4686
  const rawReply = completion.choices[0]?.message?.content;
4605
4687
  if (!rawReply) {
4606
- throw new Error(this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4688
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4607
4689
  }
4608
4690
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4609
4691
  if (!reply) {
4610
- throw new Error(this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4692
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4611
4693
  }
4612
4694
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4613
4695
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4615,6 +4697,7 @@ ${openAIMessages[0].content}`;
4615
4697
  return [reply, thinkingContent, tokenUsage];
4616
4698
  } catch (error) {
4617
4699
  this.logger(this.logTemplates.error(this.name, error));
4700
+ if (error instanceof ModelError) throw error;
4618
4701
  throw new Error(this.errorMessages.apiError(error));
4619
4702
  }
4620
4703
  }
@@ -4717,13 +4800,13 @@ ${schemaDescription}`;
4717
4800
  }
4718
4801
  const rawReply = completion.choices[0]?.message?.content;
4719
4802
  if (!rawReply) {
4720
- throw new Error(this.errorMessages.emptyResponse);
4803
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4721
4804
  }
4722
4805
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4723
4806
  if (!reply) {
4724
- throw new Error(this.errorMessages.emptyResponse);
4807
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4725
4808
  }
4726
- const validated = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m));
4809
+ const validated = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m), this.model);
4727
4810
  this.logger(`\u2705 Response validated successfully with Zod schema`);
4728
4811
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4729
4812
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4733,6 +4816,7 @@ ${schemaDescription}`;
4733
4816
  return [validated, thinkingContent, tokenUsage];
4734
4817
  } catch (error) {
4735
4818
  this.logger(this.logTemplates.error(this.name, error));
4819
+ if (error instanceof ModelError) throw error;
4736
4820
  throw new Error(this.errorMessages.apiError(error));
4737
4821
  }
4738
4822
  }
@@ -4760,11 +4844,11 @@ ${schemaDescription}`;
4760
4844
  }
4761
4845
  const rawReply = completion.choices[0]?.message?.content;
4762
4846
  if (!rawReply) {
4763
- throw new Error(this.errorMessages.emptyResponse);
4847
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4764
4848
  }
4765
4849
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4766
4850
  if (!reply) {
4767
- throw new Error(this.errorMessages.emptyResponse);
4851
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4768
4852
  }
4769
4853
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4770
4854
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4772,6 +4856,7 @@ ${schemaDescription}`;
4772
4856
  return [reply, thinkingContent, tokenUsage];
4773
4857
  } catch (error) {
4774
4858
  this.logger(this.logTemplates.error(this.name, error));
4859
+ if (error instanceof ModelError) throw error;
4775
4860
  throw new Error(this.errorMessages.apiError(error));
4776
4861
  }
4777
4862
  }
@@ -4929,7 +5014,7 @@ var QwenAgent = class extends AbstractAgent {
4929
5014
  * Returns the validated value or throws.
4930
5015
  */
4931
5016
  parseAndValidate(rawReply, zodSchema) {
4932
- return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m));
5017
+ return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m), this.model);
4933
5018
  }
4934
5019
  async doAskWithZodSchema(zodSchema, messages) {
4935
5020
  try {
@@ -4973,11 +5058,11 @@ ${schemaDescription}`;
4973
5058
  }
4974
5059
  const rawReply = completion.choices[0]?.message?.content;
4975
5060
  if (!rawReply) {
4976
- throw new Error(this.errorMessages.emptyResponse);
5061
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4977
5062
  }
4978
5063
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4979
5064
  if (!reply) {
4980
- throw new Error(this.errorMessages.emptyResponse);
5065
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4981
5066
  }
4982
5067
  const validated = this.parseAndValidate(reply, zodSchema);
4983
5068
  this.logger(`\u2705 Response validated successfully with Zod schema`);
@@ -5029,11 +5114,11 @@ ${openAIMessages[0].content}`;
5029
5114
  }
5030
5115
  const rawReply = completion.choices[0]?.message?.content;
5031
5116
  if (!rawReply) {
5032
- throw new Error(this.errorMessages.emptyResponse);
5117
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5033
5118
  }
5034
5119
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
5035
5120
  if (!reply) {
5036
- throw new Error(this.errorMessages.emptyResponse);
5121
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5037
5122
  }
5038
5123
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
5039
5124
  const thinkingContent = [reasoningContent, inlineThinking].filter(Boolean).join("\n");
@@ -5127,7 +5212,7 @@ var MiniMaxAgent = class extends AbstractAgent {
5127
5212
  * Returns the validated value or throws.
5128
5213
  */
5129
5214
  parseAndValidate(rawReply, zodSchema) {
5130
- return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m));
5215
+ return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m), this.model);
5131
5216
  }
5132
5217
  async doAskWithZodSchema(zodSchema, messages) {
5133
5218
  try {
@@ -5167,7 +5252,7 @@ ${schemaDescription}`;
5167
5252
  }
5168
5253
  const reply = completion.choices[0]?.message?.content;
5169
5254
  if (!reply) {
5170
- throw new Error(this.errorMessages.emptyResponse);
5255
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5171
5256
  }
5172
5257
  const { text: cleanReply, thinking: inlineThinking } = stripInlineThinking(reply);
5173
5258
  const validated = this.parseAndValidate(cleanReply, zodSchema);
@@ -5180,6 +5265,7 @@ ${schemaDescription}`;
5180
5265
  return [validated, thinkingContent, tokenUsage];
5181
5266
  } catch (error) {
5182
5267
  this.logger(this.logTemplates.error(this.name, error));
5268
+ if (error instanceof ModelError) throw error;
5183
5269
  throw new Error(this.errorMessages.apiError(error));
5184
5270
  }
5185
5271
  }
@@ -5217,11 +5303,11 @@ ${openAIMessages[0].content}`;
5217
5303
  }
5218
5304
  const reply = completion.choices[0]?.message?.content;
5219
5305
  if (!reply) {
5220
- throw new Error(this.errorMessages.emptyResponse);
5306
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5221
5307
  }
5222
5308
  const { text: cleanReply, thinking: inlineThinking } = stripInlineThinking(reply);
5223
5309
  if (!cleanReply) {
5224
- throw new Error(this.errorMessages.emptyResponse);
5310
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5225
5311
  }
5226
5312
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
5227
5313
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -5229,6 +5315,7 @@ ${openAIMessages[0].content}`;
5229
5315
  return [cleanReply, thinkingContent, tokenUsage];
5230
5316
  } catch (error) {
5231
5317
  this.logger(this.logTemplates.error(this.name, error));
5318
+ if (error instanceof ModelError) throw error;
5232
5319
  throw new Error(this.errorMessages.apiError(error));
5233
5320
  }
5234
5321
  }
@@ -5279,10 +5366,10 @@ ${schemaDescription}`;
5279
5366
  const response = await this.createResponse(input, zodSchema);
5280
5367
  const { text, reasoningSummary, encryptedReasoning } = this.extractResponseParts(response);
5281
5368
  if (!text) {
5282
- throw new Error(this.errorMessages.emptyResponse);
5369
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5283
5370
  }
5284
5371
  this.logger(`Meta Agent - Found reasoning summary: ${!!reasoningSummary}, encrypted reasoning: ${!!encryptedReasoning}`);
5285
- const parsedData = parseAndValidateLlmJson(text, zodSchema, (m) => this.logger(m));
5372
+ const parsedData = parseAndValidateLlmJson(text, zodSchema, (m) => this.logger(m), this.model);
5286
5373
  this.logger(`\u2705 Response validated successfully with Zod schema`);
5287
5374
  const tokenUsage = this.extractTokenUsage(response);
5288
5375
  if (parsedData) {
@@ -5291,6 +5378,7 @@ ${schemaDescription}`;
5291
5378
  return [parsedData, reasoningSummary, tokenUsage, encryptedReasoning];
5292
5379
  } catch (error) {
5293
5380
  this.logger(this.logTemplates.error(this.name, error));
5381
+ if (error instanceof ModelError) throw error;
5294
5382
  throw new Error(this.errorMessages.apiError(error));
5295
5383
  }
5296
5384
  }
@@ -5306,13 +5394,14 @@ ${schemaDescription}`;
5306
5394
  const response = await this.createResponse(input);
5307
5395
  const { text, reasoningSummary, encryptedReasoning } = this.extractResponseParts(response);
5308
5396
  if (!text) {
5309
- throw new Error(this.errorMessages.emptyResponse);
5397
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5310
5398
  }
5311
5399
  const tokenUsage = this.extractTokenUsage(response);
5312
5400
  this.logReply(text, reasoningSummary, tokenUsage);
5313
5401
  return [text, reasoningSummary, tokenUsage, encryptedReasoning];
5314
5402
  } catch (error) {
5315
5403
  this.logger(this.logTemplates.error(this.name, error));
5404
+ if (error instanceof ModelError) throw error;
5316
5405
  throw new Error(this.errorMessages.apiError(error));
5317
5406
  }
5318
5407
  }
@@ -5646,6 +5735,7 @@ export {
5646
5735
  safeValidateResponse,
5647
5736
  setBeforeAskHook,
5648
5737
  setLlmLogger,
5738
+ setRetryHook,
5649
5739
  stableHashHex,
5650
5740
  stripInlineThinking,
5651
5741
  supportsNativeJsonSchema,