@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.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 = "";
@@ -2543,6 +2545,10 @@ var beforeAskHook;
2543
2545
  function setBeforeAskHook(hook) {
2544
2546
  beforeAskHook = hook;
2545
2547
  }
2548
+ var retryHook;
2549
+ function setRetryHook(hook) {
2550
+ retryHook = hook;
2551
+ }
2546
2552
  var AbstractAgent = class {
2547
2553
  name;
2548
2554
  gameId;
@@ -2569,6 +2575,17 @@ var AbstractAgent = class {
2569
2575
  * instance for calls that legitimately run long, like maxOutputTokens.
2570
2576
  */
2571
2577
  requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS;
2578
+ /**
2579
+ * How many times one ask is re-sent after a ModelInvalidResponseError that is not a
2580
+ * cap hit: the model answered with nothing, or with text that is not the JSON the
2581
+ * schema asked for. Those are one-off generation failures the same prompt usually
2582
+ * gets right on the next try, unlike timeouts, refusals and transport errors, which
2583
+ * are never retried here. 0 (the default) hands every failure to the caller. A
2584
+ * truncated response is excluded because re-running it re-buys the whole output at
2585
+ * the cap. Each re-send runs the before-ask hook again (it is a new paid call) and
2586
+ * fires the retry hook; the error finally thrown carries `retries`.
2587
+ */
2588
+ invalidResponseRetries = 0;
2572
2589
  instruction;
2573
2590
  /**
2574
2591
  * The instruction split on CACHE_TIER_MARKER: [shared static tier, per-bot tier].
@@ -2595,26 +2612,83 @@ var AbstractAgent = class {
2595
2612
  this.thinkingBudgetTokens = modelConfig?.thinkingBudgetTokens;
2596
2613
  }
2597
2614
  /**
2598
- * Public ask API — template methods that time the provider call and stamp `durationMs`
2599
- * into the returned TokenUsage. Subclasses implement doAskWithZodSchema/doAskText and
2615
+ * Public ask API — template methods that run the before-ask hook, time the provider
2616
+ * call, stamp `durationMs` into the returned TokenUsage and apply the
2617
+ * invalidResponseRetries policy. Subclasses implement doAskWithZodSchema/doAskText and
2600
2618
  * must NOT override these.
2601
2619
  */
2602
2620
  async askWithZodSchema(zodSchema, messages) {
2603
- if (beforeAskHook) await beforeAskHook(this);
2604
- const startedAt = Date.now();
2621
+ return this.askWithRetries(() => this.doAskWithZodSchema(zodSchema, messages));
2622
+ }
2623
+ async askText(messages) {
2624
+ return this.askWithRetries(() => this.doAskText(messages));
2625
+ }
2626
+ /**
2627
+ * One attempt per loop; an empty or malformed answer (ModelInvalidResponseError, not
2628
+ * truncated) is re-sent up to invalidResponseRetries times, with the retry hook told
2629
+ * before each re-send. Anything else — a timeout, a refusal, a transport error, or the
2630
+ * last allowed attempt failing — is thrown as-is, stamped with the retry count. Every
2631
+ * settle function the hook returned runs once the ask is over, whichever way it ended.
2632
+ */
2633
+ async askWithRetries(call) {
2634
+ const settled = [];
2635
+ let retries = 0;
2605
2636
  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;
2637
+ while (true) {
2638
+ try {
2639
+ return await this.attempt(call);
2640
+ } catch (error) {
2641
+ if (retries > 0 && error && typeof error === "object") {
2642
+ error.retries = retries;
2643
+ }
2644
+ if (!(error instanceof ModelInvalidResponseError) || error.truncated || retries >= this.invalidResponseRetries) {
2645
+ throw error;
2646
+ }
2647
+ retries++;
2648
+ logger.warn(`${this.name} (${this.model}): ${error.message} \u2014 asking again (retry ${retries} of ${this.invalidResponseRetries})`, {
2649
+ gameId: this.gameId,
2650
+ userId: this.userId,
2651
+ agentName: this.name,
2652
+ model: this.model,
2653
+ activity: "llm_retry",
2654
+ attempt: retries,
2655
+ error: error.message
2656
+ });
2657
+ if (retryHook) {
2658
+ try {
2659
+ const onSettled = await retryHook({ agent: this, model: this.model, error, attempt: retries });
2660
+ if (typeof onSettled === "function") settled.push(onSettled);
2661
+ } catch (hookError) {
2662
+ logger.warn(`${this.name} (${this.model}): retry hook failed, retrying anyway`, {
2663
+ gameId: this.gameId,
2664
+ agentName: this.name,
2665
+ model: this.model,
2666
+ error: hookError instanceof Error ? hookError.message : String(hookError)
2667
+ });
2668
+ }
2669
+ }
2670
+ }
2671
+ }
2672
+ } finally {
2673
+ for (const onSettled of settled) {
2674
+ try {
2675
+ await onSettled();
2676
+ } catch (hookError) {
2677
+ logger.warn(`${this.name} (${this.model}): retry settle hook failed`, {
2678
+ gameId: this.gameId,
2679
+ agentName: this.name,
2680
+ model: this.model,
2681
+ error: hookError instanceof Error ? hookError.message : String(hookError)
2682
+ });
2683
+ }
2684
+ }
2611
2685
  }
2612
2686
  }
2613
- async askText(messages) {
2687
+ async attempt(call) {
2614
2688
  if (beforeAskHook) await beforeAskHook(this);
2615
2689
  const startedAt = Date.now();
2616
2690
  try {
2617
- const [content, thinking, usage, signature] = await this.withTimeout(this.doAskText(messages));
2691
+ const [content, thinking, usage, signature] = await this.withTimeout(call());
2618
2692
  return [content, thinking, this.stampDuration(usage, startedAt), signature];
2619
2693
  } catch (error) {
2620
2694
  this.stampErrorDuration(error, startedAt);
@@ -2914,7 +2988,7 @@ ${instruction}`);
2914
2988
  reason === "max_output_tokens"
2915
2989
  );
2916
2990
  }
2917
- throw new Error(this.errorMessages.emptyResponse);
2991
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
2918
2992
  }
2919
2993
  let tokenUsage;
2920
2994
  if (response.usage) {
@@ -3195,7 +3269,7 @@ var ClaudeAgent = class extends AbstractAgent {
3195
3269
  throw new ModelRefusalError(this.model, void 0, "refusal");
3196
3270
  }
3197
3271
  if (!("content" in response) || !Array.isArray(response.content) || response.content.length === 0) {
3198
- throw new Error(this.errorMessages.emptyResponse);
3272
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3199
3273
  }
3200
3274
  let textContent = null;
3201
3275
  let thinkingContent = "";
@@ -3212,9 +3286,9 @@ var ClaudeAgent = class extends AbstractAgent {
3212
3286
  }
3213
3287
  }
3214
3288
  if (!textContent) {
3215
- throw new Error(this.errorMessages.invalidFormat);
3289
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.invalidFormat);
3216
3290
  }
3217
- const parsedData = parseAndValidateLlmJson(textContent, zodSchema, (m) => this.logger(m));
3291
+ const parsedData = parseAndValidateLlmJson(textContent, zodSchema, (m) => this.logger(m), this.model);
3218
3292
  this.logger(`\u2705 Response validated successfully with Zod schema`);
3219
3293
  let tokenUsage;
3220
3294
  if (response.usage) {
@@ -3293,7 +3367,7 @@ var ClaudeAgent = class extends AbstractAgent {
3293
3367
  throw new ModelRefusalError(this.model, void 0, "refusal");
3294
3368
  }
3295
3369
  if (!("content" in response) || !Array.isArray(response.content) || response.content.length === 0) {
3296
- throw new Error(this.errorMessages.emptyResponse);
3370
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3297
3371
  }
3298
3372
  const textParts = [];
3299
3373
  let thinkingContent = "";
@@ -3311,7 +3385,7 @@ var ClaudeAgent = class extends AbstractAgent {
3311
3385
  }
3312
3386
  const textContent = textParts.join("");
3313
3387
  if (!textContent) {
3314
- throw new Error(this.errorMessages.emptyResponse);
3388
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3315
3389
  }
3316
3390
  let tokenUsage;
3317
3391
  if (response.usage) {
@@ -3383,7 +3457,7 @@ function throwForEmptyGeminiResponse(model, response, fallback) {
3383
3457
  const bits = [`finishReason=${finishReason ?? "none"}`];
3384
3458
  if (!response?.candidates?.length) bits.push("no candidates");
3385
3459
  if (finishMessage) bits.push(`finishMessage="${finishMessage}"`);
3386
- throw new Error(`${fallback} (${bits.join(", ")})`);
3460
+ throw new ModelInvalidResponseError(model, `${fallback} (${bits.join(", ")})`);
3387
3461
  }
3388
3462
  var GoogleAgent = class extends AbstractAgent {
3389
3463
  client;
@@ -3579,7 +3653,7 @@ var GoogleAgent = class extends AbstractAgent {
3579
3653
  if (!response.text) {
3580
3654
  throwForEmptyGeminiResponse(this.model, response, this.errorMessages.emptyResponse);
3581
3655
  }
3582
- const parsedData = parseAndValidateLlmJson(response.text, zodSchema, (m) => this.logger(m));
3656
+ const parsedData = parseAndValidateLlmJson(response.text, zodSchema, (m) => this.logger(m), this.model);
3583
3657
  if (parsedData) {
3584
3658
  this.logReply(parsedData, thinkingContent || void 0, tokenUsage);
3585
3659
  }
@@ -3815,7 +3889,7 @@ ${instruction}`);
3815
3889
  processReply(response) {
3816
3890
  const message = response?.choices?.[0]?.message;
3817
3891
  if (!message || !message.content) {
3818
- throw new Error(this.errorMessages.emptyResponse);
3892
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3819
3893
  }
3820
3894
  let reply = message.content;
3821
3895
  if (Array.isArray(reply)) {
@@ -3920,12 +3994,12 @@ ${schemaDescription}`
3920
3994
  throw new Error(this.errorMessages.apiError(apiError));
3921
3995
  }
3922
3996
  if (!response || !response.choices || response.choices.length === 0) {
3923
- throw new Error(this.errorMessages.emptyResponse);
3997
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3924
3998
  }
3925
3999
  const choice = response.choices[0];
3926
4000
  const content = choice.message?.content;
3927
4001
  if (!content) {
3928
- throw new Error(this.errorMessages.invalidFormat);
4002
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.invalidFormat);
3929
4003
  }
3930
4004
  let responseText;
3931
4005
  let thinkingContent = "";
@@ -3938,7 +4012,7 @@ ${schemaDescription}`
3938
4012
  } else {
3939
4013
  responseText = JSON.stringify(content);
3940
4014
  }
3941
- const parsedData = parseAndValidateLlmJson(responseText, zodSchema, (m) => this.logger(m));
4015
+ const parsedData = parseAndValidateLlmJson(responseText, zodSchema, (m) => this.logger(m), this.model);
3942
4016
  this.logger(`\u2705 Response validated successfully with Zod schema`);
3943
4017
  const tokenUsage = this.extractTokenUsage(response);
3944
4018
  if (parsedData) {
@@ -3947,6 +4021,7 @@ ${schemaDescription}`
3947
4021
  return [parsedData, thinkingContent, tokenUsage];
3948
4022
  } catch (error) {
3949
4023
  this.logger(this.logTemplates.error(this.name, error));
4024
+ if (error instanceof ModelError) throw error;
3950
4025
  throw new Error(this.errorMessages.apiError(error));
3951
4026
  }
3952
4027
  }
@@ -3976,12 +4051,13 @@ ${schemaDescription}`
3976
4051
  }
3977
4052
  const [content, thinkingContent, tokenUsage] = this.processReply(response);
3978
4053
  if (!content) {
3979
- throw new Error(this.errorMessages.emptyResponse);
4054
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
3980
4055
  }
3981
4056
  this.logReply(content, thinkingContent || void 0, tokenUsage);
3982
4057
  return [content, thinkingContent, tokenUsage];
3983
4058
  } catch (error) {
3984
4059
  this.logger(this.logTemplates.error(this.name, error));
4060
+ if (error instanceof ModelError) throw error;
3985
4061
  throw new Error(this.errorMessages.apiError(error));
3986
4062
  }
3987
4063
  }
@@ -3998,7 +4074,7 @@ var DeepSeekV2Agent = class extends AbstractAgent {
3998
4074
  };
3999
4075
  // Error message templates
4000
4076
  errorMessages = {
4001
- emptyResponse: "Empty or undefined response from DeepSeek API",
4077
+ emptyResponse: (finishReason) => `Empty or undefined response from DeepSeek API (finish_reason: ${finishReason ?? "unknown"})`,
4002
4078
  invalidFormat: "Invalid response format from DeepSeek API",
4003
4079
  apiError: (error) => `Failed to get response from DeepSeek API: ${error instanceof Error ? error.message : String(error)}`
4004
4080
  };
@@ -4103,14 +4179,14 @@ ${schemaDescription}`
4103
4179
  }
4104
4180
  const rawContent = response.choices[0]?.message?.content;
4105
4181
  if (!rawContent) {
4106
- throw new Error(this.errorMessages.emptyResponse);
4182
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(response.choices[0]?.finish_reason));
4107
4183
  }
4108
4184
  const { text: content, thinking: inlineThinking } = stripInlineThinking(rawContent);
4109
4185
  thinkingContent = mergeThinking(thinkingContent, inlineThinking);
4110
4186
  if (!content) {
4111
- throw new Error(this.errorMessages.emptyResponse);
4187
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(response.choices[0]?.finish_reason));
4112
4188
  }
4113
- const parsedData = parseAndValidateLlmJson(content, zodSchema, (m) => this.logger(m));
4189
+ const parsedData = parseAndValidateLlmJson(content, zodSchema, (m) => this.logger(m), this.model);
4114
4190
  this.logger(`\u2705 Response validated successfully with Zod schema`);
4115
4191
  const usageResult = extractUsageAndCalculateCost(this.model, response);
4116
4192
  let tokenUsage;
@@ -4131,6 +4207,7 @@ ${schemaDescription}`
4131
4207
  return [parsedData, thinkingContent, tokenUsage];
4132
4208
  } catch (error) {
4133
4209
  this.logger(this.logTemplates.error(this.name, error));
4210
+ if (error instanceof ModelError) throw error;
4134
4211
  throw new Error(this.errorMessages.apiError(error));
4135
4212
  }
4136
4213
  }
