Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
decide: accept gateway-published TypeSafe ids; refuse an unpriced one before transport (#5980)
garrytan60f5848ac732
diff --git a/docs/ai-providers/typesafe.md b/docs/ai-providers/typesafe.mdindex d3c4177db0..80bfa53e5b 100644--- a/docs/ai-providers/typesafe.md+++ b/docs/ai-providers/typesafe.md@@ -85,6 +85,35 @@ that already opted in. If the pinned id stops being served, calls fail with`pinned_model_unavailable` and doctor names the recovery. See[troubleshooting](../guides/system-one.md#pinned_model_unavailable).+## Self-hosted or gateway-fronted endpoints++Two settings route decide at a Jev served somewhere other than+`api.typesafe.ai` (an inference gateway, an on-prem deployment):++- `provider_base_urls.typesafe` (in `~/.gbrain/config.json`, or+ `gbrain config set provider_base_urls.typesafe https://gw.example.com/typesafe/v1`)+ replaces the origin; the `/systemone` path is appended to it. The reranker+ path uses the same setting.+- `decide.provider` accepts any model id the endpoint publishes, not only+ `jev-<version>`: `typesafe:oc/jev-1.13-free`, `typesafe:jev_custom`. The id+ may contain letters, digits, `.`, `_`, `@`, `/` and `-`; no whitespace and+ no second colon. The endpoint still has to answer with the resolved model+ name, and an id it does not serve fails with `pinned_model_unavailable`.++An id that GBrain ships no tariff for has no price, so its spend cannot be+metered against `decide.budget.daily_usd`: decide refuses it before anything+is sent, with `unpriced_model`, until you register the price the endpoint+bills you:++```bash+gbrain pricing set typesafe:oc/jev-1.13-free --rate 0.05 --source https://gw.example.com/pricing+gbrain decide probe+```++The spend ledger then records that price per call; it never records $0 for+a model whose cost is unknown. See+[troubleshooting](../guides/system-one.md#unpriced_model).+## Reranker setupCarried from #5178 by [dsandrade](https://github.com/dsandrade), who designeddiff --git a/docs/architecture/key-files/core-decide.md b/docs/architecture/key-files/core-decide.mdindex e9f20d835e..625f063ac6 100644--- a/docs/architecture/key-files/core-decide.md+++ b/docs/architecture/key-files/core-decide.md@@ -10,7 +10,7 @@ The capability contract (API, providers, egress, extension points) is `docs/arch- `src/core/ai/decide/slots.ts` — `SLOT_SPECS`: lane, question kind, harmful direction (needs the action-precision gate), thresholded, call sites, egress classes, default `min_keep`, shadow sample, what-if reproducibility, question version, fail direction and `wired` (the delivery gate: unwired slots are refused with `slot_unavailable`).-- `src/core/ai/decide/config.ts` — Every `decide.*` key with its validator (`validateDecideConfigValue`, called by `gbrain config set`), and `readDecideConfig(snapshot)` (invalid stored values fall back to defaults; all default off). `pickDecideConfig` gives search the decide subset of the one config snapshot so all-off does no work. `enableDecideEvalOverride` is the only door for `GBRAIN_DECIDE_SLOTS`.+- `src/core/ai/decide/config.ts` — Every `decide.*` key with its validator (`validateDecideConfigValue`, called by `gbrain config set`), and `readDecideConfig(snapshot)` (invalid stored values fall back to defaults; all default off). `pickDecideConfig` gives search the decide subset of the one config snapshot so all-off does no work. `enableDecideEvalOverride` is the only door for `GBRAIN_DECIDE_SLOTS`. `isValidProvider` accepts `none`, `llm:<provider:model>` and any `typesafe:<id>` of `[a-z0-9._@/-]` starting alphanumeric (#5980: gateway-published ids such as `typesafe:oc/jev-1.13-free`; no whitespace, no second colon); the snapshot's `pricing.overrides` is parsed into `DecideConfig.pricingOverrides` so the runner can price an id gbrain ships no tariff for.- `src/core/ai/decide/pack.ts` — Planner (64k per request, 32k state + longest question, 2x estimate with a digit floor, split before send, never truncate, rank-then-id order), `packShape`, and `runBatches` (≤16 in flight, one deadline, a 429 retry only when `retry-after` fits, background lanes drop to one worker after a 429, first failure stops queueing while started requests settle).@@ -18,7 +18,7 @@ The capability contract (API, providers, egress, extension points) is `docs/arch- `src/core/ai/decide/providers/llm-structured.ts` — `llm:<provider:model>`: prompt + JSON schema through `chat()`, same parser, `llmCapability` (`structured` only for openai-compatible recipes that declare structured outputs), model identity from the provider snapshot or an endpoint fingerprint.-- `src/core/ai/decide/index.ts` — `runDecide(req, ctx)` (also `gateway.decide`): provider selection, egress gate, egress fallback as its own sub-decision, daily cap and remote share before sending, `BudgetTracker` reserve/record (kind `decide`, or `rerank` for S1 on), bounded batches, mixed-model rejection, one `decide_spend` row per request (failed and timed-out requests charged their estimate).+- `src/core/ai/decide/index.ts` — `runDecide(req, ctx)` (also `gateway.decide`): provider selection, egress gate, egress fallback as its own sub-decision, daily cap and remote share before sending, `BudgetTracker` reserve/record (kind `decide`, or `rerank` for S1 on), bounded batches, mixed-model rejection, one `decide_spend` row per request (failed and timed-out requests charged their estimate). [R18]: before the daily-cap check, an id whose price resolves to nothing (`usageCostUsd(..., cfg.pricingOverrides)` null: no shipped tariff, no `pricing.overrides` entry) is refused `unpriced_model` with nothing sent and no spend row, so the ledger never records $0 for an unknown cost and no outer `BudgetTracker` is needed to protect the daily and remote-share budgets. `provider_base_urls.typesafe` (gateway `base_urls`) is the request origin, `/systemone` appended. Pinned by `test/decide/provider-ids-5980.test.ts`.- `src/core/ai/decide/egress.ts` — `checkEgress`: consent per data class (or the reranker selection for S1 on), denied sources on every provider, private pages by one batched `privatePagesFilterFragment` query (with the #5525 derived-origin rule), facts by visibility (default private), conversation text private, missing provenance refused.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex a20918744e..29d8447f3e 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -3010,6 +3010,16 @@ More: [docs/guides/write-refusals.md#unclosed_ambiguous_tail](../../docs/guides/|---|---|---|---|---|---|---|| Reclone only replaces a checkout created and managed by GBrain. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+### unpriced_model++<a id="unpriced_model"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The configured decide model has no price, so its spend cannot be metered; nothing was sent. | A `typesafe:<model>` id that gbrain ships no tariff for (a gateway-fronted or self-hosted Jev) would otherwise be admitted as $0 against `decide.budget.daily_usd` and its remote share, and the spend ledger would record $0 for a real bill (#5980). | Register the price the endpoint bills with `gbrain pricing set typesafe:<model> --rate <usd-per-1M-input-tokens> --source <pricing-page-url>`, then `gbrain decide probe`. Run: gbrain pricing list --json | agent | `gbrain config get pricing.overrides` | 1 | no |++More: [docs/guides/system-one.md#unpriced_model](../../docs/guides/system-one.md#unpriced_model)+### unsupported_export_data<a id="unsupported_export_data"></a>diff --git a/docs/guides/system-one.md b/docs/guides/system-one.mdindex b35f8b4856..5b12b4ae7f 100644--- a/docs/guides/system-one.md+++ b/docs/guides/system-one.md@@ -676,6 +676,7 @@ cause, a fix command and a link to a row here.| <a id="egress_fallback_missing"></a>`egress_fallback_missing` | Items egress refused have no fallback provider. | `gbrain config set decide.egress_fallback llm:<provider:model>`, or accept the fail direction for them. || <a id="split_mismatch"></a>`split_mismatch` | The calibration was built from a different dataset split, or not from the calibrate half only. | `gbrain decide calibrate --slot <slot> --dataset <jsonl>` on the same dataset file. || <a id="pinned_model_unavailable"></a>`pinned_model_unavailable` | The provider no longer serves the pinned model. Calls take the fail direction. | `gbrain config set decide.provider typesafe:<new-id> && gbrain decide calibrations list`, then recalibrate or adopt a reference calibration for the new id. |+| <a id="unpriced_model"></a>`unpriced_model` | The configured `typesafe:<model>` id has no shipped tariff and no operator price, so its spend cannot be metered against `decide.budget.daily_usd`. Nothing was sent. | Register the price the endpoint bills: `gbrain pricing set typesafe:<model> --rate <usd-per-1M-input-tokens> --source <pricing-page-url>`, then `gbrain decide probe`. || <a id="budget_exhausted"></a>`budget_exhausted` | Today's third-party decide spend reached `decide.budget.daily_usd`. Slots take their fail direction until UTC midnight. | Wait, or `gbrain config set decide.budget.daily_usd <usd>`. || <a id="thin_client"></a>`thin_client` | This install is a thin client; `gbrain decide` runs on the brain host. | Run `gbrain decide` on the brain host. || <a id="malformed_response"></a>`malformed_response` | The response missed a question or carried an invalid value. The decision took its fail direction. | `gbrain decide probe`; if it persists, check TypeSafe's status. |@@ -687,7 +688,7 @@ cause, a fix command and a link to a row here.Receipt skip reasons (`error_reason` on skipped or error rows) also include`egress`, `late`, `timeout`, `rate_limited`, `provider_error`, `mixed_model`,`no_embedding`, `no_entity`, `missing_provenance`, `denied_source`,-`payload_too_large`, `cache_hit` and `no_candidates`.+`payload_too_large`, `unpriced_model`, `cache_hit` and `no_candidates`.## Advanced diagnosticsdiff --git a/src/core/ai/decide/config.ts b/src/core/ai/decide/config.tsindex 3cd816223c..898caf1d33 100644--- a/src/core/ai/decide/config.ts+++ b/src/core/ai/decide/config.ts@@ -12,6 +12,8 @@* slot's consent keys. Eval runs never get key defaults; their arms say* exactly which slots are on.*/+import { parsePricingOverrides } from '../../budget/budget-tracker.ts';+import type { PricingOverrides } from '../../budget/reservation-cost.ts';import { recommendedSlots } from './reference-calibrations.ts';import { SLOT_SPECS } from './slots.ts';import { DECIDE_SLOTS, EVIDENCE_CLASSES, type DecideMode, type DecideSlot, type EvidenceClass } from './types.ts';@@ -43,8 +45,15 @@ const sourceList: Validator = (v) => {};const calibrationRef: Validator = (v) => /^(local:\d+|ref:[a-z0-9._:-]+)$/i.test(v) ? null : 'must be local:<id> or ref:<id>';+/**+ * `typesafe:<model>` accepts any model id a gateway or self-hosted Jev may+ * publish (#5980: `typesafe:oc/jev-1.13-free`): one or more of+ * `[a-z0-9._@/-]`, starting alphanumeric, no whitespace and no second colon.+ * An id with no shipped tariff is admitted here and refused at call time+ * (`unpriced_model`) until `gbrain pricing set` registers its price.+ */export function isValidProvider(v: string): boolean {- return v === 'none' || /^typesafe:jev-[a-z0-9.-]+$/i.test(v) || /^llm:[a-z0-9-]+:.+$/i.test(v);+ return v === 'none' || /^typesafe:[a-z0-9][a-z0-9._@/-]*$/i.test(v) || /^llm:[a-z0-9-]+:.+$/i.test(v);}const GLOBAL_KEYS: Record<string, Validator> = {@@ -141,6 +150,8 @@ export interface DecideConfig {slots: Record<DecideSlot, DecideSlotConfig>;/** GBRAIN_DECIDE_SLOTS eval override, honored only when the caller opts in. */evalOverride?: string;+ /** Operator prices (`pricing.overrides`, written by `gbrain pricing set`): the only way an id without a shipped tariff runs. */+ pricingOverrides?: PricingOverrides;}const num = (raw: string | undefined, fallbackValue: number, validator: Validator): number =>@@ -216,6 +227,7 @@ export function readDecideConfig(snapshot: Record<string, string | undefined> |if (raw && sourceList(raw) === null) denySources = JSON.parse(raw);} catch { /* invalid stored value: no denials beyond the private rule */ }const fb = get('decide.egress_fallback');+ const pricingOverrides = parsePricingOverrides(get('pricing.overrides'));return {provider: providerValue,egressFallback: fb && fallback(fb) === null ? fb : 'none',@@ -234,6 +246,7 @@ export function readDecideConfig(snapshot: Record<string, string | undefined> |intentWaitMs: num(get('decide.slots.intent.wait_ms'), 250, GLOBAL_KEYS['decide.slots.intent.wait_ms']!),slots,...(evalSlots ? { evalOverride: evalSlots } : {}),+ ...(pricingOverrides ? { pricingOverrides } : {}),};}diff --git a/src/core/ai/decide/index.ts b/src/core/ai/decide/index.tsindex f6646b439e..0520b8d6e2 100644--- a/src/core/ai/decide/index.ts+++ b/src/core/ai/decide/index.ts@@ -156,7 +156,13 @@ async function runTypesafe(req: DecideRequest, ctx: DecideContext, cfg: DecideCo}const budgetKind = req.budgetKind ?? 'decide';const estimatedTokens = plan.reduce((n, b) => n + b.estimatedInputTokens, 0);- const priced = (tokens: number) => usageCostUsd(a.provider, tokens, 0, budgetKind) ?? 0;+ // [R18] (#5980): an id with no shipped tariff and no operator price is+ // refused before transport. `?? 0` here would admit it as free against the+ // daily and remote-share budgets and write $0 spend rows for a real bill.+ if (usageCostUsd(a.provider, 1, 0, budgetKind, cfg.pricingOverrides) === null) {+ throw new DecideError('unpriced_model', `decide: ${a.provider} has no price; register one with gbrain pricing set ${a.provider} --rate <usd-per-1M-input-tokens> --source <url>`);+ }+ const priced = (tokens: number) => usageCostUsd(a.provider, tokens, 0, budgetKind, cfg.pricingOverrides)!;if (budgetKind === 'decide' && ctx.engine) {const spent = await dailySpend(ctx.engine, a.now()).catch(() => ({ total: 0, remote: 0 }));const estimate = priced(estimatedTokens);diff --git a/src/core/ai/decide/outcomes.ts b/src/core/ai/decide/outcomes.tsindex f771cf8b81..36260dc7a3 100644--- a/src/core/ai/decide/outcomes.ts+++ b/src/core/ai/decide/outcomes.ts@@ -37,6 +37,7 @@ export const SKIP_REASONS = ['no_calibration', 'pack_shape_mismatch', 'action_precision_low', 'no_qualification', 'pinned_model_unavailable','payload_too_large', 'llm_capability', 'egress_private_denied', 'egress_class_denied', 'missing_provenance','denied_source', 'shadow_queue_full', 'reranker_not_jev', 'cache_hit', 'no_candidates', 'egress_denied',+ 'unpriced_model',] as const;export type SkipReason = typeof SKIP_REASONS[number];@@ -49,6 +50,9 @@ export interface RefusalEntry {anchor: string;}+/** The `gbrain pricing set` call that registers a price for an unpriced decide id (argv form; the catalog renders it). */+export const UNPRICED_MODEL_FIX_ARGV: readonly string[] = ['gbrain', 'pricing', 'set', 'typesafe:<model>', '--rate', '<usd-per-1M-input-tokens>', '--source', '<pricing-page-url>'];+/** Refusal and inactive-cause catalog. Every refusal path must emit one of these keys. */export const REFUSAL_CATALOG: Readonly<Record<string, RefusalEntry>> = {no_provider: { problem: 'No decide provider is configured.', cause: 'decide.provider is none', fix: 'gbrain decide enable <slot> --provider typesafe:jev-1.13.0', anchor: '#no_provider' },@@ -65,6 +69,7 @@ export const REFUSAL_CATALOG: Readonly<Record<string, RefusalEntry>> = {egress_fallback_missing: { problem: 'Refused items have no fallback provider.', cause: 'decide.egress_fallback is none', fix: 'gbrain config set decide.egress_fallback llm:<provider:model>', anchor: '#egress_fallback_missing' },split_mismatch: { problem: 'The calibration was built from a different dataset split.', cause: 'split_hash differs from the eval split or calibrate_only is false', fix: 'gbrain decide calibrate --slot <slot> --dataset <jsonl>', anchor: '#split_mismatch' },pinned_model_unavailable: { problem: 'The pinned model is no longer served.', cause: 'the provider returned unknown or unavailable model', fix: 'gbrain config set decide.provider typesafe:<new-id> && gbrain decide calibrations list', anchor: '#pinned_model_unavailable' },+ unpriced_model: { problem: 'The decide model has no price, so its spend cannot be metered.', cause: 'the configured typesafe:<model> id has no shipped tariff and no pricing.overrides entry', fix: UNPRICED_MODEL_FIX_ARGV.join(' '), anchor: '#unpriced_model' },budget_exhausted: { problem: 'The daily decide budget is spent.', cause: 'decide_spend for the current UTC day reached decide.budget.daily_usd', fix: 'gbrain config set decide.budget.daily_usd <usd>', anchor: '#budget_exhausted' },thin_client: { problem: 'gbrain decide runs on the brain host.', cause: 'this install is a thin client', fix: 'run gbrain decide on the brain host', anchor: '#thin_client' },malformed_response: { problem: 'The provider response failed validation.', cause: 'a requested id was missing or a value was non-numeric or out of range', fix: 'gbrain decide probe', anchor: '#malformed_response' },diff --git a/src/core/ai/decide/types.ts b/src/core/ai/decide/types.tsindex 38dcc063fa..5142d35bb8 100644--- a/src/core/ai/decide/types.ts+++ b/src/core/ai/decide/types.ts@@ -114,7 +114,7 @@ export interface DecideResult {export type DecideFailureReason =| 'timeout' | 'rate_limited' | 'provider_error' | 'malformed_response' | 'mixed_model'| 'budget_exhausted' | 'no_key' | 'no_provider' | 'pinned_model_unavailable' | 'payload_too_large'- | 'egress' | 'late' | 'llm_capability';+ | 'egress' | 'late' | 'llm_capability' | 'unpriced_model';export class DecideError extends Error {reason: DecideFailureReason;diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex ca91d28e6a..fe035b1c19 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -431,6 +431,7 @@ export const CODES = {unknown_source: { class: 'caller', summary: "The named source is not registered or is archived." },unknown_tool: { class: 'caller', summary: "The named tool does not exist or is not callable on this connection.", legacy_error: 'unknown_operation' },unknown_transport: { class: 'unavailable', summary: "The caller's transport could not be identified." },+ unpriced_model: { class: 'caller', summary: "The configured decide model has no price, so its spend cannot be metered; nothing was sent.", why: 'A `typesafe:<model>` id that gbrain ships no tariff for (a gateway-fronted or self-hosted Jev) would otherwise be admitted as $0 against `decide.budget.daily_usd` and its remote share, and the spend ledger would record $0 for a real bill (#5980).', docs: 'docs/guides/system-one.md#unpriced_model', suggestion: 'Register the price the endpoint bills with `gbrain pricing set typesafe:<model> --rate <usd-per-1M-input-tokens> --source <pricing-page-url>`, then `gbrain decide probe`.', fix: { argv: ['gbrain', 'pricing', 'list', '--json'], consent: [], actor: 'agent', why: 'Read-only: shows the operator prices already registered, so the missing `typesafe:<model>` row is visible before anything is written.', requires_exclusive: false, verify: { argv: ['gbrain', 'config', 'get', 'pricing.overrides'] } } },unmanaged_path: { class: 'caller', summary: "Reclone only replaces a checkout created and managed by GBrain." },unsupported_export_data: { class: 'unavailable', summary: "The source contains data this export path cannot carry." },unsupported_mutation_protocol: { class: 'unavailable', summary: "Prepared mutation does not match its accepted target." },diff --git a/test/decide/provider-ids-5980.test.ts b/test/decide/provider-ids-5980.test.tsnew file mode 100644index 0000000000..97ddca1d32--- /dev/null+++ b/test/decide/provider-ids-5980.test.ts@@ -0,0 +1,183 @@+/**+ * #5980 — TypeSafe decide behind a gateway: provider-namespaced model ids and+ * a custom base URL.+ *+ * `decide.provider` only accepted `typesafe:jev-<…>`, so a gateway-fronted or+ * self-hosted Jev published as `typesafe:oc/jev-1.13-free` read back as+ * `none`. The id is now accepted (no whitespace, no `:`), and+ * `provider_base_urls.typesafe` is pinned as the request's origin.+ *+ * [R18]: widening the id alone would have admitted an id with no tariff as+ * $0 against the daily and remote-share budgets (`usageCostUsd(...) ?? 0`).+ * An unpriced id is refused BEFORE transport with `unpriced_model` unless the+ * operator registered a price (`pricing.overrides`, written by+ * `gbrain pricing set`); the spend ledger never records $0 for an unknown+ * cost. Pinned here with NO outer budget tracker, so the decide-level policy+ * itself is what protects the budgets.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { resetPgliteState } from '../helpers/reset-pglite.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { serializeMarkdown } from '../../src/core/markdown.ts';+import { configureGateway, resetGateway, getCurrentBudgetTracker, __setDecideTransportForTests } from '../../src/core/ai/gateway.ts';+import { isValidProvider, readDecideConfig } from '../../src/core/ai/decide/config.ts';+import { runDecide } from '../../src/core/ai/decide/index.ts';+import { REFUSAL_CATALOG, SKIP_REASONS } from '../../src/core/ai/decide/outcomes.ts';+import { dailySpend, flushDecideWrites, __resetDecideStoreForTests } from '../../src/core/ai/decide/store.ts';+import type { DecideQuestion, EvidenceItem } from '../../src/core/ai/decide/types.ts';+import { buildGatewayConfig } from '../../src/core/ai/build-gateway-config.ts';+import type { GBrainConfig } from '../../src/core/config.ts';++let engine: PGLiteEngine;++const NAMESPACED = 'typesafe:oc/jev-1.13-free';+const cand = (slug: string): EvidenceItem => ({ text: `text of ${slug}`, class: 'candidates', slug, source_id: 'default' });+const q = (id: string, input: EvidenceItem): DecideQuestion => ({ id, kind: 'noul', instructions: 'Is `c` evidence?', inputs: { c: input } });+const consentFor = (provider: string) => ({+ 'decide.provider': provider,+ 'decide.egress.typesafe.query': 'allow', 'decide.egress.typesafe.candidates': 'allow',+ 'decide.egress.typesafe.facts': 'allow', 'decide.egress.typesafe.conversation': 'allow',+});+const STATE = { query: { text: 'q', class: 'query' as const } };++function answerAll(model: string) {+ const calls: Array<{ url: string; body: any }> = [];+ __setDecideTransportForTests(async (url, init) => {+ const body = JSON.parse(init.body as string);+ calls.push({ url: String(url), body });+ return new Response(JSON.stringify({+ model, usage: { input_tokens: 200, output_tokens: 5 },+ answers: Object.fromEntries(Object.keys(body.questions).map((id) => [id, { type: 'noul', noul: 0.7 }])),+ }));+ });+ return calls;+}++async function spendRows() {+ await flushDecideWrites();+ return engine.executeRaw<{ provider: string; outcome: string; cost_usd: number }>('SELECT provider, outcome, cost_usd FROM decide_spend ORDER BY created_at');+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ const r = await importFromContent(engine, 'notes/world', serializeMarkdown({}, 'body of notes/world', '', { type: 'note', title: 'notes/world', tags: [] }), { noEmbed: true, forceRechunk: true });+ expect(r.status).toBe('imported');+});++afterAll(async () => {+ __setDecideTransportForTests(null);+ resetGateway();+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ __resetDecideStoreForTests();+ configureGateway({ env: { TYPESAFE_API_KEY: 'sk-test' } });+ const r = await importFromContent(engine, 'notes/world', serializeMarkdown({}, 'body of notes/world', '', { type: 'note', title: 'notes/world', tags: [] }), { noEmbed: true, forceRechunk: true });+ expect(r.status).toBe('imported');+ expect(getCurrentBudgetTracker() ?? undefined).toBeUndefined();+});++describe('isValidProvider accepts provider-namespaced TypeSafe ids', () => {+ test('gateway and self-hosted ids pass; whitespace, a second colon and an empty tail do not', () => {+ expect(isValidProvider('typesafe:jev-1.13.0')).toBe(true);+ expect(isValidProvider(NAMESPACED)).toBe(true);+ expect(isValidProvider('typesafe:jev_custom')).toBe(true);+ expect(isValidProvider('typesafe:org@gw/jev.1')).toBe(true);+ expect(isValidProvider('typesafe:')).toBe(false);+ expect(isValidProvider('typesafe:jev 1.13')).toBe(false);+ expect(isValidProvider('typesafe:jev:1.13')).toBe(false);+ expect(isValidProvider('typesafe:/jev')).toBe(false);+ expect(isValidProvider('none')).toBe(true);+ expect(isValidProvider('llm:openai:gpt-4o-mini')).toBe(true);+ });++ test('readDecideConfig keeps a namespaced global provider instead of reading it back as none', () => {+ expect(readDecideConfig(consentFor(NAMESPACED)).provider).toBe(NAMESPACED);+ expect(readDecideConfig({ 'decide.provider': 'typesafe:jev 1.13' }).provider).toBe('none');+ });+});++describe('[R18] unpriced-model policy, with no outer budget tracker', () => {+ test('an unpriced namespaced id is refused before transport; no spend row, nothing sent', async () => {+ const calls = answerAll('oc/jev-1.13-free');+ await expect(runDecide({ slot: 'evidence', callSite: 'search', state: STATE, questions: [q('w', cand('notes/world'))] },+ { engine, config: readDecideConfig(consentFor(NAMESPACED)) }))+ .rejects.toMatchObject({ reason: 'unpriced_model' });+ expect(calls).toHaveLength(0);+ expect(await spendRows()).toEqual([]);+ expect((await dailySpend(engine)).total).toBe(0);+ });++ test('the refusal is terminal with no engine too (probe path), and the daily budget is not consulted first', async () => {+ const calls = answerAll('oc/jev-1.13-free');+ await expect(runDecide({ slot: 'evidence', callSite: 'probe', state: {}, questions: [q('w', { text: 'We decided to ship.', class: 'query' })], provider: NAMESPACED, lane: 'background' },+ { engine: null, config: { ...readDecideConfig(consentFor(NAMESPACED)), consent: { query: true, candidates: true, facts: true, conversation: true } } }))+ .rejects.toMatchObject({ reason: 'unpriced_model' });+ expect(calls).toHaveLength(0);+ });++ test('an operator price in pricing.overrides admits the id; the ledger records that price, never $0', async () => {+ const calls = answerAll('oc/jev-1.13-free');+ const cfg = readDecideConfig({ ...consentFor(NAMESPACED), 'pricing.overrides': JSON.stringify({ [NAMESPACED]: 0.05 }) });+ const r = await runDecide({ slot: 'evidence', callSite: 'search', state: STATE, questions: [q('w', cand('notes/world'))] }, { engine, config: cfg });+ expect(r.answers.w).toEqual({ kind: 'noul', p: 0.7 });+ expect(r.model_resolved).toBe('oc/jev-1.13-free');+ expect(r.cost_usd).toBeCloseTo(200 * 0.05 / 1e6, 12);+ expect(calls).toHaveLength(1);+ const rows = await spendRows();+ expect(rows).toHaveLength(1);+ expect(rows[0]!.provider).toBe(NAMESPACED);+ expect(Number(rows[0]!.cost_usd)).toBeCloseTo(200 * 0.05 / 1e6, 12);+ expect(Number(rows[0]!.cost_usd)).toBeGreaterThan(0);+ });++ test('a priced override id still honours the daily cap and the remote share', async () => {+ const calls = answerAll('oc/jev-1.13-free');+ const base = { ...consentFor(NAMESPACED), 'pricing.overrides': JSON.stringify({ [NAMESPACED]: 0.05 }) };+ await expect(runDecide({ slot: 'evidence', callSite: 'search', state: STATE, questions: [q('w', cand('notes/world'))] },+ { engine, config: readDecideConfig({ ...base, 'decide.budget.daily_usd': '0' }) })).rejects.toMatchObject({ reason: 'budget_exhausted' });+ await expect(runDecide({ slot: 'evidence', callSite: 'search', state: STATE, questions: [q('w', cand('notes/world'))], remote: true },+ { engine, config: readDecideConfig({ ...base, 'decide.budget.remote_share': '0' }) })).rejects.toMatchObject({ reason: 'budget_exhausted' });+ expect(calls).toHaveLength(0);+ });++ test('the shipped tariff ids are unaffected', async () => {+ const calls = answerAll('jev-1.13.0');+ const r = await runDecide({ slot: 'evidence', callSite: 'search', state: STATE, questions: [q('w', cand('notes/world'))] },+ { engine, config: readDecideConfig(consentFor('typesafe:jev-1.13.0')) });+ expect(r.cost_usd).toBeCloseTo(200 * 0.042 / 1e6, 12);+ expect(calls).toHaveLength(1);+ });++ test('unpriced_model is a catalogued refusal and a receipt skip reason', () => {+ expect(SKIP_REASONS).toContain('unpriced_model');+ expect(REFUSAL_CATALOG.unpriced_model?.fix).toContain('gbrain pricing set');+ expect(REFUSAL_CATALOG.unpriced_model?.anchor).toBe('#unpriced_model');+ });+});++describe('provider_base_urls.typesafe', () => {+ test('the decide request goes to the configured origin, path preserved', async () => {+ // The user-facing key is config `provider_base_urls.typesafe`; buildGatewayConfig folds it into the gateway's base_urls.+ const built = buildGatewayConfig({ engine: 'pglite', provider_base_urls: { typesafe: 'https://gw.example.test/typesafe/v1/' } } as GBrainConfig);+ expect(built.base_urls?.typesafe).toBe('https://gw.example.test/typesafe/v1/');+ configureGateway({ ...built, env: { ...built.env, TYPESAFE_API_KEY: 'sk-test' } });+ const calls = answerAll('jev-1.13.0');+ await runDecide({ slot: 'evidence', callSite: 'search', state: STATE, questions: [q('w', cand('notes/world'))] },+ { engine, config: readDecideConfig(consentFor('typesafe:jev-1.13.0')) });+ expect(calls).toHaveLength(1);+ expect(calls[0]!.url).toBe('https://gw.example.test/typesafe/v1/systemone');+ });++ test('without an override the request goes to api.typesafe.ai', async () => {+ const calls = answerAll('jev-1.13.0');+ await runDecide({ slot: 'evidence', callSite: 'search', state: STATE, questions: [q('w', cand('notes/world'))] },+ { engine, config: readDecideConfig(consentFor('typesafe:jev-1.13.0')) });+ expect(calls[0]!.url).toBe('https://api.typesafe.ai/v1/systemone');+ });+});diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 74acacdfac..7bd07467d3 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -6099,7 +6099,7 @@{"kind": "class","members": [- "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_branch_unborn\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"merge_recommended\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_write_stall\" | \"schema_lock_blocked\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"question_not_found\" | \"question_owner_only\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"search_offset_over_cap\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined",+ "canonical?: \"unknown\" | \"keyword_candidates_incomplete\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"timeline_rows_would_be_removed\" | \"purged_content\" | \"preparation_stalled\" | \"fence_unrenderable\" | \"write_outcome_unknown\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambient_capture_off\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"budget_below_recent_runtime\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"concurrent_write\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"connection_lost\" | \"consent_required\" | \"consent_timeout\" | \"consumers_without_heartbeat\" | \"content_repair_needs_human\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"drain_stalled\" | \"managed_sync_not_moving\" | \"dream_breaker_tripped\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_backstop_skipped\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"forget_requires_owner\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_branch_unborn\" | \"git_checkout_required\" | \"git_detached_head\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"host_identity_mismatch\" | \"harness_hook_duplicates\" | \"harness_hook_unowned\" | \"held_failed\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"unclosed_ambiguous_tail\" | \"tail_exposure_approval\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"loops_extraction_skipped\" | \"maintenance_backpressure\" | \"maintenance_lock_busy\" | \"managed_failure_unsettled\" | \"merge_recommended\" | \"managed_pull_skipped\" | \"manual_only_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_lease_lost\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pattern_claims_pending\" | \"pending_writes\" | \"persistence_write_stall\" | \"schema_lock_blocked\" | \"pg_connection_stuck\" | \"pg_pool_stalled\" | \"pg_statement_build_failed\" | \"pglite_busy\" | \"pglite_vector_index_too_large\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"purge_blocked_pending_recovery\" | \"question_not_found\" | \"question_owner_only\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"pat_file_unreadable\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"search_cursor_requires_keyword\" | \"search_mode_local_only\" | \"search_offset_over_cap\" | \"serve_port_in_use\" | \"serve_status_only\" | \"setup_harness_unsupported\" | \"setup_hosted_connection\" | \"setup_owner_conflict\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_mismatch\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_parser_regression\" | \"target_escape\" | \"timeline_comment_markup\" | \"topology_change_required\" | \"transcript_secret_exposure\" | \"triage_unreliable_backoff\" | \"trust_raise_refused\" | \"two_consumers_on_host\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unpriced_model\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"write_gate_rejected\" | \"write_held\" | \"worktree_dirty\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_rescope_required\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | \"schema_pack_too_large\" | \"schema_pack_emit_mismatch\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",