@hiper2d/ai-agents 0.29.0 → 0.31.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.js CHANGED
@@ -158,6 +158,7 @@ __export(src_exports, {
158
158
  safeValidateResponse: () => safeValidateResponse,
159
159
  setBeforeAskHook: () => setBeforeAskHook,
160
160
  setLlmLogger: () => setLlmLogger,
161
+ setRetryHook: () => setRetryHook,
161
162
  stableHashHex: () => stableHashHex,
162
163
  stripInlineThinking: () => stripInlineThinking,
163
164
  supportsNativeJsonSchema: () => supportsNativeJsonSchema,
@@ -769,6 +770,77 @@ function needsPromptBasedSchema(provider) {
769
770
  return provider === "anthropic";
770
771
  }
771
772
 
773
+ // src/errors.ts
774
+ var ModelError = class extends Error {
775
+ modelType;
776
+ constructor(message, modelType) {
777
+ super(message);
778
+ this.modelType = modelType;
779
+ }
780
+ };
781
+ var ModelOverloadError = class extends ModelError {
782
+ retryable;
783
+ constructor(message, modelType, retryable = true) {
784
+ super(message, modelType);
785
+ this.name = "ModelOverloadError";
786
+ this.retryable = retryable;
787
+ }
788
+ };
789
+ var ModelRateLimitError = class extends ModelError {
790
+ retryAfter;
791
+ // seconds to wait before retrying
792
+ constructor(message, modelType, retryAfter) {
793
+ super(message, modelType);
794
+ this.name = "ModelRateLimitError";
795
+ this.retryAfter = retryAfter;
796
+ }
797
+ };
798
+ var ModelUnavailableError = class extends ModelError {
799
+ reason;
800
+ constructor(message, modelType, reason = "unknown") {
801
+ super(message, modelType);
802
+ this.name = "ModelUnavailableError";
803
+ this.reason = reason;
804
+ }
805
+ };
806
+ var ModelAuthenticationError = class extends ModelError {
807
+ constructor(message, modelType) {
808
+ super(message, modelType);
809
+ this.name = "ModelAuthenticationError";
810
+ }
811
+ };
812
+ var ModelQuotaExceededError = class extends ModelError {
813
+ constructor(message, modelType) {
814
+ super(message, modelType);
815
+ this.name = "ModelQuotaExceededError";
816
+ }
817
+ };
818
+ var ModelInvalidResponseError = class extends ModelError {
819
+ truncated;
820
+ retries;
821
+ constructor(modelType, detail, truncated = false) {
822
+ super(`${modelType} failed to produce a valid response: ${detail}`, modelType);
823
+ this.name = "ModelInvalidResponseError";
824
+ this.truncated = truncated;
825
+ }
826
+ };
827
+ var ModelTimeoutError = class extends ModelError {
828
+ timeoutMs;
829
+ constructor(modelType, timeoutMs) {
830
+ super(`${modelType} did not respond within ${Math.round(timeoutMs / 1e3)}s`, modelType);
831
+ this.name = "ModelTimeoutError";
832
+ this.timeoutMs = timeoutMs;
833
+ }
834
+ };
835
+ var ModelRefusalError = class extends ModelError {
836
+ reason;
837
+ constructor(modelType, message = `${modelType} refused to answer (stop_reason: refusal)`, reason) {
838
+ super(message, modelType);
839
+ this.name = "ModelRefusalError";
840
+ this.reason = reason;
841
+ }
842
+ };
843
+
772
844
  // src/json-response-parser.ts
773
845
  function extractFirstJsonObject(text) {
774
846
  let searchFrom = 0;
@@ -813,7 +885,7 @@ function normalizeNestedReply(value, log) {
813
885
  return value;
814
886
  }
815
887
  function parseAndValidateLlmJson(rawReply, zodSchema, log = () => {
816
- }) {
888
+ }, model = "The model") {
817
889
  const cleaned = cleanResponse(rawReply);
818
890
  const candidates = [cleaned];
819
891
  if (cleaned.startsWith('"') && cleaned.endsWith('"')) {
@@ -870,81 +942,11 @@ function parseAndValidateLlmJson(rawReply, zodSchema, log = () => {
870
942
  }
871
943
  if (zodError !== null) {
872
944
  log(`Zod validation failed: ${JSON.stringify(zodError.errors)}`);
873
- throw new Error(`Response validation failed: ${zodError.message}`);
945
+ throw new ModelInvalidResponseError(model, `Response validation failed: ${zodError.message}`);
874
946
  }
875
- throw new Error(`Failed to parse JSON response: ${parseError}. First 200 chars: ${cleaned.slice(0, 200)}`);
947
+ throw new ModelInvalidResponseError(model, `Failed to parse JSON response: ${parseError}. First 200 chars: ${cleaned.slice(0, 200)}`);
876
948
  }
877
949
 
878
- // src/errors.ts
879
- var ModelError = class extends Error {
880
- modelType;
881
- constructor(message, modelType) {
882
- super(message);
883
- this.modelType = modelType;
884
- }
885
- };
886
- var ModelOverloadError = class extends ModelError {
887
- retryable;
888
- constructor(message, modelType, retryable = true) {
889
- super(message, modelType);
890
- this.name = "ModelOverloadError";
891
- this.retryable = retryable;
892
- }
893
- };
894
- var ModelRateLimitError = class extends ModelError {
895
- retryAfter;
896
- // seconds to wait before retrying
897
- constructor(message, modelType, retryAfter) {
898
- super(message, modelType);
899
- this.name = "ModelRateLimitError";
900
- this.retryAfter = retryAfter;
901
- }
902
- };
903
- var ModelUnavailableError = class extends ModelError {
904
- reason;
905
- constructor(message, modelType, reason = "unknown") {
906
- super(message, modelType);
907
- this.name = "ModelUnavailableError";
908
- this.reason = reason;
909
- }
910
- };
911
- var ModelAuthenticationError = class extends ModelError {
912
- constructor(message, modelType) {
913
- super(message, modelType);
914
- this.name = "ModelAuthenticationError";
915
- }
916
- };
917
- var ModelQuotaExceededError = class extends ModelError {
918
- constructor(message, modelType) {
919
- super(message, modelType);
920
- this.name = "ModelQuotaExceededError";
921
- }
922
- };
923
- var ModelInvalidResponseError = class extends ModelError {
924
- truncated;
925
- constructor(modelType, detail, truncated = false) {
926
- super(`${modelType} failed to produce a valid response: ${detail}`, modelType);
927
- this.name = "ModelInvalidResponseError";
928
- this.truncated = truncated;
929
- }
930
- };
931
- var ModelTimeoutError = class extends ModelError {
932
- timeoutMs;
933
- constructor(modelType, timeoutMs) {
934
- super(`${modelType} did not respond within ${Math.round(timeoutMs / 1e3)}s`, modelType);
935
- this.name = "ModelTimeoutError";
936
- this.timeoutMs = timeoutMs;
937
- }
938
- };
939
- var ModelRefusalError = class extends ModelError {
940
- reason;
941
- constructor(modelType, message = `${modelType} refused to answer (stop_reason: refusal)`, reason) {
942
- super(message, modelType);
943
- this.name = "ModelRefusalError";
944
- this.reason = reason;
945
- }
946
- };
947
-
948
950
  // src/thinking-utils.ts
949
951
  function stripInlineThinking(raw) {
950
952
  let thinking = "";
@@ -1024,6 +1026,8 @@ var LLM_CONSTANTS = {
1024
1026
  GEMINI_FLASH: "gemini-flash",
1025
1027
  GEMINI_LITE: "gemini-lite",
1026
1028
  MISTRAL_SMALL: "mistral-small",
1029
+ // Version-free id (Large 3 used it until 2026-09-18; Large 4 took it over 2026-10-06).
1030
+ MISTRAL_LARGE: "mistral-large",
1027
1031
  GROK: "grok",
1028
1032
  KIMI: "kimi",
1029
1033
  // Kimi K3.1 Pro Highspeed: the same model served 2-3x faster at 2x the price (added
@@ -1263,7 +1267,7 @@ var SupportedAiModels = {
1263
1267
  // at medium effort; the 15-character story pipeline took 213s on 2026-10-07.
1264
1268
  tags: ["very-slow"]
1265
1269
  },
1266
- // Mistral models. One hybrid entry: reasoning is off by default on the API and switched on
1270
+ // Mistral models. Two hybrid entries: reasoning is off by default on the API and switched on
1267
1271
  // per request with `reasoning_effort` (see mistral-agent.ts); the trace comes back as a
1268
1272
  // `thinking` content chunk and works with json_schema structured output (verified live
1269
1273
  // 2026-09-18). Pinned to 'high' — the only level Mistral's docs describe ("full thinking
@@ -1284,12 +1288,27 @@ var SupportedAiModels = {
1284
1288
  // `magistral-medium-latest` as one entry — so Magistral seats had silently become Medium
1285
1289
  // seats already. Consumers map both retired ids onto Small (Medium itself is gone since 0.21.0).
1286
1290
  //
1287
- // Mistral Large 4 (`mistral-large-4`, $0.68/$2.09, $0.07 cached) was added in 0.19.0 and
1288
- // removed in 0.19.1 (2026-10-06/07): too slow to play. Like Small/Medium it accepts only
1289
- // reasoning_effort high|none, and unlike them it reasons when the field is omitted. At high
1290
- // a realistic day-2 vote took 25-154s (half past the 60s timeout) and its parallel story
1291
- // batches finished ~100s apart (Mistral served them one at a time: ~6 min per story). Off,
1292
- // it answers in ~1s with no trace. Re-test before re-adding.
1291
+ // Mistral Large 4 (`mistral-large-4`, released 2026-10-06 in public preview) was added in
1292
+ // 0.19.0 and removed in 0.19.1 the next day: at launch a realistic day-2 vote took 25-154s
1293
+ // (half past the 60s timeout) and the story batches finished ~100s apart. Re-tested
1294
+ // 2026-10-30 on the same requests and RE-ADDED in 0.31.0: 19 day-2 votes ran 6-25s (median
1295
+ // ~14s, no timeouts, 760-3,100 output tokens, $0.002-0.011 each) and the 15-character story
1296
+ // pipeline 114-118s — the launch-week slowness was serving load, since `high` is fast now
1297
+ // too. Two things still hold: Mistral serves our parallel sheet batches one at a time
1298
+ // (~22-25s each, finishing 22/50/77/99s), so story time scales with the lobby; and the
1299
+ // model reasons when the field is omitted. The API now takes low|medium|high on Large 4
1300
+ // (the 400 for `none` lists exactly those; Small still takes only high|none); the level
1301
+ // barely moved latency or trace size (4-12k chars at every level), so it stays on the
1302
+ // documented 'high' default. Model list: 1M context. Tagged `slow`: the 15-25s band.
1303
+ [LLM_CONSTANTS.MISTRAL_LARGE]: {
1304
+ displayName: "Mistral Large 4",
1305
+ // `mistral-large-latest` still points at Large 3 (no reasoning); use the explicit id.
1306
+ modelApiName: "mistral-large-4",
1307
+ apiKeyName: API_KEY_CONSTANTS.MISTRAL,
1308
+ hasThinking: true,
1309
+ reasoningEffort: "high",
1310
+ tags: ["slow"]
1311
+ },
1293
1312
  [LLM_CONSTANTS.MISTRAL_SMALL]: {
1294
1313
  displayName: "Mistral 4 Small",
1295
1314
  // Resolves to mistral-small-2603 (Small 4), which also carries the magistral-small alias.
@@ -1747,6 +1766,13 @@ var MODEL_PRICING = {
1747
1766
  outputPrice: 0.6,
1748
1767
  cacheHitPrice: 0.015
1749
1768
  },
1769
+ // Large 4: docs.mistral.ai/models/mistral-large-4-0, read 2026-10-30 ($0.70 / $0.07 cached /
1770
+ // $2.10). The $0.68/$2.09 recorded in 0.19.0 was the two-week launch discount.
1771
+ [SupportedAiModels[LLM_CONSTANTS.MISTRAL_LARGE].modelApiName]: {
1772
+ inputPrice: 0.7,
1773
+ outputPrice: 2.1,
1774
+ cacheHitPrice: 0.07
1775
+ },
1750
1776
  // Grok models. Cached price is per-model on xAI (not a uniform ratio):
1751
1777
  // grok-4.7 is $0.50/M cached vs $2.00/M input, and all rates double for prompts
1752
1778
  // >= 200K tokens, per docs.x.ai/docs/models (re-verified 2026-09-22 for 4.7).
@@ -1826,7 +1852,8 @@ var HYBRID_THINKING_API_NAMES = /* @__PURE__ */ new Set([
1826
1852
  // MiniMax left the set 2026-10-27: M3.1 Flash cannot turn thinking off (M3 could).
1827
1853
  // Mistral reasons only when asked (`reasoning_effort`), and we always ask — hybrid by the
1828
1854
  // same definition as Qwen. Added 2026-09-18 when the Mistral entries went thinking-on.
1829
- SupportedAiModels[LLM_CONSTANTS.MISTRAL_SMALL].modelApiName
1855
+ SupportedAiModels[LLM_CONSTANTS.MISTRAL_SMALL].modelApiName,
1856
+ SupportedAiModels[LLM_CONSTANTS.MISTRAL_LARGE].modelApiName
1830
1857
  ]);
1831
1858
  function isHybridThinkingModel(modelApiName) {
1832
1859
  return HYBRID_THINKING_API_NAMES.has(modelApiName);
@@ -2543,6 +2570,10 @@ var beforeAskHook;
2543
2570
  function setBeforeAskHook(hook) {
2544
2571
  beforeAskHook = hook;
2545
2572
  }
2573
+ var retryHook;
2574
+ function setRetryHook(hook) {
2575
+ retryHook = hook;
2576
+ }
2546
2577
  var AbstractAgent = class {
2547
2578
  name;
2548
2579
  gameId;
@@ -2569,6 +2600,17 @@ var AbstractAgent = class {
2569
2600
  * instance for calls that legitimately run long, like maxOutputTokens.
2570
2601
  */
2571
2602
  requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS;
2603
+ /**
2604
+ * How many times one ask is re-sent after a ModelInvalidResponseError that is not a
2605
+ * cap hit: the model answered with nothing, or with text that is not the JSON the
2606
+ * schema asked for. Those are one-off generation failures the same prompt usually
2607
+ * gets right on the next try, unlike timeouts, refusals and transport errors, which
2608
+ * are never retried here. 0 (the default) hands every failure to the caller. A
2609
+ * truncated response is excluded because re-running it re-buys the whole output at
2610
+ * the cap. Each re-send runs the before-ask hook again (it is a new paid call) and
2611
+ * fires the retry hook; the error finally thrown carries `retries`.
2612
+ */
2613
+ invalidResponseRetries = 0;
2572
2614
  instruction;
2573
2615
  /**
2574
2616
  * The instruction split on CACHE_TIER_MARKER: [shared static tier, per-bot tier].
@@ -2595,26 +2637,83 @@ var AbstractAgent = class {
2595
2637
  this.thinkingBudgetTokens = modelConfig?.thinkingBudgetTokens;
2596
2638
  }
2597
2639
  /**
2598
- * Public ask API — template methods that time the provider call and stamp `durationMs`
2599
- * into the returned TokenUsage. Subclasses implement doAskWithZodSchema/doAskText and
2640
+ * Public ask API — template methods that run the before-ask hook, time the provider
2641
+ * call, stamp `durationMs` into the returned TokenUsage and apply the
2642
+ * invalidResponseRetries policy. Subclasses implement doAskWithZodSchema/doAskText and
2600
2643
  * must NOT override these.
2601
2644
  */
2602
2645
  async askWithZodSchema(zodSchema, messages) {
2603
- if (beforeAskHook) await beforeAskHook(this);
2604
- const startedAt = Date.now();
2646
+ return this.askWithRetries(() => this.doAskWithZodSchema(zodSchema, messages));
2647
+ }
2648
+ async askText(messages) {
2649
+ return this.askWithRetries(() => this.doAskText(messages));
2650
+ }
2651
+ /**
2652
+ * One attempt per loop; an empty or malformed answer (ModelInvalidResponseError, not
2653
+ * truncated) is re-sent up to invalidResponseRetries times, with the retry hook told
2654
+ * before each re-send. Anything else — a timeout, a refusal, a transport error, or the
2655
+ * last allowed attempt failing — is thrown as-is, stamped with the retry count. Every
2656
+ * settle function the hook returned runs once the ask is over, whichever way it ended.
2657
+ */
2658
+ async askWithRetries(call) {
2659
+ const settled = [];
2660
+ let retries = 0;
2605
2661
  try {
2606
- const [result, thinking, usage, signature] = await this.withTimeout(this.doAskWithZodSchema(zodSchema, messages));
2607
- return [result, thinking, this.stampDuration(usage, startedAt), signature];
2608
- } catch (error) {
2609
- this.stampErrorDuration(error, startedAt);
2610
- throw error;
2662
+ while (true) {
2663
+ try {
2664
+ return await this.attempt(call);
2665
+ } catch (error) {
2666
+ if (retries > 0 && error && typeof error === "object") {
2667
+ error.retries = retries;
2668
+ }
2669
+ if (!(error instanceof ModelInvalidResponseError) || error.truncated || retries >= this.invalidResponseRetries) {
2670
+ throw error;
2671
+ }
2672
+ retries++;
2673
+ logger.warn(`${this.name} (${this.model}): ${error.message} \u2014 asking again (retry ${retries} of ${this.invalidResponseRetries})`, {
2674
+ gameId: this.gameId,
2675
+ userId: this.userId,
2676
+ agentName: this.name,
2677
+ model: this.model,
2678
+ activity: "llm_retry",
2679
+ attempt: retries,
2680
+ error: error.message
2681
+ });
2682
+ if (retryHook) {
2683
+ try {
2684
+ const onSettled = await retryHook({ agent: this, model: this.model, error, attempt: retries });
2685
+ if (typeof onSettled === "function") settled.push(onSettled);
2686
+ } catch (hookError) {
2687
+ logger.warn(`${this.name} (${this.model}): retry hook failed, retrying anyway`, {
2688
+ gameId: this.gameId,
2689
+ agentName: this.name,
2690
+ model: this.model,
2691
+ error: hookError instanceof Error ? hookError.message : String(hookError)
2692
+ });
2693
+ }
2694
+ }
2695
+ }
2696
+ }
2697
+ } finally {
2698
+ for (const onSettled of settled) {
2699
+ try {
2700
+ await onSettled();
2701
+ } catch (hookError) {
2702
+ logger.warn(`${this.name} (${this.model}): retry settle hook failed`, {
2703
+ gameId: this.gameId,
2704
+ agentName: this.name,
2705
+ model: this.model,
2706
+ error: hookError instanceof Error ? hookError.message : String(hookError)
2707
+ });
2708
+ }
2709
+ }
2611
2710
  }
2612
2711
  }
2613
- async askText(messages) {
2712
+ async attempt(call) {
2614
2713
  if (beforeAskHook) await beforeAskHook(this);
2615
2714
  const startedAt = Date.now();
2616
2715
  try {
2617
- const [content, thinking, usage, signature] = await this.withTimeout(this.doAskText(messages));
2716
+ const [content, thinking, usage, signature] = await this.withTimeout(call());
2618
2717
  return [content, thinking, this.stampDuration(usage, startedAt), signature];
2619
2718
  } catch (error) {
2620
2719
  this.stampErrorDuration(error, startedAt);
@@ -2914,7 +3013,7 @@ ${instruction}`);
2914
3013
  reason === "max_output_tokens"
2915
3014
  );
2916
3015
  }
2917
- throw new Error(this.errorMessages.emptyResponse);
3016
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
2918
3017
  }
2919
3018
  let tokenUsage;
2920
3019
  if (response.usage) {
@@ -3195,7 +3294,7 @@ var ClaudeAgent = class extends AbstractAgent {
3195
3294
  throw new ModelRefusalError(this.model, void 0, "refusal");
3196
3295
  }
3197
3296
  if (!("content" in response) || !Array.isArray(response.content) || response.content.length === 0) {
3198
- throw new Error(this.errorMessages.emptyResponse);
3297
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3199
3298
  }
3200
3299
  let textContent = null;
3201
3300
  let thinkingContent = "";
@@ -3212,9 +3311,9 @@ var ClaudeAgent = class extends AbstractAgent {
3212
3311
  }
3213
3312
  }
3214
3313
  if (!textContent) {
3215
- throw new Error(this.errorMessages.invalidFormat);
3314
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.invalidFormat);
3216
3315
  }
3217
- const parsedData = parseAndValidateLlmJson(textContent, zodSchema, (m) => this.logger(m));
3316
+ const parsedData = parseAndValidateLlmJson(textContent, zodSchema, (m) => this.logger(m), this.model);
3218
3317
  this.logger(`\u2705 Response validated successfully with Zod schema`);
3219
3318
  let tokenUsage;
3220
3319
  if (response.usage) {
@@ -3293,7 +3392,7 @@ var ClaudeAgent = class extends AbstractAgent {
3293
3392
  throw new ModelRefusalError(this.model, void 0, "refusal");
3294
3393
  }
3295
3394
  if (!("content" in response) || !Array.isArray(response.content) || response.content.length === 0) {
3296
- throw new Error(this.errorMessages.emptyResponse);
3395
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3297
3396
  }
3298
3397
  const textParts = [];
3299
3398
  let thinkingContent = "";
@@ -3311,7 +3410,7 @@ var ClaudeAgent = class extends AbstractAgent {
3311
3410
  }
3312
3411
  const textContent = textParts.join("");
3313
3412
  if (!textContent) {
3314
- throw new Error(this.errorMessages.emptyResponse);
3413
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3315
3414
  }
3316
3415
  let tokenUsage;
3317
3416
  if (response.usage) {
@@ -3383,7 +3482,7 @@ function throwForEmptyGeminiResponse(model, response, fallback) {
3383
3482
  const bits = [`finishReason=${finishReason ?? "none"}`];
3384
3483
  if (!response?.candidates?.length) bits.push("no candidates");
3385
3484
  if (finishMessage) bits.push(`finishMessage="${finishMessage}"`);
3386
- throw new Error(`${fallback} (${bits.join(", ")})`);
3485
+ throw new ModelInvalidResponseError(model, `${fallback} (${bits.join(", ")})`);
3387
3486
  }
3388
3487
  var GoogleAgent = class extends AbstractAgent {
3389
3488
  client;
@@ -3579,7 +3678,7 @@ var GoogleAgent = class extends AbstractAgent {
3579
3678
  if (!response.text) {
3580
3679
  throwForEmptyGeminiResponse(this.model, response, this.errorMessages.emptyResponse);
3581
3680
  }
3582
- const parsedData = parseAndValidateLlmJson(response.text, zodSchema, (m) => this.logger(m));
3681
+ const parsedData = parseAndValidateLlmJson(response.text, zodSchema, (m) => this.logger(m), this.model);
3583
3682
  if (parsedData) {
3584
3683
  this.logReply(parsedData, thinkingContent || void 0, tokenUsage);
3585
3684
  }
@@ -3815,7 +3914,7 @@ ${instruction}`);
3815
3914
  processReply(response) {
3816
3915
  const message = response?.choices?.[0]?.message;
3817
3916
  if (!message || !message.content) {
3818
- throw new Error(this.errorMessages.emptyResponse);
3917
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3819
3918
  }
3820
3919
  let reply = message.content;
3821
3920
  if (Array.isArray(reply)) {
@@ -3920,12 +4019,12 @@ ${schemaDescription}`
3920
4019
  throw new Error(this.errorMessages.apiError(apiError));
3921
4020
  }
3922
4021
  if (!response || !response.choices || response.choices.length === 0) {
3923
- throw new Error(this.errorMessages.emptyResponse);
4022
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3924
4023
  }
3925
4024
  const choice = response.choices[0];
3926
4025
  const content = choice.message?.content;
3927
4026
  if (!content) {
3928
- throw new Error(this.errorMessages.invalidFormat);
4027
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.invalidFormat);
3929
4028
  }
3930
4029
  let responseText;
3931
4030
  let thinkingContent = "";
@@ -3938,7 +4037,7 @@ ${schemaDescription}`
3938
4037
  } else {
3939
4038
  responseText = JSON.stringify(content);
3940
4039
  }
3941
- const parsedData = parseAndValidateLlmJson(responseText, zodSchema, (m) => this.logger(m));
4040
+ const parsedData = parseAndValidateLlmJson(responseText, zodSchema, (m) => this.logger(m), this.model);
3942
4041
  this.logger(`\u2705 Response validated successfully with Zod schema`);
3943
4042
  const tokenUsage = this.extractTokenUsage(response);
3944
4043
  if (parsedData) {
@@ -3947,6 +4046,7 @@ ${schemaDescription}`
3947
4046
  return [parsedData, thinkingContent, tokenUsage];
3948
4047
  } catch (error) {
3949
4048
  this.logger(this.logTemplates.error(this.name, error));
4049
+ if (error instanceof ModelError) throw error;
3950
4050
  throw new Error(this.errorMessages.apiError(error));
3951
4051
  }
3952
4052
  }
@@ -3976,12 +4076,13 @@ ${schemaDescription}`
3976
4076
  }
3977
4077
  const [content, thinkingContent, tokenUsage] = this.processReply(response);
3978
4078
  if (!content) {
3979
- throw new Error(this.errorMessages.emptyResponse);
4079
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3980
4080
  }
3981
4081
  this.logReply(content, thinkingContent || void 0, tokenUsage);
3982
4082
  return [content, thinkingContent, tokenUsage];
3983
4083
  } catch (error) {
3984
4084
  this.logger(this.logTemplates.error(this.name, error));
4085
+ if (error instanceof ModelError) throw error;
3985
4086
  throw new Error(this.errorMessages.apiError(error));
3986
4087
  }
3987
4088
  }
@@ -3998,7 +4099,7 @@ var DeepSeekV2Agent = class extends AbstractAgent {
3998
4099
  };
3999
4100
  // Error message templates
4000
4101
  errorMessages = {
4001
- emptyResponse: "Empty or undefined response from DeepSeek API",
4102
+ emptyResponse: (finishReason) => `Empty or undefined response from DeepSeek API (finish_reason: ${finishReason ?? "unknown"})`,
4002
4103
  invalidFormat: "Invalid response format from DeepSeek API",
4003
4104
  apiError: (error) => `Failed to get response from DeepSeek API: ${error instanceof Error ? error.message : String(error)}`
4004
4105
  };
@@ -4103,14 +4204,14 @@ ${schemaDescription}`
4103
4204
  }
4104
4205
  const rawContent = response.choices[0]?.message?.content;
4105
4206
  if (!rawContent) {
4106
- throw new Error(this.errorMessages.emptyResponse);
4207
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(response.choices[0]?.finish_reason));
4107
4208
  }
4108
4209
  const { text: content, thinking: inlineThinking } = stripInlineThinking(rawContent);
4109
4210
  thinkingContent = mergeThinking(thinkingContent, inlineThinking);
4110
4211
  if (!content) {
4111
- throw new Error(this.errorMessages.emptyResponse);
4212
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(response.choices[0]?.finish_reason));
4112
4213
  }
4113
- const parsedData = parseAndValidateLlmJson(content, zodSchema, (m) => this.logger(m));
4214
+ const parsedData = parseAndValidateLlmJson(content, zodSchema, (m) => this.logger(m), this.model);
4114
4215
  this.logger(`\u2705 Response validated successfully with Zod schema`);
4115
4216
  const usageResult = extractUsageAndCalculateCost(this.model, response);
4116
4217
  let tokenUsage;
@@ -4131,6 +4232,7 @@ ${schemaDescription}`
4131
4232
  return [parsedData, thinkingContent, tokenUsage];
4132
4233
  } catch (error) {
4133
4234
  this.logger(this.logTemplates.error(this.name, error));
4235
+ if (error instanceof ModelError) throw error;
4134
4236
  throw new Error(this.errorMessages.apiError(error));
4135
4237
  }
4136
4238
  }
@@ -4166,12 +4268,12 @@ ${schemaDescription}`
4166
4268
  }
4167
4269
  const rawContent = response.choices[0]?.message?.content;
4168
4270
  if (!rawContent) {
4169
- throw new Error(this.errorMessages.emptyResponse);
4271
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(response.choices[0]?.finish_reason));
4170
4272
  }
4171
4273
  const { text: content, thinking: inlineThinking } = stripInlineThinking(rawContent);
4172
4274
  thinkingContent = mergeThinking(thinkingContent, inlineThinking);
4173
4275
  if (!content) {
4174
- throw new Error(this.errorMessages.emptyResponse);
4276
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(response.choices[0]?.finish_reason));
4175
4277
  }
4176
4278
  const usageResult = extractUsageAndCalculateCost(this.model, response);
4177
4279
  let tokenUsage;
@@ -4190,6 +4292,7 @@ ${schemaDescription}`
4190
4292
  return [content, thinkingContent, tokenUsage];
4191
4293
  } catch (error) {
4192
4294
  this.logger(this.logTemplates.error(this.name, error));
4295
+ if (error instanceof ModelError) throw error;
4193
4296
  throw new Error(this.errorMessages.apiError(error));
4194
4297
  }
4195
4298
  }
@@ -4240,10 +4343,10 @@ ${schemaDescription}`;
4240
4343
  const response = await this.createResponse(input, true);
4241
4344
  const { text, reasoningSummary, encryptedReasoning } = this.extractResponseParts(response);
4242
4345
  if (!text) {
4243
- throw new Error(this.errorMessages.emptyResponse);
4346
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4244
4347
  }
4245
4348
  this.logger(`Grok Agent - Found reasoning summary: ${!!reasoningSummary}, encrypted reasoning: ${!!encryptedReasoning}`);
4246
- const parsedData = parseAndValidateLlmJson(text, zodSchema, (m) => this.logger(m));
4349
+ const parsedData = parseAndValidateLlmJson(text, zodSchema, (m) => this.logger(m), this.model);
4247
4350
  this.logger(`\u2705 Response validated successfully with Zod schema`);
4248
4351
  const tokenUsage = this.extractTokenUsage(response);
4249
4352
  if (parsedData) {
@@ -4252,6 +4355,7 @@ ${schemaDescription}`;
4252
4355
  return [parsedData, reasoningSummary, tokenUsage, encryptedReasoning];
4253
4356
  } catch (error) {
4254
4357
  this.logger(this.logTemplates.error(this.name, error));
4358
+ if (error instanceof ModelError) throw error;
4255
4359
  throw new Error(this.errorMessages.apiError(error));
4256
4360
  }
4257
4361
  }
@@ -4267,13 +4371,14 @@ ${schemaDescription}`;
4267
4371
  const response = await this.createResponse(input, false);
4268
4372
  const { text, reasoningSummary, encryptedReasoning } = this.extractResponseParts(response);
4269
4373
  if (!text) {
4270
- throw new Error(this.errorMessages.emptyResponse);
4374
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4271
4375
  }
4272
4376
  const tokenUsage = this.extractTokenUsage(response);
4273
4377
  this.logReply(text, reasoningSummary, tokenUsage);
4274
4378
  return [text, reasoningSummary, tokenUsage, encryptedReasoning];
4275
4379
  } catch (error) {
4276
4380
  this.logger(this.logTemplates.error(this.name, error));
4381
+ if (error instanceof ModelError) throw error;
4277
4382
  throw new Error(this.errorMessages.apiError(error));
4278
4383
  }
4279
4384
  }
@@ -4513,13 +4618,13 @@ ${openAIMessages[0].content}`;
4513
4618
  }
4514
4619
  const rawReply = completion.choices[0]?.message?.content;
4515
4620
  if (!rawReply) {
4516
- throw new Error(this.errorMessages.emptyResponse);
4621
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4517
4622
  }
4518
4623
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4519
4624
  if (!reply) {
4520
- throw new Error(this.errorMessages.emptyResponse);
4625
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4521
4626
  }
4522
- const parsedData = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m));
4627
+ const parsedData = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m), this.model);
4523
4628
  this.logger(`\u2705 Response validated successfully with Zod schema (JSON mode)`);
4524
4629
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4525
4630
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4550,13 +4655,13 @@ ${schemaDescription}`;
4550
4655
  }
4551
4656
  const rawReply = completion.choices[0]?.message?.content;
4552
4657
  if (!rawReply) {
4553
- throw new Error(this.errorMessages.emptyResponse);
4658
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4554
4659
  }
4555
4660
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4556
4661
  if (!reply) {
4557
- throw new Error(this.errorMessages.emptyResponse);
4662
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4558
4663
  }
4559
- const parsedData = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m));
4664
+ const parsedData = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m), this.model);
4560
4665
  this.logger(`\u2705 Response validated successfully with Zod schema (prompt mode)`);
4561
4666
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4562
4667
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4567,6 +4672,7 @@ ${schemaDescription}`;
4567
4672
  }