@@ -4166,12 +4243,12 @@ ${schemaDescription}`
4166
4243
  }
4167
4244
  const rawContent = response.choices[0]?.message?.content;
4168
4245
  if (!rawContent) {
4169
- throw new Error(this.errorMessages.emptyResponse);
4246
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(response.choices[0]?.finish_reason));
4170
4247
  }
4171
4248
  const { text: content, thinking: inlineThinking } = stripInlineThinking(rawContent);
4172
4249
  thinkingContent = mergeThinking(thinkingContent, inlineThinking);
4173
4250
  if (!content) {
4174
- throw new Error(this.errorMessages.emptyResponse);
4251
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(response.choices[0]?.finish_reason));
4175
4252
  }
4176
4253
  const usageResult = extractUsageAndCalculateCost(this.model, response);
4177
4254
  let tokenUsage;
@@ -4190,6 +4267,7 @@ ${schemaDescription}`
4190
4267
  return [content, thinkingContent, tokenUsage];
4191
4268
  } catch (error) {
4192
4269
  this.logger(this.logTemplates.error(this.name, error));
4270
+ if (error instanceof ModelError) throw error;
4193
4271
  throw new Error(this.errorMessages.apiError(error));
4194
4272
  }
4195
4273
  }
@@ -4240,10 +4318,10 @@ ${schemaDescription}`;
4240
4318
  const response = await this.createResponse(input, true);
4241
4319
  const { text, reasoningSummary, encryptedReasoning } = this.extractResponseParts(response);
4242
4320
  if (!text) {
4243
- throw new Error(this.errorMessages.emptyResponse);
4321
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4244
4322
  }
4245
4323
  this.logger(`Grok Agent - Found reasoning summary: ${!!reasoningSummary}, encrypted reasoning: ${!!encryptedReasoning}`);
4246
- const parsedData = parseAndValidateLlmJson(text, zodSchema, (m) => this.logger(m));
4324
+ const parsedData = parseAndValidateLlmJson(text, zodSchema, (m) => this.logger(m), this.model);
4247
4325
  this.logger(`\u2705 Response validated successfully with Zod schema`);
4248
4326
  const tokenUsage = this.extractTokenUsage(response);
4249
4327
  if (parsedData) {
@@ -4252,6 +4330,7 @@ ${schemaDescription}`;
4252
4330
  return [parsedData, reasoningSummary, tokenUsage, encryptedReasoning];
