@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.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 = "";
@@ -844,6 +845,8 @@ var LLM_CONSTANTS = {
844
845
  GEMINI_FLASH: "gemini-flash",
845
846
  GEMINI_LITE: "gemini-lite",
846
847
  MISTRAL_SMALL: "mistral-small",
848
+ // Version-free id (Large 3 used it until 2026-09-18; Large 4 took it over 2026-10-06).
849
+ MISTRAL_LARGE: "mistral-large",
847
850
  GROK: "grok",
848
851
  KIMI: "kimi",
849
852
  // Kimi K3.1 Pro Highspeed: the same model served 2-3x faster at 2x the price (added
@@ -1083,7 +1086,7 @@ var SupportedAiModels = {
1083
1086
  // at medium effort; the 15-character story pipeline took 213s on 2026-10-07.
1084
1087
  tags: ["very-slow"]
1085
1088
  },
1086
- // Mistral models. One hybrid entry: reasoning is off by default on the API and switched on
1089
+ // Mistral models. Two hybrid entries: reasoning is off by default on the API and switched on
1087
1090
  // per request with `reasoning_effort` (see mistral-agent.ts); the trace comes back as a
1088
1091
  // `thinking` content chunk and works with json_schema structured output (verified live
1089
1092
  // 2026-09-18). Pinned to 'high' — the only level Mistral's docs describe ("full thinking
@@ -1104,12 +1107,27 @@ var SupportedAiModels = {
1104
1107
  // `magistral-medium-latest` as one entry — so Magistral seats had silently become Medium
1105
1108
  // seats already. Consumers map both retired ids onto Small (Medium itself is gone since 0.21.0).
1106
1109
  //
1107
- // Mistral Large 4 (`mistral-large-4`, $0.68/$2.09, $0.07 cached) was added in 0.19.0 and
1108
- // removed in 0.19.1 (2026-10-06/07): too slow to play. Like Small/Medium it accepts only
1109
- // reasoning_effort high|none, and unlike them it reasons when the field is omitted. At high
1110
- // a realistic day-2 vote took 25-154s (half past the 60s timeout) and its parallel story
1111
- // batches finished ~100s apart (Mistral served them one at a time: ~6 min per story). Off,
1112
- // it answers in ~1s with no trace. Re-test before re-adding.
1110
+ // Mistral Large 4 (`mistral-large-4`, released 2026-10-06 in public preview) was added in
1111
+ // 0.19.0 and removed in 0.19.1 the next day: at launch a realistic day-2 vote took 25-154s
1112
+ // (half past the 60s timeout) and the story batches finished ~100s apart. Re-tested
1113
+ // 2026-10-30 on the same requests and RE-ADDED in 0.31.0: 19 day-2 votes ran 6-25s (median
1114
+ // ~14s, no timeouts, 760-3,100 output tokens, $0.002-0.011 each) and the 15-character story
1115
+ // pipeline 114-118s — the launch-week slowness was serving load, since `high` is fast now
1116
+ // too. Two things still hold: Mistral serves our parallel sheet batches one at a time
1117
+ // (~22-25s each, finishing 22/50/77/99s), so story time scales with the lobby; and the
1118
+ // model reasons when the field is omitted. The API now takes low|medium|high on Large 4
1119
+ // (the 400 for `none` lists exactly those; Small still takes only high|none); the level
1120
+ // barely moved latency or trace size (4-12k chars at every level), so it stays on the
1121
+ // documented 'high' default. Model list: 1M context. Tagged `slow`: the 15-25s band.
1122
+ [LLM_CONSTANTS.MISTRAL_LARGE]: {
1123
+ displayName: "Mistral Large 4",
1124
+ // `mistral-large-latest` still points at Large 3 (no reasoning); use the explicit id.
1125
+ modelApiName: "mistral-large-4",
1126
+ apiKeyName: API_KEY_CONSTANTS.MISTRAL,
1127
+ hasThinking: true,
1128
+ reasoningEffort: "high",
1129
+ tags: ["slow"]
1130
+ },
1113
1131
  [LLM_CONSTANTS.MISTRAL_SMALL]: {
1114
1132
  displayName: "Mistral 4 Small",
1115
1133
  // Resolves to mistral-small-2603 (Small 4), which also carries the magistral-small alias.
@@ -1567,6 +1585,13 @@ var MODEL_PRICING = {
1567
1585
  outputPrice: 0.6,
1568
1586
  cacheHitPrice: 0.015
1569
1587
  },
1588
+ // Large 4: docs.mistral.ai/models/mistral-large-4-0, read 2026-10-30 ($0.70 / $0.07 cached /
1589
+ // $2.10). The $0.68/$2.09 recorded in 0.19.0 was the two-week launch discount.
1590
+ [SupportedAiModels[LLM_CONSTANTS.MISTRAL_LARGE].modelApiName]: {
1591
+ inputPrice: 0.7,
1592
+ outputPrice: 2.1,
1593
+ cacheHitPrice: 0.07
1594
+ },
1570
1595
  // Grok models. Cached price is per-model on xAI (not a uniform ratio):
1571
1596
  // grok-4.7 is $0.50/M cached vs $2.00/M input, and all rates double for prompts
1572
1597
  // >= 200K tokens, per docs.x.ai/docs/models (re-verified 2026-09-22 for 4.7).
@@ -1646,7 +1671,8 @@ var HYBRID_THINKING_API_NAMES = /* @__PURE__ */ new Set([
1646
1671
  // MiniMax left the set 2026-10-27: M3.1 Flash cannot turn thinking off (M3 could).
1647
1672
  // Mistral reasons only when asked (`reasoning_effort`), and we always ask — hybrid by the
1648
1673
  // same definition as Qwen. Added 2026-09-18 when the Mistral entries went thinking-on.
1649
- SupportedAiModels[LLM_CONSTANTS.MISTRAL_SMALL].modelApiName
1674
+ SupportedAiModels[LLM_CONSTANTS.MISTRAL_SMALL].modelApiName,
1675
+ SupportedAiModels[LLM_CONSTANTS.MISTRAL_LARGE].modelApiName
1650
1676
  ]);
1651
1677
  function isHybridThinkingModel(modelApiName) {
1652
1678
  return HYBRID_THINKING_API_NAMES.has(modelApiName);
@@ -2363,6 +2389,10 @@ var beforeAskHook;
2363
2389
  function setBeforeAskHook(hook) {
2364
2390
  beforeAskHook = hook;
2365
2391
  }
2392
+ var retryHook;
2393
+ function setRetryHook(hook) {
2394
+ retryHook = hook;
2395
+ }
2366
2396
  var AbstractAgent = class {
2367
2397
  name;
2368
2398
  gameId;
@@ -2389,6 +2419,17 @@ var AbstractAgent = class {
2389
2419
  * instance for calls that legitimately run long, like maxOutputTokens.
2390
2420
  */
2391
2421
  requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS;
2422
+ /**
2423
+ * How many times one ask is re-sent after a ModelInvalidResponseError that is not a
2424
+ * cap hit: the model answered with nothing, or with text that is not the JSON the
2425
+ * schema asked for. Those are one-off generation failures the same prompt usually
2426
+ * gets right on the next try, unlike timeouts, refusals and transport errors, which
2427
+ * are never retried here. 0 (the default) hands every failure to the caller. A
2428
+ * truncated response is excluded because re-running it re-buys the whole output at
2429
+ * the cap. Each re-send runs the before-ask hook again (it is a new paid call) and
2430
+ * fires the retry hook; the error finally thrown carries `retries`.
2431
+ */
2432
+ invalidResponseRetries = 0;
2392
2433
  instruction;
2393
2434
  /**
2394
2435
  * The instruction split on CACHE_TIER_MARKER: [shared static tier, per-bot tier].
@@ -2415,26 +2456,83 @@ var AbstractAgent = class {
2415
2456
  this.thinkingBudgetTokens = modelConfig?.thinkingBudgetTokens;
2416
2457
  }
2417
2458
  /**
2418
- * Public ask API — template methods that time the provider call and stamp `durationMs`
2419
- * into the returned TokenUsage. Subclasses implement doAskWithZodSchema/doAskText and
2459
+ * Public ask API — template methods that run the before-ask hook, time the provider
2460
+ * call, stamp `durationMs` into the returned TokenUsage and apply the
2461
+ * invalidResponseRetries policy. Subclasses implement doAskWithZodSchema/doAskText and
2420
2462
  * must NOT override these.
2421
2463
  */
2422
2464
  async askWithZodSchema(zodSchema, messages) {
2423
- if (beforeAskHook) await beforeAskHook(this);
2424
- const startedAt = Date.now();
2465
+ return this.askWithRetries(() => this.doAskWithZodSchema(zodSchema, messages));
2466
+ }
2467
+ async askText(messages) {
2468
+ return this.askWithRetries(() => this.doAskText(messages));
2469
+ }
2470
+ /**
2471
+ * One attempt per loop; an empty or malformed answer (ModelInvalidResponseError, not
2472
+ * truncated) is re-sent up to invalidResponseRetries times, with the retry hook told
2473
+ * before each re-send. Anything else — a timeout, a refusal, a transport error, or the
2474
+ * last allowed attempt failing — is thrown as-is, stamped with the retry count. Every
2475
+ * settle function the hook returned runs once the ask is over, whichever way it ended.
2476
+ */
2477
+ async askWithRetries(call) {
2478
+ const settled = [];
2479
+ let retries = 0;
2425
2480
  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;
2481
+ while (true) {
2482
+ try {
2483
+ return await this.attempt(call);
2484
+ } catch (error) {
2485
+ if (retries > 0 && error && typeof error === "object") {
2486
+ error.retries = retries;
2487
+ }
2488
+ if (!(error instanceof ModelInvalidResponseError) || error.truncated || retries >= this.invalidResponseRetries) {
2489
+ throw error;
2490
+ }
2491
+ retries++;
2492
+ logger.warn(`${this.name} (${this.model}): ${error.message} \u2014 asking again (retry ${retries} of ${this.invalidResponseRetries})`, {
2493
+ gameId: this.gameId,
2494
+ userId: this.userId,
2495
+ agentName: this.name,
2496
+ model: this.model,
2497
+ activity: "llm_retry",
2498
+ attempt: retries,
2499
+ error: error.message
2500
+ });
2501
+ if (retryHook) {
2502
+ try {
2503
+ const onSettled = await retryHook({ agent: this, model: this.model, error, attempt: retries });
2504
+ if (typeof onSettled === "function") settled.push(onSettled);
2505
+ } catch (hookError) {
2506
+ logger.warn(`${this.name} (${this.model}): retry hook failed, retrying anyway`, {
2507
+ gameId: this.gameId,
2508
+ agentName: this.name,
2509
+ model: this.model,
2510
+ error: hookError instanceof Error ? hookError.message : String(hookError)
2511
+ });
2512
+ }
2513
+ }
2514
+ }
2515
+ }
2516
+ } finally {
2517
+ for (const onSettled of settled) {
2518
+ try {
2519
+ await onSettled();
2520
+ } catch (hookError) {
2521
+ logger.warn(`${this.name} (${this.model}): retry settle hook failed`, {
2522
+ gameId: this.gameId,
2523
+ agentName: this.name,
2524
+ model: this.model,
2525
+ error: hookError instanceof Error ? hookError.message : String(hookError)
2526
+ });
2527
+ }
2528
+ }
2431
2529
  }
2432
2530
  }
2433
- async askText(messages) {
2531
+ async attempt(call) {
2434
2532
  if (beforeAskHook) await beforeAskHook(this);
2435
2533
  const startedAt = Date.now();
2436
2534
  try {
2437
- const [content, thinking, usage, signature] = await this.withTimeout(this.doAskText(messages));
2535
+ const [content, thinking, usage, signature] = await this.withTimeout(call());
2438
2536
  return [content, thinking, this.stampDuration(usage, startedAt), signature];
2439
2537
  } catch (error) {
2440
2538
  this.stampErrorDuration(error, startedAt);
@@ -2734,7 +2832,7 @@ ${instruction}`);
2734
2832
  reason === "max_output_tokens"
2735
2833
  );
2736
2834
  }
2737
- throw new Error(this.errorMessages.emptyResponse);
2835
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
2738
2836
  }
2739
2837
  let tokenUsage;
2740
2838
  if (response.usage) {
@@ -3015,7 +3113,7 @@ var ClaudeAgent = class extends AbstractAgent {
3015
3113
  throw new ModelRefusalError(this.model, void 0, "refusal");
3016
3114
  }
3017
3115
  if (!("content" in response) || !Array.isArray(response.content) || response.content.length === 0) {
3018
- throw new Error(this.errorMessages.emptyResponse);
3116
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3019
3117
  }
3020
3118
  let textContent = null;
3021
3119
  let thinkingContent = "";
@@ -3032,9 +3130,9 @@ var ClaudeAgent = class extends AbstractAgent {
3032
3130
  }
3033
3131
  }
3034
3132
  if (!textContent) {
3035
- throw new Error(this.errorMessages.invalidFormat);
3133
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.invalidFormat);
3036
3134
  }
3037
- const parsedData = parseAndValidateLlmJson(textContent, zodSchema, (m) => this.logger(m));
3135
+ const parsedData = parseAndValidateLlmJson(textContent, zodSchema, (m) => this.logger(m), this.model);
3038
3136
  this.logger(`\u2705 Response validated successfully with Zod schema`);
3039
3137
  let tokenUsage;
3040
3138
  if (response.usage) {
@@ -3113,7 +3211,7 @@ var ClaudeAgent = class extends AbstractAgent {
3113
3211
  throw new ModelRefusalError(this.model, void 0, "refusal");
3114
3212
  }
3115
3213
  if (!("content" in response) || !Array.isArray(response.content) || response.content.length === 0) {
3116
- throw new Error(this.errorMessages.emptyResponse);
3214
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3117
3215
  }
3118
3216
  const textParts = [];
3119
3217
  let thinkingContent = "";
@@ -3131,7 +3229,7 @@ var ClaudeAgent = class extends AbstractAgent {
3131
3229
  }
3132
3230
  const textContent = textParts.join("");
3133
3231
  if (!textContent) {
3134
- throw new Error(this.errorMessages.emptyResponse);
3232
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3135
3233
  }
3136
3234
  let tokenUsage;
3137
3235
  if (response.usage) {
@@ -3203,7 +3301,7 @@ function throwForEmptyGeminiResponse(model, response, fallback) {
3203
3301
  const bits = [`finishReason=${finishReason ?? "none"}`];
3204
3302
  if (!response?.candidates?.length) bits.push("no candidates");
3205
3303
  if (finishMessage) bits.push(`finishMessage="${finishMessage}"`);
3206
- throw new Error(`${fallback} (${bits.join(", ")})`);
3304
+ throw new ModelInvalidResponseError(model, `${fallback} (${bits.join(", ")})`);
3207
3305
  }
3208
3306
  var GoogleAgent = class extends AbstractAgent {
3209
3307
  client;
@@ -3399,7 +3497,7 @@ var GoogleAgent = class extends AbstractAgent {
3399
3497
  if (!response.text) {
3400
3498
  throwForEmptyGeminiResponse(this.model, response, this.errorMessages.emptyResponse);
3401
3499
  }
3402
- const parsedData = parseAndValidateLlmJson(response.text, zodSchema, (m) => this.logger(m));
3500
+ const parsedData = parseAndValidateLlmJson(response.text, zodSchema, (m) => this.logger(m), this.model);
3403
3501
  if (parsedData) {
3404
3502
  this.logReply(parsedData, thinkingContent || void 0, tokenUsage);
3405
3503
  }
@@ -3635,7 +3733,7 @@ ${instruction}`);
3635
3733
  processReply(response) {
3636
3734
  const message = response?.choices?.[0]?.message;
3637
3735
  if (!message || !message.content) {
3638
- throw new Error(this.errorMessages.emptyResponse);
3736
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3639
3737
  }
3640
3738
  let reply = message.content;
3641
3739
  if (Array.isArray(reply)) {
@@ -3740,12 +3838,12 @@ ${schemaDescription}`
3740
3838
  throw new Error(this.errorMessages.apiError(apiError));
3741
3839
  }
3742
3840
  if (!response || !response.choices || response.choices.length === 0) {
3743
- throw new Error(this.errorMessages.emptyResponse);
3841
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3744
3842
  }
3745
3843
  const choice = response.choices[0];
3746
3844
  const content = choice.message?.content;
3747
3845
  if (!content) {
3748
- throw new Error(this.errorMessages.invalidFormat);
3846
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.invalidFormat);
3749
3847
  }
3750
3848
  let responseText;
3751
3849
  let thinkingContent = "";
@@ -3758,7 +3856,7 @@ ${schemaDescription}`
3758
3856
  } else {
3759
3857
  responseText = JSON.stringify(content);
3760
3858
  }
3761
- const parsedData = parseAndValidateLlmJson(responseText, zodSchema, (m) => this.logger(m));
3859
+ const parsedData = parseAndValidateLlmJson(responseText, zodSchema, (m) => this.logger(m), this.model);
3762
3860
  this.logger(`\u2705 Response validated successfully with Zod schema`);
3763
3861
  const tokenUsage = this.extractTokenUsage(response);
3764
3862
  if (parsedData) {
@@ -3767,6 +3865,7 @@ ${schemaDescription}`
3767
3865
  return [parsedData, thinkingContent, tokenUsage];
3768
3866
  } catch (error) {
3769
3867
  this.logger(this.logTemplates.error(this.name, error));
3868
+ if (error instanceof ModelError) throw error;
3770
3869
  throw new Error(this.errorMessages.apiError(error));
3771
3870
  }
3772
3871
  }
@@ -3796,12 +3895,13 @@ ${schemaDescription}`
3796
3895
  }
3797
3896
  const [content, thinkingContent, tokenUsage] = this.processReply(response);
3798
3897
  if (!content) {
3799
- throw new Error(this.errorMessages.emptyResponse);
3898
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3800
3899
  }
3801
3900
  this.logReply(content, thinkingContent || void 0, tokenUsage);
3802
3901
  return [content, thinkingContent, tokenUsage];
3803
3902
  } catch (error) {
3804
3903
  this.logger(this.logTemplates.error(this.name, error));
3904
+ if (error instanceof ModelError) throw error;
3805
3905
  throw new Error(this.errorMessages.apiError(error));
3806
3906
  }
3807
3907
  }
@@ -3818,7 +3918,7 @@ var DeepSeekV2Agent = class extends AbstractAgent {
3818
3918
  };
3819
3919
  // Error message templates
3820
3920
  errorMessages = {
3821
- emptyResponse: "Empty or undefined response from DeepSeek API",
3921
+ emptyResponse: (finishReason) => `Empty or undefined response from DeepSeek API (finish_reason: ${finishReason ?? "unknown"})`,
3822
3922
  invalidFormat: "Invalid response format from DeepSeek API",
3823
3923
  apiError: (error) => `Failed to get response from DeepSeek API: ${error instanceof Error ? error.message : String(error)}`
3824
3924
  };
@@ -3923,14 +4023,14 @@ ${schemaDescription}`
3923
4023
  }
3924
4024
  const rawContent = response.choices[0]?.message?.content;
3925
4025
  if (!rawContent) {
3926
- throw new Error(this.errorMessages.emptyResponse);
4026
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(response.choices[0]?.finish_reason));
3927
4027
  }
3928
4028
  const { text: content, thinking: inlineThinking } = stripInlineThinking(rawContent);
3929
4029
  thinkingContent = mergeThinking(thinkingContent, inlineThinking);
3930
4030
  if (!content) {
3931
- throw new Error(this.errorMessages.emptyResponse);
4031
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(response.choices[0]?.finish_reason));
3932
4032
  }
3933
- const parsedData = parseAndValidateLlmJson(content, zodSchema, (m) => this.logger(m));
4033
+ const parsedData = parseAndValidateLlmJson(content, zodSchema, (m) => this.logger(m), this.model);
3934
4034
  this.logger(`\u2705 Response validated successfully with Zod schema`);
3935
4035
  const usageResult = extractUsageAndCalculateCost(this.model, response);
3936
4036
  let tokenUsage;
@@ -3951,6 +4051,7 @@ ${schemaDescription}`
3951
4051
  return [parsedData, thinkingContent, tokenUsage];
3952
4052
  } catch (error) {
3953
4053
  this.logger(this.logTemplates.error(this.name, error));
4054
+ if (error instanceof ModelError) throw error;
3954
4055
  throw new Error(this.errorMessages.apiError(error));
3955
4056
  }
3956
4057
  }
@@ -3986,12 +4087,12 @@ ${schemaDescription}`
3986
4087
  }
3987
4088
  const rawContent = response.choices[0]?.message?.content;
3988
4089
  if (!rawContent) {
3989
- throw new Error(this.errorMessages.emptyResponse);
4090
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(response.choices[0]?.finish_reason));
3990
4091
  }
3991
4092
  const { text: content, thinking: inlineThinking } = stripInlineThinking(rawContent);
3992
4093
  thinkingContent = mergeThinking(thinkingContent, inlineThinking);
3993
4094
  if (!content) {
3994
- throw new Error(this.errorMessages.emptyResponse);
4095
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(response.choices[0]?.finish_reason));
3995
4096
  }
3996
4097
  const usageResult = extractUsageAndCalculateCost(this.model, response);
3997
4098
  let tokenUsage;
@@ -4010,6 +4111,7 @@ ${schemaDescription}`
4010
4111
  return [content, thinkingContent, tokenUsage];
4011
4112
  } catch (error) {
4012
4113
  this.logger(this.logTemplates.error(this.name, error));
4114
+ if (error instanceof ModelError) throw error;
4013
4115
  throw new Error(this.errorMessages.apiError(error));
4014
4116
  }
4015
4117
  }
@@ -4060,10 +4162,10 @@ ${schemaDescription}`;
4060
4162
  const response = await this.createResponse(input, true);
4061
4163
  const { text, reasoningSummary, encryptedReasoning } = this.extractResponseParts(response);
4062
4164
  if (!text) {
4063
- throw new Error(this.errorMessages.emptyResponse);
4165
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4064
4166
  }
4065
4167
  this.logger(`Grok Agent - Found reasoning summary: ${!!reasoningSummary}, encrypted reasoning: ${!!encryptedReasoning}`);
4066
- const parsedData = parseAndValidateLlmJson(text, zodSchema, (m) => this.logger(m));
4168
+ const parsedData = parseAndValidateLlmJson(text, zodSchema, (m) => this.logger(m), this.model);
4067
4169
  this.logger(`\u2705 Response validated successfully with Zod schema`);
4068
4170
  const tokenUsage = this.extractTokenUsage(response);
4069
4171
  if (parsedData) {
@@ -4072,6 +4174,7 @@ ${schemaDescription}`;
4072
4174
  return [parsedData, reasoningSummary, tokenUsage, encryptedReasoning];
4073
4175
  } catch (error) {
4074
4176
  this.logger(this.logTemplates.error(this.name, error));
4177
+ if (error instanceof ModelError) throw error;
4075
4178
  throw new Error(this.errorMessages.apiError(error));
4076
4179
  }
4077
4180
  }
