@hiper2d/ai-agents 0.28.1 → 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/README.md CHANGED
@@ -139,6 +139,25 @@ import { setBeforeAskHook } from '@hiper2d/ai-agents';
139
139
  setBeforeAskHook(async agent => { if (agent.userId) await budget.assertWithinBudget(agent.userId); });
140
140
  ```
141
141
 
142
+ ### Retrying empty and malformed answers
143
+
144
+ A model sometimes answers with nothing, or with text that is not the JSON the schema asked
145
+ for. Both throw `ModelInvalidResponseError`, and the same prompt usually works on the next
146
+ try, so an agent can re-send it on its own: set `agent.invalidResponseRetries` (default 0).
147
+ Timeouts, refusals, transport errors and cap hits (`truncated`) are never retried. Each
148
+ re-send runs the before-ask hook again — it is a new paid call. To show the wait in a UI,
149
+ install a retry hook; whatever function it returns is awaited once the ask has settled:
150
+
151
+ ```ts
152
+ import { setRetryHook } from '@hiper2d/ai-agents';
153
+ setRetryHook(async ({ agent, model, error, attempt }) => {
154
+ await ui.show(agent.gameId, `${agent.name}: ${error.message}, asking again`);
155
+ return () => ui.hide(agent.gameId);
156
+ });
157
+ ```
158
+
159
+ The error finally thrown after the last allowed attempt carries `retries`.
160
+
142
161
  ### Logging
143
162
 
144
163
  The library logs through an injectable sink — `setLlmLogger(fn)` — so a host app can route
package/dist/index.d.mts CHANGED
@@ -243,7 +243,7 @@ declare function extractFirstJsonObject(text: string): unknown | null;
243
243
  * ("Failed to parse JSON response:", "Response validation failed:") so log
244
244
  * queries and error handling stay stable.
245
245
  */
246
- declare function parseAndValidateLlmJson<T>(rawReply: string, zodSchema: z.ZodSchema<T>, log?: (message: string) => void): T;
246
+ declare function parseAndValidateLlmJson<T>(rawReply: string, zodSchema: z.ZodSchema<T>, log?: (message: string) => void, model?: string): T;
247
247
 
248
248
  /**
249
249
  * Custom error classes for AI agent interactions
@@ -271,16 +271,22 @@ declare class ModelQuotaExceededError extends ModelError {
271
271
  constructor(message: string, modelType: string);
272
272
  }
273
273
  /**
274
- * The model failed to produce a valid response: the output was malformed (unparseable
275
- * JSON from a structured-output ask) or cut off at the output-token cap before the
276
- * answer was complete (`status: "incomplete"` on the OpenAI Responses API). Not a
277
- * transport or availability problem — the request worked, the generation went wrong.
278
- * A retry with the same prompt often succeeds; `truncated` distinguishes a cap hit
279
- * (raise maxOutputTokens if legitimate responses genuinely need more room) from a
280
- * degenerate/runaway generation (a bigger cap only makes failures slower).
274
+ * The model failed to produce a valid response: the completion was empty (no usable
275
+ * text at all — every agent's empty-content guard throws this), the output was malformed
276
+ * (unparseable JSON, or JSON that fails the schema, from a structured-output ask), or it
277
+ * was cut off at the output-token cap before the answer was complete (`status:
278
+ * "incomplete"` on the OpenAI Responses API). Not a transport or availability problem —
279
+ * the request worked, the generation went wrong. A retry with the same prompt often
280
+ * succeeds, which is what `AbstractAgent.invalidResponseRetries` automates; `truncated`
281
+ * distinguishes a cap hit (raise maxOutputTokens if legitimate responses genuinely need
282
+ * more room; never auto-retried, since re-running it re-buys the whole output) from a
283
+ * degenerate/runaway generation (a bigger cap only makes failures slower). `retries` is
284
+ * stamped by the agent on the error it finally throws: how many automatic re-sends
285
+ * preceded it (absent when none).
281
286
  */
282
287
  declare class ModelInvalidResponseError extends ModelError {
283
288
  truncated: boolean;
289
+ retries?: number;
284
290
  constructor(modelType: string, detail: string, truncated?: boolean);
285
291
  }
286
292
  /**
@@ -580,7 +586,9 @@ declare function getProviderSignatureFields(aiType: string, signature?: string):
580
586
  * alias for thinking_budget (low = 4,096, medium = 16,384, xhigh = 262,144 tokens) and the
581
587
  * two are mutually exclusive — sending both is a 400. QwenAgent sends the budget instead,
582
588
  * because 1,024 is tighter than the lowest level effort can express.
583
- * MiniMax exposes no effort parameter.
589
+ * - MiniMax M3.1 Flash (platform.minimax.io text-chat-openai reference, 2026-10-27):
590
+ * low|medium|high|xhigh|max, default max, top-level `reasoning_effort` on Chat Completions;
591
+ * "none" → 400. Only M3.1 Flash honours it — M3 and M2.x ignore the field.
584
592
  */
585
593
  type OpenAIReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';
586
594
  type AnthropicReasoningEffort = 'low' | 'medium' | 'high' | 'xhigh' | 'max';
@@ -592,6 +600,7 @@ type MetaReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'ma
592
600
  type MistralReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';
593
601
  type XaiReasoningEffort = 'low' | 'medium' | 'high' | 'xhigh';
594
602
  type KimiReasoningEffort = 'low' | 'high' | 'max';
603
+ type MiniMaxReasoningEffort = 'low' | 'medium' | 'high' | 'xhigh' | 'max';
595
604
  /** The shared scale, lowest first. */
596
605
  declare const REASONING_EFFORT_SCALE: readonly ReasoningEffort[];
597
606
  declare const OPENAI_REASONING_EFFORTS: readonly OpenAIReasoningEffort[];
@@ -604,6 +613,7 @@ declare const META_REASONING_EFFORTS: readonly MetaReasoningEffort[];
604
613
  declare const MISTRAL_REASONING_EFFORTS: readonly MistralReasoningEffort[];
605
614
  declare const XAI_REASONING_EFFORTS: readonly XaiReasoningEffort[];
606
615
  declare const KIMI_REASONING_EFFORTS: readonly KimiReasoningEffort[];
616
+ declare const MINIMAX_REASONING_EFFORTS: readonly MiniMaxReasoningEffort[];
607
617
  /** Clamps `effort` to the nearest level in `allowed` (by rank on the shared scale, ties go up). */
608
618
  declare function clampReasoningEffort<T extends ReasoningEffort>(effort: ReasoningEffort, allowed: readonly T[]): T;
609
619
  declare const toOpenAIEffort: (effort: ReasoningEffort) => OpenAIReasoningEffort;
@@ -616,6 +626,7 @@ declare const toFuguEffort: (effort: ReasoningEffort) => FuguReasoningEffort;
616
626
  declare const toMistralEffort: (effort: ReasoningEffort) => MistralReasoningEffort;
617
627
  declare const toXaiEffort: (effort: ReasoningEffort) => XaiReasoningEffort;
618
628
  declare const toKimiEffort: (effort: ReasoningEffort) => KimiReasoningEffort;
629
+ declare const toMiniMaxEffort: (effort: ReasoningEffort) => MiniMaxReasoningEffort;
619
630
 
620
631
  /**
621
632
  * Unified token usage utilities for all AI providers
@@ -1296,6 +1307,23 @@ declare class BudgetController {
1296
1307
  type BeforeAskHook = (agent: AbstractAgent) => void | Promise<void>;
1297
1308
  /** Install (or clear, with no argument) the process-wide pre-ask hook. Call once at startup. */
1298
1309
  declare function setBeforeAskHook(hook?: BeforeAskHook): void;
1310
+ /** Awaited once the ask a retry belonged to has settled (answered, or about to throw). */
1311
+ type RetrySettledFn = () => void | Promise<void>;
1312
+ /**
1313
+ * Runs right before an ask is re-sent after an empty or malformed response (see
1314
+ * `AbstractAgent.invalidResponseRetries`); `attempt` counts retries from 1. The intended
1315
+ * use is a UI notice ("the model returned nothing, asking again"): return a function and it
1316
+ * is awaited when the whole ask settles, so the notice can be taken down again. A throwing
1317
+ * hook is logged and ignored — it never stops the retry. Async hooks are awaited.
1318
+ */
1319
+ type RetryHook = (info: {
1320
+ agent: AbstractAgent;
1321
+ model: string;
1322
+ error: ModelInvalidResponseError;
1323
+ attempt: number;
1324
+ }) => void | RetrySettledFn | Promise<void | RetrySettledFn>;
1325
+ /** Install (or clear, with no argument) the process-wide retry hook. Call once at startup. */
1326
+ declare function setRetryHook(hook?: RetryHook): void;
1299
1327
  declare abstract class AbstractAgent {
1300
1328
  name: string;
1301
1329
  gameId?: string;
@@ -1322,6 +1350,17 @@ declare abstract class AbstractAgent {
1322
1350
  * instance for calls that legitimately run long, like maxOutputTokens.
1323
1351
  */
1324
1352
  requestTimeoutMs: number;
1353
+ /**
1354
+ * How many times one ask is re-sent after a ModelInvalidResponseError that is not a
1355
+ * cap hit: the model answered with nothing, or with text that is not the JSON the
1356
+ * schema asked for. Those are one-off generation failures the same prompt usually
1357
+ * gets right on the next try, unlike timeouts, refusals and transport errors, which
1358
+ * are never retried here. 0 (the default) hands every failure to the caller. A
1359
+ * truncated response is excluded because re-running it re-buys the whole output at
1360
+ * the cap. Each re-send runs the before-ask hook again (it is a new paid call) and
1361
+ * fires the retry hook; the error finally thrown carries `retries`.
1362
+ */
1363
+ invalidResponseRetries: number;
1325
1364
  protected readonly instruction: string;
1326
1365
  /**
1327
1366
  * The instruction split on CACHE_TIER_MARKER: [shared static tier, per-bot tier].
@@ -1336,12 +1375,22 @@ declare abstract class AbstractAgent {
1336
1375
  protected readonly agentLoggingConfig: AgentLoggingConfig;
1337
1376
  protected constructor(name: string, instruction: string, model: string, temperature: number, enableThinking?: boolean, agentLoggingConfig?: AgentLoggingConfig);
1338
1377
  /**
1339
- * Public ask API — template methods that time the provider call and stamp `durationMs`
1340
- * into the returned TokenUsage. Subclasses implement doAskWithZodSchema/doAskText and
1378
+ * Public ask API — template methods that run the before-ask hook, time the provider
1379
+ * call, stamp `durationMs` into the returned TokenUsage and apply the
1380
+ * invalidResponseRetries policy. Subclasses implement doAskWithZodSchema/doAskText and
1341
1381
  * must NOT override these.
1342
1382
  */
1343
1383
  askWithZodSchema<T>(zodSchema: z.ZodSchema<T>, messages: AIMessage[]): Promise<[T, string, TokenUsage$1?, string?]>;
1344
1384
  askText(messages: AIMessage[]): Promise<[string, string, TokenUsage$1?, string?]>;
1385
+ /**
1386
+ * One attempt per loop; an empty or malformed answer (ModelInvalidResponseError, not
1387
+ * truncated) is re-sent up to invalidResponseRetries times, with the retry hook told
1388
+ * before each re-send. Anything else — a timeout, a refusal, a transport error, or the
1389
+ * last allowed attempt failing — is thrown as-is, stamped with the retry count. Every
1390
+ * settle function the hook returned runs once the ask is over, whichever way it ended.
1391
+ */
1392
+ private askWithRetries;
1393
+ private attempt;
1345
1394
  /**
1346
1395
  * Races the provider call against requestTimeoutMs. A hung provider (accepts the request,
1347
1396
  * never answers) otherwise runs until the host kills the function with no error to show.
@@ -1858,4 +1907,4 @@ declare class MiniMaxAgent extends AbstractAgent {
1858
1907
  doAskText(messages: AIMessage[]): Promise<[string, string, TokenUsage$1?, string?]>;
1859
1908
  }
1860
1909
 
1861
- export { type AIMessage, ANTHROPIC_REASONING_EFFORTS, API_KEY_CONSTANTS, AbstractAgent, type AgentActivityData, AgentFactory, type AgentLoggingConfig, type AnthropicReasoningEffort, type AnthropicTokenUsage, type ApiKeyMap, type BeforeAskHook, BotResponseError, BudgetController, type BudgetControllerOptions, BudgetExceededError, type BudgetLimit, type BudgetVerdict, CACHE_TIER_MARKER, ClaudeAgent, type CostCalculationOptions, DEEPSEEK_PEAK_SCHEDULE, DEEPSEEK_REASONING_EFFORTS, DEFAULT_LOGGING_CONFIG, DEFAULT_MAX_OUTPUT_TOKENS, DEFAULT_REQUEST_TIMEOUT_MS, type DeepSeekReasoningEffort, type DeepSeekTokenUsage, DeepSeekV2Agent, FUGU_REASONING_EFFORTS, FuguAgent, type FuguReasoningEffort, GEMINI_AUDIO_TOKENS_PER_SECOND, GEMINI_REASONING_EFFORTS, GLM_REASONING_EFFORTS, type GeminiReasoningEffort, GlmAgent, type GlmReasoningEffort, GoogleAgent, type GoogleSttOptions, type GoogleSttResult, type GoogleTokenUsage, type GoogleTtsAudioOptions, type GoogleTtsResult, GoogleVoiceAgent, Gpt5Agent, GrokAgent, type GrokTokenUsage, InMemorySpendStore, type JsonSchemaOptions, KIMI_REASONING_EFFORTS, KimiAgent, type KimiReasoningEffort, type KimiTokenUsage, type LLMModel, LLM_CONSTANTS, type LlmLogger, type LoggingConfig, MESSAGE_ROLE, META_REASONING_EFFORTS, MISTRAL_REASONING_EFFORTS, MODEL_PRICING, MetaAgent, type MetaReasoningEffort, type MetaTokenUsage, MiniMaxAgent, MistralAgent, type MistralReasoningEffort, type MistralTokenUsage, type Modality, ModelAuthenticationError, type ModelConfig, ModelError, ModelInvalidResponseError, ModelOverloadError, type ModelPricing, ModelQuotaExceededError, ModelRateLimitError, ModelRefusalError, type ModelTag, ModelTimeoutError, ModelUnavailableError, OPENAI_REASONING_EFFORTS, type OpenAIReasoningEffort, type OpenAITokenUsage, type OpenAiSttOptions, type OpenAiSttResult, type OpenAiTtsAudioOptions, type OpenAiTtsVoice, OpenAiVoiceAgent, type PeakPricing, type PricingUnit, type ProviderSchema, type TokenUsage as ProviderTokenUsage, type ProviderType, QwenAgent, REASONING_EFFORT_SCALE, type ReasoningEffort, SUPPORTED_VOICE_PROVIDERS, type SpeechRequest, type SpeechResult, type SpeechUsage, type SpendInput, type SpendKind, type SpendLedger, type SpendLedgers, type SpendStore, type SpendWindow, SupportedAiKeyNames, SupportedAiModels, type TokenPairUsage, type TokenUsage$1 as TokenUsage, type TranscriptionRequest, type TranscriptionResult, type TranscriptionUsage, VOICE_MODEL_CONSTANTS, VOICE_MODEL_PRICING, VOICE_PROVIDER_API_KEY, type VoiceAgent, VoiceAgentFactory, type VoiceModelPricing, type VoiceProvider, XAI_REASONING_EFFORTS, type XaiReasoningEffort, ZodSchemaConverter, applySpend, calculateAnthropicCost, calculateCost, calculateDeepSeekCost, calculateGeminiSttCost, calculateGeminiTtsCost, calculateGoogleCost, calculateGrokCost, calculateKimiCost, calculateMetaCost, calculateMistralCost, calculateModelCost, calculateOpenAICost, calculateOpenAiSttCost, calculateOpenAiTtsCost, clampReasoningEffort, cleanResponse, createCatalog, createVoiceAgent, describeEmptyTtsResponse, evaluateBudget, extractAnthropicTokenUsage, extractTokenUsageFromResponse$2 as extractAnthropicTokenUsageFromResponse, extractDeepSeekTokenUsage, extractTokenUsageFromResponse$6 as extractDeepSeekTokenUsageFromResponse, extractFirstJsonObject, extractGoogleTokenUsage, extractTokenUsageFromResponse$1 as extractGoogleTokenUsageFromResponse, extractGrokTokenUsage, extractTokenUsageFromResponse$4 as extractGrokTokenUsageFromResponse, extractKimiTokenUsage, extractTokenUsageFromResponse$5 as extractKimiTokenUsageFromResponse, extractMetaTokenUsage, extractTokenUsageFromResponse$3 as extractMetaTokenUsageFromResponse, extractMistralTokenUsage, extractTokenUsageFromResponse as extractMistralTokenUsageFromResponse, extractOpenAITokenUsage, extractTokenUsageFromResponse$7 as extractOpenAITokenUsageFromResponse, extractTokenUsage, extractUsageAndCalculateCost, firstRefusal, generateGoogleTtsAudio, generateOpenAiTtsAudio, generateSchemaInstructions, getModelConfigByApiName, getModelDisplayName, getModelProviderName, getModelTags, getProviderSignatureFields, isBudgetExceededError, isHybridThinkingModel, isInPeakWindow, isPeakBilling, isSafetyBlocked, isWeekendAt, ledgerSpend, logger, mergeThinking, modelHasTag, modelIsFast, needsPromptBasedSchema, normalizeTtsStyle, parseAndValidateLlmJson, pcmToWav, periodEnd, periodKey, safeValidateResponse, setBeforeAskHook, setLlmLogger, stableHashHex, stripInlineThinking, supportsNativeJsonSchema, toAnthropicEffort, toDeepSeekEffort, toFuguEffort, toGeminiEffort, toGlmEffort, toKimiEffort, toMetaEffort, toMistralEffort, toOpenAIEffort, toXaiEffort, transcribeWithGemini, transcribeWithOpenAi, validateResponse };
1910
+ export { type AIMessage, ANTHROPIC_REASONING_EFFORTS, API_KEY_CONSTANTS, AbstractAgent, type AgentActivityData, AgentFactory, type AgentLoggingConfig, type AnthropicReasoningEffort, type AnthropicTokenUsage, type ApiKeyMap, type BeforeAskHook, BotResponseError, BudgetController, type BudgetControllerOptions, BudgetExceededError, type BudgetLimit, type BudgetVerdict, CACHE_TIER_MARKER, ClaudeAgent, type CostCalculationOptions, DEEPSEEK_PEAK_SCHEDULE, DEEPSEEK_REASONING_EFFORTS, DEFAULT_LOGGING_CONFIG, DEFAULT_MAX_OUTPUT_TOKENS, DEFAULT_REQUEST_TIMEOUT_MS, type DeepSeekReasoningEffort, type DeepSeekTokenUsage, DeepSeekV2Agent, FUGU_REASONING_EFFORTS, FuguAgent, type FuguReasoningEffort, GEMINI_AUDIO_TOKENS_PER_SECOND, GEMINI_REASONING_EFFORTS, GLM_REASONING_EFFORTS, type GeminiReasoningEffort, GlmAgent, type GlmReasoningEffort, GoogleAgent, type GoogleSttOptions, type GoogleSttResult, type GoogleTokenUsage, type GoogleTtsAudioOptions, type GoogleTtsResult, GoogleVoiceAgent, Gpt5Agent, GrokAgent, type GrokTokenUsage, InMemorySpendStore, type JsonSchemaOptions, KIMI_REASONING_EFFORTS, KimiAgent, type KimiReasoningEffort, type KimiTokenUsage, type LLMModel, LLM_CONSTANTS, type LlmLogger, type LoggingConfig, MESSAGE_ROLE, META_REASONING_EFFORTS, MINIMAX_REASONING_EFFORTS, MISTRAL_REASONING_EFFORTS, MODEL_PRICING, MetaAgent, type MetaReasoningEffort, type MetaTokenUsage, MiniMaxAgent, type MiniMaxReasoningEffort, MistralAgent, type MistralReasoningEffort, type MistralTokenUsage, type Modality, ModelAuthenticationError, type ModelConfig, ModelError, ModelInvalidResponseError, ModelOverloadError, type ModelPricing, ModelQuotaExceededError, ModelRateLimitError, ModelRefusalError, type ModelTag, ModelTimeoutError, ModelUnavailableError, OPENAI_REASONING_EFFORTS, type OpenAIReasoningEffort, type OpenAITokenUsage, type OpenAiSttOptions, type OpenAiSttResult, type OpenAiTtsAudioOptions, type OpenAiTtsVoice, OpenAiVoiceAgent, type PeakPricing, type PricingUnit, type ProviderSchema, type TokenUsage as ProviderTokenUsage, type ProviderType, QwenAgent, REASONING_EFFORT_SCALE, type ReasoningEffort, type RetryHook, type RetrySettledFn, SUPPORTED_VOICE_PROVIDERS, type SpeechRequest, type SpeechResult, type SpeechUsage, type SpendInput, type SpendKind, type SpendLedger, type SpendLedgers, type SpendStore, type SpendWindow, SupportedAiKeyNames, SupportedAiModels, type TokenPairUsage, type TokenUsage$1 as TokenUsage, type TranscriptionRequest, type TranscriptionResult, type TranscriptionUsage, VOICE_MODEL_CONSTANTS, VOICE_MODEL_PRICING, VOICE_PROVIDER_API_KEY, type VoiceAgent, VoiceAgentFactory, type VoiceModelPricing, type VoiceProvider, XAI_REASONING_EFFORTS, type XaiReasoningEffort, ZodSchemaConverter, applySpend, calculateAnthropicCost, calculateCost, calculateDeepSeekCost, calculateGeminiSttCost, calculateGeminiTtsCost, calculateGoogleCost, calculateGrokCost, calculateKimiCost, calculateMetaCost, calculateMistralCost, calculateModelCost, calculateOpenAICost, calculateOpenAiSttCost, calculateOpenAiTtsCost, clampReasoningEffort, cleanResponse, createCatalog, createVoiceAgent, describeEmptyTtsResponse, evaluateBudget, extractAnthropicTokenUsage, extractTokenUsageFromResponse$2 as extractAnthropicTokenUsageFromResponse, extractDeepSeekTokenUsage, extractTokenUsageFromResponse$6 as extractDeepSeekTokenUsageFromResponse, extractFirstJsonObject, extractGoogleTokenUsage, extractTokenUsageFromResponse$1 as extractGoogleTokenUsageFromResponse, extractGrokTokenUsage, extractTokenUsageFromResponse$4 as extractGrokTokenUsageFromResponse, extractKimiTokenUsage, extractTokenUsageFromResponse$5 as extractKimiTokenUsageFromResponse, extractMetaTokenUsage, extractTokenUsageFromResponse$3 as extractMetaTokenUsageFromResponse, extractMistralTokenUsage, extractTokenUsageFromResponse as extractMistralTokenUsageFromResponse, extractOpenAITokenUsage, extractTokenUsageFromResponse$7 as extractOpenAITokenUsageFromResponse, extractTokenUsage, extractUsageAndCalculateCost, firstRefusal, generateGoogleTtsAudio, generateOpenAiTtsAudio, generateSchemaInstructions, getModelConfigByApiName, getModelDisplayName, getModelProviderName, getModelTags, getProviderSignatureFields, isBudgetExceededError, isHybridThinkingModel, isInPeakWindow, isPeakBilling, isSafetyBlocked, isWeekendAt, ledgerSpend, logger, mergeThinking, modelHasTag, modelIsFast, needsPromptBasedSchema, normalizeTtsStyle, parseAndValidateLlmJson, pcmToWav, periodEnd, periodKey, safeValidateResponse, setBeforeAskHook, setLlmLogger, setRetryHook, stableHashHex, stripInlineThinking, supportsNativeJsonSchema, toAnthropicEffort, toDeepSeekEffort, toFuguEffort, toGeminiEffort, toGlmEffort, toKimiEffort, toMetaEffort, toMiniMaxEffort, toMistralEffort, toOpenAIEffort, toXaiEffort, transcribeWithGemini, transcribeWithOpenAi, validateResponse };
package/dist/index.d.ts CHANGED
@@ -243,7 +243,7 @@ declare function extractFirstJsonObject(text: string): unknown | null;
243
243
  * ("Failed to parse JSON response:", "Response validation failed:") so log
244
244
  * queries and error handling stay stable.
245
245
  */
246
- declare function parseAndValidateLlmJson<T>(rawReply: string, zodSchema: z.ZodSchema<T>, log?: (message: string) => void): T;
246
+ declare function parseAndValidateLlmJson<T>(rawReply: string, zodSchema: z.ZodSchema<T>, log?: (message: string) => void, model?: string): T;
247
247
 
248
248
  /**
249
249
  * Custom error classes for AI agent interactions
@@ -271,16 +271,22 @@ declare class ModelQuotaExceededError extends ModelError {
271
271
  constructor(message: string, modelType: string);
272
272
  }
273
273
  /**
274
- * The model failed to produce a valid response: the output was malformed (unparseable
275
- * JSON from a structured-output ask) or cut off at the output-token cap before the
276
- * answer was complete (`status: "incomplete"` on the OpenAI Responses API). Not a
277
- * transport or availability problem — the request worked, the generation went wrong.
278
- * A retry with the same prompt often succeeds; `truncated` distinguishes a cap hit
279
- * (raise maxOutputTokens if legitimate responses genuinely need more room) from a
280
- * degenerate/runaway generation (a bigger cap only makes failures slower).
274
+ * The model failed to produce a valid response: the completion was empty (no usable
275
+ * text at all — every agent's empty-content guard throws this), the output was malformed
276
+ * (unparseable JSON, or JSON that fails the schema, from a structured-output ask), or it
277
+ * was cut off at the output-token cap before the answer was complete (`status:
278
+ * "incomplete"` on the OpenAI Responses API). Not a transport or availability problem —
279
+ * the request worked, the generation went wrong. A retry with the same prompt often
280
+ * succeeds, which is what `AbstractAgent.invalidResponseRetries` automates; `truncated`
281
+ * distinguishes a cap hit (raise maxOutputTokens if legitimate responses genuinely need
282
+ * more room; never auto-retried, since re-running it re-buys the whole output) from a
283
+ * degenerate/runaway generation (a bigger cap only makes failures slower). `retries` is
284
+ * stamped by the agent on the error it finally throws: how many automatic re-sends
285
+ * preceded it (absent when none).
281
286
  */
282
287
  declare class ModelInvalidResponseError extends ModelError {
283
288
  truncated: boolean;
289
+ retries?: number;
284
290
  constructor(modelType: string, detail: string, truncated?: boolean);
285
291
  }
286
292
  /**
@@ -580,7 +586,9 @@ declare function getProviderSignatureFields(aiType: string, signature?: string):
580
586
  * alias for thinking_budget (low = 4,096, medium = 16,384, xhigh = 262,144 tokens) and the
581
587
  * two are mutually exclusive — sending both is a 400. QwenAgent sends the budget instead,
582
588
  * because 1,024 is tighter than the lowest level effort can express.
583
- * MiniMax exposes no effort parameter.
589
+ * - MiniMax M3.1 Flash (platform.minimax.io text-chat-openai reference, 2026-10-27):
590
+ * low|medium|high|xhigh|max, default max, top-level `reasoning_effort` on Chat Completions;
591
+ * "none" → 400. Only M3.1 Flash honours it — M3 and M2.x ignore the field.
584
592
  */
585
593
  type OpenAIReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';
586
594
  type AnthropicReasoningEffort = 'low' | 'medium' | 'high' | 'xhigh' | 'max';
@@ -592,6 +600,7 @@ type MetaReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'ma
592
600
  type MistralReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';
593
601
  type XaiReasoningEffort = 'low' | 'medium' | 'high' | 'xhigh';
594
602
  type KimiReasoningEffort = 'low' | 'high' | 'max';
603
+ type MiniMaxReasoningEffort = 'low' | 'medium' | 'high' | 'xhigh' | 'max';
595
604
  /** The shared scale, lowest first. */
596
605
  declare const REASONING_EFFORT_SCALE: readonly ReasoningEffort[];
597
606
  declare const OPENAI_REASONING_EFFORTS: readonly OpenAIReasoningEffort[];
@@ -604,6 +613,7 @@ declare const META_REASONING_EFFORTS: readonly MetaReasoningEffort[];
604
613
  declare const MISTRAL_REASONING_EFFORTS: readonly MistralReasoningEffort[];
605
614
  declare const XAI_REASONING_EFFORTS: readonly XaiReasoningEffort[];
606
615
  declare const KIMI_REASONING_EFFORTS: readonly KimiReasoningEffort[];
616
+ declare const MINIMAX_REASONING_EFFORTS: readonly MiniMaxReasoningEffort[];
607
617
  /** Clamps `effort` to the nearest level in `allowed` (by rank on the shared scale, ties go up). */
608
618
  declare function clampReasoningEffort<T extends ReasoningEffort>(effort: ReasoningEffort, allowed: readonly T[]): T;
609
619
  declare const toOpenAIEffort: (effort: ReasoningEffort) => OpenAIReasoningEffort;
@@ -616,6 +626,7 @@ declare const toFuguEffort: (effort: ReasoningEffort) => FuguReasoningEffort;
616
626
  declare const toMistralEffort: (effort: ReasoningEffort) => MistralReasoningEffort;
617
627
  declare const toXaiEffort: (effort: ReasoningEffort) => XaiReasoningEffort;
618
628
  declare const toKimiEffort: (effort: ReasoningEffort) => KimiReasoningEffort;
629
+ declare const toMiniMaxEffort: (effort: ReasoningEffort) => MiniMaxReasoningEffort;
619
630
 
620
631
  /**
621
632
  * Unified token usage utilities for all AI providers
@@ -1296,6 +1307,23 @@ declare class BudgetController {
1296
1307
  type BeforeAskHook = (agent: AbstractAgent) => void | Promise<void>;
1297
1308
  /** Install (or clear, with no argument) the process-wide pre-ask hook. Call once at startup. */
1298
1309
  declare function setBeforeAskHook(hook?: BeforeAskHook): void;
1310
+ /** Awaited once the ask a retry belonged to has settled (answered, or about to throw). */
1311
+ type RetrySettledFn = () => void | Promise<void>;
1312
+ /**
1313
+ * Runs right before an ask is re-sent after an empty or malformed response (see
1314
+ * `AbstractAgent.invalidResponseRetries`); `attempt` counts retries from 1. The intended
1315
+ * use is a UI notice ("the model returned nothing, asking again"): return a function and it
1316
+ * is awaited when the whole ask settles, so the notice can be taken down again. A throwing
1317
+ * hook is logged and ignored — it never stops the retry. Async hooks are awaited.
1318
+ */
1319
+ type RetryHook = (info: {
1320
+ agent: AbstractAgent;
1321
+ model: string;
1322
+ error: ModelInvalidResponseError;
1323
+ attempt: number;
1324
+ }) => void | RetrySettledFn | Promise<void | RetrySettledFn>;
1325
+ /** Install (or clear, with no argument) the process-wide retry hook. Call once at startup. */
1326
+ declare function setRetryHook(hook?: RetryHook): void;
1299
1327
  declare abstract class AbstractAgent {
1300
1328
  name: string;
1301
1329
  gameId?: string;
@@ -1322,6 +1350,17 @@ declare abstract class AbstractAgent {
1322
1350
  * instance for calls that legitimately run long, like maxOutputTokens.
1323
1351
  */
1324
1352
  requestTimeoutMs: number;
1353
+ /**
1354
+ * How many times one ask is re-sent after a ModelInvalidResponseError that is not a
1355
+ * cap hit: the model answered with nothing, or with text that is not the JSON the
1356
+ * schema asked for. Those are one-off generation failures the same prompt usually
1357
+ * gets right on the next try, unlike timeouts, refusals and transport errors, which
1358
+ * are never retried here. 0 (the default) hands every failure to the caller. A
1359
+ * truncated response is excluded because re-running it re-buys the whole output at
1360
+ * the cap. Each re-send runs the before-ask hook again (it is a new paid call) and
1361
+ * fires the retry hook; the error finally thrown carries `retries`.
1362
+ */
1363
+ invalidResponseRetries: number;
1325
1364
  protected readonly instruction: string;
1326
1365
  /**
1327
1366
  * The instruction split on CACHE_TIER_MARKER: [shared static tier, per-bot tier].
@@ -1336,12 +1375,22 @@ declare abstract class AbstractAgent {
1336
1375
  protected readonly agentLoggingConfig: AgentLoggingConfig;
1337
1376
  protected constructor(name: string, instruction: string, model: string, temperature: number, enableThinking?: boolean, agentLoggingConfig?: AgentLoggingConfig);
1338
1377
  /**
1339
- * Public ask API — template methods that time the provider call and stamp `durationMs`
1340
- * into the returned TokenUsage. Subclasses implement doAskWithZodSchema/doAskText and
1378
+ * Public ask API — template methods that run the before-ask hook, time the provider
1379
+ * call, stamp `durationMs` into the returned TokenUsage and apply the
1380
+ * invalidResponseRetries policy. Subclasses implement doAskWithZodSchema/doAskText and
1341
1381
  * must NOT override these.
1342
1382
  */
1343
1383
  askWithZodSchema<T>(zodSchema: z.ZodSchema<T>, messages: AIMessage[]): Promise<[T, string, TokenUsage$1?, string?]>;
1344
1384
  askText(messages: AIMessage[]): Promise<[string, string, TokenUsage$1?, string?]>;
1385
+ /**
1386
+ * One attempt per loop; an empty or malformed answer (ModelInvalidResponseError, not
1387
+ * truncated) is re-sent up to invalidResponseRetries times, with the retry hook told
1388
+ * before each re-send. Anything else — a timeout, a refusal, a transport error, or the
1389
+ * last allowed attempt failing — is thrown as-is, stamped with the retry count. Every
1390
+ * settle function the hook returned runs once the ask is over, whichever way it ended.
1391
+ */
1392
+ private askWithRetries;
1393
+ private attempt;
1345
1394
  /**
1346
1395
  * Races the provider call against requestTimeoutMs. A hung provider (accepts the request,
1347
1396
  * never answers) otherwise runs until the host kills the function with no error to show.
@@ -1858,4 +1907,4 @@ declare class MiniMaxAgent extends AbstractAgent {
1858
1907
  doAskText(messages: AIMessage[]): Promise<[string, string, TokenUsage$1?, string?]>;
1859
1908
  }
1860
1909
 
1861
- export { type AIMessage, ANTHROPIC_REASONING_EFFORTS, API_KEY_CONSTANTS, AbstractAgent, type AgentActivityData, AgentFactory, type AgentLoggingConfig, type AnthropicReasoningEffort, type AnthropicTokenUsage, type ApiKeyMap, type BeforeAskHook, BotResponseError, BudgetController, type BudgetControllerOptions, BudgetExceededError, type BudgetLimit, type BudgetVerdict, CACHE_TIER_MARKER, ClaudeAgent, type CostCalculationOptions, DEEPSEEK_PEAK_SCHEDULE, DEEPSEEK_REASONING_EFFORTS, DEFAULT_LOGGING_CONFIG, DEFAULT_MAX_OUTPUT_TOKENS, DEFAULT_REQUEST_TIMEOUT_MS, type DeepSeekReasoningEffort, type DeepSeekTokenUsage, DeepSeekV2Agent, FUGU_REASONING_EFFORTS, FuguAgent, type FuguReasoningEffort, GEMINI_AUDIO_TOKENS_PER_SECOND, GEMINI_REASONING_EFFORTS, GLM_REASONING_EFFORTS, type GeminiReasoningEffort, GlmAgent, type GlmReasoningEffort, GoogleAgent, type GoogleSttOptions, type GoogleSttResult, type GoogleTokenUsage, type GoogleTtsAudioOptions, type GoogleTtsResult, GoogleVoiceAgent, Gpt5Agent, GrokAgent, type GrokTokenUsage, InMemorySpendStore, type JsonSchemaOptions, KIMI_REASONING_EFFORTS, KimiAgent, type KimiReasoningEffort, type KimiTokenUsage, type LLMModel, LLM_CONSTANTS, type LlmLogger, type LoggingConfig, MESSAGE_ROLE, META_REASONING_EFFORTS, MISTRAL_REASONING_EFFORTS, MODEL_PRICING, MetaAgent, type MetaReasoningEffort, type MetaTokenUsage, MiniMaxAgent, MistralAgent, type MistralReasoningEffort, type MistralTokenUsage, type Modality, ModelAuthenticationError, type ModelConfig, ModelError, ModelInvalidResponseError, ModelOverloadError, type ModelPricing, ModelQuotaExceededError, ModelRateLimitError, ModelRefusalError, type ModelTag, ModelTimeoutError, ModelUnavailableError, OPENAI_REASONING_EFFORTS, type OpenAIReasoningEffort, type OpenAITokenUsage, type OpenAiSttOptions, type OpenAiSttResult, type OpenAiTtsAudioOptions, type OpenAiTtsVoice, OpenAiVoiceAgent, type PeakPricing, type PricingUnit, type ProviderSchema, type TokenUsage as ProviderTokenUsage, type ProviderType, QwenAgent, REASONING_EFFORT_SCALE, type ReasoningEffort, SUPPORTED_VOICE_PROVIDERS, type SpeechRequest, type SpeechResult, type SpeechUsage, type SpendInput, type SpendKind, type SpendLedger, type SpendLedgers, type SpendStore, type SpendWindow, SupportedAiKeyNames, SupportedAiModels, type TokenPairUsage, type TokenUsage$1 as TokenUsage, type TranscriptionRequest, type TranscriptionResult, type TranscriptionUsage, VOICE_MODEL_CONSTANTS, VOICE_MODEL_PRICING, VOICE_PROVIDER_API_KEY, type VoiceAgent, VoiceAgentFactory, type VoiceModelPricing, type VoiceProvider, XAI_REASONING_EFFORTS, type XaiReasoningEffort, ZodSchemaConverter, applySpend, calculateAnthropicCost, calculateCost, calculateDeepSeekCost, calculateGeminiSttCost, calculateGeminiTtsCost, calculateGoogleCost, calculateGrokCost, calculateKimiCost, calculateMetaCost, calculateMistralCost, calculateModelCost, calculateOpenAICost, calculateOpenAiSttCost, calculateOpenAiTtsCost, clampReasoningEffort, cleanResponse, createCatalog, createVoiceAgent, describeEmptyTtsResponse, evaluateBudget, extractAnthropicTokenUsage, extractTokenUsageFromResponse$2 as extractAnthropicTokenUsageFromResponse, extractDeepSeekTokenUsage, extractTokenUsageFromResponse$6 as extractDeepSeekTokenUsageFromResponse, extractFirstJsonObject, extractGoogleTokenUsage, extractTokenUsageFromResponse$1 as extractGoogleTokenUsageFromResponse, extractGrokTokenUsage, extractTokenUsageFromResponse$4 as extractGrokTokenUsageFromResponse, extractKimiTokenUsage, extractTokenUsageFromResponse$5 as extractKimiTokenUsageFromResponse, extractMetaTokenUsage, extractTokenUsageFromResponse$3 as extractMetaTokenUsageFromResponse, extractMistralTokenUsage, extractTokenUsageFromResponse as extractMistralTokenUsageFromResponse, extractOpenAITokenUsage, extractTokenUsageFromResponse$7 as extractOpenAITokenUsageFromResponse, extractTokenUsage, extractUsageAndCalculateCost, firstRefusal, generateGoogleTtsAudio, generateOpenAiTtsAudio, generateSchemaInstructions, getModelConfigByApiName, getModelDisplayName, getModelProviderName, getModelTags, getProviderSignatureFields, isBudgetExceededError, isHybridThinkingModel, isInPeakWindow, isPeakBilling, isSafetyBlocked, isWeekendAt, ledgerSpend, logger, mergeThinking, modelHasTag, modelIsFast, needsPromptBasedSchema, normalizeTtsStyle, parseAndValidateLlmJson, pcmToWav, periodEnd, periodKey, safeValidateResponse, setBeforeAskHook, setLlmLogger, stableHashHex, stripInlineThinking, supportsNativeJsonSchema, toAnthropicEffort, toDeepSeekEffort, toFuguEffort, toGeminiEffort, toGlmEffort, toKimiEffort, toMetaEffort, toMistralEffort, toOpenAIEffort, toXaiEffort, transcribeWithGemini, transcribeWithOpenAi, validateResponse };
1910
+ export { type AIMessage, ANTHROPIC_REASONING_EFFORTS, API_KEY_CONSTANTS, AbstractAgent, type AgentActivityData, AgentFactory, type AgentLoggingConfig, type AnthropicReasoningEffort, type AnthropicTokenUsage, type ApiKeyMap, type BeforeAskHook, BotResponseError, BudgetController, type BudgetControllerOptions, BudgetExceededError, type BudgetLimit, type BudgetVerdict, CACHE_TIER_MARKER, ClaudeAgent, type CostCalculationOptions, DEEPSEEK_PEAK_SCHEDULE, DEEPSEEK_REASONING_EFFORTS, DEFAULT_LOGGING_CONFIG, DEFAULT_MAX_OUTPUT_TOKENS, DEFAULT_REQUEST_TIMEOUT_MS, type DeepSeekReasoningEffort, type DeepSeekTokenUsage, DeepSeekV2Agent, FUGU_REASONING_EFFORTS, FuguAgent, type FuguReasoningEffort, GEMINI_AUDIO_TOKENS_PER_SECOND, GEMINI_REASONING_EFFORTS, GLM_REASONING_EFFORTS, type GeminiReasoningEffort, GlmAgent, type GlmReasoningEffort, GoogleAgent, type GoogleSttOptions, type GoogleSttResult, type GoogleTokenUsage, type GoogleTtsAudioOptions, type GoogleTtsResult, GoogleVoiceAgent, Gpt5Agent, GrokAgent, type GrokTokenUsage, InMemorySpendStore, type JsonSchemaOptions, KIMI_REASONING_EFFORTS, KimiAgent, type KimiReasoningEffort, type KimiTokenUsage, type LLMModel, LLM_CONSTANTS, type LlmLogger, type LoggingConfig, MESSAGE_ROLE, META_REASONING_EFFORTS, MINIMAX_REASONING_EFFORTS, MISTRAL_REASONING_EFFORTS, MODEL_PRICING, MetaAgent, type MetaReasoningEffort, type MetaTokenUsage, MiniMaxAgent, type MiniMaxReasoningEffort, MistralAgent, type MistralReasoningEffort, type MistralTokenUsage, type Modality, ModelAuthenticationError, type ModelConfig, ModelError, ModelInvalidResponseError, ModelOverloadError, type ModelPricing, ModelQuotaExceededError, ModelRateLimitError, ModelRefusalError, type ModelTag, ModelTimeoutError, ModelUnavailableError, OPENAI_REASONING_EFFORTS, type OpenAIReasoningEffort, type OpenAITokenUsage, type OpenAiSttOptions, type OpenAiSttResult, type OpenAiTtsAudioOptions, type OpenAiTtsVoice, OpenAiVoiceAgent, type PeakPricing, type PricingUnit, type ProviderSchema, type TokenUsage as ProviderTokenUsage, type ProviderType, QwenAgent, REASONING_EFFORT_SCALE, type ReasoningEffort, type RetryHook, type RetrySettledFn, SUPPORTED_VOICE_PROVIDERS, type SpeechRequest, type SpeechResult, type SpeechUsage, type SpendInput, type SpendKind, type SpendLedger, type SpendLedgers, type SpendStore, type SpendWindow, SupportedAiKeyNames, SupportedAiModels, type TokenPairUsage, type TokenUsage$1 as TokenUsage, type TranscriptionRequest, type TranscriptionResult, type TranscriptionUsage, VOICE_MODEL_CONSTANTS, VOICE_MODEL_PRICING, VOICE_PROVIDER_API_KEY, type VoiceAgent, VoiceAgentFactory, type VoiceModelPricing, type VoiceProvider, XAI_REASONING_EFFORTS, type XaiReasoningEffort, ZodSchemaConverter, applySpend, calculateAnthropicCost, calculateCost, calculateDeepSeekCost, calculateGeminiSttCost, calculateGeminiTtsCost, calculateGoogleCost, calculateGrokCost, calculateKimiCost, calculateMetaCost, calculateMistralCost, calculateModelCost, calculateOpenAICost, calculateOpenAiSttCost, calculateOpenAiTtsCost, clampReasoningEffort, cleanResponse, createCatalog, createVoiceAgent, describeEmptyTtsResponse, evaluateBudget, extractAnthropicTokenUsage, extractTokenUsageFromResponse$2 as extractAnthropicTokenUsageFromResponse, extractDeepSeekTokenUsage, extractTokenUsageFromResponse$6 as extractDeepSeekTokenUsageFromResponse, extractFirstJsonObject, extractGoogleTokenUsage, extractTokenUsageFromResponse$1 as extractGoogleTokenUsageFromResponse, extractGrokTokenUsage, extractTokenUsageFromResponse$4 as extractGrokTokenUsageFromResponse, extractKimiTokenUsage, extractTokenUsageFromResponse$5 as extractKimiTokenUsageFromResponse, extractMetaTokenUsage, extractTokenUsageFromResponse$3 as extractMetaTokenUsageFromResponse, extractMistralTokenUsage, extractTokenUsageFromResponse as extractMistralTokenUsageFromResponse, extractOpenAITokenUsage, extractTokenUsageFromResponse$7 as extractOpenAITokenUsageFromResponse, extractTokenUsage, extractUsageAndCalculateCost, firstRefusal, generateGoogleTtsAudio, generateOpenAiTtsAudio, generateSchemaInstructions, getModelConfigByApiName, getModelDisplayName, getModelProviderName, getModelTags, getProviderSignatureFields, isBudgetExceededError, isHybridThinkingModel, isInPeakWindow, isPeakBilling, isSafetyBlocked, isWeekendAt, ledgerSpend, logger, mergeThinking, modelHasTag, modelIsFast, needsPromptBasedSchema, normalizeTtsStyle, parseAndValidateLlmJson, pcmToWav, periodEnd, periodKey, safeValidateResponse, setBeforeAskHook, setLlmLogger, setRetryHook, stableHashHex, stripInlineThinking, supportsNativeJsonSchema, toAnthropicEffort, toDeepSeekEffort, toFuguEffort, toGeminiEffort, toGlmEffort, toKimiEffort, toMetaEffort, toMiniMaxEffort, toMistralEffort, toOpenAIEffort, toXaiEffort, transcribeWithGemini, transcribeWithOpenAi, validateResponse };