4253
4331
  } catch (error) {
4254
4332
  this.logger(this.logTemplates.error(this.name, error));
4333
+ if (error instanceof ModelError) throw error;
4255
4334
  throw new Error(this.errorMessages.apiError(error));
4256
4335
  }
4257
4336
  }
@@ -4267,13 +4346,14 @@ ${schemaDescription}`;
4267
4346
  const response = await this.createResponse(input, false);
4268
4347
  const { text, reasoningSummary, encryptedReasoning } = this.extractResponseParts(response);
4269
4348
  if (!text) {
4270
- throw new Error(this.errorMessages.emptyResponse);
4349
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4271
4350
  }
4272
4351
  const tokenUsage = this.extractTokenUsage(response);
4273
4352
  this.logReply(text, reasoningSummary, tokenUsage);
4274
4353
  return [text, reasoningSummary, tokenUsage, encryptedReasoning];
4275
4354
  } catch (error) {
4276
4355
  this.logger(this.logTemplates.error(this.name, error));
4356
+ if (error instanceof ModelError) throw error;
4277
4357
  throw new Error(this.errorMessages.apiError(error));
4278
4358
  }
4279
4359
  }
@@ -4513,13 +4593,13 @@ ${openAIMessages[0].content}`;
4513
4593
  }
4514
4594
  const rawReply = completion.choices[0]?.message?.content;
