@hiper2d/ai-agents 0.32.0 → 0.34.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.d.mts CHANGED
@@ -25,6 +25,7 @@ interface TokenUsage$1 {
25
25
  costUSD: number;
26
26
  reasoningTokens?: number;
27
27
  cachedInputTokens?: number;
28
+ cacheWriteTokens?: number;
28
29
  durationMs?: number;
29
30
  }
30
31
  interface ApiKeyMap {
@@ -1435,19 +1436,25 @@ declare class AgentFactory {
1435
1436
  }
1436
1437
 
1437
1438
  type CacheTtl = '5m' | '1h';
1439
+ /** Prompt-cache setting for a ClaudeAgent: a TTL for every breakpoint, or 'off' for none. */
1440
+ type ClaudeCacheMode = CacheTtl | 'off';
1438
1441
  declare class ClaudeAgent extends AbstractAgent {
1439
1442
  private readonly client;
1440
1443
  /**
1441
- * TTL for every breakpoint this agent places (system tiers and the message anchor).
1442
- * Anthropic bills a 5m write at 1.25x input, a 1h write at 2x, reads at 0.1x, and a read
1443
- * refreshes the timer on either TTL. Default '1h' because the main consumer runs at human
1444
- * pace: consecutive calls for one agent measured 12-78 minutes apart, so 5m entries
1445
- * expired before they were ever read (0-16% hit rate over 30 days, hits only on gaps
1446
- * under five minutes). Set '5m' for continuous traffic where every call lands inside the
1447
- * window; there the cheaper write wins. One knob for all breakpoints on purpose: Anthropic
1444
+ * TTL for every breakpoint this agent places (system tiers and the message anchor), or
1445
+ * 'off' to place none. Anthropic bills a 5m write at 1.25x input, a 1h write at 2x, reads
1446
+ * at 0.1x, and a read refreshes the timer on either TTL; with no breakpoint every token is
1447
+ * plain 1x input (Claude has no implicit caching). Caching pays only when enough of what
1448
+ * is written gets read back: break-even is ~22% of the prompt read at 5m and ~53% at 1h.
1449
+ * Measured on Werewolf (human-paced, consecutive calls for one bot 12-78 minutes apart):
1450
+ * 5m read 0-16% back, 1h 42-43% over 30 days of production bot turns (2026-11-06) — both
1451
+ * cost more than no cache, so that host sets 'off'. Default '1h' for continuous traffic
1452
+ * where calls land inside the window. One knob for all breakpoints on purpose: Anthropic
1448
1453
  * requires 1h entries to precede 5m ones, and a single TTL keeps that trivially true.
1449
1454
  */
1450
- cacheTtl: CacheTtl;
1455
+ cacheTtl: ClaudeCacheMode;
1456
+ /** The cache_control to attach to a breakpoint, or none when caching is off. */
1457
+ private get cacheControl();
1451
1458
  private get defaultParams();
1452
1459
  private readonly logTemplates;
1453
1460
  private readonly errorMessages;
@@ -1483,9 +1490,11 @@ declare class ClaudeAgent extends AbstractAgent {
1483
1490
  * Builds TokenUsage from the response. Anthropic's input_tokens EXCLUDES cached tokens
1484
1491
  * (total prompt = input_tokens + cache_read + cache_creation), unlike the OpenAI-shaped
1485
1492
  * providers whose prompt_tokens include them — so reconstruct the full prompt size here
1486
- * before pricing. Cache reads bill at the cacheHitPrice (~0.1x); cache writes bill at
1487
- * 1.25x input, which MODEL_PRICING doesn't model, so written tokens are priced at the
1488
- * plain input rate (~20% undercount on the written span only).
1493
+ * before pricing. Cache reads bill at the cacheHitPrice (~0.1x). Cache writes bill at a
1494
+ * multiple of input by TTL (1.25x for 5m, 2x for 1h); MODEL_PRICING has no write rate, so
1495
+ * the premium is added on top at the call's effective input rate (which keeps any
1496
+ * long-context tier). Until 0.33.0 writes were priced at plain input, under-reporting
1497
+ * every 1h write by half.
1489
1498
  */
1490
1499
  private buildTokenUsage;
1491
1500
  private convertRole;
@@ -1911,4 +1920,4 @@ declare class MiniMaxAgent extends AbstractAgent {
1911
1920
  doAskText(messages: AIMessage[]): Promise<[string, string, TokenUsage$1?, string?]>;
1912
1921
  }
1913
1922
 
1914
- 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 };
1923
+ 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 ClaudeCacheMode, 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
@@ -25,6 +25,7 @@ interface TokenUsage$1 {
25
25
  costUSD: number;
26
26
  reasoningTokens?: number;
27
27
  cachedInputTokens?: number;
28
+ cacheWriteTokens?: number;
28
29
  durationMs?: number;
29
30
  }
30
31
  interface ApiKeyMap {
@@ -1435,19 +1436,25 @@ declare class AgentFactory {
1435
1436
  }
1436
1437
 
1437
1438
  type CacheTtl = '5m' | '1h';
1439
+ /** Prompt-cache setting for a ClaudeAgent: a TTL for every breakpoint, or 'off' for none. */
1440
+ type ClaudeCacheMode = CacheTtl | 'off';
1438
1441
  declare class ClaudeAgent extends AbstractAgent {
1439
1442
  private readonly client;
1440
1443
  /**
1441
- * TTL for every breakpoint this agent places (system tiers and the message anchor).
1442
- * Anthropic bills a 5m write at 1.25x input, a 1h write at 2x, reads at 0.1x, and a read
1443
- * refreshes the timer on either TTL. Default '1h' because the main consumer runs at human
1444
- * pace: consecutive calls for one agent measured 12-78 minutes apart, so 5m entries
1445
- * expired before they were ever read (0-16% hit rate over 30 days, hits only on gaps
1446
- * under five minutes). Set '5m' for continuous traffic where every call lands inside the
1447
- * window; there the cheaper write wins. One knob for all breakpoints on purpose: Anthropic
1444
+ * TTL for every breakpoint this agent places (system tiers and the message anchor), or
1445
+ * 'off' to place none. Anthropic bills a 5m write at 1.25x input, a 1h write at 2x, reads
1446
+ * at 0.1x, and a read refreshes the timer on either TTL; with no breakpoint every token is
1447
+ * plain 1x input (Claude has no implicit caching). Caching pays only when enough of what
1448
+ * is written gets read back: break-even is ~22% of the prompt read at 5m and ~53% at 1h.
1449
+ * Measured on Werewolf (human-paced, consecutive calls for one bot 12-78 minutes apart):
1450
+ * 5m read 0-16% back, 1h 42-43% over 30 days of production bot turns (2026-11-06) — both
1451
+ * cost more than no cache, so that host sets 'off'. Default '1h' for continuous traffic
1452
+ * where calls land inside the window. One knob for all breakpoints on purpose: Anthropic
1448
1453
  * requires 1h entries to precede 5m ones, and a single TTL keeps that trivially true.
1449
1454
  */
1450
- cacheTtl: CacheTtl;
1455
+ cacheTtl: ClaudeCacheMode;
1456
+ /** The cache_control to attach to a breakpoint, or none when caching is off. */
1457
+ private get cacheControl();
1451
1458
  private get defaultParams();
1452
1459
  private readonly logTemplates;
1453
1460
  private readonly errorMessages;
@@ -1483,9 +1490,11 @@ declare class ClaudeAgent extends AbstractAgent {
1483
1490
  * Builds TokenUsage from the response. Anthropic's input_tokens EXCLUDES cached tokens
1484
1491
  * (total prompt = input_tokens + cache_read + cache_creation), unlike the OpenAI-shaped
1485
1492
  * providers whose prompt_tokens include them — so reconstruct the full prompt size here
1486
- * before pricing. Cache reads bill at the cacheHitPrice (~0.1x); cache writes bill at
1487
- * 1.25x input, which MODEL_PRICING doesn't model, so written tokens are priced at the
1488
- * plain input rate (~20% undercount on the written span only).
1493
+ * before pricing. Cache reads bill at the cacheHitPrice (~0.1x). Cache writes bill at a
1494
+ * multiple of input by TTL (1.25x for 5m, 2x for 1h); MODEL_PRICING has no write rate, so
1495
+ * the premium is added on top at the call's effective input rate (which keeps any
1496
+ * long-context tier). Until 0.33.0 writes were priced at plain input, under-reporting
1497
+ * every 1h write by half.
1489
1498
  */
1490
1499
  private buildTokenUsage;
1491
1500
  private convertRole;
@@ -1911,4 +1920,4 @@ declare class MiniMaxAgent extends AbstractAgent {
1911
1920
  doAskText(messages: AIMessage[]): Promise<[string, string, TokenUsage$1?, string?]>;
1912
1921
  }
1913
1922
 
1914
- 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 };
1923
+ 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 ClaudeCacheMode, 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.js CHANGED
@@ -1050,10 +1050,11 @@ var LLM_CONSTANTS = {
1050
1050
  var DEFAULT_MAX_OUTPUT_TOKENS = 8192;
1051
1051
  var DEFAULT_REQUEST_TIMEOUT_MS = 6e4;
1052
1052
  var SupportedAiModels = {
1053
- // Claude Fable 5.1 (2026-09-02, was Fable 5) - frontier reasoning model. Thinking is always on (no non-thinking variant).
1053
+ // Claude Fable 5.2 (2026-11-10, was 5.1 since 2026-09-02, Fable 5 before) - frontier reasoning model.
1054
+ // Thinking is always on (no non-thinking variant). Id verified against GET /v1/models.
1054
1055
  [LLM_CONSTANTS.CLAUDE_FABLE]: {
1055
- displayName: "Claude Fable 5.1",
1056
- modelApiName: "claude-fable-5-1",
1056
+ displayName: "Claude Fable 5.2",
1057
+ modelApiName: "claude-fable-5-2",
1057
1058
  apiKeyName: API_KEY_CONSTANTS.ANTHROPIC,
1058
1059
  hasThinking: true,
1059
1060
  reasoningEffort: "high",
@@ -1688,6 +1689,7 @@ var MODEL_PRICING = {
1688
1689
  [SupportedAiModels[LLM_CONSTANTS.CLAUDE_FABLE].modelApiName]: {
1689
1690
  // Full 1M context window at standard pricing (no extended-context premium).
1690
1691
  // Fable 5.1 (2026-09-02): same $10/$50 as Fable 5, but cache reads dropped to $0.25/MTok.
1692
+ // Fable 5.2 (2026-11-10): same prices as 5.1.
1691
1693
  inputPrice: 10,
1692
1694
  outputPrice: 50,
1693
1695
  cacheHitPrice: 0.25
@@ -3053,22 +3055,29 @@ ${instruction}`);
3053
3055
 
3054
3056
  // src/agents/anthropic-agent.ts
3055
3057
  var import_sdk = require("@anthropic-ai/sdk");
3058
+ var CACHE_WRITE_MULTIPLIER = { "5m": 1.25, "1h": 2 };
3056
3059
  var rejectsDisabledThinking = (model) => model.includes("fable") || model.includes("opus-5-5");
3057
3060
  var usesBetweenToolsForOff = (model) => model.includes("sonnet-5-5");
3058
3061
  var usesAdaptiveThinking = (model) => !model.includes("haiku-4");
3059
3062
  var ClaudeAgent = class extends AbstractAgent {
3060
3063
  client;
3061
3064
  /**
3062
- * TTL for every breakpoint this agent places (system tiers and the message anchor).
3063
- * Anthropic bills a 5m write at 1.25x input, a 1h write at 2x, reads at 0.1x, and a read
3064
- * refreshes the timer on either TTL. Default '1h' because the main consumer runs at human
3065
- * pace: consecutive calls for one agent measured 12-78 minutes apart, so 5m entries
3066
- * expired before they were ever read (0-16% hit rate over 30 days, hits only on gaps
3067
- * under five minutes). Set '5m' for continuous traffic where every call lands inside the
3068
- * window; there the cheaper write wins. One knob for all breakpoints on purpose: Anthropic
3065
+ * TTL for every breakpoint this agent places (system tiers and the message anchor), or
3066
+ * 'off' to place none. Anthropic bills a 5m write at 1.25x input, a 1h write at 2x, reads
3067
+ * at 0.1x, and a read refreshes the timer on either TTL; with no breakpoint every token is
3068
+ * plain 1x input (Claude has no implicit caching). Caching pays only when enough of what
3069
+ * is written gets read back: break-even is ~22% of the prompt read at 5m and ~53% at 1h.
3070
+ * Measured on Werewolf (human-paced, consecutive calls for one bot 12-78 minutes apart):
3071
+ * 5m read 0-16% back, 1h 42-43% over 30 days of production bot turns (2026-11-06) — both
3072
+ * cost more than no cache, so that host sets 'off'. Default '1h' for continuous traffic
3073
+ * where calls land inside the window. One knob for all breakpoints on purpose: Anthropic
3069
3074
  * requires 1h entries to precede 5m ones, and a single TTL keeps that trivially true.
3070
3075
  */
3071
3076
  cacheTtl = "1h";
3077
+ /** The cache_control to attach to a breakpoint, or none when caching is off. */
3078
+ get cacheControl() {
3079
+ return this.cacheTtl === "off" ? {} : { cache_control: { type: "ephemeral", ttl: this.cacheTtl } };
3080
+ }
3072
3081
  // System-prompt breakpoints, one per cache tier (see CACHE_TIER_MARKER):
3073
3082
  // block 1 - shared static rules, byte-identical across all bots and games with the
3074
3083
  // same rule set. Caches are scoped per model, so one entry serves every bot
@@ -3084,7 +3093,7 @@ var ClaudeAgent = class extends AbstractAgent {
3084
3093
  get defaultParams() {
3085
3094
  return {
3086
3095
  max_tokens: this.maxOutputTokens,
3087
- system: this.instructionParts.map((part) => ({ type: "text", text: part, cache_control: { type: "ephemeral", ttl: this.cacheTtl } })),
3096
+ system: this.instructionParts.map((part) => ({ type: "text", text: part, ...this.cacheControl })),
3088
3097
  model: this.model
3089
3098
  };
3090
3099
  }
@@ -3183,6 +3192,9 @@ var ClaudeAgent = class extends AbstractAgent {
3183
3192
  * which for us is exactly the never-repeated tail — every entry it wrote would be dead.
3184
3193
  */
3185
3194
  applyCacheBreakpoint(messages) {
3195
+ if (this.cacheTtl === "off") {
3196
+ return;
3197
+ }
3186
3198
  if (messages.length < 2) {
3187
3199
  return;
3188
3200
  }
@@ -3205,9 +3217,11 @@ var ClaudeAgent = class extends AbstractAgent {
3205
3217
  * Builds TokenUsage from the response. Anthropic's input_tokens EXCLUDES cached tokens
3206
3218
  * (total prompt = input_tokens + cache_read + cache_creation), unlike the OpenAI-shaped
3207
3219
  * providers whose prompt_tokens include them — so reconstruct the full prompt size here
3208
- * before pricing. Cache reads bill at the cacheHitPrice (~0.1x); cache writes bill at
3209
- * 1.25x input, which MODEL_PRICING doesn't model, so written tokens are priced at the
3210
- * plain input rate (~20% undercount on the written span only).
3220
+ * before pricing. Cache reads bill at the cacheHitPrice (~0.1x). Cache writes bill at a
3221
+ * multiple of input by TTL (1.25x for 5m, 2x for 1h); MODEL_PRICING has no write rate, so
3222
+ * the premium is added on top at the call's effective input rate (which keeps any
3223
+ * long-context tier). Until 0.33.0 writes were priced at plain input, under-reporting
3224
+ * every 1h write by half.
3211
3225
  */
3212
3226
  buildTokenUsage(usage) {
3213
3227
  const cacheReadTokens = usage.cache_read_input_tokens ?? 0;
@@ -3215,7 +3229,14 @@ var ClaudeAgent = class extends AbstractAgent {
3215
3229
  const uncachedInputTokens = usage.input_tokens || 0;
3216
3230
  const inputTokens = uncachedInputTokens + cacheReadTokens + cacheWriteTokens;
3217
3231
  const outputTokens = usage.output_tokens || 0;
3218
- const cost = calculateAnthropicCost(this.model, inputTokens, outputTokens, cacheReadTokens);
3232
+ let cost = calculateAnthropicCost(this.model, inputTokens, outputTokens, cacheReadTokens);
3233
+ if (cacheWriteTokens > 0) {
3234
+ const byTtl = usage.cache_creation;
3235
+ const written1h = byTtl ? byTtl.ephemeral_1h_input_tokens ?? 0 : this.cacheTtl === "1h" ? cacheWriteTokens : 0;
3236
+ const written5m = byTtl ? byTtl.ephemeral_5m_input_tokens ?? 0 : cacheWriteTokens - written1h;
3237
+ const inputRate = inputTokens > 0 ? calculateAnthropicCost(this.model, inputTokens, 0, 0) / inputTokens : 0;
3238
+ cost += inputRate * (written1h * (CACHE_WRITE_MULTIPLIER["1h"] - 1) + written5m * (CACHE_WRITE_MULTIPLIER["5m"] - 1));
3239
+ }
3219
3240
  if (cacheReadTokens > 0 || cacheWriteTokens > 0) {
3220
3241
  this.logger(`\u{1F4BE} Prompt cache: ${cacheReadTokens} read, ${cacheWriteTokens} written, ${uncachedInputTokens} uncached`);
3221
3242
  }
@@ -3224,8 +3245,9 @@ var ClaudeAgent = class extends AbstractAgent {
3224
3245
  outputTokens,
3225
3246
  totalTokens: inputTokens + outputTokens,
3226
3247
  costUSD: cost,
3227
- // Cache reads only — writes are a billing premium, not reuse of prior context.
3228
- ...cacheReadTokens > 0 ? { cachedInputTokens: cacheReadTokens } : {}
3248
+ // Breakdowns of inputTokens, omitted when zero (Firestore rejects undefined).
3249
+ ...cacheReadTokens > 0 ? { cachedInputTokens: cacheReadTokens } : {},
3250
+ ...cacheWriteTokens > 0 ? { cacheWriteTokens } : {}
3229
3251
  };
3230
3252
  }
3231
3253
  convertRole(role) {