Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
pricing: Haiku 5.5 long-prompt tier bills the whole request above 100K (#6448 item 1)
garrytan5d9208f24b0d
diff --git a/docs/architecture/key-files/core-minions-1.md b/docs/architecture/key-files/core-minions-1.mdindex af1e51d32a..f1091a7fad 100644--- a/docs/architecture/key-files/core-minions-1.md+++ b/docs/architecture/key-files/core-minions-1.md@@ -56,7 +56,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/handlers/subagent-persistence.ts` — subagent transcript + tool-execution persistence (pure peel from subagent.ts): loadPriorMessages/Tools/ToolsV2, persistMessage, persistToolExecPending/Complete/Failed (all `$N::text::jsonb` discipline), plus `finalizeWriteAccounting`: derives pages_attempted/written/failed from the job's put_page ledger rows (settled only — pending counts toward neither), merges them into every SubagentResult, and throws UnrecoverableError on require_writes jobs with no settled successful write, including zero-attempt clean finishes, unless `isLegitimateZeroWrite` accepts the zero-attempt `end_turn` finish: the oneshot explicit skip (`oneshot_skipped: true` on a `synth_mode_used: 'oneshot'` result) or, when the submitter set `allow_clean_zero_writes` (the patterns phase), a run with at least one completed tool execution in its ledger — all-attempted-failed, dirty stops, prose-only finishes and runs whose only tools failed still dead-letter (the oneshot runner banks each skip as a `oneshot-<inv8>-skip` ledger row before its transcript, so a retried job's ledger-first recovery completes as the same skip without a model call); `scopeToolUseIdPrefix` narrows the scan to the oneshot invocation family. Fresh `brain_put_page` rejects are normalized by `src/core/minions/tools/put-page-result.ts` before ledger settlement; accounting reclassifies rejected historical completed envelopes (including JSON strings) without changing the stored rows. Unchanged-page saves and persisted pages whose embedding failed still count as writes.-- `src/core/minions/handlers/subagent.ts` — LLM-loop handler. Two-phase tool persistence (pending → complete/failed), replay reconciliation for mid-dispatch crashes, dual-signal abort (`ctx.signal` + `ctx.shutdownSignal`), Anthropic prompt caching on system + tool defs. `makeSubagentHandler({engine, client?, ...})` factory; `MessagesClient` is an injectable interface the real SDK implements structurally. Per-turn output cap resolves via `resolveMaxOutputTokens` (`data.max_tokens` → `agent.max_output_tokens` config → 8192 default); a `stop_reason: 'max_tokens'` final turn surfaces as `SubagentStopReason 'max_tokens'` (not a silent `end_turn`), and a max_tokens stop mid-tool-round injects a truncation note into the tool-result turn so the model re-issues the dropped call. Every stop-reason mapping lives in `src/core/minions/subagent-stop-reason.ts` (#6448): `directStopReason` (Messages path: `max_tokens` → `max_tokens`, `refusal` → `refusal`, an empty or whitespace-only final text on a clean stop → `error`), `gatewayStopReason` (`toolLoop`'s `length` → `max_tokens`, `refusal`/`content_filter` → `refusal`, `empty_response`/`aborted`/`unrecoverable` → `error`) and `replayTerminalStopReason` (a persisted terminal turn: `tokens_out >= cap` → `max_tokens`, else `error` when its text is empty); on both replay paths ANY trailing assistant turn without tool calls is terminal, text or not, so a thinking-only tail is answered from the transcript instead of re-sent as an assistant prefill. Pinned by `test/subagent-stop-reason-6448.test.ts`. Throws `RateLeaseUnavailableError` (renewable) when rate-lease capacity is full. Both loop paths (the direct Anthropic SDK turn loop and the gateway toolLoop's `acquireTurnPermit`) heartbeat the held lease at ttl/3 for the duration of each provider call — single-flight renewals so a stalled renewal never stacks behind a starved pool; a FALSE renewal means the lease row was pruned/stolen (the slot is already re-admitted), so the in-flight call aborts and converts to a lease-full requeue instead of running above `maxConcurrent`. Anthropic 400 `prompt is too long` responses (status 400 + body matches `/prompt is too long|prompt_too_long|context.*length/i`) classify as `UnrecoverableError` so the job goes straight to `dead` on first attempt instead of stalling three times. Catches both initial-prompt overflow and turn-N tool-loop accumulation that `synthesize.ts`'s chunker can't bound ahead of time. terminal-state short-circuit on resume. When a stored message thread already ends in `stop_reason: 'end_turn'`, the handler returns `{ ok: true }` immediately instead of issuing another `messages.create` call (re-prompting past `end_turn` would get a 400 and dead-letter an already-successful job). Pinned by `test/subagent-handler.test.ts`. Oneshot dispatch: `data.mode === 'oneshot'` on a FRESH job (zero persisted messages) routes to `runSubagentOneshot` (subagent-oneshot.ts) before either loop; a validation fallback re-enters the loops in the SAME job, stamped `synth_mode_used: 'agentic_fallback'` + `fallback_reason`. Write accounting (`finalizeWriteAccounting` in subagent-persistence.ts): every job's result carries pages_attempted/written/failed derived from the tool-execution ledger (settled rows only); `data.require_writes` jobs (dream synthesize + patterns fan-outs) require at least one settled successful page write; zero successes, including a clean prose-only finish or pending-only ledger, throw UnrecoverableError, except the deliberate zero-write completions `isLegitimateZeroWrite` accepts (an explicit oneshot skip, or an `allow_clean_zero_writes` child with a completed tool execution). Optional-write jobs can still complete without writing. `resolveMaxOutputTokens` takes the model: thinking-by-default models (Claude 5 by name or recipe-declared `thinking_by_default` such as DeepSeek v4, via the gateway's shared `isThinkingModel`) default to 32000 when neither per-job nor config caps are set. Gateway-path `onToolCallStart` has a uniq_subagent_tools_use_id backstop: a provider repeating a tool id across turns persists under a `#m<idx>o<ordinal>`-suffixed debug id (second violation reconciles to the existing row's gbrain_tool_use_id) instead of dead-lettering the job. Persistence helpers live in subagent-persistence.ts (pure peel; `__testing` unchanged). Tool-execution rows carry NO job-wide unique on the raw provider `tool_use_id` (migration v131 drops `uniq_subagent_tools_use_id`: providers like claude-cli legitimately re-mint the same short id every turn, and a collision would dead-letter the job); row identity is the stable `(job_id, message_idx, ordinal)` unique, and readers/settlement resolve an execution by `(message_idx, tool_use_id)`. Settle writes (complete/failed) target exactly ONE row — the call's own ordinal first, then a legacy ordinal=NULL row, never a row that already settled complete (a broader status disjunct could only capture a same-id sibling's row); pending inserts guard legacy NULL-ordinal rows via NOT EXISTS and use the stable-id `ON CONFLICT` as the zombie-worker backstop. Replay/reconcile resolve an execution by persisted ordinal first (validated against the raw id), then by `(message_idx, tool_use_id)` only when the id is unique within the turn, then the same-tool legacy positional fallback. Mixed-version window: a still-running pre-v131 `gbrain jobs work` daemon errors on tool persistence after the migration until it restarts (its two-phase writes targeted the dropped constraint)+- `src/core/minions/handlers/subagent.ts` — LLM-loop handler. Two-phase tool persistence (pending → complete/failed), replay reconciliation for mid-dispatch crashes, dual-signal abort (`ctx.signal` + `ctx.shutdownSignal`), Anthropic prompt caching on system + tool defs. `makeSubagentHandler({engine, client?, ...})` factory; `MessagesClient` is an injectable interface the real SDK implements structurally. Per-turn output cap resolves via `resolveMaxOutputTokens` (`data.max_tokens` → `agent.max_output_tokens` config → 8192 default); a `stop_reason: 'max_tokens'` final turn surfaces as `SubagentStopReason 'max_tokens'` (not a silent `end_turn`), and a max_tokens stop mid-tool-round injects a truncation note into the tool-result turn so the model re-issues the dropped call. Every stop-reason mapping (direct, gateway and replay paths) lives in `src/core/minions/subagent-stop-reason.ts` (#6448; see Core Minions 2/2): an empty or refused final turn is `error`/`refusal`, never `end_turn`, and any trailing tool-free assistant turn is terminal on replay. Throws `RateLeaseUnavailableError` (renewable) when rate-lease capacity is full. Both loop paths (the direct Anthropic SDK turn loop and the gateway toolLoop's `acquireTurnPermit`) heartbeat the held lease at ttl/3 for the duration of each provider call — single-flight renewals so a stalled renewal never stacks behind a starved pool; a FALSE renewal means the lease row was pruned/stolen (the slot is already re-admitted), so the in-flight call aborts and converts to a lease-full requeue instead of running above `maxConcurrent`. Anthropic 400 `prompt is too long` responses (status 400 + body matches `/prompt is too long|prompt_too_long|context.*length/i`) classify as `UnrecoverableError` so the job goes straight to `dead` on first attempt instead of stalling three times. Catches both initial-prompt overflow and turn-N tool-loop accumulation that `synthesize.ts`'s chunker can't bound ahead of time. terminal-state short-circuit on resume. When a stored message thread already ends in `stop_reason: 'end_turn'`, the handler returns `{ ok: true }` immediately instead of issuing another `messages.create` call (re-prompting past `end_turn` would get a 400 and dead-letter an already-successful job). Pinned by `test/subagent-handler.test.ts`. Oneshot dispatch: `data.mode === 'oneshot'` on a FRESH job (zero persisted messages) routes to `runSubagentOneshot` (subagent-oneshot.ts) before either loop; a validation fallback re-enters the loops in the SAME job, stamped `synth_mode_used: 'agentic_fallback'` + `fallback_reason`. Write accounting (`finalizeWriteAccounting` in subagent-persistence.ts): every job's result carries pages_attempted/written/failed derived from the tool-execution ledger (settled rows only); `data.require_writes` jobs (dream synthesize + patterns fan-outs) require at least one settled successful page write; zero successes, including a clean prose-only finish or pending-only ledger, throw UnrecoverableError, except the deliberate zero-write completions `isLegitimateZeroWrite` accepts (an explicit oneshot skip, or an `allow_clean_zero_writes` child with a completed tool execution). Optional-write jobs can still complete without writing. `resolveMaxOutputTokens` takes the model: thinking-by-default models (Claude 5 by name or recipe-declared `thinking_by_default` such as DeepSeek v4, via the gateway's shared `isThinkingModel`) default to 32000 when neither per-job nor config caps are set. Gateway-path `onToolCallStart` has a uniq_subagent_tools_use_id backstop: a provider repeating a tool id across turns persists under a `#m<idx>o<ordinal>`-suffixed debug id (second violation reconciles to the existing row's gbrain_tool_use_id) instead of dead-lettering the job. Persistence helpers live in subagent-persistence.ts (pure peel; `__testing` unchanged). Tool-execution rows carry NO job-wide unique on the raw provider `tool_use_id` (migration v131 drops `uniq_subagent_tools_use_id`: providers like claude-cli legitimately re-mint the same short id every turn, and a collision would dead-letter the job); row identity is the stable `(job_id, message_idx, ordinal)` unique, and readers/settlement resolve an execution by `(message_idx, tool_use_id)`. Settle writes (complete/failed) target exactly ONE row — the call's own ordinal first, then a legacy ordinal=NULL row, never a row that already settled complete (a broader status disjunct could only capture a same-id sibling's row); pending inserts guard legacy NULL-ordinal rows via NOT EXISTS and use the stable-id `ON CONFLICT` as the zombie-worker backstop. Replay/reconcile resolve an execution by persisted ordinal first (validated against the raw id), then by `(message_idx, tool_use_id)` only when the id is unique within the turn, then the same-tool legacy positional fallback. Mixed-version window: a still-running pre-v131 `gbrain jobs work` daemon errors on tool persistence after the migration until it restarts (its two-phase writes targeted the dropped constraint)- `src/core/minions/handlers/supervisor-audit.ts` — supervisor lifecycle JSONL audit at `~/.gbrain/audit/supervisor-YYYY-Www.jsonl` (ISO-week rotation; shares `computeIsoWeekName()` with `shell-audit.ts`). `writeSupervisorEvent(emission, supervisorPid)` appends one line per event (`started`, `worker_spawned`, `worker_exited`, `backoff`, `health_warn`, `health_error`, `max_crashes_exceeded`, `shutting_down`, `stopped`, `worker_spawn_failed`). `readSupervisorEvents({sinceMs})` is the readback for `gbrain doctor`. Exports `isCrashExit(event)`, `summarizeCrashes(events)`, `CrashSummary` type, and `CLEAN_EXIT_CAUSES` denylist (`'clean_exit' | 'graceful_shutdown' | 'wedge_restart' | 'configuration_blocked'`). Single shared point — both `gbrain doctor` (supervisor check) and `gbrain jobs supervisor status` import from here so the two surfaces can't drift. `isCrashExit` classifies a single `worker_exited` against the denylist: clean/graceful, deliberate wedge restarts and configuration blocks are NON-crashes; everything else (incl. any future `likely_cause` from `child-worker-supervisor.ts`) is a crash; audit lines lacking `likely_cause` fall back to `code !== 0`. `summarizeCrashes` returns `{total, by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}, clean_exits}` — the `legacy` bucket catches both old fallback entries AND unrecognized future causes (fail-loud, not silent underreport); denylist-over-allowlist is deliberate. Pinned by `test/supervisor-audit.test.ts` (14 cases) and 4 source-grep wiring assertions in `test/doctor.test.ts`.diff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.mdindex 00a3d1a154..dd67bb9c9e 100644--- a/docs/architecture/key-files/core-minions-2.md+++ b/docs/architecture/key-files/core-minions-2.md@@ -8,6 +8,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/minions/spawn-helpers.ts` — pure `detectTini()` + `buildSpawnInvocation()` consumed by both `supervisor.ts` and `autopilot.ts` (one implementation for both spawn sites; tini wrapping is testable without `mock.module()`, rule R2 of `scripts/check-test-isolation.sh`). `detectTini()` calls `execFileSync('which', ['tini'])` with explicit `env: process.env` so Bun sees runtime PATH mutations. `buildSpawnInvocation(tiniPath, cmd, args)` returns `{cmd, args}` with `tini -s --` prepended when present, or the bare invocation otherwise. Subreaper mode also serves job children; it does not imply PID 1 or containment of descendants that escape the process group. Pinned by `test/spawn-helpers.test.ts` (5) and `test/supervisor-tini.test.ts` (4).- `src/core/minions/spend-authorization.ts` + `spend-record.ts` — submit-time spend authorization on queued paid jobs. `spend-record.ts` holds the stored shape (`version`, `kind` `authorized`/`legacy_default`, `group_id`, `of`, `cap_usd` or `uncapped`, `cap_source`, `via`, `command`, `est_usd`, `argv`, `authorized_at`), its strict parser and `spendBasis` (`authorized`, `legacy_default`, `unrecorded`, `invalid` with a `why`). `jobSpendAuthorization(auth, {command, est_usd, of, argv})` builds a group from a consent `Authorization`; `legacyDefaultClaimSetSql` is the claim's fence and legacy stamp. `runWithJobSpend(engine, job, ctx, handler)` runs at both handler seams (worker, `run-child`; the dream inline drain only claims private-queue subagents, which never carry an authorization): NULL rows run as before, uncapped records reserve nothing, capped records run under `withAIInvocationGuard` (nested) so each provider attempt reserves its maximum against `group:<id>` and settles measured usage. Settled exhaustion (or an unpriced model under a user cap) throws `SpendGroupRefusedError` (`derived_cap_exhausted`/`cost_cap_exceeded`/`no_pricing`, group amounts, rerun fix with twice the cap) and records it as `result.spend_refusal`; live-hold pressure throws `SpendGroupPressureError` (a lease release, at most `MAX_PRESSURE_RENEWALS` = 6, counted from `minion_lease_pressure_log`); unpriced models under derived/default caps warn and run. Every claimed paid job logs one `job_spend_basis` line. `spendSubmitSummary` prints the producer's group, kept authorizations (with `gbrain jobs cancel --group`) and reused rows; `groupJobs`/`jobGroupAmounts` back `jobs list --group`/`jobs cancel --group`/`jobs get`. Tests: `test/minions-spend-authorization.test.ts`, `test/minions-spend-authorization.serial.test.ts`, `test/minions-spend-enforcement-child.test.ts`.+- `src/core/minions/subagent-stop-reason.ts` — the one home of the subagent handler's stop-reason mapping (#6448 items 2/3): `isEmptyFinalText` (empty or whitespace-only text); `directStopReason` for the Messages path (`max_tokens` → `max_tokens`, `refusal` → `refusal`, a clean stop whose final text is empty → `error`); `gatewayStopReason` for `toolLoop` (`length` → `max_tokens`, `refusal`/`content_filter` → `refusal`, `empty_response`/`aborted`/`unrecoverable` → `error`, `end` → `end_turn`); `replayTerminalStopReason` for a persisted terminal turn (`tokens_out >= cap` → `max_tokens`, empty text → `error`, else `end_turn`). On both replay paths in `handlers/subagent.ts` ANY trailing assistant turn without tool calls is terminal, text or not, so a thinking-only or empty tail is answered from the transcript instead of being re-sent as an assistant prefill; the gateway's `empty_response` stop reason is additive (`gateway.ts` `ToolLoopStopReason`). Pinned by `test/subagent-stop-reason-6448.test.ts` and `test/subagent-stop-reason-helper.test.ts`.- `src/core/minions/submission-authority.ts` — versioned authority kept outside caller job data. Submission normalization and worker revalidation bind remote jobs to immutable principal/grant/source/payload ceilings; application authority preserves trusted internal work. `coalesceDecision(rawRow, authority)` is the one coalesce rule for all five `MinionQueue.add` coalesce paths (idempotency fast path, param coalescing, pending and waiting caps, insert race); rows are read with `LEGACY_AUTHORITY_COLUMN` so only SQL NULL authority gets the legacy rule (dead/cancelled keys released by a CAS update, completed/failed coalesce for application callers only, live rows refused with the `legacy_job_authority` catalogue error); `UNREVIEWED_LIVE_JOBS_WHERE` is the claim gate's predicate, shared with doctor `legacy_job_authority`. Tests: `test/minions-legacy-coalesce.test.ts` (PGLite) and `test/e2e/minions-legacy-coalesce-postgres.test.ts`, both over `test/helpers/legacy-coalesce-matrix.ts`. `src/core/minions/authorize-legacy.ts` provides explicit local preview and transactional snapshot comparison for selected historical rows: `--ids`, or `--select <filter>` whose preview saves the exact id set under a hash of the filter and the snapshot digest with `saveApprovedSet` (preview-approval helper) so `--expect <hash> --yes` authorizes exactly that set; every refusal is a catalogue error (`legacy_job_selection_invalid`, `legacy_jobs_active`, `preview_changed`). `src/core/minions/source-filesystem.ts` provides reentrant canonical root/worktree locking and descriptor-based confined reads/writes. Both worker modes enforce the same authority gate. Upgrade protocol: `docs/guides/authorization-upgrade.md`.- `src/core/minions/supervisor-pid.ts` — `readSupervisorPid(pidFile) → {pid, running}`: the shared `existsSync → readFileSync → parseInt → process.kill(pid,0)` PID-file + liveness reader shared by `jobs.ts` (supervisor status), `jobs.ts` (stats), and `doctor.ts`. EPERM from the liveness probe counts as running. Pinned by `test/supervisor-pid.test.ts`.diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.mdindex 910090e751..f5e96d191c 100644--- a/docs/architecture/key-files/providers.md+++ b/docs/architecture/key-files/providers.md@@ -50,7 +50,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/model-id.ts` — `splitProviderModelId(input: string | null | undefined): {provider: string | null, model: string}` shared parser for the pricing side. Splits on `:` first, then `/`. Defensive contract: null/undefined/empty/whitespace returns `{provider: null, model: ''}`. Five sites consume it (`src/core/anthropic-pricing.ts:estimateMaxCostUsd`, `src/core/budget/budget-tracker.ts:lookupPricing`, `src/core/eval-contradictions/cost-tracker.ts:pricingFor`, `src/core/model-config.ts:isAnthropicProvider`) so the pricing + classification surface has no parallel re-implementations of `provider:model` splitting — slash-form ids (`anthropic/claude-sonnet-4-6`) classify correctly instead of falling through to "unknown model". Distinct from the gateway-side `parseModelId` in `src/core/ai/model-resolver.ts`, which throws on bare names because routing needs an explicit provider; this one returns `{provider: null, model: 'bare'}` because pricing lookups happen against bare model ids. Pinned by `test/model-id.test.ts`.-- `src/core/model-pricing.ts` — single source of truth for paid-cloud CHAT/completion model pricing (USD per 1M tokens, input | output). `CANONICAL_PRICING` is a `provider:model`-keyed table (Anthropic Opus 5/4.8/4.7/4.6 `$5/$25`, Sonnet 4.6 `$3/$15`, Haiku 4.5 `$1/$5` both dateless + dated, plus OpenAI / Google / Together / DeepSeek panel models). Exported as `gbrain/core/model-pricing` for companion evaluators to enforce the canonical price cap. `canonicalLookup(modelId)` resolves bare (`claude-opus-4-8`), colon (`anthropic:claude-opus-4-8`), and slash (`anthropic/...`) forms — bare ids default to the `anthropic:` provider; nested OpenRouter ids (`openrouter:anthropic/...`) intentionally MISS so OpenRouter markup isn't repriced as the inner vendor; after the exact match, a case-insensitive fallback folds BOTH sides (some canonical keys carry cased model tails verbatim), safe only while no two canonical keys collide case-insensitively (pinned by the drift guard). Every other chat-pricing table is a DERIVED view of this one (NOT a hand-copied duplicate), so cross-table price drift is structurally impossible. Embeddings live separately in `embedding-pricing.ts` (different unit). DeepSeek rows (`deepseek-flash`, its legacy alias `deepseek-v4-flash`, `deepseek-v4-pro`) carry the vendor's PEAK rate so caps bound the worst case; `peakRateNote(models)` in `src/core/budget/reservation-cost.ts` labels estimates that use them. OpenRouter rows are the router's own catalogue rate, never the vendor's. `bun run check:recipe-pricing` (`scripts/check-recipe-pricing.ts`) requires every recipe touchpoint model to price or be named in the recipe's `unpriced_models`. Pinned by `test/model-pricing.test.ts` whose drift guard asserts each derived view equals canonical and that the cross-modal panel models are all present.+- `src/core/model-pricing.ts` — single source of truth for paid-cloud CHAT/completion model pricing (USD per 1M tokens, input | output). `CANONICAL_PRICING` is a `provider:model`-keyed table (Anthropic Opus 5/4.8/4.7/4.6 `$5/$25`, Sonnet 4.6 `$3/$15`, Haiku 4.5 `$1/$5` both dateless + dated, plus OpenAI / Google / Together / DeepSeek panel models). Exported as `gbrain/core/model-pricing` for companion evaluators to enforce the canonical price cap. `canonicalLookup(modelId)` resolves bare (`claude-opus-4-8`), colon (`anthropic:claude-opus-4-8`), and slash (`anthropic/...`) forms — bare ids default to the `anthropic:` provider; nested OpenRouter ids (`openrouter:anthropic/...`) intentionally MISS so OpenRouter markup isn't repriced as the inner vendor; after the exact match, a case-insensitive fallback folds BOTH sides (some canonical keys carry cased model tails verbatim), safe only while no two canonical keys collide case-insensitively (pinned by the drift guard). Every other chat-pricing table is a DERIVED view of this one (NOT a hand-copied duplicate), so cross-table price drift is structurally impossible. Embeddings live separately in `embedding-pricing.ts` (different unit). DeepSeek rows (`deepseek-flash`, its legacy alias `deepseek-v4-flash`, `deepseek-v4-pro`) carry the vendor's PEAK rate so caps bound the worst case; `peakRateNote(models)` in `src/core/budget/reservation-cost.ts` labels estimates that use them. OpenRouter rows are the router's own catalogue rate, never the vendor's. `bun run check:recipe-pricing` (`scripts/check-recipe-pricing.ts`) requires every recipe touchpoint model to price or be named in the recipe's `unpriced_models`. Pinned by `test/model-pricing.test.ts` whose drift guard asserts each derived view equals canonical and that the cross-modal panel models are all present. **Long-prompt tiers (#6448 item 1):** a row may carry `long_prompt: LongPromptTier` (`threshold_tokens` + a full rate set); `priceAtPromptSize(row, inputTokens)` returns the tier (tier-free) when the call's input tokens are STRICTLY above the threshold, else the base row. Haiku 5.5 declares the vendor's 5x tier above `ANTHROPIC_LONG_PROMPT_THRESHOLD_TOKENS` (100,000; the tier's cache rates derive from the tier's input rate by the row's multipliers, pinned by the drift guard). Every spend site prices through it: `usageCostUsd` / `reservationCostUsd` in `src/core/budget/reservation-cost.ts` (so `BudgetTracker.reserve`/`record` and the audit line see the tier; the reservation sizes the tier by the ESTIMATED input tokens, the record by the served `input_tokens + cache_read + cache_write`) and `estimateChatCostUsd` in `src/core/ai/chat-usage.ts`. The gateway's pre-call input estimate is `estimateChatInputTokens` in `src/core/ai/chat-input-estimate.ts` (system + text + tool calls/results + tool definitions at `CHAT_INPUT_CHARS_PER_TOKEN`), shared with the reservation so a 100K+ reservation is held at the tier rate. Pinned by `test/model-pricing-long-context-tier.test.ts` and `test/model-pricing-tier-helpers.test.ts`.- `src/core/post-upgrade-reembed.ts` — Pure functions backing the `gbrain upgrade` chunker-bump cost prompt. `computeReembedEstimate(engine, model)` queries real SQL (`COUNT(*)` + `COALESCE(SUM(LENGTH(compiled_truth)) + SUM(LENGTH(timeline)), 0)`) on `pages WHERE chunker_version < MARKDOWN_CHUNKER_VERSION`. `formatReembedPrompt(est)` is the stderr-line formatter (count, model, cost estimate when priced). `runPostUpgradeReembedPrompt(engine, model, opts)` re-embeds only on consent: a TTY operator must answer `y` to `[chunker-bump] Re-embed now? [y/N]`; the default, EOF and every non-TTY run decline and print `REEMBED_DEFERRED_HINT` (`gbrain reindex --markdown`, or `gbrain repair safe-chunks --apply --no-embed` then `gbrain embed --stale`), so an unattended upgrade never spends. Reasons: `no_pending`, `bypassed_no_reembed`, `consent_required`, `tty_declined`, `tty_consented`. `GBRAIN_NO_REEMBED=1` skips the prompt with a doctor-warning marker. `opts.confirm` and `opts.isTTY` are test seams.diff --git a/src/core/ai/chat-input-estimate.ts b/src/core/ai/chat-input-estimate.tsnew file mode 100644index 0000000000..eeccb6f03c--- /dev/null+++ b/src/core/ai/chat-input-estimate.ts@@ -0,0 +1,50 @@+/**+ * chat-input-estimate — the pre-flight input-token estimate `gateway.chat()`+ * reserves against the budget tracker before the SDK has counted anything.+ *+ * Heuristic (~4 chars/token). Everything the provider tokenizes as prompt is+ * counted: the system prompt, every text block, tool-call inputs and+ * tool-result outputs in the history, and the tool definitions (name,+ * description and JSON schema) — a tool-heavy subagent turn used to be+ * estimated from its text blocks alone, so a prompt that had already crossed+ * a model's long-prompt pricing threshold (#6448 item 1) was reserved at the+ * base tier. Cap math stays best-effort; `record()` settles the exact count.+ */++export interface ChatInputEstimateOpts {+ system?: string;+ messages?: Array<{ content?: unknown }>;+ tools?: Array<{ name?: string; description?: string; inputSchema?: unknown }>;+}++export const CHAT_INPUT_CHARS_PER_TOKEN = 4;++function jsonChars(value: unknown): number {+ if (value === undefined || value === null) return 0;+ if (typeof value === 'string') return value.length;+ try {+ return JSON.stringify(value)?.length ?? 0;+ } catch {+ return String(value).length;+ }+}++export function estimateChatInputTokens(opts: ChatInputEstimateOpts): number {+ let chars = (opts.system ?? '').length;+ for (const m of opts.messages ?? []) {+ if (typeof m.content === 'string') {+ chars += m.content.length;+ continue;+ }+ if (!Array.isArray(m.content)) continue;+ for (const block of m.content as Array<Record<string, unknown>>) {+ if (typeof block?.text === 'string') chars += block.text.length;+ if (block?.type === 'tool-call') chars += jsonChars(block.input) + jsonChars(block.toolName);+ if (block?.type === 'tool-result') chars += jsonChars(block.output);+ }+ }+ for (const tool of opts.tools ?? []) {+ chars += jsonChars(tool.name) + jsonChars(tool.description) + jsonChars(tool.inputSchema);+ }+ return Math.ceil(chars / CHAT_INPUT_CHARS_PER_TOKEN);+}diff --git a/src/core/ai/chat-usage.ts b/src/core/ai/chat-usage.tsindex 62d25298bc..9e37f91092 100644--- a/src/core/ai/chat-usage.ts+++ b/src/core/ai/chat-usage.ts@@ -30,7 +30,7 @@*/import { AsyncLocalStorage } from 'node:async_hooks';-import { canonicalLookup } from '../model-pricing.ts';+import { canonicalLookup, priceAtPromptSize } from '../model-pricing.ts';import { priceFor, type PricingOverrides } from '../budget/reservation-cost.ts';export interface ChatUsageRecord {@@ -127,10 +127,13 @@ export function estimateChatCostUsd(cache_write_tokens?: number;},): number | null {- const p = canonicalLookup(model);- if (!p) return null;+ const row = canonicalLookup(model);+ if (!row) return null;const cacheRead = usage.cache_read_tokens ?? 0;const cacheWrite = usage.cache_write_tokens ?? 0;+ // #6448 item 1: the prompt size that selects a long-prompt tier is the+ // whole prompt — uncached input plus both cache buckets.+ const p = priceAtPromptSize(row, usage.input_tokens + cacheRead + cacheWrite);return ((usage.input_tokens * p.input +usage.output_tokens * p.output +diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex fbe8e98a13..821a174f3c 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -37,6 +37,7 @@ import { DEFAULT_CHARS_PER_TOKEN, DEFAULT_SAFETY_FACTOR, embedRequestMaxInputTokexport { splitByTokenBudget, capBatchItems, NO_BATCH_CAP_SUB_BATCH_ITEMS } from './embed-batch-plan.ts';import { BudgetTracker, type BudgetReservation } from '../budget/budget-tracker.ts';import { failedCallUsage, recordOnTracker } from './budget-record.ts';+import { estimateChatInputTokens } from './chat-input-estimate.ts';import { chatWithFallback, normalizeChatFallbackChain } from './chat-fallback.ts';import { applyThinkingOff, thinkingOffMaxOutputTokens } from './thinking-off.ts';import type {@@ -2757,23 +2758,6 @@ export function getCurrentBudgetTracker(): BudgetTracker | null {return __budgetStore.getStore() ?? null;}-/** Internal helper: estimate input tokens from messages + system. Heuristic only- * (~4 chars/token); cap math is best-effort because we pre-flight reservation- * before the SDK has counted anything. */-function estimateChatInputTokens(opts: { system?: string; messages?: Array<{ content?: unknown }> }): number {- let chars = (opts.system ?? '').length;- for (const m of opts.messages ?? []) {- if (typeof m.content === 'string') chars += m.content.length;- else if (Array.isArray(m.content)) {- for (const block of m.content) {- const t = (block as { text?: unknown }).text;- if (typeof t === 'string') chars += t.length;- }- }- }- return Math.ceil(chars / 4);-}-// ---- Chat (commit 1) ----/**diff --git a/src/core/budget/reservation-cost.ts b/src/core/budget/reservation-cost.tsindex 9e3f2198bc..03916b0d13 100644--- a/src/core/budget/reservation-cost.ts+++ b/src/core/budget/reservation-cost.ts@@ -7,7 +7,7 @@*/import { ANTHROPIC_PRICING, type ModelPricing } from '../anthropic-pricing.ts';-import { canonicalLookup } from '../model-pricing.ts';+import { canonicalLookup, priceAtPromptSize } from '../model-pricing.ts';import { lookupEmbeddingPrice } from '../embedding-pricing.ts';import { splitProviderModelId } from '../model-id.ts';import { resolveRecipe } from '../ai/model-resolver.ts';@@ -226,8 +226,14 @@ export function usageCostUsd(// #4312: operator overrides win — the operator owns their bill (negotiated// rates, proxy routes the shipped tables can't know about). Missing both →// null, and the TX2 fail-closed contract in reserve() still applies.- const p = priceFor(modelId, kind, overrides)?.pricing;- if (!p) return null;+ const row = priceFor(modelId, kind, overrides)?.pricing;+ if (!row) return null;+ // #6448 item 1: a prompt past the model's long-prompt threshold bills the+ // WHOLE request at the upper tier. `inputTokens` is the prompt size — the+ // pre-flight estimate at reserve(), the provider's total input (cache+ // included) at record() — so a reservation whose estimate crosses the+ // threshold is held at the upper tariff (conservative) and settles exact.+ const p = priceAtPromptSize(row, inputTokens);return (inputTokens / 1_000_000) * p.input + (outputTokens / 1_000_000) * p.output;}diff --git a/src/core/model-pricing.ts b/src/core/model-pricing.tsindex 3285aaacc6..c4cfd5b09e 100644--- a/src/core/model-pricing.ts+++ b/src/core/model-pricing.ts@@ -57,6 +57,53 @@ export interface ModelPricing {* absent (under-estimate for writes; documented, not silent).*/cache_write?: number;+ /**+ * #6448 item 1 — long-prompt tier. Some providers bill the WHOLE request at+ * higher rates once its prompt exceeds `threshold_tokens` input tokens+ * (Anthropic's long-context pricing: Haiku 5.5 bills 5x on input, cache+ * and output above 100K). `priceAtPromptSize()` selects this tier from the+ * request's total input tokens (cache reads and writes included; they are+ * part of the prompt). Absent when the provider publishes one flat rate.+ */+ long_prompt?: LongPromptTier;+}++/** The rates a request pays once its prompt exceeds `threshold_tokens` (strictly greater). */+export interface LongPromptTier {+ threshold_tokens: number;+ input: number;+ output: number;+ cache_read?: number;+ cache_write?: number;+}++/**+ * Anthropic's long-context boundary: a prompt of MORE than 100,000 input+ * tokens bills at the long-prompt tier (platform.claude.com/docs/en/about-claude/pricing,+ * checked 2026-10-11). Exactly 100,000 is still the base tier.+ */+export const ANTHROPIC_LONG_PROMPT_THRESHOLD_TOKENS = 100_000;++/**+ * The flat rates a request of `inputTokens` prompt tokens pays: the+ * `long_prompt` tier when the prompt exceeds its threshold, else the base+ * row. Returns a tier-free `ModelPricing` so every consumer prices with one+ * `input`/`output`/`cache_*` set and cannot apply the base rate to part of a+ * long prompt. A missing or non-finite size prices at the base tier.+ */+export function priceAtPromptSize(pricing: ModelPricing, inputTokens: number | null | undefined): ModelPricing {+ const tier = pricing.long_prompt;+ if (!tier || typeof inputTokens !== 'number' || !Number.isFinite(inputTokens) || inputTokens <= tier.threshold_tokens) {+ if (!tier) return pricing;+ const { long_prompt: _omit, ...base } = pricing;+ return base;+ }+ return {+ input: tier.input,+ output: tier.output,+ ...(tier.cache_read !== undefined ? { cache_read: tier.cache_read } : {}),+ ...(tier.cache_write !== undefined ? { cache_write: tier.cache_write } : {}),+ };}/** Anthropic prompt-cache multipliers (verified 2026-08 against published@@ -118,10 +165,16 @@ export const CANONICAL_PRICING: Record<string, ModelPricing> = {'anthropic:claude-sonnet-5': anthro( 2.00, 10.00),'anthropic:claude-sonnet-4-6': anthro( 3.00, 15.00),// Haiku 5.5: $0.10 in / $0.50 out for prompts up to 100,000 tokens- // (platform.claude.com/docs/en/about-claude/pricing, checked 2026-10-08).- // Longer prompts bill 5x ($0.50 / $2.50); that tier is not modeled. The- // default facts extraction model on Anthropic-keyed installs.- 'anthropic:claude-haiku-5-5': anthro( 0.10, 0.50),+ // (platform.claude.com/docs/en/about-claude/pricing, checked 2026-10-11).+ // Longer prompts bill 5x on every rate ($0.50 in / $0.625 5m cache write /+ // $0.05 cache read / $2.50 out) — the `long_prompt` tier, selected per+ // request by priceAtPromptSize() (#6448 item 1). The 1h cache-write rate+ // ($0.20 / $1.00) stays unmodeled. The default facts extraction model on+ // Anthropic-keyed installs.+ 'anthropic:claude-haiku-5-5': {+ ...anthro( 0.10, 0.50),+ long_prompt: { threshold_tokens: ANTHROPIC_LONG_PROMPT_THRESHOLD_TOKENS, ...anthro( 0.50, 2.50) },+ },// Haiku 4.5 — both the dateless canonical id and the dated snapshot.'anthropic:claude-haiku-4-5': anthro( 1.00, 5.00),'anthropic:claude-haiku-4-5-20251001': anthro( 1.00, 5.00),diff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.jsonindex 544c47c9ea..03991aa022 100644--- a/test/fixtures/goldens/exports/runtime.json+++ b/test/fixtures/goldens/exports/runtime.json@@ -545,8 +545,10 @@"ANTHROPIC_CACHE_READ_MULT","ANTHROPIC_CACHE_READ_MULT_OVERRIDES","ANTHROPIC_CACHE_WRITE_5M_MULT",+ "ANTHROPIC_LONG_PROMPT_THRESHOLD_TOKENS","CANONICAL_PRICING",- "canonicalLookup"+ "canonicalLookup",+ "priceAtPromptSize"],"./core/skillopt": ["loadHeldOut",diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 2691c0f4fc..644f08ac14 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -2962,6 +2962,13 @@"1.25"]},+ {+ "kind": "variable",+ "name": "ANTHROPIC_LONG_PROMPT_THRESHOLD_TOKENS",+ "signature": [+ "100000"+ ]+ },{"kind": "variable","name": "CANONICAL_PRICING",@@ -2975,6 +2982,18 @@"cache_read?: number | undefined","cache_write?: number | undefined","input: number",+ "output: number",+ "threshold_tokens: number"+ ],+ "name": "LongPromptTier"+ },+ {+ "kind": "interface",+ "members": [+ "cache_read?: number | undefined",+ "cache_write?: number | undefined",+ "input: number",+ "long_prompt?: LongPromptTier | undefined","output: number"],"name": "ModelPricing"@@ -2985,6 +3004,13 @@"signature": ["(modelId: string | null | undefined) => ModelPricing | undefined"]+ },+ {+ "kind": "function",+ "name": "priceAtPromptSize",+ "signature": [+ "(pricing: ModelPricing, inputTokens: number | null | undefined) => ModelPricing"+ ]}],"./core/skillopt": [diff --git a/test/model-pricing-long-context-tier.test.ts b/test/model-pricing-long-context-tier.test.tsnew file mode 100644index 0000000000..902c956007--- /dev/null+++ b/test/model-pricing-long-context-tier.test.ts@@ -0,0 +1,103 @@+/**+ * #6448 item 1 (fix wave 15 P6.1b) — long-prompt pricing tier.+ *+ * Haiku 5.5 bills every rate 5x once a prompt exceeds 100,000 input tokens.+ * The canonical row carries that tier; `priceAtPromptSize` selects it per+ * request; `usageCostUsd` / `reservationCostUsd` (and so the budget tracker's+ * reserve and record) and `estimateChatCostUsd` (the durable chat ledger)+ * price the WHOLE prompt at the upper tier past the threshold. The pre-flight+ * estimate counts tool definitions and tool-result output, so a tool-heavy+ * prompt that crosses the threshold is reserved at the tier it will bill at.+ * No live call anywhere here.+ */+import { describe, expect, test } from 'bun:test';+import { mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { reservationCostUsd, usageCostUsd } from '../src/core/budget/reservation-cost.ts';+import { BudgetExhausted, BudgetTracker } from '../src/core/budget/budget-tracker.ts';+import { estimateChatCostUsd } from '../src/core/ai/chat-usage.ts';++// Behaviour only through the pre-existing cost APIs, so this file runs (and+// fails for the wrong dollar amounts, never an import) against master.+// The tier row and `priceAtPromptSize` / `estimateChatInputTokens` helpers are+// pinned in test/model-pricing-tier-helpers.test.ts.+const HAIKU = 'anthropic:claude-haiku-5-5';+const T = 100_000;+const auditPath = () => join(mkdtempSync(join(tmpdir(), 'budget-tier-')), 'audit.jsonl');++describe('usageCostUsd / reservationCostUsd apply the tier to the whole prompt', () => {+ test('threshold: 99,999 in + 1,000 out bills base; 100,001 bills the 5x tier', () => {+ expect(usageCostUsd(HAIKU, T - 1, 1_000, 'chat')).toBeCloseTo((99_999 * 0.10 + 1_000 * 0.50) / 1e6, 12);+ expect(usageCostUsd(HAIKU, T, 1_000, 'chat')).toBeCloseTo((100_000 * 0.10 + 1_000 * 0.50) / 1e6, 12);+ // Astra's probe: $0.0105 before the fix; the declared tariff gives $0.0525005.+ expect(usageCostUsd(HAIKU, T + 1, 1_000, 'chat')).toBeCloseTo(0.0525005, 10);+ expect(reservationCostUsd(HAIKU, 'chat', T + 1, 1_000)).toBeCloseTo(0.0525005, 10);+ });++ test('bare and dated forms of the id price the same tier', () => {+ expect(usageCostUsd('claude-haiku-5-5', T + 1, 0, 'chat')).toBeCloseTo((T + 1) * 0.50 / 1e6, 12);+ expect(usageCostUsd('anthropic/claude-haiku-5-5', T + 1, 0, 'chat')).toBeCloseTo((T + 1) * 0.50 / 1e6, 12);+ });++ test('models without a tier are unchanged at any size', () => {+ expect(usageCostUsd('anthropic:claude-sonnet-5-5', 400_000, 1_000, 'chat')).toBeCloseTo((400_000 * 2 + 1_000 * 10) / 1e6, 12);+ });+});++describe('budget tracker: the cap admits long prompts at their real tariff', () => {+ test('a 100,001-token Haiku call is refused under a $0.03 cap (it was admitted at $0.0105)', () => {+ const tracker = new BudgetTracker({ maxCostUsd: 0.03, label: 'tier-test', auditPath: auditPath() });+ let thrown: unknown;+ try {+ tracker.reserve({ modelId: HAIKU, estimatedInputTokens: T + 1, maxOutputTokens: 1_000, kind: 'chat' });+ } catch (e) { thrown = e; }+ expect(thrown).toBeInstanceOf(BudgetExhausted);+ expect((thrown as BudgetExhausted).reason).toBe('cost');+ // The same prompt one token under the threshold is admitted.+ expect(tracker.reserve({ modelId: HAIKU, estimatedInputTokens: T - 1, maxOutputTokens: 1_000, kind: 'chat' })).toBeDefined();+ });++ test('concurrent reservations: tiers are per request, and the second long prompt is refused by the held projection', () => {+ const tracker = new BudgetTracker({ maxCostUsd: 0.06, label: 'tier-test', auditPath: auditPath() });+ // Two 60K prompts: each below the threshold, both admitted at base even+ // though their SUM crosses 100K — the tier is a property of one request.+ const a = tracker.reserve({ modelId: HAIKU, estimatedInputTokens: 60_000, maxOutputTokens: 0, kind: 'chat' });+ const b = tracker.reserve({ modelId: HAIKU, estimatedInputTokens: 60_000, maxOutputTokens: 0, kind: 'chat' });+ expect(a).toBeDefined();+ expect(b).toBeDefined();+ tracker.release(a);+ tracker.release(b);+ // Two 100,001-token prompts at $0.0525 each: the first is held, the+ // second must not fit under the remaining $0.0075.+ const first = tracker.reserve({ modelId: HAIKU, estimatedInputTokens: T + 1, maxOutputTokens: 1_000, kind: 'chat' });+ expect(first).toBeDefined();+ expect(() => tracker.reserve({ modelId: HAIKU, estimatedInputTokens: T + 1, maxOutputTokens: 1_000, kind: 'chat' }))+ .toThrow(BudgetExhausted);+ });++ test('record() prices the provider-reported total (cache included) at the tier', () => {+ const tracker = new BudgetTracker({ maxCostUsd: 1, label: 'tier-test', auditPath: auditPath() });+ const r = tracker.reserve({ modelId: HAIKU, estimatedInputTokens: 1_000, maxOutputTokens: 100, kind: 'chat' });+ // The SDK's inputTokens is input + cache_creation + cache_read: a prompt+ // served mostly from cache is still a long prompt for tier selection.+ tracker.record({ modelId: HAIKU, reservation: r, inputTokens: T + 1, outputTokens: 1_000 });+ expect(tracker.snapshot().cumulativeCostUsd).toBeCloseTo(0.0525005, 10);+ });+});++describe('durable chat ledger: estimateChatCostUsd', () => {+ test('cache buckets count toward the prompt size and bill at the tier cache rates', () => {+ // 10,001 uncached + 90,000 cache reads = 100,001 prompt tokens → tier.+ const usd = estimateChatCostUsd(HAIKU, { input_tokens: 10_001, output_tokens: 1_000, cache_read_tokens: 90_000 });+ expect(usd).toBeCloseTo((10_001 * 0.50 + 90_000 * 0.05 + 1_000 * 2.50) / 1e6, 12);+ // One token less in cache: base tier on every bucket.+ const base = estimateChatCostUsd(HAIKU, { input_tokens: 10_001, output_tokens: 1_000, cache_read_tokens: 89_999 });+ expect(base).toBeCloseTo((10_001 * 0.10 + 89_999 * 0.01 + 1_000 * 0.50) / 1e6, 12);+ });++ test('cache writes count toward the prompt size too', () => {+ const usd = estimateChatCostUsd(HAIKU, { input_tokens: 1, output_tokens: 0, cache_write_tokens: T });+ expect(usd).toBeCloseTo((1 * 0.50 + T * 0.625) / 1e6, 12);+ });+});diff --git a/test/model-pricing-tier-helpers.test.ts b/test/model-pricing-tier-helpers.test.tsnew file mode 100644index 0000000000..cf499f4efe--- /dev/null+++ b/test/model-pricing-tier-helpers.test.ts@@ -0,0 +1,83 @@+/**+ * #6448 item 1 (fix wave 15 P6.1b) — the long-prompt tier row and its two+ * helpers: `priceAtPromptSize` (model-pricing.ts) and the tool-aware+ * `estimateChatInputTokens` (ai/chat-input-estimate.ts). Behaviour through the+ * cost APIs is pinned in test/model-pricing-long-context-tier.test.ts.+ */+import { describe, expect, test } from 'bun:test';+import {+ ANTHROPIC_LONG_PROMPT_THRESHOLD_TOKENS,+ CANONICAL_PRICING,+ canonicalLookup,+ priceAtPromptSize,+} from '../src/core/model-pricing.ts';+import { reservationCostUsd } from '../src/core/budget/reservation-cost.ts';+import { estimateChatInputTokens } from '../src/core/ai/chat-input-estimate.ts';++const HAIKU = 'anthropic:claude-haiku-5-5';+const T = ANTHROPIC_LONG_PROMPT_THRESHOLD_TOKENS;++describe('canonical row: Haiku 5.5 long-prompt tier', () => {+ const expectRates = (p: { input: number; output: number; cache_read?: number; cache_write?: number }, want: [number, number, number, number]) => {+ expect(p.input).toBeCloseTo(want[0], 12);+ expect(p.output).toBeCloseTo(want[1], 12);+ expect(p.cache_read).toBeCloseTo(want[2], 12);+ expect(p.cache_write).toBeCloseTo(want[3], 12);+ };+ const BASE: [number, number, number, number] = [0.10, 0.50, 0.01, 0.125];+ const TIER: [number, number, number, number] = [0.50, 2.50, 0.05, 0.625];++ test('the tier is declared at 5x every base rate above 100,000 tokens', () => {+ const row = CANONICAL_PRICING[HAIKU]!;+ expectRates(row, BASE);+ expect(row.long_prompt?.threshold_tokens).toBe(100_000);+ expectRates(row.long_prompt!, TIER);+ });++ test('priceAtPromptSize: 99,999 and exactly 100,000 are base; 100,001 is the tier (tier-free result)', () => {+ const row = canonicalLookup(HAIKU)!;+ expectRates(priceAtPromptSize(row, T - 1), BASE);+ expectRates(priceAtPromptSize(row, T), BASE);+ expect(priceAtPromptSize(row, T).long_prompt).toBeUndefined();+ expectRates(priceAtPromptSize(row, T + 1), TIER);+ expect(priceAtPromptSize(row, T + 1).long_prompt).toBeUndefined();+ expect(Object.keys(priceAtPromptSize(row, T + 1)).sort()).toEqual(['cache_read', 'cache_write', 'input', 'output']);+ });++ test('a row without a tier is returned as is, and a missing size prices at base', () => {+ const sonnet = canonicalLookup('anthropic:claude-sonnet-5-5')!;+ expect(priceAtPromptSize(sonnet, 5_000_000)).toBe(sonnet);+ expect(priceAtPromptSize(canonicalLookup(HAIKU)!, null).input).toBe(0.10);+ expect(priceAtPromptSize(canonicalLookup(HAIKU)!, Number.NaN).input).toBe(0.10);+ });+});++describe('pre-flight estimate counts tool schemas and tool results', () => {+ const system = 'x'.repeat(400);+ const schema = { type: 'object', properties: { slug: { type: 'string', description: 'y'.repeat(2_000) } } };++ test('tool definitions add to the estimate', () => {+ const without = estimateChatInputTokens({ system, messages: [{ content: 'hi' }] });+ const withTools = estimateChatInputTokens({ system, messages: [{ content: 'hi' }], tools: [{ name: 'put_page', description: 'write', inputSchema: schema }] });+ expect(without).toBe(Math.ceil(402 / 4));+ expect(withTools).toBeGreaterThanOrEqual(without + Math.floor(JSON.stringify(schema).length / 4));+ });++ test('tool-result output and tool-call input in the history add to the estimate; text blocks still count', () => {+ const big = { rows: Array.from({ length: 200 }, (_, i) => ({ i, text: 'z'.repeat(50) })) };+ const textOnly = estimateChatInputTokens({ messages: [{ content: [{ type: 'text', text: 'abcd'.repeat(10) }] }] });+ expect(textOnly).toBe(10);+ const withResult = estimateChatInputTokens({ messages: [+ { content: [{ type: 'tool-call', toolCallId: 't1', toolName: 'search', input: { q: 'q'.repeat(400) } }] },+ { content: [{ type: 'tool-result', toolCallId: 't1', toolName: 'search', output: big }] },+ ] });+ expect(withResult).toBeGreaterThanOrEqual(Math.floor((JSON.stringify(big).length + 400) / 4));+ });++ test('a long tool-heavy prompt crosses the threshold the way it will bill', () => {+ const output = 'w'.repeat(4 * (T + 10));+ const est = estimateChatInputTokens({ messages: [{ content: [{ type: 'tool-result', toolCallId: 't', toolName: 'read', output }] }] });+ expect(est).toBeGreaterThan(T);+ expect(reservationCostUsd(HAIKU, 'chat', est, 1_000)).toBeCloseTo((est * 0.50 + 1_000 * 2.50) / 1e6, 12);+ });+});diff --git a/test/model-pricing.test.ts b/test/model-pricing.test.tsindex df131fb2ab..28ee9f5600 100644--- a/test/model-pricing.test.ts+++ b/test/model-pricing.test.ts@@ -99,6 +99,30 @@ describe('CANONICAL_PRICING — table integrity', () => {}});+ // #6448 item 1: a long-prompt tier is an UPPER tier (every rate at or above+ // the base row) with a positive threshold, and an anthropic: tier derives+ // its cache rates from ITS input rate with the same multipliers as the row.+ test('every long_prompt tier is finite, above its base row, and derives its cache rates like the row', () => {+ let tiers = 0;+ for (const [key, p] of Object.entries(CANONICAL_PRICING)) {+ const tier = p.long_prompt;+ if (!tier) continue;+ tiers++;+ expect(Number.isFinite(tier.threshold_tokens) && tier.threshold_tokens > 0).toBe(true);+ expect(tier.input).toBeGreaterThanOrEqual(p.input);+ expect(tier.output).toBeGreaterThanOrEqual(p.output);+ if (key.startsWith('anthropic:')) {+ const mult = ANTHROPIC_CACHE_READ_MULT_OVERRIDES[key] ?? ANTHROPIC_CACHE_READ_MULT;+ expect(tier.cache_read).toBeCloseTo(tier.input * mult, 10);+ expect(tier.cache_write).toBeCloseTo(tier.input * ANTHROPIC_CACHE_WRITE_5M_MULT, 10);+ } else {+ expect(tier.cache_read).toBeUndefined();+ expect(tier.cache_write).toBeUndefined();+ }+ }+ expect(tiers).toBeGreaterThanOrEqual(1); // Haiku 5.5+ });+test('every cache-read multiplier override names a canonical row with matching cache_read', () => {for (const [key, mult] of Object.entries(ANTHROPIC_CACHE_READ_MULT_OVERRIDES)) {const p = CANONICAL_PRICING[key];