4515
4595
  if (!rawReply) {
4516
- throw new Error(this.errorMessages.emptyResponse);
4596
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4517
4597
  }
4518
4598
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4519
4599
  if (!reply) {
4520
- throw new Error(this.errorMessages.emptyResponse);
4600
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4521
4601
  }
4522
- const parsedData = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m));
4602
+ const parsedData = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m), this.model);
4523
4603
  this.logger(`\u2705 Response validated successfully with Zod schema (JSON mode)`);
4524
4604
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4525
4605
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4550,13 +4630,13 @@ ${schemaDescription}`;
4550
4630
  }
4551
4631
  const rawReply = completion.choices[0]?.message?.content;
4552
4632
  if (!rawReply) {
4553
- throw new Error(this.errorMessages.emptyResponse);
4633
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4554
4634
  }
4555
4635
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4556
4636
  if (!reply) {
4557
- throw new Error(this.errorMessages.emptyResponse);
4637
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4558
4638
  }
4559
- const parsedData = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m));
4639
+ const parsedData = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m), this.model);
4560
4640
  this.logger(`\u2705 Response validated successfully with Zod schema (prompt mode)`);
4561
4641
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4562
4642
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4567,6 +4647,7 @@ ${schemaDescription}`;
4567
4647
  }
4568
4648
  } catch (error) {
4569
4649
  this.logger(this.logTemplates.error(this.name, error));
4650
+ if (error instanceof ModelError) throw error;
4570
4651
  throw new Error(this.errorMessages.apiError(error));
4571
4652
  }
