Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(spend): a priced model with no context ceiling refuses as no_context_ceiling (#6990)

time-attack5f8d98136c11
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 030dd7d05e..58b9b62854 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -92,6 +92,7 @@ of making a duplicate.
| <a id="managed_pull_skipped"></a>`managed_pull_skipped` (cycle warn); doctor `sync_freshness` "upstream unknown" or "upstream N commit(s) ahead" | `managed_pull_skipped` | A managed brain never runs `git pull` inside a cycle: Git pull needs an explicit drained maintenance window, so an explicit `gbrain sync` without `--no-pull` is refused with `writer_coordinator_required`. An unattended cycle asked to pull (autopilot passes `pull: true`, `gbrain dream --pull`) instead syncs the checkout as it is and reports it: the sync phase result carries `details.upstream_refresh` (`pulled`, `failed`, `skipped_managed` or `not_requested`), and when the checkout tracks an upstream the phase is `warn` with `details.warning` (`code`, `cause`, `fix`, `docs`). Every sync also records the checkout's last upstream observation (the upstream commit, when it was last fetched or pushed, and how many upstream commits the synced commit lacks) in the source row. Doctor `sync_freshness` reports that separately from the local projection: a source with a `remote_url` whose observation is missing or older than 24 hours is "upstream unknown", and any source whose observation saw upstream commits it has not synced is "behind"; neither is reported fresh. `details.upstream_unknown_count` and `details.upstream_behind_count` count them. | `gbrain sources refresh <source>` (the printed `fix` fills in the source). It drains writes to the source's checkout, fast-forwards it to its upstream and runs the managed sync for every source bound to that checkout; see [worktree refresh refusals](#worktree-refresh-refusals) for what it can refuse. On a brain that is not managed, `gbrain sync --source <source>` pulls and records the observation. |
| <a id="managed_sync_flag_refused"></a>`managed_sync_flag_refused` (`detail` = the flag) | `managed_sync_flag_refused` | A managed source keeps every failed-receipt and ignored-file guard, so `gbrain sync --skip-failed` and `gbrain sync --include-gitignored` have no managed meaning. The refusal names the flag and comes before anything runs: at parse in `gbrain sync` (before a legacy ledger row is acknowledged or the cost gate runs, `--all` included), before the serve-delegation ladder looks for the serve's socket, and in the managed-sync guard that sync jobs, MCP `sync_brain` and the cycle reach. Nothing is admitted and no cursor is written. | Rerun the printed `fix` (the same command without the flag). A failed file is fixed and then retried by the plain `gbrain sync --source <source> --no-pull`; an ignored file syncs once it is committed and not ignored. `gbrain sync status --source <source> --json` shows the source's failures and holds. |
| <a id="facts_absorb_write_refused"></a>`facts_absorb_write_refused (<code>)`; `ingest_log` `write_refused: <code> …` | `facts_absorb_write_refused` | A durable `facts-absorb` job extracted facts but the write path refused to store them, for example `writer_coordinator_required` because the entity's Markdown file sits in a claimed canonical worktree before `sources writer activate`, or `permission_denied`, `invalid_params` or `writer_registration_required`. These refusals do not change on retry, so the job goes straight to `dead` on its first attempt instead of re-running inference; on a brain that is not yet activated, a job whose source root is a claimed worktree is refused before extraction starts, so it makes no model call; the `facts:absorb` row in `ingest_log` (and doctor `facts_extraction_health`) records `write_refused` with the real code, not a provider failure. Two outcomes are not refusals and are logged under their own reasons, which doctor never counts toward its threshold: `write_pending_accepted`, a facts write that was accepted and whose receipt is still queued, running or recovering when the job stopped waiting (the job waits up to 30 s, bounded by its deadline; the write commits later), and `write_deferred_unadmitted`, a canonical writer that was busy before anything was admitted (`writer_lock_unavailable`, no receipt; the job retries). Doctor warns about deferrals only when they persist (see the check's `gbrain sources writer status` fix). Doctor's incident count is a historical metric: it counts the `facts:absorb` rows of a rolling 24 h window, says when they age out, and keeps counting them after the cause is fixed and the job retried, so a warning there does not by itself mean anything is still broken; the threshold (`facts.absorb_warn_threshold`) is unchanged. The current state is the check's `jobs still dead` count: facts-absorb jobs that went dead or failed in the last 24 h and that no later job for the same page completed after, each named with `gbrain jobs retry <id>`. The source page itself was already saved. | Fix the named cause first: `gbrain sources writer status <source>`, then finish the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook) for a claimed worktree, or fix the grant. Then `gbrain jobs retry <job id>` (the error names the id). |
+| <a id="no_context_ceiling"></a>`no_context_ceiling` | `no_context_ceiling` | A queued job under a cost cap you set stopped before a provider call: the model has a registered price, but gbrain knows no context-token ceiling for it, so it cannot reserve the most one call could cost. OpenRouter models hit this, because that provider declares no context window per model. The message names the model, and the JSON `fix` asks you before it reruns the command without your cap. Re-registering the price does not help. | Choose one. Rerun the command without your cap (the `fix` command, which replaces `--max-usd` with `--yes`): the default cap applies and this model runs unmetered with a warning. Or keep your cap: look up the model's context window on the provider's model page (OpenRouter lists it as `context_length`) and give it to the brain-host operator. `gbrain jobs list --group <id> --json` shows the stopped job. |
| <a id="no_pricing"></a>`no_pricing` | `no_pricing` | A cost cap you set (`--max-cost`, `--max-usd`, `--max-cost-usd`, or an explicit cap in config such as `cycle.extract_atoms.budget_usd`) cannot be enforced, because gbrain has no price for the model the run was about to call. The run stops before that call. Under a default cap an unpriced model warns and runs instead. The message names the model, provider and kind, and JSON output carries the same guidance as fields: `code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope` and `docs`. | Look up the provider's current price for the model, for example by searching the web for its pricing page. A chat model needs USD per 1M input tokens and USD per 1M output tokens; an embedding or reranker model needs USD per 1M tokens. On the brain host, run `gbrain pricing set <model> --input <usd> --output <usd> --source <pricing-page-url>` (or `--rate <usd>`), then retry. An agent connected over MCP cannot register prices: give the command to the brain's operator. See [registering a model price](../operations/spend-controls.md#registering-a-model-price). |
| <a id="managed_raw_upload"></a>raw upload on a managed brain | `writer_coordinator_required` | `gbrain files upload-raw` of a small (git-storage) file whose `.raw/` destination is inside a managed canonical worktree. The persistence coordinator does not publish raw files yet, so the worktree refuses writes from outside it; starting a `gbrain serve` owner does not change that. The refusal comes before anything is created: no `.raw/` directory and no `files` row. With no storage backend, `file_upload` for such a page no longer suggests `upload-raw`. | Configure `storage` (supabase, s3 or local) in the gbrain config, then run the printed `gbrain files upload <file> --page <slug>`; check it with `gbrain files list <slug>`. |
| <a id="timeline_rows_would_be_removed"></a>`timeline_rows_would_be_removed` | `timeline_rows_would_be_removed` | A remote `put_page` (or a `put_pages` entry) has no Timeline section at all — no `<!-- timeline -->` sentinel and no `## Timeline` or `## History` heading — and would delete dated entries the page has, including rows `add_timeline_entry` added. `put_page` content replaces the whole page, so the omission must be explicit. Nothing was written. A section that is present but empty is a deliberate delete and is not refused; a local `gbrain put` without `--expected-revision` keeps the rows instead. | Re-read with `get_page include_content:true`, keep the Timeline section and resubmit with a new `request_id`; to remove every dated entry on purpose, resubmit the same content with `drop_timeline: true` (on put_pages, per entry). A successful write that deletes rows reports `timeline_rows_removed {count, earliest, latest, warning, fix}` (dates only); `get_versions` then `revert_version` restores them as new rows. |
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 73cbe6244e..d35c767e75 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -916,6 +916,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.307.0', text: 'A Codex connection installed with `gbrain connect --harness codex --install` (or `bootstrap harness`) now keeps Codex\'s own per-tool settings (`[mcp_servers.<name>.tools.<tool>]`, written when you pick "always allow") instead of refusing the next install or `--fresh-token` renewal with `configuration_conflict`: settings inside the gbrain-managed block are carried into the rewritten block, settings outside it stay where they are, and any other edit to the entry (its URL, headers or other keys) still refuses. Removing the connection refuses with `configuration_conflict` while such settings sit outside the block, naming the tables to delete, so the server is never left half-defined.' },
// #6796 (apply-migrations applied_pending_host_work).
{ since: '0.60.307.0', text: '`gbrain apply-migrations --list` now shows v0.53.0 as `applied_pending_host_work` instead of `applied` while its stored shared-skills report still names host work (a source\'s inventory, writer, projection or publication-policy stage, or a brain-level pending action), and no longer prints "All migrations up to date" for it; `--list --json` rows carry that status and an `applied_pending_host_work` array whose fix is the read-only `gbrain apply-migrations --migration 0.53.0 --dry-run --json` inventory. Scripts that match `applied` should accept both. `gbrain doctor` warns on `minions_migration` (`details.code: migration_host_work_pending`) until a later `gbrain apply-migrations --yes` re-check finds the work done. Unenrolled members (every new brain), sources that opted out and a declined migration are never reported.' },
+ { since: '0.60.307.0', text: 'A queued job under a cost cap you set that calls a model with a registered price but no known context-token ceiling (OpenRouter models) now stops with `no_context_ceiling` instead of `no_pricing`. The message says the price is already known; the fix asks before rerunning without your cap (`--yes` in place of `--max-usd`), or asks for the model\'s context size for the brain-host operator. Under a default or derived cap the warning names the missing ceiling. Nothing else changed: no provider call is made either way.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 4d928ac8b0..26ac58e526 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -416,6 +416,11 @@ export const CODES = {
missing_source_scope: { class: 'server', summary: "A remote tool call reached dispatch without a resolved source scope; the shared default source is refused." },
missing_source_value: { class: 'caller', summary: "A source flag was given without a value." },
models_strict_violation: { class: 'caller', summary: "A configured model is not allowed under models strict mode." },
+ no_context_ceiling: { class: 'unavailable', summary: "The model has a known price but no known context-token ceiling, so a user-set cost cap cannot bound one call; the job stopped before any provider call.",
+ why: "A user cap is enforced per provider attempt by reserving the most that attempt could cost: its input ceiling times the input price plus its output ceiling times the output price. Some providers (OpenRouter) declare no ceiling for their models, so the reservation has no bound even though the price is registered.",
+ docs: 'docs/guides/write-refusals.md#no_context_ceiling',
+ suggestion: "Do not retry unchanged and do not re-register the price. Ask the user whether to rerun without the user cap (the model then runs unmetered under the default cap), or to give the model's context size to the brain-host operator.",
+ fix: { argv: ['gbrain', 'pricing', 'list', '--json'], consent: [], actor: 'agent', why: 'Read-only: shows that the model already has a registered price, so the missing input is its context size.', requires_exclusive: false } },
no_pricing: { class: 'unavailable', summary: "gbrain has no price for the model, so a user-set cost cap cannot be enforced." },
no_refresh_token: { class: 'caller', summary: "Google connect credential error: no refresh token.", docs: 'docs/guides/google-connect.md#troubleshooting' },
no_routing_eval: { class: 'caller', summary: "The skill has no routing-eval rows to bootstrap a benchmark from." },
diff --git a/src/core/minions/delegated-spend.ts b/src/core/minions/delegated-spend.ts
index 1eaea338d2..ce7107a219 100644
--- a/src/core/minions/delegated-spend.ts
+++ b/src/core/minions/delegated-spend.ts
@@ -37,6 +37,11 @@ export function maximumInvocationCents(call: AIInvocation, overrides?: PricingOv
return Math.ceil((call.maxInputTokens! * Math.max(p.input * 2, p.read, p.write) + maxOutputTokens! * p.output) / 100) / 100;
}
+/** Why maximumInvocationCents is null: a known price with no declared input ceiling is `no_context_ceiling` (#6990). */
+export function unboundedInvocationCause(call: AIInvocation, overrides?: PricingOverrides): 'no_pricing' | 'no_context_ceiling' {
+ return prices(call, overrides) && !Number.isSafeInteger(call.maxInputTokens) ? 'no_context_ceiling' : 'no_pricing';
+}
+
export function actualCents(call: AIInvocation, usage: AIInvocationUsage | null, overrides?: PricingOverrides): number | null {
const p = prices(call, overrides);
if (!p || !usage) return null;
diff --git a/src/core/minions/spend-authorization.ts b/src/core/minions/spend-authorization.ts
index 55394e1b30..3ab4a5b874 100644
--- a/src/core/minions/spend-authorization.ts
+++ b/src/core/minions/spend-authorization.ts
@@ -23,7 +23,7 @@ import { opError } from '../ops/contract.ts';
import { loadPricingOverrides } from '../budget/budget-tracker.ts';
import { withAIInvocationGuard } from '../ai/invocation-guard.ts';
import { GroupBudgetRefusal, RESERVATION_TTL_MS, readGroupSpend, reserveGroup, settle, type GroupSpend } from './budget-meter.ts';
-import { actualCents, maximumInvocationCents } from './delegated-spend.ts';
+import { actualCents, maximumInvocationCents, unboundedInvocationCause } from './delegated-spend.ts';
import { UnrecoverableError } from './errors.ts';
import { RateLeaseUnavailableError } from './rate-leases.ts';
import type { MinionJob, MinionJobContext } from './types.ts';
@@ -178,7 +178,7 @@ export function noteChildSpendEnforcement(features: readonly string[]): void {
export function childSpendEnforcementReady(): boolean { return childSpendEnforcement; }
/** The resume command: the producer's argv with a doubled `--max-usd`, or null for a legacy row. */
-function resumeArgv(record: SpendAuthorization, capUsd: number): string[] | null {
+function resumeArgv(record: SpendAuthorization, capUsd: number | null): string[] | null {
if (!record.argv) return null;
const argv: string[] = [];
for (let i = 0; i < record.argv.length; i++) {
@@ -187,7 +187,7 @@ function resumeArgv(record: SpendAuthorization, capUsd: number): string[] | null
if (/^--max-(usd|cost|cost-usd)=/.test(a) || a === '--yes' || a === '-y' || a === '--no-confirm') continue;
argv.push(a);
}
- return [...argv, '--max-usd', resumeMaxUsd(capUsd).toFixed(2), '--yes'];
+ return capUsd === null ? [...argv, '--yes'] : [...argv, '--max-usd', resumeMaxUsd(capUsd).toFixed(2), '--yes'];
}
/** The terminal envelope for a group that ran out (`kind: 'cost'`) or met an unpriced model under a user cap. */
@@ -195,10 +195,25 @@ export async function spendRefusal(
engine: BrainEngine,
job: Pick<MinionJob, 'id' | 'name'>,
record: SpendAuthorization,
- cause: { kind: 'cost'; overdueHolds?: boolean } | { kind: 'no_pricing'; model: string },
+ cause: { kind: 'cost'; overdueHolds?: boolean } | { kind: 'no_pricing' | 'no_context_ceiling'; model: string },
): Promise<SpendGroupRefusedError> {
const group = groupAmounts(record, await readGroupSpend(engine, `group:${record.group_id}`));
const listArgv = ['gbrain', 'jobs', 'list', '--group', record.group_id, '--json'];
+ if (cause.kind === 'no_context_ceiling') {
+ const capped = resumeArgv(record, null);
+ const rerun = capped ? shellQuote(capped) : `${record.command} with --yes instead of --max-usd`;
+ const e = opError('no_context_ceiling',
+ `Job ${job.id} (${record.command}) stopped: ${cause.model} has a known price, but gbrain knows no context-token ceiling for it, so the most one call could cost under the user's $${record.cap_usd!.toFixed(2)} cap cannot be bounded. No provider call was made.`,
+ `Do not retry unchanged and do not change the price (it is already known). Ask the user to choose: rerun without the user cap (${rerun}; the default cap then applies and this model runs unmetered with a warning), or have the brain-host operator supply ${cause.model}'s context size (its context-token ceiling from the provider's model page).`,
+ { why: 'A user-set cap is enforced per provider attempt by reserving the most that attempt could cost, which needs the model\'s input ceiling as well as its price.',
+ docs: 'docs/guides/write-refusals.md#no_context_ceiling',
+ fix: { ...(capped ? { argv: capped } : {}), ask_user: true, consent: ['paid'], actor: 'agent', requires_exclusive: false,
+ why: `Reruns ${record.command} without the user cap, so ${cause.model} runs unmetered under the default cap.`,
+ user_message: `${cause.model} has a known price but no known context size, so your $${record.cap_usd!.toFixed(2)} cap can't bound its calls. Rerun ${record.command} without your cap (that model then runs unmetered), or tell me the model's context size so the operator can declare it?`,
+ inputs: [{ name: 'context_tokens', how: `${cause.model}'s context window in tokens, from the provider's model page (OpenRouter lists it as context_length); the brain-host operator declares it.` }],
+ verify: { argv: listArgv } } });
+ return new SpendGroupRefusedError({ ...e.toJSON(), group } as SpendRefusalEnvelope);
+ }
if (cause.kind === 'no_pricing') {
const e = opError('no_pricing',
`Job ${job.id} (${record.command}) stopped: gbrain has no price for ${cause.model}, so the user's $${record.cap_usd!.toFixed(2)} cap cannot be enforced. No provider call was made.`,
@@ -212,7 +227,7 @@ export async function spendRefusal(
const derived = record.cap_source === 'derived';
const resume = resumeArgv(record, cap);
const n = resumeMaxUsd(cap);
- const reconcile = cause.overdueHolds && group.overdue_usd > 0
+ const reconcile = cause.kind === 'cost' && cause.overdueHolds && group.overdue_usd > 0
? ` $${group.overdue_usd.toFixed(2)} of it is held by attempts that never reported usage; they count as spent until reconciled.`
: '';
const message = `Job ${job.id} (${record.command}) stopped: its group ${record.group_id} reached the $${cap.toFixed(2)} ${derived ? 'cost cap derived from the estimate' : `${record.cap_source} cost cap`} `
@@ -295,10 +310,13 @@ export async function runWithJobSpend<T>(
const guard = async (call: Parameters<Parameters<typeof withAIInvocationGuard>[0]>[0]) => {
const max = maximumInvocationCents(call, pricingOverrides);
if (max === null) {
- if (record.cap_source === 'user') throw (seen.refusal = await spendRefusal(engine, job, record, { kind: 'no_pricing', model: call.model }));
+ const kind = unboundedInvocationCause(call, pricingOverrides);
+ if (record.cap_source === 'user') throw (seen.refusal = await spendRefusal(engine, job, record, { kind, model: call.model }));
if (!warned) {
warned = true;
- process.stderr.write(`[budget] BUDGET_TRACKER_NO_PRICING: model "${call.model}" has no known price; job ${job.id} runs it unmetered under its ${record.cap_source} $${record.cap_usd!.toFixed(2)} cap. Register its rate with \`gbrain pricing set\` to meter it.\n`);
+ process.stderr.write(kind === 'no_context_ceiling'
+ ? `[budget] BUDGET_TRACKER_NO_PRICING: model "${call.model}" has a known price but no known context-token ceiling; job ${job.id} runs it unmetered under its ${record.cap_source} $${record.cap_usd!.toFixed(2)} cap.\n`
+ : `[budget] BUDGET_TRACKER_NO_PRICING: model "${call.model}" has no known price; job ${job.id} runs it unmetered under its ${record.cap_source} $${record.cap_usd!.toFixed(2)} cap. Register its rate with \`gbrain pricing set\` to meter it.\n`);
}
}
let hold;
diff --git a/test/minions-spend-authorization.test.ts b/test/minions-spend-authorization.test.ts
index 3b01461e51..89d080ba7e 100644
--- a/test/minions-spend-authorization.test.ts
+++ b/test/minions-spend-authorization.test.ts
@@ -12,8 +12,9 @@ import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from '
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { MinionQueue } from '../src/core/minions/queue.ts';
import { invokeAI } from '../src/core/ai/invocation-guard.ts';
+import { chatInvocation } from '../src/core/ai/guarded-generation.ts';
import {
- jobSpendAuthorization, parseSpendAuthorization, runWithJobSpend, spendBasis, spendSubmitSummary,
+ jobSpendAuthorization, parseSpendAuthorization, runWithJobSpend, spendBasis, spendSubmitSummary, SpendGroupRefusedError,
type SpendAuthorization,
} from '../src/core/minions/spend-authorization.ts';
import type { MinionJob, MinionJobContext } from '../src/core/minions/types.ts';
@@ -220,3 +221,36 @@ test('a user-capped job admits and settles a registered zero-price local model',
await engine.setConfig('pricing.overrides', previous ?? '{}');
}
});
+
+// #6990: a registered price with no declared context ceiling (OpenRouter declares none) is not a
+// missing price. The refusal names the missing ceiling, never sends the operator back to pricing set.
+test('a priced model with no context ceiling refuses as no_context_ceiling under a user cap', async () => {
+ const previous = await engine.getConfig('pricing.overrides');
+ const model = 'openrouter:anthropic/claude-haiku-5.5';
+ await engine.setConfig('pricing.overrides', JSON.stringify({ [model]: { input: 0.1, output: 0.5 } }));
+ try {
+ const call = chatInvocation('test-openrouter', model, 1000);
+ expect(call.maxInputTokens).toBeUndefined();
+ const job = await claimed('subagent', {}, record(1, 'user'));
+ let calls = 0;
+ const refusal = await runWithJobSpend(engine, job, ctxFor(job), async () => invokeAI(call,
+ async () => { calls++; return 'unexpected'; }, () => ({ inputTokens: 1, outputTokens: 1 }))).catch(e => e as SpendGroupRefusedError);
+ expect(calls).toBe(0);
+ expect(refusal).toBeInstanceOf(SpendGroupRefusedError);
+ const envelope = (refusal as SpendGroupRefusedError).envelope;
+ expect(envelope.code).toBe('no_context_ceiling');
+ expect(envelope.message).toContain(model);
+ expect(envelope.message).toContain('No provider call was made');
+ expect(envelope.docs).toBe('docs/guides/write-refusals.md#no_context_ceiling');
+ expect(envelope.fix).toMatchObject({ argv: ['gbrain', 'book-mirror', '--slug', 'a-book', '--yes'], consent: ['paid'], next: 'ask_user',
+ verify: { argv: ['gbrain', 'jobs', 'list', '--group', job.spend_authorization!.group_id, '--json'] } });
+ const fix = envelope.fix as { user_message?: string; inputs?: Array<{ name: string }> };
+ expect(fix.user_message).toContain(model);
+ expect(fix.inputs!.map(i => i.name)).toEqual(['context_tokens']);
+ await expect(runWithJobSpend(engine, job, ctxFor(job), async () => invokeAI(chatInvocation('test-unpriced', 'openrouter:example/unpriced-model', 1000),
+ async () => { calls++; return 'unexpected'; }, () => null))).rejects.toThrow('no_pricing');
+ expect(calls).toBe(0);
+ } finally {
+ await engine.setConfig('pricing.overrides', previous ?? '{}');
+ }
+});