@@ -4087,13 +4190,14 @@ ${schemaDescription}`;
4087
4190
  const response = await this.createResponse(input, false);
4088
4191
  const { text, reasoningSummary, encryptedReasoning } = this.extractResponseParts(response);
4089
4192
  if (!text) {
4090
- throw new Error(this.errorMessages.emptyResponse);
4193
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4091
4194
  }
4092
4195
  const tokenUsage = this.extractTokenUsage(response);
4093
4196
  this.logReply(text, reasoningSummary, tokenUsage);
4094
4197
  return [text, reasoningSummary, tokenUsage, encryptedReasoning];
4095
4198
  } catch (error) {
4096
4199
  this.logger(this.logTemplates.error(this.name, error));
4200
+ if (error instanceof ModelError) throw error;
4097
4201
  throw new Error(this.errorMessages.apiError(error));
4098
4202
  }
4099
4203
  }
@@ -4333,13 +4437,13 @@ ${openAIMessages[0].content}`;
4333
4437
  }
4334
4438
  const rawReply = completion.choices[0]?.message?.content;
4335
4439
  if (!rawReply) {
4336
- throw new Error(this.errorMessages.emptyResponse);
4440
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4337
4441
  }
4338
4442
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4339
4443
  if (!reply) {
4340
- throw new Error(this.errorMessages.emptyResponse);
4444
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4341
4445
  }