4572
4653
  }
@@ -4603,11 +4684,11 @@ ${openAIMessages[0].content}`;
4603
4684
  }
4604
4685
  const rawReply = completion.choices[0]?.message?.content;
4605
4686
  if (!rawReply) {
4606
- throw new Error(this.errorMessages.emptyResponse);
4687
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4607
4688
  }
4608
4689
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4609
4690
  if (!reply) {
4610
- throw new Error(this.errorMessages.emptyResponse);
4691
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4611
4692
  }
4612
4693
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4613
4694
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4615,6 +4696,7 @@ ${openAIMessages[0].content}`;
4615
4696
  return [reply, thinkingContent, tokenUsage];
4616
4697
  } catch (error) {
4617
4698
  this.logger(this.logTemplates.error(this.name, error));
4699
+ if (error instanceof ModelError) throw error;
4618
4700
  throw new Error(this.errorMessages.apiError(error));
4619
4701
  }
4620
4702
  }
@@ -4691,7 +4773,7 @@ var GlmAgent = class extends AbstractAgent {
4691
4773
  * Returns the validated value or throws.
4692
4774
  */
4693
4775
  parseAndValidate(rawReply, zodSchema) {
4694
- return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m));
4776
+ return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m), this.model);
4695
4777
  }
4696
4778
  async doAskWithZodSchema(zodSchema, messages) {
4697
4779
  try {
@@ -4731,11 +4813,11 @@ ${schemaDescription}`;
4731
4813
  }
4732
4814
  const rawReply = completion.choices[0]?.message?.content;
4733
4815
  if (!rawReply) {
4734
- throw new Error(this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4816
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4735
4817
  }
4736
4818
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4737
4819
  if (!reply) {
4738
- throw new Error(this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4820
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4739
4821
  }
4740
4822
  const validated = this.parseAndValidate(reply, zodSchema);
4741
4823
  this.logger(`\u2705 Response validated successfully with Zod schema`);
@@ -4747,6 +4829,7 @@ ${schemaDescription}`;
4747
4829
  return [validated, thinkingContent, tokenUsage];
4748
4830
  } catch (error) {
4749
4831
  this.logger(this.logTemplates.error(this.name, error));
4832
+ if (error instanceof ModelError) throw error;
4750
4833
  throw new Error(this.errorMessages.apiError(error));
4751
4834
  }
4752
4835
  }