4568
4673
  } catch (error) {
4569
4674
  this.logger(this.logTemplates.error(this.name, error));
4675
+ if (error instanceof ModelError) throw error;
4570
4676
  throw new Error(this.errorMessages.apiError(error));
4571
4677
  }
4572
4678
  }
@@ -4603,11 +4709,11 @@ ${openAIMessages[0].content}`;
4603
4709
  }
4604
4710
  const rawReply = completion.choices[0]?.message?.content;
4605
4711
  if (!rawReply) {
4606
- throw new Error(this.errorMessages.emptyResponse);
4712
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4607
4713
  }
4608
4714
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4609
4715
  if (!reply) {
4610
- throw new Error(this.errorMessages.emptyResponse);
4716
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4611
4717
  }
4612
4718
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4613
4719
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4615,6 +4721,7 @@ ${openAIMessages[0].content}`;
4615
4721
  return [reply, thinkingContent, tokenUsage];
4616
4722
  } catch (error) {
4617
4723
  this.logger(this.logTemplates.error(this.name, error));
4724
+ if (error instanceof ModelError) throw error;
4618
4725
  throw new Error(this.errorMessages.apiError(error));
4619
4726
  }
4620
4727
  }
@@ -4691,7 +4798,7 @@ var GlmAgent = class extends AbstractAgent {
4691
4798
  * Returns the validated value or throws.
4692
4799
  */
4693
4800
  parseAndValidate(rawReply, zodSchema) {
4694
- return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m));
4801
+ return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m), this.model);
4695
4802
  }