4342
- const parsedData = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m));
4446
+ const parsedData = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m), this.model);
4343
4447
  this.logger(`\u2705 Response validated successfully with Zod schema (JSON mode)`);
4344
4448
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4345
4449
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4370,13 +4474,13 @@ ${schemaDescription}`;
4370
4474
  }
4371
4475
  const rawReply = completion.choices[0]?.message?.content;
4372
4476
  if (!rawReply) {
4373
- throw new Error(this.errorMessages.emptyResponse);
4477
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4374
4478
  }
4375
4479
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4376
4480
  if (!reply) {
4377
- throw new Error(this.errorMessages.emptyResponse);
4481
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4378
4482
  }
4379
- const parsedData = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m));
4483
+ const parsedData = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m), this.model);
4380
4484
  this.logger(`\u2705 Response validated successfully with Zod schema (prompt mode)`);
4381
4485
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4382
4486
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4387,6 +4491,7 @@ ${schemaDescription}`;
4387
4491
  }
4388
4492
  } catch (error) {
4389
4493
  this.logger(this.logTemplates.error(this.name, error));
4494
+ if (error instanceof ModelError) throw error;
4390
4495
  throw new Error(this.errorMessages.apiError(error));
4391
4496
  }
4392
4497
  }
@@ -4423,11 +4528,11 @@ ${openAIMessages[0].content}`;
4423
4528
  }
4424
4529
  const rawReply = completion.choices[0]?.message?.content;
4425
4530
  if (!rawReply) {
4426
- throw new Error(this.errorMessages.emptyResponse);
4531
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4427
4532
  }
4428
4533
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4429
4534
  if (!reply) {
4430
- throw new Error(this.errorMessages.emptyResponse);
4535
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4431
4536
  }
4432
4537
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4433
4538
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4435,6 +4540,7 @@ ${openAIMessages[0].content}`;
4435
4540
  return [reply, thinkingContent, tokenUsage];