@@ -4783,11 +4866,11 @@ ${openAIMessages[0].content}`;
4783
4866
  }
4784
4867
  const rawReply = completion.choices[0]?.message?.content;
4785
4868
  if (!rawReply) {
4786
- throw new Error(this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4869
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4787
4870
  }
4788
4871
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4789
4872
  if (!reply) {
4790
- throw new Error(this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4873
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse(completion.choices[0]?.finish_reason));
4791
4874
  }
4792
4875
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4793
4876
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4795,6 +4878,7 @@ ${openAIMessages[0].content}`;
4795
4878
  return [reply, thinkingContent, tokenUsage];
4796
4879
  } catch (error) {
4797
4880
  this.logger(this.logTemplates.error(this.name, error));
4881
+ if (error instanceof ModelError) throw error;
4798
4882
  throw new Error(this.errorMessages.apiError(error));
4799
4883
  }
4800
4884
  }
@@ -4897,13 +4981,13 @@ ${schemaDescription}`;
4897
4981
  }
4898
4982
  const rawReply = completion.choices[0]?.message?.content;
4899
4983
  if (!rawReply) {
4900
- throw new Error(this.errorMessages.emptyResponse);
4984
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4901
4985
  }
4902
4986
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4903
4987
  if (!reply) {
4904
- throw new Error(this.errorMessages.emptyResponse);
4988
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4905
4989
  }
4906
- const validated = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m));
4990
+ const validated = parseAndValidateLlmJson(reply, zodSchema, (m) => this.logger(m), this.model);
4907
4991
  this.logger(`\u2705 Response validated successfully with Zod schema`);
4908
4992
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4909
4993
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4913,6 +4997,7 @@ ${schemaDescription}`;
4913
4997
  return [validated, thinkingContent, tokenUsage];
4914
4998
  } catch (error) {
4915
4999
  this.logger(this.logTemplates.error(this.name, error));
5000
+ if (error instanceof ModelError) throw error;
4916
5001
  throw new Error(this.errorMessages.apiError(error));
4917
5002
  }