4696
4803
  async doAskWithZodSchema(zodSchema, messages) {
4697
4804
  try {
@@ -4731,11 +4838,11 @@ ${schemaDescription}`;
4731
4838
  }
4732
4839
  const rawReply = completion.choices[0]?.message?.content;
4733
4840
  if (!rawReply) {
4734
- throw new Error(this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4841
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4735
4842
  }
4736
4843
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4737
4844
  if (!reply) {
4738
- throw new Error(this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4845
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4739
4846
  }
4740
4847
  const validated = this.parseAndValidate(reply, zodSchema);
4741
4848
  this.logger(`\u2705 Response validated successfully with Zod schema`);
@@ -4747,6 +4854,7 @@ ${schemaDescription}`;
4747
4854
  return [validated, thinkingContent, tokenUsage];
4748
4855
  } catch (error) {
4749
4856
  this.logger(this.logTemplates.error(this.name, error));
4857
+ if (error instanceof ModelError) throw error;
4750
4858
  throw new Error(this.errorMessages.apiError(error));
4751
4859
  }
4752
4860
  }
@@ -4783,11 +4891,11 @@ ${openAIMessages[0].content}`;
4783
4891
  }
4784
4892
  const rawReply = completion.choices[0]?.message?.content;
4785
4893
  if (!rawReply) {
4786
- throw new Error(this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4894
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4787
4895
  }
4788
4896
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4789
4897
  if (!reply) {
4790
- throw new Error(this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4898
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4791
4899
  }
4792
4900
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4793
4901
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4795,6 +4903,7 @@ ${openAIMessages[0].content}`;
4795
4903
  return [reply, thinkingContent, tokenUsage];
