Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(gateway): embed spend records bank provider-reported usage.tokens (#5642)
garrytan5d2997e14d72
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 25f497ce22..bcb40929f4 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -11,7 +11,7 @@ src/commands/extract-conversation-facts.ts 2146 ratchet grown v0.46.x per-providsrc/commands/extract.ts 2623 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference)src/commands/jobs.ts 658 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2)src/commands/serve-http.ts 915 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts-src/core/ai/gateway.ts 4365 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state)+src/core/ai/gateway.ts 4391 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge)src/commands/sync.ts 473 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals)src/core/cycle.ts 3192 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +3 #5536: keyless embed phase clean-skips when embedding_disabled is setsrc/core/cycle/synthesize.ts 3293 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option)diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex c36c2a43de..e38b4b64ba 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -1592,10 +1592,17 @@ export async function embed(texts: string[], opts?: EmbedOpts): Promise<Float32Aconst allEmbeddings: Float32Array[] = [];let _embedThrew = false;+ // Provider-reported input tokens summed across sub-batches; null as soon as+ // any sub-batch's provider did not report (all-or-nothing: a partial sum+ // would undercharge the budget while looking measured).+ let reportedTokens: number | null = 0;try {for (const batch of batches) {const result = await embedSubBatch(batch, model, providerOpts, expected, recipe, modelId, opts);- allEmbeddings.push(...result);+ allEmbeddings.push(...result.embeddings);+ reportedTokens = reportedTokens !== null && result.reportedTokens !== null+ ? reportedTokens + result.reportedTokens+ : null;}return screenEmbeddings(truncated, sent, allEmbeddings, `${recipe.id}:${modelId}`);} catch (err) {@@ -1603,22 +1610,25 @@ export async function embed(texts: string[], opts?: EmbedOpts): Promise<Float32Athrow err;} finally {if (tracker) {- // Embed token usage is not surfaced by the AI SDK shape we use; charge- // based on the truncated input character count using the recipe's- // chars-per-token. On failure, A3 amended says charge the pessimistic- // estimate too — embed has no output side, so the input estimate IS- // the worst case.+ // Charge what the provider reported (embedMany surfaces usage.tokens)+ // when every sub-batch reported it; otherwise fall back to the+ // chars-per-token estimate over the truncated input. On failure, A3+ // amended says charge the pessimistic estimate — embed has no output+ // side, so the input estimate IS the worst case.+ const measured = !_embedThrew && reportedTokens !== null && reportedTokens > 0+ ? reportedTokens+ : null;const charsPerToken = recipe.touchpoints?.embedding?.chars_per_token ?? DEFAULT_CHARS_PER_TOKEN;const totalChars = truncated.reduce((s, t) => s + t.length, 0);recordOnTracker(tracker, {modelId: `${recipe.id}:${modelId}`,requestedModelId: resolveTarget,- inputTokens: Math.ceil(totalChars / Math.max(charsPerToken, 1)),+ inputTokens: measured ?? Math.ceil(totalChars / Math.max(charsPerToken, 1)),outputTokens: 0,embeddingDims: expected,kind: 'embed',label: _embedThrew ? 'gateway.embed.failed' : 'gateway.embed',- estimated: true,+ estimated: measured === null,});}}@@ -1692,6 +1702,11 @@ export function __getShrinkStateForTests(recipeId: string): ShrinkEntry | undefi/*** Embed a single sub-batch with automatic halving on token-limit errors.* If the batch is already at MIN_SUB_BATCH and still fails, throws.+ *+ * `reportedTokens` is the provider's usage.tokens for this sub-batch (summed+ * across halves when the batch split), or null when the provider did not+ * report usage — the caller's budget record falls back to the chars-per-token+ * estimate in that case.*/async function embedSubBatch(texts: string[],@@ -1701,7 +1716,7 @@ async function embedSubBatch(recipe: Recipe,modelId: string,opts?: EmbedOpts,-): Promise<Float32Array[]> {+): Promise<{ embeddings: Float32Array[]; reportedTokens: number | null }> {try {const callTransport = () => invokeAI({ operation: 'gateway.embed', kind: 'embedding', model: `${recipe.id}:${modelId}`,maxInputTokens: embedRequestMaxInputTokens(texts, recipe, modelId), maxOutputTokens: 0 }, () => _embedTransport({@@ -1742,7 +1757,13 @@ async function embedSubBatch(}recordSubBatchSuccess(recipe);- return result.embeddings.map((e: number[]) => new Float32Array(e));+ const usageTokens = (result as { usage?: { tokens?: unknown } }).usage?.tokens;+ return {+ embeddings: result.embeddings.map((e: number[]) => new Float32Array(e)),+ reportedTokens: typeof usageTokens === 'number' && Number.isFinite(usageTokens) && usageTokens > 0+ ? usageTokens+ : null,+ };} catch (err) {if (isAIInvocationPolicyError(err)) throw err;// On token-limit error, tighten the recipe's effective safety factor@@ -1753,7 +1774,12 @@ async function embedSubBatch(const mid = Math.ceil(texts.length / 2);const left = await embedSubBatch(texts.slice(0, mid), model, providerOpts, expectedDims, recipe, modelId, opts);const right = await embedSubBatch(texts.slice(mid), model, providerOpts, expectedDims, recipe, modelId, opts);- return [...left, ...right];+ return {+ embeddings: [...left.embeddings, ...right.embeddings],+ reportedTokens: left.reportedTokens !== null && right.reportedTokens !== null+ ? left.reportedTokens + right.reportedTokens+ : null,+ };}reportEmbeddingAuthFailure(recipe, err);throw normalizeAIError(err, `embed(${recipe.id}:${modelId})`, redactKeys);diff --git a/test/ai/gateway-ledger-records.serial.test.ts b/test/ai/gateway-ledger-records.serial.test.tsindex 41a8756e59..d9055cd27c 100644--- a/test/ai/gateway-ledger-records.serial.test.ts+++ b/test/ai/gateway-ledger-records.serial.test.ts@@ -96,16 +96,18 @@ describe('chat() record site', () => {});describe('embed() record site', () => {- test('char-estimated tokens -> estimated embedding row with the requested model', async () => {+ test('provider-reported tokens -> measured embedding row with the requested model', async () => {configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 8, env: { OPENAI_API_KEY: 'sk-test' } });__setEmbedTransportForTests((async (args: { values: string[] }) => ({embeddings: args.values.map(() => Array.from({ length: 8 }, () => 0.1)),usage: { tokens: 3 },})) as never);await withBudgetTracker(tracker, () => embed(['alpha beta', 'gamma']));+ // The stub reports usage.tokens, so the record banks EXACTLY that count+ // (not the chars-per-token estimate) and the row reads 'measured'.expect(tracker.snapshot().models).toEqual([expect.objectContaining({requested_model: 'openai:text-embedding-3-small', model: 'openai:text-embedding-3-small',- touchpoint: 'embedding', calls: 1, failed_calls: 0, cost_basis: 'estimated',+ touchpoint: 'embedding', calls: 1, failed_calls: 0, cost_basis: 'measured', input_tokens: 3,})]);});});diff --git a/test/embed-budget-provider-tokens.test.ts b/test/embed-budget-provider-tokens.test.tsnew file mode 100644index 0000000000..4c0c4bb59e--- /dev/null+++ b/test/embed-budget-provider-tokens.test.ts@@ -0,0 +1,97 @@+/**+ * embed() banks provider-reported tokens into the BudgetTracker record.+ *+ * The AI SDK's embedMany DOES surface usage (`usage.tokens`), but the+ * gateway's embed spend record ignored it and always charged+ * `ceil(chars / chars_per_token)` flagged `estimated` — the "not surfaced by+ * the AI SDK shape" comment had gone stale. The char heuristic misprices any+ * batch whose token density differs from the recipe constant (dense unicode —+ * Vietnamese diacritics, CJK — tokenizes at a fraction of the assumed+ * chars-per-token, so real spend lands a multiple ABOVE the estimate; terse+ * ASCII lands below it).+ *+ * Pins (transport stubbed at the __setEmbedTransportForTests seam):+ * - provider reports usage.tokens → the ledger row carries EXACTLY that+ * count, cost_basis 'measured' (fails pre-fix: char estimate, 'estimated')+ * - provider omits usage → chars-per-token fallback, cost_basis 'estimated'+ * (unchanged behavior, pinned)+ * - reported tokens accumulate across calls on the ledger row+ */++import { describe, test, expect, afterEach } from 'bun:test';+import {+ configureGateway,+ resetGateway,+ embed,+ withBudgetTracker,+ __setEmbedTransportForTests,+} from '../src/core/ai/gateway.ts';+import { BudgetTracker } from '../src/core/budget/budget-tracker.ts';++const DIMS = 1024;++function configureVoyage() {+ configureGateway({+ embedding_model: 'voyage:voyage-4',+ embedding_dimensions: DIMS,+ env: { VOYAGE_API_KEY: 'sk-fake' },+ });+}++function stubTransport(opts: { tokens?: number }) {+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({+ embeddings: values.map(() => Array.from({ length: DIMS }, () => 0.1)),+ ...(opts.tokens !== undefined ? { usage: { tokens: opts.tokens } } : {}),+ })) as any);+}++function embedRow(tracker: BudgetTracker) {+ const rows = tracker.snapshot().models.filter(r => r.touchpoint === 'embedding');+ expect(rows.length).toBe(1);+ return rows[0];+}++afterEach(() => {+ __setEmbedTransportForTests(null);+ resetGateway();+});++describe('embed budget uses provider-reported usage.tokens', () => {+ test('reported usage is charged exactly, cost_basis measured', async () => {+ configureVoyage();+ // 40 chars of input; the char heuristic would charge a different number+ // than the provider's 137 for any plausible chars_per_token.+ stubTransport({ tokens: 137 });+ const tracker = new BudgetTracker({ label: 'embed-usage-test' });+ await withBudgetTracker(tracker, () => embed(['xin chào thế giới — đây là một câu dài']));+ const row = embedRow(tracker);+ expect(row.input_tokens).toBe(137);+ expect(row.cost_basis).toBe('measured');+ });++ test('missing usage falls back to the chars-per-token estimate, flagged estimated', async () => {+ configureVoyage();+ stubTransport({});+ const tracker = new BudgetTracker({ label: 'embed-estimate-test' });+ const text = 'a'.repeat(400);+ await withBudgetTracker(tracker, () => embed([text]));+ const row = embedRow(tracker);+ expect(row.cost_basis).toBe('estimated');+ expect(row.input_tokens).toBeGreaterThan(0); // heuristic, not provider truth+ expect(row.input_tokens).not.toBe(137);+ });++ test('reported tokens accumulate across calls', async () => {+ configureVoyage();+ stubTransport({ tokens: 50 });+ const tracker = new BudgetTracker({ label: 'embed-sum-test' });+ await withBudgetTracker(tracker, async () => {+ await embed(['first batch']);+ await embed(['second batch']);+ });+ const row = embedRow(tracker);+ expect(row.calls).toBe(2);+ expect(row.input_tokens).toBe(100);+ expect(row.cost_basis).toBe('measured');+ });+});