4918
5003
  }
@@ -4940,11 +5025,11 @@ ${schemaDescription}`;
4940
5025
  }
4941
5026
  const rawReply = completion.choices[0]?.message?.content;
4942
5027
  if (!rawReply) {
4943
- throw new Error(this.errorMessages.emptyResponse);
5028
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4944
5029
  }
4945
5030
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
4946
5031
  if (!reply) {
4947
- throw new Error(this.errorMessages.emptyResponse);
5032
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
4948
5033
  }
4949
5034
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
4950
5035
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -4952,6 +5037,7 @@ ${schemaDescription}`;
4952
5037
  return [reply, thinkingContent, tokenUsage];
4953
5038
  } catch (error) {
4954
5039
  this.logger(this.logTemplates.error(this.name, error));
5040
+ if (error instanceof ModelError) throw error;
4955
5041
  throw new Error(this.errorMessages.apiError(error));
4956
5042
  }
4957
5043
  }
@@ -5109,7 +5195,7 @@ var QwenAgent = class extends AbstractAgent {
5109
5195
  * Returns the validated value or throws.
5110
5196
  */
5111
5197
  parseAndValidate(rawReply, zodSchema) {
5112
- return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m));
5198
+ return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m), this.model);
5113
5199
  }
5114
5200
  async doAskWithZodSchema(zodSchema, messages) {
5115
5201
  try {
@@ -5153,11 +5239,11 @@ ${schemaDescription}`;
5153
5239
  }
5154
5240
  const rawReply = completion.choices[0]?.message?.content;
5155
5241
  if (!rawReply) {
5156
- throw new Error(this.errorMessages.emptyResponse);
5242
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5157
5243
  }
5158
5244
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
5159
5245
  if (!reply) {
5160
- throw new Error(this.errorMessages.emptyResponse);
5246
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5161
5247
  }
5162
5248
  const validated = this.parseAndValidate(reply, zodSchema);
5163
5249
  this.logger(`\u2705 Response validated successfully with Zod schema`);
@@ -5209,11 +5295,11 @@ ${openAIMessages[0].content}`;
5209
5295
  }
5210
5296
  const rawReply = completion.choices[0]?.message?.content;
5211
5297
  if (!rawReply) {
5212
- throw new Error(this.errorMessages.emptyResponse);
5298
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5213
5299
  }
5214
5300
  const { text: reply, thinking: inlineThinking } = stripInlineThinking(rawReply);
5215
5301
  if (!reply) {
5216
- throw new Error(this.errorMessages.emptyResponse);
5302
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5217
5303
  }
5218
5304
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
5219
5305
  const thinkingContent = [reasoningContent, inlineThinking].filter(Boolean).join("\n");
@@ -5307,7 +5393,7 @@ var MiniMaxAgent = class extends AbstractAgent {
5307
5393
  * Returns the validated value or throws.
5308
5394
  */
5309
5395
  parseAndValidate(rawReply, zodSchema) {
5310
- return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m));
5396
+ return parseAndValidateLlmJson(rawReply, zodSchema, (m) => this.logger(m), this.model);
5311
5397
  }
5312
5398
  async doAskWithZodSchema(zodSchema, messages) {
5313
5399
  try {
@@ -5347,7 +5433,7 @@ ${schemaDescription}`;
5347
5433
  }
5348
5434
  const reply = completion.choices[0]?.message?.content;
5349
5435
  if (!reply) {
5350
- throw new Error(this.errorMessages.emptyResponse);
5436
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5351
5437
  }
5352
5438
  const { text: cleanReply, thinking: inlineThinking } = stripInlineThinking(reply);
5353
5439
  const validated = this.parseAndValidate(cleanReply, zodSchema);
@@ -5360,6 +5446,7 @@ ${schemaDescription}`;
5360
5446
  return [validated, thinkingContent, tokenUsage];
5361
5447
  } catch (error) {
5362
5448
  this.logger(this.logTemplates.error(this.name, error));
5449
+ if (error instanceof ModelError) throw error;
5363
5450
  throw new Error(this.errorMessages.apiError(error));
5364
5451
  }
5365
5452
  }