4796
4904
  } catch (error) {
4797
4905
  this.logger(this.logTemplates.error(this.name, error));
4906
+ if (error instanceof ModelError) throw error;
4798
4907
  throw new Error(this.errorMessages.apiError(error));
4799
4908
  }
4800
4909
  }
@@ -4897,13 +5006,13 @@ ${schemaDescription}`;
4897
5006
  }
4898
5007
  const rawReply = completion.choices[0]?.message?.content;
4899
5008
  if (!rawReply) {
4900
- throw new Error(this.errorMessages.emptyResponse);
5009
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4901
5010
  }
4902
5011
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4903
5012
  if (!reply) {
4904
- throw new Error(this.errorMessages.emptyResponse);
5013
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4905
5014
  }
4906
- const validated = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m));
5015
+ const validated = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m), this.model);
4907
5016
  this.logger(`\u2705 Response validated successfully with Zod schema`);
4908
5017
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4909
5018
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4913,6 +5022,7 @@ ${schemaDescription}`;
4913
5022
  return [validated, thinkingContent, tokenUsage];
4914
5023
  } catch (error) {
4915
5024
  this.logger(this.logTemplates.error(this.name, error));
5025
+ if (error instanceof ModelError) throw error;
4916
5026
  throw new Error(this.errorMessages.apiError(error));
4917
5027
  }