4436
4541
  } catch (error) {
4437
4542
  this.logger(this.logTemplates.error(this.name, error));
4543
+ if (error instanceof ModelError) throw error;
4438
4544
  throw new Error(this.errorMessages.apiError(error));
4439
4545
  }
4440
4546
  }
@@ -4511,7 +4617,7 @@ var GlmAgent = class extends AbstractAgent {
4511
4617
  * Returns the validated value or throws.
4512
4618
  */
4513
4619
  parseAndValidate(rawReply, zodSchema) {
4514
- return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m));
4620
+ return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m), this.model);
4515
4621
  }
4516
4622
  async doAskWithZodSchema(zodSchema, messages) {
4517
4623
  try {
@@ -4551,11 +4657,11 @@ ${schemaDescription}`;
4551
4657
  }
4552
4658
  const rawReply = completion.choices[0]?.message?.content;
4553
4659
  if (!rawReply) {
4554
- throw new Error(this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4660
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4555
4661
  }
4556
4662
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4557
4663
  if (!reply) {
4558
- throw new Error(this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4664
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4559
4665
  }
4560
4666
  const validated = this.parseAndValidate(reply, zodSchema);
4561
4667
  this.logger(`\u2705 Response validated successfully with Zod schema`);
@@ -4567,6 +4673,7 @@ ${schemaDescription}`;
4567
4673
  return [validated, thinkingContent, tokenUsage];
4568
4674
  } catch (error) {
4569
4675
  this.logger(this.logTemplates.error(this.name, error));
4676
+ if (error instanceof ModelError) throw error;
4570
4677
  throw new Error(this.errorMessages.apiError(error));
4571
4678
  }
4572
4679
  }
