Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(embed): --max-usd prices with pricing.overrides (#6984)
time-attack266d33556a9b
diff --git a/src/commands/embed.ts b/src/commands/embed.tsindex 189c648d56..33af9272d3 100644--- a/src/commands/embed.ts+++ b/src/commands/embed.ts@@ -33,6 +33,7 @@ import { slog, serr } from '../core/console-prefix.ts';import { embedBudgetStopVerdict, noteEmbedBudgetStop } from '../core/embed-budget-stop.ts';import { embedCostCap, embedCostStopVerdict, noteEmbedCostStop } from '../core/embed-cost-cap.ts';import type { Authorization } from '../core/consent.ts';+import { loadPricingOverrides } from '../core/budget/budget-tracker.ts';import { filterOutEmbedSkipped, isEmbedSkipped } from '../core/embed-skip.ts';import { runSlidingPool } from '../core/worker-pool.ts';import { isAborted, anySignal, AbortError } from '../core/abort-check.ts';@@ -916,7 +917,7 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConfreturn 'argv' in held ? runEmbed(engine, held.argv, selectedConfig, consent) : held;}const authorization = consent?.authorization ?? null;- const costCap = args.includes('--dry-run') || args.includes('--background') ? null : embedCostCap(authorization?.cap_usd, authorization?.cap_source);+ const costCap = args.includes('--dry-run') || args.includes('--background') || authorization?.cap_usd == null ? null : embedCostCap(authorization.cap_usd, authorization.cap_source, await loadPricingOverrides(engine));if (args.includes('--images')) return (await import('../core/embed-stale-images.ts')).runEmbedStaleImagesCli(engine, args, costCap); // lazy: keeps import-file out of embed's graph// v0.36+ T7: --background submits via Minion queue, returns job_id to// stdout, exits. Same semantics in TTY and cron (D9).diff --git a/src/core/embed-cost-cap.ts b/src/core/embed-cost-cap.tsindex 25904e8e1b..36132e9385 100644--- a/src/core/embed-cost-cap.ts+++ b/src/core/embed-cost-cap.ts@@ -9,7 +9,7 @@* the CLI exits BUDGET_STOP_EXIT_CODE with the command that resumes.*/import type { CapSource } from './consent.ts';-import { BudgetExhausted, BudgetTracker } from './budget/budget-tracker.ts';+import { BudgetExhausted, BudgetTracker, type PricingOverrides } from './budget/budget-tracker.ts';import { withBudgetTracker } from './ai/gateway.ts';import { shellQuote } from './shell-quote.ts';@@ -29,10 +29,14 @@ export interface EmbedCostStopFields {resume_command?: string;}-/** Null when the authorization carries no finite positive cap (nothing to meter). */-export function embedCostCap(capUsd: number | null | undefined, capSource: CapSource | null | undefined): EmbedCostCap | null {+/**+ * Null when the authorization carries no finite positive cap (nothing to meter).+ * `pricingOverrides` is the brain's `pricing.overrides` (loadPricingOverrides),+ * so an operator-declared rate prices the run the same way a queued embed job does.+ */+export function embedCostCap(capUsd: number | null | undefined, capSource: CapSource | null | undefined, pricingOverrides?: PricingOverrides): EmbedCostCap | null {if (typeof capUsd !== 'number' || !Number.isFinite(capUsd) || capUsd <= 0) return null;- const tracker = new BudgetTracker({ maxCostUsd: capUsd, label: 'embed', ...(capSource ? { capSource } : {}) });+ const tracker = new BudgetTracker({ maxCostUsd: capUsd, label: 'embed', ...(capSource ? { capSource } : {}), ...(pricingOverrides ? { pricingOverrides } : {}) });const controller = new AbortController();let refusal: BudgetExhausted | null = null;// The refusal itself (cost, or a model with no price under a user cap) is kept for the verdict.diff --git a/src/core/held-embedding.ts b/src/core/held-embedding.tsindex 9600beda8a..e6f4198fa3 100644--- a/src/core/held-embedding.ts+++ b/src/core/held-embedding.ts@@ -35,6 +35,7 @@ import { quoteIdentifier } from './search/embedding-column.ts';import { embeddingWriteTarget } from './page-state/projections.ts';import { budgetRowAppliesFilter } from './page-size-policy.ts';import { reservationCostUsd } from './budget/reservation-cost.ts';+import { loadPricingOverrides } from './budget/budget-tracker.ts';import { estimatePageEmbedUsd, listBudgetLimitedPages } from './page-embedding-budget.ts';import {approvalAmount, approvalBasis, budgetLimitedPhrase, heldApproveAction, heldPreviewCommand, renderedCommand,@@ -207,7 +208,7 @@ export async function heldApprovalUsd(engine: BrainEngine, args: readonly stringconst unchanged = 'nothing ran: every hold and per-page cap is unchanged';if (await embedWouldSpend(engine)) {const model = getEmbeddingModel();- if (reservationCostUsd(model, 'embed', 1, 0) !== null) return maxUsd;+ if (reservationCostUsd(model, 'embed', 1, 0, await loadPricingOverrides(engine)) !== null) return maxUsd;const { noPricingFix, noPricingGuidance, noPricingMessage } = await import('./budget/no-pricing.ts');const guidance = noPricingGuidance(model, 'embed');throw opError('no_pricing', `[embed] ${noPricingMessage(guidance, { capUsd: maxUsd })} (${unchanged}.)`, 'Register the model\'s price, then re-run the approval.',diff --git a/test/embed-max-usd-metered.serial.test.ts b/test/embed-max-usd-metered.serial.test.tsindex ecdf7aac3d..00c58ac26d 100644--- a/test/embed-max-usd-metered.serial.test.ts+++ b/test/embed-max-usd-metered.serial.test.ts@@ -114,6 +114,28 @@ describe('embed --max-usd is metered', () => {expect(calls).toBe(1);});+ test('#6984: the cap prices with pricing.overrides (an operator rate replaces the shipped one)', async () => {+ await engine.setConfig('pricing.overrides', JSON.stringify({ 'openai:text-embedding-3-large': { pricePerMTok: 0.0001 } }));+ try {+ const { exit } = await cli(['--slugs', ...SLUGS, '--max-usd', '0.10']);+ expect(exit).toBe(0);+ expect(calls).toBe(SLUGS.length);+ expect(await embedded()).toEqual(SLUGS);+ } finally { await engine.unsetConfig('pricing.overrides'); }+ });++ test('#6984: a model priced only by pricing.overrides runs under a user cap instead of refusing no_pricing', async () => {+ configureGateway({ embedding_model: 'openrouter:qwen/qwen3-embedding-8b', embedding_dimensions: DIMS, env: { OPENROUTER_API_KEY: 'sk-or-test-fake' } });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => { calls++; return { embeddings: values.map(() => new Array(DIMS).fill(0.001)), usage: { tokens: 10 } }; }) as never);+ await engine.setConfig('pricing.overrides', JSON.stringify({ 'openrouter:qwen/qwen3-embedding-8b': { pricePerMTok: 0.01 } }));+ try {+ const { out, exit } = await cli(['--slugs', ...SLUGS, '--max-usd', '0.10']);+ expect(out).not.toContain('no_pricing');+ expect(exit).toBe(0);+ expect(await embedded()).toEqual(SLUGS);+ } finally { await engine.unsetConfig('pricing.overrides'); }+ });+test('a free provider needs no authorization and runs unmetered', async () => {configureGateway({ embedding_model: 'ollama:nomic-embed-text', embedding_dimensions: DIMS, env: {} });__setEmbedTransportForTests((async ({ values }: { values: string[] }) => { calls++; return { embeddings: values.map(() => new Array(DIMS).fill(0.001)), usage: { tokens: tokensPerCall } }; }) as never);@@ -143,4 +165,21 @@ describe('embed --stale --images --max-usd is metered', () => {expect(exit).toBe(BUDGET_STOP_EXIT_CODE);expect(fetches).toBe(1);});++ test('#6984: --images prices the cap with pricing.overrides too', async () => {+ let fetches = 0;+ globalThis.fetch = (async () => {+ fetches++;+ return new Response(JSON.stringify({ data: [{ embedding: Array.from({ length: 1024 }, () => 0.1) }], usage: { total_tokens: 1_000_000 } }), { status: 200, headers: { 'Content-Type': 'application/json' } });+ }) as unknown as typeof fetch;+ configureGateway({ embedding_model: 'voyage:voyage-multimodal-3', embedding_multimodal_model: 'voyage:voyage-multimodal-3', embedding_dimensions: 1024, env: { VOYAGE_API_KEY: 'test-key' } });+ await engine.executeRaw("UPDATE content_chunks SET embedding_image = NULL WHERE page_id IN (SELECT id FROM pages WHERE source_id = 'img')");+ await engine.setConfig('pricing.overrides', JSON.stringify({ 'voyage:voyage-multimodal-3': { pricePerMTok: 0.0001 } }));+ try {+ const { out, exit } = await withEnv({ GBRAIN_EMBEDDING_MULTIMODAL: 'true' }, () => cli(['--stale', '--images', '--source', 'img', '--max-usd', '0.10', '--json']));+ expect(JSON.parse(out.slice(out.search(/^\{/m)))).toMatchObject({ rebuilt: 2, failures: 0 });+ expect(exit).toBe(0);+ expect(fetches).toBe(2);+ } finally { await engine.unsetConfig('pricing.overrides'); }+ });});