4918
5028
  }
@@ -4940,11 +5050,11 @@ ${schemaDescription}`;
4940
5050
  }
4941
5051
  const rawReply = completion.choices[0]?.message?.content;
4942
5052
  if (!rawReply) {
4943
- throw new Error(this.errorMessages.emptyResponse);
5053
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4944
5054
  }
4945
5055
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4946
5056
  if (!reply) {
4947
- throw new Error(this.errorMessages.emptyResponse);
5057
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4948
5058
  }
4949
5059
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4950
5060
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4952,6 +5062,7 @@ ${schemaDescription}`;
4952
5062
  return [reply, thinkingContent, tokenUsage];
4953
5063
  } catch (error) {
4954
5064
  this.logger(this.logTemplates.error(this.name, error));
5065
+ if (error instanceof ModelError) throw error;
4955
5066
  throw new Error(this.errorMessages.apiError(error));
4956
5067
  }
4957
5068
  }
@@ -5109,7 +5220,7 @@ var QwenAgent = class extends AbstractAgent {
5109
5220
  * Returns the validated value or throws.
5110
5221
  */
5111
5222
  parseAndValidate(rawReply, zodSchema) {
5112
- return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m));
5223
+ return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m), this.model);
5113
5224
  }
5114
5225
  async doAskWithZodSchema(zodSchema, messages) {
5115
5226
  try {
@@ -5153,11 +5264,11 @@ ${schemaDescription}`;
5153
5264
  }
5154
5265
  const rawReply = completion.choices[0]?.message?.content;
5155
5266
  if (!rawReply) {
5156
- throw new Error(this.errorMessages.emptyResponse);
5267
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5157
5268
  }
5158
5269
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
5159
5270
  if (!reply) {
5160
- throw new Error(this.errorMessages.emptyResponse);
5271
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5161
5272
  }
5162
5273
  const validated = this.parseAndValidate(reply, zodSchema);
5163
5274
  this.logger(`\u2705 Response validated successfully with Zod schema`);
@@ -5209,11 +5320,11 @@ ${openAIMessages[0].content}`;
5209
5320
  }
5210
5321
  const rawReply = completion.choices[0]?.message?.content;
5211
5322
  if (!rawReply) {
5212
- throw new Error(this.errorMessages.emptyResponse);
5323
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5213
5324
  }
5214
5325
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
5215
5326
  if (!reply) {
5216
- throw new Error(this.errorMessages.emptyResponse);
5327
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5217
5328
  }
5218
5329
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
5219
5330
  const thinkingContent = [reasoningContent, inlineThinking].filter(Boolean).join("\n");
@@ -5307,7 +5418,7 @@ var MiniMaxAgent = class extends AbstractAgent {
5307
5418
  * Returns the validated value or throws.
5308
5419
  */
5309
5420
  parseAndValidate(rawReply, zodSchema) {
5310
- return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m));
5421
+ return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m), this.model);
5311
5422
  }