@@ -4603,11 +4710,11 @@ ${openAIMessages[0].content}`;
4603
4710
  }
4604
4711
  const rawReply = completion.choices[0]?.message?.content;
4605
4712
  if (!rawReply) {
4606
- throw new Error(this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4713
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4607
4714
  }
4608
4715
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4609
4716
  if (!reply) {
4610
- throw new Error(this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4717
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4611
4718
  }
4612
4719
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4613
4720
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4615,6 +4722,7 @@ ${openAIMessages[0].content}`;
4615
4722
  return [reply, thinkingContent, tokenUsage];
4616
4723
  } catch (error) {
4617
4724
  this.logger(this.logTemplates.error(this.name, error));
4725
+ if (error instanceof ModelError) throw error;
4618
4726
  throw new Error(this.errorMessages.apiError(error));
4619
4727
  }
4620
4728
  }
@@ -4717,13 +4825,13 @@ ${schemaDescription}`;
4717
4825
  }
4718
4826
  const rawReply = completion.choices[0]?.message?.content;
4719
4827
  if (!rawReply) {
4720
- throw new Error(this.errorMessages.emptyResponse);
4828
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4721
4829
  }
4722
4830
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4723
4831
  if (!reply) {
4724
- throw new Error(this.errorMessages.emptyResponse);
4832
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4725
4833
  }
4726
- const validated = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m));
4834
+ const validated = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m), this.model);
4727
4835
  this.logger(`\u2705 Response validated successfully with Zod schema`);
4728
4836
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4729
4837
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4733,6 +4841,7 @@ ${schemaDescription}`;
4733
4841
  return [validated, thinkingContent, tokenUsage];