@@ -5397,11 +5484,11 @@ ${openAIMessages[0].content}`;
5397
5484
  }
5398
5485
  const reply = completion.choices[0]?.message?.content;
5399
5486
  if (!reply) {
5400
- throw new Error(this.errorMessages.emptyResponse);
5487
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5401
5488
  }
5402
5489
  const { text: cleanReply, thinking: inlineThinking } = stripInlineThinking(reply);
5403
5490
  if (!cleanReply) {
5404
- throw new Error(this.errorMessages.emptyResponse);
5491
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5405
5492
  }
5406
5493
  const { thinkingContent: reasoningContent, tokenUsage } = this.extractThinkingAndUsage(completion);
5407
5494
  const thinkingContent = mergeThinking(reasoningContent, inlineThinking);
@@ -5409,6 +5496,7 @@ ${openAIMessages[0].content}`;
5409
5496
  return [cleanReply, thinkingContent, tokenUsage];
5410
5497
  } catch (error) {
5411
5498
  this.logger(this.logTemplates.error(this.name, error));
5499
+ if (error instanceof ModelError) throw error;
5412
5500
  throw new Error(this.errorMessages.apiError(error));
5413
5501
  }
5414
5502
  }
@@ -5459,10 +5547,10 @@ ${schemaDescription}`;
5459
5547
  const response = await this.createResponse(input, zodSchema);
5460
5548
  const { text, reasoningSummary, encryptedReasoning } = this.extractResponseParts(response);
5461
5549
  if (!text) {
5462
- throw new Error(this.errorMessages.emptyResponse);
5550
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5463
5551
  }
5464
5552
  this.logger(`Meta Agent - Found reasoning summary: ${!!reasoningSummary}, encrypted reasoning: ${!!encryptedReasoning}`);
5465
- const parsedData = parseAndValidateLlmJson(text, zodSchema, (m) => this.logger(m));
5553
+ const parsedData = parseAndValidateLlmJson(text, zodSchema, (m) => this.logger(m), this.model);
5466
5554
  this.logger(`\u2705 Response validated successfully with Zod schema`);
5467
5555
  const tokenUsage = this.extractTokenUsage(response);
5468
5556
  if (parsedData) {
@@ -5471,6 +5559,7 @@ ${schemaDescription}`;
5471
5559
  return [parsedData, reasoningSummary, tokenUsage, encryptedReasoning];
5472
5560
  } catch (error) {
5473
5561
  this.logger(this.logTemplates.error(this.name, error));
5562
+ if (error instanceof ModelError) throw error;
5474
5563
  throw new Error(this.errorMessages.apiError(error));
5475
5564
  }
5476
5565
  }
@@ -5486,13 +5575,14 @@ ${schemaDescription}`;
5486
5575
  const response = await this.createResponse(input);
5487
5576
  const { text, reasoningSummary, encryptedReasoning } = this.extractResponseParts(response);
5488
5577
  if (!text) {
5489
- throw new Error(this.errorMessages.emptyResponse);
5578
+ throw new ModelInvalidResponseError(this.model, this.errorMessages.emptyResponse);
5490
5579
  }
5491
5580
  const tokenUsage = this.extractTokenUsage(response);
5492
5581
  this.logReply(text, reasoningSummary, tokenUsage);
5493
5582
  return [text, reasoningSummary, tokenUsage, encryptedReasoning];
5494
5583
  } catch (error) {
5495
5584
  this.logger(this.logTemplates.error(this.name, error));
5585
+ if (error instanceof ModelError) throw error;
5496
5586
  throw new Error(this.errorMessages.apiError(error));
5497
5587
  }
5498
5588
  }
@@ -5827,6 +5917,7 @@ var AgentFactory = class {
5827
5917
  safeValidateResponse,
5828
5918
  setBeforeAskHook,
5829
5919
  setLlmLogger,
5920
+ setRetryHook,
5830
5921
  stableHashHex,
5831
5922
  stripInlineThinking,
5832
5923
  supportsNativeJsonSchema,