5312
5423
  async doAskWithZodSchema(zodSchema, messages) {
5313
5424
  try {
@@ -5347,7 +5458,7 @@ ${schemaDescription}`;
5347
5458
  }
5348
5459
  const reply = completion.choices[0]?.message?.content;
5349
5460
  if (!reply) {
5350
- throw new Error(this.errorMessages.emptyResponse);
5461
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5351
5462
  }
5352
5463
  const { text: cleanReply, thinking: inlineThinking } = stripInlineThinking(reply);
5353
5464
  const validated = this.parseAndValidate(cleanReply, zodSchema);
@@ -5360,6 +5471,7 @@ ${schemaDescription}`;
5360
5471
  return [validated, thinkingContent, tokenUsage];
5361
5472
  } catch (error) {
5362
5473
  this.logger(this.logTemplates.error(this.name, error));
5474
+ if (error instanceof ModelError) throw error;
5363
5475
  throw new Error(this.errorMessages.apiError(error));
5364
5476
  }
5365
5477
  }
@@ -5397,11 +5509,11 @@ ${openAIMessages[0].content}`;
5397
5509
  }
5398
5510
  const reply = completion.choices[0]?.message?.content;
5399
5511
  if (!reply) {
5400
- throw new Error(this.errorMessages.emptyResponse);
5512
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5401
5513
  }
5402
5514
  const { text: cleanReply, thinking: inlineThinking } = stripInlineThinking(reply);
5403
5515
  if (!cleanReply) {
5404
- throw new Error(this.errorMessages.emptyResponse);
5516
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5405
5517
  }
5406
5518
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
5407
5519
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -5409,6 +5521,7 @@ ${openAIMessages[0].content}`;
5409
5521
  return [cleanReply, thinkingContent, tokenUsage];