4734
4842
  } catch (error) {
4735
4843
  this.logger(this.logTemplates.error(this.name, error));
4844
+ if (error instanceof ModelError) throw error;
4736
4845
  throw new Error(this.errorMessages.apiError(error));
4737
4846
  }
4738
4847
  }
@@ -4760,11 +4869,11 @@ ${schemaDescription}`;
4760
4869
  }
4761
4870
  const rawReply = completion.choices[0]?.message?.content;
4762
4871
  if (!rawReply) {
4763
- throw new Error(this.errorMessages.emptyResponse);
4872
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4764
4873
  }
4765
4874
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4766
4875
  if (!reply) {
4767
- throw new Error(this.errorMessages.emptyResponse);
4876
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4768
4877
  }
4769
4878
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4770
4879
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4772,6 +4881,7 @@ ${schemaDescription}`;
4772
4881
  return [reply, thinkingContent, tokenUsage];
4773
4882
  } catch (error) {
4774
4883
  this.logger(this.logTemplates.error(this.name, error));
4884
+ if (error instanceof ModelError) throw error;
4775
4885
  throw new Error(this.errorMessages.apiError(error));
4776
4886
  }
4777
4887
  }
@@ -4929,7 +5039,7 @@ var QwenAgent = class extends AbstractAgent {
4929
5039
  * Returns the validated value or throws.
4930
5040
  */
4931
5041
  parseAndValidate(rawReply, zodSchema) {
4932
- return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m));
5042
+ return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m), this.model);
4933
5043
  }