5410
5522
  } catch (error) {
5411
5523
  this.logger(this.logTemplates.error(this.name, error));
5524
+ if (error instanceof ModelError) throw error;
5412
5525
  throw new Error(this.errorMessages.apiError(error));
5413
5526
  }
5414
5527
  }
@@ -5459,10 +5572,10 @@ ${schemaDescription}`;
5459
5572
  const response = await this.createResponse(input, zodSchema);
5460
5573
  const { text, reasoningSummary, encryptedReasoning } = this.extractResponseParts(response);
5461
5574
  if (!text) {
5462
- throw new Error(this.errorMessages.emptyResponse);
5575
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5463
5576
  }
5464
5577
  this.logger(`Meta Agent - Found reasoning summary: ${!!reasoningSummary}, encrypted reasoning: ${!!encryptedReasoning}`);
5465
- const parsedData = parseAndValidateLlmJson(text, zodSchema, (m) => this.logger(m));
5578
+ const parsedData = parseAndValidateLlmJson(text, zodSchema, (m) => this.logger(m), this.model);
5466
5579
  this.logger(`\u2705 Response validated successfully with Zod schema`);
5467
5580
  const tokenUsage = this.extractTokenUsage(response);
5468
5581
  if (parsedData) {
@@ -5471,6 +5584,7 @@ ${schemaDescription}`;
5471
5584
  return [parsedData, reasoningSummary, tokenUsage, encryptedReasoning];
5472
5585
  } catch (error) {
5473
5586
  this.logger(this.logTemplates.error(this.name, error));
5587
+ if (error instanceof ModelError) throw error;
5474
5588
  throw new Error(this.errorMessages.apiError(error));
5475
5589
  }
5476
5590
  }
@@ -5486,13 +5600,14 @@ ${schemaDescription}`;
5486
5600
  const response = await this.createResponse(input);
5487
5601
  const { text, reasoningSummary, encryptedReasoning } = this.extractResponseParts(response);
5488
5602
  if (!text) {
5489
- throw new Error(this.errorMessages.emptyResponse);
5603
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5490
5604
  }
5491
5605
  const tokenUsage = this.extractTokenUsage(response);
5492
5606
  this.logReply(text, reasoningSummary, tokenUsage);
5493
5607
  return [text, reasoningSummary, tokenUsage, encryptedReasoning];
5494
5608
  } catch (error) {
5495
5609
  this.logger(this.logTemplates.error(this.name, error));
5610
+ if (error instanceof ModelError) throw error;
5496
5611
  throw new Error(this.errorMessages.apiError(error));
5497
5612
  }
5498
5613
  }
@@ -5662,6 +5777,7 @@ var AgentFactory = class {
5662
5777
  case LLM_CONSTANTS.DEEPSEEK_PRO:
5663
5778
  return new DeepSeekV2Agent(name, instruction, model.modelApiName, key, model.temperature ?? 0, shouldEnableThinking);
5664
5779
  // Mistral models
5780
+ case LLM_CONSTANTS.MISTRAL_LARGE:
5665
5781
  case LLM_CONSTANTS.MISTRAL_SMALL:
5666
5782
  return new MistralAgent(name, instruction, model.modelApiName, key, shouldEnableThinking);
5667
5783
  case LLM_CONSTANTS.KIMI:
@@ -5827,6 +5943,7 @@ var AgentFactory = class {
5827
5943
  safeValidateResponse,
5828
5944
  setBeforeAskHook,
5829
5945
  setLlmLogger,
5946
+ setRetryHook,
5830
5947
  stableHashHex,
5831
5948
  stripInlineThinking,
5832
5949
  supportsNativeJsonSchema,