4934
5044
  async doAskWithZodSchema(zodSchema, messages) {
4935
5045
  try {
@@ -4973,11 +5083,11 @@ ${schemaDescription}`;
4973
5083
  }
4974
5084
  const rawReply = completion.choices[0]?.message?.content;
4975
5085
  if (!rawReply) {
4976
- throw new Error(this.errorMessages.emptyResponse);
5086
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4977
5087
  }
4978
5088
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4979
5089
  if (!reply) {
4980
- throw new Error(this.errorMessages.emptyResponse);
5090
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4981
5091
  }
4982
5092
  const validated = this.parseAndValidate(reply, zodSchema);
4983
5093
  this.logger(`\u2705 Response validated successfully with Zod schema`);
@@ -5029,11 +5139,11 @@ ${openAIMessages[0].content}`;
5029
5139
  }
5030
5140
  const rawReply = completion.choices[0]?.message?.content;
5031
5141
  if (!rawReply) {
5032
- throw new Error(this.errorMessages.emptyResponse);
5142
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5033
5143
  }
5034
5144
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
5035
5145
  if (!reply) {
5036
- throw new Error(this.errorMessages.emptyResponse);
5146
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5037
5147
  }
5038
5148
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
5039
5149
  const thinkingContent = [reasoningContent, inlineThinking].filter(Boolean).join("\n");
@@ -5127,7 +5237,7 @@ var MiniMaxAgent = class extends AbstractAgent {
5127
5237
  * Returns the validated value or throws.
5128
5238
  */
5129
5239
  parseAndValidate(rawReply, zodSchema) {
5130
- return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m));
5240
+ return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m), this.model);
5131
5241
  }
5132
5242
  async doAskWithZodSchema(zodSchema, messages) {
5133
5243
  try {
@@ -5167,7 +5277,7 @@ ${schemaDescription}`;
5167
5277
  }
5168
5278
  const reply = completion.choices[0]?.message?.content;
5169
5279
  if (!reply) {
5170
- throw new Error(this.errorMessages.emptyResponse);
5280
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5171
5281
  }
5172
5282
  const { text: cleanReply, thinking: inlineThinking } = stripInlineThinking(reply);
5173
5283
  const validated = this.parseAndValidate(cleanReply, zodSchema);
@@ -5180,6 +5290,7 @@ ${schemaDescription}`;
5180
5290
  return [validated, thinkingContent, tokenUsage];
5181
5291
  } catch (error) {
5182
5292
  this.logger(this.logTemplates.error(this.name, error));
5293
+ if (error instanceof ModelError) throw error;
5183
5294
  throw new Error(this.errorMessages.apiError(error));
5184
5295
  }
5185
5296
  }
@@ -5217,11 +5328,11 @@ ${openAIMessages[0].content}`;
5217
5328
  }
5218
5329
  const reply = completion.choices[0]?.message?.content;
5219
5330
  if (!reply) {
5220
- throw new Error(this.errorMessages.emptyResponse);
5331
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5221
5332
  }
5222
5333
  const { text: cleanReply, thinking: inlineThinking } = stripInlineThinking(reply);
5223
5334
  if (!cleanReply) {
5224
- throw new Error(this.errorMessages.emptyResponse);
5335
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5225
5336
  }
5226
5337
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
5227
5338
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -5229,6 +5340,7 @@ ${openAIMessages[0].content}`;
5229
5340
  return [cleanReply, thinkingContent, tokenUsage];
5230
5341
  } catch (error) {
5231
5342
  this.logger(this.logTemplates.error(this.name, error));
5343
+ if (error instanceof ModelError) throw error;
5232
5344
  throw new Error(this.errorMessages.apiError(error));
5233
5345
  }
5234
5346
  }
@@ -5279,10 +5391,10 @@ ${schemaDescription}`;
5279
5391
  const response = await this.createResponse(input, zodSchema);
5280
5392
  const { text, reasoningSummary, encryptedReasoning } = this.extractResponseParts(response);
5281
5393
  if (!text) {
5282
- throw new Error(this.errorMessages.emptyResponse);
5394
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5283
5395
  }
5284
5396
  this.logger(`Meta Agent - Found reasoning summary: ${!!reasoningSummary}, encrypted reasoning: ${!!encryptedReasoning}`);
5285
- const parsedData = parseAndValidateLlmJson(text, zodSchema, (m) => this.logger(m));
5397
+ const parsedData = parseAndValidateLlmJson(text, zodSchema, (m) => this.logger(m), this.model);
5286
5398
  this.logger(`\u2705 Response validated successfully with Zod schema`);
5287
5399
  const tokenUsage = this.extractTokenUsage(response);
5288
5400
  if (parsedData) {
@@ -5291,6 +5403,7 @@ ${schemaDescription}`;
5291
5403
  return [parsedData, reasoningSummary, tokenUsage, encryptedReasoning];
5292
5404
  } catch (error) {
5293
5405
  this.logger(this.logTemplates.error(this.name, error));
5406
+ if (error instanceof ModelError) throw error;
5294
5407
  throw new Error(this.errorMessages.apiError(error));
5295
5408
  }
5296
5409
  }
@@ -5306,13 +5419,14 @@ ${schemaDescription}`;
5306
5419
  const response = await this.createResponse(input);
5307
5420
  const { text, reasoningSummary, encryptedReasoning } = this.extractResponseParts(response);
5308
5421
  if (!text) {
5309
- throw new Error(this.errorMessages.emptyResponse);
5422
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5310
5423
  }
5311
5424
  const tokenUsage = this.extractTokenUsage(response);
5312
5425
  this.logReply(text, reasoningSummary, tokenUsage);
5313
5426
  return [text, reasoningSummary, tokenUsage, encryptedReasoning];
5314
5427
  } catch (error) {
5315
5428
  this.logger(this.logTemplates.error(this.name, error));
5429
+ if (error instanceof ModelError) throw error;
5316
5430
  throw new Error(this.errorMessages.apiError(error));
5317
5431
  }
5318
5432
  }
@@ -5482,6 +5596,7 @@ var AgentFactory = class {
5482
5596
  case LLM_CONSTANTS.DEEPSEEK_PRO:
5483
5597
  return new DeepSeekV2Agent(name, instruction, model.modelApiName, key, model.temperature ?? 0, shouldEnableThinking);
5484
5598
  // Mistral models
5599
+ case LLM_CONSTANTS.MISTRAL_LARGE:
5485
5600
  case LLM_CONSTANTS.MISTRAL_SMALL:
5486
5601
  return new MistralAgent(name, instruction, model.modelApiName, key, shouldEnableThinking);
5487
5602
  case LLM_CONSTANTS.KIMI:
@@ -5646,6 +5761,7 @@ export {
5646
5761
  safeValidateResponse,
5647
5762
  setBeforeAskHook,
5648
5763
  setLlmLogger,
5764
+ setRetryHook,
5649
5765
  stableHashHex,
5650
5766
  stripInlineThinking,
5651
5767
  supportsNativeJsonSchema,