@full-self-browsing/lattice 0.0.0-bootstrap.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["toArrayBuffer","fail","numberField","DEFAULT_BASE_URL","numberField","isBlobLike"],"sources":["../src/contract/contract.ts","../src/contract/invariants.ts","../src/contract/pii-detectors.ts","../src/routing/catalog.ts","../src/contract/preflight.ts","../src/contract/tripwire.ts","../src/outputs/contracts.ts","../src/receipts/keyset.ts","../src/receipts/sign.ts","../src/receipts/verify.ts","../src/results/errors.ts","../src/providers/adapters.ts","../src/providers/anthropic.ts","../src/providers/fake.ts","../src/providers/gemini.ts","../src/providers/lm-studio.ts","../src/providers/openrouter.ts","../src/providers/xai.ts","../src/plan/plan.ts","../src/version.ts","../src/replay/materialize.ts","../src/replay/replay.ts","../src/agent/infra/cost-tracker.ts","../src/agent/infra/transcript-store.ts","../src/agent/infra/goal-progress.ts","../src/agent/infra/action-history.ts","../src/agent/infra/permission-context.ts","../src/agent/eval.ts","../src/context/context-pack.ts","../src/policy/policy.ts","../src/providers/packaging.ts","../src/routing/router.ts","../src/storage/fingerprint.ts","../src/tracing/tracing.ts","../src/runtime/config.ts","../src/runtime/create-ai.ts","../src/sessions/session.ts","../src/storage/local.ts","../src/storage/memory.ts"],"sourcesContent":["import type { CapabilityModality } from \"../providers/provider.js\";\n\nexport type {\n FieldFromTableInvariant,\n InvariantDeclaration,\n MatchesInvariant,\n MustCiteInvariant,\n NoPiiInvariant,\n} from \"./invariants.js\";\n\n// Local alias so the union can be referenced in this module without\n// re-importing through the public re-export above.\nimport type { InvariantDeclaration as InvariantDeclarationUnion } from \"./invariants.js\";\n\n/**\n * Budget invariant declaration attached to a CapabilityContract.\n *\n * Phase 7 implements `maxCostUsd` enforcement at pre-flight. The\n * `p95LatencyMs` field is declared per CONTRACT-02 but is informational\n * only in Phase 7 — latency observations are wired in a later phase.\n *\n * Phase 19 (v1.2) adds `maxIterations` and `maxWallTimeMs` for the agent\n * runtime. Both are additive and optional; non-agent callers ignore them.\n * `maxIterations` caps the number of `runAgent` iterations; `maxWallTimeMs`\n * caps wall-clock duration per `runAgent` invocation. Both are enforced\n * pre-iteration in the agent loop.\n */\nexport interface BudgetInvariant {\n readonly maxCostUsd?: number;\n readonly maxIterations?: number;\n readonly maxWallTimeMs?: number;\n readonly p95LatencyMs?: number;\n}\n\n/**\n * Quality-floor invariant.\n *\n * `suite` is a fixture-directory path string; `minScore` is in 0..1.\n * Phase 7 forwards this into the pre-flight evaluator but only enforces\n * capability-side rejects. Full enforcement lives in Phase 12 (`lattice eval`).\n */\nexport interface QualityFloorInvariant {\n readonly suite: string;\n readonly minScore: number;\n}\n\n/**\n * The full Capability Contract attached to `RunIntent.contract`.\n *\n * All fields are optional. v1.0 callers compile and run unchanged when\n * the field is omitted entirely. PROJECT.md explicitly rejects mandatory\n * contracts.\n */\nexport interface CapabilityContract {\n readonly kind: \"capability-contract\";\n readonly budget?: BudgetInvariant;\n readonly invariants?: readonly InvariantDeclarationUnion[];\n readonly qualityFloor?: QualityFloorInvariant;\n readonly requiredModalities?: readonly CapabilityModality[];\n readonly requiredPrivacy?: \"standard\" | \"sensitive\" | \"restricted\";\n}\n\n/**\n * Reject-reason taxonomy added to `RouteRejectReason.code` by Phase 7's\n * pre-flight evaluator. Closed four-value union per the locked decisions\n * in 07-CONTEXT.md.\n */\nexport type ContractRejectReasonCode =\n | \"contract-budget-exceeded\"\n | \"contract-quality-floor\"\n | \"contract-modality-missing\"\n | \"contract-privacy-mismatch\";\n\n/** Input shape accepted by `contract()`. Mirrors `CapabilityContract` minus `kind`. */\nexport interface CapabilityContractInput {\n readonly budget?: BudgetInvariant;\n readonly invariants?: readonly InvariantDeclarationUnion[];\n readonly qualityFloor?: QualityFloorInvariant;\n readonly requiredModalities?: readonly CapabilityModality[];\n readonly requiredPrivacy?: \"standard\" | \"sensitive\" | \"restricted\";\n}\n\n/**\n * Factory for `CapabilityContract` values.\n *\n * Mirrors the `output()` and adapter factory style — exact-optional safe\n * (does not emit `field: undefined` properties under `exactOptionalPropertyTypes`).\n * Returns a frozen value with frozen nested objects so downstream code can\n * rely on structural immutability when canonicalizing in Phase 9.\n */\nexport function contract(input: CapabilityContractInput = {}): CapabilityContract {\n return Object.freeze({\n kind: \"capability-contract\" as const,\n ...(input.budget !== undefined ? { budget: Object.freeze({ ...input.budget }) } : {}),\n ...(input.invariants !== undefined\n ? { invariants: Object.freeze(input.invariants.map((inv) => Object.freeze({ ...inv }))) }\n : {}),\n ...(input.qualityFloor !== undefined\n ? { qualityFloor: Object.freeze({ ...input.qualityFloor }) }\n : {}),\n ...(input.requiredModalities !== undefined\n ? { requiredModalities: Object.freeze([...input.requiredModalities]) }\n : {}),\n ...(input.requiredPrivacy !== undefined ? { requiredPrivacy: input.requiredPrivacy } : {}),\n });\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n/**\n * Tripwire invariant declaration variants produced by the `inv` fluent\n * builder. Each variant is a frozen value carrying a discriminant `kind`\n * and an `id` (auto-generated or caller-supplied).\n *\n * Phase 8 reshapes the Phase 7 placeholder `{ kind: \"policy\"|\"semantic\"|\"schema\" }`\n * into this discriminated union. Phase 7 never populated `invariants`\n * (see 07-04-SUMMARY decisions), so the change is additive in practice\n * but technically a breaking type change for any external caller that\n * authored a literal of the old shape.\n */\n\nexport interface MustCiteInvariant {\n readonly id: string;\n readonly kind: \"must-cite\";\n readonly artifactName: string;\n}\n\nexport interface FieldFromTableInvariant {\n readonly id: string;\n readonly kind: \"field-from-table\";\n readonly path: string;\n readonly allowedValues: readonly string[];\n}\n\nexport interface NoPiiInvariant {\n readonly id: string;\n readonly kind: \"no-pii\";\n readonly path: string;\n}\n\nexport interface MatchesInvariant<T = unknown> {\n readonly id: string;\n readonly kind: \"matches\";\n readonly path: string;\n readonly schema: StandardSchemaV1<unknown, T>;\n}\n\nexport type InvariantDeclaration =\n | MustCiteInvariant\n | FieldFromTableInvariant\n | NoPiiInvariant\n | MatchesInvariant;\n\nexport interface InvariantOptions {\n readonly id?: string;\n}\n\nlet counter = 0;\n\nfunction nextId(kind: string, options?: InvariantOptions): string {\n counter += 1;\n return options?.id ?? `${kind}-${counter}`;\n}\n\n/**\n * Fluent builder for tripwire invariants.\n *\n * Each helper returns a frozen `InvariantDeclaration` with an auto-generated\n * id of the form `${kind}-${counter}`. Callers may override the id via the\n * second-positional `options.id` arg.\n *\n * The counter is monotonic across kinds — calling `inv.mustCite(\"a\")` then\n * `inv.fieldFromTable(\"x\", [\"y\"])` yields ids `must-cite-1` then\n * `field-from-table-2`. This keeps ids globally unique within a process.\n *\n * Note on `inv.matches`: the caller supplies the StandardSchema validator,\n * and the tripwire evaluator trusts whatever `~standard.validate` returns.\n * This is by design — `matches` is the caller-driven escape hatch (see\n * T-08-05 in the 08-01-PLAN threat register).\n */\nexport const inv = {\n mustCite(artifactName: string, options?: InvariantOptions): MustCiteInvariant {\n return Object.freeze({\n id: nextId(\"must-cite\", options),\n kind: \"must-cite\" as const,\n artifactName,\n });\n },\n fieldFromTable(\n path: string,\n allowedValues: readonly string[],\n options?: InvariantOptions,\n ): FieldFromTableInvariant {\n return Object.freeze({\n id: nextId(\"field-from-table\", options),\n kind: \"field-from-table\" as const,\n path,\n allowedValues: Object.freeze([...allowedValues]),\n });\n },\n noPII(path: string, options?: InvariantOptions): NoPiiInvariant {\n return Object.freeze({\n id: nextId(\"no-pii\", options),\n kind: \"no-pii\" as const,\n path,\n });\n },\n matches<T>(\n path: string,\n schema: StandardSchemaV1<unknown, T>,\n options?: InvariantOptions,\n ): MatchesInvariant<T> {\n return Object.freeze({\n id: nextId(\"matches\", options),\n kind: \"matches\" as const,\n path,\n schema,\n });\n },\n /**\n * Test-only: reset the auto-id counter. NOT exported from the package\n * root barrel — callers must import `inv` directly from this module if\n * they ever need it, which is intentional friction.\n */\n __resetCounterForTests(): void {\n counter = 0;\n },\n} as const;\n","/**\n * Regex-based PII detectors used by the `no-pii` tripwire invariant.\n *\n * Phase 8 ships four detectors (email, US SSN, Luhn-valid credit card,\n * US phone). They are intentionally regex-only — zero new dependencies —\n * per the v1.1 scope locked in 08-CONTEXT.md.\n *\n * Each detector returns either `{ matched: true, substring }` carrying\n * ONLY the matched fragment, or `{ matched: false }`. The substring shape\n * is required so the tripwire evaluator can emit redacted evidence\n * (Phase 9 receipts must not leak the full input).\n *\n * Detector order in `defaultPiiDetectors` is deterministic so the\n * evaluator's first-violation semantics produce stable receipts.\n */\n\nexport type PiiDetectorResult =\n | { readonly matched: true; readonly substring: string }\n | { readonly matched: false };\n\nexport interface PiiDetector {\n readonly name: string;\n detect(input: string): PiiDetectorResult;\n}\n\n/**\n * Luhn check digit validator.\n *\n * Strips non-digit characters from `digits`, requires the resulting length\n * to be 13-19 (ISO/IEC 7812 PAN range), then walks right-to-left doubling\n * every second digit and summing. Returns true when the sum is a multiple\n * of 10.\n */\nfunction luhn(digits: string): boolean {\n const cleaned = digits.replace(/\\D/g, \"\");\n if (cleaned.length < 13 || cleaned.length > 19) return false;\n\n let sum = 0;\n let shouldDouble = false;\n for (let i = cleaned.length - 1; i >= 0; i -= 1) {\n const code = cleaned.charCodeAt(i);\n // Defensive: charAt cannot produce non-digits here because of the\n // `replace(/\\D/g, \"\")` above, but keep a guard for clarity.\n if (code < 48 || code > 57) return false;\n let digit = code - 48;\n if (shouldDouble) {\n digit *= 2;\n if (digit > 9) digit -= 9;\n }\n sum += digit;\n shouldDouble = !shouldDouble;\n }\n return sum % 10 === 0;\n}\n\nfunction execFirst(regex: RegExp, input: string): string | undefined {\n // Always create a fresh exec; we do not rely on regex statefulness.\n const match = regex.exec(input);\n return match ? match[0] : undefined;\n}\n\nconst emailDetector: PiiDetector = {\n name: \"email\",\n detect(input: string): PiiDetectorResult {\n // Local + domain + TLD. Requires at least one non-empty label on each\n // side and a dot in the domain part. Rejects `@bad`, `bad@`, `not-an-email`.\n const substring = execFirst(/[\\w.+-]+@[\\w-]+\\.[\\w.-]+/, input);\n return substring !== undefined ? { matched: true, substring } : { matched: false };\n },\n};\n\nconst ssnDetector: PiiDetector = {\n name: \"us-ssn\",\n detect(input: string): PiiDetectorResult {\n // 3-2-4 grouped SSN with word boundaries on both sides to avoid\n // collapsing into longer adjacent digit runs (e.g., phone numbers).\n const substring = execFirst(/\\b\\d{3}-\\d{2}-\\d{4}\\b/, input);\n return substring !== undefined ? { matched: true, substring } : { matched: false };\n },\n};\n\nconst creditCardDetector: PiiDetector = {\n name: \"credit-card\",\n detect(input: string): PiiDetectorResult {\n // Match any 13-19 character sequence of digits with optional single\n // space or dash separators, then validate with Luhn. The regex is\n // intentionally permissive on separators (banks/forms vary); Luhn\n // filters trivially-formatted strings per Pitfall #5 in CONTEXT.md.\n const candidate = execFirst(/\\b(?:\\d[ -]?){13,19}\\b/, input);\n if (candidate === undefined) return { matched: false };\n // Strip trailing space/dash that the regex may have absorbed.\n const trimmed = candidate.replace(/[ -]+$/, \"\");\n if (!luhn(trimmed)) return { matched: false };\n return { matched: true, substring: trimmed };\n },\n};\n\nconst phoneDetector: PiiDetector = {\n name: \"us-phone\",\n detect(input: string): PiiDetectorResult {\n // Dashed form first, then parenthesized form. Combined alternation so\n // the regex engine picks whichever fires first in input order.\n const substring = execFirst(/\\b\\d{3}-\\d{3}-\\d{4}\\b|\\(\\d{3}\\)\\s?\\d{3}-\\d{4}/, input);\n return substring !== undefined ? { matched: true, substring } : { matched: false };\n },\n};\n\n/**\n * Default PII detectors used by `evaluateTripwires` for `no-pii` invariants.\n *\n * Order is deterministic: email, us-ssn, credit-card, us-phone. Callers who\n * need a different set can pass their own list to `evaluateTripwires`.\n */\nexport const defaultPiiDetectors: readonly PiiDetector[] = Object.freeze([\n emailDetector,\n ssnDetector,\n creditCardDetector,\n phoneDetector,\n]);\n","import type {\n CapabilityModality,\n ModelCapability,\n ProviderAdapter,\n ProviderPricingHint,\n ProviderRef,\n} from \"../providers/provider.js\";\n\nexport const DEFAULT_CATALOG_VERSION = \"lattice:catalog:v1\";\n\nexport interface CapabilityCatalog {\n readonly version: string;\n readonly models: readonly ModelCapability[];\n}\n\nexport function createCapabilityCatalog(\n providers: readonly (ProviderRef | ProviderAdapter)[],\n): CapabilityCatalog {\n return {\n version: DEFAULT_CATALOG_VERSION,\n models: providers.flatMap((provider) => {\n if (provider.kind === \"provider-adapter\" && provider.capabilities !== undefined) {\n return provider.capabilities;\n }\n\n return [defaultCapabilityForProvider(provider.id)];\n }),\n };\n}\n\nexport function defaultCapabilityForProvider(providerId: string): ModelCapability {\n return {\n providerId,\n modelId: `${providerId}:default`,\n inputModalities: [\"text\", \"json\", \"image\", \"audio\", \"document\", \"file\", \"url\", \"tool\"],\n outputModalities: [\"text\", \"json\"],\n fileTransport: [\"inline\", \"json\", \"url\", \"base64\", \"extracted-text\", \"transcript\"],\n contextWindow: 16_000,\n structuredOutput: true,\n toolUse: false,\n streaming: false,\n pricing: {\n inputCostPer1M: 0,\n outputCostPer1M: 0,\n inputPer1kTokens: 0,\n outputPer1kTokens: 0,\n },\n latency: \"interactive\",\n dataPolicy: {\n privacy: [\"standard\", \"sensitive\"],\n uploadRetention: \"none\",\n supportsNoLogging: true,\n supportsNoTraining: true,\n },\n available: true,\n };\n}\n\n/**\n * Resolve the effective per-1k token pricing for a capability.\n *\n * Prefers the explicit `inputPer1kTokens` / `outputPer1kTokens` fields and\n * falls back to dividing the legacy per-1M fields by 1000 when only those\n * are present. Returns `undefined` per side when neither shape supplies a\n * value, so callers can distinguish \"free / zero\" (`0`) from \"unknown\"\n * (`undefined`) — Phase 7 cost normalization treats unknown pricing as\n * `usage.costUsd === null`, not `0`.\n */\nexport function effectivePer1kPricing(\n pricing: ProviderPricingHint | undefined,\n): {\n readonly inputPer1kTokens: number | undefined;\n readonly outputPer1kTokens: number | undefined;\n} {\n if (pricing === undefined) {\n return { inputPer1kTokens: undefined, outputPer1kTokens: undefined };\n }\n\n const inputPer1k =\n pricing.inputPer1kTokens ??\n (pricing.inputCostPer1M !== undefined ? pricing.inputCostPer1M / 1000 : undefined);\n const outputPer1k =\n pricing.outputPer1kTokens ??\n (pricing.outputCostPer1M !== undefined ? pricing.outputCostPer1M / 1000 : undefined);\n\n return {\n inputPer1kTokens: inputPer1k,\n outputPer1kTokens: outputPer1k,\n };\n}\n\nexport function modalRank(modality: CapabilityModality): number {\n const ranks: Record<CapabilityModality, number> = {\n text: 0,\n json: 1,\n image: 2,\n audio: 3,\n document: 4,\n file: 5,\n url: 6,\n video: 7,\n tool: 8,\n };\n\n return ranks[modality];\n}\n","import type { RouteRejectReason } from \"../plan/plan.js\";\nimport type { ModelCapability } from \"../providers/provider.js\";\nimport { effectivePer1kPricing } from \"../routing/catalog.js\";\nimport type { CapabilityContract } from \"./contract.js\";\n\n/**\n * Result of a single pre-flight contract evaluation against a candidate\n * capability. `reasons` is empty when `ok` is true and contains one or more\n * `RouteRejectReason` entries when `ok` is false.\n *\n * The evaluator surfaces ALL failing reasons in a single pass — not the\n * first-failing only — so the deterministic router can aggregate per-candidate\n * rejection detail (CONTEXT.md \"Pre-flight surfaces ALL failed candidates\n * with per-candidate rejection reasons\").\n */\nexport interface ContractPreflightResult {\n readonly ok: boolean;\n readonly reasons: readonly RouteRejectReason[];\n}\n\n/**\n * Input for the pure cost estimator. Token counts come from the router's\n * existing `estimateRoute()` helper so preflight and router agree on the\n * projected output size (one source of truth — see `evaluateContractAgainstRoute`).\n */\nexport interface EstimateRouteCostInput {\n readonly capability: ModelCapability;\n readonly estimatedInputTokens: number;\n readonly estimatedOutputTokens: number;\n}\n\n/**\n * Pure cost estimator. Returns `null` when pricing is unknown (so downstream\n * gates can distinguish \"free / zero\" from \"unmeasured\" per the Phase 7\n * cost-normalization decision). Uses static catalog metadata only — no probes,\n * no external pricing APIs.\n */\nexport function estimateRouteCost(input: EstimateRouteCostInput): number | null {\n const { inputPer1kTokens, outputPer1kTokens } = effectivePer1kPricing(\n input.capability.pricing,\n );\n if (inputPer1kTokens === undefined && outputPer1kTokens === undefined) {\n return null;\n }\n const inputCost = ((inputPer1kTokens ?? 0) * input.estimatedInputTokens) / 1000;\n const outputCost = ((outputPer1kTokens ?? 0) * input.estimatedOutputTokens) / 1000;\n return inputCost + outputCost;\n}\n\n/** Input for the pre-flight evaluator. */\nexport interface EvaluateContractInput {\n readonly capability: ModelCapability;\n readonly estimatedInputTokens: number;\n readonly estimatedOutputTokens: number;\n}\n\n/**\n * Pure pre-flight evaluator. Phase 9 receipts will reuse this for deterministic\n * verdict reconstruction.\n *\n * Token estimation: Phase 7 does NOT define a separate token estimator. Output-\n * token projection is the canonical responsibility of the router's existing\n * `estimateRoute()` helper (in `routing/router.ts`), which already produces an\n * `estimatedOutputTokens` value. The router passes that same value into this\n * evaluator via `EvaluateContractInput.estimatedOutputTokens`, so preflight\n * and the router always agree on the projected output size. Phase 9 receipts\n * will pin the router's estimate as the deterministic input — intentionally\n * one source of truth.\n *\n * Reject taxonomy (Phase 7 emits three of four codes):\n * - `contract-budget-exceeded` (CONTRACT-04 + COST-03)\n * - `contract-modality-missing` (CONTRACT-06)\n * - `contract-privacy-mismatch` (CONTRACT-06)\n * - `contract-quality-floor` (reserved for Phase 12 `lattice eval`; NEVER emitted here)\n */\nexport function evaluateContractAgainstRoute(\n contract: CapabilityContract | undefined,\n input: EvaluateContractInput,\n): ContractPreflightResult {\n if (contract === undefined) {\n return { ok: true, reasons: [] };\n }\n const reasons: RouteRejectReason[] = [];\n\n // BUDGET — CONTRACT-04 + COST-03\n if (contract.budget?.maxCostUsd !== undefined) {\n const estimatedCost = estimateRouteCost({\n capability: input.capability,\n estimatedInputTokens: input.estimatedInputTokens,\n estimatedOutputTokens: input.estimatedOutputTokens,\n });\n if (estimatedCost === null) {\n reasons.push({\n code: \"contract-budget-exceeded\",\n message: `${input.capability.modelId} pricing unknown; contract budget declared (maxCostUsd=${contract.budget.maxCostUsd}).`,\n });\n } else if (estimatedCost > contract.budget.maxCostUsd) {\n reasons.push({\n code: \"contract-budget-exceeded\",\n message: `${input.capability.modelId} estimated ${estimatedCost.toFixed(6)} exceeds contract budget ${contract.budget.maxCostUsd}.`,\n });\n }\n }\n\n // MODALITY — CONTRACT-06 (contract-modality-missing)\n if (contract.requiredModalities !== undefined) {\n for (const modality of contract.requiredModalities) {\n if (\n !input.capability.inputModalities.includes(modality) &&\n !input.capability.outputModalities.includes(modality)\n ) {\n reasons.push({\n code: \"contract-modality-missing\",\n message: `${input.capability.modelId} does not support required modality ${modality}.`,\n });\n }\n }\n }\n\n // PRIVACY — CONTRACT-06 (contract-privacy-mismatch)\n if (contract.requiredPrivacy !== undefined) {\n if (!input.capability.dataPolicy.privacy.includes(contract.requiredPrivacy)) {\n reasons.push({\n code: \"contract-privacy-mismatch\",\n message: `${input.capability.modelId} does not satisfy contract privacy ${contract.requiredPrivacy}.`,\n });\n }\n }\n\n // QUALITY FLOOR — declared but NOT enforced on the capability side in Phase 7.\n // CONTEXT.md: \"qualityFloor is parsed and forwarded into the pre-flight\n // evaluator but only enforced by Phase 12's lattice eval\".\n // The reject code \"contract-quality-floor\" stays reserved for Phase 12.\n\n return { ok: reasons.length === 0, reasons };\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nimport type {\n FieldFromTableInvariant,\n InvariantDeclaration,\n MatchesInvariant,\n MustCiteInvariant,\n NoPiiInvariant,\n} from \"./invariants.js\";\nimport { defaultPiiDetectors, type PiiDetector } from \"./pii-detectors.js\";\n\n/**\n * Evidence emitted when a tripwire invariant fires.\n *\n * `observed` is the SHAPE-MATCHED redacted payload, not the raw output:\n * - for `must-cite`: the citations array as found at the located path\n * - for `field-from-table`: the actual value at `path`\n * - for `no-pii`: ONLY `{ detector, substring }` — never the full input\n * (T-08-01 in the 08-01-PLAN threat register)\n * - for `matches`: the value at `path`\n *\n * Phase 9 receipts will sign this evidence, so leaking the full PII into\n * `observed` would defeat redact-before-sign.\n */\nexport interface TripwireEvidence {\n readonly invariantId: string;\n readonly kind: \"must-cite\" | \"field-from-table\" | \"no-pii\" | \"matches\";\n readonly path: string;\n readonly observed: unknown;\n readonly message: string;\n}\n\nexport type TripwireResult =\n | { readonly ok: true }\n | { readonly ok: false; readonly evidence: TripwireEvidence };\n\n/**\n * Pure tripwire evaluator.\n *\n * No I/O, no Date.now, no random — same `(output, invariants)` always\n * returns the same `TripwireResult`. Phase 9 receipts can reconstruct the\n * verdict deterministically (T-08-04).\n *\n * Evaluates invariants in declaration order; the FIRST failing invariant\n * aborts and returns its evidence. Subsequent invariants are not evaluated.\n *\n * @param output The provider output to inspect.\n * @param invariants Invariants to evaluate, in declaration order.\n * @param detectors PII detectors used for `no-pii` invariants. Defaults\n * to `defaultPiiDetectors`. Callers can pass a custom\n * list to override.\n */\nexport async function evaluateTripwires(\n output: unknown,\n invariants: readonly InvariantDeclaration[],\n detectors: readonly PiiDetector[] = defaultPiiDetectors,\n): Promise<TripwireResult> {\n for (const declaration of invariants) {\n const result = await evaluateOne(output, declaration, detectors);\n if (!result.ok) return result;\n }\n return { ok: true };\n}\n\nasync function evaluateOne(\n output: unknown,\n declaration: InvariantDeclaration,\n detectors: readonly PiiDetector[],\n): Promise<TripwireResult> {\n switch (declaration.kind) {\n case \"must-cite\":\n return evaluateMustCite(output, declaration);\n case \"field-from-table\":\n return evaluateFieldFromTable(output, declaration);\n case \"no-pii\":\n return evaluateNoPii(output, declaration, detectors);\n case \"matches\":\n return evaluateMatches(output, declaration);\n default: {\n // Exhaustiveness guard. If a new kind is added without updating this\n // switch, TS will reject the assignment below.\n const _exhaustive: never = declaration;\n throw new Error(`Unknown invariant kind: ${JSON.stringify(_exhaustive)}`);\n }\n }\n}\n\nfunction evaluateMustCite(output: unknown, decl: MustCiteInvariant): TripwireResult {\n const located = locateCitations(output);\n const cites = located?.value ?? [];\n const path = located?.path ?? \"citations\";\n\n const matched = cites.some((entry) => {\n if (typeof entry === \"string\") return entry === decl.artifactName;\n if (typeof entry === \"object\" && entry !== null && \"source\" in entry) {\n return (entry as { source?: unknown }).source === decl.artifactName;\n }\n return false;\n });\n\n if (matched) return { ok: true };\n\n return {\n ok: false,\n evidence: {\n invariantId: decl.id,\n kind: \"must-cite\",\n path,\n observed: cites,\n message: `must-cite: no citation found for \"${decl.artifactName}\".`,\n },\n };\n}\n\n/**\n * Locate the citations payload in `output`. Searches top-level for a\n * `citations` or `evidence` key holding an array. Per 08-CONTEXT.md:\n * \"Path defaults to evidence if the output has a citations field; the\n * runtime locates the citations payload in the output.\"\n *\n * Returns `undefined` when neither field is an array.\n */\nfunction locateCitations(\n output: unknown,\n): { readonly value: readonly unknown[]; readonly path: string } | undefined {\n if (typeof output !== \"object\" || output === null) return undefined;\n const record = output as Record<string, unknown>;\n for (const key of [\"citations\", \"evidence\"] as const) {\n const value = record[key];\n if (Array.isArray(value)) return { value, path: key };\n }\n return undefined;\n}\n\nfunction evaluateFieldFromTable(\n output: unknown,\n decl: FieldFromTableInvariant,\n): TripwireResult {\n const value = resolvePath(output, decl.path);\n if (typeof value === \"string\" && decl.allowedValues.includes(value)) {\n return { ok: true };\n }\n return {\n ok: false,\n evidence: {\n invariantId: decl.id,\n kind: \"field-from-table\",\n path: decl.path,\n observed: value,\n message: `field-from-table: value at \"${decl.path}\" not in allowedValues.`,\n },\n };\n}\n\nfunction evaluateNoPii(\n output: unknown,\n decl: NoPiiInvariant,\n detectors: readonly PiiDetector[],\n): TripwireResult {\n const value = resolvePath(output, decl.path);\n if (typeof value !== \"string\") return { ok: true };\n\n for (const detector of detectors) {\n const result = detector.detect(value);\n if (result.matched) {\n return {\n ok: false,\n evidence: {\n invariantId: decl.id,\n kind: \"no-pii\",\n path: decl.path,\n // CRITICAL: redacted — only the detector name and the matched\n // substring, never the full input string (T-08-01).\n observed: { detector: detector.name, substring: result.substring },\n message: `no-pii: detector \"${detector.name}\" flagged content at \"${decl.path}\".`,\n },\n };\n }\n }\n return { ok: true };\n}\n\nasync function evaluateMatches(\n output: unknown,\n decl: MatchesInvariant,\n): Promise<TripwireResult> {\n const value = resolvePath(output, decl.path);\n const validateResult = decl.schema[\"~standard\"].validate(value);\n const validation: StandardSchemaV1.Result<unknown> =\n validateResult instanceof Promise ? await validateResult : validateResult;\n\n if (\"issues\" in validation && validation.issues !== undefined) {\n const firstIssue = validation.issues[0];\n return {\n ok: false,\n evidence: {\n invariantId: decl.id,\n kind: \"matches\",\n path: decl.path,\n observed: value,\n message: firstIssue?.message ?? `matches: schema validation failed at \"${decl.path}\".`,\n },\n };\n }\n return { ok: true };\n}\n\n/**\n * Resolve a dotted/bracketed path expression against a value.\n *\n * Supports three segment forms:\n * - dotted key: `a.b.c`\n * - bracket index: `a[0].b`\n * - wildcard: `a[*].b` (materializes the array of resolutions)\n *\n * Returns `undefined` for missing paths (does not throw).\n *\n * NOTE (T-08-03): `[*]` materializes the array; deeply nested wildcard\n * chains could allocate O(N^k). Accepted for v1.1 — provider responses\n * are bounded by output token caps.\n */\nfunction resolvePath(value: unknown, path: string): unknown {\n if (path === \"\") return value;\n const tokens = tokenize(path);\n return walk(value, tokens, 0);\n}\n\ntype Token =\n | { readonly type: \"key\"; readonly name: string }\n | { readonly type: \"index\"; readonly index: number }\n | { readonly type: \"wildcard\" };\n\nfunction tokenize(path: string): readonly Token[] {\n const tokens: Token[] = [];\n let i = 0;\n let buffer = \"\";\n const flushKey = (): void => {\n if (buffer.length > 0) {\n tokens.push({ type: \"key\", name: buffer });\n buffer = \"\";\n }\n };\n while (i < path.length) {\n const ch = path[i];\n if (ch === \".\") {\n flushKey();\n i += 1;\n continue;\n }\n if (ch === \"[\") {\n flushKey();\n const end = path.indexOf(\"]\", i + 1);\n if (end === -1) {\n // Malformed path — treat the rest as a literal key so we degrade\n // to `undefined` rather than throw on user input.\n buffer = path.slice(i);\n i = path.length;\n continue;\n }\n const inner = path.slice(i + 1, end);\n if (inner === \"*\") {\n tokens.push({ type: \"wildcard\" });\n } else {\n const idx = Number(inner);\n if (Number.isInteger(idx) && idx >= 0) {\n tokens.push({ type: \"index\", index: idx });\n } else {\n // Non-numeric bracket content — treat as a key (e.g. `a[b]` →\n // unusual but plausible).\n tokens.push({ type: \"key\", name: inner });\n }\n }\n i = end + 1;\n continue;\n }\n buffer += ch;\n i += 1;\n }\n flushKey();\n return tokens;\n}\n\nfunction walk(value: unknown, tokens: readonly Token[], cursor: number): unknown {\n if (cursor >= tokens.length) return value;\n if (value === undefined || value === null) return undefined;\n const token = tokens[cursor]!;\n if (token.type === \"key\") {\n if (typeof value !== \"object\") return undefined;\n const next = (value as Record<string, unknown>)[token.name];\n return walk(next, tokens, cursor + 1);\n }\n if (token.type === \"index\") {\n if (!Array.isArray(value)) return undefined;\n return walk(value[token.index], tokens, cursor + 1);\n }\n // wildcard\n if (!Array.isArray(value)) return undefined;\n return value.map((entry) => walk(entry, tokens, cursor + 1));\n}\n\n/**\n * Test-only export: lets unit tests exercise the path resolver directly.\n * Not part of the public surface; lives behind a `__` prefix to discourage\n * runtime use.\n */\nexport function __resolvePathForTests(value: unknown, path: string): unknown {\n return resolvePath(value, path);\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nimport type { ArtifactKind } from \"../artifacts/artifact.js\";\n\nexport type TextOutputContract = \"text\";\n\nexport interface CitationRef {\n readonly artifactId: string;\n readonly label?: string;\n readonly span?: {\n readonly start?: number;\n readonly end?: number;\n };\n readonly metadata?: Record<string, unknown>;\n}\n\nexport interface CitationsOutputContract {\n readonly kind: \"citations\";\n}\n\nexport interface ArtifactRefsOutputContract {\n readonly kind: \"artifacts\";\n readonly artifactKind?: ArtifactKind | string;\n}\n\nexport type SchemaOutputContract = StandardSchemaV1;\n\nexport type OutputContract =\n | TextOutputContract\n | SchemaOutputContract\n | CitationsOutputContract\n | ArtifactRefsOutputContract;\n\nexport type OutputContractMap = Record<string, OutputContract>;\n\nexport const output = {\n citations(): CitationsOutputContract {\n return { kind: \"citations\" };\n },\n\n artifacts(options: {\n readonly artifactKind?: ArtifactKind | string;\n } = {}): ArtifactRefsOutputContract {\n return { kind: \"artifacts\", ...options };\n },\n};\n","import type { KeyEntry, KeySet } from \"./types.js\";\n\n/**\n * In-memory KeySet factory.\n *\n * Verification flow (plan 09-03):\n * - keySet.lookup(kid) returns undefined → VerifyError {kind: \"key-not-found\"}\n * - entry.state === \"revoked\" → VerifyError {kind: \"key-revoked\"}\n * - entry.state === \"retired\" → VerifyOk + keyState: \"retired\" (caller may warn)\n * - entry.state === \"active\" → VerifyOk + keyState: \"active\"\n *\n * Duplicate kids: last write wins (deterministic — callers control entry order).\n * Empty entries array is legal — every lookup returns undefined.\n * Returned KeySet exposes only `lookup` — no enumeration.\n *\n * See 09-CONTEXT.md \"Key Management (UNRETROFITTABLE)\".\n */\nexport function createMemoryKeySet(entries: readonly KeyEntry[]): KeySet {\n const byKid = new Map<string, KeyEntry>();\n for (const entry of entries) {\n byKid.set(entry.kid, entry);\n }\n return {\n lookup(kid: string): KeyEntry | undefined {\n return byKid.get(kid);\n },\n };\n}\n","/**\n * WebCrypto Ed25519 wrappers + in-memory signer factory.\n *\n * 09-CONTEXT.md (UNRETROFITTABLE):\n * - Algorithm name is the LITERAL string \"Ed25519\" (no params object needed\n * for sign/verify; Node 24 subtle accepts both forms).\n * - ReceiptSigner returns 64-byte Ed25519 signatures.\n * - The runtime accepts a signer reference, NEVER raw private keys.\n * - Production users plug their own signer (KMS adapter / OS keyring).\n * createInMemorySigner is the in-process default for tests and dev.\n *\n * Reconciled in plan 09-03 to import ReceiptSigner from ./types.js (plan 09-01\n * owns the spine). `ReceiptSigner_Local` retained as a deprecated alias for\n * backward compatibility with Wave 1 sibling imports.\n */\n\nimport type { ReceiptSigner } from \"./types.js\";\n\n/**\n * @deprecated Use ReceiptSigner from \"./types.js\". Retained as an alias\n * during the Wave 1 -> Wave 2 reconciliation.\n */\nexport type ReceiptSigner_Local = ReceiptSigner;\n\nconst ALG = \"Ed25519\" as const;\n\n/**\n * Copy a Uint8Array into a fresh ArrayBuffer. WebCrypto's BufferSource type\n * (under exactOptionalPropertyTypes + strict TS) rejects `Uint8Array<ArrayBufferLike>`\n * because the underlying buffer could be a SharedArrayBuffer. Matches the\n * pattern used in storage/fingerprint.ts.\n */\nfunction toArrayBuffer(bytes: Uint8Array): ArrayBuffer {\n const copy = new Uint8Array(bytes.byteLength);\n copy.set(bytes);\n return copy.buffer as ArrayBuffer;\n}\n\nexport async function importEd25519PrivateKey(\n jwk: JsonWebKey,\n): Promise<CryptoKey> {\n return crypto.subtle.importKey(\"jwk\", jwk, ALG, true, [\"sign\"]);\n}\n\nexport async function importEd25519PublicKey(\n jwk: JsonWebKey,\n): Promise<CryptoKey> {\n return crypto.subtle.importKey(\"jwk\", jwk, ALG, true, [\"verify\"]);\n}\n\nexport interface GeneratedEd25519KeyPair {\n readonly privateKeyJwk: JsonWebKey;\n readonly publicKeyJwk: JsonWebKey;\n}\n\nexport async function generateEd25519KeyPairJwk(): Promise<GeneratedEd25519KeyPair> {\n const pair = (await crypto.subtle.generateKey(ALG, true, [\n \"sign\",\n \"verify\",\n ])) as CryptoKeyPair;\n const [privateKeyJwk, publicKeyJwk] = await Promise.all([\n crypto.subtle.exportKey(\"jwk\", pair.privateKey),\n crypto.subtle.exportKey(\"jwk\", pair.publicKey),\n ]);\n return { privateKeyJwk, publicKeyJwk };\n}\n\nexport async function verifyEd25519Signature(\n publicKeyJwk: JsonWebKey,\n message: Uint8Array,\n signature: Uint8Array,\n): Promise<boolean> {\n let key: CryptoKey;\n try {\n key = await importEd25519PublicKey(publicKeyJwk);\n } catch {\n return false;\n }\n try {\n return await crypto.subtle.verify(\n ALG,\n key,\n toArrayBuffer(signature),\n toArrayBuffer(message),\n );\n } catch {\n // Malformed signature length or other subtle error — treat as invalid.\n return false;\n }\n}\n\nexport function createInMemorySigner(\n privateKeyJwk: JsonWebKey,\n options: { readonly kid: string; readonly publicKeyJwk: JsonWebKey },\n): ReceiptSigner {\n // Lazily import the key on first sign() — keeps the factory synchronous\n // and avoids touching crypto.subtle during module load.\n let cachedKey: CryptoKey | undefined;\n const ensureKey = async (): Promise<CryptoKey> => {\n if (cachedKey === undefined) {\n cachedKey = await importEd25519PrivateKey(privateKeyJwk);\n }\n return cachedKey;\n };\n return {\n kid: options.kid,\n publicKeyJwk: options.publicKeyJwk,\n async sign(bytes: Uint8Array): Promise<Uint8Array> {\n const key = await ensureKey();\n const sig = await crypto.subtle.sign(ALG, key, toArrayBuffer(bytes));\n return new Uint8Array(sig);\n },\n };\n}\n","import { canonicalizeReceiptBody } from \"./canonical.js\";\nimport {\n PAYLOAD_TYPE,\n base64Encode,\n buildPae,\n decodeEnvelope,\n} from \"./envelope.js\";\nimport { verifyEd25519Signature } from \"./sign.js\";\nimport type {\n CapabilityReceiptBody,\n KeyEntry,\n KeySet,\n ReceiptEnvelope,\n VerifyError,\n VerifyResult,\n} from \"./types.js\";\n\nfunction fail(kind: VerifyError[\"kind\"], message: string): VerifyResult {\n return { ok: false, error: { kind, message } };\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.byteLength !== b.byteLength) return false;\n for (let i = 0; i < a.byteLength; i += 1) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\n/**\n * Receipt body shape check. We trust the JSON parse — but we re-validate\n * that the required fields exist with the right primitive types before\n * canonicalizing again. Anything off -> version-mismatch (the body is\n * structurally NOT a v1 receipt, even if it parses as JSON).\n */\nfunction asReceiptBody(value: unknown): CapabilityReceiptBody | undefined {\n if (typeof value !== \"object\" || value === null) return undefined;\n const v = value as Record<string, unknown>;\n // CRYPTO-01: accept undefined / v1 / v1.1 so they all reach Step 4 (the\n // schema-version-too-low chokepoint). An unknown non-undefined literal\n // (e.g. lattice-receipt/v2 or \"garbage\") is still a structural shape\n // failure and falls through to the version-mismatch path here.\n if (\n v.version !== undefined &&\n v.version !== \"lattice-receipt/v1\" &&\n v.version !== \"lattice-receipt/v1.1\"\n ) {\n return undefined;\n }\n if (typeof v.receiptId !== \"string\") return undefined;\n if (typeof v.runId !== \"string\") return undefined;\n if (typeof v.issuedAt !== \"string\") return undefined;\n if (typeof v.kid !== \"string\") return undefined;\n if (typeof v.model !== \"object\" || v.model === null) return undefined;\n if (typeof v.route !== \"object\" || v.route === null) return undefined;\n if (typeof v.usage !== \"object\" || v.usage === null) return undefined;\n if (typeof v.contractVerdict !== \"string\") return undefined;\n if (!Array.isArray(v.inputHashes)) return undefined;\n if (typeof v.redactionPolicyId !== \"string\") return undefined;\n if (!Array.isArray(v.redactions)) return undefined;\n return v as unknown as CapabilityReceiptBody;\n}\n\n/**\n * Pure receipt verifier.\n *\n * Returns a typed VerifyResult — never throws across the verification\n * boundary (PITFALLS.md security: \"Verifier panics on malformed receipts\n * -> DoS via crafted input\"). All parsing failures become typed errors.\n *\n * Decision tree (first match wins):\n * 1. decodeEnvelope throws OR signatures[] empty -> envelope-malformed\n * 2. payload bytes are not valid JSON -> envelope-malformed\n * 3. body shape check fails OR version unknown literal -> version-mismatch\n * 4. body.version === undefined OR \"lattice-receipt/v1\"-> schema-version-too-low (CRYPTO-01)\n * 5. keySet.lookup(keyid) === undefined -> key-not-found\n * 6. entry.state === \"revoked\" -> key-revoked\n * 7. re-canonicalized body != signed payloadBytes -> canonicalization-mismatch\n * 8. Ed25519 verification of PAE fails -> signature-invalid\n * 9. body.kid !== entry.kid (defense in depth) -> signature-invalid\n * 10. otherwise -> ok + keyState\n */\nexport async function verifyReceipt(\n envelope: ReceiptEnvelope,\n keySet: KeySet,\n): Promise<VerifyResult> {\n // Step 1: decode envelope (catches wrong payloadType, base64 errors).\n let decoded;\n try {\n decoded = decodeEnvelope(envelope);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(\"envelope-malformed\", message);\n }\n if (decoded.signatures.length === 0) {\n return fail(\"envelope-malformed\", \"envelope has no signatures\");\n }\n\n // Step 2: parse the canonical payload.\n let parsed: unknown;\n try {\n parsed = JSON.parse(new TextDecoder().decode(decoded.payloadBytes));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(\"envelope-malformed\", `payload is not valid JSON: ${message}`);\n }\n\n // Step 3: structural body check + version check.\n const body = asReceiptBody(parsed);\n if (body === undefined) {\n return fail(\n \"version-mismatch\",\n \"receipt body is not a lattice-receipt/v1 shape\",\n );\n }\n\n // Step 4: receipt-downgrade defense (CRYPTO-01).\n // Reject receipts whose body.version is absent or equals the v1 literal.\n // v1 receipts predate the step-marker integrity surface added in v1.2;\n // an attacker holding a valid signing key could mint a v1-shaped body\n // and submit it to a v1.1 verifier to bypass step-chain commitments.\n // Short-circuits before any cryptographic work (keyset lookup, canonical\n // re-check, signature verify) so the downgrade verdict is unambiguous.\n // See SECURITY.md (Phase 26 threat model) and Radicle 2026-03 precedent.\n if (body.version === undefined || body.version === \"lattice-receipt/v1\") {\n return fail(\n \"schema-version-too-low\",\n \"Receipt body.version must be 'lattice-receipt/v1.1' — v1 receipts are not accepted (CRYPTO-01).\",\n );\n }\n\n // Step 5: keyset lookup (use first signature; multi-sig deferred to v1.2).\n const firstSig = decoded.signatures[0]!;\n const entry: KeyEntry | undefined = keySet.lookup(firstSig.keyid);\n if (entry === undefined) {\n return fail(\n \"key-not-found\",\n `keySet has no entry for kid \"${firstSig.keyid}\"`,\n );\n }\n if (entry.state === \"revoked\") {\n return fail(\"key-revoked\", `key \"${entry.kid}\" is revoked`);\n }\n\n // Step 6: re-canonicalize body and compare byte-for-byte against\n // decoded.payloadBytes. Catches any swap of canonical form mid-flight\n // (the signed bytes must canonicalize back to themselves).\n const reCanonical = canonicalizeReceiptBody(body);\n if (!bytesEqual(reCanonical, decoded.payloadBytes)) {\n return fail(\n \"canonicalization-mismatch\",\n \"re-canonicalized body does not match signed payload bytes\",\n );\n }\n\n // Step 7: rebuild PAE and verify Ed25519 signature.\n const payloadB64 = base64Encode(decoded.payloadBytes);\n const pae = buildPae(PAYLOAD_TYPE, payloadB64);\n const sigValid = await verifyEd25519Signature(\n entry.publicKeyJwk,\n pae,\n firstSig.sig,\n );\n if (!sigValid) {\n return fail(\"signature-invalid\", \"Ed25519 signature does not verify\");\n }\n\n // Step 8: defense-in-depth — body.kid MUST equal envelope keyid.\n if (body.kid !== entry.kid) {\n return fail(\n \"signature-invalid\",\n `body.kid \"${body.kid}\" does not match envelope keyid \"${entry.kid}\"`,\n );\n }\n\n // Step 9: success — surface the key state so callers can warn on retired.\n return { ok: true, body, keyState: entry.state };\n}\n","import type { TripwireEvidence } from \"../contract/tripwire.js\";\nimport type { RouteRejectReason } from \"../plan/plan.js\";\n\nexport interface ValidationIssue {\n readonly message: string;\n readonly path?: readonly (string | number | symbol)[];\n}\n\nexport interface ValidationError {\n readonly kind: \"validation\";\n readonly message: string;\n readonly output?: string;\n readonly issues: readonly ValidationIssue[];\n}\n\nexport interface ExecutionUnavailableError {\n readonly kind: \"execution_unavailable\";\n readonly message: string;\n}\n\nexport interface NoRouteError {\n readonly kind: \"no_route\";\n readonly message: string;\n readonly reasons: readonly string[];\n}\n\nexport interface ProviderExecutionError {\n readonly kind: \"provider_execution\";\n readonly message: string;\n readonly providerId?: string;\n readonly modelId?: string;\n}\n\nexport interface TimeoutError {\n readonly kind: \"timeout\";\n readonly message: string;\n}\n\n/**\n * Phase 7 addition: emitted by the runtime when no candidate route can\n * satisfy the caller-supplied `CapabilityContract` (budget, modality,\n * privacy, or quality-floor invariants).\n *\n * `noRouteReasons` carries the full deterministic-router rejection list\n * so callers can inspect per-candidate detail. Phase 9 (receipts) will\n * persist this array for deterministic verdict reconstruction.\n */\nexport interface NoContractMatchError {\n readonly kind: \"no-contract-match\";\n readonly message: string;\n readonly noRouteReasons: readonly RouteRejectReason[];\n}\n\n/**\n * Phase 8 addition: emitted when a `CapabilityContract.invariants` tripwire\n * fires after the provider returned a schema-valid output. Carries the\n * `TripwireEvidence` produced by `evaluateTripwires`.\n *\n * `terminal: true` is a structural marker — combined with the `isTerminal()`\n * predicate it tells the fallback chain in `runWithConfig` to refuse retry.\n * `NoContractMatchError` does NOT carry the field (to avoid breaking Phase 7\n * callers) but `isTerminal()` still returns true for it via the kind check.\n */\nexport interface TripwireViolationError {\n readonly kind: \"tripwire-violated\";\n readonly message: string;\n readonly invariantId: string;\n readonly evidence: TripwireEvidence;\n readonly terminal: true;\n}\n\nexport type LatticeRunError =\n | ValidationError\n | ExecutionUnavailableError\n | NoRouteError\n | ProviderExecutionError\n | TimeoutError\n | NoContractMatchError\n | TripwireViolationError;\n\n/**\n * Returns `true` for run errors that MUST NOT be retried by the fallback\n * chain. Phase 8 covers two kinds:\n *\n * - `tripwire-violated` — the contract's invariants rejected the output;\n * a different provider will not change the verdict, so retry burns\n * budget for no gain (T-08-06 in 08-02-PLAN threat register).\n * - `no-contract-match` — no route satisfies the contract at all; the\n * run never executed and no retry will help.\n *\n * All other error kinds return `false` and remain eligible for fallback.\n * The predicate is exported so Phase 12's eval gate and any user-side\n * retry wrappers can share one source of truth.\n */\nexport function isTerminal(error: LatticeRunError): boolean {\n return error.kind === \"tripwire-violated\" || error.kind === \"no-contract-match\";\n}\n","import type { UsageRecord } from \"../plan/plan.js\";\nimport type { ProviderAdapter, ProviderRunResponse, Usage } from \"./provider.js\";\nimport { defaultCapabilityForProvider } from \"../routing/catalog.js\";\n\nexport interface OpenAICompatibleProviderOptions {\n readonly id?: string;\n readonly model: string;\n readonly baseUrl: string;\n readonly apiKey?: string;\n readonly fetch?: typeof fetch;\n /**\n * Phase 7 addition: caller-supplied per-1k pricing. When provided, the\n * adapter computes `normalizedUsage.costUsd` from the API-reported token\n * counts. When omitted, `normalizedUsage.costUsd` is `null` so downstream\n * consumers can distinguish \"unmeasured\" from \"free\" (per 07-CONTEXT.md).\n */\n readonly pricing?: {\n readonly inputPer1kTokens?: number;\n readonly outputPer1kTokens?: number;\n };\n}\n\nexport interface SdkLikeProviderOptions {\n readonly id?: string;\n readonly model: string;\n readonly generate: (input: {\n readonly task: string;\n readonly outputNames: readonly string[];\n }) => Promise<ProviderRunResponse> | ProviderRunResponse;\n}\n\nexport function createOpenAICompatibleProvider(\n options: OpenAICompatibleProviderOptions,\n): ProviderAdapter {\n const id = options.id ?? \"openai-compatible\";\n const fetchImpl = options.fetch ?? fetch;\n\n return {\n id,\n kind: \"provider-adapter\",\n capabilities: [\n {\n ...defaultCapabilityForProvider(id),\n modelId: options.model,\n fileTransport: [\"inline\", \"json\", \"url\", \"base64\", \"extracted-text\", \"transcript\"],\n },\n ],\n async execute(request) {\n const init: RequestInit = {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(options.apiKey !== undefined ? { authorization: `Bearer ${options.apiKey}` } : {}),\n },\n body: JSON.stringify({\n model: options.model,\n messages: [\n {\n role: \"user\",\n content: [\n {\n type: \"text\",\n text: request.task,\n },\n {\n type: \"text\",\n text: JSON.stringify({\n contextPack: request.contextPack === undefined\n ? undefined\n : {\n id: request.contextPack.id,\n tokenBudget: request.contextPack.tokenBudget,\n estimatedTokens: request.contextPack.estimatedTokens,\n included: request.contextPack.included,\n summarized: request.contextPack.summarized,\n archived: request.contextPack.archived,\n omitted: request.contextPack.omitted,\n warnings: request.contextPack.warnings,\n },\n }),\n },\n ...request.artifacts.map((inputArtifact) => ({\n type: \"text\",\n text: JSON.stringify({\n artifactId: inputArtifact.id,\n kind: inputArtifact.kind,\n mediaType: inputArtifact.mediaType,\n privacy: inputArtifact.privacy,\n transport: request.providerPackaging?.artifacts.find(\n (item) => item.artifactId === inputArtifact.id,\n )?.transport ?? request.plan?.providerPackaging?.artifacts.find(\n (item) => item.artifactId === inputArtifact.id,\n )?.transport,\n value:\n typeof inputArtifact.value === \"string\" && inputArtifact.kind !== \"url\"\n ? inputArtifact.value\n : undefined,\n url:\n inputArtifact.kind === \"url\" && typeof inputArtifact.value === \"string\"\n ? inputArtifact.value\n : undefined,\n }),\n })),\n ],\n },\n ],\n }),\n ...(request.signal !== undefined ? { signal: request.signal } : {}),\n };\n const response = await fetchImpl(`${options.baseUrl.replace(/\\/$/u, \"\")}/chat/completions`, init);\n\n if (!response.ok) {\n throw new Error(`OpenAI-compatible provider failed with ${response.status}.`);\n }\n\n const body = await response.json() as {\n choices?: readonly { message?: { content?: unknown } }[];\n usage?: unknown;\n };\n const text = String(body.choices?.[0]?.message?.content ?? \"\");\n const usage = normalizeUsage(body.usage);\n const normalizedUsage = normalizeUsageToRunUsage(body.usage, options.pricing);\n\n return {\n rawOutputs: Object.fromEntries(request.outputs.map((name) => [name, text])),\n ...(usage !== undefined ? { usage } : {}),\n normalizedUsage,\n rawResponse: body,\n };\n },\n };\n}\n\n/**\n * Phase 7 normalization: maps raw provider usage payloads (OpenAI's\n * `prompt_tokens`/`completion_tokens`, the Responses API's\n * `input_tokens`/`output_tokens`, or camelCase variants) to the shared\n * `Usage` shape. When `pricing` is supplied, `costUsd` is computed from\n * the normalized token counts. Otherwise `costUsd` is `null` so consumers\n * can distinguish \"unmeasured\" from \"zero\".\n */\nfunction normalizeUsageToRunUsage(\n rawUsage: unknown,\n pricing?: {\n readonly inputPer1kTokens?: number;\n readonly outputPer1kTokens?: number;\n },\n): Usage {\n let promptTokens = 0;\n let completionTokens = 0;\n if (typeof rawUsage === \"object\" && rawUsage !== null) {\n const record = rawUsage as Record<string, unknown>;\n promptTokens =\n numberField(record, \"prompt_tokens\") ??\n numberField(record, \"input_tokens\") ??\n numberField(record, \"inputTokens\") ??\n 0;\n completionTokens =\n numberField(record, \"completion_tokens\") ??\n numberField(record, \"output_tokens\") ??\n numberField(record, \"outputTokens\") ??\n 0;\n }\n let costUsd: number | null = null;\n if (\n pricing !== undefined &&\n (pricing.inputPer1kTokens !== undefined || pricing.outputPer1kTokens !== undefined)\n ) {\n const inputCost = ((pricing.inputPer1kTokens ?? 0) * promptTokens) / 1000;\n const outputCost = ((pricing.outputPer1kTokens ?? 0) * completionTokens) / 1000;\n costUsd = inputCost + outputCost;\n }\n return { promptTokens, completionTokens, costUsd };\n}\n\nfunction normalizeUsage(usage: unknown): UsageRecord | undefined {\n if (typeof usage !== \"object\" || usage === null) {\n return undefined;\n }\n\n const record = usage as Record<string, unknown>;\n const inputTokens = numberField(record, \"prompt_tokens\") ?? numberField(record, \"input_tokens\");\n const outputTokens =\n numberField(record, \"completion_tokens\") ?? numberField(record, \"output_tokens\");\n const totalTokens = numberField(record, \"total_tokens\");\n\n return {\n ...(inputTokens !== undefined ? { inputTokens } : {}),\n ...(outputTokens !== undefined ? { outputTokens } : {}),\n ...(totalTokens !== undefined ? { totalTokens } : {}),\n };\n}\n\nfunction numberField(record: Record<string, unknown>, key: string): number | undefined {\n const value = record[key];\n\n return typeof value === \"number\" ? value : undefined;\n}\n\nexport function createOpenAIProvider(options: OpenAICompatibleProviderOptions): ProviderAdapter {\n return createOpenAICompatibleProvider({\n ...options,\n id: options.id ?? \"openai\",\n baseUrl: options.baseUrl,\n });\n}\n\nexport function createAISdkProvider(options: SdkLikeProviderOptions): ProviderAdapter {\n const id = options.id ?? \"ai-sdk\";\n\n return {\n id,\n kind: \"provider-adapter\",\n capabilities: [\n {\n ...defaultCapabilityForProvider(id),\n modelId: options.model,\n toolUse: true,\n streaming: true,\n },\n ],\n execute: async (request) => {\n const response = await options.generate({\n task: request.task,\n outputNames: request.outputs,\n });\n const normalizedUsage: Usage = {\n promptTokens: response.usage?.inputTokens ?? 0,\n completionTokens: response.usage?.outputTokens ?? 0,\n costUsd: null,\n };\n return { ...response, normalizedUsage };\n },\n };\n}\n","import type { UsageRecord } from \"../plan/plan.js\";\nimport type { ProviderAdapter, ProviderRunResponse, Usage } from \"./provider.js\";\nimport { defaultCapabilityForProvider } from \"../routing/catalog.js\";\n\n/**\n * Options for {@link createAnthropicProvider}.\n *\n * Mirrors `OpenAICompatibleProviderOptions` ergonomics (Phase 7 pattern) but\n * for the Anthropic Messages API at `/v1/messages` -- which uses a top-level\n * `system` field and a `content[0].text` response shape that diverges from\n * the OpenAI Chat Completions schema (see FSB v0.9.x `extension/ai/universal-provider.js`\n * lines 280-297 + 566-573 for the production reference).\n *\n * SECURITY: `apiKey` is a runtime parameter -- do NOT hardcode or log it.\n *\n * DEFERRED (Phase 4 carryforward notes):\n * - prompt caching (deferred to a follow-on phase)\n * - streaming (deferred; this adapter is single-shot Promise -- per CONTEXT.md D-06)\n * - tool use (Anthropic tool_use blocks are deferred)\n * - resume-from-eviction -- see Phase 5 (MV3-survivability adapter contract)\n *\n * Ref: FSB v0.10.0-attempt-2 Phase 4 (D-02 + D-07: full custom adapter; preserve top-level `system`).\n */\nexport interface AnthropicProviderOptions {\n readonly id?: string;\n readonly model: string;\n readonly apiKey: string;\n /** Defaults to `https://api.anthropic.com`. Override for proxies. */\n readonly baseUrl?: string;\n /** Defaults to `2023-06-01`. Override only if the consumer has tested a newer pinned version. */\n readonly anthropicVersion?: string;\n readonly fetch?: typeof fetch;\n readonly pricing?: {\n readonly inputPer1kTokens?: number;\n readonly outputPer1kTokens?: number;\n };\n}\n\nconst DEFAULT_BASE_URL = \"https://api.anthropic.com\";\nconst DEFAULT_ANTHROPIC_VERSION = \"2023-06-01\";\nconst DEFAULT_MAX_TOKENS = 2000;\n\nexport function createAnthropicProvider(options: AnthropicProviderOptions): ProviderAdapter {\n const id = options.id ?? \"anthropic\";\n const fetchImpl = options.fetch ?? fetch;\n const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/u, \"\");\n const anthropicVersion = options.anthropicVersion ?? DEFAULT_ANTHROPIC_VERSION;\n\n return {\n id,\n kind: \"provider-adapter\",\n capabilities: [\n {\n ...defaultCapabilityForProvider(id),\n modelId: options.model,\n fileTransport: [\"inline\", \"json\", \"url\", \"base64\", \"extracted-text\", \"transcript\"],\n },\n ],\n async execute(request) {\n const init: RequestInit = {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-api-key\": options.apiKey,\n \"anthropic-version\": anthropicVersion,\n },\n body: JSON.stringify({\n model: options.model,\n // D-07: top-level `system` field PRESERVED (Anthropic Messages API\n // contract; NOT folded into the `messages` array).\n system: \"\",\n messages: [\n {\n role: \"user\",\n content: request.task,\n },\n ],\n max_tokens: DEFAULT_MAX_TOKENS,\n }),\n ...(request.signal !== undefined ? { signal: request.signal } : {}),\n };\n\n const response = await fetchImpl(`${baseUrl}/v1/messages`, init);\n\n if (!response.ok) {\n throw new Error(`Anthropic provider failed with ${response.status}.`);\n }\n\n const body = (await response.json()) as {\n content?: readonly { text?: unknown }[];\n usage?: unknown;\n };\n\n const text = String(body.content?.[0]?.text ?? \"\");\n const usage = normalizeAnthropicUsage(body.usage);\n const normalizedUsage = normalizeAnthropicUsageToRunUsage(body.usage, options.pricing);\n\n return {\n rawOutputs: Object.fromEntries(request.outputs.map((name) => [name, text])),\n ...(usage !== undefined ? { usage } : {}),\n normalizedUsage,\n rawResponse: body,\n };\n },\n };\n}\n\n/**\n * Anthropic uses `input_tokens` / `output_tokens` (not OpenAI's\n * `prompt_tokens` / `completion_tokens`). This helper maps to Lattice's\n * `Usage` shape and applies pricing when supplied (Phase 7 pattern).\n */\nfunction normalizeAnthropicUsageToRunUsage(\n rawUsage: unknown,\n pricing?: {\n readonly inputPer1kTokens?: number;\n readonly outputPer1kTokens?: number;\n },\n): Usage {\n let promptTokens = 0;\n let completionTokens = 0;\n if (typeof rawUsage === \"object\" && rawUsage !== null) {\n const record = rawUsage as Record<string, unknown>;\n promptTokens = numberField(record, \"input_tokens\") ?? numberField(record, \"inputTokens\") ?? 0;\n completionTokens =\n numberField(record, \"output_tokens\") ?? numberField(record, \"outputTokens\") ?? 0;\n }\n let costUsd: number | null = null;\n if (\n pricing !== undefined &&\n (pricing.inputPer1kTokens !== undefined || pricing.outputPer1kTokens !== undefined)\n ) {\n const inputCost = ((pricing.inputPer1kTokens ?? 0) * promptTokens) / 1000;\n const outputCost = ((pricing.outputPer1kTokens ?? 0) * completionTokens) / 1000;\n costUsd = inputCost + outputCost;\n }\n return { promptTokens, completionTokens, costUsd };\n}\n\nfunction normalizeAnthropicUsage(usage: unknown): UsageRecord | undefined {\n if (typeof usage !== \"object\" || usage === null) {\n return undefined;\n }\n const record = usage as Record<string, unknown>;\n const inputTokens = numberField(record, \"input_tokens\");\n const outputTokens = numberField(record, \"output_tokens\");\n const totalTokens =\n inputTokens !== undefined && outputTokens !== undefined\n ? inputTokens + outputTokens\n : undefined;\n return {\n ...(inputTokens !== undefined ? { inputTokens } : {}),\n ...(outputTokens !== undefined ? { outputTokens } : {}),\n ...(totalTokens !== undefined ? { totalTokens } : {}),\n };\n}\n\nfunction numberField(record: Record<string, unknown>, key: string): number | undefined {\n const value = record[key];\n return typeof value === \"number\" ? value : undefined;\n}\n","import type { ArtifactInput } from \"../artifacts/artifact.js\";\nimport type {\n ModelCapability,\n ProviderAdapter,\n ProviderRunRequest,\n ProviderRunResponse,\n Usage,\n} from \"./provider.js\";\nimport { defaultCapabilityForProvider } from \"../routing/catalog.js\";\n\nexport interface FakeProviderOptions {\n readonly id?: string;\n readonly modelId?: string;\n readonly response?:\n | ProviderRunResponse\n | ((request: ProviderRunRequest) => ProviderRunResponse | Promise<ProviderRunResponse>);\n readonly artifacts?: readonly ArtifactInput[];\n /**\n * Phase 7 addition: when provided, REPLACES the default single-capability\n * array so callers (notably Plan 07-04's modality/privacy reject tests)\n * can construct a fake adapter with arbitrary\n * `inputModalities` / `outputModalities` / `dataPolicy` / `pricing`\n * without mutating the returned adapter's readonly `capabilities` array.\n * When omitted, the existing default capability is used.\n */\n readonly capabilities?: readonly ModelCapability[];\n}\n\nconst DEFAULT_FAKE_USAGE: Usage = {\n promptTokens: 0,\n completionTokens: 0,\n costUsd: null,\n};\n\nexport function createFakeProvider(options: FakeProviderOptions = {}): ProviderAdapter {\n const id = options.id ?? \"fake\";\n const modelId = options.modelId ?? `${id}:deterministic`;\n const defaultCapability: ModelCapability = {\n ...defaultCapabilityForProvider(id),\n modelId,\n inputModalities: [\"text\", \"json\", \"image\", \"audio\", \"document\", \"file\", \"url\", \"tool\"],\n outputModalities: [\"text\", \"json\"],\n toolUse: true,\n };\n const capabilities = options.capabilities ?? [defaultCapability];\n\n return {\n id,\n kind: \"provider-adapter\",\n capabilities,\n async execute(request) {\n const baseResponse =\n typeof options.response === \"function\"\n ? await options.response(request)\n : options.response;\n\n if (baseResponse !== undefined) {\n return baseResponse.normalizedUsage !== undefined\n ? baseResponse\n : { ...baseResponse, normalizedUsage: { ...DEFAULT_FAKE_USAGE } };\n }\n\n return {\n rawOutputs: Object.fromEntries(\n request.outputs.map((name) => [name, defaultOutputForName(name)]),\n ),\n ...(options.artifacts !== undefined ? { artifactRefs: options.artifacts } : {}),\n normalizedUsage: { ...DEFAULT_FAKE_USAGE },\n };\n },\n };\n}\n\nfunction defaultOutputForName(name: string): unknown {\n if (/action|json|data|decision/u.test(name)) {\n return {\n kind: \"clarify\",\n reason: \"fake provider default structured response\",\n };\n }\n\n if (/citations|evidence/u.test(name)) {\n return [];\n }\n\n if (/generated|artifacts/u.test(name)) {\n return [];\n }\n\n return `Fake response for ${name}.`;\n}\n","import type { UsageRecord } from \"../plan/plan.js\";\nimport type { ProviderAdapter, ProviderRunResponse, Usage } from \"./provider.js\";\nimport { defaultCapabilityForProvider } from \"../routing/catalog.js\";\n\n/**\n * Options for {@link createGeminiProvider}.\n *\n * Mirrors `OpenAICompatibleProviderOptions` ergonomics (Phase 7 pattern) but\n * for Google's Generative Language API at\n * `/v1beta/models/{model}:generateContent` -- which uses `contents[].parts[].text`\n * (NOT OpenAI's `messages[]`), `role: \"model\"` for assistant turns (NOT\n * `\"assistant\"`), authenticates via `?key=` query string, and applies a\n * 4-category `safetySettings` block at `BLOCK_NONE` thresholds (FSB convention\n * mirrored from `extension/ai/universal-provider.js:255-272`).\n *\n * SECURITY: `apiKey` is a runtime parameter -- do NOT hardcode or log it.\n *\n * DEFERRED (Phase 4 carryforward notes):\n * - multimodal (vision) -- deferred\n * - streaming -- deferred (single-shot Promise per CONTEXT.md D-06)\n * - tool use -- deferred\n * - resume-from-eviction -- see Phase 5 (MV3-survivability adapter contract)\n *\n * Ref: FSB v0.10.0-attempt-2 Phase 4 (D-02 + D-07: full custom adapter; preserve role:\"model\").\n */\nexport interface GeminiProviderOptions {\n readonly id?: string;\n readonly model: string;\n readonly apiKey: string;\n /** Defaults to `https://generativelanguage.googleapis.com`. */\n readonly baseUrl?: string;\n readonly fetch?: typeof fetch;\n readonly pricing?: {\n readonly inputPer1kTokens?: number;\n readonly outputPer1kTokens?: number;\n };\n}\n\nconst DEFAULT_BASE_URL = \"https://generativelanguage.googleapis.com\";\nconst DEFAULT_MAX_OUTPUT_TOKENS = 2000;\nconst DEFAULT_TEMPERATURE = 0.7;\nconst DEFAULT_TOP_P = 0.9;\n\n/**\n * 4 HARM_CATEGORY entries at BLOCK_NONE (FSB convention mirrored from\n * `extension/ai/universal-provider.js:255-272`). If Google restricts\n * BLOCK_NONE in the future, that is a re-spec concern, not a Phase 4\n * design defect (CONTEXT.md Specific Ideas note).\n */\nconst SAFETY_SETTINGS = [\n { category: \"HARM_CATEGORY_HARASSMENT\", threshold: \"BLOCK_NONE\" },\n { category: \"HARM_CATEGORY_HATE_SPEECH\", threshold: \"BLOCK_NONE\" },\n { category: \"HARM_CATEGORY_SEXUALLY_EXPLICIT\", threshold: \"BLOCK_NONE\" },\n { category: \"HARM_CATEGORY_DANGEROUS_CONTENT\", threshold: \"BLOCK_NONE\" },\n] as const;\n\nexport function createGeminiProvider(options: GeminiProviderOptions): ProviderAdapter {\n const id = options.id ?? \"gemini\";\n const fetchImpl = options.fetch ?? fetch;\n const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/u, \"\");\n\n return {\n id,\n kind: \"provider-adapter\",\n capabilities: [\n {\n ...defaultCapabilityForProvider(id),\n modelId: options.model,\n fileTransport: [\"inline\", \"json\", \"url\", \"base64\", \"extracted-text\", \"transcript\"],\n },\n ],\n async execute(request) {\n const init: RequestInit = {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n contents: [\n {\n role: \"user\",\n parts: [{ text: request.task }],\n },\n ],\n generationConfig: {\n temperature: DEFAULT_TEMPERATURE,\n topP: DEFAULT_TOP_P,\n maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,\n },\n safetySettings: SAFETY_SETTINGS,\n }),\n ...(request.signal !== undefined ? { signal: request.signal } : {}),\n };\n\n const url = `${baseUrl}/v1beta/models/${encodeURIComponent(options.model)}:generateContent?key=${encodeURIComponent(options.apiKey)}`;\n const response = await fetchImpl(url, init);\n\n if (!response.ok) {\n throw new Error(`Gemini provider failed with ${response.status}.`);\n }\n\n const body = (await response.json()) as {\n candidates?: readonly {\n content?: { parts?: readonly { text?: unknown }[] };\n }[];\n usageMetadata?: unknown;\n };\n\n if (!Array.isArray(body.candidates) || body.candidates.length === 0) {\n throw new Error(\"Gemini provider returned no candidates.\");\n }\n\n const text = String(body.candidates[0]?.content?.parts?.[0]?.text ?? \"\");\n const usage = normalizeGeminiUsage(body.usageMetadata);\n const normalizedUsage = normalizeGeminiUsageToRunUsage(body.usageMetadata, options.pricing);\n\n return {\n rawOutputs: Object.fromEntries(request.outputs.map((name) => [name, text])),\n ...(usage !== undefined ? { usage } : {}),\n normalizedUsage,\n rawResponse: body,\n };\n },\n };\n}\n\n/**\n * Gemini uses `usageMetadata.promptTokenCount` / `candidatesTokenCount` /\n * `totalTokenCount` (NOT OpenAI's `prompt_tokens` / `completion_tokens`).\n * This helper maps to Lattice's `Usage` shape and applies pricing when supplied.\n */\nfunction normalizeGeminiUsageToRunUsage(\n rawUsage: unknown,\n pricing?: {\n readonly inputPer1kTokens?: number;\n readonly outputPer1kTokens?: number;\n },\n): Usage {\n let promptTokens = 0;\n let completionTokens = 0;\n if (typeof rawUsage === \"object\" && rawUsage !== null) {\n const record = rawUsage as Record<string, unknown>;\n promptTokens = numberField(record, \"promptTokenCount\") ?? 0;\n completionTokens = numberField(record, \"candidatesTokenCount\") ?? 0;\n }\n let costUsd: number | null = null;\n if (\n pricing !== undefined &&\n (pricing.inputPer1kTokens !== undefined || pricing.outputPer1kTokens !== undefined)\n ) {\n const inputCost = ((pricing.inputPer1kTokens ?? 0) * promptTokens) / 1000;\n const outputCost = ((pricing.outputPer1kTokens ?? 0) * completionTokens) / 1000;\n costUsd = inputCost + outputCost;\n }\n return { promptTokens, completionTokens, costUsd };\n}\n\nfunction normalizeGeminiUsage(usage: unknown): UsageRecord | undefined {\n if (typeof usage !== \"object\" || usage === null) {\n return undefined;\n }\n const record = usage as Record<string, unknown>;\n const inputTokens = numberField(record, \"promptTokenCount\");\n const outputTokens = numberField(record, \"candidatesTokenCount\");\n const totalTokens = numberField(record, \"totalTokenCount\");\n return {\n ...(inputTokens !== undefined ? { inputTokens } : {}),\n ...(outputTokens !== undefined ? { outputTokens } : {}),\n ...(totalTokens !== undefined ? { totalTokens } : {}),\n };\n}\n\nfunction numberField(record: Record<string, unknown>, key: string): number | undefined {\n const value = record[key];\n return typeof value === \"number\" ? value : undefined;\n}\n","import type { ProviderAdapter } from \"./provider.js\";\nimport { createOpenAICompatibleProvider, type OpenAICompatibleProviderOptions } from \"./adapters.js\";\n\n/**\n * Options for {@link createLmStudioProvider}.\n *\n * Thin wrapper around {@link createOpenAICompatibleProvider} pinned to\n * LM Studio's default local server URL `http://localhost:1234/v1`. Wire\n * shape is OpenAI Chat Completions. LM Studio is no-auth by convention\n * (CD-03): `apiKey` is OPTIONAL; when omitted, the underlying factory\n * sends no `Authorization` header (see\n * `lattice/packages/lattice/src/providers/adapters.ts:53` for the\n * conditional auth-header wiring).\n *\n * DEFERRED (D-16 carryforward):\n * - latency-tail diagnostics -- observability concern; LM Studio is\n * the canary for latency tails (INV-03);\n * diagnostics module deferred to a\n * follow-on observability phase.\n * - streaming -- deferred (single-shot per D-06).\n * - resume-from-eviction -- see Phase 5 (MV3-survivability adapter).\n *\n * Ref: FSB v0.10.0-attempt-2 Phase 4 (D-03: thin wrapper; D-16: latency-tail deferred; CD-03 no-opt-out).\n */\nexport interface LmStudioProviderOptions\n extends Omit<OpenAICompatibleProviderOptions, \"id\" | \"baseUrl\" | \"apiKey\"> {\n readonly id?: string;\n /** Defaults to `http://localhost:1234/v1`. Override for non-localhost deployments. */\n readonly baseUrl?: string;\n /**\n * Optional. LM Studio is no-auth by convention (CD-03 default).\n * When provided, sent as `Authorization: Bearer <apiKey>` (matches the\n * underlying OpenAI-compat factory). Use only for proxied LM Studio\n * deployments that have a token gate in front.\n */\n readonly apiKey?: string;\n}\n\nconst DEFAULT_LM_STUDIO_BASE_URL = \"http://localhost:1234/v1\";\n\nexport function createLmStudioProvider(options: LmStudioProviderOptions): ProviderAdapter {\n return createOpenAICompatibleProvider({\n ...options,\n id: options.id ?? \"lm-studio\",\n baseUrl: options.baseUrl ?? DEFAULT_LM_STUDIO_BASE_URL,\n });\n}\n","import type { ProviderAdapter } from \"./provider.js\";\nimport { createOpenAICompatibleProvider, type OpenAICompatibleProviderOptions } from \"./adapters.js\";\n\n/**\n * Options for {@link createOpenRouterProvider}.\n *\n * Thin wrapper around {@link createOpenAICompatibleProvider} pinned to\n * OpenRouter's base URL `https://openrouter.ai/api/v1`. Wire shape is\n * OpenAI Chat Completions; no provider-specific quirks at the\n * single-shot Promise contract level.\n *\n * SECURITY: `apiKey` is a runtime parameter -- do NOT hardcode or log it.\n *\n * DEFERRED (D-17 carryforward; Phase 4 ships the named adapter as a\n * first-class OpenAI-compat wrapper):\n * - model-routing array -- caller supplies `model` (single id); OpenRouter's\n * `models: [primary, fallback, ...]` array\n * feature is deferred to a follow-on phase.\n * - fallback-array -- deferred (same phase as model-routing).\n * - per-message routing -- deferred.\n * - streaming -- deferred (single-shot per CONTEXT.md D-06).\n * - resume-from-eviction -- see Phase 5 (MV3-survivability adapter).\n *\n * Ref: FSB v0.10.0-attempt-2 Phase 4 (D-03: thin wrapper; D-17: model-routing deferred).\n */\nexport interface OpenRouterProviderOptions\n extends Omit<OpenAICompatibleProviderOptions, \"id\" | \"baseUrl\"> {\n readonly id?: string;\n /** Defaults to `https://openrouter.ai/api/v1`. Override for proxies. */\n readonly baseUrl?: string;\n}\n\nconst DEFAULT_OPENROUTER_BASE_URL = \"https://openrouter.ai/api/v1\";\n\nexport function createOpenRouterProvider(options: OpenRouterProviderOptions): ProviderAdapter {\n return createOpenAICompatibleProvider({\n ...options,\n id: options.id ?? \"openrouter\",\n baseUrl: options.baseUrl ?? DEFAULT_OPENROUTER_BASE_URL,\n });\n}\n","import type { ProviderAdapter } from \"./provider.js\";\nimport { createOpenAICompatibleProvider, type OpenAICompatibleProviderOptions } from \"./adapters.js\";\n\n/**\n * Options for {@link createXaiProvider}.\n *\n * Thin wrapper around {@link createOpenAICompatibleProvider} pinned to\n * xAI's base URL `https://api.x.ai/v1`. The wire shape is identical to\n * OpenAI Chat Completions, with one provider-specific quirk preserved:\n * `response.usage.completion_tokens_details.reasoning_tokens` (xAI's\n * separate reasoning-token accounting; see FSB\n * `extension/ai/universal-provider.js:585-594` for the production reference).\n *\n * SECURITY: `apiKey` is a runtime parameter -- do NOT hardcode or log it.\n *\n * DEFERRED (Phase 4 carryforward notes):\n * - tool-streaming -- deferred\n * - streaming -- deferred (single-shot Promise per CONTEXT.md D-06)\n * - resume-from-eviction -- see Phase 5 (MV3-survivability adapter contract)\n *\n * Ref: FSB v0.10.0-attempt-2 Phase 4 (D-03 + D-07: thin wrapper; reasoning_tokens quirk preserved).\n */\nexport interface XaiProviderOptions extends Omit<OpenAICompatibleProviderOptions, \"id\" | \"baseUrl\"> {\n readonly id?: string;\n /** Defaults to `https://api.x.ai/v1`. Override for proxies. */\n readonly baseUrl?: string;\n}\n\nconst DEFAULT_XAI_BASE_URL = \"https://api.x.ai/v1\";\n\nexport function createXaiProvider(options: XaiProviderOptions): ProviderAdapter {\n const inner = createOpenAICompatibleProvider({\n ...options,\n id: options.id ?? \"xai\",\n baseUrl: options.baseUrl ?? DEFAULT_XAI_BASE_URL,\n });\n const innerExecute = inner.execute;\n if (innerExecute === undefined) {\n return inner;\n }\n return {\n ...inner,\n async execute(request) {\n const response = await innerExecute(request);\n // D-07: PRESERVE xAI's `completion_tokens_details.reasoning_tokens`\n // quirk. The default OpenAI-compat usage extractor does not surface\n // reasoning_tokens; we inspect rawResponse and augment the legacy\n // UsageRecord when the field is present. The Phase 7 normalized\n // `Usage` (promptTokens/completionTokens/costUsd) is unchanged by\n // design -- normalized usage represents billable tokens; reasoning_tokens\n // is xAI-extra-counts that consumers access via rawResponse for now.\n const raw = response.rawResponse as\n | {\n usage?: {\n completion_tokens_details?: { reasoning_tokens?: unknown };\n };\n }\n | undefined;\n const reasoningTokens = raw?.usage?.completion_tokens_details?.reasoning_tokens;\n if (typeof reasoningTokens === \"number\" && response.usage !== undefined) {\n const inputTokens = response.usage.inputTokens ?? 0;\n const outputTokens = response.usage.outputTokens ?? 0;\n return {\n ...response,\n usage: {\n ...response.usage,\n // Recompute totalTokens INCLUDING reasoning tokens (matches\n // FSB universal-provider.js:593 production behavior).\n totalTokens: inputTokens + outputTokens + reasoningTokens,\n },\n };\n }\n return response;\n },\n };\n}\n","import type { ArtifactRef } from \"../artifacts/artifact.js\";\nimport type { OutputContractMap } from \"../outputs/contracts.js\";\nimport type {\n CapabilityModality,\n ModelCapability,\n ProviderTransportMode,\n} from \"../providers/provider.js\";\n\nexport type ExecutionPlanStatus =\n | \"stub\"\n | \"planned\"\n | \"no-route\"\n | \"running\"\n | \"completed\"\n | \"failed\";\n\nexport type ExecutionStageKind =\n | \"analysis\"\n | \"transforms\"\n | \"context-packing\"\n | \"provider-packaging\"\n | \"tool-execution\"\n | \"execution\"\n | \"validation\"\n | \"tripwire\"\n | \"persistence\"\n | \"replay\";\n\nexport type ExecutionStageStatus =\n | \"pending\"\n | \"running\"\n | \"completed\"\n | \"skipped\"\n | \"failed\";\n\nexport interface ExecutionPlanStage {\n readonly id: string;\n readonly kind: ExecutionStageKind;\n readonly status: ExecutionStageStatus;\n readonly inputArtifacts?: readonly string[];\n readonly outputArtifacts?: readonly string[];\n readonly warnings: readonly string[];\n readonly metadata?: Record<string, unknown>;\n}\n\nexport interface RouteRejectReason {\n readonly code: string;\n readonly message: string;\n}\n\nexport interface RouteCandidate {\n readonly providerId: string;\n readonly modelId: string;\n readonly capability: ModelCapability;\n readonly score: number;\n readonly accepted: boolean;\n readonly reasons: readonly RouteRejectReason[];\n readonly estimates: RouteEstimates;\n}\n\nexport interface RouteEstimates {\n readonly inputTokens: number;\n readonly outputTokens: number;\n readonly costUsd?: number;\n readonly latencyMs?: number;\n}\n\nexport interface SelectedRoute {\n readonly providerId: string;\n readonly modelId: string;\n readonly score: number;\n readonly estimates: RouteEstimates;\n readonly inputModalities: readonly CapabilityModality[];\n readonly outputModalities: readonly CapabilityModality[];\n readonly fileTransport: readonly ProviderTransportMode[];\n}\n\nexport interface FallbackRoute {\n readonly providerId: string;\n readonly modelId: string;\n readonly score: number;\n readonly reason: \"policy-preserving-fallback\";\n}\n\nexport interface RouteDecision {\n readonly catalogVersion: string;\n readonly selected?: SelectedRoute;\n readonly candidates: readonly RouteCandidate[];\n readonly rejected: readonly RouteCandidate[];\n readonly fallbackChain: readonly FallbackRoute[];\n readonly noRouteReasons: readonly RouteRejectReason[];\n}\n\nexport interface ContextPackPlan {\n readonly id: string;\n readonly tokenBudget: number;\n readonly estimatedTokens: number;\n readonly included: readonly ContextPackItemPlan[];\n readonly summarized: readonly ContextPackItemPlan[];\n readonly archived: readonly ContextPackItemPlan[];\n readonly omitted: readonly ContextPackItemPlan[];\n readonly warnings: readonly string[];\n}\n\nexport interface ContextPackItemPlan {\n readonly artifactId?: string;\n readonly sessionTurnId?: string;\n readonly reason: string;\n readonly estimatedTokens: number;\n readonly trust: \"developer\" | \"user\" | \"tool\" | \"model-summary\";\n}\n\nexport interface ProviderPackagingPlan {\n readonly providerId: string;\n readonly modelId: string;\n readonly artifacts: readonly ProviderPackagedArtifactPlan[];\n readonly warnings: readonly string[];\n}\n\nexport interface ProviderPackagedArtifactPlan {\n readonly artifactId: string;\n readonly transport: ProviderTransportMode;\n readonly mediaType?: string;\n readonly lineageTransform: \"provider-packaging\";\n readonly warnings: readonly string[];\n}\n\nexport interface ProviderAttemptRecord {\n readonly providerId: string;\n readonly modelId: string;\n readonly status: \"pending\" | \"running\" | \"succeeded\" | \"failed\" | \"cancelled\";\n readonly startedAt?: string;\n readonly completedAt?: string;\n readonly error?: string;\n readonly usage?: UsageRecord;\n}\n\nexport interface UsageRecord {\n readonly inputTokens?: number;\n readonly outputTokens?: number;\n readonly totalTokens?: number;\n readonly costUsd?: number;\n readonly latencyMs?: number;\n}\n\nexport interface ExecutionPlan {\n readonly id: string;\n readonly kind: \"execution-plan\";\n readonly version: 1;\n readonly createdAt: string;\n readonly status: ExecutionPlanStatus;\n readonly task: string;\n readonly outputNames: readonly string[];\n readonly artifactRefs: readonly ArtifactRef[];\n readonly route: RouteDecision;\n readonly stages: readonly ExecutionPlanStage[];\n readonly context?: ContextPackPlan;\n readonly providerPackaging?: ProviderPackagingPlan;\n readonly attempts: readonly ProviderAttemptRecord[];\n readonly warnings: readonly string[];\n readonly metadata?: Record<string, unknown>;\n}\n\nexport interface ExecutionPlanStub {\n readonly id: string;\n readonly kind: \"plan-stub\";\n readonly createdAt: string;\n readonly status: \"stub\";\n readonly stages: readonly [];\n readonly warnings: readonly string[];\n}\n\nexport type ResultPlan = ExecutionPlan | ExecutionPlanStub;\n\nexport interface CreateExecutionPlanInput {\n readonly task: string;\n readonly artifacts: readonly ArtifactRef[];\n readonly outputs: OutputContractMap;\n readonly route: RouteDecision;\n readonly context?: ContextPackPlan;\n readonly providerPackaging?: ProviderPackagingPlan;\n readonly warnings?: readonly string[];\n readonly metadata?: Record<string, unknown>;\n}\n\nexport function createExecutionPlan(input: CreateExecutionPlanInput): ExecutionPlan {\n const selected = input.route.selected;\n const status: ExecutionPlanStatus = selected === undefined ? \"no-route\" : \"planned\";\n const contextWarnings = input.context?.warnings ?? [];\n const packagingWarnings = input.providerPackaging?.warnings ?? [];\n const warnings = [\n ...(input.warnings ?? []),\n ...contextWarnings,\n ...packagingWarnings,\n ...input.route.noRouteReasons.map((reason) => reason.message),\n ];\n\n return {\n id: createPlanId(),\n kind: \"execution-plan\",\n version: 1,\n createdAt: new Date().toISOString(),\n status,\n task: input.task,\n outputNames: Object.keys(input.outputs),\n artifactRefs: input.artifacts,\n route: input.route,\n stages: createDefaultStages(status, input.artifacts, warnings),\n ...(input.context !== undefined ? { context: input.context } : {}),\n ...(input.providerPackaging !== undefined\n ? { providerPackaging: input.providerPackaging }\n : {}),\n attempts:\n selected === undefined\n ? []\n : [\n {\n providerId: selected.providerId,\n modelId: selected.modelId,\n status: \"pending\",\n },\n ],\n warnings,\n ...(input.metadata !== undefined ? { metadata: input.metadata } : {}),\n };\n}\n\nexport function createExecutionPlanStub(\n warnings: readonly string[] = [],\n): ExecutionPlanStub {\n return {\n id: createPlanId(),\n kind: \"plan-stub\",\n createdAt: new Date().toISOString(),\n status: \"stub\",\n stages: [],\n warnings: [...warnings],\n };\n}\n\nexport function withPlanStatus(\n plan: ExecutionPlan,\n status: ExecutionPlanStatus,\n updates: {\n readonly stages?: readonly ExecutionPlanStage[];\n readonly attempts?: readonly ProviderAttemptRecord[];\n readonly warnings?: readonly string[];\n } = {},\n): ExecutionPlan {\n return {\n ...plan,\n status,\n ...(updates.stages !== undefined ? { stages: updates.stages } : {}),\n ...(updates.attempts !== undefined ? { attempts: updates.attempts } : {}),\n ...(updates.warnings !== undefined ? { warnings: updates.warnings } : {}),\n };\n}\n\nexport function markStage(\n stages: readonly ExecutionPlanStage[],\n kind: ExecutionStageKind,\n status: ExecutionStageStatus,\n metadata?: Record<string, unknown>,\n): readonly ExecutionPlanStage[] {\n return stages.map((stage) =>\n stage.kind === kind\n ? {\n ...stage,\n status,\n ...(metadata !== undefined\n ? { metadata: { ...stage.metadata, ...metadata } }\n : {}),\n }\n : stage,\n );\n}\n\nfunction createDefaultStages(\n status: ExecutionPlanStatus,\n artifacts: readonly ArtifactRef[],\n warnings: readonly string[],\n): readonly ExecutionPlanStage[] {\n const skipped = status === \"no-route\";\n const artifactIds = artifacts.map((artifact) => artifact.id);\n\n return [\n {\n id: \"stage:analysis\",\n kind: \"analysis\",\n status: \"completed\",\n inputArtifacts: artifactIds,\n warnings: [],\n },\n {\n id: \"stage:transforms\",\n kind: \"transforms\",\n status: \"pending\",\n inputArtifacts: artifactIds,\n warnings: [],\n },\n {\n id: \"stage:context-packing\",\n kind: \"context-packing\",\n status: \"completed\",\n inputArtifacts: artifactIds,\n warnings: [],\n },\n {\n id: \"stage:provider-packaging\",\n kind: \"provider-packaging\",\n status: skipped ? \"skipped\" : \"completed\",\n inputArtifacts: artifactIds,\n warnings,\n },\n {\n id: \"stage:tool-execution\",\n kind: \"tool-execution\",\n status: \"pending\",\n warnings: [],\n },\n {\n id: \"stage:execution\",\n kind: \"execution\",\n status: skipped ? \"skipped\" : \"pending\",\n warnings: skipped ? warnings : [],\n },\n {\n id: \"stage:validation\",\n kind: \"validation\",\n status: skipped ? \"skipped\" : \"pending\",\n warnings: [],\n },\n {\n id: \"stage:tripwire\",\n kind: \"tripwire\",\n status: skipped ? \"skipped\" : \"pending\",\n warnings: [],\n },\n {\n id: \"stage:persistence\",\n kind: \"persistence\",\n status: \"pending\",\n warnings: [],\n },\n ];\n}\n\nfunction createPlanId(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return `plan:${crypto.randomUUID()}`;\n }\n\n return `plan:${Date.now()}:${Math.random().toString(16).slice(2)}`;\n}\n","export const latticeVersion = \"0.0.0\";\n","/**\n * Phase 10 — materializeReplayEnvelope.\n *\n * Reconstructs a `ReplayEnvelope` from a signed `ReceiptEnvelope` plus a\n * pluggable artifact loader. The flow is:\n *\n * 1. verifyReceipt(receipt, keySet) — REQUIRED before any other work.\n * A tampered or revoked receipt MUST short-circuit before the artifact\n * loader is invoked (no side effects on bad input).\n * 2. Parse the verified body to learn `inputHashes`.\n * 3. Invoke `artifactLoader(hash)` once per input hash, in order.\n * 4. Assemble a `ReplayEnvelope` whose `plan` reproduces the receipt's\n * route/usage fields, attach the receipt itself, and (optionally) the\n * caller-supplied contract / task / outputs / policy.\n *\n * v1.1 limitation: the receipt body does NOT carry the original task string,\n * outputs schema, or policy snapshot. Callers may supply them via the options\n * bag; when omitted, the envelope's `task` defaults to \"\" and `outputs`\n * remains undefined. Phase 11's `lattice repro` CLI accepts a sidecar JSON\n * file to populate these fields.\n *\n * Errors NEVER cross the boundary as plain `Error`. All failures surface as\n * typed `MaterializationError` values thrown from the async function so the\n * caller can pattern-match on `error.kind` (and a `MaterializationError` IS\n * a thrown object whose `kind` discriminates the failure mode).\n */\n\nimport type { ArtifactInput } from \"../artifacts/artifact.js\";\nimport { toArtifactRef } from \"../artifacts/artifact.js\";\nimport type { CapabilityContract } from \"../contract/contract.js\";\nimport type { OutputContractMap } from \"../outputs/contracts.js\";\nimport type { InferOutputMap } from \"../outputs/infer.js\";\nimport { createExecutionPlan, type ExecutionPlan, type UsageRecord } from \"../plan/plan.js\";\nimport type { PolicySpec } from \"../policy/policy.js\";\nimport type { CapabilityModality } from \"../providers/provider.js\";\nimport type {\n CapabilityReceiptBody,\n KeySet,\n ReceiptEnvelope,\n} from \"../receipts/types.js\";\nimport { verifyReceipt } from \"../receipts/verify.js\";\nimport { latticeVersion } from \"../version.js\";\n\nimport type { ReplayEnvelope } from \"./replay.js\";\n\n/**\n * Discriminated union of materialization failure modes.\n *\n * - \"verify-failed\" — receipt failed verifyReceipt (signature, key\n * missing/revoked, canonicalization mismatch).\n * - \"artifact-load-failed\" — the artifactLoader callback rejected for at\n * least one input hash.\n * - \"envelope-malformed\" — receipt verified but the verified body is\n * structurally unusable (should never happen\n * under verifyReceipt invariants, but kept as a\n * defensive third branch).\n */\nexport interface MaterializationError {\n readonly kind: \"verify-failed\" | \"artifact-load-failed\" | \"envelope-malformed\";\n readonly message: string;\n}\n\nfunction asMaterializationError(value: unknown): value is MaterializationError {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { kind?: unknown }).kind === \"string\" &&\n typeof (value as { message?: unknown }).message === \"string\"\n );\n}\n\n/** Throwable shape — `instanceof Error` is not required for typed unions, so\n * the function just throws a plain object literal that matches the\n * `MaterializationError` shape. Callers pattern-match on `err.kind`. */\nfunction fail(\n kind: MaterializationError[\"kind\"],\n message: string,\n): MaterializationError {\n return { kind, message };\n}\n\n/**\n * Async callback that resolves an artifact body from its sha256 hex digest.\n * Phase 10 ships only the in-memory variant for tests. Phase 11's CLI plugs\n * in a filesystem-backed loader reading from `.lattice/fixtures/<sha256>.bin`.\n */\nexport type ArtifactLoader = (hash: string) => Promise<ArtifactInput>;\n\nexport interface MaterializeReplayEnvelopeOptions<\n TOutputs extends OutputContractMap = OutputContractMap,\n> {\n readonly artifactLoader: ArtifactLoader;\n readonly keySet: KeySet;\n /** Optional original task string. Defaults to \"\" when omitted. */\n readonly task?: string;\n /**\n * Optional caller-supplied outputs map. When provided, the resulting\n * `ReplayEnvelope.outputs` is populated and `replayOffline` will return\n * an `ok: true` result. When omitted, `replayOffline` reports an\n * `execution_unavailable` failure (current Phase 5 semantics).\n */\n readonly outputs?: InferOutputMap<TOutputs>;\n readonly policy?: PolicySpec;\n readonly contract?: CapabilityContract;\n}\n\n/**\n * Pure async function that reconstructs a `ReplayEnvelope` from a receipt.\n *\n * Verify-FIRST ordering: `verifyReceipt` runs before `artifactLoader` is\n * touched. Tampered receipts MUST NOT cause loader side effects.\n */\nexport async function materializeReplayEnvelope<\n TOutputs extends OutputContractMap = OutputContractMap,\n>(\n receipt: ReceiptEnvelope,\n options: MaterializeReplayEnvelopeOptions<TOutputs>,\n): Promise<ReplayEnvelope<TOutputs>> {\n // Step 1: verify FIRST. No artifact loader call before this resolves.\n const verifyResult = await verifyReceipt(receipt, options.keySet);\n if (!verifyResult.ok) {\n throw fail(\n verifyResult.error.kind === \"envelope-malformed\"\n ? \"envelope-malformed\"\n : \"verify-failed\",\n verifyResult.error.message,\n );\n }\n\n const body: CapabilityReceiptBody = verifyResult.body;\n\n // Step 2: load every artifact referenced by the receipt's inputHashes.\n // We treat any loader rejection as `artifact-load-failed` and surface the\n // underlying message — the loader is the system boundary, so its error\n // text is the most informative thing we have.\n const loadedInputs: ArtifactInput[] = [];\n for (const hash of body.inputHashes) {\n if (hash === \"\") {\n // Skip empty-hash slots — Phase 9 emits \"\" for unfingerprintable\n // values (e.g., undefined artifact bodies). They have no resolvable\n // content and the replay artifacts array preserves order via the\n // remaining loaded entries.\n continue;\n }\n try {\n const input = await options.artifactLoader(hash);\n loadedInputs.push(input);\n } catch (error) {\n const message =\n error instanceof Error\n ? error.message\n : asMaterializationError(error)\n ? error.message\n : String(error);\n throw fail(\"artifact-load-failed\", message);\n }\n }\n\n // Step 3: assemble the ExecutionPlan envelope shell. The receipt does NOT\n // carry the full RouteDecision/ContextPack — we synthesize a minimal but\n // valid plan that reproduces the receipt's route + usage fields. This is\n // intentionally lossy and matches the v1.1 limitation note in 10-CONTEXT.md.\n const artifactRefs = loadedInputs.map(toArtifactRef);\n const outputsMap = (options.outputs !== undefined\n ? (Object.fromEntries(\n Object.keys(options.outputs as Record<string, unknown>).map((k) => [\n k,\n \"text\" as const,\n ]),\n ) as OutputContractMap)\n : ({} as OutputContractMap));\n\n const plan: ExecutionPlan = createExecutionPlan({\n task: options.task ?? \"\",\n artifacts: artifactRefs,\n outputs: outputsMap,\n route: {\n catalogVersion: \"materialized\",\n selected: {\n providerId: body.route.providerId,\n modelId: body.route.capabilityId,\n score: 0,\n estimates: { inputTokens: 0, outputTokens: 0 },\n inputModalities: [] as readonly CapabilityModality[],\n outputModalities: [] as readonly CapabilityModality[],\n fileTransport: [],\n },\n candidates: [],\n rejected: [],\n fallbackChain: [],\n noRouteReasons: [],\n },\n warnings: [],\n metadata: {\n materialized: true,\n receiptId: body.receiptId,\n runId: body.runId,\n contractVerdict: body.contractVerdict,\n ...(options.policy !== undefined ? { policy: { ...options.policy } } : {}),\n },\n });\n\n const usage: UsageRecord = {\n inputTokens: body.usage.promptTokens,\n outputTokens: body.usage.completionTokens,\n ...(body.usage.costUsd !== null\n ? { costUsd: Number(body.usage.costUsd) }\n : {}),\n };\n\n const envelope: ReplayEnvelope<TOutputs> = {\n kind: \"replay-envelope\",\n version: 1,\n runtimeVersion: latticeVersion,\n catalogVersion: \"materialized\",\n createdAt: new Date().toISOString(),\n plan,\n artifacts: artifactRefs,\n ...(options.outputs !== undefined ? { outputs: options.outputs } : {}),\n warnings: [],\n errors: [],\n usage,\n events: [],\n receipt,\n ...(options.contract !== undefined ? { contract: options.contract } : {}),\n };\n\n return envelope;\n}\n","import type { ArtifactRef } from \"../artifacts/artifact.js\";\nimport type { CapabilityContract } from \"../contract/contract.js\";\nimport type { OutputContractMap } from \"../outputs/contracts.js\";\nimport type { InferOutputMap } from \"../outputs/infer.js\";\nimport type { ExecutionPlan, UsageRecord } from \"../plan/plan.js\";\nimport type { Usage } from \"../providers/provider.js\";\nimport type { ReceiptEnvelope } from \"../receipts/types.js\";\nimport type { RunResult } from \"../results/result.js\";\nimport type { AI, RunIntent } from \"../runtime/create-ai.js\";\nimport type { RunEvent } from \"../tracing/tracing.js\";\nimport { latticeVersion } from \"../version.js\";\n\nexport interface ReplayEnvelope<TOutputs extends OutputContractMap = OutputContractMap> {\n readonly kind: \"replay-envelope\";\n readonly version: 1;\n readonly runtimeVersion: string;\n readonly catalogVersion: string;\n readonly createdAt: string;\n readonly plan: ExecutionPlan;\n readonly artifacts: readonly ArtifactRef[];\n readonly outputs?: InferOutputMap<TOutputs>;\n readonly warnings: readonly string[];\n readonly errors: readonly string[];\n readonly usage?: UsageRecord;\n readonly events: readonly RunEvent[];\n /**\n * Phase 10 — optional signed receipt recorded alongside the envelope so a\n * single artifact is sufficient to materialize an offline replay session\n * deterministically. Type-only import — replay.ts stays runtime-import-free\n * of the receipts builder.\n */\n readonly receipt?: ReceiptEnvelope;\n /**\n * Phase 10 — optional contract recorded so replays can re-run pre-flight\n * checks deterministically.\n */\n readonly contract?: CapabilityContract;\n}\n\nexport function createReplayEnvelope<TOutputs extends OutputContractMap>(\n result: RunResult<TOutputs>,\n): ReplayEnvelope<TOutputs> {\n if (result.plan.kind !== \"execution-plan\") {\n throw new Error(\"Replay envelopes require an execution plan.\");\n }\n\n const usage = result.plan.attempts.at(-1)?.usage;\n\n return {\n kind: \"replay-envelope\",\n version: 1,\n runtimeVersion: latticeVersion,\n catalogVersion: result.plan.route.catalogVersion,\n createdAt: new Date().toISOString(),\n plan: redactPlan(result.plan),\n artifacts: result.ok ? result.artifacts : result.plan.artifactRefs,\n ...(result.ok ? { outputs: result.outputs } : {}),\n warnings: result.plan.warnings,\n errors: result.ok ? [] : [result.error.message],\n ...(usage !== undefined ? { usage } : {}),\n events: result.events ?? [],\n };\n}\n\nexport async function replayOffline<TOutputs extends OutputContractMap>(\n envelope: ReplayEnvelope<TOutputs>,\n): Promise<RunResult<TOutputs>> {\n const replayedUsage = envelopeUsage(envelope);\n if (envelope.outputs === undefined) {\n return {\n ok: false,\n error: {\n kind: \"execution_unavailable\",\n message: \"Replay envelope does not contain successful outputs.\",\n },\n usage: replayedUsage,\n plan: envelope.plan,\n events: envelope.events,\n };\n }\n\n return {\n ok: true,\n outputs: envelope.outputs,\n artifacts: envelope.artifacts,\n usage: replayedUsage,\n plan: envelope.plan,\n events: envelope.events,\n };\n}\n\nfunction envelopeUsage(envelope: ReplayEnvelope<OutputContractMap>): Usage {\n if (envelope.usage === undefined) {\n return { promptTokens: 0, completionTokens: 0, costUsd: null };\n }\n return {\n promptTokens: envelope.usage.inputTokens ?? 0,\n completionTokens: envelope.usage.outputTokens ?? 0,\n costUsd: envelope.usage.costUsd ?? null,\n };\n}\n\nexport async function rerunLive<TOutputs extends OutputContractMap>(\n ai: AI,\n envelope: ReplayEnvelope<TOutputs>,\n intent: RunIntent<TOutputs>,\n): Promise<RunResult<TOutputs>> {\n const result = await ai.run(intent);\n\n if (result.plan.kind === \"execution-plan\") {\n return {\n ...result,\n plan: {\n ...result.plan,\n warnings: [\n ...result.plan.warnings,\n `Live rerun of ${envelope.plan.id}: provider behavior, model versions, cost, and latency may differ.`,\n ],\n },\n };\n }\n\n return result;\n}\n\nexport function redactReplayEnvelope<TOutputs extends OutputContractMap>(\n envelope: ReplayEnvelope<TOutputs>,\n): ReplayEnvelope<TOutputs> {\n return {\n ...envelope,\n plan: redactPlan(envelope.plan),\n artifacts: envelope.artifacts.map(redactArtifactRef),\n events: envelope.events.map((event) => {\n const metadata = redactRecord(event.metadata);\n\n return {\n ...event,\n ...(metadata !== undefined ? { metadata } : {}),\n };\n }),\n };\n}\n\nexport function redactPlan(plan: ExecutionPlan): ExecutionPlan {\n return {\n ...plan,\n task: redactText(plan.task),\n artifactRefs: plan.artifactRefs.map(redactArtifactRef),\n ...(plan.providerPackaging !== undefined\n ? {\n providerPackaging: {\n ...plan.providerPackaging,\n artifacts: plan.providerPackaging.artifacts.map((item) => ({\n ...item,\n warnings: item.warnings.map(redactText),\n })),\n warnings: plan.providerPackaging.warnings.map(redactText),\n },\n }\n : {}),\n warnings: plan.warnings.map(redactText),\n };\n}\n\nexport function redactArtifactRef(ref: ArtifactRef): ArtifactRef {\n const redactedMetadata = redactRecord(ref.metadata);\n\n return {\n ...ref,\n ...(redactedMetadata !== undefined ? { metadata: redactedMetadata } : {}),\n ...(ref.source === \"url\"\n ? {\n metadata: {\n ...redactedMetadata,\n redactedSource: \"url\",\n },\n }\n : {}),\n };\n}\n\nfunction redactRecord(\n record: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n if (record === undefined) {\n return undefined;\n }\n\n return Object.fromEntries(\n Object.entries(record).map(([key, value]) => [\n key,\n shouldRedactKey(key) ? \"[redacted]\" : redactValue(value),\n ]),\n );\n}\n\nfunction redactValue(value: unknown): unknown {\n if (typeof value === \"string\") {\n return redactText(value);\n }\n\n if (Array.isArray(value)) {\n return value.map(redactValue);\n }\n\n if (typeof value === \"object\" && value !== null) {\n return redactRecord(value as Record<string, unknown>);\n }\n\n return value;\n}\n\nfunction redactText(value: string): string {\n return value\n .replace(/Bearer\\s+[A-Za-z0-9._-]+/gu, \"Bearer [redacted]\")\n .replace(/https?:\\/\\/[^\\s)]+/gu, \"[redacted-url]\")\n .replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}/gu, \"[redacted-email]\");\n}\n\nfunction shouldRedactKey(key: string): boolean {\n return /api.?key|authorization|token|secret|password|credential|signed.?url|raw|body|transcript/iu.test(key);\n}\n","/**\n * CostTracker — Phase 21 (v1.2).\n *\n * Pure accumulator over per-iteration `Usage`. Standalone (no dependency\n * on the agent runtime); callers can plug it in via a hook handler or\n * read it after a run completes.\n */\n\nimport type { BudgetInvariant } from \"../../contract/contract.js\";\nimport type { Usage } from \"../../providers/provider.js\";\n\nexport type CostBudgetStatus = \"ok\" | \"warning\" | \"exceeded\";\n\nexport interface CostTracker {\n readonly kind: \"cost-tracker\";\n /** Append a per-iteration Usage record. Mutates internal state. */\n recordIteration(usage: Usage): void;\n /** Returns the running sum across all recorded iterations. */\n total(): Usage;\n /**\n * Reports budget status against `contract.budget`:\n * - \"ok\" — under 80% of maxCostUsd.\n * - \"warning\" — at or over 80% but under 100%.\n * - \"exceeded\" — at or over 100% of maxCostUsd.\n * Returns \"ok\" when no budget is declared or when cumulative cost is null.\n */\n budgetStatus(budget?: BudgetInvariant): CostBudgetStatus;\n}\n\nconst WARNING_THRESHOLD = 0.8;\n\nexport function createCostTracker(): CostTracker {\n let promptTokens = 0;\n let completionTokens = 0;\n let costUsd: number | null = null;\n\n return {\n kind: \"cost-tracker\" as const,\n recordIteration(usage: Usage): void {\n promptTokens += usage.promptTokens;\n completionTokens += usage.completionTokens;\n if (usage.costUsd !== null) {\n costUsd = (costUsd ?? 0) + usage.costUsd;\n }\n },\n total(): Usage {\n return { promptTokens, completionTokens, costUsd };\n },\n budgetStatus(budget?: BudgetInvariant): CostBudgetStatus {\n const max = budget?.maxCostUsd;\n if (max === undefined || costUsd === null) return \"ok\";\n if (costUsd >= max) return \"exceeded\";\n if (costUsd >= max * WARNING_THRESHOLD) return \"warning\";\n return \"ok\";\n },\n };\n}\n","/**\n * TranscriptStore — Phase 21 (v1.2).\n *\n * Records the running conversation log with filtered tail reads sized for\n * context-window management. Always preserves the FIRST user turn (the\n * original task) in tail reads so the model retains its mission.\n */\n\nimport type { ConversationTurn } from \"../format-tools.js\";\n\n/**\n * Token estimator used by `tailByTokens`. The default ~4 chars / token is\n * the OpenAI rule of thumb for English text. Callers with provider-specific\n * tokenizers can supply their own.\n */\nexport type TokenEstimator = (text: string) => number;\n\nconst DEFAULT_TOKEN_ESTIMATOR: TokenEstimator = (text) => Math.ceil(text.length / 4);\n\nexport interface TranscriptStore {\n readonly kind: \"transcript-store\";\n append(turn: ConversationTurn): void;\n all(): readonly ConversationTurn[];\n /** Returns the first user turn (if any) + the most-recent `limit` turns. */\n tail(limit: number): readonly ConversationTurn[];\n /**\n * Returns the first user turn (if any) + the most-recent turns whose\n * combined token estimate fits within `maxTokens`. The default estimator\n * is the ~4 chars / token rule; callers can override for provider-\n * specific tokenizers.\n */\n tailByTokens(maxTokens: number, estimator?: TokenEstimator): readonly ConversationTurn[];\n}\n\nexport function createTranscriptStore(): TranscriptStore {\n const turns: ConversationTurn[] = [];\n\n function firstUserTurn(): ConversationTurn | null {\n for (const turn of turns) {\n if (turn.role === \"user\") return turn;\n }\n return null;\n }\n\n return {\n kind: \"transcript-store\" as const,\n append(turn: ConversationTurn): void {\n turns.push(turn);\n },\n all(): readonly ConversationTurn[] {\n return Object.freeze([...turns]);\n },\n tail(limit: number): readonly ConversationTurn[] {\n if (limit <= 0) return Object.freeze([]);\n if (turns.length <= limit) return Object.freeze([...turns]);\n const start = turns.length - limit;\n const tail = turns.slice(start);\n const first = firstUserTurn();\n if (first === null || tail.includes(first)) {\n return Object.freeze(tail);\n }\n return Object.freeze([first, ...tail]);\n },\n tailByTokens(\n maxTokens: number,\n estimator: TokenEstimator = DEFAULT_TOKEN_ESTIMATOR,\n ): readonly ConversationTurn[] {\n if (maxTokens <= 0) return Object.freeze([]);\n const reversed = [...turns].reverse();\n const selected: ConversationTurn[] = [];\n let used = 0;\n for (const turn of reversed) {\n const cost = estimator(turn.content);\n if (used + cost > maxTokens) break;\n selected.unshift(turn);\n used += cost;\n }\n const first = firstUserTurn();\n if (first !== null && !selected.includes(first)) {\n selected.unshift(first);\n }\n return Object.freeze(selected);\n },\n };\n}\n","/**\n * GoalProgressTracker — Phase 21 (v1.2).\n *\n * Stuck-detection primitive. The caller declares a goal-satisfaction\n * score per iteration (0..1); the tracker reports a coarse status the\n * agent loop can use to back off or surface to the human.\n */\n\nexport type ProgressStatus = \"progressing\" | \"stalled\" | \"regressed\";\n\nexport interface GoalProgressOptions {\n /**\n * Window of recent steps used for stall + regression detection.\n * Default 3. The tracker waits until it has at least this many steps\n * before reporting anything other than \"progressing\".\n */\n readonly windowSize?: number;\n /** Max satisfaction delta across the window to count as \"stalled\". Default 0.02. */\n readonly stallThreshold?: number;\n /** Min drop from prior max to count as \"regressed\". Default 0.1. */\n readonly regressionThreshold?: number;\n}\n\nexport interface GoalProgressStep {\n readonly iterationIndex: number;\n readonly goalSatisfaction: number;\n}\n\nexport interface GoalProgressTracker {\n readonly kind: \"goal-progress-tracker\";\n recordStep(step: GoalProgressStep): void;\n status(): ProgressStatus;\n}\n\nexport function createGoalProgressTracker(\n options: GoalProgressOptions = {},\n): GoalProgressTracker {\n const windowSize = options.windowSize ?? 3;\n const stallThreshold = options.stallThreshold ?? 0.02;\n const regressionThreshold = options.regressionThreshold ?? 0.1;\n const steps: GoalProgressStep[] = [];\n\n return {\n kind: \"goal-progress-tracker\" as const,\n recordStep(step: GoalProgressStep): void {\n steps.push(step);\n },\n status(): ProgressStatus {\n if (steps.length < windowSize) return \"progressing\";\n const window = steps.slice(-windowSize);\n const latest = window[window.length - 1]!;\n const earlierMax = steps\n .slice(0, -1)\n .reduce((m, s) => (s.goalSatisfaction > m ? s.goalSatisfaction : m), -Infinity);\n if (latest.goalSatisfaction < earlierMax - regressionThreshold) {\n return \"regressed\";\n }\n const min = window.reduce((m, s) => (s.goalSatisfaction < m ? s.goalSatisfaction : m), Infinity);\n const max = window.reduce((m, s) => (s.goalSatisfaction > m ? s.goalSatisfaction : m), -Infinity);\n if (max - min <= stallThreshold) {\n return \"stalled\";\n }\n return \"progressing\";\n },\n };\n}\n","/**\n * ActionHistory — Phase 21 (v1.2).\n *\n * Detects stuck patterns in the agent loop's tool-call sequence:\n * - \"consecutive-identical-tool-call\" — same (toolName, argsHash) N+ times in a row\n * - \"ping-pong\" — last 4 records alternate between 2 distinct (toolName, argsHash) pairs\n * - \"no-progress\" — reserved for callers wiring goal-progress feedback here\n *\n * Standalone (no dependency on the agent runtime); callers register the\n * primitive externally and pump `recordAction` from their loop or hook.\n */\n\nexport const STUCK_REASONS = [\n \"consecutive-identical-tool-call\",\n \"no-progress\",\n \"ping-pong\",\n] as const;\n\nexport type StuckReason = typeof STUCK_REASONS[number];\n\nexport interface ActionRecord {\n readonly iterationIndex: number;\n readonly toolName: string;\n readonly argsHash: string;\n}\n\nexport interface ActionHistoryOptions {\n /** Number of consecutive identical records that triggers the consecutive detector. Default 3. */\n readonly consecutiveLimit?: number;\n}\n\nexport interface ActionHistory {\n readonly kind: \"action-history\";\n /**\n * Append a record. Returns the latest StuckReason triggered by this\n * record, or null when no detector fires. The most recent reason wins\n * when multiple apply.\n */\n recordAction(action: ActionRecord): StuckReason | null;\n history(): readonly ActionRecord[];\n}\n\nfunction actionKey(record: ActionRecord): string {\n return `${record.toolName}::${record.argsHash}`;\n}\n\nexport function createActionHistory(options: ActionHistoryOptions = {}): ActionHistory {\n const consecutiveLimit = options.consecutiveLimit ?? 3;\n const records: ActionRecord[] = [];\n\n return {\n kind: \"action-history\" as const,\n recordAction(action: ActionRecord): StuckReason | null {\n records.push(action);\n // Consecutive identical detector.\n if (records.length >= consecutiveLimit) {\n const tail = records.slice(-consecutiveLimit);\n const firstKey = actionKey(tail[0]!);\n if (tail.every((r) => actionKey(r) === firstKey)) {\n return \"consecutive-identical-tool-call\";\n }\n }\n // Ping-pong detector (last 4 alternate between exactly 2 keys).\n if (records.length >= 4) {\n const last4 = records.slice(-4);\n const keys = last4.map(actionKey);\n const distinct = Array.from(new Set(keys));\n if (\n distinct.length === 2 &&\n keys[0] === keys[2] &&\n keys[1] === keys[3] &&\n keys[0] !== keys[1]\n ) {\n return \"ping-pong\";\n }\n }\n return null;\n },\n history(): readonly ActionRecord[] {\n return Object.freeze([...records]);\n },\n };\n}\n","/**\n * PermissionContext — Phase 21 (v1.2).\n *\n * Gates tool execution per-tool / per-iteration / per-resource. Includes\n * a SAFETY-band hook helper that wires the context into the agent loop's\n * BEFORE_TOOL pipeline via the Phase 19 `controls.deny(reason)` veto.\n */\n\nimport { BAND, type HookHandler, type RegisterOptions } from \"../../contract/bands.js\";\n\nexport interface PermissionRule {\n /** Match on tool name. String = exact match; RegExp = test. Both undefined = match-any. */\n readonly toolName?: string | RegExp;\n /**\n * Optional resource matcher. The caller passes `resource` on each\n * decide() invocation; this rule fires only when the rule's resource\n * matches.\n */\n readonly resource?: string | RegExp;\n readonly verdict: \"allow\" | \"deny\";\n readonly reason?: string;\n}\n\nexport interface PermissionDecisionInput {\n readonly toolName: string;\n readonly iterationIndex: number;\n readonly resource?: string;\n readonly args?: unknown;\n}\n\nexport type PermissionVerdict =\n | { readonly allow: true }\n | { readonly allow: false; readonly reason: string };\n\nexport interface PermissionContext {\n readonly kind: \"permission-context\";\n decide(input: PermissionDecisionInput): PermissionVerdict;\n}\n\nfunction matches(matcher: string | RegExp | undefined, value: string | undefined): boolean {\n if (matcher === undefined) return true;\n if (value === undefined) return false;\n if (typeof matcher === \"string\") return matcher === value;\n return matcher.test(value);\n}\n\nexport function createPermissionContext(\n rules: readonly PermissionRule[],\n): PermissionContext {\n return {\n kind: \"permission-context\" as const,\n decide(input: PermissionDecisionInput): PermissionVerdict {\n for (const rule of rules) {\n if (!matches(rule.toolName, input.toolName)) continue;\n if (rule.resource !== undefined && !matches(rule.resource, input.resource)) continue;\n if (rule.verdict === \"allow\") return { allow: true };\n return { allow: false, reason: rule.reason ?? `denied by permission rule for ${input.toolName}` };\n }\n // Default: allow when no rule matches.\n return { allow: true };\n },\n };\n}\n\n/**\n * Hook handler shape suitable for registering on `BEFORE_TOOL` at\n * BAND.SAFETY. Reads `toolName` and `iterationIndex` from the agent\n * runtime's BEFORE_TOOL context shape (`{ iterationIndex, toolName,\n * args }`) and translates a deny verdict into `controls.deny(reason)`.\n */\nexport interface PermissionHookContext {\n readonly iterationIndex: number;\n readonly toolName: string;\n readonly resource?: string;\n readonly args?: unknown;\n}\n\nexport function createPermissionGuardHook(\n context: PermissionContext,\n): HookHandler<PermissionHookContext> {\n return (ctx, controls) => {\n const verdict = context.decide({\n iterationIndex: ctx.iterationIndex,\n toolName: ctx.toolName,\n ...(ctx.resource !== undefined ? { resource: ctx.resource } : {}),\n ...(ctx.args !== undefined ? { args: ctx.args } : {}),\n });\n if (!verdict.allow) {\n controls?.deny(verdict.reason);\n }\n };\n}\n\n/**\n * Convenience: returns RegisterOptions for the SAFETY-band registration.\n * Callers do `pipeline.register(\"BEFORE_TOOL\", hook, permissionGuardRegisterOptions())`.\n */\nexport function permissionGuardRegisterOptions(): RegisterOptions {\n return { band: BAND.SAFETY };\n}\n","/**\n * evalAgentRun — Phase 22 (v1.2).\n *\n * Pure helper that gates a baseline-relative regression on iterations-to-goal\n * and total cost for an agent run. Standalone (no I/O). Callers wire fixture\n * discovery + persistence themselves; this kernel is the comparison engine.\n *\n * The shape mirrors the existing v1.1 `lattice eval` cost-regression contract\n * so a future `lattice eval --agent` CLI subcommand can reuse the same gate.\n */\n\nimport type { Usage } from \"../providers/provider.js\";\n\n/**\n * Summary of an agent run sufficient for regression analysis. Callers\n * typically derive this from an `AgentSuccess` via `iterations.length` and\n * cumulative `usage`. The schema is intentionally minimal so callers can\n * persist + load it across runs without dragging the full ReplayEnvelope.\n */\nexport interface AgentRunSnapshot {\n readonly iterationsToGoal: number;\n readonly usage: Usage;\n}\n\nexport interface EvalOptions {\n /**\n * Maximum tolerated INCREASE in iterations-to-goal versus the baseline.\n * Default 1 (one extra iteration tolerated). Set to 0 to require parity.\n */\n readonly iterationsToGoalRegressionLimit?: number;\n /**\n * Maximum tolerated FRACTIONAL cost increase versus the baseline.\n * Default 0.10 (10% increase tolerated). Compared as\n * `(current - baseline) / baseline`. Cost regressions are only\n * considered when BOTH snapshots have a non-null `costUsd`; mixed-cost\n * snapshots emit a `mixed-cost-unknown` regression so callers can decide\n * how to handle them.\n */\n readonly costUsdRegressionLimit?: number;\n}\n\nexport type EvalRegressionKind =\n | \"iterations-to-goal\"\n | \"cost-regression\"\n | \"mixed-cost-unknown\";\n\nexport interface EvalRegression {\n readonly kind: EvalRegressionKind;\n readonly baseline: number | null;\n readonly current: number | null;\n readonly limit: number;\n readonly message: string;\n}\n\nexport interface AgentEvalResult {\n readonly ok: boolean;\n readonly regressions: ReadonlyArray<EvalRegression>;\n}\n\nexport function evalAgentRun(\n baseline: AgentRunSnapshot,\n current: AgentRunSnapshot,\n options: EvalOptions = {},\n): AgentEvalResult {\n const iterLimit = options.iterationsToGoalRegressionLimit ?? 1;\n const costLimit = options.costUsdRegressionLimit ?? 0.1;\n const regressions: EvalRegression[] = [];\n\n // Iterations-to-goal regression.\n const iterDelta = current.iterationsToGoal - baseline.iterationsToGoal;\n if (iterDelta > iterLimit) {\n regressions.push({\n kind: \"iterations-to-goal\",\n baseline: baseline.iterationsToGoal,\n current: current.iterationsToGoal,\n limit: iterLimit,\n message: `Iterations-to-goal ${current.iterationsToGoal} exceeds baseline ${baseline.iterationsToGoal} by ${iterDelta} (limit: ${iterLimit}).`,\n });\n }\n\n // Cost regression.\n const bCost = baseline.usage.costUsd;\n const cCost = current.usage.costUsd;\n if (bCost === null && cCost === null) {\n // Both unmeasured — no signal, no regression.\n } else if (bCost === null || cCost === null) {\n regressions.push({\n kind: \"mixed-cost-unknown\",\n baseline: bCost,\n current: cCost,\n limit: costLimit,\n message: `Cost mixed: baseline=${bCost} current=${cCost}; cannot compare regression.`,\n });\n } else if (bCost > 0) {\n const ratio = (cCost - bCost) / bCost;\n if (ratio > costLimit) {\n regressions.push({\n kind: \"cost-regression\",\n baseline: bCost,\n current: cCost,\n limit: costLimit,\n message: `Cost regression: $${cCost.toFixed(6)} vs baseline $${bCost.toFixed(6)} (+${(ratio * 100).toFixed(1)}%; limit ${(costLimit * 100).toFixed(1)}%).`,\n });\n }\n } else if (bCost === 0 && cCost > 0) {\n // Baseline is free; any positive cost is a regression by definition.\n regressions.push({\n kind: \"cost-regression\",\n baseline: bCost,\n current: cCost,\n limit: costLimit,\n message: `Cost regression: baseline was $0; current $${cCost.toFixed(6)}.`,\n });\n }\n\n return {\n ok: regressions.length === 0,\n regressions: Object.freeze(regressions),\n };\n}\n","import type { ArtifactInput, ArtifactRef } from \"../artifacts/artifact.js\";\nimport { toArtifactRef } from \"../artifacts/artifact.js\";\nimport type {\n ContextPackItemPlan,\n ContextPackPlan,\n SelectedRoute,\n} from \"../plan/plan.js\";\nimport type { SessionRecord } from \"../sessions/session.js\";\n\nexport type TrustLabel = \"developer\" | \"user\" | \"tool\" | \"model-summary\";\n\nexport interface ContextPack extends ContextPackPlan {\n readonly kind: \"context-pack\";\n}\n\nexport interface BuildContextPackInput {\n readonly task: string;\n readonly artifacts: readonly ArtifactInput[];\n readonly route?: SelectedRoute;\n readonly session?: SessionRecord;\n readonly tokenBudget?: number;\n}\n\nexport interface ContextSummarizer {\n summarize(input: {\n readonly artifacts: readonly ArtifactRef[];\n readonly budgetTokens: number;\n }): Promise<readonly ArtifactRef[]> | readonly ArtifactRef[];\n}\n\nexport function buildContextPack(input: BuildContextPackInput): ContextPack {\n const routeBudget =\n input.route?.estimates.inputTokens ?? input.route?.inputModalities.length ?? 0;\n const tokenBudget =\n input.tokenBudget ?? Math.max(512, Math.min(input.route?.estimates.inputTokens ?? 4_000, 16_000));\n const remainingBudget = Math.max(512, tokenBudget - estimateTokens(input.task) - routeBudget);\n const included: ContextPackItemPlan[] = [];\n const summarized: ContextPackItemPlan[] = [];\n const archived: ContextPackItemPlan[] = [];\n const omitted: ContextPackItemPlan[] = [];\n const warnings: string[] = [];\n let usedTokens = 0;\n\n for (const artifact of input.artifacts) {\n const artifactTokens = estimateArtifactTokens(artifact);\n const item: ContextPackItemPlan = {\n artifactId: artifact.id,\n reason: \"Run artifact included for provider consideration.\",\n estimatedTokens: artifactTokens,\n trust: trustForArtifact(artifact),\n };\n\n if (usedTokens + artifactTokens <= remainingBudget) {\n included.push(item);\n usedTokens += artifactTokens;\n continue;\n }\n\n if (artifact.kind === \"text\" || artifact.kind === \"document\" || artifact.kind === \"json\") {\n summarized.push({\n ...item,\n reason: \"Artifact exceeded live context budget and needs summary packaging.\",\n });\n usedTokens += Math.min(artifactTokens, 256);\n continue;\n }\n\n omitted.push({\n ...item,\n reason: \"Artifact exceeded context budget and cannot be summarized by the default packer.\",\n });\n warnings.push(`Artifact ${artifact.id} omitted from live context budget.`);\n }\n\n for (const turn of input.session?.turns ?? []) {\n const turnTokens = estimateTokens(turn.task);\n const item: ContextPackItemPlan = {\n sessionTurnId: turn.id,\n reason: \"Prior session turn retained for continuity.\",\n estimatedTokens: turnTokens,\n trust: \"user\",\n };\n\n if (usedTokens + turnTokens <= remainingBudget) {\n included.push(item);\n usedTokens += turnTokens;\n } else {\n archived.push({\n ...item,\n reason: \"Prior session turn archived because the run budget was exhausted.\",\n });\n }\n }\n\n return {\n id: createContextPackId(),\n kind: \"context-pack\",\n tokenBudget,\n estimatedTokens: usedTokens,\n included,\n summarized,\n archived,\n omitted,\n warnings,\n };\n}\n\nexport function estimateArtifactTokens(artifact: ArtifactInput | ArtifactRef): number {\n if (artifact.size?.characters !== undefined) {\n return estimateTokensFromCharacters(artifact.size.characters);\n }\n\n if (artifact.size?.bytes !== undefined) {\n return estimateTokensFromCharacters(Math.ceil(artifact.size.bytes / 2));\n }\n\n if (\"value\" in artifact && typeof artifact.value === \"string\") {\n return estimateTokens(artifact.value);\n }\n\n if (\"value\" in artifact && artifact.value !== undefined) {\n const serialized = JSON.stringify(artifact.value);\n\n return serialized === undefined ? 64 : estimateTokens(serialized);\n }\n\n return 64;\n}\n\nexport function estimateTokens(value: string): number {\n return Math.max(1, estimateTokensFromCharacters(value.length));\n}\n\nexport function toContextArtifactRefs(\n artifacts: readonly ArtifactInput[],\n): readonly ArtifactRef[] {\n return artifacts.map(toArtifactRef);\n}\n\nfunction estimateTokensFromCharacters(characters: number): number {\n return Math.ceil(characters / 4);\n}\n\nfunction trustForArtifact(artifact: ArtifactRef): TrustLabel {\n if (artifact.source === \"tool\") {\n return \"tool\";\n }\n\n if (artifact.source === \"generated\") {\n return \"model-summary\";\n }\n\n return \"user\";\n}\n\nfunction createContextPackId(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return `context-pack:${crypto.randomUUID()}`;\n }\n\n return `context-pack:${Date.now()}:${Math.random().toString(16).slice(2)}`;\n}\n","export interface PolicySpec {\n readonly maxCostUsd?: number;\n readonly latency?: \"interactive\" | \"batch\";\n readonly privacy?: \"standard\" | \"sensitive\" | \"restricted\";\n readonly providerAllowList?: readonly string[];\n readonly providerDenyList?: readonly string[];\n readonly noUpload?: boolean;\n readonly noPublicUrl?: boolean;\n readonly noLogging?: boolean;\n readonly metadata?: Record<string, unknown>;\n}\n\nexport function mergePolicy(\n defaultPolicy?: PolicySpec,\n runPolicy?: PolicySpec,\n): PolicySpec | undefined {\n if (defaultPolicy === undefined && runPolicy === undefined) {\n return undefined;\n }\n\n return {\n ...defaultPolicy,\n ...runPolicy,\n };\n}\n","import type { ArtifactInput, ArtifactRef } from \"../artifacts/artifact.js\";\nimport { artifact, toArtifactRef } from \"../artifacts/artifact.js\";\nimport type { PolicySpec } from \"../policy/policy.js\";\nimport type {\n ProviderPackagedArtifactPlan,\n ProviderPackagingPlan,\n SelectedRoute,\n} from \"../plan/plan.js\";\nimport type { ProviderTransportMode } from \"./provider.js\";\n\nexport interface ProviderPackagingResult {\n readonly plan: ProviderPackagingPlan;\n readonly packagedArtifacts: readonly ArtifactRef[];\n readonly blocked: readonly string[];\n}\n\nexport function packageArtifactsForProvider(input: {\n readonly artifacts: readonly ArtifactInput[];\n readonly route?: SelectedRoute;\n readonly policy?: PolicySpec;\n}): ProviderPackagingResult {\n const route = input.route;\n\n if (route === undefined) {\n return {\n plan: {\n providerId: \"none\",\n modelId: \"none\",\n artifacts: [],\n warnings: [\"No selected route; provider packaging skipped.\"],\n },\n packagedArtifacts: [],\n blocked: [],\n };\n }\n\n const packaged: ProviderPackagedArtifactPlan[] = [];\n const packagedArtifacts: ArtifactRef[] = [];\n const warnings: string[] = [];\n const blocked: string[] = [];\n\n for (const inputArtifact of input.artifacts) {\n const choice = chooseTransport(inputArtifact, route.fileTransport, input.policy);\n\n if (choice.blocked !== undefined) {\n blocked.push(choice.blocked);\n warnings.push(choice.blocked);\n continue;\n }\n\n packaged.push({\n artifactId: inputArtifact.id,\n transport: choice.transport,\n ...(inputArtifact.mediaType !== undefined ? { mediaType: inputArtifact.mediaType } : {}),\n lineageTransform: \"provider-packaging\",\n warnings: choice.warnings,\n });\n\n packagedArtifacts.push(\n toArtifactRef(\n artifact.derive({\n id: `${inputArtifact.id}:packaged:${route.providerId}:${route.modelId}`,\n kind: inputArtifact.kind,\n source: choice.transport === \"provider-upload\" ? \"provider-upload\" : \"generated\",\n parents: [inputArtifact],\n transform: {\n kind: \"provider-packaging\",\n name: `${route.providerId}:${choice.transport}`,\n metadata: {\n providerId: route.providerId,\n modelId: route.modelId,\n transport: choice.transport,\n },\n },\n metadata: {\n providerId: route.providerId,\n modelId: route.modelId,\n transport: choice.transport,\n },\n ...(inputArtifact.mediaType !== undefined ? { mediaType: inputArtifact.mediaType } : {}),\n privacy: inputArtifact.privacy,\n }),\n ),\n );\n }\n\n return {\n plan: {\n providerId: route.providerId,\n modelId: route.modelId,\n artifacts: packaged,\n warnings,\n },\n packagedArtifacts,\n blocked,\n };\n}\n\nfunction chooseTransport(\n inputArtifact: ArtifactInput,\n supported: readonly ProviderTransportMode[],\n policy?: PolicySpec,\n): {\n readonly transport: ProviderTransportMode;\n readonly warnings: readonly string[];\n readonly blocked?: string;\n} {\n const warnings: string[] = [];\n const preferred = preferredTransports(inputArtifact);\n\n for (const transport of preferred) {\n if (!supported.includes(transport)) {\n continue;\n }\n\n if (policy?.noUpload === true && transport === \"provider-upload\") {\n continue;\n }\n\n if (policy?.noPublicUrl === true && transport === \"url\") {\n continue;\n }\n\n if (\n inputArtifact.privacy === \"restricted\" &&\n (transport === \"provider-upload\" || transport === \"url\" || transport === \"base64\")\n ) {\n continue;\n }\n\n if (transport === \"base64\") {\n warnings.push(`Artifact ${inputArtifact.id} will be encoded as base64.`);\n }\n\n return { transport, warnings };\n }\n\n return {\n transport: \"inline\",\n warnings,\n blocked: `No policy-safe transport for artifact ${inputArtifact.id}.`,\n };\n}\n\nfunction preferredTransports(inputArtifact: ArtifactInput): readonly ProviderTransportMode[] {\n switch (inputArtifact.kind) {\n case \"text\":\n return [\"inline\", \"extracted-text\"];\n case \"json\":\n case \"tool-result\":\n return [\"json\", \"inline\"];\n case \"url\":\n return [\"url\", \"inline\"];\n case \"document\":\n return [\"extracted-text\", \"provider-upload\", \"base64\", \"url\"];\n case \"audio\":\n return [\"transcript\", \"provider-upload\", \"base64\", \"url\"];\n case \"image\":\n case \"file\":\n case \"video\":\n return [\"provider-upload\", \"base64\", \"url\"];\n }\n}\n","import type { ArtifactInput } from \"../artifacts/artifact.js\";\nimport type { CapabilityContract } from \"../contract/contract.js\";\nimport { evaluateContractAgainstRoute } from \"../contract/preflight.js\";\nimport type { OutputContract, OutputContractMap } from \"../outputs/contracts.js\";\nimport type { PolicySpec } from \"../policy/policy.js\";\nimport type {\n CapabilityModality,\n ModelCapability,\n} from \"../providers/provider.js\";\nimport type {\n RouteCandidate,\n RouteDecision,\n RouteEstimates,\n RouteRejectReason,\n} from \"../plan/plan.js\";\nimport { estimateArtifactTokens, estimateTokens } from \"../context/context-pack.js\";\nimport type { CapabilityCatalog } from \"./catalog.js\";\n\nexport interface RouteRequest {\n readonly task: string;\n readonly artifacts: readonly ArtifactInput[];\n readonly outputs: OutputContractMap;\n readonly policy?: PolicySpec;\n readonly provider?: string;\n readonly model?: string;\n readonly contract?: CapabilityContract;\n}\n\nexport function routeDeterministically(\n catalog: CapabilityCatalog,\n request: RouteRequest,\n): RouteDecision {\n const requiredInputs = requiredInputModalities(request.artifacts);\n const requiredOutputs = requiredOutputModalities(request.outputs);\n const requiresStructuredOutput = outputRequiresStructuredOutput(request.outputs);\n const estimatedInputTokens =\n estimateTokens(request.task) +\n request.artifacts.reduce((total, artifact) => total + estimateArtifactTokens(artifact), 0);\n const candidates = catalog.models\n .map((capability, index) =>\n evaluateCapability(capability, {\n requiredInputs,\n requiredOutputs,\n requiresStructuredOutput,\n estimatedInputTokens,\n ...(request.policy !== undefined ? { policy: request.policy } : {}),\n ...(request.provider !== undefined ? { provider: request.provider } : {}),\n ...(request.model !== undefined ? { model: request.model } : {}),\n ...(request.contract !== undefined ? { contract: request.contract } : {}),\n index,\n }),\n )\n .sort(compareCandidates);\n const accepted = candidates.filter((candidate) => candidate.accepted);\n const selected = accepted[0];\n\n return {\n catalogVersion: catalog.version,\n ...(selected !== undefined\n ? {\n selected: {\n providerId: selected.providerId,\n modelId: selected.modelId,\n score: selected.score,\n estimates: selected.estimates,\n inputModalities: selected.capability.inputModalities,\n outputModalities: selected.capability.outputModalities,\n fileTransport: selected.capability.fileTransport,\n },\n }\n : {}),\n candidates,\n rejected: candidates.filter((candidate) => !candidate.accepted),\n fallbackChain: accepted.slice(1).map((candidate) => ({\n providerId: candidate.providerId,\n modelId: candidate.modelId,\n score: candidate.score,\n reason: \"policy-preserving-fallback\",\n })),\n noRouteReasons:\n selected === undefined\n ? summarizeNoRouteReasons(candidates)\n : [],\n };\n}\n\nfunction evaluateCapability(\n capability: ModelCapability,\n input: {\n readonly requiredInputs: readonly CapabilityModality[];\n readonly requiredOutputs: readonly CapabilityModality[];\n readonly requiresStructuredOutput: boolean;\n readonly estimatedInputTokens: number;\n readonly policy?: PolicySpec;\n readonly provider?: string;\n readonly model?: string;\n readonly contract?: CapabilityContract;\n readonly index: number;\n },\n): RouteCandidate {\n const reasons: RouteRejectReason[] = [];\n\n if (capability.available === false) {\n reasons.push({\n code: \"provider-unavailable\",\n message: `${capability.providerId}/${capability.modelId} is not available.`,\n });\n }\n\n if (input.provider !== undefined && capability.providerId !== input.provider) {\n reasons.push({\n code: \"provider-forced-mismatch\",\n message: `Provider override requires ${input.provider}.`,\n });\n }\n\n if (input.model !== undefined && capability.modelId !== input.model) {\n reasons.push({\n code: \"model-forced-mismatch\",\n message: `Model override requires ${input.model}.`,\n });\n }\n\n for (const modality of input.requiredInputs) {\n if (!capability.inputModalities.includes(modality)) {\n reasons.push({\n code: \"input-modality-unsupported\",\n message: `${capability.modelId} does not support ${modality} input.`,\n });\n }\n }\n\n for (const modality of input.requiredOutputs) {\n if (!capability.outputModalities.includes(modality)) {\n reasons.push({\n code: \"output-modality-unsupported\",\n message: `${capability.modelId} does not support ${modality} output.`,\n });\n }\n }\n\n if (input.requiresStructuredOutput && !capability.structuredOutput) {\n reasons.push({\n code: \"structured-output-unsupported\",\n message: `${capability.modelId} does not support structured output contracts.`,\n });\n }\n\n if (input.estimatedInputTokens > capability.contextWindow) {\n reasons.push({\n code: \"context-window-exceeded\",\n message: `Estimated input ${input.estimatedInputTokens} tokens exceeds ${capability.contextWindow}.`,\n });\n }\n\n const estimates = estimateRoute(capability, input.estimatedInputTokens);\n addPolicyRejectReasons(reasons, capability, estimates, input.policy);\n\n // Phase 7 contract preflight — reuse the router's own output-token estimate\n // so preflight and the router agree on the projected output size (one source\n // of truth, consumed by Phase 9 receipts).\n const contractResult = evaluateContractAgainstRoute(input.contract, {\n capability,\n estimatedInputTokens: input.estimatedInputTokens,\n estimatedOutputTokens: estimates.outputTokens,\n });\n for (const reason of contractResult.reasons) {\n reasons.push(reason);\n }\n\n const score = scoreCapability(capability, estimates, input.index);\n\n return {\n providerId: capability.providerId,\n modelId: capability.modelId,\n capability,\n score,\n accepted: reasons.length === 0,\n reasons,\n estimates,\n };\n}\n\nfunction addPolicyRejectReasons(\n reasons: RouteRejectReason[],\n capability: ModelCapability,\n estimates: RouteEstimates,\n policy?: PolicySpec,\n): void {\n if (policy === undefined) {\n return;\n }\n\n if (\n policy.providerAllowList !== undefined &&\n !policy.providerAllowList.includes(capability.providerId)\n ) {\n reasons.push({\n code: \"provider-not-allowed\",\n message: `${capability.providerId} is not in the provider allow list.`,\n });\n }\n\n if (policy.providerDenyList?.includes(capability.providerId) === true) {\n reasons.push({\n code: \"provider-denied\",\n message: `${capability.providerId} is in the provider deny list.`,\n });\n }\n\n if (\n policy.privacy !== undefined &&\n !capability.dataPolicy.privacy.includes(policy.privacy)\n ) {\n reasons.push({\n code: \"privacy-unsupported\",\n message: `${capability.modelId} does not satisfy ${policy.privacy} privacy.`,\n });\n }\n\n if (policy.noLogging === true && capability.dataPolicy.supportsNoLogging !== true) {\n reasons.push({\n code: \"no-logging-unsupported\",\n message: `${capability.modelId} cannot satisfy noLogging.`,\n });\n }\n\n if (\n policy.noUpload === true &&\n capability.fileTransport.length > 0 &&\n capability.fileTransport.every((transport) => transport === \"provider-upload\")\n ) {\n reasons.push({\n code: \"no-upload-violated\",\n message: `${capability.modelId} requires an upload transport disallowed by policy.`,\n });\n }\n\n if (policy.latency !== undefined && capability.latency !== policy.latency) {\n reasons.push({\n code: \"latency-class-mismatch\",\n message: `${capability.modelId} latency class is ${capability.latency}, not ${policy.latency}.`,\n });\n }\n\n if (\n policy.maxCostUsd !== undefined &&\n estimates.costUsd !== undefined &&\n estimates.costUsd > policy.maxCostUsd\n ) {\n reasons.push({\n code: \"budget-exceeded\",\n message: `${capability.modelId} estimated cost ${estimates.costUsd} exceeds maxCostUsd ${policy.maxCostUsd}.`,\n });\n }\n}\n\nfunction estimateRoute(\n capability: ModelCapability,\n inputTokens: number,\n): RouteEstimates {\n const outputTokens = 512;\n const inputCost =\n capability.pricing?.inputCostPer1M === undefined\n ? undefined\n : (inputTokens / 1_000_000) * capability.pricing.inputCostPer1M;\n const outputCost =\n capability.pricing?.outputCostPer1M === undefined\n ? undefined\n : (outputTokens / 1_000_000) * capability.pricing.outputCostPer1M;\n\n return {\n inputTokens,\n outputTokens,\n ...(inputCost !== undefined || outputCost !== undefined\n ? { costUsd: (inputCost ?? 0) + (outputCost ?? 0) }\n : {}),\n latencyMs: capability.latency === \"interactive\" ? 1_000 : 10_000,\n };\n}\n\nfunction scoreCapability(\n capability: ModelCapability,\n estimates: RouteEstimates,\n index: number,\n): number {\n const costScore = Math.round((estimates.costUsd ?? 0) * 1_000_000);\n const latencyScore = capability.latency === \"interactive\" ? 0 : 100_000;\n const contextHeadroom = Math.max(0, capability.contextWindow - estimates.inputTokens);\n const contextScore = Math.max(0, 10_000 - Math.min(contextHeadroom, 10_000));\n\n return costScore + latencyScore + contextScore + index;\n}\n\nfunction compareCandidates(left: RouteCandidate, right: RouteCandidate): number {\n if (left.accepted !== right.accepted) {\n return left.accepted ? -1 : 1;\n }\n\n if (left.score !== right.score) {\n return left.score - right.score;\n }\n\n const provider = left.providerId.localeCompare(right.providerId);\n\n return provider === 0 ? left.modelId.localeCompare(right.modelId) : provider;\n}\n\nfunction requiredInputModalities(\n artifacts: readonly ArtifactInput[],\n): readonly CapabilityModality[] {\n const modalities = new Set<CapabilityModality>([\"text\"]);\n\n for (const artifact of artifacts) {\n switch (artifact.kind) {\n case \"text\":\n modalities.add(\"text\");\n break;\n case \"json\":\n modalities.add(\"json\");\n break;\n case \"image\":\n modalities.add(\"image\");\n break;\n case \"audio\":\n modalities.add(\"audio\");\n break;\n case \"video\":\n modalities.add(\"video\");\n break;\n case \"document\":\n modalities.add(\"document\");\n break;\n case \"url\":\n modalities.add(\"url\");\n break;\n case \"tool-result\":\n modalities.add(\"tool\");\n break;\n case \"file\":\n modalities.add(\"file\");\n break;\n }\n }\n\n return [...modalities];\n}\n\nfunction requiredOutputModalities(\n outputs: OutputContractMap,\n): readonly CapabilityModality[] {\n const modalities = new Set<CapabilityModality>();\n\n for (const contract of Object.values(outputs)) {\n if (contract === \"text\") {\n modalities.add(\"text\");\n continue;\n }\n\n if (isStructuredContract(contract)) {\n modalities.add(\"json\");\n continue;\n }\n\n if (isReferenceContract(contract)) {\n modalities.add(\"json\");\n }\n }\n\n return [...modalities];\n}\n\nfunction outputRequiresStructuredOutput(outputs: OutputContractMap): boolean {\n return Object.values(outputs).some(isStructuredContract);\n}\n\nfunction isStructuredContract(contract: OutputContract): boolean {\n return (\n typeof contract === \"object\" &&\n contract !== null &&\n \"~standard\" in contract\n );\n}\n\nfunction isReferenceContract(contract: OutputContract): boolean {\n return (\n typeof contract === \"object\" &&\n contract !== null &&\n \"kind\" in contract &&\n (contract.kind === \"citations\" || contract.kind === \"artifacts\")\n );\n}\n\nfunction summarizeNoRouteReasons(\n candidates: readonly RouteCandidate[],\n): readonly RouteRejectReason[] {\n if (candidates.length === 0) {\n return [\n {\n code: \"catalog-empty\",\n message: \"No provider capabilities are configured.\",\n },\n ];\n }\n\n const unique = new Map<string, RouteRejectReason>();\n\n for (const candidate of candidates) {\n for (const reason of candidate.reasons) {\n unique.set(reason.code, reason);\n }\n }\n\n return [...unique.values()];\n}\n","import type { ArtifactFingerprint } from \"../artifacts/artifact.js\";\n\nconst textEncoder = new TextEncoder();\n\nexport async function fingerprintArtifactValue(\n value: unknown,\n): Promise<ArtifactFingerprint | undefined> {\n const bytes = await valueToBytes(value);\n\n if (bytes === undefined) {\n return undefined;\n }\n\n const digest = await crypto.subtle.digest(\"SHA-256\", toArrayBuffer(bytes));\n\n return {\n algorithm: \"sha256\",\n value: toHex(new Uint8Array(digest)),\n };\n}\n\nasync function valueToBytes(value: unknown): Promise<Uint8Array | undefined> {\n if (typeof value === \"string\") {\n return textEncoder.encode(value);\n }\n\n if (value instanceof Uint8Array) {\n return value;\n }\n\n if (value instanceof ArrayBuffer) {\n return new Uint8Array(value);\n }\n\n if (isBlobLike(value)) {\n return new Uint8Array(await value.arrayBuffer());\n }\n\n const serialized = JSON.stringify(value);\n\n return serialized === undefined ? undefined : textEncoder.encode(serialized);\n}\n\nfunction isBlobLike(value: unknown): value is Blob {\n return typeof Blob !== \"undefined\" && value instanceof Blob;\n}\n\nfunction toHex(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction toArrayBuffer(bytes: Uint8Array): ArrayBuffer {\n const copy = new Uint8Array(bytes.byteLength);\n copy.set(bytes);\n\n return copy.buffer as ArrayBuffer;\n}\n","export interface TracerLike {\n readonly kind: \"tracer\";\n readonly span?: <T>(\n name: string,\n fn: () => T | Promise<T>,\n attributes?: Record<string, unknown>,\n ) => T | Promise<T>;\n readonly event?: (name: string, attributes?: Record<string, unknown>) => void;\n}\n\nexport type RunEventKind =\n | \"run.start\"\n | \"artifact.ingested\"\n | \"context.packed\"\n | \"router.candidates\"\n | \"stage.start\"\n | \"stage.complete\"\n | \"provider.attempt\"\n | \"fallback.activated\"\n | \"validation.complete\"\n | \"validation.failed\"\n | \"artifact.created\"\n | \"run.complete\"\n | \"run.failed\"\n | \"tool.call\"\n | \"replay.offline\"\n | \"replay.live\"\n | \"step.transition\"\n // Phase 20 (v1.2): recovery / eviction-resume markers paired with the\n // AgentHost storage seam + SurvivabilityAdapter. Closes TRACE-EXT-01.\n | \"recovery.start\"\n | \"recovery.complete\"\n | \"recovery.failed\";\n\nexport interface RunEvent {\n readonly kind: RunEventKind;\n readonly timestamp: string;\n readonly runId: string;\n readonly planId?: string;\n readonly stageId?: string;\n readonly providerId?: string;\n readonly modelId?: string;\n readonly artifactId?: string;\n readonly metadata?: Record<string, unknown>;\n}\n\nexport type RunEventSink = (event: RunEvent) => void | Promise<void>;\n\nexport function createRunEvent(\n kind: RunEventKind,\n input: Omit<RunEvent, \"kind\" | \"timestamp\">,\n): RunEvent {\n return {\n kind,\n timestamp: new Date().toISOString(),\n ...input,\n };\n}\n","import type { PolicySpec } from \"../policy/policy.js\";\nimport type {\n ProviderAdapter,\n ProviderRef,\n ProviderRegistryInput,\n} from \"../providers/provider.js\";\nimport type { ReceiptSigner } from \"../receipts/types.js\";\nimport type { SessionStore } from \"../sessions/session.js\";\nimport type { StorageLike } from \"../storage/storage.js\";\nimport type { RunEventSink, TracerLike } from \"../tracing/tracing.js\";\n\nexport interface LatticeConfig {\n readonly providers?: ProviderRegistryInput;\n readonly storage?: StorageLike | false;\n readonly sessions?: SessionStore | false;\n readonly defaults?: { readonly policy?: PolicySpec };\n readonly tracing?: TracerLike | false;\n readonly events?: RunEventSink | readonly RunEventSink[];\n /**\n * Phase 9 — when configured, every terminal branch of `ai.run` emits a\n * signed `CapabilityReceipt` attached to `RunResult.receipt`. When absent,\n * no receipts are issued and `RunResult.receipt` is undefined.\n */\n readonly signer?: ReceiptSigner;\n}\n\nexport type NormalizedProviderEntry = ProviderRef | ProviderAdapter;\n\nexport interface NormalizedLatticeConfig {\n readonly providers: readonly NormalizedProviderEntry[];\n readonly storage?: StorageLike;\n readonly sessions?: SessionStore;\n readonly defaults: { readonly policy?: PolicySpec };\n readonly tracing?: TracerLike;\n readonly events: readonly RunEventSink[];\n readonly signer?: ReceiptSigner;\n}\n\nexport function normalizeConfig(config: LatticeConfig = {}): NormalizedLatticeConfig {\n const normalized: {\n providers: readonly NormalizedProviderEntry[];\n defaults: { readonly policy?: PolicySpec };\n storage?: StorageLike;\n sessions?: SessionStore;\n tracing?: TracerLike;\n events: readonly RunEventSink[];\n signer?: ReceiptSigner;\n } = {\n providers: normalizeProviders(config.providers),\n defaults: config.defaults ?? {},\n events: normalizeEventSinks(config.events),\n };\n\n if (config.storage !== undefined && config.storage !== false) {\n normalized.storage = config.storage;\n }\n\n if (config.sessions !== undefined && config.sessions !== false) {\n normalized.sessions = config.sessions;\n }\n\n if (config.tracing !== undefined && config.tracing !== false) {\n normalized.tracing = config.tracing;\n }\n\n if (config.signer !== undefined) {\n normalized.signer = config.signer;\n }\n\n return normalized;\n}\n\nfunction normalizeEventSinks(\n events: RunEventSink | readonly RunEventSink[] | undefined,\n): readonly RunEventSink[] {\n if (events === undefined) {\n return [];\n }\n\n return typeof events === \"function\" ? [events] : events;\n}\n\nfunction normalizeProviders(\n providers: ProviderRegistryInput = [],\n): readonly NormalizedProviderEntry[] {\n return providers.map((provider) => {\n if (typeof provider === \"string\") {\n return {\n id: provider,\n kind: \"provider-ref\",\n };\n }\n\n return provider;\n });\n}\n","import canonicalize from \"canonicalize\";\n\nimport type { ArtifactInput, ArtifactRef } from \"../artifacts/artifact.js\";\nimport { toArtifactRef } from \"../artifacts/artifact.js\";\nimport type { CapabilityContract } from \"../contract/contract.js\";\nimport { evaluateTripwires, type TripwireEvidence } from \"../contract/tripwire.js\";\nimport {\n buildContextPack,\n type ContextPack,\n type ContextSummarizer,\n} from \"../context/context-pack.js\";\nimport type { OutputContractMap } from \"../outputs/contracts.js\";\nimport { validateOutputMap } from \"../outputs/validate.js\";\nimport {\n createExecutionPlan,\n markStage,\n withPlanStatus,\n type ExecutionPlan,\n type ProviderAttemptRecord,\n type RouteRejectReason,\n type SelectedRoute,\n type UsageRecord,\n} from \"../plan/plan.js\";\nimport { mergePolicy, type PolicySpec } from \"../policy/policy.js\";\nimport { packageArtifactsForProvider } from \"../providers/packaging.js\";\nimport type {\n ProviderAdapter,\n ProviderRunRequest,\n ProviderRunResponse,\n Usage,\n} from \"../providers/provider.js\";\nimport { createReceipt } from \"../receipts/receipt.js\";\nimport type {\n ContractVerdict,\n ReceiptEnvelope,\n ReceiptModel,\n ReceiptRoute,\n} from \"../receipts/types.js\";\nimport { createCapabilityCatalog } from \"../routing/catalog.js\";\nimport { routeDeterministically } from \"../routing/router.js\";\nimport type { RunResult } from \"../results/result.js\";\nimport type { SessionRecord, SessionRef } from \"../sessions/session.js\";\nimport { fingerprintArtifactValue } from \"../storage/fingerprint.js\";\nimport { runTool, type ToolCallResult, type ToolDefinition } from \"../tools/tools.js\";\nimport { createRunEvent, type RunEvent } from \"../tracing/tracing.js\";\nimport {\n normalizeConfig,\n type LatticeConfig,\n type NormalizedLatticeConfig,\n} from \"./config.js\";\n\nexport interface RuntimeOverrides {\n readonly provider?: string;\n readonly model?: string;\n readonly routingPolicy?: PolicySpec;\n readonly tokenBudget?: number;\n readonly summarizer?: ContextSummarizer;\n readonly transforms?: readonly RuntimeArtifactTransform[];\n readonly hooks?: RuntimeHooks;\n}\n\nexport interface RuntimeArtifactTransform {\n readonly name: string;\n transform(input: {\n readonly task: string;\n readonly artifacts: readonly ArtifactInput[];\n }): Promise<ArtifactInput | readonly ArtifactInput[]> | ArtifactInput | readonly ArtifactInput[];\n}\n\nexport interface RuntimeHooks {\n readonly beforeProviderCall?: (input: {\n readonly plan: ExecutionPlan;\n readonly request: ProviderRunRequest;\n }) => void | Promise<void>;\n readonly afterProviderCall?: (input: {\n readonly plan: ExecutionPlan;\n readonly response: unknown;\n }) => void | Promise<void>;\n}\n\nexport interface RunIntent<TOutputs extends OutputContractMap> {\n readonly task: string;\n readonly artifacts?: readonly ArtifactInput[];\n readonly outputs: TOutputs;\n readonly policy?: PolicySpec;\n readonly session?: SessionRef;\n readonly signal?: AbortSignal;\n readonly overrides?: RuntimeOverrides;\n readonly tools?: readonly ToolDefinition<any>[];\n readonly toolInputs?: Record<string, unknown>;\n readonly contract?: CapabilityContract;\n}\n\nconst ZERO_USAGE: Usage = { promptTokens: 0, completionTokens: 0, costUsd: 0 };\nconst UNMEASURED_USAGE: Usage = { promptTokens: 0, completionTokens: 0, costUsd: null };\n\nexport interface AI {\n session(id: string): SessionRef;\n plan<const TOutputs extends OutputContractMap>(\n intent: RunIntent<TOutputs>,\n ): Promise<ExecutionPlan>;\n run<const TOutputs extends OutputContractMap>(\n intent: RunIntent<TOutputs>,\n ): Promise<RunResult<TOutputs>>;\n /**\n * Phase 19 (v1.2): single-agent execution loop. Drives multiple provider\n * iterations under one call, dispatching tool requests between iterations.\n * Composes with the v1.2 hook pipeline (SAFETY-band veto, OBSERVABILITY-band\n * checkpoint receipts) and the v1.1 capability receipts (when\n * `intent.signer` is provided + `intent.autoRegisterCheckpoint !== false`).\n *\n * See `packages/lattice/src/agent/runtime.ts` for orchestration details.\n */\n runAgent<const TOutputs extends OutputContractMap>(\n intent: import(\"../agent/types.js\").AgentIntent<TOutputs>,\n ): Promise<import(\"../agent/types.js\").AgentResult<TOutputs>>;\n}\n\ninterface BuiltPlan {\n readonly plan: ExecutionPlan;\n readonly artifacts: readonly ArtifactInput[];\n readonly contextPack: ContextPack;\n readonly packagedArtifacts: readonly ArtifactRef[];\n readonly blockedPackaging: readonly string[];\n readonly toolResults: readonly ToolCallResult[];\n readonly mergedPolicy?: PolicySpec;\n readonly sessionRecord?: SessionRecord;\n}\n\nexport function createAI(config: LatticeConfig = {}): AI {\n const normalized = normalizeConfig(config);\n\n return {\n session(id: string): SessionRef {\n return {\n id,\n kind: \"session-ref\",\n };\n },\n async plan<const TOutputs extends OutputContractMap>(\n intent: RunIntent<TOutputs>,\n ): Promise<ExecutionPlan> {\n return (await buildPlan(normalized, intent)).plan;\n },\n run<const TOutputs extends OutputContractMap>(\n intent: RunIntent<TOutputs>,\n ): Promise<RunResult<TOutputs>> {\n return runWithConfig(normalized, intent);\n },\n runAgent<const TOutputs extends OutputContractMap>(\n intent: import(\"../agent/types.js\").AgentIntent<TOutputs>,\n ): Promise<import(\"../agent/types.js\").AgentResult<TOutputs>> {\n // Lazy import avoids a hard cycle (agent/runtime.ts imports from\n // ../runtime/config.js for its `LatticeConfig` parameter type only).\n return import(\"../agent/runtime.js\").then((mod) => mod.runAgent(intent, config));\n },\n };\n}\n\nasync function runWithConfig<const TOutputs extends OutputContractMap>(\n normalized: NormalizedLatticeConfig,\n intent: RunIntent<TOutputs>,\n): Promise<RunResult<TOutputs>> {\n if (intent.signal?.aborted === true) {\n throw new DOMException(\"Run aborted before execution.\", \"AbortError\");\n }\n\n const runId = createRunId();\n const events: RunEvent[] = [];\n await emitEvent(normalized, events, createRunEvent(\"run.start\", { runId }));\n\n const built = await buildPlan(normalized, intent, runId, events);\n let plan = built.plan;\n const selected = plan.route.selected;\n\n if (selected === undefined) {\n const contractReasons = plan.route.noRouteReasons.filter(\n (r) =>\n r.code === \"contract-budget-exceeded\" ||\n r.code === \"contract-quality-floor\" ||\n r.code === \"contract-modality-missing\" ||\n r.code === \"contract-privacy-mismatch\",\n );\n const isContractFailure = contractReasons.length > 0;\n const receipt = await maybeIssueReceipt(normalized, {\n runId,\n ...(intent.contract !== undefined ? { contract: intent.contract } : {}),\n artifacts: intent.artifacts ?? [],\n contractVerdict: isContractFailure\n ? \"no-contract-match\"\n : \"execution-failed\",\n model: {\n requested: intent.overrides?.model ?? \"\",\n observed: null,\n },\n route: { providerId: \"\", capabilityId: \"\", attemptNumber: 0 },\n usage: ZERO_USAGE,\n ...(isContractFailure\n ? { noRouteReasons: plan.route.noRouteReasons }\n : {}),\n });\n const failure: RunResult<TOutputs> = isContractFailure\n ? {\n ok: false as const,\n error: {\n kind: \"no-contract-match\" as const,\n message: \"No route satisfies the contract.\",\n noRouteReasons: plan.route.noRouteReasons,\n },\n usage: { ...ZERO_USAGE },\n plan,\n events,\n ...(receipt !== undefined ? { receipt } : {}),\n }\n : {\n ok: false as const,\n error: {\n kind: \"no_route\" as const,\n message: \"No route satisfied the run requirements.\",\n reasons: plan.route.noRouteReasons.map((reason) => reason.message),\n },\n usage: { ...ZERO_USAGE },\n plan,\n events,\n ...(receipt !== undefined ? { receipt } : {}),\n };\n await emitEvent(normalized, events, createRunEvent(\"run.failed\", {\n runId,\n planId: plan.id,\n metadata: { reason: isContractFailure ? \"no-contract-match\" : \"no-route\" },\n }));\n\n return failure;\n }\n\n const routes = [\n selected,\n ...plan.route.fallbackChain.map((fallback) =>\n routeFromCandidate(plan, fallback.providerId, fallback.modelId) ?? {\n providerId: fallback.providerId,\n modelId: fallback.modelId,\n score: fallback.score,\n estimates: selected.estimates,\n inputModalities: selected.inputModalities,\n outputModalities: selected.outputModalities,\n fileTransport: selected.fileTransport,\n } satisfies SelectedRoute,\n ),\n ];\n const attempts: ProviderAttemptRecord[] = [];\n let lastError: Error | undefined;\n let anyExecutableAdapter = false;\n\n for (const [index, route] of routes.entries()) {\n const adapter = findExecutableAdapter(normalized, route.providerId);\n\n if (adapter === undefined) {\n lastError = new Error(\"No Phase 1 provider adapter with execute() is configured.\");\n continue;\n }\n\n anyExecutableAdapter = true;\n\n if (index > 0) {\n await emitEvent(normalized, events, createRunEvent(\"fallback.activated\", {\n runId,\n planId: plan.id,\n providerId: route.providerId,\n modelId: route.modelId,\n }));\n }\n\n const startedAt = new Date().toISOString();\n const attemptPackaging = packageArtifactsForProvider({\n artifacts: built.artifacts,\n route,\n ...(built.mergedPolicy !== undefined ? { policy: built.mergedPolicy } : {}),\n });\n\n if (attemptPackaging.blocked.length > 0) {\n const message = attemptPackaging.blocked.join(\"; \");\n attempts.push(attemptFailed(route.providerId, route.modelId, startedAt, new Date().toISOString(), message));\n lastError = new Error(message);\n continue;\n }\n\n const request: ProviderRunRequest = {\n task: intent.task,\n artifacts: built.artifacts,\n outputs: Object.keys(intent.outputs),\n outputContracts: intent.outputs,\n ...(built.mergedPolicy !== undefined ? { policy: built.mergedPolicy } : {}),\n ...(intent.signal !== undefined ? { signal: intent.signal } : {}),\n plan,\n contextPack: built.contextPack,\n providerPackaging: attemptPackaging.plan,\n packagedArtifacts: attemptPackaging.packagedArtifacts,\n };\n\n try {\n await emitEvent(normalized, events, createRunEvent(\"provider.attempt\", {\n runId,\n planId: plan.id,\n providerId: route.providerId,\n modelId: route.modelId,\n metadata: { status: \"started\", fallback: index > 0 },\n }));\n await intent.overrides?.hooks?.beforeProviderCall?.({ plan, request });\n\n plan = withPlanStatus(plan, \"running\", {\n stages: markStage(plan.stages, \"execution\", \"running\"),\n attempts: [\n ...attempts,\n {\n providerId: route.providerId,\n modelId: route.modelId,\n status: \"running\",\n startedAt,\n },\n ],\n });\n\n const response = await adapter.execute(request);\n await intent.overrides?.hooks?.afterProviderCall?.({ plan, response });\n\n const completedAt = new Date().toISOString();\n const validation = await validateOutputMap(intent.outputs, response.rawOutputs, plan);\n const succeededAttempt = attemptSucceeded(\n route.providerId,\n route.modelId,\n startedAt,\n completedAt,\n response.usage,\n );\n\n if (!validation.ok) {\n attempts.push({\n ...succeededAttempt,\n status: \"failed\",\n error: validation.error.message,\n });\n const failedPlan = withPlanStatus(plan, \"failed\", {\n stages: markStage(plan.stages, \"validation\", \"failed\"),\n attempts,\n });\n await emitEvent(normalized, events, createRunEvent(\"validation.failed\", {\n runId,\n planId: plan.id,\n providerId: route.providerId,\n modelId: route.modelId,\n metadata: { error: validation.error.message },\n }));\n if (index === routes.length - 1) {\n const receipt = await maybeIssueReceipt(normalized, {\n runId,\n ...(intent.contract !== undefined\n ? { contract: intent.contract }\n : {}),\n artifacts: built.artifacts,\n contractVerdict: \"validation-failed\",\n model: { requested: route.modelId, observed: null },\n route: {\n providerId: route.providerId,\n capabilityId: route.modelId,\n attemptNumber: attempts.length,\n },\n usage: normalizeAdapterUsage(response),\n });\n return {\n ...validation,\n usage: normalizeAdapterUsage(response),\n plan: failedPlan,\n events,\n ...(receipt !== undefined ? { receipt } : {}),\n };\n }\n lastError = new Error(validation.error.message);\n continue;\n }\n\n // Phase 8 tripwire evaluation — TRIP-02, TRIP-03, TRIP-04, TRIP-05.\n // Runs ONLY when output schema validation succeeded (we are inside the\n // `validation.ok === true` branch). First violation aborts the run\n // and short-circuits the fallback chain (terminal by construction —\n // see the early return below).\n const invariants = intent.contract?.invariants ?? [];\n if (invariants.length > 0) {\n // validation.ok === true was just verified; narrow to the success\n // shape so we can hand the validated outputs to the evaluator.\n const validatedSuccess = validation as Extract<typeof validation, { ok: true }>;\n const tripwireResult = await evaluateTripwires(\n validatedSuccess.outputs,\n invariants,\n );\n if (!tripwireResult.ok) {\n const tripwireFailedAt = new Date().toISOString();\n attempts.push({\n ...succeededAttempt,\n status: \"failed\",\n error: tripwireResult.evidence.message,\n completedAt: tripwireFailedAt,\n });\n const failedPlan = withPlanStatus(plan, \"failed\", {\n stages: markStage(\n markStage(\n markStage(plan.stages, \"execution\", \"completed\"),\n \"validation\",\n \"completed\",\n ),\n \"tripwire\",\n \"failed\",\n { invariantId: tripwireResult.evidence.invariantId },\n ),\n attempts,\n });\n await emitEvent(\n normalized,\n events,\n createRunEvent(\"run.failed\", {\n runId,\n planId: failedPlan.id,\n providerId: route.providerId,\n modelId: route.modelId,\n metadata: {\n reason: \"tripwire-violated\",\n invariantId: tripwireResult.evidence.invariantId,\n },\n }),\n );\n const receipt = await maybeIssueReceipt(normalized, {\n runId,\n ...(intent.contract !== undefined\n ? { contract: intent.contract }\n : {}),\n artifacts: built.artifacts,\n contractVerdict: \"tripwire-violated\",\n model: { requested: route.modelId, observed: null },\n route: {\n providerId: route.providerId,\n capabilityId: route.modelId,\n attemptNumber: attempts.length,\n },\n usage: normalizeAdapterUsage(response),\n tripwireEvidence: tripwireResult.evidence,\n });\n // TERMINAL by design — isTerminal(error) === true; fallback chain\n // bypassed via early return before the `for` loop advances.\n return {\n ok: false,\n error: {\n kind: \"tripwire-violated\" as const,\n message: tripwireResult.evidence.message,\n invariantId: tripwireResult.evidence.invariantId,\n evidence: tripwireResult.evidence,\n terminal: true as const,\n },\n usage: normalizeAdapterUsage(response),\n plan: failedPlan,\n events,\n ...(receipt !== undefined ? { receipt } : {}),\n };\n }\n }\n\n attempts.push(succeededAttempt);\n const artifactRefs =\n response.artifactRefs !== undefined\n ? response.artifactRefs.map(toArtifactRef)\n : [];\n const completedPlan = withPlanStatus(plan, \"completed\", {\n stages: markStage(\n markStage(\n markStage(\n markStage(\n markStage(plan.stages, \"execution\", \"completed\"),\n \"validation\",\n \"completed\",\n ),\n \"persistence\",\n \"completed\",\n ),\n \"tool-execution\",\n built.toolResults.length > 0 ? \"completed\" : \"skipped\",\n ),\n \"tripwire\",\n invariants.length > 0 ? \"completed\" : \"skipped\",\n ),\n attempts,\n });\n\n if (built.sessionRecord !== undefined && normalized.sessions !== undefined) {\n await normalized.sessions.appendTurn({\n sessionId: built.sessionRecord.id,\n task: intent.task,\n artifactRefs: built.artifacts.map(toArtifactRef),\n outputArtifactRefs: artifactRefs,\n planId: completedPlan.id,\n });\n }\n\n await emitEvent(normalized, events, createRunEvent(\"validation.complete\", {\n runId,\n planId: completedPlan.id,\n providerId: route.providerId,\n modelId: route.modelId,\n }));\n await emitEvent(normalized, events, createRunEvent(\"run.complete\", {\n runId,\n planId: completedPlan.id,\n }));\n\n const successValidation = validation as Extract<\n typeof validation,\n { ok: true }\n >;\n const receipt = await maybeIssueReceipt(normalized, {\n runId,\n ...(intent.contract !== undefined ? { contract: intent.contract } : {}),\n artifacts: built.artifacts,\n contractVerdict: \"success\",\n model: { requested: route.modelId, observed: null },\n route: {\n providerId: route.providerId,\n capabilityId: route.modelId,\n attemptNumber: attempts.length,\n },\n usage: normalizeAdapterUsage(response),\n outputs: JSON.stringify(successValidation.outputs),\n });\n\n return {\n ...validation,\n artifacts: artifactRefs,\n usage: normalizeAdapterUsage(response),\n plan: completedPlan,\n events,\n ...(receipt !== undefined ? { receipt } : {}),\n };\n } catch (error) {\n const completedAt = new Date().toISOString();\n const message =\n error instanceof Error ? error.message : \"Provider adapter execution failed.\";\n attempts.push(attemptFailed(route.providerId, route.modelId, startedAt, completedAt, message));\n lastError = error instanceof Error ? error : new Error(message);\n await emitEvent(normalized, events, createRunEvent(\"provider.attempt\", {\n runId,\n planId: plan.id,\n providerId: route.providerId,\n modelId: route.modelId,\n metadata: { status: \"failed\", error: message },\n }));\n }\n }\n\n if (!anyExecutableAdapter) {\n const receipt = await maybeIssueReceipt(normalized, {\n runId,\n ...(intent.contract !== undefined ? { contract: intent.contract } : {}),\n artifacts: built.artifacts,\n contractVerdict: \"execution-failed\",\n model: { requested: selected.modelId, observed: null },\n route: {\n providerId: selected.providerId,\n capabilityId: selected.modelId,\n attemptNumber: 0,\n },\n usage: ZERO_USAGE,\n });\n return {\n ok: false,\n error: {\n kind: \"execution_unavailable\",\n message: \"No Phase 1 provider adapter with execute() is configured.\",\n },\n usage: { ...ZERO_USAGE },\n plan,\n events,\n ...(receipt !== undefined ? { receipt } : {}),\n };\n }\n\n const failedPlan = withPlanStatus(plan, \"failed\", {\n stages: markStage(plan.stages, \"execution\", \"failed\"),\n attempts,\n });\n await emitEvent(normalized, events, createRunEvent(\"run.failed\", {\n runId,\n planId: failedPlan.id,\n metadata: {\n error: lastError?.message ?? \"Provider adapter execution failed.\",\n },\n }));\n\n const receipt = await maybeIssueReceipt(normalized, {\n runId,\n ...(intent.contract !== undefined ? { contract: intent.contract } : {}),\n artifacts: built.artifacts,\n contractVerdict: \"execution-failed\",\n model: { requested: selected.modelId, observed: null },\n route: {\n providerId: selected.providerId,\n capabilityId: selected.modelId,\n attemptNumber: attempts.length,\n },\n usage: UNMEASURED_USAGE,\n });\n\n return {\n ok: false,\n error: {\n kind: \"provider_execution\",\n message: lastError?.message ?? \"Provider adapter execution failed.\",\n providerId: selected.providerId,\n modelId: selected.modelId,\n },\n usage: { ...UNMEASURED_USAGE },\n plan: failedPlan,\n events,\n ...(receipt !== undefined ? { receipt } : {}),\n };\n}\n\nasync function buildPlan<const TOutputs extends OutputContractMap>(\n normalized: NormalizedLatticeConfig,\n intent: RunIntent<TOutputs>,\n runId = createRunId(),\n events: RunEvent[] = [],\n): Promise<BuiltPlan> {\n const prepared = await prepareArtifacts(intent);\n const artifacts = prepared.artifacts;\n const mergedPolicy = mergePolicy(\n mergePolicy(normalized.defaults.policy, intent.policy),\n intent.overrides?.routingPolicy,\n );\n const sessionRecord =\n intent.session !== undefined && normalized.sessions !== undefined\n ? await loadOrCreateSession(normalized, intent.session)\n : undefined;\n const catalog = createCapabilityCatalog(normalized.providers);\n const route = routeDeterministically(catalog, {\n task: intent.task,\n artifacts,\n outputs: intent.outputs,\n ...(mergedPolicy !== undefined ? { policy: mergedPolicy } : {}),\n ...(intent.overrides?.provider !== undefined\n ? { provider: intent.overrides.provider }\n : {}),\n ...(intent.overrides?.model !== undefined ? { model: intent.overrides.model } : {}),\n ...(intent.contract !== undefined ? { contract: intent.contract } : {}),\n });\n const contextPack = buildContextPack({\n task: intent.task,\n artifacts,\n ...(route.selected !== undefined ? { route: route.selected } : {}),\n ...(sessionRecord !== undefined ? { session: sessionRecord } : {}),\n ...(intent.overrides?.tokenBudget !== undefined\n ? { tokenBudget: intent.overrides.tokenBudget }\n : {}),\n });\n const summaryRefs =\n contextPack.summarized.length > 0 && intent.overrides?.summarizer !== undefined\n ? await intent.overrides.summarizer.summarize({\n artifacts: artifacts.map(toArtifactRef),\n budgetTokens: contextPack.tokenBudget,\n })\n : [];\n const packaging = packageArtifactsForProvider({\n artifacts,\n ...(route.selected !== undefined ? { route: route.selected } : {}),\n ...(mergedPolicy !== undefined ? { policy: mergedPolicy } : {}),\n });\n let plan = createExecutionPlan({\n task: intent.task,\n artifacts: artifacts.map(toArtifactRef),\n outputs: intent.outputs,\n route,\n context: contextPack,\n providerPackaging: packaging.plan,\n warnings: packaging.blocked,\n metadata: {\n ...(intent.tools !== undefined\n ? { tools: intent.tools.map((tool) => tool.name) }\n : {}),\n ...(summaryRefs.length > 0\n ? { summaryArtifactIds: summaryRefs.map((summary) => summary.id) }\n : {}),\n },\n });\n plan = withPlanStatus(plan, plan.status, {\n stages: markStage(\n plan.stages,\n \"tool-execution\",\n prepared.toolResults.length > 0 ? \"completed\" : \"skipped\",\n prepared.toolResults.length > 0\n ? {\n toolNames: prepared.toolResults.map((result) => result.toolName),\n }\n : undefined,\n ),\n });\n\n for (const result of prepared.toolResults) {\n await emitEvent(normalized, events, createRunEvent(\"tool.call\", {\n runId,\n planId: plan.id,\n artifactId: result.artifact.id,\n metadata: {\n toolName: result.toolName,\n callId: result.callId,\n },\n }));\n await emitEvent(normalized, events, createRunEvent(\"artifact.created\", {\n runId,\n planId: plan.id,\n artifactId: result.artifact.id,\n metadata: {\n source: \"tool\",\n },\n }));\n }\n\n for (const artifactRef of artifacts.map(toArtifactRef)) {\n await emitEvent(normalized, events, createRunEvent(\"artifact.ingested\", {\n runId,\n planId: plan.id,\n artifactId: artifactRef.id,\n }));\n }\n\n await emitEvent(normalized, events, createRunEvent(\"context.packed\", {\n runId,\n planId: plan.id,\n metadata: {\n estimatedTokens: contextPack.estimatedTokens,\n included: contextPack.included.length,\n summarized: contextPack.summarized.length,\n omitted: contextPack.omitted.length,\n },\n }));\n await emitEvent(normalized, events, createRunEvent(\"router.candidates\", {\n runId,\n planId: plan.id,\n metadata: {\n selected: route.selected?.modelId,\n rejected: route.rejected.length,\n fallbacks: route.fallbackChain.length,\n },\n }));\n\n return {\n plan,\n artifacts,\n contextPack,\n packagedArtifacts: packaging.packagedArtifacts,\n blockedPackaging: packaging.blocked,\n toolResults: prepared.toolResults,\n ...(mergedPolicy !== undefined ? { mergedPolicy } : {}),\n ...(sessionRecord !== undefined ? { sessionRecord } : {}),\n };\n}\n\nasync function prepareArtifacts<const TOutputs extends OutputContractMap>(\n intent: RunIntent<TOutputs>,\n): Promise<{\n readonly artifacts: readonly ArtifactInput[];\n readonly toolResults: readonly ToolCallResult[];\n}> {\n let artifacts = [...(intent.artifacts ?? [])];\n\n for (const transform of intent.overrides?.transforms ?? []) {\n const transformed = await transform.transform({\n task: intent.task,\n artifacts,\n });\n artifacts = artifacts.concat(Array.isArray(transformed) ? transformed : [transformed]);\n }\n\n const toolResults: ToolCallResult[] = [];\n\n for (const tool of intent.tools ?? []) {\n const result = await runTool(tool, intent.toolInputs?.[tool.name] ?? {});\n toolResults.push(result);\n artifacts.push(result.artifact);\n }\n\n return { artifacts, toolResults };\n}\n\nasync function loadOrCreateSession(\n normalized: NormalizedLatticeConfig,\n session: SessionRef,\n): Promise<SessionRecord> {\n const existing = await normalized.sessions?.load(session.id);\n\n if (existing !== undefined) {\n return existing;\n }\n\n if (normalized.sessions === undefined) {\n throw new Error(\"Session storage is not configured.\");\n }\n\n return normalized.sessions.create({ id: session.id });\n}\n\nfunction attemptSucceeded(\n providerId: string,\n modelId: string,\n startedAt: string,\n completedAt: string,\n usage?: UsageRecord,\n): ProviderAttemptRecord {\n return {\n providerId,\n modelId,\n status: \"succeeded\",\n startedAt,\n completedAt,\n ...(usage !== undefined ? { usage } : {}),\n };\n}\n\nfunction attemptFailed(\n providerId: string,\n modelId: string,\n startedAt: string,\n completedAt: string,\n error: string,\n): ProviderAttemptRecord {\n return {\n providerId,\n modelId,\n status: \"failed\",\n startedAt,\n completedAt,\n error,\n };\n}\n\nfunction findExecutableAdapter(\n normalized: NormalizedLatticeConfig,\n providerId: string,\n): (ProviderAdapter & Required<Pick<ProviderAdapter, \"execute\">>) | undefined {\n return normalized.providers.find((provider) =>\n provider.kind === \"provider-adapter\" &&\n provider.id === providerId &&\n typeof provider.execute === \"function\",\n ) as (ProviderAdapter & Required<Pick<ProviderAdapter, \"execute\">>) | undefined;\n}\n\nfunction routeFromCandidate(\n plan: ExecutionPlan,\n providerId: string,\n modelId: string,\n): SelectedRoute | undefined {\n const candidate = plan.route.candidates.find(\n (item) => item.providerId === providerId && item.modelId === modelId,\n );\n\n if (candidate === undefined) {\n return undefined;\n }\n\n return {\n providerId,\n modelId,\n score: candidate.score,\n estimates: candidate.estimates,\n inputModalities: candidate.capability.inputModalities,\n outputModalities: candidate.capability.outputModalities,\n fileTransport: candidate.capability.fileTransport,\n };\n}\n\nasync function emitEvent(\n normalized: NormalizedLatticeConfig,\n events: RunEvent[],\n event: RunEvent,\n): Promise<void> {\n events.push(event);\n normalized.tracing?.event?.(event.kind, {\n ...event.metadata,\n planId: event.planId,\n providerId: event.providerId,\n modelId: event.modelId,\n artifactId: event.artifactId,\n });\n\n await Promise.all(normalized.events.map((sink) => sink(event)));\n}\n\nfunction createRunId(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return `run:${crypto.randomUUID()}`;\n }\n\n return `run:${Date.now()}:${Math.random().toString(16).slice(2)}`;\n}\n\n/**\n * Normalize an adapter response into the `RunResult.usage` shape.\n *\n * Prefers `ProviderRunResponse.normalizedUsage` (the Phase 7 shape emitted by\n * openai / openai-compat / ai-sdk / fake adapters). Falls back to mapping the\n * legacy `UsageRecord` (inputTokens / outputTokens) so v1.0 adapters that have\n * not yet been re-rolled still surface a usable Usage value.\n */\nfunction normalizeAdapterUsage(response: ProviderRunResponse): Usage {\n if (response.normalizedUsage !== undefined) {\n return response.normalizedUsage;\n }\n return {\n promptTokens: response.usage?.inputTokens ?? 0,\n completionTokens: response.usage?.outputTokens ?? 0,\n costUsd: response.usage?.costUsd ?? null,\n };\n}\n\n/**\n * Phase 9 — hash each artifact's canonical value via SHA-256 and return the\n * hex digests in declaration order. Missing/undefined values produce an\n * empty string so the array length matches `artifacts.length` exactly.\n */\nasync function hashInputArtifacts(\n artifacts: readonly ArtifactInput[],\n): Promise<readonly string[]> {\n const out: string[] = [];\n for (const artifact of artifacts) {\n const fp = await fingerprintArtifactValue(\n (artifact as { readonly value?: unknown }).value,\n );\n out.push(fp?.value ?? \"\");\n }\n return out;\n}\n\n/**\n * Phase 9 — SHA-256 hex of `canonicalize(contract)` for the receipt's\n * contractHash field. Returns null when no contract is attached or when\n * canonicalize cannot serialize the input.\n */\nasync function sha256HexOfCanonicalContract(\n contract: unknown,\n): Promise<string | null> {\n if (contract === undefined || contract === null) return null;\n const canonical = canonicalize(contract);\n if (canonical === undefined) return null;\n const bytes = new TextEncoder().encode(canonical);\n const ab = new Uint8Array(bytes.byteLength);\n ab.set(bytes);\n const digest = await crypto.subtle.digest(\"SHA-256\", ab.buffer as ArrayBuffer);\n return Array.from(new Uint8Array(digest))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\ninterface MaybeIssueReceiptInput {\n readonly runId: string;\n readonly contract?: CapabilityContract;\n readonly artifacts: readonly ArtifactInput[];\n readonly contractVerdict: ContractVerdict;\n readonly model: ReceiptModel;\n readonly route: ReceiptRoute;\n readonly usage: Usage;\n readonly outputs?: unknown;\n readonly noRouteReasons?: readonly RouteRejectReason[];\n readonly tripwireEvidence?: TripwireEvidence;\n}\n\n/**\n * Phase 9 — issue a signed receipt at a terminal branch when a signer is\n * configured. Signer failures degrade gracefully to `undefined` so a faulty\n * signer never crashes `ai.run`.\n */\nasync function maybeIssueReceipt(\n normalized: NormalizedLatticeConfig,\n input: MaybeIssueReceiptInput,\n): Promise<ReceiptEnvelope | undefined> {\n if (normalized.signer === undefined) return undefined;\n try {\n const inputHashes = await hashInputArtifacts(input.artifacts);\n const outputHash =\n input.outputs === undefined\n ? null\n : ((await fingerprintArtifactValue(input.outputs))?.value ?? null);\n const contractHash = await sha256HexOfCanonicalContract(input.contract);\n return await createReceipt(\n {\n runId: input.runId,\n model: input.model,\n route: input.route,\n usage: input.usage,\n contractVerdict: input.contractVerdict,\n contractHash,\n inputHashes,\n outputHash,\n ...(input.noRouteReasons !== undefined\n ? { noRouteReasons: input.noRouteReasons }\n : {}),\n ...(input.tripwireEvidence !== undefined\n ? { tripwireEvidence: input.tripwireEvidence }\n : {}),\n },\n normalized.signer,\n );\n } catch {\n // Receipt emission is best-effort. A signer failure must NOT crash\n // ai.run — the run result already encodes the verdict.\n return undefined;\n }\n}\n","import type { ArtifactRef } from \"../artifacts/artifact.js\";\n\nexport interface SessionRef {\n readonly id: string;\n readonly kind?: \"session-ref\";\n}\n\nexport interface SessionTurn {\n readonly id: string;\n readonly task: string;\n readonly artifactRefs: readonly ArtifactRef[];\n readonly planId?: string;\n readonly outputArtifactRefs: readonly ArtifactRef[];\n readonly createdAt: string;\n}\n\nexport interface SessionSummary {\n readonly id: string;\n readonly artifactRef: ArtifactRef;\n readonly sourceTurnIds: readonly string[];\n readonly trust: \"model-summary\";\n readonly createdAt: string;\n}\n\nexport interface SessionRecord extends SessionRef {\n readonly kind: \"session-ref\";\n readonly parentId?: string;\n readonly branchPointRunId?: string;\n readonly turns: readonly SessionTurn[];\n readonly summaries: readonly SessionSummary[];\n readonly artifactRefs: readonly ArtifactRef[];\n readonly planIds: readonly string[];\n readonly createdAt: string;\n readonly updatedAt: string;\n}\n\nexport interface CreateSessionOptions {\n readonly id?: string;\n readonly parentId?: string;\n readonly branchPointRunId?: string;\n}\n\nexport interface AppendSessionTurnInput {\n readonly sessionId: string;\n readonly task: string;\n readonly artifactRefs: readonly ArtifactRef[];\n readonly outputArtifactRefs?: readonly ArtifactRef[];\n readonly planId?: string;\n}\n\nexport interface SessionStore {\n readonly kind: \"session-store\";\n readonly id: string;\n create(options?: CreateSessionOptions): Promise<SessionRecord>;\n load(id: string): Promise<SessionRecord | undefined>;\n save(session: SessionRecord): Promise<SessionRecord>;\n branch(parentId: string, options?: Omit<CreateSessionOptions, \"parentId\">): Promise<SessionRecord>;\n appendTurn(input: AppendSessionTurnInput): Promise<SessionRecord>;\n}\n\nexport interface MemorySessionStoreOptions {\n readonly id?: string;\n}\n\nexport function createMemorySessionStore(\n options: MemorySessionStoreOptions = {},\n): SessionStore {\n const storeId = options.id ?? \"memory-sessions\";\n const sessions = new Map<string, SessionRecord>();\n\n return {\n kind: \"session-store\",\n id: storeId,\n\n async create(createOptions = {}) {\n const now = new Date().toISOString();\n const session: SessionRecord = {\n id: createOptions.id ?? createSessionId(),\n kind: \"session-ref\",\n ...(createOptions.parentId !== undefined ? { parentId: createOptions.parentId } : {}),\n ...(createOptions.branchPointRunId !== undefined\n ? { branchPointRunId: createOptions.branchPointRunId }\n : {}),\n turns: [],\n summaries: [],\n artifactRefs: [],\n planIds: [],\n createdAt: now,\n updatedAt: now,\n };\n\n sessions.set(session.id, clone(session));\n\n return clone(session);\n },\n\n async load(id) {\n const session = sessions.get(id);\n\n return session === undefined ? undefined : clone(session);\n },\n\n async save(session) {\n sessions.set(session.id, clone(session));\n\n return clone(session);\n },\n\n async branch(parentId, branchOptions = {}) {\n const parent = sessions.get(parentId);\n const branched = await this.create({\n ...branchOptions,\n parentId,\n });\n\n if (parent === undefined) {\n return branched;\n }\n\n const inherited: SessionRecord = {\n ...branched,\n turns: clone(parent.turns),\n summaries: clone(parent.summaries),\n artifactRefs: clone(parent.artifactRefs),\n planIds: clone(parent.planIds),\n };\n\n sessions.set(inherited.id, clone(inherited));\n\n return clone(inherited);\n },\n\n async appendTurn(input) {\n const existing = sessions.get(input.sessionId) ?? await this.create({ id: input.sessionId });\n const turn: SessionTurn = {\n id: createTurnId(),\n task: input.task,\n artifactRefs: clone(input.artifactRefs),\n outputArtifactRefs: clone(input.outputArtifactRefs ?? []),\n ...(input.planId !== undefined ? { planId: input.planId } : {}),\n createdAt: new Date().toISOString(),\n };\n const artifactRefs = mergeArtifactRefs(\n existing.artifactRefs,\n input.artifactRefs,\n input.outputArtifactRefs ?? [],\n );\n const planIds =\n input.planId === undefined\n ? existing.planIds\n : [...existing.planIds, input.planId];\n const next: SessionRecord = {\n ...existing,\n turns: [...existing.turns, turn],\n artifactRefs,\n planIds,\n updatedAt: new Date().toISOString(),\n };\n\n sessions.set(next.id, clone(next));\n\n return clone(next);\n },\n };\n}\n\nfunction mergeArtifactRefs(\n current: readonly ArtifactRef[],\n ...groups: readonly (readonly ArtifactRef[])[]\n): readonly ArtifactRef[] {\n const byId = new Map(current.map((artifact) => [artifact.id, artifact]));\n\n for (const group of groups) {\n for (const artifact of group) {\n byId.set(artifact.id, artifact);\n }\n }\n\n return [...byId.values()];\n}\n\nfunction createSessionId(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return `session:${crypto.randomUUID()}`;\n }\n\n return `session:${Date.now()}:${Math.random().toString(16).slice(2)}`;\n}\n\nfunction createTurnId(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return `turn:${crypto.randomUUID()}`;\n }\n\n return `turn:${Date.now()}:${Math.random().toString(16).slice(2)}`;\n}\n\nfunction clone<T>(value: T): T {\n try {\n return structuredClone(value);\n } catch {\n return value;\n }\n}\n","import { mkdir, readFile, readdir, rm, stat, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport type { ArtifactInput, ArtifactRef } from \"../artifacts/artifact.js\";\nimport { toArtifactRef } from \"../artifacts/artifact.js\";\nimport { fingerprintArtifactValue } from \"./fingerprint.js\";\nimport type {\n ArtifactStore,\n StoredArtifactEnvelope,\n StoredArtifactPayloadDescriptor,\n} from \"./storage.js\";\n\nexport interface LocalArtifactStoreOptions {\n readonly id?: string;\n}\n\nexport function createLocalArtifactStore(\n rootDir: string | URL,\n options: LocalArtifactStoreOptions = {},\n): ArtifactStore {\n const rootPath = rootDir instanceof URL ? fileURLToPath(rootDir) : rootDir;\n const storeId = options.id ?? \"local\";\n\n return {\n kind: \"artifact-store\",\n id: storeId,\n\n async put(artifact: ArtifactInput): Promise<ArtifactRef> {\n const artifactDir = artifactDirectory(rootPath, artifact.id);\n const fingerprint =\n artifact.fingerprint ?? await fingerprintArtifactValue(artifact.value);\n const storedArtifact: ArtifactInput = {\n ...artifact,\n storage: {\n storeId,\n key: artifact.id,\n },\n ...(fingerprint !== undefined ? { fingerprint } : {}),\n };\n const ref = toArtifactRef(storedArtifact);\n\n await rm(artifactDir, { recursive: true, force: true });\n await mkdir(artifactDir, { recursive: true });\n\n const payload = await writePayload(artifactDir, artifact.value);\n const envelope: StoredArtifactEnvelope = {\n version: 1,\n ref,\n ...(payload !== undefined ? { payload } : {}),\n };\n\n await writeFile(\n metadataPath(rootPath, artifact.id),\n `${JSON.stringify(envelope, null, 2)}\\n`,\n \"utf8\",\n );\n\n return ref;\n },\n\n async get(id: string): Promise<ArtifactRef | undefined> {\n const envelope = await readEnvelope(rootPath, id);\n\n return envelope?.ref;\n },\n\n async load(id: string): Promise<ArtifactInput | undefined> {\n const envelope = await readEnvelope(rootPath, id);\n\n if (envelope === undefined) {\n return undefined;\n }\n\n if (envelope.payload === undefined) {\n return envelope.ref;\n }\n\n const value = await readPayload(artifactDirectory(rootPath, id), envelope.payload);\n\n return {\n ...envelope.ref,\n value,\n };\n },\n\n async has(id: string): Promise<boolean> {\n try {\n await stat(metadataPath(rootPath, id));\n\n return true;\n } catch (error) {\n if (isNotFoundError(error)) {\n return false;\n }\n\n throw error;\n }\n },\n\n async delete(id: string): Promise<boolean> {\n const exists = await this.has(id);\n\n if (!exists) {\n return false;\n }\n\n await rm(artifactDirectory(rootPath, id), { recursive: true, force: true });\n\n return true;\n },\n\n async list(): Promise<readonly ArtifactRef[]> {\n const artifactsPath = join(rootPath, \"artifacts\");\n let entries: readonly { isDirectory(): boolean; name: string }[];\n\n try {\n entries = await readdir(artifactsPath, { withFileTypes: true });\n } catch (error) {\n if (isNotFoundError(error)) {\n return [];\n }\n\n throw error;\n }\n\n const refs = await Promise.all(\n entries\n .filter((entry) => entry.isDirectory())\n .map(async (entry) => {\n const envelope = await readEnvelopeByDirectory(\n join(artifactsPath, entry.name),\n );\n\n return envelope.ref;\n }),\n );\n\n return refs.sort((left, right) => left.id.localeCompare(right.id));\n },\n };\n}\n\nasync function writePayload(\n artifactDir: string,\n value: unknown,\n): Promise<StoredArtifactPayloadDescriptor | undefined> {\n if (value === undefined) {\n return undefined;\n }\n\n if (value instanceof Uint8Array || value instanceof ArrayBuffer || isBlobLike(value)) {\n await writeFile(join(artifactDir, \"payload.bin\"), await toBinaryPayload(value));\n\n return {\n kind: \"binary\",\n path: \"payload.bin\",\n };\n }\n\n const serialized = JSON.stringify(value, null, 2);\n\n if (serialized === undefined) {\n return undefined;\n }\n\n await writeFile(join(artifactDir, \"payload.json\"), `${serialized}\\n`, \"utf8\");\n\n return {\n kind: \"json\",\n path: \"payload.json\",\n };\n}\n\nasync function readPayload(\n artifactDir: string,\n payload: StoredArtifactPayloadDescriptor,\n): Promise<unknown> {\n const payloadPath = join(artifactDir, payload.path);\n\n if (payload.kind === \"binary\") {\n const bytes = await readFile(payloadPath);\n\n return new Uint8Array(bytes);\n }\n\n return JSON.parse(await readFile(payloadPath, \"utf8\"));\n}\n\nasync function readEnvelope(\n rootPath: string,\n id: string,\n): Promise<StoredArtifactEnvelope | undefined> {\n try {\n return JSON.parse(await readFile(metadataPath(rootPath, id), \"utf8\"));\n } catch (error) {\n if (isNotFoundError(error)) {\n return undefined;\n }\n\n throw error;\n }\n}\n\nasync function readEnvelopeByDirectory(\n artifactDir: string,\n): Promise<StoredArtifactEnvelope> {\n return JSON.parse(await readFile(join(artifactDir, \"metadata.json\"), \"utf8\"));\n}\n\nasync function toBinaryPayload(\n value: Blob | ArrayBuffer | Uint8Array,\n): Promise<Uint8Array> {\n if (value instanceof Uint8Array) {\n return value;\n }\n\n if (value instanceof ArrayBuffer) {\n return new Uint8Array(value);\n }\n\n return new Uint8Array(await value.arrayBuffer());\n}\n\nfunction artifactDirectory(rootPath: string, id: string): string {\n return join(rootPath, \"artifacts\", encodeURIComponent(id));\n}\n\nfunction metadataPath(rootPath: string, id: string): string {\n return join(artifactDirectory(rootPath, id), \"metadata.json\");\n}\n\nfunction isBlobLike(value: unknown): value is Blob {\n return typeof Blob !== \"undefined\" && value instanceof Blob;\n}\n\nfunction isNotFoundError(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n error.code === \"ENOENT\"\n );\n}\n","import type { ArtifactInput, ArtifactRef } from \"../artifacts/artifact.js\";\nimport { toArtifactRef } from \"../artifacts/artifact.js\";\nimport { fingerprintArtifactValue } from \"./fingerprint.js\";\nimport type { ArtifactStore } from \"./storage.js\";\n\nexport interface MemoryArtifactStoreOptions {\n readonly id?: string;\n}\n\ninterface MemoryArtifactRecord {\n readonly ref: ArtifactRef;\n readonly artifact: ArtifactInput;\n}\n\nexport function createMemoryArtifactStore(\n options: MemoryArtifactStoreOptions = {},\n): ArtifactStore {\n const storeId = options.id ?? \"memory\";\n const artifacts = new Map<string, MemoryArtifactRecord>();\n\n return {\n kind: \"artifact-store\",\n id: storeId,\n\n async put(artifact) {\n const fingerprint =\n artifact.fingerprint ?? await fingerprintArtifactValue(artifact.value);\n const storedArtifact: ArtifactInput = {\n ...cloneArtifactInput(artifact),\n storage: {\n storeId,\n key: artifact.id,\n },\n ...(fingerprint !== undefined ? { fingerprint } : {}),\n };\n const ref = toArtifactRef(storedArtifact);\n\n artifacts.set(artifact.id, {\n ref: cloneArtifactRef(ref),\n artifact: cloneArtifactInput(storedArtifact),\n });\n\n return cloneArtifactRef(ref);\n },\n\n async get(id) {\n const record = artifacts.get(id);\n\n return record === undefined ? undefined : cloneArtifactRef(record.ref);\n },\n\n async load(id) {\n const record = artifacts.get(id);\n\n return record === undefined ? undefined : cloneArtifactInput(record.artifact);\n },\n\n async has(id) {\n return artifacts.has(id);\n },\n\n async delete(id) {\n return artifacts.delete(id);\n },\n\n async list() {\n return Array.from(artifacts.values(), (record) =>\n cloneArtifactRef(record.ref),\n );\n },\n };\n}\n\nfunction cloneArtifactInput(artifact: ArtifactInput): ArtifactInput {\n return cloneValue(artifact);\n}\n\nfunction cloneArtifactRef(ref: ArtifactRef): ArtifactRef {\n return cloneValue(ref);\n}\n\nfunction cloneValue<T>(value: T): T {\n try {\n return structuredClone(value);\n } catch {\n return value;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA0FA,SAAgB,SAAS,QAAiC,EAAE,EAAsB;AAChF,QAAO,OAAO,OAAO;EACnB,MAAM;EACN,GAAI,MAAM,WAAW,KAAA,IAAY,EAAE,QAAQ,OAAO,OAAO,EAAE,GAAG,MAAM,QAAQ,CAAC,EAAE,GAAG,EAAE;EACpF,GAAI,MAAM,eAAe,KAAA,IACrB,EAAE,YAAY,OAAO,OAAO,MAAM,WAAW,KAAK,QAAQ,OAAO,OAAO,EAAE,GAAG,KAAK,CAAC,CAAC,CAAC,EAAE,GACvF,EAAE;EACN,GAAI,MAAM,iBAAiB,KAAA,IACvB,EAAE,cAAc,OAAO,OAAO,EAAE,GAAG,MAAM,cAAc,CAAC,EAAE,GAC1D,EAAE;EACN,GAAI,MAAM,uBAAuB,KAAA,IAC7B,EAAE,oBAAoB,OAAO,OAAO,CAAC,GAAG,MAAM,mBAAmB,CAAC,EAAE,GACpE,EAAE;EACN,GAAI,MAAM,oBAAoB,KAAA,IAAY,EAAE,iBAAiB,MAAM,iBAAiB,GAAG,EAAE;EA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X,UAAO,MAAM,KAAK,UAAU,QAAQ,GAAG,WACrC,iBAAiB,OAAO,IAAI,CAC7B;;EAEJ;;AAGH,SAAS,mBAAmB,UAAwC;AAClE,QAAO,WAAW,SAAS;;AAG7B,SAAS,iBAAiB,KAA+B;AACvD,QAAO,WAAW,IAAI;;AAGxB,SAAS,WAAc,OAAa;AAClC,KAAI;AACF,SAAO,gBAAgB,MAAM;SACvB;AACN,SAAO"}
1
+ {"version":3,"file":"index.js","names":["toArrayBuffer","fail","numberField","emitFallbackEvent","stringifyErr","_mapProfileToNegotiatedCapabilities","DEFAULT_BASE_URL","numberField","stringifyErr","stringifyErr","_mapProfileToNegotiatedCapabilities","isBlobLike"],"sources":["../src/contract/contract.ts","../src/contract/invariants.ts","../src/contract/pii-detectors.ts","../src/routing/catalog.ts","../src/contract/preflight.ts","../src/contract/tripwire.ts","../src/outputs/contracts.ts","../src/receipts/keyset.ts","../src/receipts/sign.ts","../src/receipts/verify.ts","../src/results/errors.ts","../src/capabilities/profile.ts","../src/capabilities/registry.generated.ts","../src/capabilities/registry.static.ts","../src/capabilities/lookup.ts","../src/capabilities/sanitizer-recommendations.ts","../src/capabilities/negotiate.ts","../src/tracing/tracing.ts","../src/tools/tool-call-validation.ts","../src/sanitizers/sanitizers.ts","../src/providers/adapters.ts","../src/providers/anthropic.ts","../src/providers/fake.ts","../src/providers/gemini.ts","../src/providers/lm-studio.ts","../src/providers/openrouter.ts","../src/providers/xai.ts","../src/plan/plan.ts","../src/version.ts","../src/replay/materialize.ts","../src/replay/replay.ts","../src/agent/crew/agent-spec.ts","../src/agent/infra/transcript-store.ts","../src/agent/infra/goal-progress.ts","../src/agent/infra/permission-context.ts","../src/agent/eval.ts","../src/context/context-pack.ts","../src/policy/policy.ts","../src/providers/packaging.ts","../src/routing/router.ts","../src/storage/fingerprint.ts","../src/runtime/config.ts","../src/runtime/create-ai.ts","../src/sessions/session.ts","../src/storage/local.ts","../src/storage/memory.ts","../src/prompts/scaffolds.ts"],"sourcesContent":["import type { CapabilityModality } from \"../providers/provider.js\";\n\nexport type {\n FieldFromTableInvariant,\n InvariantDeclaration,\n MatchesInvariant,\n MustCiteInvariant,\n NoPiiInvariant,\n} from \"./invariants.js\";\n\n// Local alias so the union can be referenced in this module without\n// re-importing through the public re-export above.\nimport type { InvariantDeclaration as InvariantDeclarationUnion } from \"./invariants.js\";\n\n/**\n * Budget invariant declaration attached to a CapabilityContract.\n *\n * Phase 7 implements `maxCostUsd` enforcement at pre-flight. The\n * `p95LatencyMs` field is declared per CONTRACT-02 but is informational\n * only in Phase 7 — latency observations are wired in a later phase.\n *\n * Phase 19 (v1.2) adds `maxIterations` and `maxWallTimeMs` for the agent\n * runtime. Both are additive and optional; non-agent callers ignore them.\n * `maxIterations` caps the number of `runAgent` iterations; `maxWallTimeMs`\n * caps wall-clock duration per `runAgent` invocation. Both are enforced\n * pre-iteration in the agent loop.\n */\nexport interface BudgetInvariant {\n readonly maxCostUsd?: number;\n readonly maxIterations?: number;\n readonly maxWallTimeMs?: number;\n readonly p95LatencyMs?: number;\n}\n\n/**\n * Quality-floor invariant.\n *\n * `suite` is a fixture-directory path string; `minScore` is in 0..1.\n * Phase 7 forwards this into the pre-flight evaluator but only enforces\n * capability-side rejects. Full enforcement lives in Phase 12 (`lattice eval`).\n */\nexport interface QualityFloorInvariant {\n readonly suite: string;\n readonly minScore: number;\n}\n\n/**\n * The full Capability Contract attached to `RunIntent.contract`.\n *\n * All fields are optional. v1.0 callers compile and run unchanged when\n * the field is omitted entirely. PROJECT.md explicitly rejects mandatory\n * contracts.\n */\nexport interface CapabilityContract {\n readonly kind: \"capability-contract\";\n readonly budget?: BudgetInvariant;\n readonly invariants?: readonly InvariantDeclarationUnion[];\n readonly qualityFloor?: QualityFloorInvariant;\n readonly requiredModalities?: readonly CapabilityModality[];\n readonly requiredPrivacy?: \"standard\" | \"sensitive\" | \"restricted\";\n}\n\n/**\n * Reject-reason taxonomy added to `RouteRejectReason.code` by Phase 7's\n * pre-flight evaluator. Closed four-value union per the locked decisions\n * in 07-CONTEXT.md.\n */\nexport type ContractRejectReasonCode =\n | \"contract-budget-exceeded\"\n | \"contract-quality-floor\"\n | \"contract-modality-missing\"\n | \"contract-privacy-mismatch\";\n\n/** Input shape accepted by `contract()`. Mirrors `CapabilityContract` minus `kind`. */\nexport interface CapabilityContractInput {\n readonly budget?: BudgetInvariant;\n readonly invariants?: readonly InvariantDeclarationUnion[];\n readonly qualityFloor?: QualityFloorInvariant;\n readonly requiredModalities?: readonly CapabilityModality[];\n readonly requiredPrivacy?: \"standard\" | \"sensitive\" | \"restricted\";\n}\n\n/**\n * Factory for `CapabilityContract` values.\n *\n * Mirrors the `output()` and adapter factory style — exact-optional safe\n * (does not emit `field: undefined` properties under `exactOptionalPropertyTypes`).\n * Returns a frozen value with frozen nested objects so downstream code can\n * rely on structural immutability when canonicalizing in Phase 9.\n */\nexport function contract(input: CapabilityContractInput = {}): CapabilityContract {\n return Object.freeze({\n kind: \"capability-contract\" as const,\n ...(input.budget !== undefined ? { budget: Object.freeze({ ...input.budget }) } : {}),\n ...(input.invariants !== undefined\n ? { invariants: Object.freeze(input.invariants.map((inv) => Object.freeze({ ...inv }))) }\n : {}),\n ...(input.qualityFloor !== undefined\n ? { qualityFloor: Object.freeze({ ...input.qualityFloor }) }\n : {}),\n ...(input.requiredModalities !== undefined\n ? { requiredModalities: Object.freeze([...input.requiredModalities]) }\n : {}),\n ...(input.requiredPrivacy !== undefined ? { requiredPrivacy: input.requiredPrivacy } : {}),\n });\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n/**\n * Tripwire invariant declaration variants produced by the `inv` fluent\n * builder. Each variant is a frozen value carrying a discriminant `kind`\n * and an `id` (auto-generated or caller-supplied).\n *\n * Phase 8 reshapes the Phase 7 placeholder `{ kind: \"policy\"|\"semantic\"|\"schema\" }`\n * into this discriminated union. Phase 7 never populated `invariants`\n * (see 07-04-SUMMARY decisions), so the change is additive in practice\n * but technically a breaking type change for any external caller that\n * authored a literal of the old shape.\n */\n\nexport interface MustCiteInvariant {\n readonly id: string;\n readonly kind: \"must-cite\";\n readonly artifactName: string;\n}\n\nexport interface FieldFromTableInvariant {\n readonly id: string;\n readonly kind: \"field-from-table\";\n readonly path: string;\n readonly allowedValues: readonly string[];\n}\n\nexport interface NoPiiInvariant {\n readonly id: string;\n readonly kind: \"no-pii\";\n readonly path: string;\n}\n\nexport interface MatchesInvariant<T = unknown> {\n readonly id: string;\n readonly kind: \"matches\";\n readonly path: string;\n readonly schema: StandardSchemaV1<unknown, T>;\n}\n\nexport type InvariantDeclaration =\n | MustCiteInvariant\n | FieldFromTableInvariant\n | NoPiiInvariant\n | MatchesInvariant;\n\nexport interface InvariantOptions {\n readonly id?: string;\n}\n\nlet counter = 0;\n\nfunction nextId(kind: string, options?: InvariantOptions): string {\n counter += 1;\n return options?.id ?? `${kind}-${counter}`;\n}\n\n/**\n * Fluent builder for tripwire invariants.\n *\n * Each helper returns a frozen `InvariantDeclaration` with an auto-generated\n * id of the form `${kind}-${counter}`. Callers may override the id via the\n * second-positional `options.id` arg.\n *\n * The counter is monotonic across kinds — calling `inv.mustCite(\"a\")` then\n * `inv.fieldFromTable(\"x\", [\"y\"])` yields ids `must-cite-1` then\n * `field-from-table-2`. This keeps ids globally unique within a process.\n *\n * Note on `inv.matches`: the caller supplies the StandardSchema validator,\n * and the tripwire evaluator trusts whatever `~standard.validate` returns.\n * This is by design — `matches` is the caller-driven escape hatch (see\n * T-08-05 in the 08-01-PLAN threat register).\n */\nexport const inv = {\n mustCite(artifactName: string, options?: InvariantOptions): MustCiteInvariant {\n return Object.freeze({\n id: nextId(\"must-cite\", options),\n kind: \"must-cite\" as const,\n artifactName,\n });\n },\n fieldFromTable(\n path: string,\n allowedValues: readonly string[],\n options?: InvariantOptions,\n ): FieldFromTableInvariant {\n return Object.freeze({\n id: nextId(\"field-from-table\", options),\n kind: \"field-from-table\" as const,\n path,\n allowedValues: Object.freeze([...allowedValues]),\n });\n },\n noPII(path: string, options?: InvariantOptions): NoPiiInvariant {\n return Object.freeze({\n id: nextId(\"no-pii\", options),\n kind: \"no-pii\" as const,\n path,\n });\n },\n matches<T>(\n path: string,\n schema: StandardSchemaV1<unknown, T>,\n options?: InvariantOptions,\n ): MatchesInvariant<T> {\n return Object.freeze({\n id: nextId(\"matches\", options),\n kind: \"matches\" as const,\n path,\n schema,\n });\n },\n /**\n * Test-only: reset the auto-id counter. NOT exported from the package\n * root barrel — callers must import `inv` directly from this module if\n * they ever need it, which is intentional friction.\n */\n __resetCounterForTests(): void {\n counter = 0;\n },\n} as const;\n","/**\n * Regex-based PII detectors used by the `no-pii` tripwire invariant.\n *\n * Phase 8 ships four detectors (email, US SSN, Luhn-valid credit card,\n * US phone). They are intentionally regex-only — zero new dependencies —\n * per the v1.1 scope locked in 08-CONTEXT.md.\n *\n * Each detector returns either `{ matched: true, substring }` carrying\n * ONLY the matched fragment, or `{ matched: false }`. The substring shape\n * is required so the tripwire evaluator can emit redacted evidence\n * (Phase 9 receipts must not leak the full input).\n *\n * Detector order in `defaultPiiDetectors` is deterministic so the\n * evaluator's first-violation semantics produce stable receipts.\n */\n\nexport type PiiDetectorResult =\n | { readonly matched: true; readonly substring: string }\n | { readonly matched: false };\n\nexport interface PiiDetector {\n readonly name: string;\n detect(input: string): PiiDetectorResult;\n}\n\n/**\n * Luhn check digit validator.\n *\n * Strips non-digit characters from `digits`, requires the resulting length\n * to be 13-19 (ISO/IEC 7812 PAN range), then walks right-to-left doubling\n * every second digit and summing. Returns true when the sum is a multiple\n * of 10.\n */\nfunction luhn(digits: string): boolean {\n const cleaned = digits.replace(/\\D/g, \"\");\n if (cleaned.length < 13 || cleaned.length > 19) return false;\n\n let sum = 0;\n let shouldDouble = false;\n for (let i = cleaned.length - 1; i >= 0; i -= 1) {\n const code = cleaned.charCodeAt(i);\n // Defensive: charAt cannot produce non-digits here because of the\n // `replace(/\\D/g, \"\")` above, but keep a guard for clarity.\n if (code < 48 || code > 57) return false;\n let digit = code - 48;\n if (shouldDouble) {\n digit *= 2;\n if (digit > 9) digit -= 9;\n }\n sum += digit;\n shouldDouble = !shouldDouble;\n }\n return sum % 10 === 0;\n}\n\nfunction execFirst(regex: RegExp, input: string): string | undefined {\n // Always create a fresh exec; we do not rely on regex statefulness.\n const match = regex.exec(input);\n return match ? match[0] : undefined;\n}\n\nconst emailDetector: PiiDetector = {\n name: \"email\",\n detect(input: string): PiiDetectorResult {\n // Local + domain + TLD. Requires at least one non-empty label on each\n // side and a dot in the domain part. Rejects `@bad`, `bad@`, `not-an-email`.\n const substring = execFirst(/[\\w.+-]+@[\\w-]+\\.[\\w.-]+/, input);\n return substring !== undefined ? { matched: true, substring } : { matched: false };\n },\n};\n\nconst ssnDetector: PiiDetector = {\n name: \"us-ssn\",\n detect(input: string): PiiDetectorResult {\n // 3-2-4 grouped SSN with word boundaries on both sides to avoid\n // collapsing into longer adjacent digit runs (e.g., phone numbers).\n const substring = execFirst(/\\b\\d{3}-\\d{2}-\\d{4}\\b/, input);\n return substring !== undefined ? { matched: true, substring } : { matched: false };\n },\n};\n\nconst creditCardDetector: PiiDetector = {\n name: \"credit-card\",\n detect(input: string): PiiDetectorResult {\n // Match any 13-19 character sequence of digits with optional single\n // space or dash separators, then validate with Luhn. The regex is\n // intentionally permissive on separators (banks/forms vary); Luhn\n // filters trivially-formatted strings per Pitfall #5 in CONTEXT.md.\n const candidate = execFirst(/\\b(?:\\d[ -]?){13,19}\\b/, input);\n if (candidate === undefined) return { matched: false };\n // Strip trailing space/dash that the regex may have absorbed.\n const trimmed = candidate.replace(/[ -]+$/, \"\");\n if (!luhn(trimmed)) return { matched: false };\n return { matched: true, substring: trimmed };\n },\n};\n\nconst phoneDetector: PiiDetector = {\n name: \"us-phone\",\n detect(input: string): PiiDetectorResult {\n // Dashed form first, then parenthesized form. Combined alternation so\n // the regex engine picks whichever fires first in input order.\n const substring = execFirst(/\\b\\d{3}-\\d{3}-\\d{4}\\b|\\(\\d{3}\\)\\s?\\d{3}-\\d{4}/, input);\n return substring !== undefined ? { matched: true, substring } : { matched: false };\n },\n};\n\n/**\n * Default PII detectors used by `evaluateTripwires` for `no-pii` invariants.\n *\n * Order is deterministic: email, us-ssn, credit-card, us-phone. Callers who\n * need a different set can pass their own list to `evaluateTripwires`.\n */\nexport const defaultPiiDetectors: readonly PiiDetector[] = Object.freeze([\n emailDetector,\n ssnDetector,\n creditCardDetector,\n phoneDetector,\n]);\n","import type {\n CapabilityModality,\n ModelCapability,\n ProviderAdapter,\n ProviderPricingHint,\n ProviderRef,\n} from \"../providers/provider.js\";\n\nexport const DEFAULT_CATALOG_VERSION = \"lattice:catalog:v1\";\n\nexport interface CapabilityCatalog {\n readonly version: string;\n readonly models: readonly ModelCapability[];\n}\n\nexport function createCapabilityCatalog(\n providers: readonly (ProviderRef | ProviderAdapter)[],\n): CapabilityCatalog {\n return {\n version: DEFAULT_CATALOG_VERSION,\n models: providers.flatMap((provider) => {\n if (provider.kind === \"provider-adapter\" && provider.capabilities !== undefined) {\n return provider.capabilities;\n }\n\n return [defaultCapabilityForProvider(provider.id)];\n }),\n };\n}\n\nexport function defaultCapabilityForProvider(providerId: string): ModelCapability {\n return {\n providerId,\n modelId: `${providerId}:default`,\n inputModalities: [\"text\", \"json\", \"image\", \"audio\", \"document\", \"file\", \"url\", \"tool\"],\n outputModalities: [\"text\", \"json\"],\n fileTransport: [\"inline\", \"json\", \"url\", \"base64\", \"extracted-text\", \"transcript\"],\n contextWindow: 16_000,\n structuredOutput: true,\n toolUse: false,\n streaming: false,\n pricing: {\n inputCostPer1M: 0,\n outputCostPer1M: 0,\n inputPer1kTokens: 0,\n outputPer1kTokens: 0,\n },\n latency: \"interactive\",\n dataPolicy: {\n privacy: [\"standard\", \"sensitive\"],\n uploadRetention: \"none\",\n supportsNoLogging: true,\n supportsNoTraining: true,\n },\n available: true,\n };\n}\n\n/**\n * Resolve the effective per-1k token pricing for a capability.\n *\n * Prefers the explicit `inputPer1kTokens` / `outputPer1kTokens` fields and\n * falls back to dividing the legacy per-1M fields by 1000 when only those\n * are present. Returns `undefined` per side when neither shape supplies a\n * value, so callers can distinguish \"free / zero\" (`0`) from \"unknown\"\n * (`undefined`) — Phase 7 cost normalization treats unknown pricing as\n * `usage.costUsd === null`, not `0`.\n */\nexport function effectivePer1kPricing(\n pricing: ProviderPricingHint | undefined,\n): {\n readonly inputPer1kTokens: number | undefined;\n readonly outputPer1kTokens: number | undefined;\n} {\n if (pricing === undefined) {\n return { inputPer1kTokens: undefined, outputPer1kTokens: undefined };\n }\n\n const inputPer1k =\n pricing.inputPer1kTokens ??\n (pricing.inputCostPer1M !== undefined ? pricing.inputCostPer1M / 1000 : undefined);\n const outputPer1k =\n pricing.outputPer1kTokens ??\n (pricing.outputCostPer1M !== undefined ? pricing.outputCostPer1M / 1000 : undefined);\n\n return {\n inputPer1kTokens: inputPer1k,\n outputPer1kTokens: outputPer1k,\n };\n}\n\nexport function modalRank(modality: CapabilityModality): number {\n const ranks: Record<CapabilityModality, number> = {\n text: 0,\n json: 1,\n image: 2,\n audio: 3,\n document: 4,\n file: 5,\n url: 6,\n video: 7,\n tool: 8,\n };\n\n return ranks[modality];\n}\n","import type { RouteRejectReason } from \"../plan/plan.js\";\nimport type { ModelCapability } from \"../providers/provider.js\";\nimport { effectivePer1kPricing } from \"../routing/catalog.js\";\nimport type { CapabilityContract } from \"./contract.js\";\n\n/**\n * Result of a single pre-flight contract evaluation against a candidate\n * capability. `reasons` is empty when `ok` is true and contains one or more\n * `RouteRejectReason` entries when `ok` is false.\n *\n * The evaluator surfaces ALL failing reasons in a single pass — not the\n * first-failing only — so the deterministic router can aggregate per-candidate\n * rejection detail (CONTEXT.md \"Pre-flight surfaces ALL failed candidates\n * with per-candidate rejection reasons\").\n */\nexport interface ContractPreflightResult {\n readonly ok: boolean;\n readonly reasons: readonly RouteRejectReason[];\n}\n\n/**\n * Input for the pure cost estimator. Token counts come from the router's\n * existing `estimateRoute()` helper so preflight and router agree on the\n * projected output size (one source of truth — see `evaluateContractAgainstRoute`).\n */\nexport interface EstimateRouteCostInput {\n readonly capability: ModelCapability;\n readonly estimatedInputTokens: number;\n readonly estimatedOutputTokens: number;\n}\n\n/**\n * Pure cost estimator. Returns `null` when pricing is unknown (so downstream\n * gates can distinguish \"free / zero\" from \"unmeasured\" per the Phase 7\n * cost-normalization decision). Uses static catalog metadata only — no probes,\n * no external pricing APIs.\n */\nexport function estimateRouteCost(input: EstimateRouteCostInput): number | null {\n const { inputPer1kTokens, outputPer1kTokens } = effectivePer1kPricing(\n input.capability.pricing,\n );\n if (inputPer1kTokens === undefined && outputPer1kTokens === undefined) {\n return null;\n }\n const inputCost = ((inputPer1kTokens ?? 0) * input.estimatedInputTokens) / 1000;\n const outputCost = ((outputPer1kTokens ?? 0) * input.estimatedOutputTokens) / 1000;\n return inputCost + outputCost;\n}\n\n/** Input for the pre-flight evaluator. */\nexport interface EvaluateContractInput {\n readonly capability: ModelCapability;\n readonly estimatedInputTokens: number;\n readonly estimatedOutputTokens: number;\n}\n\n/**\n * Pure pre-flight evaluator. Phase 9 receipts will reuse this for deterministic\n * verdict reconstruction.\n *\n * Token estimation: Phase 7 does NOT define a separate token estimator. Output-\n * token projection is the canonical responsibility of the router's existing\n * `estimateRoute()` helper (in `routing/router.ts`), which already produces an\n * `estimatedOutputTokens` value. The router passes that same value into this\n * evaluator via `EvaluateContractInput.estimatedOutputTokens`, so preflight\n * and the router always agree on the projected output size. Phase 9 receipts\n * will pin the router's estimate as the deterministic input — intentionally\n * one source of truth.\n *\n * Reject taxonomy (Phase 7 emits three of four codes):\n * - `contract-budget-exceeded` (CONTRACT-04 + COST-03)\n * - `contract-modality-missing` (CONTRACT-06)\n * - `contract-privacy-mismatch` (CONTRACT-06)\n * - `contract-quality-floor` (reserved for Phase 12 `lattice eval`; NEVER emitted here)\n */\nexport function evaluateContractAgainstRoute(\n contract: CapabilityContract | undefined,\n input: EvaluateContractInput,\n): ContractPreflightResult {\n if (contract === undefined) {\n return { ok: true, reasons: [] };\n }\n const reasons: RouteRejectReason[] = [];\n\n // BUDGET — CONTRACT-04 + COST-03\n if (contract.budget?.maxCostUsd !== undefined) {\n const estimatedCost = estimateRouteCost({\n capability: input.capability,\n estimatedInputTokens: input.estimatedInputTokens,\n estimatedOutputTokens: input.estimatedOutputTokens,\n });\n if (estimatedCost === null) {\n reasons.push({\n code: \"contract-budget-exceeded\",\n message: `${input.capability.modelId} pricing unknown; contract budget declared (maxCostUsd=${contract.budget.maxCostUsd}).`,\n });\n } else if (estimatedCost > contract.budget.maxCostUsd) {\n reasons.push({\n code: \"contract-budget-exceeded\",\n message: `${input.capability.modelId} estimated ${estimatedCost.toFixed(6)} exceeds contract budget ${contract.budget.maxCostUsd}.`,\n });\n }\n }\n\n // MODALITY — CONTRACT-06 (contract-modality-missing)\n if (contract.requiredModalities !== undefined) {\n for (const modality of contract.requiredModalities) {\n if (\n !input.capability.inputModalities.includes(modality) &&\n !input.capability.outputModalities.includes(modality)\n ) {\n reasons.push({\n code: \"contract-modality-missing\",\n message: `${input.capability.modelId} does not support required modality ${modality}.`,\n });\n }\n }\n }\n\n // PRIVACY — CONTRACT-06 (contract-privacy-mismatch)\n if (contract.requiredPrivacy !== undefined) {\n if (!input.capability.dataPolicy.privacy.includes(contract.requiredPrivacy)) {\n reasons.push({\n code: \"contract-privacy-mismatch\",\n message: `${input.capability.modelId} does not satisfy contract privacy ${contract.requiredPrivacy}.`,\n });\n }\n }\n\n // QUALITY FLOOR — declared but NOT enforced on the capability side in Phase 7.\n // CONTEXT.md: \"qualityFloor is parsed and forwarded into the pre-flight\n // evaluator but only enforced by Phase 12's lattice eval\".\n // The reject code \"contract-quality-floor\" stays reserved for Phase 12.\n\n return { ok: reasons.length === 0, reasons };\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nimport type {\n FieldFromTableInvariant,\n InvariantDeclaration,\n MatchesInvariant,\n MustCiteInvariant,\n NoPiiInvariant,\n} from \"./invariants.js\";\nimport { defaultPiiDetectors, type PiiDetector } from \"./pii-detectors.js\";\n\n/**\n * Evidence emitted when a tripwire invariant fires.\n *\n * `observed` is the SHAPE-MATCHED redacted payload, not the raw output:\n * - for `must-cite`: the citations array as found at the located path\n * - for `field-from-table`: the actual value at `path`\n * - for `no-pii`: ONLY `{ detector, substring }` — never the full input\n * (T-08-01 in the 08-01-PLAN threat register)\n * - for `matches`: the value at `path`\n *\n * Phase 9 receipts will sign this evidence, so leaking the full PII into\n * `observed` would defeat redact-before-sign.\n */\nexport interface TripwireEvidence {\n readonly invariantId: string;\n readonly kind: \"must-cite\" | \"field-from-table\" | \"no-pii\" | \"matches\";\n readonly path: string;\n readonly observed: unknown;\n readonly message: string;\n}\n\nexport type TripwireResult =\n | { readonly ok: true }\n | { readonly ok: false; readonly evidence: TripwireEvidence };\n\n/**\n * Pure tripwire evaluator.\n *\n * No I/O, no Date.now, no random — same `(output, invariants)` always\n * returns the same `TripwireResult`. Phase 9 receipts can reconstruct the\n * verdict deterministically (T-08-04).\n *\n * Evaluates invariants in declaration order; the FIRST failing invariant\n * aborts and returns its evidence. Subsequent invariants are not evaluated.\n *\n * @param output The provider output to inspect.\n * @param invariants Invariants to evaluate, in declaration order.\n * @param detectors PII detectors used for `no-pii` invariants. Defaults\n * to `defaultPiiDetectors`. Callers can pass a custom\n * list to override.\n */\nexport async function evaluateTripwires(\n output: unknown,\n invariants: readonly InvariantDeclaration[],\n detectors: readonly PiiDetector[] = defaultPiiDetectors,\n): Promise<TripwireResult> {\n for (const declaration of invariants) {\n const result = await evaluateOne(output, declaration, detectors);\n if (!result.ok) return result;\n }\n return { ok: true };\n}\n\nasync function evaluateOne(\n output: unknown,\n declaration: InvariantDeclaration,\n detectors: readonly PiiDetector[],\n): Promise<TripwireResult> {\n switch (declaration.kind) {\n case \"must-cite\":\n return evaluateMustCite(output, declaration);\n case \"field-from-table\":\n return evaluateFieldFromTable(output, declaration);\n case \"no-pii\":\n return evaluateNoPii(output, declaration, detectors);\n case \"matches\":\n return evaluateMatches(output, declaration);\n default: {\n // Exhaustiveness guard. If a new kind is added without updating this\n // switch, TS will reject the assignment below.\n const _exhaustive: never = declaration;\n throw new Error(`Unknown invariant kind: ${JSON.stringify(_exhaustive)}`);\n }\n }\n}\n\nfunction evaluateMustCite(output: unknown, decl: MustCiteInvariant): TripwireResult {\n const located = locateCitations(output);\n const cites = located?.value ?? [];\n const path = located?.path ?? \"citations\";\n\n const matched = cites.some((entry) => {\n if (typeof entry === \"string\") return entry === decl.artifactName;\n if (typeof entry === \"object\" && entry !== null && \"source\" in entry) {\n return (entry as { source?: unknown }).source === decl.artifactName;\n }\n return false;\n });\n\n if (matched) return { ok: true };\n\n return {\n ok: false,\n evidence: {\n invariantId: decl.id,\n kind: \"must-cite\",\n path,\n observed: cites,\n message: `must-cite: no citation found for \"${decl.artifactName}\".`,\n },\n };\n}\n\n/**\n * Locate the citations payload in `output`. Searches top-level for a\n * `citations` or `evidence` key holding an array. Per 08-CONTEXT.md:\n * \"Path defaults to evidence if the output has a citations field; the\n * runtime locates the citations payload in the output.\"\n *\n * Returns `undefined` when neither field is an array.\n */\nfunction locateCitations(\n output: unknown,\n): { readonly value: readonly unknown[]; readonly path: string } | undefined {\n if (typeof output !== \"object\" || output === null) return undefined;\n const record = output as Record<string, unknown>;\n for (const key of [\"citations\", \"evidence\"] as const) {\n const value = record[key];\n if (Array.isArray(value)) return { value, path: key };\n }\n return undefined;\n}\n\nfunction evaluateFieldFromTable(\n output: unknown,\n decl: FieldFromTableInvariant,\n): TripwireResult {\n const value = resolvePath(output, decl.path);\n if (typeof value === \"string\" && decl.allowedValues.includes(value)) {\n return { ok: true };\n }\n return {\n ok: false,\n evidence: {\n invariantId: decl.id,\n kind: \"field-from-table\",\n path: decl.path,\n observed: value,\n message: `field-from-table: value at \"${decl.path}\" not in allowedValues.`,\n },\n };\n}\n\nfunction evaluateNoPii(\n output: unknown,\n decl: NoPiiInvariant,\n detectors: readonly PiiDetector[],\n): TripwireResult {\n const value = resolvePath(output, decl.path);\n if (typeof value !== \"string\") return { ok: true };\n\n for (const detector of detectors) {\n const result = detector.detect(value);\n if (result.matched) {\n return {\n ok: false,\n evidence: {\n invariantId: decl.id,\n kind: \"no-pii\",\n path: decl.path,\n // CRITICAL: redacted — only the detector name and the matched\n // substring, never the full input string (T-08-01).\n observed: { detector: detector.name, substring: result.substring },\n message: `no-pii: detector \"${detector.name}\" flagged content at \"${decl.path}\".`,\n },\n };\n }\n }\n return { ok: true };\n}\n\nasync function evaluateMatches(\n output: unknown,\n decl: MatchesInvariant,\n): Promise<TripwireResult> {\n const value = resolvePath(output, decl.path);\n const validateResult = decl.schema[\"~standard\"].validate(value);\n const validation: StandardSchemaV1.Result<unknown> =\n validateResult instanceof Promise ? await validateResult : validateResult;\n\n if (\"issues\" in validation && validation.issues !== undefined) {\n const firstIssue = validation.issues[0];\n return {\n ok: false,\n evidence: {\n invariantId: decl.id,\n kind: \"matches\",\n path: decl.path,\n observed: value,\n message: firstIssue?.message ?? `matches: schema validation failed at \"${decl.path}\".`,\n },\n };\n }\n return { ok: true };\n}\n\n/**\n * Resolve a dotted/bracketed path expression against a value.\n *\n * Supports three segment forms:\n * - dotted key: `a.b.c`\n * - bracket index: `a[0].b`\n * - wildcard: `a[*].b` (materializes the array of resolutions)\n *\n * Returns `undefined` for missing paths (does not throw).\n *\n * NOTE (T-08-03): `[*]` materializes the array; deeply nested wildcard\n * chains could allocate O(N^k). Accepted for v1.1 — provider responses\n * are bounded by output token caps.\n */\nfunction resolvePath(value: unknown, path: string): unknown {\n if (path === \"\") return value;\n const tokens = tokenize(path);\n return walk(value, tokens, 0);\n}\n\ntype Token =\n | { readonly type: \"key\"; readonly name: string }\n | { readonly type: \"index\"; readonly index: number }\n | { readonly type: \"wildcard\" };\n\nfunction tokenize(path: string): readonly Token[] {\n const tokens: Token[] = [];\n let i = 0;\n let buffer = \"\";\n const flushKey = (): void => {\n if (buffer.length > 0) {\n tokens.push({ type: \"key\", name: buffer });\n buffer = \"\";\n }\n };\n while (i < path.length) {\n const ch = path[i];\n if (ch === \".\") {\n flushKey();\n i += 1;\n continue;\n }\n if (ch === \"[\") {\n flushKey();\n const end = path.indexOf(\"]\", i + 1);\n if (end === -1) {\n // Malformed path — treat the rest as a literal key so we degrade\n // to `undefined` rather than throw on user input.\n buffer = path.slice(i);\n i = path.length;\n continue;\n }\n const inner = path.slice(i + 1, end);\n if (inner === \"*\") {\n tokens.push({ type: \"wildcard\" });\n } else {\n const idx = Number(inner);\n if (Number.isInteger(idx) && idx >= 0) {\n tokens.push({ type: \"index\", index: idx });\n } else {\n // Non-numeric bracket content — treat as a key (e.g. `a[b]` →\n // unusual but plausible).\n tokens.push({ type: \"key\", name: inner });\n }\n }\n i = end + 1;\n continue;\n }\n buffer += ch;\n i += 1;\n }\n flushKey();\n return tokens;\n}\n\nfunction walk(value: unknown, tokens: readonly Token[], cursor: number): unknown {\n if (cursor >= tokens.length) return value;\n if (value === undefined || value === null) return undefined;\n const token = tokens[cursor]!;\n if (token.type === \"key\") {\n if (typeof value !== \"object\") return undefined;\n const next = (value as Record<string, unknown>)[token.name];\n return walk(next, tokens, cursor + 1);\n }\n if (token.type === \"index\") {\n if (!Array.isArray(value)) return undefined;\n return walk(value[token.index], tokens, cursor + 1);\n }\n // wildcard\n if (!Array.isArray(value)) return undefined;\n return value.map((entry) => walk(entry, tokens, cursor + 1));\n}\n\n/**\n * Test-only export: lets unit tests exercise the path resolver directly.\n * Not part of the public surface; lives behind a `__` prefix to discourage\n * runtime use.\n */\nexport function __resolvePathForTests(value: unknown, path: string): unknown {\n return resolvePath(value, path);\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nimport type { ArtifactKind } from \"../artifacts/artifact.js\";\n\nexport type TextOutputContract = \"text\";\n\nexport interface CitationRef {\n readonly artifactId: string;\n readonly label?: string;\n readonly span?: {\n readonly start?: number;\n readonly end?: number;\n };\n readonly metadata?: Record<string, unknown>;\n}\n\nexport interface CitationsOutputContract {\n readonly kind: \"citations\";\n}\n\nexport interface ArtifactRefsOutputContract {\n readonly kind: \"artifacts\";\n readonly artifactKind?: ArtifactKind | string;\n}\n\nexport type SchemaOutputContract = StandardSchemaV1;\n\nexport type OutputContract =\n | TextOutputContract\n | SchemaOutputContract\n | CitationsOutputContract\n | ArtifactRefsOutputContract;\n\nexport type OutputContractMap = Record<string, OutputContract>;\n\nexport const output = {\n citations(): CitationsOutputContract {\n return { kind: \"citations\" };\n },\n\n artifacts(options: {\n readonly artifactKind?: ArtifactKind | string;\n } = {}): ArtifactRefsOutputContract {\n return { kind: \"artifacts\", ...options };\n },\n};\n","import type { KeyEntry, KeySet } from \"./types.js\";\n\n/**\n * In-memory KeySet factory.\n *\n * Verification flow (plan 09-03):\n * - keySet.lookup(kid) returns undefined → VerifyError {kind: \"key-not-found\"}\n * - entry.state === \"revoked\" → VerifyError {kind: \"key-revoked\"}\n * - entry.state === \"retired\" → VerifyOk + keyState: \"retired\" (caller may warn)\n * - entry.state === \"active\" → VerifyOk + keyState: \"active\"\n *\n * Duplicate kids: last write wins (deterministic — callers control entry order).\n * Empty entries array is legal — every lookup returns undefined.\n * Returned KeySet exposes only `lookup` — no enumeration.\n *\n * See 09-CONTEXT.md \"Key Management (UNRETROFITTABLE)\".\n */\nexport function createMemoryKeySet(entries: readonly KeyEntry[]): KeySet {\n const byKid = new Map<string, KeyEntry>();\n for (const entry of entries) {\n byKid.set(entry.kid, entry);\n }\n return {\n lookup(kid: string): KeyEntry | undefined {\n return byKid.get(kid);\n },\n };\n}\n","/**\n * WebCrypto Ed25519 wrappers + in-memory signer factory.\n *\n * 09-CONTEXT.md (UNRETROFITTABLE):\n * - Algorithm name is the LITERAL string \"Ed25519\" (no params object needed\n * for sign/verify; Node 24 subtle accepts both forms).\n * - ReceiptSigner returns 64-byte Ed25519 signatures.\n * - The runtime accepts a signer reference, NEVER raw private keys.\n * - Production users plug their own signer (KMS adapter / OS keyring).\n * createInMemorySigner is the in-process default for tests and dev.\n *\n * Reconciled in plan 09-03 to import ReceiptSigner from ./types.js (plan 09-01\n * owns the spine). `ReceiptSigner_Local` retained as a deprecated alias for\n * backward compatibility with Wave 1 sibling imports.\n */\n\nimport type { ReceiptSigner } from \"./types.js\";\n\n/**\n * @deprecated Use ReceiptSigner from \"./types.js\". Retained as an alias\n * during the Wave 1 -> Wave 2 reconciliation.\n */\nexport type ReceiptSigner_Local = ReceiptSigner;\n\nconst ALG = \"Ed25519\" as const;\n\n/**\n * Copy a Uint8Array into a fresh ArrayBuffer. WebCrypto's BufferSource type\n * (under exactOptionalPropertyTypes + strict TS) rejects `Uint8Array<ArrayBufferLike>`\n * because the underlying buffer could be a SharedArrayBuffer. Matches the\n * pattern used in storage/fingerprint.ts.\n */\nfunction toArrayBuffer(bytes: Uint8Array): ArrayBuffer {\n const copy = new Uint8Array(bytes.byteLength);\n copy.set(bytes);\n return copy.buffer as ArrayBuffer;\n}\n\nexport async function importEd25519PrivateKey(\n jwk: JsonWebKey,\n): Promise<CryptoKey> {\n return crypto.subtle.importKey(\"jwk\", jwk, ALG, true, [\"sign\"]);\n}\n\nexport async function importEd25519PublicKey(\n jwk: JsonWebKey,\n): Promise<CryptoKey> {\n return crypto.subtle.importKey(\"jwk\", jwk, ALG, true, [\"verify\"]);\n}\n\nexport interface GeneratedEd25519KeyPair {\n readonly privateKeyJwk: JsonWebKey;\n readonly publicKeyJwk: JsonWebKey;\n}\n\nexport async function generateEd25519KeyPairJwk(): Promise<GeneratedEd25519KeyPair> {\n const pair = (await crypto.subtle.generateKey(ALG, true, [\n \"sign\",\n \"verify\",\n ])) as CryptoKeyPair;\n const [privateKeyJwk, publicKeyJwk] = await Promise.all([\n crypto.subtle.exportKey(\"jwk\", pair.privateKey),\n crypto.subtle.exportKey(\"jwk\", pair.publicKey),\n ]);\n return { privateKeyJwk, publicKeyJwk };\n}\n\nexport async function verifyEd25519Signature(\n publicKeyJwk: JsonWebKey,\n message: Uint8Array,\n signature: Uint8Array,\n): Promise<boolean> {\n let key: CryptoKey;\n try {\n key = await importEd25519PublicKey(publicKeyJwk);\n } catch {\n return false;\n }\n try {\n return await crypto.subtle.verify(\n ALG,\n key,\n toArrayBuffer(signature),\n toArrayBuffer(message),\n );\n } catch {\n // Malformed signature length or other subtle error — treat as invalid.\n return false;\n }\n}\n\nexport function createInMemorySigner(\n privateKeyJwk: JsonWebKey,\n options: { readonly kid: string; readonly publicKeyJwk: JsonWebKey },\n): ReceiptSigner {\n // Lazily import the key on first sign() — keeps the factory synchronous\n // and avoids touching crypto.subtle during module load.\n let cachedKey: CryptoKey | undefined;\n const ensureKey = async (): Promise<CryptoKey> => {\n if (cachedKey === undefined) {\n cachedKey = await importEd25519PrivateKey(privateKeyJwk);\n }\n return cachedKey;\n };\n return {\n kid: options.kid,\n publicKeyJwk: options.publicKeyJwk,\n async sign(bytes: Uint8Array): Promise<Uint8Array> {\n const key = await ensureKey();\n const sig = await crypto.subtle.sign(ALG, key, toArrayBuffer(bytes));\n return new Uint8Array(sig);\n },\n };\n}\n","import { canonicalizeReceiptBody } from \"./canonical.js\";\nimport {\n PAYLOAD_TYPE,\n base64Encode,\n buildPae,\n decodeEnvelope,\n} from \"./envelope.js\";\nimport { verifyEd25519Signature } from \"./sign.js\";\nimport type {\n CapabilityReceiptBody,\n KeyEntry,\n KeySet,\n ReceiptEnvelope,\n VerifyError,\n VerifyResult,\n} from \"./types.js\";\n\nfunction fail(kind: VerifyError[\"kind\"], message: string): VerifyResult {\n return { ok: false, error: { kind, message } };\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.byteLength !== b.byteLength) return false;\n for (let i = 0; i < a.byteLength; i += 1) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\n/**\n * Receipt body shape check. We trust the JSON parse — but we re-validate\n * that the required fields exist with the right primitive types before\n * canonicalizing again. Anything off -> version-mismatch (the body is\n * structurally NOT a v1 receipt, even if it parses as JSON).\n */\nfunction asReceiptBody(value: unknown): CapabilityReceiptBody | undefined {\n if (typeof value !== \"object\" || value === null) return undefined;\n const v = value as Record<string, unknown>;\n // CRYPTO-01: accept undefined / v1 / v1.1 / v1.2 so too-low versions all\n // reach Step 4 (the schema-version-too-low chokepoint). An unknown\n // non-undefined literal (e.g. lattice-receipt/v2 or \"garbage\") is still a\n // structural shape failure and falls through to the version-mismatch path.\n if (\n v.version !== undefined &&\n v.version !== \"lattice-receipt/v1\" &&\n v.version !== \"lattice-receipt/v1.1\" &&\n v.version !== \"lattice-receipt/v1.2\"\n ) {\n return undefined;\n }\n if (typeof v.receiptId !== \"string\") return undefined;\n if (typeof v.runId !== \"string\") return undefined;\n if (typeof v.issuedAt !== \"string\") return undefined;\n if (typeof v.kid !== \"string\") return undefined;\n if (typeof v.model !== \"object\" || v.model === null) return undefined;\n if (typeof v.route !== \"object\" || v.route === null) return undefined;\n if (typeof v.usage !== \"object\" || v.usage === null) return undefined;\n if (typeof v.contractVerdict !== \"string\") return undefined;\n if (!Array.isArray(v.inputHashes)) return undefined;\n if (typeof v.redactionPolicyId !== \"string\") return undefined;\n if (!Array.isArray(v.redactions)) return undefined;\n return v as unknown as CapabilityReceiptBody;\n}\n\n/**\n * Pure receipt verifier.\n *\n * Returns a typed VerifyResult — never throws across the verification\n * boundary (PITFALLS.md security: \"Verifier panics on malformed receipts\n * -> DoS via crafted input\"). All parsing failures become typed errors.\n *\n * Decision tree (first match wins):\n * 1. decodeEnvelope throws OR signatures[] empty -> envelope-malformed\n * 2. payload bytes are not valid JSON -> envelope-malformed\n * 3. body shape check fails OR version unknown literal -> version-mismatch\n * 4. body.version === undefined OR \"lattice-receipt/v1\"-> schema-version-too-low (CRYPTO-01)\n * 5. keySet.lookup(keyid) === undefined -> key-not-found\n * 6. entry.state === \"revoked\" -> key-revoked\n * 7. re-canonicalized body != signed payloadBytes -> canonicalization-mismatch\n * 8. Ed25519 verification of PAE fails -> signature-invalid\n * 9. body.kid !== entry.kid (defense in depth) -> signature-invalid\n * 10. otherwise -> ok + keyState\n */\nexport async function verifyReceipt(\n envelope: ReceiptEnvelope,\n keySet: KeySet,\n): Promise<VerifyResult> {\n // Step 1: decode envelope (catches wrong payloadType, base64 errors).\n let decoded;\n try {\n decoded = decodeEnvelope(envelope);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(\"envelope-malformed\", message);\n }\n if (decoded.signatures.length === 0) {\n return fail(\"envelope-malformed\", \"envelope has no signatures\");\n }\n\n // Step 2: parse the canonical payload.\n let parsed: unknown;\n try {\n parsed = JSON.parse(new TextDecoder().decode(decoded.payloadBytes));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(\"envelope-malformed\", `payload is not valid JSON: ${message}`);\n }\n\n // Step 3: structural body check + version check.\n const body = asReceiptBody(parsed);\n if (body === undefined) {\n return fail(\n \"version-mismatch\",\n \"receipt body is not a lattice-receipt/v1.1 or lattice-receipt/v1.2 shape\",\n );\n }\n\n // Step 4: receipt-downgrade defense (CRYPTO-01).\n // Reject receipts whose body.version is absent or equals the v1 literal.\n // v1 receipts predate the v1.1 step-marker integrity surface and the v1.2\n // modelClass audit tag; an attacker holding a valid signing key could mint a\n // v1-shaped body and submit it to bypass newer schema commitments.\n // Short-circuits before any cryptographic work (keyset lookup, canonical\n // re-check, signature verify) so the downgrade verdict is unambiguous.\n // See SECURITY.md (Phase 26 threat model) and Radicle 2026-03 precedent.\n if (body.version === undefined || body.version === \"lattice-receipt/v1\") {\n return fail(\n \"schema-version-too-low\",\n \"Receipt body.version must be 'lattice-receipt/v1.1' or 'lattice-receipt/v1.2' — v1 receipts are not accepted (CRYPTO-01).\",\n );\n }\n\n // Step 5: keyset lookup (use first signature; multi-sig deferred to a future schema).\n const firstSig = decoded.signatures[0]!;\n const entry: KeyEntry | undefined = keySet.lookup(firstSig.keyid);\n if (entry === undefined) {\n return fail(\n \"key-not-found\",\n `keySet has no entry for kid \"${firstSig.keyid}\"`,\n );\n }\n if (entry.state === \"revoked\") {\n return fail(\"key-revoked\", `key \"${entry.kid}\" is revoked`);\n }\n\n // Step 6: re-canonicalize body and compare byte-for-byte against\n // decoded.payloadBytes. Catches any swap of canonical form mid-flight\n // (the signed bytes must canonicalize back to themselves).\n const reCanonical = canonicalizeReceiptBody(body);\n if (!bytesEqual(reCanonical, decoded.payloadBytes)) {\n return fail(\n \"canonicalization-mismatch\",\n \"re-canonicalized body does not match signed payload bytes\",\n );\n }\n\n // Step 7: rebuild PAE and verify Ed25519 signature.\n const payloadB64 = base64Encode(decoded.payloadBytes);\n const pae = buildPae(PAYLOAD_TYPE, payloadB64);\n const sigValid = await verifyEd25519Signature(\n entry.publicKeyJwk,\n pae,\n firstSig.sig,\n );\n if (!sigValid) {\n return fail(\"signature-invalid\", \"Ed25519 signature does not verify\");\n }\n\n // Step 8: defense-in-depth — body.kid MUST equal envelope keyid.\n if (body.kid !== entry.kid) {\n return fail(\n \"signature-invalid\",\n `body.kid \"${body.kid}\" does not match envelope keyid \"${entry.kid}\"`,\n );\n }\n\n // Step 9: success — surface the key state so callers can warn on retired.\n return { ok: true, body, keyState: entry.state };\n}\n","import type { TripwireEvidence } from \"../contract/tripwire.js\";\nimport type { RouteRejectReason } from \"../plan/plan.js\";\n\nexport interface ValidationIssue {\n readonly message: string;\n readonly path?: readonly (string | number | symbol)[];\n}\n\nexport interface ValidationError {\n readonly kind: \"validation\";\n readonly message: string;\n readonly output?: string;\n readonly issues: readonly ValidationIssue[];\n}\n\nexport interface ExecutionUnavailableError {\n readonly kind: \"execution_unavailable\";\n readonly message: string;\n}\n\nexport interface NoRouteError {\n readonly kind: \"no_route\";\n readonly message: string;\n readonly reasons: readonly string[];\n}\n\nexport interface ProviderExecutionError {\n readonly kind: \"provider_execution\";\n readonly message: string;\n readonly providerId?: string;\n readonly modelId?: string;\n}\n\nexport interface TimeoutError {\n readonly kind: \"timeout\";\n readonly message: string;\n}\n\n/**\n * Phase 7 addition: emitted by the runtime when no candidate route can\n * satisfy the caller-supplied `CapabilityContract` (budget, modality,\n * privacy, or quality-floor invariants).\n *\n * `noRouteReasons` carries the full deterministic-router rejection list\n * so callers can inspect per-candidate detail. Phase 9 (receipts) will\n * persist this array for deterministic verdict reconstruction.\n */\nexport interface NoContractMatchError {\n readonly kind: \"no-contract-match\";\n readonly message: string;\n readonly noRouteReasons: readonly RouteRejectReason[];\n}\n\n/**\n * Phase 8 addition: emitted when a `CapabilityContract.invariants` tripwire\n * fires after the provider returned a schema-valid output. Carries the\n * `TripwireEvidence` produced by `evaluateTripwires`.\n *\n * `terminal: true` is a structural marker — combined with the `isTerminal()`\n * predicate it tells the fallback chain in `runWithConfig` to refuse retry.\n * `NoContractMatchError` does NOT carry the field (to avoid breaking Phase 7\n * callers) but `isTerminal()` still returns true for it via the kind check.\n */\nexport interface TripwireViolationError {\n readonly kind: \"tripwire-violated\";\n readonly message: string;\n readonly invariantId: string;\n readonly evidence: TripwireEvidence;\n readonly terminal: true;\n}\n\nexport type LatticeRunError =\n | ValidationError\n | ExecutionUnavailableError\n | NoRouteError\n | ProviderExecutionError\n | TimeoutError\n | NoContractMatchError\n | TripwireViolationError;\n\n/**\n * Returns `true` for run errors that MUST NOT be retried by the fallback\n * chain. Phase 8 covers two kinds:\n *\n * - `tripwire-violated` — the contract's invariants rejected the output;\n * a different provider will not change the verdict, so retry burns\n * budget for no gain (T-08-06 in 08-02-PLAN threat register).\n * - `no-contract-match` — no route satisfies the contract at all; the\n * run never executed and no retry will help.\n *\n * All other error kinds return `false` and remain eligible for fallback.\n * The predicate is exported so Phase 12's eval gate and any user-side\n * retry wrappers can share one source of truth.\n */\nexport function isTerminal(error: LatticeRunError): boolean {\n return error.kind === \"tripwire-violated\" || error.kind === \"no-contract-match\";\n}\n","// Phase 33 — D-05 / D-06 / D-12 / D-13 / D-14 — Public capability profile types.\n// CAPS-01 surface.\n//\n// `ModelCapabilityProfile` is a sibling to `ModelCapability` (in\n// `../providers/provider.ts`), not a replacement. `ModelCapability` tracks\n// modality + cost + tool-use + streaming on the router-facing capability\n// catalog. `ModelCapabilityProfile` tracks training lineage, reasoning\n// surface, tool-call surface, known failure modes, and recommended prompt\n// strategy on the consumer-facing capability registry. Both surfaces are\n// queried at run construction time but answer orthogonal questions.\n\n/**\n * Closed enum of the 7 Lattice transport adapters (D-06). Adding a new\n * adapter is a typed breaking change. Phase 34 quirk dispatch reads this\n * field.\n */\nexport type CapabilityAdapter =\n | \"openrouter\"\n | \"anthropic\"\n | \"openai\"\n | \"openai-compat\"\n | \"xai\"\n | \"gemini\"\n | \"lm-studio\";\n\n/**\n * Runtime list of the closed `CapabilityAdapter` union. MUST stay in sync with\n * the type above; the test suite asserts membership equivalence so drift fails\n * CI. Used by `isCapabilityAdapter` (below) and Phase 34 `negotiateCapabilities`\n * to narrow `string` -> `CapabilityAdapter` without an unsafe cast (IN-04).\n */\nexport const CAPABILITY_ADAPTERS: readonly CapabilityAdapter[] = [\n \"openrouter\",\n \"anthropic\",\n \"openai\",\n \"openai-compat\",\n \"xai\",\n \"gemini\",\n \"lm-studio\",\n] as const;\n\n/**\n * Runtime type guard for the closed `CapabilityAdapter` union (IN-04). Returns\n * true iff `id` is one of the 7 first-party adapter identifiers. Consumers passing\n * a third-party adapter id (e.g., `\"openrouter-prod\"` typo) get `false` and the\n * caller can route to the graceful-degradation empty-stub path without performing\n * a registry lookup that would silently miss.\n */\nexport function isCapabilityAdapter(id: string): id is CapabilityAdapter {\n return (CAPABILITY_ADAPTERS as readonly string[]).includes(id);\n}\n\n/**\n * Closed enum of the 5 training-lineage buckets (D-14). Receipt v1.2\n * (Phase 38) carries this value verbatim via the `modelClass` field.\n * Stable across model patches — gpt-4o-2024-05-13 and gpt-4o-2024-08-06\n * share a trainingClass so receipts remain comparable across rebuilds.\n */\nexport type TrainingClass =\n | \"frontier_rlhf\"\n | \"mid_tier_rlhf\"\n | \"open_weight_instruct\"\n | \"open_weight_base\"\n | \"local_quantized\";\n\n/**\n * Closed enum of the 5 recommended prompt-tuning buckets (research open\n * question 2). DISTINCT from `TrainingClass`: `reasoning` is orthogonal\n * to lineage (a frontier RLHF model with hidden_cot routes to the\n * `reasoning` strategy bucket); `local` is the granularity boundary\n * for the deployed-locally strategy bucket (vs the `local_quantized`\n * lineage signal). Phase 35 prompt-scaffold dispatch reads this field.\n */\nexport type RecommendedPromptStrategy =\n | \"frontier\"\n | \"mid_tier\"\n | \"open_weight\"\n | \"reasoning\"\n | \"local\";\n\n/**\n * Closed enum of the 7 known model-class output-shape failure modes at\n * v1.3.0 (D-12). Adding a member in v1.4+ is an intentional typed\n * breaking change — Phase 36 sanitizer dispatch enforces exhaustiveness\n * via a `_exhaustive: never` switch (see test-d/capabilities.test-d.ts).\n */\nexport type KnownFailureMode =\n | \"internal_envelope_leak\"\n | \"reasoning_tag_leak\"\n | \"system_prompt_echo\"\n | \"template_artifact_leak\"\n | \"hallucinated_tool_name\"\n | \"malformed_tool_arguments\"\n | \"premature_termination\";\n\n/**\n * Closed enum of the 5 reasoning-surface shapes a model exposes. Drives\n * the Phase 36 sanitizer's choice of leak-cleanup pass (e.g., `<think>`\n * tag stripping for `inlined_tags`).\n */\nexport type ReasoningSurface =\n | \"none\"\n | \"hidden_cot\"\n | \"inlined_tags\"\n | \"interleaved_thinking\"\n | \"streamed_reasoning\";\n\n/**\n * Closed enum of the 5 tool-call surface shapes a model exposes. Drives\n * the Phase 37 tool-call validator's choice of arguments parser.\n */\nexport type ToolCallSurface =\n | \"none\"\n | \"native_strict\"\n | \"native_lenient\"\n | \"json_only\"\n | \"text_only\";\n\n/**\n * Phase 33 — D-05 / D-08 — Capability profile for one (adapter, model)\n * pair. Sibling to `ModelCapability`, not a replacement. Built-time baked\n * via the OpenRouter snapshot generator (Phase 33-03) plus hand-edited\n * supplemental static profiles (Phase 33-04).\n *\n * Canonical key: `${adapter}:${modelId}` — one profile per (adapter,\n * model) pair. `openrouter:openai/gpt-oss-120b` and `openai:gpt-oss-120b`\n * are two distinct entries with the same `originFamily: \"openai\"`.\n */\nexport interface ModelCapabilityProfile {\n /**\n * The model identifier as the adapter sees it. For OpenRouter this is\n * the `vendor/model` shape (e.g., `openai/gpt-oss-120b`); for direct\n * adapters this is the provider's native id (e.g., `claude-opus-4`).\n * Combined with `adapter` to form the canonical lookup key `${adapter}:${id}` (D-08).\n */\n readonly id: string;\n /**\n * The Lattice transport adapter that ships this profile (D-05 /\n * D-06). Phase 34 adapter-quirk dispatch reads this field. Closed\n * union of 7 values.\n */\n readonly adapter: CapabilityAdapter;\n /**\n * The model creator (D-07). Open extensible string — new orgs emerge\n * frequently and should not break the type. Examples: `openai`,\n * `anthropic`, `meta`, `mistral`, `google`, `xai`, `deepseek`, `qwen`.\n * Phase 35 prompt-scaffold dispatch falls back to\n * `recommendedPromptStrategy` for unknown originFamily values.\n */\n readonly originFamily: string;\n /**\n * Training-lineage classification (D-14). Receipt v1.2 `modelClass`\n * (Phase 38) carries this value verbatim. Drives the failure-mode\n * default set in the classifier.\n */\n readonly trainingClass: TrainingClass;\n /**\n * Shape of the model's reasoning output. Drives the Phase 36\n * sanitizer's reasoning-leak cleanup pass.\n */\n readonly reasoningSurface: ReasoningSurface;\n /**\n * Shape of the model's tool-call output. Drives the Phase 37\n * tool-call validator's arguments parser.\n */\n readonly toolCallSurface: ToolCallSurface;\n /**\n * The actual context window the adapter will accept on a request, in\n * tokens. For OpenRouter this is `top_provider.context_length ?? context_length`\n * (Phase 33 Pitfall 2) — what OpenRouter routing actually offers, not\n * the model card's aspirational maximum.\n */\n readonly contextWindow: number;\n /**\n * Failure modes this model class is known to exhibit (D-14). Class-\n * derived defaults plus per-family overrides. Phase 36 sanitizer\n * dispatch exhaustively switches on each entry.\n */\n readonly knownFailureModes: readonly KnownFailureMode[];\n /**\n * Recommended prompt-tuning bucket (research open question 2). Phase\n * 35 prompt-scaffold dispatch reads this field. Distinct from\n * `trainingClass` — see `RecommendedPromptStrategy` JSDoc.\n */\n readonly recommendedPromptStrategy: RecommendedPromptStrategy;\n}\n\n/**\n * Frozen list of every `KnownFailureMode` member. Useful for exhaustive\n * iteration in downstream tests and Phase 36 sanitizer registration.\n * Adding a new mode requires updating this array AND the\n * `KnownFailureMode` union AND the Phase 36 exhaustive switch — the\n * `satisfies` clause enforces array-vs-union parity at compile time.\n */\nexport const ALL_KNOWN_FAILURE_MODES = [\n \"internal_envelope_leak\",\n \"reasoning_tag_leak\",\n \"system_prompt_echo\",\n \"template_artifact_leak\",\n \"hallucinated_tool_name\",\n \"malformed_tool_arguments\",\n \"premature_termination\",\n] as const satisfies readonly KnownFailureMode[];\n\n/**\n * Frozen list of every `TrainingClass` member. Useful for exhaustive\n * iteration when constructing the failure-mode defaults table (D-14)\n * and for Phase 38 receipt-class enumeration.\n */\nexport const ALL_TRAINING_CLASSES = [\n \"frontier_rlhf\",\n \"mid_tier_rlhf\",\n \"open_weight_instruct\",\n \"open_weight_base\",\n \"local_quantized\",\n] as const satisfies readonly TrainingClass[];\n","// AUTO-GENERATED FILE — DO NOT EDIT.\n// Source: scripts/refresh-model-registry.mjs\n// Upstream: https://openrouter.ai/api/v1/models\n// Regenerate with: node scripts/refresh-model-registry.mjs\n// CI drift gate: .github/workflows/registry-drift.yml (weekly cron)\nimport type { ModelCapabilityProfile } from \"./profile.js\";\n\nexport const GENERATED_PROFILES = [\n {\n id: \"ai21/jamba-large-1.7\",\n adapter: \"openrouter\",\n originFamily: \"ai21\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 256000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"aion-labs/aion-1.0\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"aion-labs/aion-1.0-mini\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"aion-labs/aion-2.0\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"aion-labs/aion-rp-llama-3.1-8b\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 32768,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"allenai/olmo-3-32b-think\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 65536,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"amazon/nova-2-lite-v1\",\n adapter: \"openrouter\",\n originFamily: \"amazon\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 1000000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"amazon/nova-lite-v1\",\n adapter: \"openrouter\",\n originFamily: \"amazon\",\n trainingClass: \"mid_tier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 300000,\n knownFailureModes: [\"system_prompt_echo\"],\n recommendedPromptStrategy: \"mid_tier\",\n },\n {\n id: \"amazon/nova-micro-v1\",\n adapter: \"openrouter\",\n originFamily: \"amazon\",\n trainingClass: \"mid_tier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 128000,\n knownFailureModes: [\"system_prompt_echo\"],\n recommendedPromptStrategy: \"mid_tier\",\n },\n {\n id: \"amazon/nova-premier-v1\",\n adapter: \"openrouter\",\n originFamily: \"amazon\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 1000000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"amazon/nova-pro-v1\",\n adapter: \"openrouter\",\n originFamily: \"amazon\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 300000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"anthracite-org/magnum-v4-72b\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 16384,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"anthropic/claude-3-haiku\",\n adapter: \"openrouter\",\n originFamily: \"anthropic\",\n trainingClass: \"mid_tier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 200000,\n knownFailureModes: [\"system_prompt_echo\"],\n recommendedPromptStrategy: \"mid_tier\",\n },\n {\n id: \"anthropic/claude-3.5-haiku\",\n adapter: \"openrouter\",\n originFamily: \"anthropic\",\n trainingClass: \"mid_tier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 200000,\n knownFailureModes: [\"system_prompt_echo\"],\n recommendedPromptStrategy: \"mid_tier\",\n },\n {\n id: \"anthropic/claude-fable-5\",\n adapter: \"openrouter\",\n originFamily: \"anthropic\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1000000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"anthropic/claude-haiku-4.5\",\n adapter: \"openrouter\",\n originFamily: \"anthropic\",\n trainingClass: \"mid_tier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 200000,\n knownFailureModes: [\"system_prompt_echo\"],\n recommendedPromptStrategy: \"mid_tier\",\n },\n {\n id: \"anthropic/claude-opus-4\",\n adapter: \"openrouter\",\n originFamily: \"anthropic\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 200000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"anthropic/claude-opus-4.1\",\n adapter: \"openrouter\",\n originFamily: \"anthropic\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 200000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"anthropic/claude-opus-4.5\",\n adapter: \"openrouter\",\n originFamily: \"anthropic\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 200000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"anthropic/claude-opus-4.6\",\n adapter: \"openrouter\",\n originFamily: \"anthropic\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1000000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"anthropic/claude-opus-4.6-fast\",\n adapter: \"openrouter\",\n originFamily: \"anthropic\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1000000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"anthropic/claude-opus-4.7\",\n adapter: \"openrouter\",\n originFamily: \"anthropic\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1000000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"anthropic/claude-opus-4.7-fast\",\n adapter: \"openrouter\",\n originFamily: \"anthropic\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1000000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"anthropic/claude-opus-4.8\",\n adapter: \"openrouter\",\n originFamily: \"anthropic\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1000000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"anthropic/claude-opus-4.8-fast\",\n adapter: \"openrouter\",\n originFamily: \"anthropic\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1000000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"anthropic/claude-sonnet-4\",\n adapter: \"openrouter\",\n originFamily: \"anthropic\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 1000000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"anthropic/claude-sonnet-4.5\",\n adapter: \"openrouter\",\n originFamily: \"anthropic\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1000000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"anthropic/claude-sonnet-4.6\",\n adapter: \"openrouter\",\n originFamily: \"anthropic\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1000000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"arcee-ai/coder-large\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 32768,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"arcee-ai/trinity-large-thinking\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"arcee-ai/trinity-mini\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"arcee-ai/virtuoso-large\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"baidu/ernie-4.5-vl-424b-a47b\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 123000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"bytedance-seed/seed-1.6\",\n adapter: \"openrouter\",\n originFamily: \"bytedance\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"bytedance-seed/seed-1.6-flash\",\n adapter: \"openrouter\",\n originFamily: \"bytedance\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"bytedance-seed/seed-2.0-lite\",\n adapter: \"openrouter\",\n originFamily: \"bytedance\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"bytedance-seed/seed-2.0-mini\",\n adapter: \"openrouter\",\n originFamily: \"bytedance\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"bytedance/ui-tars-1.5-7b\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 128000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"cognitivecomputations/dolphin-mistral-24b-venice-edition:free\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 32768,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"cohere/command-a\",\n adapter: \"openrouter\",\n originFamily: \"cohere\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 256000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"cohere/command-r-08-2024\",\n adapter: \"openrouter\",\n originFamily: \"cohere\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 128000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"cohere/command-r-plus-08-2024\",\n adapter: \"openrouter\",\n originFamily: \"cohere\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 128000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"cohere/command-r7b-12-2024\",\n adapter: \"openrouter\",\n originFamily: \"cohere\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 128000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"deepcogito/cogito-v2.1-671b\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 128000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"deepseek/deepseek-chat\",\n adapter: \"openrouter\",\n originFamily: \"deepseek\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 128000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"deepseek/deepseek-chat-v3-0324\",\n adapter: \"openrouter\",\n originFamily: \"deepseek\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 32768,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"deepseek/deepseek-chat-v3.1\",\n adapter: \"openrouter\",\n originFamily: \"deepseek\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 163840,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"deepseek/deepseek-r1\",\n adapter: \"openrouter\",\n originFamily: \"deepseek\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"inlined_tags\",\n toolCallSurface: \"native_strict\",\n contextWindow: 64000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\", \"reasoning_tag_leak\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"deepseek/deepseek-r1-0528\",\n adapter: \"openrouter\",\n originFamily: \"deepseek\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"inlined_tags\",\n toolCallSurface: \"native_strict\",\n contextWindow: 163840,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\", \"reasoning_tag_leak\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"deepseek/deepseek-r1-distill-llama-70b\",\n adapter: \"openrouter\",\n originFamily: \"deepseek\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"inlined_tags\",\n toolCallSurface: \"none\",\n contextWindow: 8192,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\", \"reasoning_tag_leak\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"deepseek/deepseek-r1-distill-qwen-32b\",\n adapter: \"openrouter\",\n originFamily: \"deepseek\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"inlined_tags\",\n toolCallSurface: \"none\",\n contextWindow: 32768,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\", \"reasoning_tag_leak\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"deepseek/deepseek-v3.1-terminus\",\n adapter: \"openrouter\",\n originFamily: \"deepseek\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 163840,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"deepseek/deepseek-v3.2\",\n adapter: \"openrouter\",\n originFamily: \"deepseek\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 128000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"deepseek/deepseek-v3.2-exp\",\n adapter: \"openrouter\",\n originFamily: \"deepseek\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 163840,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"deepseek/deepseek-v4-flash\",\n adapter: \"openrouter\",\n originFamily: \"deepseek\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1048576,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"deepseek/deepseek-v4-pro\",\n adapter: \"openrouter\",\n originFamily: \"deepseek\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1048576,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"essentialai/rnj-1-instruct\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 32768,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"google/gemini-2.5-flash\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1048576,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/gemini-2.5-flash-image\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 32768,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/gemini-2.5-flash-lite\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1048576,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/gemini-2.5-flash-lite-preview-09-2025\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1048576,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/gemini-2.5-pro\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1048576,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/gemini-2.5-pro-preview\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1048576,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/gemini-2.5-pro-preview-05-06\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1048576,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/gemini-3-flash-preview\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1048576,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/gemini-3-pro-image-preview\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 65536,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/gemini-3.1-flash-image-preview\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 65536,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/gemini-3.1-flash-lite\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1048576,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/gemini-3.1-flash-lite-preview\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1048576,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/gemini-3.1-pro-preview\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1048576,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/gemini-3.1-pro-preview-customtools\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1048576,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/gemini-3.5-flash\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1048576,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/gemma-2-27b-it\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 8192,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/gemma-3-12b-it\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 131072,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/gemma-3-27b-it\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 131072,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/gemma-3-4b-it\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 131072,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/gemma-3n-e4b-it\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 32768,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/gemma-4-26b-a4b-it\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/gemma-4-26b-a4b-it:free\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 262144,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/gemma-4-31b-it\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/gemma-4-31b-it:free\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 262144,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/lyria-3-clip-preview\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 1048576,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"google/lyria-3-pro-preview\",\n adapter: \"openrouter\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 1048576,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"gryphe/mythomax-l2-13b\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 4096,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"ibm-granite/granite-4.0-h-micro\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 131000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"ibm-granite/granite-4.1-8b\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"inception/mercury-2\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 128000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"inclusionai/ling-2.6-1t\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"inclusionai/ling-2.6-flash\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"inclusionai/ring-2.6-1t\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"inflection/inflection-3-pi\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 8000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"inflection/inflection-3-productivity\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 8000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"kwaipilot/kat-coder-pro-v2\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 256000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"liquid/lfm-2-24b-a2b\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 32768,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"liquid/lfm-2.5-1.2b-instruct:free\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 32768,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"liquid/lfm-2.5-1.2b-thinking:free\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 32768,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"mancer/weaver\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 8000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"meta-llama/llama-3-70b-instruct\",\n adapter: \"openrouter\",\n originFamily: \"meta\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 8192,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"meta-llama/llama-3-8b-instruct\",\n adapter: \"openrouter\",\n originFamily: \"meta\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 8192,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"meta-llama/llama-3.1-70b-instruct\",\n adapter: \"openrouter\",\n originFamily: \"meta\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"meta-llama/llama-3.1-8b-instruct\",\n adapter: \"openrouter\",\n originFamily: \"meta\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"meta-llama/llama-3.2-11b-vision-instruct\",\n adapter: \"openrouter\",\n originFamily: \"meta\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"meta-llama/llama-3.2-1b-instruct\",\n adapter: \"openrouter\",\n originFamily: \"meta\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 60000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"meta-llama/llama-3.2-3b-instruct\",\n adapter: \"openrouter\",\n originFamily: \"meta\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 80000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"meta-llama/llama-3.2-3b-instruct:free\",\n adapter: \"openrouter\",\n originFamily: \"meta\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"meta-llama/llama-3.3-70b-instruct\",\n adapter: \"openrouter\",\n originFamily: \"meta\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"meta-llama/llama-3.3-70b-instruct:free\",\n adapter: \"openrouter\",\n originFamily: \"meta\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 65536,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"meta-llama/llama-4-maverick\",\n adapter: \"openrouter\",\n originFamily: \"meta\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1048576,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"meta-llama/llama-4-scout\",\n adapter: \"openrouter\",\n originFamily: \"meta\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 327680,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"meta-llama/llama-guard-3-8b\",\n adapter: \"openrouter\",\n originFamily: \"meta\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"meta-llama/llama-guard-4-12b\",\n adapter: \"openrouter\",\n originFamily: \"meta\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 163840,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"microsoft/phi-4\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 16384,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"microsoft/phi-4-mini-instruct\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 128000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"microsoft/wizardlm-2-8x22b\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 65535,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"minimax/minimax-01\",\n adapter: \"openrouter\",\n originFamily: \"minimax\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 1000192,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"minimax/minimax-m1\",\n adapter: \"openrouter\",\n originFamily: \"minimax\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 1000000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"minimax/minimax-m2\",\n adapter: \"openrouter\",\n originFamily: \"minimax\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 196608,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"minimax/minimax-m2-her\",\n adapter: \"openrouter\",\n originFamily: \"minimax\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 65536,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"minimax/minimax-m2.1\",\n adapter: \"openrouter\",\n originFamily: \"minimax\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 196608,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"minimax/minimax-m2.5\",\n adapter: \"openrouter\",\n originFamily: \"minimax\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 196608,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"minimax/minimax-m2.7\",\n adapter: \"openrouter\",\n originFamily: \"minimax\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 204800,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"minimax/minimax-m3\",\n adapter: \"openrouter\",\n originFamily: \"minimax\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 524288,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"mistralai/codestral-2508\",\n adapter: \"openrouter\",\n originFamily: \"mistral\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 256000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"mistralai/devstral-2512\",\n adapter: \"openrouter\",\n originFamily: \"mistral\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"mistralai/ministral-14b-2512\",\n adapter: \"openrouter\",\n originFamily: \"mistral\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"mistralai/ministral-3b-2512\",\n adapter: \"openrouter\",\n originFamily: \"mistral\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"mistralai/ministral-8b-2512\",\n adapter: \"openrouter\",\n originFamily: \"mistral\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"mistralai/mistral-large\",\n adapter: \"openrouter\",\n originFamily: \"mistral\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 128000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"mistralai/mistral-large-2407\",\n adapter: \"openrouter\",\n originFamily: \"mistral\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"mistralai/mistral-large-2512\",\n adapter: \"openrouter\",\n originFamily: \"mistral\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"mistralai/mistral-medium-3\",\n adapter: \"openrouter\",\n originFamily: \"mistral\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"mistralai/mistral-medium-3-5\",\n adapter: \"openrouter\",\n originFamily: \"mistral\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"mistralai/mistral-medium-3.1\",\n adapter: \"openrouter\",\n originFamily: \"mistral\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"mistralai/mistral-nemo\",\n adapter: \"openrouter\",\n originFamily: \"mistral\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"mistralai/mistral-saba\",\n adapter: \"openrouter\",\n originFamily: \"mistral\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 32768,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"mistralai/mistral-small-24b-instruct-2501\",\n adapter: \"openrouter\",\n originFamily: \"mistral\",\n trainingClass: \"mid_tier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 32768,\n knownFailureModes: [\"system_prompt_echo\"],\n recommendedPromptStrategy: \"mid_tier\",\n },\n {\n id: \"mistralai/mistral-small-2603\",\n adapter: \"openrouter\",\n originFamily: \"mistral\",\n trainingClass: \"mid_tier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"system_prompt_echo\"],\n recommendedPromptStrategy: \"mid_tier\",\n },\n {\n id: \"mistralai/mistral-small-3.1-24b-instruct\",\n adapter: \"openrouter\",\n originFamily: \"mistral\",\n trainingClass: \"mid_tier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 128000,\n knownFailureModes: [\"system_prompt_echo\"],\n recommendedPromptStrategy: \"mid_tier\",\n },\n {\n id: \"mistralai/mistral-small-3.2-24b-instruct\",\n adapter: \"openrouter\",\n originFamily: \"mistral\",\n trainingClass: \"mid_tier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 128000,\n knownFailureModes: [\"system_prompt_echo\"],\n recommendedPromptStrategy: \"mid_tier\",\n },\n {\n id: \"mistralai/mixtral-8x22b-instruct\",\n adapter: \"openrouter\",\n originFamily: \"mistral\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 65536,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"mistralai/voxtral-small-24b-2507\",\n adapter: \"openrouter\",\n originFamily: \"mistral\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 32000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"moonshotai/kimi-k2\",\n adapter: \"openrouter\",\n originFamily: \"moonshot\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"moonshotai/kimi-k2-0905\",\n adapter: \"openrouter\",\n originFamily: \"moonshot\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"moonshotai/kimi-k2-thinking\",\n adapter: \"openrouter\",\n originFamily: \"moonshot\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"moonshotai/kimi-k2.5\",\n adapter: \"openrouter\",\n originFamily: \"moonshot\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"moonshotai/kimi-k2.6\",\n adapter: \"openrouter\",\n originFamily: \"moonshot\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262142,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"morph/morph-v3-fast\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 81920,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"morph/morph-v3-large\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"nex-agi/nex-n2-pro:free\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"nousresearch/hermes-3-llama-3.1-405b\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"nousresearch/hermes-3-llama-3.1-405b:free\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"nousresearch/hermes-3-llama-3.1-70b\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"nousresearch/hermes-4-405b\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"nousresearch/hermes-4-70b\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"nvidia/llama-3.3-nemotron-super-49b-v1.5\",\n adapter: \"openrouter\",\n originFamily: \"nvidia\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"nvidia/nemotron-3-nano-30b-a3b\",\n adapter: \"openrouter\",\n originFamily: \"nvidia\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"nvidia/nemotron-3-nano-30b-a3b:free\",\n adapter: \"openrouter\",\n originFamily: \"nvidia\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 256000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free\",\n adapter: \"openrouter\",\n originFamily: \"nvidia\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 256000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"nvidia/nemotron-3-super-120b-a12b\",\n adapter: \"openrouter\",\n originFamily: \"nvidia\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"nvidia/nemotron-3-super-120b-a12b:free\",\n adapter: \"openrouter\",\n originFamily: \"nvidia\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"nvidia/nemotron-3-ultra-550b-a55b\",\n adapter: \"openrouter\",\n originFamily: \"nvidia\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"nvidia/nemotron-3-ultra-550b-a55b:free\",\n adapter: \"openrouter\",\n originFamily: \"nvidia\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 1000000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"nvidia/nemotron-3.5-content-safety:free\",\n adapter: \"openrouter\",\n originFamily: \"nvidia\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 128000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"nvidia/nemotron-nano-12b-v2-vl:free\",\n adapter: \"openrouter\",\n originFamily: \"nvidia\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 128000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"nvidia/nemotron-nano-9b-v2:free\",\n adapter: \"openrouter\",\n originFamily: \"nvidia\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 128000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"openai/gpt-3.5-turbo\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 16385,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-3.5-turbo-0613\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 4095,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-3.5-turbo-16k\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 16385,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-3.5-turbo-instruct\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 4095,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-4\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 8191,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-4-turbo\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 128000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-4-turbo-preview\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 128000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-4.1\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1047576,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-4.1-mini\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1047576,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-4.1-nano\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1047576,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-4o\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 128000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-4o-2024-05-13\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 128000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-4o-2024-08-06\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 128000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-4o-2024-11-20\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 128000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-4o-mini\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 128000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-4o-mini-2024-07-18\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 128000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-4o-mini-search-preview\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 128000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-4o-search-preview\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 128000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 400000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5-chat\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 128000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5-codex\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 400000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5-image\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 400000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5-image-mini\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 400000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5-mini\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 400000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5-nano\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 400000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5-pro\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 400000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5.1\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 400000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5.1-chat\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 128000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5.1-codex\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 400000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5.1-codex-max\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 400000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5.1-codex-mini\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 400000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5.2\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 400000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5.2-chat\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 128000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5.2-codex\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 400000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5.2-pro\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 400000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5.3-chat\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 128000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5.3-codex\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 400000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5.4\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1050000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5.4-image-2\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 272000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5.4-mini\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 400000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5.4-nano\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 400000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5.4-pro\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1050000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5.5\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1050000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-5.5-pro\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1050000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-audio\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 128000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-audio-mini\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 128000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-chat-latest\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 400000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/gpt-oss-120b\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"openai/gpt-oss-120b:free\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"openai/gpt-oss-20b\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"openai/gpt-oss-20b:free\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"openai/gpt-oss-safeguard-20b\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"openai/o1\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"hidden_cot\",\n toolCallSurface: \"native_strict\",\n contextWindow: 200000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/o1-pro\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"hidden_cot\",\n toolCallSurface: \"none\",\n contextWindow: 200000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/o3\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"hidden_cot\",\n toolCallSurface: \"native_strict\",\n contextWindow: 200000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/o3-deep-research\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"hidden_cot\",\n toolCallSurface: \"native_strict\",\n contextWindow: 200000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/o3-mini\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"hidden_cot\",\n toolCallSurface: \"native_strict\",\n contextWindow: 200000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/o3-mini-high\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"hidden_cot\",\n toolCallSurface: \"native_strict\",\n contextWindow: 200000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/o3-pro\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"hidden_cot\",\n toolCallSurface: \"native_strict\",\n contextWindow: 200000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/o4-mini\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 200000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/o4-mini-deep-research\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 200000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openai/o4-mini-high\",\n adapter: \"openrouter\",\n originFamily: \"openai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 200000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"openrouter/auto\",\n adapter: \"openrouter\",\n originFamily: \"openrouter\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 2000000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"openrouter/bodybuilder\",\n adapter: \"openrouter\",\n originFamily: \"openrouter\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 128000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"openrouter/free\",\n adapter: \"openrouter\",\n originFamily: \"openrouter\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 200000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"openrouter/fusion\",\n adapter: \"openrouter\",\n originFamily: \"openrouter\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 128000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"openrouter/owl-alpha\",\n adapter: \"openrouter\",\n originFamily: \"openrouter\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1048756,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"openrouter/pareto-code\",\n adapter: \"openrouter\",\n originFamily: \"openrouter\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 2000000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"perceptron/perceptron-mk1\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 32768,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"perplexity/sonar\",\n adapter: \"openrouter\",\n originFamily: \"perplexity\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 127072,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"perplexity/sonar-deep-research\",\n adapter: \"openrouter\",\n originFamily: \"perplexity\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 128000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"perplexity/sonar-pro\",\n adapter: \"openrouter\",\n originFamily: \"perplexity\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 200000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"perplexity/sonar-pro-search\",\n adapter: \"openrouter\",\n originFamily: \"perplexity\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 200000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"perplexity/sonar-reasoning-pro\",\n adapter: \"openrouter\",\n originFamily: \"perplexity\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 128000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"poolside/laguna-m.1:free\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"poolside/laguna-xs.2:free\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"prime-intellect/intellect-3\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen-2.5-72b-instruct\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 32768,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen-2.5-7b-instruct\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 32768,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen-2.5-coder-32b-instruct\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 32768,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen-plus\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 1000000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen-plus-2025-07-28\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1000000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen-plus-2025-07-28:thinking\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1000000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen2.5-vl-72b-instruct\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 32000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-14b\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 40960,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-235b-a22b\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-235b-a22b-2507\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-235b-a22b-thinking-2507\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-30b-a3b\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 40960,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-30b-a3b-instruct-2507\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 128000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-30b-a3b-thinking-2507\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-32b\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 40960,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-8b\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 40960,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-coder\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-coder-30b-a3b-instruct\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 160000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-coder-flash\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 1000000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-coder-next\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-coder-plus\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1000000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-coder:free\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 262000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-max\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-max-thinking\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-next-80b-a3b-instruct\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-next-80b-a3b-instruct:free\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-next-80b-a3b-thinking\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-vl-235b-a22b-instruct\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-vl-235b-a22b-thinking\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-vl-30b-a3b-instruct\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-vl-30b-a3b-thinking\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-vl-32b-instruct\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-vl-8b-instruct\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3-vl-8b-thinking\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3.5-122b-a10b\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3.5-27b\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3.5-35b-a3b\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3.5-397b-a17b\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3.5-9b\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3.5-flash-02-23\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1000000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3.5-plus-02-15\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1000000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3.5-plus-20260420\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1000000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3.6-27b\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3.6-35b-a3b\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3.6-flash\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1000000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3.6-max-preview\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3.6-plus\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1000000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3.7-max\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1000000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"qwen/qwen3.7-plus\",\n adapter: \"openrouter\",\n originFamily: \"qwen\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1000000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"rekaai/reka-edge\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 16384,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"rekaai/reka-flash-3\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 65536,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"relace/relace-apply-3\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 256000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"relace/relace-search\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 256000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"sao10k/l3-lunaris-8b\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 8192,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"sao10k/l3.1-70b-hanami-x1\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 16000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"sao10k/l3.1-euryale-70b\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"sao10k/l3.3-euryale-70b\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"stepfun/step-3.5-flash\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"stepfun/step-3.7-flash\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 256000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"switchpoint/router\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"tencent/hunyuan-a13b-instruct\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"tencent/hy3-preview\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"thedrummer/cydonia-24b-v4.1\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"thedrummer/rocinante-12b\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 32768,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"thedrummer/skyfall-36b-v2\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 32768,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"thedrummer/unslopnemo-12b\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 32768,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"undi95/remm-slerp-l2-13b\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 6144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"upstage/solar-pro-3\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 128000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"writer/palmyra-x5\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 1040000,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"x-ai/grok-4.20\",\n adapter: \"openrouter\",\n originFamily: \"xai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 2000000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"x-ai/grok-4.20-multi-agent\",\n adapter: \"openrouter\",\n originFamily: \"xai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 2000000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"x-ai/grok-4.3\",\n adapter: \"openrouter\",\n originFamily: \"xai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1000000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"x-ai/grok-build-0.1\",\n adapter: \"openrouter\",\n originFamily: \"xai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 256000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"xiaomi/mimo-v2-flash\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"xiaomi/mimo-v2.5\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 1048576,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"xiaomi/mimo-v2.5-pro\",\n adapter: \"openrouter\",\n originFamily: \"unknown\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 1048576,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"z-ai/glm-4.5\",\n adapter: \"openrouter\",\n originFamily: \"zai\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"z-ai/glm-4.5-air\",\n adapter: \"openrouter\",\n originFamily: \"zai\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 131070,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"z-ai/glm-4.5v\",\n adapter: \"openrouter\",\n originFamily: \"zai\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 65536,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"z-ai/glm-4.6\",\n adapter: \"openrouter\",\n originFamily: \"zai\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 202752,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"z-ai/glm-4.6v\",\n adapter: \"openrouter\",\n originFamily: \"zai\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 131072,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"z-ai/glm-4.7\",\n adapter: \"openrouter\",\n originFamily: \"zai\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 202752,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"z-ai/glm-4.7-flash\",\n adapter: \"openrouter\",\n originFamily: \"zai\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 202752,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"z-ai/glm-5\",\n adapter: \"openrouter\",\n originFamily: \"zai\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 202752,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"z-ai/glm-5-turbo\",\n adapter: \"openrouter\",\n originFamily: \"zai\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 262144,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n {\n id: \"z-ai/glm-5.1\",\n adapter: \"openrouter\",\n originFamily: \"zai\",\n trainingClass: \"open_weight_instruct\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 202752,\n knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"],\n recommendedPromptStrategy: \"open_weight\",\n },\n] as const satisfies readonly ModelCapabilityProfile[];\n","// Phase 33 — CAPS-05 — Static supplemental profiles.\n//\n// Hand-edited sibling to registry.generated.ts. Profiles for models that\n// OpenRouter does not surface (or that consumers reach through Lattice's\n// direct adapters rather than through OpenRouter routing). The lookup\n// module merges STATIC_PROFILES + GENERATED_PROFILES at Map-build time;\n// direct adapters (anthropic, gemini, xai, lm-studio) win over the\n// openrouter routing equivalent per D-10 ADAPTER_ORDER.\n//\n// Source-file order is alphabetical by canonical key for human review\n// ease. The runtime lookup order is governed by ADAPTER_ORDER in\n// lookup.ts and is INDEPENDENT of source-file order.\n//\n// Rationale (cited in CONTEXT.md <specifics> and PLAN.md):\n// - anthropic:claude-opus-4 — direct Anthropic, frontier_rlhf;\n// contextWindow 200000 matches Anthropic's\n// published max for Opus-class.\n// - gemini:gemini-2.5-pro — direct Gemini, frontier_rlhf;\n// contextWindow 2097152 (2M) matches\n// Google's published 2M-token max for 2.5 Pro.\n// - lm-studio:local-template — generic local-quantized template (A7);\n// contextWindow 8192 is a sensible default;\n// consumers parameterize via their LM Studio\n// configuration if they need a different value.\n// Carries the full FAILURE_MODE_DEFAULTS.local_quantized\n// set per D-14: internal_envelope_leak,\n// system_prompt_echo, template_artifact_leak,\n// malformed_tool_arguments, premature_termination.\n// - xai:grok-4 — direct xAI, frontier_rlhf;\n// contextWindow 131072 matches xAI's\n// published 128K-token max.\n//\n// All 3 frontier profiles have empty knownFailureModes (matches\n// FAILURE_MODE_DEFAULTS.frontier_rlhf which is []).\nimport type { ModelCapabilityProfile } from \"./profile.js\";\n\nexport const STATIC_PROFILES = [\n {\n id: \"claude-opus-4\",\n adapter: \"anthropic\",\n originFamily: \"anthropic\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 200000,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"gemini-2.5-pro\",\n adapter: \"gemini\",\n originFamily: \"google\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_strict\",\n contextWindow: 2097152,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n {\n id: \"local-template\",\n adapter: \"lm-studio\",\n originFamily: \"unknown\",\n trainingClass: \"local_quantized\",\n reasoningSurface: \"none\",\n toolCallSurface: \"none\",\n contextWindow: 8192,\n knownFailureModes: [\n \"internal_envelope_leak\",\n \"system_prompt_echo\",\n \"template_artifact_leak\",\n \"malformed_tool_arguments\",\n \"premature_termination\",\n ],\n recommendedPromptStrategy: \"local\",\n },\n {\n id: \"grok-4\",\n adapter: \"xai\",\n originFamily: \"xai\",\n trainingClass: \"frontier_rlhf\",\n reasoningSurface: \"none\",\n toolCallSurface: \"native_lenient\",\n contextWindow: 131072,\n knownFailureModes: [],\n recommendedPromptStrategy: \"frontier\",\n },\n] as const satisfies readonly ModelCapabilityProfile[];\n","// Phase 33 — D-09 / D-10 / D-11 — Public lookup surface for the model\n// capability registry. CAPS-02 surface.\n//\n// Three exported functions:\n// - getCapabilityProfile(canonicalKey) — strict, exact `${adapter}:${id}` lookup (D-09)\n// - findCapabilityProfile(id) — fuzzy, multi-adapter, OpenRouter suffix-strip (D-10)\n// - stripOpenRouterVariant(id) — pure helper, OpenRouter-shape only (D-11)\n//\n// Phase 34 (quirks) and Phase 36 (sanitizers) reuse stripOpenRouterVariant.\n// The lazy Map cache is built once on first lookup from STATIC + GENERATED\n// arrays and reused across calls; _resetLookupCacheForTests is exported for\n// vitest case isolation but is NOT re-exported from the public surface.\n\nimport type { CapabilityAdapter, ModelCapabilityProfile } from \"./profile.js\";\nimport { GENERATED_PROFILES } from \"./registry.generated.js\";\nimport { STATIC_PROFILES } from \"./registry.static.js\";\n\n/**\n * D-10 adapter order — direct adapters first, OpenRouter last. The\n * `findCapabilityProfile` helper walks this list and concatenates hits in\n * order, so consumers iterating over the result see direct-adapter\n * profiles before the OpenRouter routing equivalent. This makes the\n * \"I have a direct adapter wired AND I have OpenRouter wired\" case\n * deterministic (direct wins; OpenRouter is the fallback).\n */\nconst ADAPTER_ORDER: ReadonlyArray<CapabilityAdapter> = [\n \"anthropic\",\n \"openai\",\n \"gemini\",\n \"xai\",\n \"openai-compat\",\n \"lm-studio\",\n \"openrouter\",\n];\n\n/**\n * D-11 — anchored, bounded OpenRouter variant regex. Matches the live\n * variant set verified against the OpenRouter feed on 2026-06-08:\n * `:free` and `:thinking` only. Linear-time worst case — no nested\n * quantifiers, finite alternation, anchored on both ends (Pitfall 4 +\n * threat T-33-02-02 mitigation).\n *\n * Pattern: `vendor/model:variant` where `vendor` and `model` are each\n * non-empty non-`/` segments. Direct-adapter canonical keys like\n * `anthropic:claude-opus-4` do NOT match (no slash before the colon).\n */\nconst OPENROUTER_VARIANT_RE = /^[^/]+\\/[^/]+:(?:free|thinking)$/;\n\n/**\n * Strip the OpenRouter variant suffix (`:free` or `:thinking`) from an\n * OpenRouter-shaped id (`vendor/model:variant`). Other adapter id shapes\n * pass through verbatim — does not, for example, alter\n * `anthropic:claude-opus-4` (direct-adapter canonical key) or\n * `openai/gpt-4o:beta` (unrecognized variant per Pitfall 4).\n *\n * Exported because Phase 34 (adapter quirks) and Phase 36 (output\n * sanitizers) need the same normalization. Phase 33 D-11 scope.\n */\nexport function stripOpenRouterVariant(id: string): string {\n if (!OPENROUTER_VARIANT_RE.test(id)) return id;\n const colonIdx = id.lastIndexOf(\":\");\n return colonIdx === -1 ? id : id.slice(0, colonIdx);\n}\n\n/**\n * Lazy Map cache. Built once on first call to `getLookupMap`; reused for\n * every subsequent strict or fuzzy lookup. Test-only reset via\n * `_resetLookupCacheForTests` because vitest's `vi.doMock` flow needs to\n * re-import lookup.ts with a fresh cache when the mocked registries\n * change between cases.\n */\nlet _lookupCache: Map<string, ModelCapabilityProfile> | undefined;\n\nfunction getLookupMap(): Map<string, ModelCapabilityProfile> {\n if (_lookupCache !== undefined) return _lookupCache;\n const map = new Map<string, ModelCapabilityProfile>();\n // STATIC first so generated entries with the same canonical key would\n // overwrite. By current design STATIC and GENERATED do not share keys\n // (static profiles use direct adapters; generated entries use the\n // openrouter adapter), but the iteration order documents the\n // precedence in case a future plan introduces overlap.\n //\n // The explicit `readonly ModelCapabilityProfile[]` widening is required\n // because the bootstrap arrays ship as `readonly []` (an empty tuple)\n // via `[] as const satisfies readonly ModelCapabilityProfile[]`. Plan\n // 04 populates them with real rows; the iteration variable type stays\n // `ModelCapabilityProfile` either way.\n const staticProfiles: readonly ModelCapabilityProfile[] = STATIC_PROFILES;\n const generatedProfiles: readonly ModelCapabilityProfile[] = GENERATED_PROFILES;\n for (const profile of staticProfiles) {\n map.set(`${profile.adapter}:${profile.id}`, profile);\n }\n for (const profile of generatedProfiles) {\n map.set(`${profile.adapter}:${profile.id}`, profile);\n }\n _lookupCache = map;\n return map;\n}\n\n/**\n * Test-only escape hatch — reset the lazy Map cache. NOT re-exported\n * from src/index.ts; only reachable by tests importing lookup.ts\n * directly. Vitest `vi.doMock` flow uses `vi.resetModules()` to force\n * re-import; this reset is a belt-and-suspenders for any future test\n * that wants to mutate the underlying arrays in-place.\n */\nexport function _resetLookupCacheForTests(): void {\n _lookupCache = undefined;\n}\n\n/**\n * D-09 strict lookup — return the capability profile for the exact\n * `${adapter}:${modelId}` canonical key. Returns `undefined` if the key\n * is not registered. No fuzzy matching — use `findCapabilityProfile`\n * for that.\n *\n * Examples:\n * getCapabilityProfile(\"openrouter:openai/gpt-oss-120b\") -> profile\n * getCapabilityProfile(\"anthropic:claude-opus-4\") -> profile\n * getCapabilityProfile(\"not-a-real-key\") -> undefined\n *\n * The lookup is case-sensitive on the canonical key. Threat T-33-02-01\n * mitigation: backing store is `Map<string, ModelCapabilityProfile>`,\n * not a plain object literal, so `__proto__` and other prototype-chain\n * keys are safe (Map uses SameValueZero, not property lookup).\n */\nexport function getCapabilityProfile(\n canonicalKey: string,\n): ModelCapabilityProfile | undefined {\n return getLookupMap().get(canonicalKey);\n}\n\n/**\n * D-10 fuzzy lookup — strip the OpenRouter variant suffix (if any) and\n * return ALL matching profiles across every adapter, in deterministic\n * order: direct adapters first (anthropic, openai, gemini, xai,\n * openai-compat, lm-studio), then OpenRouter.\n *\n * Useful for pre-routing capability inspection where the adapter has\n * not yet been chosen — the consumer can iterate the returned list\n * and pick the first compatible one. Returns `[]` when no match is\n * found across any adapter.\n *\n * Suffix-strip is OpenRouter-shape-only per D-11. Direct-adapter ids\n * pass through verbatim:\n * findCapabilityProfile(\"openai/gpt-oss-120b:free\")\n * -> [openrouter:openai/gpt-oss-120b]\n * findCapabilityProfile(\"claude-opus-4\")\n * -> [anthropic:claude-opus-4, ...] (no suffix-strip)\n */\nexport function findCapabilityProfile(id: string): ModelCapabilityProfile[] {\n const stripped = stripOpenRouterVariant(id);\n const map = getLookupMap();\n const matches: ModelCapabilityProfile[] = [];\n for (const adapter of ADAPTER_ORDER) {\n const hit = map.get(`${adapter}:${stripped}`);\n if (hit) matches.push(hit);\n }\n return matches;\n}\n","// Phase 34 — D-13 / D-14 / D-15 / D-16 — Sanitizer dispatch keys and\n// failure-mode recommendation table. QUIRK-01 / NEG-02 surface.\n//\n// Phase 36 ships the IMPLEMENTATIONS registered under the SanitizerKey ids\n// defined here. This module is purely the dispatch key type + recommendation\n// derivation table + helper.\n\nimport type { KnownFailureMode } from \"./profile.js\";\n\n/**\n * D-13 — Phase 36 sanitizer registration keys. Closed string-literal union;\n * adding a 4th sanitizer in v1.4 is an intentional typed breaking change\n * that mirrors the `KnownFailureMode` discipline.\n *\n * Phase 36 registers implementations under EXACTLY these 3 ids:\n * - \"stripReasoningTags\" — strips <think>/</think> (and model-specific) reasoning tags\n * - \"stripChatTemplateArtifacts\" — removes chat-template artifact leaks from output\n * - \"unwrapInternalEnvelope\" — extracts the user-visible payload from internal wrapper\n */\nexport type SanitizerKey =\n | \"stripReasoningTags\"\n | \"stripChatTemplateArtifacts\"\n | \"unwrapInternalEnvelope\";\n\n/**\n * D-14 + D-16 — Exhaustive mapping from KnownFailureMode to SanitizerKey\n * (or null when the failure mode is not a sanitizer concern). The\n * `Record<KnownFailureMode, ...>` annotation enforces compile-time\n * exhaustiveness — adding a new mode to KnownFailureMode in v1.4+ will\n * cause a type-check failure here until the planner decides on a mapping.\n *\n * Null semantics per D-16:\n * - system_prompt_echo -> null (consumer-side prompt engineering, not a sanitizer)\n * - hallucinated_tool_name -> null (Phase 37 tool-call validator territory)\n * - malformed_tool_arguments -> null (Phase 37 tool-call validator territory)\n * - premature_termination -> null (consumer-side max_tokens config)\n */\nexport const SANITIZER_BY_FAILURE_MODE: Record<KnownFailureMode, SanitizerKey | null> = {\n internal_envelope_leak: \"unwrapInternalEnvelope\",\n reasoning_tag_leak: \"stripReasoningTags\",\n template_artifact_leak: \"stripChatTemplateArtifacts\",\n system_prompt_echo: null, // consumer-side prompt engineering, not a sanitizer\n hallucinated_tool_name: null, // Phase 37 tool-call validator territory\n malformed_tool_arguments: null, // Phase 37 tool-call validator territory\n premature_termination: null, // consumer-side max_tokens config\n} as const;\n\n/**\n * D-14 / D-15 — Maps a list of known failure modes through the recommendation\n * table and filters nulls. `recommendedSanitizers` always contains real keys.\n *\n * Implementation:\n * - Iterates modes in input order (Set insertion order)\n * - Skips null entries (D-16)\n * - Deduplicates via Set (so repeated modes yield one key)\n * - Returns a readonly array (frozen via spread)\n *\n * Consumers use this to populate `NegotiatedCapabilities.recommendedSanitizers`.\n * Phase 36 registers implementations under the same key ids.\n */\nexport function getRecommendedSanitizers(\n modes: readonly KnownFailureMode[],\n): readonly SanitizerKey[] {\n const seen = new Set<SanitizerKey>();\n for (const mode of modes) {\n const key = SANITIZER_BY_FAILURE_MODE[mode];\n if (key !== null) seen.add(key);\n }\n return [...seen];\n}\n","// Phase 34 — D-02 / D-04 / D-09 / D-10 / D-12 — Capability negotiation\n// surface. NEG-01 / NEG-02 surface.\n//\n// Pitfall 5 mitigation: the top-level `negotiateCapabilities` helper has ZERO\n// live-path logic. It purely delegates to `adapter.negotiateCapabilities` when\n// present. All /models fetch logic, retry policy, and TTL caching live in the\n// per-adapter implementations (Plans 02-05). This avoids the double-logic trap\n// where the helper and the adapter independently implement the same behavior\n// and drift over time.\n\nimport type { CapabilityAdapter, KnownFailureMode, ModelCapabilityProfile } from \"./profile.js\";\nimport { isCapabilityAdapter } from \"./profile.js\";\nimport type { SanitizerKey } from \"./sanitizer-recommendations.js\";\nimport { getCapabilityProfile } from \"./lookup.js\";\nimport { getRecommendedSanitizers } from \"./sanitizer-recommendations.js\";\nimport type { ProviderAdapter } from \"../providers/provider.js\";\n\n/**\n * Phase 34 — SC-3 — Consumer-facing capability shape returned by\n * `adapter.negotiateCapabilities()` and the top-level `negotiateCapabilities()`\n * helper. Simplified relative to `ModelCapabilityProfile` (the registry\n * profile); consumers needing the full enum (e.g., native_strict vs\n * native_lenient) should look up the profile directly via `getCapabilityProfile`.\n *\n * Source values (D-09):\n * - \"live\" — /models endpoint hit, registry profile intersected\n * - \"registry-fallback\" — /models hit failed transiently (5xx/network/timeout),\n * fell back to Phase 33 static registry (D-09)\n * - \"registry\" — adapter intentionally has no /models endpoint\n * (LM Studio, openai-compat), OR consumer-adapter\n * fallback path (D-04)\n */\nexport interface NegotiatedCapabilities {\n readonly modelId: string;\n readonly contextWindow: number;\n readonly supports: {\n readonly nativeToolCalling: boolean;\n readonly structuredOutputs: boolean;\n readonly parallelToolCalls: boolean;\n readonly extendedThinking: boolean;\n readonly streaming: boolean;\n };\n readonly knownFailureModes: readonly KnownFailureMode[];\n readonly recommendedSanitizers: readonly SanitizerKey[];\n readonly source: \"live\" | \"registry-fallback\" | \"registry\";\n}\n\n/**\n * D-10 — Typed error thrown by `negotiateCapabilities` when the adapter's\n * /models endpoint returns 401 or 403. Mirrors `AgentDeniedError` shape\n * (the only existing v1.2 `class extends Error` precedent in agent/types.ts).\n *\n * Why throw (vs return-as-error-union):\n * - Auth errors indicate a broken apiKey config — it is the caller's bug\n * - Silently falling back would hide the misconfiguration\n * - `try/catch` ergonomics work cleanly with `class extends Error`\n * - `instanceof NegotiationAuthError` is the consumer ergonomic\n *\n * IMPORTANT: `NegotiationAuthError` is throwable from `negotiateCapabilities`\n * ONLY — never from `execute()`. Auth errors from /models do NOT contaminate\n * the request path.\n *\n * T-34-01-02: message field set by adapter implementations in Plans 02-04\n * MUST NOT include the apiKey. Only adapter, modelId, and httpStatus are carried.\n */\nexport class NegotiationAuthError extends Error {\n readonly kind = \"negotiation-auth-failed\" as const;\n readonly adapter: CapabilityAdapter;\n readonly modelId: string;\n readonly httpStatus: 401 | 403;\n\n constructor(\n adapter: CapabilityAdapter,\n modelId: string,\n httpStatus: 401 | 403,\n message: string,\n ) {\n super(message);\n this.name = \"NegotiationAuthError\";\n this.adapter = adapter;\n this.modelId = modelId;\n this.httpStatus = httpStatus;\n }\n}\n\n/**\n * Phase 34 — D-02 / D-04 — Top-level helper for capability negotiation.\n *\n * Pitfall 5 (zero live-path logic): delegates verbatim to\n * `adapter.negotiateCapabilities(modelId)` when the adapter implements it.\n * No inflight-coalescing, no cache, no source value transformation. The\n * adapter owns all of that.\n *\n * When the adapter has NO `negotiateCapabilities` (consumer-provided v1.2\n * adapters, third-party adapters), falls back to the Phase 33 registry\n * via `synthesizeNegotiatedCapabilitiesFromRegistry` with source \"registry\"\n * (D-04). Consumer adapters get useful behavior out of the box without any\n * migration code.\n *\n * Verifiable per Pitfall 5: grep for `new Map<` in this function body should\n * return zero matches; LOC count of the function body is < 10 lines.\n */\nexport async function negotiateCapabilities(\n adapter: ProviderAdapter,\n modelId: string,\n): Promise<NegotiatedCapabilities> {\n if (adapter.negotiateCapabilities !== undefined) {\n return adapter.negotiateCapabilities(modelId);\n }\n // IN-04: validate adapter.id against the closed CapabilityAdapter union before\n // looking it up in the registry. An unknown id (e.g., typo \"openrouter-prod\")\n // routes to the empty-stub path directly -- the prior `as CapabilityAdapter`\n // cast silently produced an empty stub via the registry not-found branch,\n // which is the same observable outcome but obscured the failure mode at the\n // type level. The guard narrows `string` to `CapabilityAdapter` without an\n // unsafe cast and makes the graceful-degradation contract explicit.\n if (!isCapabilityAdapter(adapter.id)) {\n return synthesizeNegotiatedCapabilitiesFromRegistry(\n // Pass an arbitrary known adapter to drive the not-found stub path; the\n // returned shape sets `streaming: adapter !== \"lm-studio\"` and zero values\n // elsewhere. We use \"openai\" (the most permissive default) so consumers\n // with an unrecognized adapter id still get streaming: true.\n \"openai\",\n modelId,\n \"registry\",\n );\n }\n return synthesizeNegotiatedCapabilitiesFromRegistry(\n adapter.id,\n modelId,\n \"registry\",\n );\n}\n\n/**\n * Phase 34 — D-04 / D-09 — Synthesizes a `NegotiatedCapabilities` shape from\n * the Phase 33 static registry. Used by:\n * 1. The top-level helper (above) for consumer-adapter fallback (D-04).\n * 2. Per-adapter negotiate() implementations (Plans 02-05) when /models\n * fails transiently (D-09, source \"registry-fallback\").\n *\n * Exported as a named export so Plans 02-05 can reuse the fallback synthesis\n * without duplicating the mapping logic.\n *\n * Implementation note: the boolean derivations are intentionally minimal\n * (heuristic, not definitive). The per-adapter negotiate() implementations\n * in Plans 02-05 own the richer derivation from live /models data.\n * This helper is a SAFETY NET for adapters without /models endpoints and\n * for transient-fallback cases.\n *\n * Anti-shape (documented in CONTEXT.md <specifics>): boolean `nativeToolCalling`\n * loses the strict-vs-lenient distinction in `toolCallSurface`. Consumers\n * needing the enum should look up the profile directly via `getCapabilityProfile`.\n */\nexport function synthesizeNegotiatedCapabilitiesFromRegistry(\n adapter: CapabilityAdapter,\n modelId: string,\n source: \"registry\" | \"registry-fallback\",\n): NegotiatedCapabilities {\n const canonicalKey = `${adapter}:${modelId}`;\n const profile = getCapabilityProfile(canonicalKey);\n\n if (profile === undefined) {\n // Not-found stub per Test 3 in capabilities-negotiate-helper.test.ts:\n // Return a graceful-degradation empty shape rather than throwing.\n // Documented here so the behavior is traceable: Plans 02-05 may log\n // the capabilities.negotiation.fallback event in this case.\n //\n // IN-03: keep `streaming` consistent with mapProfileToNegotiatedCapabilities\n // (line 198 below) -- LM Studio defaults to streaming: false even when no\n // profile exists, so consumers querying an unknown lm-studio model get the\n // same conservative default as a known one.\n return {\n modelId,\n contextWindow: 0,\n supports: {\n nativeToolCalling: false,\n structuredOutputs: false,\n parallelToolCalls: false,\n extendedThinking: false,\n streaming: adapter !== \"lm-studio\",\n },\n knownFailureModes: [],\n recommendedSanitizers: [],\n source,\n };\n }\n\n return mapProfileToNegotiatedCapabilities(profile, source);\n}\n\n/**\n * Internal helper: maps a `ModelCapabilityProfile` to `NegotiatedCapabilities`.\n * This mapping is intentionally a SIMPLIFIED view. The boolean `nativeToolCalling`\n * loses the strict-vs-lenient distinction in `toolCallSurface`; consumers needing\n * the enum should call `getCapabilityProfile` directly.\n */\nfunction mapProfileToNegotiatedCapabilities(\n profile: ModelCapabilityProfile,\n source: \"live\" | \"registry\" | \"registry-fallback\",\n): NegotiatedCapabilities {\n // nativeToolCalling: true if toolCallSurface starts with \"native_\" (native_strict or native_lenient)\n const nativeToolCalling =\n profile.toolCallSurface === \"native_strict\" ||\n profile.toolCallSurface === \"native_lenient\";\n\n // extendedThinking: true if reasoningSurface is NOT \"none\" and NOT \"hidden_cot\"\n // (i.e., the model exposes a visible reasoning trace — inlined_tags, interleaved, streamed)\n const extendedThinking =\n profile.reasoningSurface !== \"none\" &&\n profile.reasoningSurface !== \"hidden_cot\";\n\n // structuredOutputs: heuristic — frontier_rlhf models generally support structured outputs;\n // Plans 02-04 override this with live /models data for the richer derivation.\n const structuredOutputs = profile.trainingClass === \"frontier_rlhf\";\n\n // parallelToolCalls: heuristic — native_strict and native_lenient models can in principle\n // do parallel tool calls; Plans 02-04 set this more precisely from live data.\n const parallelToolCalls = nativeToolCalling;\n\n // streaming: default true for all adapters except LM Studio (local server may not stream)\n const streaming = profile.adapter !== \"lm-studio\";\n\n return {\n modelId: profile.id,\n contextWindow: profile.contextWindow,\n supports: {\n nativeToolCalling,\n structuredOutputs,\n parallelToolCalls,\n extendedThinking,\n streaming,\n },\n knownFailureModes: profile.knownFailureModes,\n recommendedSanitizers: getRecommendedSanitizers(profile.knownFailureModes),\n source,\n };\n}\n\n/**\n * Re-export for Plans 02-05 that need to intersect a live /models response\n * with the static registry profile. The \"live\" source is used when /models\n * succeeded; Plans 02-05 call this with the appropriate source value.\n */\nexport { mapProfileToNegotiatedCapabilities as _mapProfileToNegotiatedCapabilities };\n","export interface TracerLike {\n readonly kind: \"tracer\";\n readonly span?: <T>(\n name: string,\n fn: () => T | Promise<T>,\n attributes?: Record<string, unknown>,\n ) => T | Promise<T>;\n readonly event?: (name: string, attributes?: Record<string, unknown>) => void;\n}\n\nexport type RunEventKind =\n | \"run.start\"\n | \"artifact.ingested\"\n | \"context.packed\"\n | \"router.candidates\"\n | \"stage.start\"\n | \"stage.complete\"\n | \"provider.attempt\"\n | \"fallback.activated\"\n | \"validation.complete\"\n | \"validation.failed\"\n | \"artifact.created\"\n | \"run.complete\"\n | \"run.failed\"\n | \"tool.call\"\n | \"replay.offline\"\n | \"replay.live\"\n | \"step.transition\"\n // Phase 20 (v1.2): recovery / eviction-resume markers paired with the\n // AgentHost storage seam + SurvivabilityAdapter. Closes TRACE-EXT-01.\n | \"recovery.start\"\n | \"recovery.complete\"\n | \"recovery.failed\"\n // Phase 34 (v1.3): capability-negotiation fallback marker. Fires when\n // adapter.negotiateCapabilities() falls back from /models to the static\n // Phase 33 registry due to transient (5xx, network, timeout) failure.\n // Auth errors (401, 403) do NOT fire this event -- they throw\n // NegotiationAuthError instead.\n | \"capabilities.negotiation.fallback\";\n\nexport interface RunEvent {\n readonly kind: RunEventKind;\n readonly timestamp: string;\n readonly runId: string;\n readonly planId?: string;\n readonly stageId?: string;\n readonly providerId?: string;\n readonly modelId?: string;\n readonly artifactId?: string;\n readonly metadata?: Record<string, unknown>;\n}\n\nexport type RunEventSink = (event: RunEvent) => void | Promise<void>;\n\nexport function createRunEvent(\n kind: RunEventKind,\n input: Omit<RunEvent, \"kind\" | \"timestamp\">,\n): RunEvent {\n return {\n kind,\n timestamp: new Date().toISOString(),\n ...input,\n };\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nimport { validateSchemaOutput } from \"../outputs/validate.js\";\nimport type { ToolUseRequest } from \"../agent/types.js\";\nimport type { ValidationIssue } from \"../results/errors.js\";\nimport type { ToolDefinition } from \"./tools.js\";\n\nexport type ToolCallValidationFailureReason =\n | \"unknown_tool\"\n | \"invalid_args\"\n | \"extra_fields\";\n\nexport interface ValidatedToolCall {\n readonly id: string;\n readonly name: string;\n readonly args: unknown;\n}\n\ntype ToolCallValidationTool = Pick<ToolDefinition, \"name\" | \"inputSchema\">;\n\nexport interface ValidateToolCallsOption {\n readonly tools: readonly ToolCallValidationTool[];\n readonly onFailure?: \"throw\" | \"drop\" | \"callback\";\n readonly onValidationFailure?: (error: ToolCallValidationError) => void | Promise<void>;\n readonly allowExtraFields?: boolean;\n}\n\nexport class ToolCallValidationError extends Error {\n readonly kind = \"tool-call-validation\" as const;\n readonly reason: ToolCallValidationFailureReason;\n readonly toolName: string;\n readonly attemptedArgs: unknown;\n readonly validationIssues: readonly ValidationIssue[];\n readonly requestId: string;\n\n constructor(input: {\n readonly reason: ToolCallValidationFailureReason;\n readonly toolName: string;\n readonly attemptedArgs: unknown;\n readonly validationIssues?: readonly ValidationIssue[];\n readonly requestId: string;\n }) {\n super(createValidationMessage(input.reason, input.toolName, input.requestId));\n this.name = \"ToolCallValidationError\";\n this.reason = input.reason;\n this.toolName = input.toolName;\n this.attemptedArgs = input.attemptedArgs;\n this.validationIssues = input.validationIssues ?? [];\n this.requestId = input.requestId;\n }\n}\n\nexport async function validateToolCallRequests(\n requests: readonly ToolUseRequest[],\n option: ValidateToolCallsOption | undefined,\n): Promise<readonly ValidatedToolCall[] | undefined> {\n if (option === undefined) {\n return undefined;\n }\n\n const onFailure = option.onFailure ?? \"throw\";\n if (onFailure === \"callback\" && option.onValidationFailure === undefined) {\n throw new Error(\n 'validateToolCalls.onValidationFailure is required when onFailure is \"callback\".',\n );\n }\n\n const toolsByName = new Map(option.tools.map((tool) => [tool.name, tool]));\n const validCalls: ValidatedToolCall[] = [];\n\n for (const request of requests) {\n const tool = toolsByName.get(request.name);\n if (tool === undefined) {\n await handleValidationError(\n new ToolCallValidationError({\n reason: \"unknown_tool\",\n toolName: request.name,\n attemptedArgs: request.args,\n requestId: request.id,\n }),\n onFailure,\n option.onValidationFailure,\n );\n continue;\n }\n\n const validation = await validateSchemaOutput(tool.name, tool.inputSchema, request.args);\n if (!validation.ok) {\n await handleValidationError(\n new ToolCallValidationError({\n reason: \"invalid_args\",\n toolName: request.name,\n attemptedArgs: request.args,\n validationIssues: validation.issue.issues,\n requestId: request.id,\n }),\n onFailure,\n option.onValidationFailure,\n );\n continue;\n }\n\n const extraFields = option.allowExtraFields === true\n ? []\n : findExtraFields(tool.inputSchema, request.args);\n if (extraFields.length > 0) {\n await handleValidationError(\n new ToolCallValidationError({\n reason: \"extra_fields\",\n toolName: request.name,\n attemptedArgs: request.args,\n validationIssues: extraFields.map((field) => ({\n message: `Unexpected tool argument field \"${field}\".`,\n path: [field],\n })),\n requestId: request.id,\n }),\n onFailure,\n option.onValidationFailure,\n );\n continue;\n }\n\n validCalls.push({\n id: request.id,\n name: request.name,\n args: validation.value,\n });\n }\n\n return validCalls;\n}\n\nasync function handleValidationError(\n error: ToolCallValidationError,\n onFailure: \"throw\" | \"drop\" | \"callback\",\n callback: ValidateToolCallsOption[\"onValidationFailure\"],\n): Promise<void> {\n if (onFailure === \"throw\") {\n throw error;\n }\n if (onFailure === \"callback\") {\n await callback?.(error);\n }\n}\n\nfunction findExtraFields(\n schema: StandardSchemaV1,\n value: unknown,\n): readonly string[] {\n if (!isRecord(value)) {\n return [];\n }\n\n const allowedFields = getObjectSchemaKeys(schema);\n if (allowedFields === undefined) {\n return [];\n }\n\n const allowed = new Set(allowedFields);\n return Object.keys(value).filter((field) => !allowed.has(field));\n}\n\nfunction getObjectSchemaKeys(schema: StandardSchemaV1): readonly string[] | undefined {\n const candidate = schema as {\n readonly shape?: unknown;\n readonly def?: { readonly type?: unknown; readonly shape?: unknown };\n readonly _def?: { readonly type?: unknown; readonly shape?: unknown };\n };\n\n const directShape = normalizeShape(candidate.shape);\n if (directShape !== undefined) {\n return directShape;\n }\n\n if (candidate.def?.type === \"object\") {\n const defShape = normalizeShape(candidate.def.shape);\n if (defShape !== undefined) {\n return defShape;\n }\n }\n\n if (candidate._def?.type === \"object\") {\n return normalizeShape(candidate._def.shape);\n }\n\n return undefined;\n}\n\nfunction normalizeShape(shape: unknown): readonly string[] | undefined {\n const resolved = typeof shape === \"function\" ? (shape as () => unknown)() : shape;\n if (!isRecord(resolved)) {\n return undefined;\n }\n\n return Object.keys(resolved);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction createValidationMessage(\n reason: ToolCallValidationFailureReason,\n toolName: string,\n requestId: string,\n): string {\n if (reason === \"unknown_tool\") {\n return `Unknown tool call \"${toolName}\" (${requestId}).`;\n }\n if (reason === \"extra_fields\") {\n return `Tool call \"${toolName}\" contains unexpected argument fields (${requestId}).`;\n }\n return `Invalid arguments for tool call \"${toolName}\" (${requestId}).`;\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nexport interface SanitizerContext {\n readonly providerId: string;\n readonly modelId?: string;\n readonly outputName: string;\n}\n\nexport type SanitizerFn = (\n text: string,\n context: SanitizerContext,\n) => string | Promise<string>;\n\nexport type SanitizeOutputOption = SanitizerFn | readonly SanitizerFn[];\n\nexport interface InternalEnvelopeOptions {\n readonly field?: string;\n readonly path?: string;\n readonly schema?: StandardSchemaV1;\n}\n\ntype ParsedEnvelopeOptions =\n | { readonly kind: \"path\"; readonly path: readonly string[]; readonly schema?: StandardSchemaV1 }\n | { readonly kind: \"schema\"; readonly schema: StandardSchemaV1 };\n\nexport async function applyOutputSanitizers(\n rawOutputs: Record<string, unknown>,\n sanitizeOutput: SanitizeOutputOption | undefined,\n context: Omit<SanitizerContext, \"outputName\">,\n): Promise<Record<string, unknown>> {\n if (sanitizeOutput === undefined) return rawOutputs;\n\n const sanitizers = Array.isArray(sanitizeOutput) ? sanitizeOutput : [sanitizeOutput];\n const sanitizedEntries = await Promise.all(\n Object.entries(rawOutputs).map(async ([outputName, value]) => {\n if (typeof value !== \"string\") {\n return [outputName, value] as const;\n }\n\n let sanitized = value;\n const sanitizerContext: SanitizerContext = {\n ...context,\n outputName,\n };\n for (const sanitizer of sanitizers) {\n sanitized = await sanitizer(sanitized, sanitizerContext);\n }\n return [outputName, sanitized] as const;\n }),\n );\n\n return Object.fromEntries(sanitizedEntries);\n}\n\nexport function stripReasoningTags(): SanitizerFn {\n return (text) => {\n let next = text;\n\n next = next.replace(\n /^\\s*(?:reasoning|analysis|scratchpad)\\s*:\\s*(?:.|\\n)*?(?:\\n\\s*(?:final|answer)\\s*:\\s*)/iu,\n \"\",\n );\n next = stripDelimitedBlock(next, \"think\");\n next = stripDelimitedBlock(next, \"reasoning\");\n next = stripDelimitedBlock(next, \"scratchpad\");\n\n return next === text ? text : next.trim();\n };\n}\n\nexport function stripChatTemplateArtifacts(): SanitizerFn {\n return (text) => {\n let next = text;\n\n next = next.replace(/<\\|im_start\\|>\\s*(?:system|user|assistant)?\\s*/giu, \"\");\n next = next.replace(/\\s*<\\|im_end\\|>/giu, \"\");\n next = next.replace(/\\[\\/?INST\\]/giu, \"\");\n next = next.replace(/<<SYS>>|<<\\/SYS>>/giu, \"\");\n next = next.replace(/^\\s*(?:system|user|assistant)\\s*:\\s*/iu, \"\");\n\n return next === text ? text : next.trim();\n };\n}\n\nexport function unwrapInternalEnvelope(\n schemaOrPath: string | InternalEnvelopeOptions | StandardSchemaV1,\n): SanitizerFn {\n const options = parseEnvelopeOptions(schemaOrPath);\n\n return async (text) => {\n const parsed = parseJsonObject(text);\n if (parsed === undefined) return text;\n\n if (options.schema !== undefined) {\n const validation = await validateSchema(options.schema, parsed);\n if (!validation.ok) return text;\n }\n\n const value = options.kind === \"path\"\n ? getPathValue(parsed, options.path)\n : findOnlyStringField(parsed);\n\n return typeof value === \"string\" ? value : text;\n };\n}\n\nfunction stripDelimitedBlock(text: string, tag: string): string {\n const pattern = new RegExp(`<${tag}\\\\b[^>]*>[\\\\s\\\\S]*?<\\\\/${tag}>`, \"giu\");\n return text.replace(pattern, \"\");\n}\n\nfunction parseEnvelopeOptions(\n schemaOrPath: string | InternalEnvelopeOptions | StandardSchemaV1,\n): ParsedEnvelopeOptions {\n if (typeof schemaOrPath === \"string\") {\n return { kind: \"path\", path: splitPath(schemaOrPath) };\n }\n\n if (isStandardSchema(schemaOrPath)) {\n return { kind: \"schema\", schema: schemaOrPath };\n }\n\n const path = schemaOrPath.path ?? schemaOrPath.field;\n if (path !== undefined) {\n return {\n kind: \"path\",\n path: splitPath(path),\n ...(schemaOrPath.schema !== undefined ? { schema: schemaOrPath.schema } : {}),\n };\n }\n\n if (schemaOrPath.schema !== undefined) {\n return { kind: \"schema\", schema: schemaOrPath.schema };\n }\n\n return { kind: \"path\", path: [] };\n}\n\nfunction splitPath(path: string): readonly string[] {\n return path.split(\".\").map((part) => part.trim()).filter(Boolean);\n}\n\nfunction parseJsonObject(text: string): Record<string, unknown> | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return undefined;\n }\n\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n return undefined;\n }\n\n return parsed as Record<string, unknown>;\n}\n\nfunction getPathValue(\n value: Record<string, unknown>,\n path: readonly string[],\n): unknown {\n if (path.length === 0) return undefined;\n\n let current: unknown = value;\n for (const segment of path) {\n if (typeof current !== \"object\" || current === null || Array.isArray(current)) {\n return undefined;\n }\n\n if (!Object.prototype.hasOwnProperty.call(current, segment)) {\n return undefined;\n }\n\n current = (current as Record<string, unknown>)[segment];\n }\n\n return current;\n}\n\nfunction findOnlyStringField(value: Record<string, unknown>): string | undefined {\n const stringValues = Object.values(value).filter((field): field is string => typeof field === \"string\");\n return stringValues.length === 1 ? stringValues[0] : undefined;\n}\n\nasync function validateSchema(\n schema: StandardSchemaV1,\n value: unknown,\n): Promise<{ readonly ok: true } | { readonly ok: false }> {\n const result = schema[\"~standard\"].validate(value);\n const resolved = result instanceof Promise ? await result : result;\n return \"issues\" in resolved ? { ok: false } : { ok: true };\n}\n\nfunction isStandardSchema(value: unknown): value is StandardSchemaV1 {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"~standard\" in value &&\n typeof (value as { readonly \"~standard\"?: { readonly validate?: unknown } })[\"~standard\"]\n ?.validate === \"function\"\n );\n}\n","import type { UsageRecord } from \"../plan/plan.js\";\nimport type { ProviderAdapter, ProviderRunResponse, Usage } from \"./provider.js\";\nimport { defaultCapabilityForProvider } from \"../routing/catalog.js\";\nimport type { OpenAIQuirks, OpenAICompatQuirks } from \"./quirks.js\";\nimport type { NegotiatedCapabilities } from \"../capabilities/negotiate.js\";\nimport {\n NegotiationAuthError,\n synthesizeNegotiatedCapabilitiesFromRegistry,\n _mapProfileToNegotiatedCapabilities,\n} from \"../capabilities/negotiate.js\";\nimport { getCapabilityProfile } from \"../capabilities/lookup.js\";\nimport type { CapabilityAdapter } from \"../capabilities/profile.js\";\nimport type { RunEventSink } from \"../tracing/tracing.js\";\nimport { createRunEvent } from \"../tracing/tracing.js\";\nimport { parseToolUseEnvelope } from \"../agent/format-tools.js\";\nimport {\n validateToolCallRequests,\n type ValidateToolCallsOption,\n} from \"../tools/tool-call-validation.js\";\nimport {\n applyOutputSanitizers,\n type SanitizeOutputOption,\n} from \"../sanitizers/index.js\";\n\nexport interface OpenAICompatibleProviderOptions {\n readonly id?: string;\n readonly model: string;\n readonly baseUrl: string;\n readonly apiKey?: string;\n readonly fetch?: typeof fetch;\n /**\n * Phase 7 addition: caller-supplied per-1k pricing. When provided, the\n * adapter computes `normalizedUsage.costUsd` from the API-reported token\n * counts. When omitted, `normalizedUsage.costUsd` is `null` so downstream\n * consumers can distinguish \"unmeasured\" from \"free\" (per 07-CONTEXT.md).\n */\n readonly pricing?: {\n readonly inputPer1kTokens?: number;\n readonly outputPer1kTokens?: number;\n };\n /**\n * Phase 34 — D-05/D-06/D-08 — TTL for the per-instance models cache.\n * Default 300_000ms (5 minutes). Set to 0 to disable caching.\n * Set to Infinity for process-lifetime caching.\n *\n * NOTE: for createOpenAICompatibleProvider, this option is accepted for\n * option-bag uniformity but is NOT USED — openai-compat has no /models\n * endpoint (D-04). Document in JSDoc for consumers pointing at known servers.\n */\n readonly modelsCacheTtlMs?: number;\n /**\n * Phase 34 — D-11 — Number of retry attempts on transient /models errors\n * (5xx, network, timeout). Default 2. Set to 0 to disable retries.\n *\n * NOTE: for createOpenAICompatibleProvider, this option is accepted for\n * option-bag uniformity but is NOT USED — openai-compat has no /models\n * endpoint (D-04).\n */\n readonly modelsRetryCount?: number;\n /**\n * Phase 34 — D-12 — Optional RunEventSink for capability negotiation events.\n * When provided, emits the \"capabilities.negotiation.fallback\" event on\n * transient /models errors (5xx, network, timeout).\n *\n * NOTE: for createOpenAICompatibleProvider, this option is accepted for\n * option-bag uniformity but the event is NOT FIRED for source: \"registry\"\n * (the documented happy path for openai-compat). Emitting events for the\n * intentional no-endpoint path would produce noisy false-positives.\n */\n readonly runEventSink?: RunEventSink;\n /**\n * Phase 36 — Optional output sanitizer pipeline. When provided, string\n * rawOutputs are transformed in order after provider text extraction and\n * before the adapter returns.\n */\n readonly sanitizeOutput?: SanitizeOutputOption;\n /**\n * Phase 37 — Optional returned tool-call validator. When provided, the\n * adapter parses prompt-reencoded tool_calls envelopes and returns\n * normalized validated calls without mutating rawOutputs or rawResponse.\n */\n readonly validateToolCalls?: ValidateToolCallsOption;\n}\n\nexport interface SdkLikeProviderOptions {\n readonly id?: string;\n readonly model: string;\n readonly generate: (input: {\n readonly task: string;\n readonly outputNames: readonly string[];\n }) => Promise<ProviderRunResponse> | ProviderRunResponse;\n}\n\n/**\n * Phase 34 — D-04 / QUIRK-02 — OpenAI-compatible provider factory.\n *\n * This factory is the prototypical \"intentional no remote /models endpoint\"\n * adapter per D-04. The consumer points this adapter at any OpenAI-shaped\n * endpoint (vLLM, TGI, Ollama, custom), and the factory returns conservative\n * defaults for the quirks block because the server could be anything.\n *\n * The `negotiateCapabilities` method performs NO fetch; it returns\n * synthesizeNegotiatedCapabilitiesFromRegistry with source: \"registry\"\n * (the intentional-no-endpoint signal, as distinct from \"registry-fallback\"\n * which signals a transient failure). Plan 34-05 (LM Studio) reuses this\n * same pattern.\n *\n * D-04 citation: \"consumer adapters without a /models endpoint skip the\n * fetch layer entirely and delegate to synthesizeNegotiatedCapabilitiesFromRegistry.\"\n */\nexport function createOpenAICompatibleProvider(\n options: OpenAICompatibleProviderOptions,\n): ProviderAdapter & {\n readonly quirks: OpenAICompatQuirks;\n readonly negotiateCapabilities: (modelId: string) => Promise<NegotiatedCapabilities>;\n} {\n const id = options.id ?? \"openai-compatible\";\n const fetchImpl = options.fetch ?? fetch;\n\n // Phase 34 — D-04 — OpenAI-compat negotiate() is registry-only (no fetch,\n // no cache, no inflight). Source: \"registry\" signals intentional no-endpoint.\n const negotiate = async (modelId: string): Promise<NegotiatedCapabilities> => {\n const adapterId = (id) as CapabilityAdapter;\n // No fetch; no cache; no inflight coalescing. Direct synthesis from registry per D-04.\n // Source: \"registry\" signals intentional no-endpoint (vs \"registry-fallback\"\n // which signals a transient failure we couldn't recover from).\n return synthesizeNegotiatedCapabilitiesFromRegistry(adapterId, modelId, \"registry\");\n };\n\n return {\n id,\n kind: \"provider-adapter\",\n // Phase 34 — QUIRK-02 / OpenAICompatQuirks — conservative defaults.\n // openai-compat servers (vLLM, TGI, Ollama, custom) vary widely in which\n // response_format and tool_choice features they implement. Defaults are\n // conservatively false except streamingDiverges which is true because\n // self-hosted servers often have subtle streaming differences.\n quirks: {\n supportsToolChoice: false,\n parallelToolCalls: false,\n structuredOutputs: false,\n responseFormatHonored: false,\n streamingDiverges: true,\n } satisfies OpenAICompatQuirks,\n negotiateCapabilities: negotiate,\n capabilities: [\n {\n ...defaultCapabilityForProvider(id),\n modelId: options.model,\n fileTransport: [\"inline\", \"json\", \"url\", \"base64\", \"extracted-text\", \"transcript\"],\n },\n ],\n async execute(request) {\n const init: RequestInit = {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(options.apiKey !== undefined ? { authorization: `Bearer ${options.apiKey}` } : {}),\n },\n body: JSON.stringify({\n model: options.model,\n messages: [\n {\n role: \"user\",\n content: [\n {\n type: \"text\",\n text: request.task,\n },\n {\n type: \"text\",\n text: JSON.stringify({\n contextPack: request.contextPack === undefined\n ? undefined\n : {\n id: request.contextPack.id,\n tokenBudget: request.contextPack.tokenBudget,\n estimatedTokens: request.contextPack.estimatedTokens,\n included: request.contextPack.included,\n summarized: request.contextPack.summarized,\n archived: request.contextPack.archived,\n omitted: request.contextPack.omitted,\n warnings: request.contextPack.warnings,\n },\n }),\n },\n ...request.artifacts.map((inputArtifact) => ({\n type: \"text\",\n text: JSON.stringify({\n artifactId: inputArtifact.id,\n kind: inputArtifact.kind,\n mediaType: inputArtifact.mediaType,\n privacy: inputArtifact.privacy,\n transport: request.providerPackaging?.artifacts.find(\n (item) => item.artifactId === inputArtifact.id,\n )?.transport ?? request.plan?.providerPackaging?.artifacts.find(\n (item) => item.artifactId === inputArtifact.id,\n )?.transport,\n value:\n typeof inputArtifact.value === \"string\" && inputArtifact.kind !== \"url\"\n ? inputArtifact.value\n : undefined,\n url:\n inputArtifact.kind === \"url\" && typeof inputArtifact.value === \"string\"\n ? inputArtifact.value\n : undefined,\n }),\n })),\n ],\n },\n ],\n }),\n ...(request.signal !== undefined ? { signal: request.signal } : {}),\n };\n const response = await fetchImpl(`${options.baseUrl.replace(/\\/$/u, \"\")}/chat/completions`, init);\n\n if (!response.ok) {\n throw new Error(`OpenAI-compatible provider failed with ${response.status}.`);\n }\n\n const body = await response.json() as {\n choices?: readonly { message?: { content?: unknown } }[];\n usage?: unknown;\n };\n const text = String(body.choices?.[0]?.message?.content ?? \"\");\n const rawOutputs = Object.fromEntries(request.outputs.map((name) => [name, text]));\n const sanitizedOutputs = await applyOutputSanitizers(rawOutputs, options.sanitizeOutput, {\n providerId: id,\n modelId: options.model,\n });\n const parsedToolCalls = parseToolUseEnvelope(text);\n const toolCalls = parsedToolCalls === null\n ? undefined\n : await validateToolCallRequests(parsedToolCalls, options.validateToolCalls);\n const usage = normalizeUsage(body.usage);\n const normalizedUsage = normalizeUsageToRunUsage(body.usage, options.pricing);\n\n return {\n rawOutputs: sanitizedOutputs,\n ...(usage !== undefined ? { usage } : {}),\n normalizedUsage,\n ...(toolCalls !== undefined ? { toolCalls } : {}),\n rawResponse: body,\n };\n },\n };\n}\n\n/**\n * Phase 7 normalization: maps raw provider usage payloads (OpenAI's\n * `prompt_tokens`/`completion_tokens`, the Responses API's\n * `input_tokens`/`output_tokens`, or camelCase variants) to the shared\n * `Usage` shape. When `pricing` is supplied, `costUsd` is computed from\n * the normalized token counts. Otherwise `costUsd` is `null` so consumers\n * can distinguish \"unmeasured\" from \"zero\".\n */\nfunction normalizeUsageToRunUsage(\n rawUsage: unknown,\n pricing?: {\n readonly inputPer1kTokens?: number;\n readonly outputPer1kTokens?: number;\n },\n): Usage {\n let promptTokens = 0;\n let completionTokens = 0;\n if (typeof rawUsage === \"object\" && rawUsage !== null) {\n const record = rawUsage as Record<string, unknown>;\n promptTokens =\n numberField(record, \"prompt_tokens\") ??\n numberField(record, \"input_tokens\") ??\n numberField(record, \"inputTokens\") ??\n 0;\n completionTokens =\n numberField(record, \"completion_tokens\") ??\n numberField(record, \"output_tokens\") ??\n numberField(record, \"outputTokens\") ??\n 0;\n }\n let costUsd: number | null = null;\n if (\n pricing !== undefined &&\n (pricing.inputPer1kTokens !== undefined || pricing.outputPer1kTokens !== undefined)\n ) {\n const inputCost = ((pricing.inputPer1kTokens ?? 0) * promptTokens) / 1000;\n const outputCost = ((pricing.outputPer1kTokens ?? 0) * completionTokens) / 1000;\n costUsd = inputCost + outputCost;\n }\n return { promptTokens, completionTokens, costUsd };\n}\n\nfunction normalizeUsage(usage: unknown): UsageRecord | undefined {\n if (typeof usage !== \"object\" || usage === null) {\n return undefined;\n }\n\n const record = usage as Record<string, unknown>;\n const inputTokens = numberField(record, \"prompt_tokens\") ?? numberField(record, \"input_tokens\");\n const outputTokens =\n numberField(record, \"completion_tokens\") ?? numberField(record, \"output_tokens\");\n const totalTokens = numberField(record, \"total_tokens\");\n\n return {\n ...(inputTokens !== undefined ? { inputTokens } : {}),\n ...(outputTokens !== undefined ? { outputTokens } : {}),\n ...(totalTokens !== undefined ? { totalTokens } : {}),\n };\n}\n\nfunction numberField(record: Record<string, unknown>, key: string): number | undefined {\n const value = record[key];\n\n return typeof value === \"number\" ? value : undefined;\n}\n\n/**\n * Phase 34 — D-12 — Emits a \"capabilities.negotiation.fallback\" RunEvent if\n * a sink is provided. The runId uses a synthetic value since negotiation\n * happens outside a run context.\n *\n * T-34-03-01: errorReason is produced by stringifyErr (message only, NOT\n * stack) to prevent apiKey leaking in error strings that include request headers.\n */\nfunction emitFallbackEvent(\n sink: RunEventSink | undefined,\n payload: {\n readonly adapter: string;\n readonly modelId: string;\n readonly errorReason: string;\n readonly fallbackSource: \"registry-fallback\";\n },\n): void {\n if (sink === undefined) return;\n const event = createRunEvent(\"capabilities.negotiation.fallback\", {\n // Synthetic runId: negotiation happens outside a run context (no run.id available).\n // Pattern documented in Plan 34-02 (Anthropic reference impl).\n runId: `negotiate-${payload.adapter}-${payload.modelId}`,\n providerId: payload.adapter,\n modelId: payload.modelId,\n metadata: {\n adapter: payload.adapter,\n modelId: payload.modelId,\n errorReason: payload.errorReason,\n fallbackSource: payload.fallbackSource,\n },\n });\n void sink(event);\n}\n\n/**\n * Stringify an error for event metadata. Returns only the message (NOT the\n * stack) to prevent apiKey or sensitive header values from leaking into\n * event payloads via fetch errors that may embed the request init.\n * T-34-03-01 mitigation.\n */\nfunction stringifyErr(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Phase 34 — QUIRK-02 / NEG-01 / NEG-02 — Merge an OpenAI /v1/models\n * sparse response with the Phase 33 registry.\n *\n * OpenAI's /models response is famously SPARSE per RESEARCH §Q2:\n * `{ id, object, created, owned_by }` only. No capabilities block.\n * The /models call confirms the model EXISTS in the user's org, but\n * tells us nothing about its capabilities. We source supports.* from\n * the Phase 33 registry instead.\n *\n * Source semantics per D-09:\n * - \"live\" when the model id is found in the /models response\n * (the id was verified to exist — useful signal for org membership)\n * - \"registry-fallback\" when the model is NOT in the /models response\n * (model not in org, or stale; emit fallback event)\n *\n * Anti-pattern warning (RESEARCH §Anti-patterns): DO NOT assume OpenAI\n * /v1/models returns capability flags. It doesn't. Only id/object/created/\n * owned_by are returned. Source supports.* ONLY from the registry.\n */\nfunction mergeOpenAIModelsWithRegistry(\n modelId: string,\n body: unknown,\n emitFallback: () => void,\n): NegotiatedCapabilities {\n // LENIENT-PARSE: body may be malformed; defensive chaining throughout (Pitfall 1).\n const data = (body as { data?: unknown })?.data;\n const found = Array.isArray(data)\n ? (data as Array<unknown>).find(\n (m): m is { id: string } =>\n typeof m === \"object\" && m !== null && (m as { id?: unknown }).id === modelId,\n )\n : undefined;\n\n if (found === undefined) {\n // Model not in /models response — emit fallback event and fall back to registry.\n emitFallback();\n return synthesizeNegotiatedCapabilitiesFromRegistry(\"openai\", modelId, \"registry-fallback\");\n }\n\n // Model found in /models response — source supports.* from registry profile.\n // The /models call confirmed the model EXISTS in the org (useful signal), but\n // sparse /models tells us nothing about capabilities. Per RESEARCH §Q2 planning\n // note 2: use source: \"live\" since the model id was verified to exist.\n const registryProfile = getCapabilityProfile(`openai:${modelId}`);\n if (registryProfile !== undefined) {\n return _mapProfileToNegotiatedCapabilities(registryProfile, \"live\");\n }\n\n // Model exists in org (/models confirmed) but Phase 33 registry doesn't have it.\n // Use source: \"live\" per planning_context note 2 (the model id was verified).\n // Supports.* are unknown — return empty-stub shape with source: \"live\".\n //\n // We construct the empty stub inline because synthesizeNegotiatedCapabilitiesFromRegistry\n // only accepts \"registry\" | \"registry-fallback\" as source values. The shape below mirrors\n // the not-found branch of that helper (negotiate.ts:149-162) but with source: \"live\"\n // since the model id was verified via /v1/models.\n return {\n modelId,\n contextWindow: 0,\n supports: {\n nativeToolCalling: false,\n structuredOutputs: false,\n parallelToolCalls: false,\n extendedThinking: false,\n streaming: true,\n },\n knownFailureModes: [],\n recommendedSanitizers: [],\n source: \"live\",\n };\n}\n\n/**\n * Phase 34 — QUIRK-02 / NEG-01 / NEG-02 — OpenAI provider factory.\n *\n * Extends the base OpenAI-compat factory with:\n * 1. `quirks: OpenAIQuirks` — verified per RESEARCH §Q6 OpenAI vocabulary.\n * 2. `negotiateCapabilities(modelId)` — queries OpenAI /v1/models GET with\n * Authorization: Bearer header; SPARSE response; intersects with Phase 33\n * registry for supports.* (per RESEARCH §Anti-patterns — don't assume\n * OpenAI /v1/models returns capability flags, it doesn't).\n *\n * The negotiate() pattern mirrors Plan 34-02 (Anthropic thick reference):\n * - Per-instance TTL cache (modelsCacheTtlMs, default 300_000ms)\n * - Single-flight inflight coalescing with .finally cleanup (Pitfall 4)\n * - Retry with [0, 200, 1000]ms backoff (modelsRetryCount, default 2)\n * - 401/403 throws NegotiationAuthError (D-10: no retry, no fallback, no event)\n * - 5xx/network/timeout falls back to registry with source: \"registry-fallback\"\n * - emitFallbackEvent fires the \"capabilities.negotiation.fallback\" RunEvent\n *\n * SECURITY (T-34-03-07): inflight Map MUST use .finally cleanup to prevent\n * leak on rejection. Verifiable: grep `.finally` in this file.\n */\nexport function createOpenAIProvider(\n options: OpenAICompatibleProviderOptions,\n): ProviderAdapter & {\n readonly quirks: OpenAIQuirks;\n readonly negotiateCapabilities: (modelId: string) => Promise<NegotiatedCapabilities>;\n} {\n const id = options.id ?? \"openai\";\n const fetchImpl = options.fetch ?? fetch;\n const baseUrl = (options.baseUrl ?? \"https://api.openai.com\").replace(/\\/$/u, \"\");\n const ttlMs = options.modelsCacheTtlMs ?? 300_000;\n const retryCount = options.modelsRetryCount ?? 2;\n\n // Per-instance TTL cache (D-05/D-06/D-07/D-08). One Map per factory call.\n const cache = new Map<string, { result: NegotiatedCapabilities; expiresAt: number }>();\n // Per-instance inflight coalescing Map (Q7). .finally cleanup is mandatory (Pitfall 4).\n const inflight = new Map<string, Promise<NegotiatedCapabilities>>();\n\n async function fetchAndNegotiate(modelId: string): Promise<NegotiatedCapabilities> {\n const url = `${baseUrl}/v1/models`;\n // IN-02: omit Authorization entirely when apiKey is undefined; sending\n // \"Bearer \" literal would trigger noisy 401s and intrusion-detection flags.\n // Mirrors the OpenAI-compat execute path (line 137).\n const headers: Record<string, string> = {\n \"accept\": \"application/json\",\n ...(options.apiKey !== undefined ? { authorization: `Bearer ${options.apiKey}` } : {}),\n };\n const attempts = retryCount + 1;\n const backoffMs = [0, 200, 1000];\n let lastErr: unknown;\n for (let i = 0; i < attempts; i += 1) {\n if (i > 0) {\n const delay = backoffMs[Math.min(i, backoffMs.length - 1)] ?? 1000;\n await new Promise<void>((r) => setTimeout(r, delay));\n }\n try {\n const resp = await fetchImpl(url, {\n method: \"GET\",\n headers,\n signal: AbortSignal.timeout(30_000),\n });\n if (resp.status === 401 || resp.status === 403) {\n throw new NegotiationAuthError(\n \"openai\",\n modelId,\n resp.status as 401 | 403,\n `OpenAI /v1/models returned ${resp.status}: check apiKey config.`,\n );\n }\n if (!resp.ok) {\n throw new Error(`HTTP ${resp.status}`);\n }\n const body = await resp.json() as unknown;\n return mergeOpenAIModelsWithRegistry(modelId, body, () => {\n emitFallbackEvent(options.runEventSink, {\n adapter: \"openai\",\n modelId,\n errorReason: \"model not found in /v1/models response\",\n fallbackSource: \"registry-fallback\",\n });\n });\n } catch (err) {\n if (err instanceof NegotiationAuthError) throw err; // D-10: auth never retries\n lastErr = err;\n }\n }\n // All retries exhausted — transient fallback + event.\n emitFallbackEvent(options.runEventSink, {\n adapter: \"openai\",\n modelId,\n errorReason: stringifyErr(lastErr),\n fallbackSource: \"registry-fallback\",\n });\n return synthesizeNegotiatedCapabilitiesFromRegistry(\"openai\", modelId, \"registry-fallback\");\n }\n\n async function negotiate(modelId: string): Promise<NegotiatedCapabilities> {\n // 1. Cache check (D-07 lazy expiry).\n const cached = cache.get(modelId);\n if (cached !== undefined && cached.expiresAt > Date.now()) return cached.result;\n\n // 2. Inflight coalesce (Q7).\n const existing = inflight.get(modelId);\n if (existing !== undefined) return existing;\n\n // 3. New fetch promise; clear inflight in .finally (Pitfall 4).\n const fetchPromise = (async () => {\n try {\n const result = await fetchAndNegotiate(modelId);\n if (ttlMs > 0) {\n cache.set(modelId, { result, expiresAt: Date.now() + ttlMs });\n }\n return result;\n } finally {\n inflight.delete(modelId);\n }\n })();\n inflight.set(modelId, fetchPromise);\n return fetchPromise;\n }\n\n const innerCompat = createOpenAICompatibleProvider({\n ...options,\n id,\n baseUrl,\n });\n\n return {\n ...innerCompat,\n // Phase 34 — QUIRK-02 / OpenAIQuirks — verified per RESEARCH §Q6 OpenAI vocabulary.\n // CITED: https://platform.openai.com/docs/guides/structured-outputs\n // - strictModeSupported: function-calling strict:true available on gpt-4o-2024-08-06+, o1+\n // - structuredOutputsTier2: json_schema response_format on gpt-4o and gpt-4o-mini series\n // CITED: RESEARCH §Q6 — supportsToolChoice, parallelToolCalls, structuredOutputs,\n // responseFormatHonored all true for OpenAI. streamingDiverges false (OpenAI streaming\n // output matches buffered per RESEARCH §A7 caveat: parallel_tool_calls is supported but\n // disabled by default; the quirk flag reflects that the feature exists).\n quirks: {\n supportsToolChoice: true,\n parallelToolCalls: true,\n structuredOutputs: true,\n responseFormatHonored: true,\n streamingDiverges: false,\n strictModeSupported: true,\n structuredOutputsTier2: true,\n } satisfies OpenAIQuirks,\n negotiateCapabilities: negotiate,\n };\n}\n\nexport function createAISdkProvider(options: SdkLikeProviderOptions): ProviderAdapter {\n const id = options.id ?? \"ai-sdk\";\n\n return {\n id,\n kind: \"provider-adapter\",\n capabilities: [\n {\n ...defaultCapabilityForProvider(id),\n modelId: options.model,\n toolUse: true,\n streaming: true,\n },\n ],\n execute: async (request) => {\n const response = await options.generate({\n task: request.task,\n outputNames: request.outputs,\n });\n const normalizedUsage: Usage = {\n promptTokens: response.usage?.inputTokens ?? 0,\n completionTokens: response.usage?.outputTokens ?? 0,\n costUsd: null,\n };\n return { ...response, normalizedUsage };\n },\n };\n}\n","import type { UsageRecord } from \"../plan/plan.js\";\nimport type { ProviderAdapter, ProviderRunResponse, Usage } from \"./provider.js\";\nimport type { AnthropicQuirks } from \"./quirks.js\";\nimport type { NegotiatedCapabilities } from \"../capabilities/negotiate.js\";\nimport type { RunEventSink } from \"../tracing/tracing.js\";\nimport { defaultCapabilityForProvider } from \"../routing/catalog.js\";\nimport { NegotiationAuthError, synthesizeNegotiatedCapabilitiesFromRegistry } from \"../capabilities/negotiate.js\";\nimport { getCapabilityProfile } from \"../capabilities/lookup.js\";\nimport { getRecommendedSanitizers } from \"../capabilities/sanitizer-recommendations.js\";\nimport { createRunEvent } from \"../tracing/tracing.js\";\nimport { parseToolUseEnvelope } from \"../agent/format-tools.js\";\nimport {\n validateToolCallRequests,\n type ValidateToolCallsOption,\n} from \"../tools/tool-call-validation.js\";\nimport {\n applyOutputSanitizers,\n type SanitizeOutputOption,\n} from \"../sanitizers/index.js\";\n\n/**\n * Options for {@link createAnthropicProvider}.\n *\n * Mirrors `OpenAICompatibleProviderOptions` ergonomics (Phase 7 pattern) but\n * for the Anthropic Messages API at `/v1/messages` -- which uses a top-level\n * `system` field and a `content[0].text` response shape that diverges from\n * the OpenAI Chat Completions schema (see FSB v0.9.x `extension/ai/universal-provider.js`\n * lines 280-297 + 566-573 for the production reference).\n *\n * SECURITY: `apiKey` is a runtime parameter -- do NOT hardcode or log it.\n *\n * DEFERRED (Phase 4 carryforward notes):\n * - prompt caching (Phase 39: opt-in via `ProviderRunRequest.cacheSystemPrefix` —\n * emitted as a cache_control-marked system block when present)\n * - streaming (deferred; this adapter is single-shot Promise -- per CONTEXT.md D-06)\n * - tool use (Anthropic tool_use blocks are deferred)\n * - resume-from-eviction -- see Phase 5 (MV3-survivability adapter contract)\n *\n * Ref: FSB v0.10.0-attempt-2 Phase 4 (D-02 + D-07: full custom adapter; preserve top-level `system`).\n */\nexport interface AnthropicProviderOptions {\n readonly id?: string;\n readonly model: string;\n readonly apiKey: string;\n /** Defaults to `https://api.anthropic.com`. Override for proxies. */\n readonly baseUrl?: string;\n /** Defaults to `2023-06-01`. Override only if the consumer has tested a newer pinned version. */\n readonly anthropicVersion?: string;\n readonly fetch?: typeof fetch;\n readonly pricing?: {\n readonly inputPer1kTokens?: number;\n readonly outputPer1kTokens?: number;\n };\n /**\n * D-08: Per-instance TTL for the /v1/models response cache (milliseconds).\n * Default 300_000 (5 minutes). `0` disables caching (always re-fetch -- for testing).\n * `Infinity` disables expiry (process-lifetime for the instance).\n */\n readonly modelsCacheTtlMs?: number;\n /**\n * D-11: Number of retries for transient /v1/models fetch failures (5xx, network,\n * timeout). Default 2 (3 total attempts). `0` disables retries.\n * Backoff schedule: [0ms, 200ms, 1000ms].\n */\n readonly modelsRetryCount?: number;\n /**\n * D-12: Optional RunEventSink for emitting `capabilities.negotiation.fallback`\n * events when the /v1/models fetch falls back to the Phase 33 static registry.\n * If absent, fallback emits no event (no-op). Auth errors (401/403) never emit\n * the fallback event -- they throw `NegotiationAuthError` instead.\n */\n readonly runEventSink?: RunEventSink;\n readonly sanitizeOutput?: SanitizeOutputOption;\n readonly validateToolCalls?: ValidateToolCallsOption;\n}\n\n/** Internal TTL cache entry shape (D-07 lazy-expiry). */\ninterface CacheEntry {\n readonly result: NegotiatedCapabilities;\n /** Date.now() + ttlMs; Infinity when ttlMs === Infinity */\n readonly expiresAt: number;\n}\n\nconst DEFAULT_BASE_URL = \"https://api.anthropic.com\";\nconst DEFAULT_ANTHROPIC_VERSION = \"2023-06-01\";\nconst DEFAULT_MAX_TOKENS = 2000;\nconst DEFAULT_MODELS_CACHE_TTL_MS = 300_000;\nconst DEFAULT_MODELS_RETRY_COUNT = 2;\n/** D-11: Backoff schedule for transient /v1/models failures -- immediate, 200ms, 1s. */\nconst MODELS_BACKOFF_MS = [0, 200, 1000] as const;\n\nexport function createAnthropicProvider(options: AnthropicProviderOptions): ProviderAdapter & {\n readonly quirks: AnthropicQuirks;\n readonly negotiateCapabilities: (modelId: string) => Promise<NegotiatedCapabilities>;\n} {\n const id = options.id ?? \"anthropic\";\n const fetchImpl = options.fetch ?? fetch;\n const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/u, \"\");\n const anthropicVersion = options.anthropicVersion ?? DEFAULT_ANTHROPIC_VERSION;\n\n // D-08: TTL cache configuration\n const ttlMs = options.modelsCacheTtlMs ?? DEFAULT_MODELS_CACHE_TTL_MS;\n // D-11: Retry count (0 = no retries, so attempts = 1)\n const retryCount = options.modelsRetryCount ?? DEFAULT_MODELS_RETRY_COUNT;\n\n // D-05 / D-06: Per-instance Maps; each createAnthropicProvider() call gets its own.\n const cache = new Map<string, CacheEntry>();\n const inflight = new Map<string, Promise<NegotiatedCapabilities>>();\n\n /**\n * D-12: Emits the `capabilities.negotiation.fallback` RunEvent via the\n * consumer-supplied sink. If no sink is provided, this is a no-op.\n *\n * SECURITY (T-34-02-01): errorReason is derived from `err.message` ONLY --\n * not `err.stack`, `err.toString()`, or any serialization that could include\n * request headers (which carry the apiKey). `stringifyErr` enforces this.\n *\n * JSDoc synthetic runId: negotiate() runs outside of a Lattice run context\n * (no ai.run() in scope). The runId `\"negotiate-${id}-${modelId}\"` is a\n * synthetic value that scopes the event to this adapter instance + modelId.\n * Consumers filtering on runId should treat \"negotiate-\" prefix as a signal\n * that this event originated from capability negotiation, not a user-facing run.\n */\n function emitFallbackEvent(payload: {\n adapter: string;\n modelId: string;\n errorReason: string;\n fallbackSource: \"registry-fallback\";\n }): void {\n if (options.runEventSink === undefined) return;\n const event = createRunEvent(\"capabilities.negotiation.fallback\", {\n runId: `negotiate-${id}-${payload.modelId}`,\n providerId: id,\n modelId: payload.modelId,\n metadata: {\n adapter: payload.adapter,\n modelId: payload.modelId,\n errorReason: payload.errorReason,\n fallbackSource: payload.fallbackSource,\n },\n });\n void options.runEventSink(event);\n }\n\n /**\n * Pure error message extractor. Returns `err.message` for Error instances,\n * `String(err)` for everything else. Deliberately does NOT include stack,\n * headers, or other fields (T-34-02-01 mitigation).\n */\n function stringifyErr(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n }\n\n /**\n * Merges a live /v1/models response body with the Phase 33 static registry\n * profile for the given modelId. Called on HTTP 200 responses only.\n *\n * LENIENT PARSING (Pitfall 1): every field access uses optional chaining.\n * Missing `capabilities.thinking` or other sub-fields default to false rather\n * than throwing. This ensures forward-compatibility with future API shape changes.\n *\n * contextWindow policy: Anthropic's max_input_tokens is set to 0 in the fixture\n * for models where it is unreliable. When 0, falls through to the registry profile's\n * contextWindow (if present) or 0 as a final default (RESEARCH §Q1).\n */\n function mergeAnthropicModelsWithRegistry(\n modelId: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n body: any,\n ): NegotiatedCapabilities {\n // Pitfall 1: lenient parse -- never crash on unexpected shapes\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n const found = body?.data?.find?.((m: unknown) => {\n if (typeof m !== \"object\" || m === null) return false;\n return (m as Record<string, unknown>)[\"id\"] === modelId;\n }) as Record<string, unknown> | undefined;\n\n if (found === undefined) {\n // Model not found in live response -- treat as registry-fallback\n // (200 received but this modelId isn't listed; signal to consumer that\n // something is off, per planner advisory in task spec).\n //\n // WR-04 (Phase 34 review): emit the fallback event here so consumers\n // observing the event stream can detect that an Anthropic model was\n // missing from a successful /v1/models response. Matches the OpenAI\n // (adapters.ts:362-366), Gemini, and OpenRouter behavior.\n emitFallbackEvent({\n adapter: \"anthropic\",\n modelId,\n errorReason: \"model not found in /v1/models response\",\n fallbackSource: \"registry-fallback\",\n });\n return synthesizeNegotiatedCapabilitiesFromRegistry(\"anthropic\", modelId, \"registry-fallback\");\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const caps = (found[\"capabilities\"] as Record<string, unknown> | undefined) ?? {};\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const structuredOutputsSupported = (caps[\"structured_outputs\"] as Record<string, unknown> | undefined)?.[\"supported\"] === true;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const thinkingSupported = (caps[\"thinking\"] as Record<string, unknown> | undefined)?.[\"supported\"] === true;\n\n // contextWindow: use max_input_tokens when > 0; fall through to registry profile\n const maxInputTokensRaw = found[\"max_input_tokens\"];\n const maxInputTokens = typeof maxInputTokensRaw === \"number\" && maxInputTokensRaw > 0\n ? maxInputTokensRaw\n : undefined;\n\n // Registry profile for contextWindow fallback + knownFailureModes\n const registryProfile = getCapabilityProfile(`anthropic:${modelId}`);\n const contextWindow = maxInputTokens ?? registryProfile?.contextWindow ?? 0;\n\n const knownFailureModes = registryProfile?.knownFailureModes ?? ([] as const);\n\n return {\n modelId,\n contextWindow,\n supports: {\n nativeToolCalling: true, // Anthropic tool_use is the reference implementation\n structuredOutputs: structuredOutputsSupported,\n parallelToolCalls: true, // Anthropic supports parallel tool calls per registry\n extendedThinking: thinkingSupported,\n streaming: true, // Anthropic native streaming\n },\n knownFailureModes,\n recommendedSanitizers: getRecommendedSanitizers(knownFailureModes),\n source: \"live\",\n };\n }\n\n /**\n * D-09 / D-10 / D-11: Core /v1/models fetch with retry-backoff, auth-error-throw,\n * and transient-fallback. Called only once per modelId (inflight coalescing prevents\n * concurrent duplicate fetches).\n *\n * URL shape: `${baseUrl}/v1/models?limit=1000` to page all models in one request.\n * Headers per RESEARCH §Q1: x-api-key, anthropic-version, accept.\n */\n async function fetchAndNegotiate(modelId: string): Promise<NegotiatedCapabilities> {\n const url = `${baseUrl}/v1/models?limit=1000`;\n const headers = {\n \"x-api-key\": options.apiKey,\n \"anthropic-version\": anthropicVersion,\n \"accept\": \"application/json\",\n };\n\n const attempts = retryCount + 1;\n let lastErr: unknown;\n\n for (let i = 0; i < attempts; i += 1) {\n const delayMs = MODELS_BACKOFF_MS[i] ?? MODELS_BACKOFF_MS[MODELS_BACKOFF_MS.length - 1]!;\n if (delayMs > 0) {\n await new Promise<void>((resolve) => setTimeout(resolve, delayMs));\n }\n\n try {\n const resp = await fetchImpl(url, {\n method: \"GET\",\n headers,\n signal: AbortSignal.timeout(30_000),\n });\n\n // D-10: auth errors throw immediately, never fall back, never retry\n // T-34-02-04: message does NOT include the actual apiKey value\n if (resp.status === 401 || resp.status === 403) {\n throw new NegotiationAuthError(\n \"anthropic\",\n modelId,\n resp.status as 401 | 403,\n `Anthropic /v1/models returned ${resp.status}: check apiKey config.`,\n );\n }\n\n if (!resp.ok) {\n throw new Error(`HTTP ${resp.status}`);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const body = await resp.json();\n return mergeAnthropicModelsWithRegistry(modelId, body);\n } catch (err) {\n // D-10: auth errors always propagate -- never retry, never fall back\n if (err instanceof NegotiationAuthError) throw err;\n lastErr = err;\n // Continue loop for transient errors (5xx, network, timeout)\n }\n }\n\n // D-09 + D-12: all retries exhausted -- fall back to Phase 33 registry + emit event\n emitFallbackEvent({\n adapter: \"anthropic\",\n modelId,\n errorReason: stringifyErr(lastErr),\n fallbackSource: \"registry-fallback\",\n });\n return synthesizeNegotiatedCapabilitiesFromRegistry(\"anthropic\", modelId, \"registry-fallback\");\n }\n\n /**\n * D-07: Lazy expiry cache check + D-Q7: inflight coalescing.\n *\n * Cache check: stale entries are evicted lazily on read (no background setInterval\n * -- library must not pin the Node event loop).\n *\n * Inflight coalescing: concurrent calls for the same modelId share one fetch\n * Promise. Pitfall 4 mitigation: `.finally` block ALWAYS clears the inflight\n * Map entry, even on rejection. This ensures that a rejected Promise doesn't\n * \"poison\" the Map -- the next caller after all concurrent calls settle will\n * trigger a fresh fetch attempt.\n */\n async function negotiateCapabilities(modelId: string): Promise<NegotiatedCapabilities> {\n // 1. D-07: lazy TTL expiry check\n const cached = cache.get(modelId);\n if (cached !== undefined && cached.expiresAt > Date.now()) {\n return cached.result;\n }\n\n // 2. Q7: inflight coalescing -- return existing Promise if one is in-flight\n const existing = inflight.get(modelId);\n if (existing !== undefined) return existing;\n\n // 3. Start a new fetch Promise; .finally cleanup guarantees Map clearing (Pitfall 4)\n const fetchPromise = (async () => {\n try {\n const result = await fetchAndNegotiate(modelId);\n // D-08: cache result when TTL > 0; Infinity disables expiry\n if (ttlMs > 0) {\n cache.set(modelId, {\n result,\n expiresAt: ttlMs === Infinity ? Infinity : Date.now() + ttlMs,\n });\n }\n return result;\n } finally {\n // Pitfall 4: ALWAYS remove from inflight Map -- even on rejection.\n // This prevents a failed fetch from permanently blocking future calls.\n inflight.delete(modelId);\n }\n })();\n\n inflight.set(modelId, fetchPromise);\n return fetchPromise;\n }\n\n return {\n id,\n kind: \"provider-adapter\",\n capabilities: [\n {\n ...defaultCapabilityForProvider(id),\n modelId: options.model,\n fileTransport: [\"inline\", \"json\", \"url\", \"base64\", \"extracted-text\", \"transcript\"],\n },\n ],\n /**\n * QUIRK-02: Anthropic adapter quirks block -- values verified against\n * Anthropic documentation and /v1/models capabilities field (RESEARCH §Q6/§Q1).\n *\n * Universal 5-boolean base (AdapterQuirks):\n * - supportsToolChoice: true -- tool_choice is supported per Anthropic tool use docs\n * - parallelToolCalls: true -- parallel tool calls verified in Anthropic tool_use spec\n * - structuredOutputs: true -- structured_outputs.supported in /v1/models capabilities block\n * - responseFormatHonored: true -- Anthropic honors response_format JSON schema strictly\n * - streamingDiverges: false -- Anthropic streaming output matches buffered output\n *\n * Anthropic-narrowed 3 fields (AnthropicQuirks):\n * - promptCachingSupported: true\n * CITED: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching\n * Cache_control on system and user turns GA on all active Claude models.\n * - extendedThinkingSupported: true\n * CITED: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking\n * Thinking blocks available via the \"thinking\" request parameter (claude-3-7-sonnet+,\n * claude-*-4 families). Verified via /v1/models capabilities.thinking.supported.\n * - toolUseInputSchemaStrict: true\n * CITED: https://docs.anthropic.com/en/docs/build-with-claude/tool-use\n * Anthropic tool_use blocks require strict JSON Schema in the input_schema field.\n */\n quirks: {\n supportsToolChoice: true,\n parallelToolCalls: true,\n structuredOutputs: true,\n responseFormatHonored: true,\n streamingDiverges: false,\n promptCachingSupported: true,\n extendedThinkingSupported: true,\n toolUseInputSchemaStrict: true,\n } satisfies AnthropicQuirks,\n negotiateCapabilities,\n async execute(request) {\n // Phase 39 (DELEG-04): opt-in prompt-cache prefix. When present, hoist\n // it to a `cache_control`-marked system content block — Anthropic prompt\n // caching is content-block-granular, so this is the shape that makes\n // cache hits structurally possible (Pitfall 1). When absent, keep\n // `system: \"\"` exactly so the request body stays byte-identical for all\n // existing callers (T-39-11). Conditional VALUE, not conditional spread:\n // the `system` key is always present per the Messages API contract (D-07).\n const system =\n request.cacheSystemPrefix !== undefined\n ? [\n {\n type: \"text\",\n text: request.cacheSystemPrefix,\n cache_control: { type: \"ephemeral\" },\n },\n ]\n : \"\";\n const init: RequestInit = {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-api-key\": options.apiKey,\n \"anthropic-version\": anthropicVersion,\n },\n body: JSON.stringify({\n model: options.model,\n // D-07: top-level `system` field PRESERVED (Anthropic Messages API\n // contract; NOT folded into the `messages` array).\n system,\n messages: [\n {\n role: \"user\",\n content: request.task,\n },\n ],\n max_tokens: DEFAULT_MAX_TOKENS,\n }),\n ...(request.signal !== undefined ? { signal: request.signal } : {}),\n };\n\n const response = await fetchImpl(`${baseUrl}/v1/messages`, init);\n\n if (!response.ok) {\n throw new Error(`Anthropic provider failed with ${response.status}.`);\n }\n\n const body = (await response.json()) as {\n content?: readonly { text?: unknown }[];\n usage?: unknown;\n };\n\n const text = String(body.content?.[0]?.text ?? \"\");\n const rawOutputs = Object.fromEntries(request.outputs.map((name) => [name, text]));\n const sanitizedOutputs = await applyOutputSanitizers(rawOutputs, options.sanitizeOutput, {\n providerId: id,\n modelId: options.model,\n });\n const parsedToolCalls = parseToolUseEnvelope(text);\n const toolCalls = parsedToolCalls === null\n ? undefined\n : await validateToolCallRequests(parsedToolCalls, options.validateToolCalls);\n const usage = normalizeAnthropicUsage(body.usage);\n const normalizedUsage = normalizeAnthropicUsageToRunUsage(body.usage, options.pricing);\n\n return {\n rawOutputs: sanitizedOutputs,\n ...(usage !== undefined ? { usage } : {}),\n normalizedUsage,\n ...(toolCalls !== undefined ? { toolCalls } : {}),\n rawResponse: body,\n };\n },\n };\n}\n\n/**\n * Anthropic uses `input_tokens` / `output_tokens` (not OpenAI's\n * `prompt_tokens` / `completion_tokens`). This helper maps to Lattice's\n * `Usage` shape and applies pricing when supplied (Phase 7 pattern).\n */\nfunction normalizeAnthropicUsageToRunUsage(\n rawUsage: unknown,\n pricing?: {\n readonly inputPer1kTokens?: number;\n readonly outputPer1kTokens?: number;\n },\n): Usage {\n let promptTokens = 0;\n let completionTokens = 0;\n if (typeof rawUsage === \"object\" && rawUsage !== null) {\n const record = rawUsage as Record<string, unknown>;\n promptTokens = numberField(record, \"input_tokens\") ?? numberField(record, \"inputTokens\") ?? 0;\n completionTokens =\n numberField(record, \"output_tokens\") ?? numberField(record, \"outputTokens\") ?? 0;\n }\n let costUsd: number | null = null;\n if (\n pricing !== undefined &&\n (pricing.inputPer1kTokens !== undefined || pricing.outputPer1kTokens !== undefined)\n ) {\n const inputCost = ((pricing.inputPer1kTokens ?? 0) * promptTokens) / 1000;\n const outputCost = ((pricing.outputPer1kTokens ?? 0) * completionTokens) / 1000;\n costUsd = inputCost + outputCost;\n }\n return { promptTokens, completionTokens, costUsd };\n}\n\nfunction normalizeAnthropicUsage(usage: unknown): UsageRecord | undefined {\n if (typeof usage !== \"object\" || usage === null) {\n return undefined;\n }\n const record = usage as Record<string, unknown>;\n const inputTokens = numberField(record, \"input_tokens\");\n const outputTokens = numberField(record, \"output_tokens\");\n const totalTokens =\n inputTokens !== undefined && outputTokens !== undefined\n ? inputTokens + outputTokens\n : undefined;\n return {\n ...(inputTokens !== undefined ? { inputTokens } : {}),\n ...(outputTokens !== undefined ? { outputTokens } : {}),\n ...(totalTokens !== undefined ? { totalTokens } : {}),\n };\n}\n\nfunction numberField(record: Record<string, unknown>, key: string): number | undefined {\n const value = record[key];\n return typeof value === \"number\" ? value : undefined;\n}\n","import type { ArtifactInput } from \"../artifacts/artifact.js\";\nimport type {\n ModelCapability,\n ProviderAdapter,\n ProviderRunRequest,\n ProviderRunResponse,\n Usage,\n} from \"./provider.js\";\nimport { defaultCapabilityForProvider } from \"../routing/catalog.js\";\n\nexport interface FakeProviderOptions {\n readonly id?: string;\n readonly modelId?: string;\n readonly response?:\n | ProviderRunResponse\n | ((request: ProviderRunRequest) => ProviderRunResponse | Promise<ProviderRunResponse>);\n readonly artifacts?: readonly ArtifactInput[];\n /**\n * Phase 7 addition: when provided, REPLACES the default single-capability\n * array so callers (notably Plan 07-04's modality/privacy reject tests)\n * can construct a fake adapter with arbitrary\n * `inputModalities` / `outputModalities` / `dataPolicy` / `pricing`\n * without mutating the returned adapter's readonly `capabilities` array.\n * When omitted, the existing default capability is used.\n */\n readonly capabilities?: readonly ModelCapability[];\n}\n\nconst DEFAULT_FAKE_USAGE: Usage = {\n promptTokens: 0,\n completionTokens: 0,\n costUsd: null,\n};\n\nexport function createFakeProvider(options: FakeProviderOptions = {}): ProviderAdapter {\n const id = options.id ?? \"fake\";\n const modelId = options.modelId ?? `${id}:deterministic`;\n const defaultCapability: ModelCapability = {\n ...defaultCapabilityForProvider(id),\n modelId,\n inputModalities: [\"text\", \"json\", \"image\", \"audio\", \"document\", \"file\", \"url\", \"tool\"],\n outputModalities: [\"text\", \"json\"],\n toolUse: true,\n };\n const capabilities = options.capabilities ?? [defaultCapability];\n\n return {\n id,\n kind: \"provider-adapter\",\n capabilities,\n async execute(request) {\n const baseResponse =\n typeof options.response === \"function\"\n ? await options.response(request)\n : options.response;\n\n if (baseResponse !== undefined) {\n return baseResponse.normalizedUsage !== undefined\n ? baseResponse\n : { ...baseResponse, normalizedUsage: { ...DEFAULT_FAKE_USAGE } };\n }\n\n return {\n rawOutputs: Object.fromEntries(\n request.outputs.map((name) => [name, defaultOutputForName(name)]),\n ),\n ...(options.artifacts !== undefined ? { artifactRefs: options.artifacts } : {}),\n normalizedUsage: { ...DEFAULT_FAKE_USAGE },\n };\n },\n };\n}\n\nfunction defaultOutputForName(name: string): unknown {\n if (/action|json|data|decision/u.test(name)) {\n return {\n kind: \"clarify\",\n reason: \"fake provider default structured response\",\n };\n }\n\n if (/citations|evidence/u.test(name)) {\n return [];\n }\n\n if (/generated|artifacts/u.test(name)) {\n return [];\n }\n\n return `Fake response for ${name}.`;\n}\n","import type { UsageRecord } from \"../plan/plan.js\";\nimport type { ProviderAdapter, ProviderRunResponse, Usage } from \"./provider.js\";\nimport { defaultCapabilityForProvider } from \"../routing/catalog.js\";\nimport type { GeminiQuirks } from \"./quirks.js\";\nimport type { NegotiatedCapabilities } from \"../capabilities/negotiate.js\";\nimport {\n NegotiationAuthError,\n synthesizeNegotiatedCapabilitiesFromRegistry,\n} from \"../capabilities/negotiate.js\";\nimport { getCapabilityProfile } from \"../capabilities/lookup.js\";\nimport { getRecommendedSanitizers } from \"../capabilities/sanitizer-recommendations.js\";\nimport type { RunEventSink } from \"../tracing/tracing.js\";\nimport { createRunEvent } from \"../tracing/tracing.js\";\nimport { parseToolUseEnvelope } from \"../agent/format-tools.js\";\nimport {\n validateToolCallRequests,\n type ValidateToolCallsOption,\n} from \"../tools/tool-call-validation.js\";\nimport {\n applyOutputSanitizers,\n type SanitizeOutputOption,\n} from \"../sanitizers/index.js\";\n\n/**\n * Options for {@link createGeminiProvider}.\n *\n * Mirrors `OpenAICompatibleProviderOptions` ergonomics (Phase 7 pattern) but\n * for Google's Generative Language API at\n * `/v1beta/models/{model}:generateContent` -- which uses `contents[].parts[].text`\n * (NOT OpenAI's `messages[]`), `role: \"model\"` for assistant turns (NOT\n * `\"assistant\"`), authenticates via `?key=` query string for execute(), and applies a\n * 4-category `safetySettings` block at `BLOCK_NONE` thresholds (FSB convention\n * mirrored from `extension/ai/universal-provider.js:255-272`).\n *\n * SECURITY: `apiKey` is a runtime parameter -- do NOT hardcode or log it.\n *\n * DEFERRED (Phase 4 carryforward notes):\n * - multimodal (vision) -- deferred\n * - streaming -- deferred (single-shot Promise per CONTEXT.md D-06)\n * - tool use -- deferred\n * - resume-from-eviction -- see Phase 5 (MV3-survivability adapter contract)\n *\n * NOTE (Phase 34): negotiate() uses x-goog-api-key HEADER (preferred per RESEARCH §Q3).\n * The existing execute() path uses ?key= query string -- execute() migration is out-of-scope\n * for Phase 34 (additive only; T-34-04-01).\n *\n * Ref: FSB v0.10.0-attempt-2 Phase 4 (D-02 + D-07: full custom adapter; preserve role:\"model\").\n */\nexport interface GeminiProviderOptions {\n readonly id?: string;\n readonly model: string;\n readonly apiKey: string;\n /** Defaults to `https://generativelanguage.googleapis.com`. */\n readonly baseUrl?: string;\n readonly fetch?: typeof fetch;\n readonly pricing?: {\n readonly inputPer1kTokens?: number;\n readonly outputPer1kTokens?: number;\n };\n /**\n * D-08: TTL for per-instance /models response cache, in milliseconds.\n * Default: 300_000ms (5 minutes). 0 = always refetch (tests). Infinity = process-lifetime.\n */\n readonly modelsCacheTtlMs?: number;\n /**\n * D-11: Number of retries on transient /models fetch errors. Default: 2.\n * Retry schedule: immediate + 200ms + 1000ms (3 total attempts at retryCount=2).\n * 0 = no retries (1 attempt total).\n */\n readonly modelsRetryCount?: number;\n /**\n * D-12: Optional event sink for observability. When provided, the adapter\n * emits a \"capabilities.negotiation.fallback\" RunEvent on transient /models failure.\n * If absent, no event is emitted (silent fallback).\n */\n readonly runEventSink?: RunEventSink;\n readonly sanitizeOutput?: SanitizeOutputOption;\n readonly validateToolCalls?: ValidateToolCallsOption;\n}\n\nconst DEFAULT_BASE_URL = \"https://generativelanguage.googleapis.com\";\nconst DEFAULT_MAX_OUTPUT_TOKENS = 2000;\nconst DEFAULT_TEMPERATURE = 0.7;\nconst DEFAULT_TOP_P = 0.9;\n\n/**\n * 4 HARM_CATEGORY entries at BLOCK_NONE (FSB convention mirrored from\n * `extension/ai/universal-provider.js:255-272`). If Google restricts\n * BLOCK_NONE in the future, that is a re-spec concern, not a Phase 4\n * design defect (CONTEXT.md Specific Ideas note).\n */\nconst SAFETY_SETTINGS = [\n { category: \"HARM_CATEGORY_HARASSMENT\", threshold: \"BLOCK_NONE\" },\n { category: \"HARM_CATEGORY_HATE_SPEECH\", threshold: \"BLOCK_NONE\" },\n { category: \"HARM_CATEGORY_SEXUALLY_EXPLICIT\", threshold: \"BLOCK_NONE\" },\n { category: \"HARM_CATEGORY_DANGEROUS_CONTENT\", threshold: \"BLOCK_NONE\" },\n] as const;\n\n/**\n * Phase 34 — D-03 — Gemini quirks block. Values verified against\n * Gemini API documentation and gemini.ts:50-55 (safety settings) behavior.\n *\n * CITED: https://ai.google.dev/api/generate-content#v1beta.GenerationConfig\n * - responseSchemaSupported: gemini-1.5-pro+ and gemini-2.x\n * - safetySettingsConfigurable: verified in gemini.ts:50-55\n * - systemInstructionSupported: gemini-1.5+ systemInstruction field\n */\nconst GEMINI_QUIRKS: GeminiQuirks = {\n supportsToolChoice: true,\n parallelToolCalls: true,\n structuredOutputs: true,\n responseFormatHonored: true,\n streamingDiverges: false,\n responseSchemaSupported: true, // CITED: Gemini API responseSchema/responseJsonSchema\n safetySettingsConfigurable: true, // VERIFIED: gemini.ts:50-55 4-category BLOCK_NONE\n systemInstructionSupported: true, // CITED: gemini-1.5+ supports system_instruction\n};\n\n/**\n * Phase 34 — D-03 / D-05..D-12 — Extended Gemini provider factory.\n *\n * Returns a `ProviderAdapter` narrowed to expose:\n * - `quirks: GeminiQuirks` — static adapter capability flags\n * - `negotiateCapabilities(modelId)` — live /v1beta/models fetch with medium-thick\n * derivation (inputTokenLimit + thinking + supportedGenerationMethods from upstream)\n * intersected with Phase 33 registry; TTL cache + inflight coalescing + retry +\n * auth-throw + transient-fallback + event.\n *\n * NOTE on auth strategy (T-34-04-01): negotiate() uses x-goog-api-key HEADER\n * (preferred per RESEARCH §Q3 -- avoids leaking the key in server-side logs that\n * capture URL query strings). The existing execute() path uses ?key= query string\n * and is NOT changed by Phase 34 (out-of-scope migration).\n */\nexport function createGeminiProvider(\n options: GeminiProviderOptions,\n): ProviderAdapter & {\n readonly quirks: GeminiQuirks;\n readonly negotiateCapabilities: (modelId: string) => Promise<NegotiatedCapabilities>;\n} {\n const id = options.id ?? \"gemini\";\n const fetchImpl = options.fetch ?? fetch;\n const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/u, \"\");\n\n // D-05/D-06: per-instance cache and inflight Maps. Live inside the closure so\n // each createGeminiProvider({}) call gets its own Map (no cross-contamination).\n const ttlMs = options.modelsCacheTtlMs ?? 300_000;\n const retryCount = options.modelsRetryCount ?? 2;\n const cache = new Map<string, { result: NegotiatedCapabilities; expiresAt: number }>();\n const inflight = new Map<string, Promise<NegotiatedCapabilities>>();\n\n /**\n * D-07 lazy expiry + Q7 inflight coalescing + Pitfall 4 .finally cleanup.\n * Public surface: `adapter.negotiateCapabilities(modelId)`.\n */\n async function negotiate(modelId: string): Promise<NegotiatedCapabilities> {\n // 1. Cache check (D-07 lazy expiry)\n const cached = cache.get(modelId);\n if (cached !== undefined && cached.expiresAt > Date.now()) return cached.result;\n\n // 2. Inflight coalesce (Q7)\n const existing = inflight.get(modelId);\n if (existing !== undefined) return existing;\n\n // 3. New fetch promise; clear inflight in .finally (Pitfall 4)\n const fetchPromise = (async () => {\n try {\n const result = await fetchAndNegotiate(modelId);\n if (ttlMs > 0) {\n cache.set(modelId, { result, expiresAt: Date.now() + ttlMs });\n }\n return result;\n } finally {\n inflight.delete(modelId);\n }\n })();\n\n inflight.set(modelId, fetchPromise);\n return fetchPromise;\n }\n\n /**\n * Phase 34 — D-09..D-11 — Fetches /v1beta/models and merges with registry.\n *\n * URL: ${baseUrl}/v1beta/models (NOT /v1/models -- Gemini uses /v1beta/ prefix)\n * Auth: x-goog-api-key HEADER (preferred per RESEARCH §Q3 -- NOT ?key= query-string;\n * avoids leaking the key in server-side log captures of request URLs).\n * Retry: [0ms, 200ms, 1000ms] backoff on transient errors (D-11).\n * Auth error (401/403): throws NegotiationAuthError (D-10, no fallback).\n * Transient error (5xx/network): falls back to registry with \"registry-fallback\" (D-09).\n */\n async function fetchAndNegotiate(modelId: string): Promise<NegotiatedCapabilities> {\n // NOTE: URL is /v1beta/models (not /v1/models -- Gemini API prefix differs from OpenAI)\n const url = `${baseUrl}/v1beta/models`;\n const headers: Record<string, string> = {\n // SECURITY: key sent as HEADER (x-goog-api-key), NOT as ?key= query-string.\n // RESEARCH §Q3: header form is preferred to avoid leaking the key in upstream logs.\n \"x-goog-api-key\": options.apiKey,\n \"accept\": \"application/json\",\n };\n\n const attempts = retryCount + 1;\n const backoffSchedule = [0, 200, 1000];\n let lastErr: unknown;\n\n for (let i = 0; i < attempts; i += 1) {\n const delay = backoffSchedule[i] ?? 1000;\n if (delay > 0) {\n await new Promise<void>((r) => setTimeout(r, delay));\n }\n try {\n const resp = await fetchImpl(url, {\n method: \"GET\",\n headers,\n signal: AbortSignal.timeout(30_000),\n });\n\n if (resp.status === 401 || resp.status === 403) {\n throw new NegotiationAuthError(\n \"gemini\",\n modelId,\n resp.status as 401 | 403,\n `Gemini /v1beta/models returned ${resp.status}: check apiKey config.`,\n );\n }\n\n if (!resp.ok) {\n throw new Error(`HTTP ${resp.status}`);\n }\n\n const body: unknown = await resp.json();\n return mergeGeminiModelsWithRegistry(modelId, body);\n } catch (err) {\n if (err instanceof NegotiationAuthError) throw err; // D-10: auth never falls back\n lastErr = err;\n }\n }\n\n // All retries exhausted -- fallback + event (D-09/D-12)\n emitFallbackEvent({\n adapter: \"gemini\",\n modelId,\n errorReason: stringifyErr(lastErr),\n fallbackSource: \"registry-fallback\",\n });\n return synthesizeNegotiatedCapabilitiesFromRegistry(\"gemini\", modelId, \"registry-fallback\");\n }\n\n /**\n * MEDIUM-THICK derivation: consumes upstream truth from Gemini /v1beta/models\n * where available (inputTokenLimit -> contextWindow, thinking -> extendedThinking,\n * supportedGenerationMethods -> streaming + nativeToolCalling) and falls back\n * to registry for the rest (knownFailureModes, recommendedSanitizers).\n *\n * Lenient parsing per Pitfall 1: all field accesses use optional chaining.\n * Missing `thinking` field does not crash -- defaults to false.\n */\n function mergeGeminiModelsWithRegistry(\n modelId: string,\n body: unknown,\n ): NegotiatedCapabilities {\n const models = (body as Record<string, unknown>)?.models;\n\n // Lenient model search: Gemini names are \"models/${id}\", base id, or exact name\n const found = Array.isArray(models)\n ? (models as unknown[]).find((m: unknown) => {\n const rec = m as Record<string, unknown>;\n return (\n rec?.name === `models/${modelId}` ||\n rec?.baseModelId === modelId ||\n rec?.name === modelId\n );\n })\n : undefined;\n\n if (found === undefined) {\n // Model not found in /models response -- treat as registry-fallback\n emitFallbackEvent({\n adapter: \"gemini\",\n modelId,\n errorReason: \"model not found in /v1beta/models response\",\n fallbackSource: \"registry-fallback\",\n });\n return synthesizeNegotiatedCapabilitiesFromRegistry(\"gemini\", modelId, \"registry-fallback\");\n }\n\n const foundRec = found as Record<string, unknown>;\n const registryProfile = getCapabilityProfile(`gemini:${modelId}`);\n\n // THICK derivation from upstream\n const contextWindow =\n typeof foundRec.inputTokenLimit === \"number\" && foundRec.inputTokenLimit > 0\n ? foundRec.inputTokenLimit\n : (registryProfile?.contextWindow ?? 0);\n\n // thinking field: THICK from upstream; missing field -> false (lenient parse)\n const extendedThinking =\n foundRec.thinking === true;\n\n // supportedGenerationMethods: THICK from upstream\n const methods = Array.isArray(foundRec.supportedGenerationMethods)\n ? (foundRec.supportedGenerationMethods as unknown[]).map(String)\n : [];\n const streaming = methods.includes(\"streamGenerateContent\");\n // nativeToolCalling: generateContent method indicates tools surface\n const nativeToolCalling = methods.includes(\"generateContent\") || methods.length > 0;\n\n // structuredOutputs and parallelToolCalls: from quirks-block-style adapter posture\n // (Gemini 1.5+ supports responseSchema; per-model truth lives in registry)\n const structuredOutputs = true; // quirks.responseSchemaSupported (adapter posture)\n const parallelToolCalls = true; // Gemini supports parallel tool calls\n\n const knownFailureModes = registryProfile?.knownFailureModes ?? [];\n const recommendedSanitizers = getRecommendedSanitizers(knownFailureModes);\n\n return {\n modelId,\n contextWindow,\n supports: {\n nativeToolCalling,\n structuredOutputs,\n parallelToolCalls,\n extendedThinking,\n streaming,\n },\n knownFailureModes,\n recommendedSanitizers,\n source: \"live\",\n };\n }\n\n /**\n * D-12: Emit capabilities.negotiation.fallback RunEvent via the optional sink.\n * SECURITY (T-34-04-02): stringifyErr extracts err.message only -- NOT err.stack\n * or JSON.stringify(headers), so the apiKey cannot leak into the event payload.\n * Synthetic runId pattern: negotiate happens outside a run; documented here.\n */\n function emitFallbackEvent(payload: {\n adapter: string;\n modelId: string;\n errorReason: string;\n fallbackSource: string;\n }): void {\n if (options.runEventSink === undefined) return;\n const event = createRunEvent(\"capabilities.negotiation.fallback\", {\n runId: `negotiate-gemini-${payload.modelId}`,\n providerId: id,\n modelId: payload.modelId,\n metadata: {\n adapter: payload.adapter,\n modelId: payload.modelId,\n errorReason: payload.errorReason,\n fallbackSource: payload.fallbackSource,\n },\n });\n void options.runEventSink(event);\n }\n\n return {\n id,\n kind: \"provider-adapter\",\n capabilities: [\n {\n ...defaultCapabilityForProvider(id),\n modelId: options.model,\n fileTransport: [\"inline\", \"json\", \"url\", \"base64\", \"extracted-text\", \"transcript\"],\n },\n ],\n quirks: GEMINI_QUIRKS,\n negotiateCapabilities: negotiate,\n async execute(request) {\n const init: RequestInit = {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n contents: [\n {\n role: \"user\",\n parts: [{ text: request.task }],\n },\n ],\n generationConfig: {\n temperature: DEFAULT_TEMPERATURE,\n topP: DEFAULT_TOP_P,\n maxOutputTokens: DEFAULT_MAX_OUTPUT_TOKENS,\n },\n safetySettings: SAFETY_SETTINGS,\n }),\n ...(request.signal !== undefined ? { signal: request.signal } : {}),\n };\n\n const url = `${baseUrl}/v1beta/models/${encodeURIComponent(options.model)}:generateContent?key=${encodeURIComponent(options.apiKey)}`;\n const response = await fetchImpl(url, init);\n\n if (!response.ok) {\n throw new Error(`Gemini provider failed with ${response.status}.`);\n }\n\n const body = (await response.json()) as {\n candidates?: readonly {\n content?: { parts?: readonly { text?: unknown }[] };\n }[];\n usageMetadata?: unknown;\n };\n\n if (!Array.isArray(body.candidates) || body.candidates.length === 0) {\n throw new Error(\"Gemini provider returned no candidates.\");\n }\n\n const text = String(body.candidates[0]?.content?.parts?.[0]?.text ?? \"\");\n const rawOutputs = Object.fromEntries(request.outputs.map((name) => [name, text]));\n const sanitizedOutputs = await applyOutputSanitizers(rawOutputs, options.sanitizeOutput, {\n providerId: id,\n modelId: options.model,\n });\n const parsedToolCalls = parseToolUseEnvelope(text);\n const toolCalls = parsedToolCalls === null\n ? undefined\n : await validateToolCallRequests(parsedToolCalls, options.validateToolCalls);\n const usage = normalizeGeminiUsage(body.usageMetadata);\n const normalizedUsage = normalizeGeminiUsageToRunUsage(body.usageMetadata, options.pricing);\n\n return {\n rawOutputs: sanitizedOutputs,\n ...(usage !== undefined ? { usage } : {}),\n normalizedUsage,\n ...(toolCalls !== undefined ? { toolCalls } : {}),\n rawResponse: body,\n };\n },\n };\n}\n\n/**\n * Gemini uses `usageMetadata.promptTokenCount` / `candidatesTokenCount` /\n * `totalTokenCount` (NOT OpenAI's `prompt_tokens` / `completion_tokens`).\n * This helper maps to Lattice's `Usage` shape and applies pricing when supplied.\n */\nfunction normalizeGeminiUsageToRunUsage(\n rawUsage: unknown,\n pricing?: {\n readonly inputPer1kTokens?: number;\n readonly outputPer1kTokens?: number;\n },\n): Usage {\n let promptTokens = 0;\n let completionTokens = 0;\n if (typeof rawUsage === \"object\" && rawUsage !== null) {\n const record = rawUsage as Record<string, unknown>;\n promptTokens = numberField(record, \"promptTokenCount\") ?? 0;\n completionTokens = numberField(record, \"candidatesTokenCount\") ?? 0;\n }\n let costUsd: number | null = null;\n if (\n pricing !== undefined &&\n (pricing.inputPer1kTokens !== undefined || pricing.outputPer1kTokens !== undefined)\n ) {\n const inputCost = ((pricing.inputPer1kTokens ?? 0) * promptTokens) / 1000;\n const outputCost = ((pricing.outputPer1kTokens ?? 0) * completionTokens) / 1000;\n costUsd = inputCost + outputCost;\n }\n return { promptTokens, completionTokens, costUsd };\n}\n\nfunction normalizeGeminiUsage(usage: unknown): UsageRecord | undefined {\n if (typeof usage !== \"object\" || usage === null) {\n return undefined;\n }\n const record = usage as Record<string, unknown>;\n const inputTokens = numberField(record, \"promptTokenCount\");\n const outputTokens = numberField(record, \"candidatesTokenCount\");\n const totalTokens = numberField(record, \"totalTokenCount\");\n return {\n ...(inputTokens !== undefined ? { inputTokens } : {}),\n ...(outputTokens !== undefined ? { outputTokens } : {}),\n ...(totalTokens !== undefined ? { totalTokens } : {}),\n };\n}\n\nfunction numberField(record: Record<string, unknown>, key: string): number | undefined {\n const value = record[key];\n return typeof value === \"number\" ? value : undefined;\n}\n\n/**\n * T-34-04-02: Returns err.message only -- NOT err.stack (which could include\n * headers or the apiKey via a fetch rejection), NOT JSON.stringify(err).\n */\nfunction stringifyErr(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n","import type { ProviderAdapter } from \"./provider.js\";\nimport type { LmStudioQuirks } from \"./quirks.js\";\nimport type { NegotiatedCapabilities } from \"../capabilities/negotiate.js\";\nimport { synthesizeNegotiatedCapabilitiesFromRegistry } from \"../capabilities/negotiate.js\";\nimport { createOpenAICompatibleProvider, type OpenAICompatibleProviderOptions } from \"./adapters.js\";\n\n/**\n * Options for {@link createLmStudioProvider}.\n *\n * Thin wrapper around {@link createOpenAICompatibleProvider} pinned to\n * LM Studio's default local server URL `http://localhost:1234/v1`. Wire\n * shape is OpenAI Chat Completions. LM Studio is no-auth by convention\n * (CD-03): `apiKey` is OPTIONAL; when omitted, the underlying factory\n * sends no `Authorization` header (see\n * `lattice/packages/lattice/src/providers/adapters.ts:53` for the\n * conditional auth-header wiring).\n *\n * Phase 34 additions:\n * - `modelsCacheTtlMs` -- Reserved for future /models discovery; LM Studio\n * currently has no remote /models endpoint. Accepted for option-bag\n * uniformity but NOT USED (D-04 intentional no-endpoint pattern).\n * - `runEventSink` -- Accepted for option-bag uniformity but NEVER fired\n * because source: \"registry\" is the documented happy path for LM Studio\n * (no event for intentional no-endpoint per RESEARCH Open Question 5).\n *\n * DEFERRED (D-16 carryforward):\n * - latency-tail diagnostics -- observability concern; LM Studio is\n * the canary for latency tails (INV-03);\n * diagnostics module deferred to a\n * follow-on observability phase.\n * - streaming -- deferred (single-shot per D-06).\n * - resume-from-eviction -- see Phase 5 (MV3-survivability adapter).\n *\n * Ref: FSB v0.10.0-attempt-2 Phase 4 (D-03: thin wrapper; D-16: latency-tail deferred; CD-03 no-opt-out).\n */\nexport interface LmStudioProviderOptions\n extends Omit<OpenAICompatibleProviderOptions, \"id\" | \"baseUrl\" | \"apiKey\"> {\n readonly id?: string;\n /** Defaults to `http://localhost:1234/v1`. Override for non-localhost deployments. */\n readonly baseUrl?: string;\n /**\n * Optional. LM Studio is no-auth by convention (CD-03 default).\n * When provided, sent as `Authorization: Bearer <apiKey>` (matches the\n * underlying OpenAI-compat factory). Use only for proxied LM Studio\n * deployments that have a token gate in front.\n */\n readonly apiKey?: string;\n}\n\nconst DEFAULT_LM_STUDIO_BASE_URL = \"http://localhost:1234/v1\";\n\n/**\n * Phase 34 — D-04 / QUIRK-02 — LM Studio provider factory.\n *\n * LM Studio is the prototypical \"intentional no remote /models endpoint\"\n * adapter per D-04 (alongside OpenAI-compat). The factory returns conservative\n * defaults for the quirks block because LM Studio runs LOCAL quantized models\n * whose capabilities vary wildly by chat template + model file.\n *\n * The `negotiateCapabilities` method performs NO fetch; it returns\n * `synthesizeNegotiatedCapabilitiesFromRegistry` with source: \"registry\"\n * (the intentional-no-endpoint signal, distinct from \"registry-fallback\"\n * which signals a transient failure). Mirrors Plan 34-03 Task 2 (OpenAI-compat\n * registry-only pattern) verbatim.\n *\n * D-04 citation: \"consumer adapters without a /models endpoint skip the\n * fetch layer entirely and delegate to synthesizeNegotiatedCapabilitiesFromRegistry.\"\n *\n * Open Question 5 (RESEARCH §): no event emitted for source: \"registry\" because\n * this is the intentional happy path for LM Studio -- emitting a \"fallback\" event\n * would produce false-positive noise for consumers monitoring the event stream.\n */\nexport function createLmStudioProvider(\n options: LmStudioProviderOptions,\n): ProviderAdapter & {\n readonly quirks: LmStudioQuirks;\n readonly negotiateCapabilities: (modelId: string) => Promise<NegotiatedCapabilities>;\n} {\n const resolvedId = options.id ?? \"lm-studio\";\n const resolvedBaseUrl = options.baseUrl ?? DEFAULT_LM_STUDIO_BASE_URL;\n\n // Phase 34 — D-04 — LM Studio negotiate() is registry-only.\n // No fetch, no cache, no inflight coalescing, no event emission.\n // Source: \"registry\" signals intentional no-endpoint (per D-04).\n // Open Question 5: no event emitted for source: \"registry\" (intentional no-endpoint).\n const negotiate = async (modelId: string): Promise<NegotiatedCapabilities> => {\n return synthesizeNegotiatedCapabilitiesFromRegistry(\"lm-studio\", modelId, \"registry\");\n };\n\n // Delegate execute() and capabilities to the OpenAI-compat factory.\n const inner = createOpenAICompatibleProvider({\n ...options,\n id: resolvedId,\n baseUrl: resolvedBaseUrl,\n });\n\n return {\n ...inner,\n // Phase 34 — QUIRK-02 / LmStudioQuirks — conservative defaults.\n // LM Studio runs LOCAL quantized models whose capabilities vary wildly\n // by chat template + model file. Conservative false values for all 5\n // universal booleans. streamingDiverges: true because some LM Studio\n // chat templates produce different output streaming vs buffered.\n //\n // CITED: lmstudio-bug-tracker issue 1342 -- Jinja template mismatches\n // between model training and LM Studio server defaults cause output\n // format corruption -> customChatTemplateRiskFlag: true\n // VERIFIED: lm-studio.ts apiKey is optional (CD-03) ->\n // noAuthRequired: true (no auth needed for local localhost:1234 server)\n quirks: {\n supportsToolChoice: false,\n parallelToolCalls: false,\n structuredOutputs: false,\n responseFormatHonored: false,\n streamingDiverges: true,\n customChatTemplateRiskFlag: true,\n noAuthRequired: true,\n } satisfies LmStudioQuirks,\n negotiateCapabilities: negotiate,\n };\n}\n","import type { ProviderAdapter } from \"./provider.js\";\nimport { createOpenAICompatibleProvider, type OpenAICompatibleProviderOptions } from \"./adapters.js\";\nimport type { OpenRouterQuirks } from \"./quirks.js\";\nimport type { NegotiatedCapabilities } from \"../capabilities/negotiate.js\";\nimport {\n NegotiationAuthError,\n synthesizeNegotiatedCapabilitiesFromRegistry,\n} from \"../capabilities/negotiate.js\";\nimport { getCapabilityProfile, stripOpenRouterVariant } from \"../capabilities/lookup.js\";\nimport { getRecommendedSanitizers } from \"../capabilities/sanitizer-recommendations.js\";\nimport type { RunEventSink } from \"../tracing/tracing.js\";\nimport { createRunEvent } from \"../tracing/tracing.js\";\n\n/**\n * Options for {@link createOpenRouterProvider}.\n *\n * Thin wrapper around {@link createOpenAICompatibleProvider} pinned to\n * OpenRouter's base URL `https://openrouter.ai/api/v1`. Wire shape is\n * OpenAI Chat Completions; no provider-specific quirks at the\n * single-shot Promise contract level.\n *\n * SECURITY: `apiKey` is a runtime parameter -- do NOT hardcode or log it.\n *\n * DEFERRED (D-17 carryforward; Phase 4 ships the named adapter as a\n * first-class OpenAI-compat wrapper):\n * - model-routing array -- caller supplies `model` (single id); OpenRouter's\n * `models: [primary, fallback, ...]` array\n * feature is deferred to a follow-on phase.\n * - fallback-array -- deferred (same phase as model-routing).\n * - per-message routing -- deferred.\n * - streaming -- deferred (single-shot per CONTEXT.md D-06).\n * - resume-from-eviction -- see Phase 5 (MV3-survivability adapter).\n *\n * Ref: FSB v0.10.0-attempt-2 Phase 4 (D-03: thin wrapper; D-17: model-routing deferred).\n */\nexport interface OpenRouterProviderOptions\n extends Omit<OpenAICompatibleProviderOptions, \"id\" | \"baseUrl\"> {\n readonly id?: string;\n /** Defaults to `https://openrouter.ai/api/v1`. Override for proxies. */\n readonly baseUrl?: string;\n /**\n * D-08: TTL for per-instance /models response cache, in milliseconds.\n * Default: 300_000ms (5 minutes). 0 = always refetch (tests). Infinity = process-lifetime.\n */\n readonly modelsCacheTtlMs?: number;\n /**\n * D-11: Number of retries on transient /models fetch errors. Default: 2.\n * Retry schedule: immediate + 200ms + 1000ms (3 total attempts at retryCount=2).\n * 0 = no retries (1 attempt total).\n */\n readonly modelsRetryCount?: number;\n /**\n * D-12: Optional event sink for observability. When provided, the adapter\n * emits a \"capabilities.negotiation.fallback\" RunEvent on transient /models failure.\n * If absent, no event is emitted (silent fallback).\n */\n readonly runEventSink?: RunEventSink;\n}\n\nconst DEFAULT_OPENROUTER_BASE_URL = \"https://openrouter.ai/api/v1\";\n\n/**\n * Phase 34 — D-03 — OpenRouter quirks block. Values verified against\n * OpenRouter API documentation and observed behavior.\n *\n * CITED: https://openrouter.ai/docs/provider-routing\n * - providerRoutingArraySupported: provider.order/only/ignore arrays for explicit routing\n * CITED: https://openrouter.ai/docs pricing / sort options\n * - floorPricingHints: max_price, sort: \"throughput\" | \"price\" hints for cost-aware routing\n * CITED: https://openrouter.ai/docs allow_fallbacks\n * - allowFallbacks: provider.allow_fallbacks boolean controls upstream-provider fallback behavior\n */\nconst OPENROUTER_QUIRKS: OpenRouterQuirks = {\n supportsToolChoice: true,\n parallelToolCalls: true,\n structuredOutputs: true,\n responseFormatHonored: true,\n streamingDiverges: false,\n providerRoutingArraySupported: true, // CITED: openrouter.ai/docs provider routing order/only/ignore\n floorPricingHints: true, // CITED: openrouter.ai/docs max_price / sort: \"throughput\" | \"price\"\n allowFallbacks: true, // CITED: openrouter.ai/docs allow_fallbacks boolean\n};\n\n/**\n * Phase 34 — D-03 / D-05..D-12 — Extended OpenRouter provider factory.\n *\n * Returns a `ProviderAdapter` narrowed to expose:\n * - `quirks: OpenRouterQuirks` — static adapter capability flags (8 booleans)\n * - `negotiateCapabilities(modelId)` — live /api/v1/models fetch with rich /models\n * intersection (supported_parameters -> nativeToolCalling + structuredOutputs,\n * top_provider.context_length -> contextWindow) intersected with Phase 33 registry\n * for knownFailureModes + recommendedSanitizers.\n *\n * CRITICAL for ANCHOR CASE STUDY (session_1780792387779):\n * negotiate(\"openai/gpt-oss-120b:free\") MUST resolve to:\n * - result.knownFailureModes.includes(\"internal_envelope_leak\") -> TRUE\n * - result.recommendedSanitizers.includes(\"unwrapInternalEnvelope\") -> TRUE\n * - result.source === \"live\" -> TRUE\n * This proves: live-fetch -> id suffix-strip via stripOpenRouterVariant\n * -> registry intersection -> getRecommendedSanitizers derivation.\n *\n * Anti-pattern (RESEARCH §Anti-pattern, lines 534-535):\n * The /api/v1/models endpoint is UNAUTHENTICATED (public discovery surface verified\n * Phase 33). Do NOT send Authorization Bearer to this endpoint -- it is NOT required\n * and would add unnecessary API key exposure surface in transit logs.\n */\nexport function createOpenRouterProvider(\n options: OpenRouterProviderOptions,\n): ProviderAdapter & {\n readonly quirks: OpenRouterQuirks;\n readonly negotiateCapabilities: (modelId: string) => Promise<NegotiatedCapabilities>;\n} {\n const baseUrl = (options.baseUrl ?? DEFAULT_OPENROUTER_BASE_URL).replace(/\\/$/u, \"\");\n const fetchImpl = options.fetch ?? fetch;\n\n // D-05/D-06: per-instance cache and inflight Maps. Live inside the closure so\n // each createOpenRouterProvider({}) call gets its own Map (no cross-contamination).\n const ttlMs = options.modelsCacheTtlMs ?? 300_000;\n const retryCount = options.modelsRetryCount ?? 2;\n const cache = new Map<string, { result: NegotiatedCapabilities; expiresAt: number }>();\n const inflight = new Map<string, Promise<NegotiatedCapabilities>>();\n\n /**\n * D-07 lazy expiry + Q7 inflight coalescing + Pitfall 4 .finally cleanup.\n * Public surface: `adapter.negotiateCapabilities(modelId)`.\n */\n async function negotiate(modelId: string): Promise<NegotiatedCapabilities> {\n // 1. Cache check (D-07 lazy expiry)\n const cached = cache.get(modelId);\n if (cached !== undefined && cached.expiresAt > Date.now()) return cached.result;\n\n // 2. Inflight coalesce (Q7)\n const existing = inflight.get(modelId);\n if (existing !== undefined) return existing;\n\n // 3. New fetch promise; clear inflight in .finally (Pitfall 4)\n const fetchPromise = (async () => {\n try {\n const result = await fetchAndNegotiate(modelId);\n if (ttlMs > 0) {\n cache.set(modelId, { result, expiresAt: Date.now() + ttlMs });\n }\n return result;\n } finally {\n inflight.delete(modelId);\n }\n })();\n\n inflight.set(modelId, fetchPromise);\n return fetchPromise;\n }\n\n /**\n * Phase 34 — D-09..D-11 — Fetches /api/v1/models and merges with registry.\n *\n * URL: ${baseUrl}/api/v1/models (NOTE: /api/v1/models -- different prefix from\n * OpenAI's /v1/models; OpenRouter's discovery endpoint is under /api/v1/)\n * Auth: NONE -- OpenRouter /api/v1/models is a public unauthenticated endpoint.\n * Per RESEARCH §Anti-pattern (lines 534-535): do NOT send Authorization Bearer\n * to this endpoint. This is a known anti-pattern; do not \"fix\" it.\n * Retry: [0ms, 200ms, 1000ms] backoff on transient errors (D-11).\n * Auth error (401/403): throws NegotiationAuthError (D-10, no fallback) -- defensive,\n * even though the endpoint is unauthenticated today, OpenRouter may add auth later.\n * Transient error (5xx/network): falls back to registry with \"registry-fallback\" (D-09).\n */\n async function fetchAndNegotiate(modelId: string): Promise<NegotiatedCapabilities> {\n // NOTE: URL is /api/v1/models (NOT /v1/models -- OpenRouter uses /api/v1/ prefix)\n const url = `${baseUrl}/api/v1/models`;\n // Anti-pattern guard: NO Authorization header on this call.\n // RESEARCH §Anti-pattern (lines 534-535): OpenRouter /api/v1/models is unauthenticated.\n // Sending Bearer here would expose the API key unnecessarily.\n const headers: Record<string, string> = {\n \"accept\": \"application/json\",\n };\n\n const attempts = retryCount + 1;\n const backoffSchedule = [0, 200, 1000];\n let lastErr: unknown;\n\n for (let i = 0; i < attempts; i += 1) {\n const delay = backoffSchedule[i] ?? 1000;\n if (delay > 0) {\n await new Promise<void>((r) => setTimeout(r, delay));\n }\n try {\n const resp = await fetchImpl(url, {\n method: \"GET\",\n headers,\n signal: AbortSignal.timeout(30_000),\n });\n\n if (resp.status === 401 || resp.status === 403) {\n // Defensive: even though the endpoint is unauthenticated today, treat\n // auth errors as fatal per D-10 (same as other adapters)\n throw new NegotiationAuthError(\n \"openrouter\",\n modelId,\n resp.status as 401 | 403,\n `OpenRouter /api/v1/models returned ${resp.status}.`,\n );\n }\n\n if (!resp.ok) {\n throw new Error(`HTTP ${resp.status}`);\n }\n\n const body: unknown = await resp.json();\n return mergeOpenRouterModelsWithRegistry(modelId, body);\n } catch (err) {\n if (err instanceof NegotiationAuthError) throw err; // D-10: auth never falls back\n lastErr = err;\n }\n }\n\n // All retries exhausted -- fallback + event (D-09/D-12)\n emitFallbackEvent({\n adapter: \"openrouter\",\n modelId,\n errorReason: stringifyErr(lastErr),\n fallbackSource: \"registry-fallback\",\n });\n return synthesizeNegotiatedCapabilitiesFromRegistry(\"openrouter\", modelId, \"registry-fallback\");\n }\n\n /**\n * RICH /models intersection: consumes OpenRouter's /api/v1/models structured data\n * to populate NegotiatedCapabilities.supports.* from upstream (THICK derivation where\n * available), then intersects with Phase 33 registry for knownFailureModes +\n * recommendedSanitizers.\n *\n * ANCHOR CASE STUDY (session_1780792387779) flow:\n * 1. Find \"openai/gpt-oss-120b:free\" (or strip suffix -> \"openai/gpt-oss-120b\")\n * 2. Build canonical key: \"openrouter:openai/gpt-oss-120b\" (via stripOpenRouterVariant)\n * 3. getCapabilityProfile(\"openrouter:openai/gpt-oss-120b\") -> Phase 33 profile with\n * knownFailureModes: [\"internal_envelope_leak\", \"system_prompt_echo\", \"malformed_tool_arguments\"]\n * 4. getRecommendedSanitizers(knownFailureModes) -> [\"unwrapInternalEnvelope\"]\n * 5. result.recommendedSanitizers.includes(\"unwrapInternalEnvelope\") -> TRUE\n *\n * Pitfall 3 / A1 precedence chain (RESEARCH §Q5):\n * contextWindow = top_provider.context_length ?? context_length ?? registryProfile.contextWindow\n *\n * Lenient parsing per Pitfall 1: all field accesses use optional chaining.\n */\n function mergeOpenRouterModelsWithRegistry(\n modelId: string,\n body: unknown,\n ): NegotiatedCapabilities {\n const rows = (body as Record<string, unknown>)?.data;\n\n // Lenient model search: match by exact id OR by suffix-stripped id.\n // Also matches entries in /models whose id, when stripped, matches the canonical id.\n // Examples:\n // \"openai/gpt-oss-120b:free\" -> matches row with id \"openai/gpt-oss-120b:free\" (exact)\n // \"openai/gpt-oss-120b\" -> matches row with id \"openai/gpt-oss-120b\" (exact) OR\n // \"openai/gpt-oss-120b:free\" (strip then compare)\n const found = Array.isArray(rows)\n ? (rows as unknown[]).find((m: unknown) => {\n const rec = m as Record<string, unknown>;\n if (typeof rec?.id !== \"string\") return false;\n const rowId = rec.id;\n // Direct match or suffix-stripped modelId matches row id\n if (rowId === modelId || rowId === stripOpenRouterVariant(modelId)) return true;\n // Row's suffix-stripped id matches the stripped query id (handles base-form queries\n // against :free/:thinking variant rows in the /models response)\n const strippedModelId = stripOpenRouterVariant(modelId);\n const strippedRowId = stripOpenRouterVariant(rowId);\n return strippedRowId === strippedModelId;\n })\n : undefined;\n\n // Build canonical registry key using suffix-strip (D-11 via stripOpenRouterVariant from Phase 33)\n // \"openai/gpt-oss-120b:free\" -> \"openai/gpt-oss-120b\" -> \"openrouter:openai/gpt-oss-120b\"\n const stripped = stripOpenRouterVariant(modelId);\n const canonicalKey = `openrouter:${stripped}`;\n const registryProfile = getCapabilityProfile(canonicalKey);\n\n if (found === undefined) {\n // Model not found in /api/v1/models response -- treat as registry-fallback\n emitFallbackEvent({\n adapter: \"openrouter\",\n modelId,\n errorReason: \"model not found in /api/v1/models response\",\n fallbackSource: \"registry-fallback\",\n });\n // Still use registry intersection -- the registry may have the profile even\n // when /models didn't return it (Test 6 fallback case)\n return {\n ...synthesizeNegotiatedCapabilitiesFromRegistry(\"openrouter\", stripped, \"registry-fallback\"),\n // Preserve the input modelId verbatim (per Test 4 acceptance criterion)\n modelId,\n };\n }\n\n const foundRec = found as Record<string, unknown>;\n const topProvider = foundRec.top_provider as Record<string, unknown> | undefined;\n\n // Pitfall 3 / A1 precedence chain: prefer top_provider.context_length, then context_length,\n // then registry (RESEARCH §Q5 verified against live OpenRouter data)\n const contextWindow =\n typeof topProvider?.context_length === \"number\" && topProvider.context_length > 0\n ? topProvider.context_length\n : typeof foundRec.context_length === \"number\" && foundRec.context_length > 0\n ? foundRec.context_length\n : (registryProfile?.contextWindow ?? 0);\n\n // THICK derivation from supported_parameters (RESEARCH §Q5)\n const supportedParams = Array.isArray(foundRec.supported_parameters)\n ? (foundRec.supported_parameters as unknown[]).map(String)\n : [];\n\n const nativeToolCalling = supportedParams.includes(\"tools\");\n const structuredOutputs = supportedParams.includes(\"response_format\");\n // parallelToolCalls: heuristic -- tool_choice implies parallel tool support\n const parallelToolCalls = supportedParams.includes(\"tool_choice\");\n // extendedThinking: some OpenRouter rows expose reasoning or thinking parameter\n const extendedThinking =\n supportedParams.includes(\"reasoning\") || supportedParams.includes(\"thinking\");\n // streaming: OpenRouter supports streaming on virtually all models\n const streaming = true;\n\n // Registry intersection for failure modes + sanitizers (the ANCHOR CASE STUDY path)\n const knownFailureModes = registryProfile?.knownFailureModes ?? [];\n // getRecommendedSanitizers is the ONLY derivation path for recommendedSanitizers\n const recommendedSanitizers = getRecommendedSanitizers(knownFailureModes);\n\n return {\n // PRESERVE the input modelId verbatim (per Test 4 / anchor case study acceptance criteria)\n modelId,\n contextWindow,\n supports: {\n nativeToolCalling,\n structuredOutputs,\n parallelToolCalls,\n extendedThinking,\n streaming,\n },\n knownFailureModes,\n recommendedSanitizers,\n source: \"live\",\n };\n }\n\n /**\n * D-12: Emit capabilities.negotiation.fallback RunEvent via the optional sink.\n * SECURITY (T-34-04-02): stringifyErr extracts err.message only -- NOT err.stack\n * or JSON.stringify(headers), so the apiKey cannot leak into the event payload.\n * Synthetic runId pattern: negotiate happens outside a run; documented here.\n */\n function emitFallbackEvent(payload: {\n adapter: string;\n modelId: string;\n errorReason: string;\n fallbackSource: string;\n }): void {\n if (options.runEventSink === undefined) return;\n const event = createRunEvent(\"capabilities.negotiation.fallback\", {\n runId: `negotiate-openrouter-${payload.modelId}`,\n providerId: options.id ?? \"openrouter\",\n modelId: payload.modelId,\n metadata: {\n adapter: payload.adapter,\n modelId: payload.modelId,\n errorReason: payload.errorReason,\n fallbackSource: payload.fallbackSource,\n },\n });\n void options.runEventSink(event);\n }\n\n // Create the underlying OpenAI-compat execute() adapter for chat completions\n const baseAdapter = createOpenAICompatibleProvider({\n ...options,\n id: options.id ?? \"openrouter\",\n baseUrl,\n });\n\n return {\n ...baseAdapter,\n quirks: OPENROUTER_QUIRKS,\n negotiateCapabilities: negotiate,\n };\n}\n\n/**\n * T-34-04-02: Returns err.message only -- NOT err.stack (which could include\n * headers or the apiKey via a fetch rejection), NOT JSON.stringify(err).\n */\nfunction stringifyErr(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n","import type { ProviderAdapter } from \"./provider.js\";\nimport { createOpenAICompatibleProvider, type OpenAICompatibleProviderOptions } from \"./adapters.js\";\nimport type { XaiQuirks } from \"./quirks.js\";\nimport type { NegotiatedCapabilities } from \"../capabilities/negotiate.js\";\nimport {\n NegotiationAuthError,\n synthesizeNegotiatedCapabilitiesFromRegistry,\n _mapProfileToNegotiatedCapabilities,\n} from \"../capabilities/negotiate.js\";\nimport { getCapabilityProfile } from \"../capabilities/lookup.js\";\nimport type { RunEventSink } from \"../tracing/tracing.js\";\nimport { createRunEvent } from \"../tracing/tracing.js\";\n\n/**\n * Options for {@link createXaiProvider}.\n *\n * Thin wrapper around {@link createOpenAICompatibleProvider} pinned to\n * xAI's base URL `https://api.x.ai/v1`. The wire shape is identical to\n * OpenAI Chat Completions, with one provider-specific quirk preserved:\n * `response.usage.completion_tokens_details.reasoning_tokens` (xAI's\n * separate reasoning-token accounting; see FSB\n * `extension/ai/universal-provider.js:585-594` for the production reference).\n *\n * SECURITY: `apiKey` is a runtime parameter -- do NOT hardcode or log it.\n *\n * DEFERRED (Phase 4 carryforward notes):\n * - tool-streaming -- deferred\n * - streaming -- deferred (single-shot Promise per CONTEXT.md D-06)\n * - resume-from-eviction -- see Phase 5 (MV3-survivability adapter contract)\n *\n * Ref: FSB v0.10.0-attempt-2 Phase 4 (D-03 + D-07: thin wrapper; reasoning_tokens quirk preserved).\n *\n * Phase 34 additions:\n * - `modelsCacheTtlMs?` — D-05/D-06/D-08; default 300_000ms; 0 disables; Infinity = process-lifetime\n * - `modelsRetryCount?` — D-11; default 2; 0 disables retry\n * - `runEventSink?` — D-12; fires \"capabilities.negotiation.fallback\" on transient errors\n */\nexport interface XaiProviderOptions extends Omit<OpenAICompatibleProviderOptions, \"id\" | \"baseUrl\"> {\n readonly id?: string;\n /** Defaults to `https://api.x.ai/v1`. Override for proxies. */\n readonly baseUrl?: string;\n}\n\nconst DEFAULT_XAI_BASE_URL = \"https://api.x.ai/v1\";\n\n// ---------------------------------------------------------------------------\n// Internal helpers (mirroring Plan 34-02 Anthropic reference implementation)\n// ---------------------------------------------------------------------------\n\n/**\n * Phase 34 — D-12 — Emit a \"capabilities.negotiation.fallback\" RunEvent if\n * a sink is provided. Uses a synthetic runId (negotiation is outside a run).\n *\n * T-34-03-01: errorReason uses stringifyErr (message only, not stack) to\n * prevent apiKey leaking via fetch error strings that may embed request headers.\n */\nfunction emitFallbackEvent(\n sink: RunEventSink | undefined,\n payload: {\n readonly adapter: string;\n readonly modelId: string;\n readonly errorReason: string;\n readonly fallbackSource: \"registry-fallback\";\n },\n): void {\n if (sink === undefined) return;\n const event = createRunEvent(\"capabilities.negotiation.fallback\", {\n // Synthetic runId: negotiation happens outside a run context.\n // Pattern documented in Plan 34-02 (Anthropic reference impl).\n runId: `negotiate-${payload.adapter}-${payload.modelId}`,\n providerId: payload.adapter,\n modelId: payload.modelId,\n metadata: {\n adapter: payload.adapter,\n modelId: payload.modelId,\n errorReason: payload.errorReason,\n fallbackSource: payload.fallbackSource,\n },\n });\n void sink(event);\n}\n\n/**\n * Stringify an error for event metadata. Returns only the message (NOT the\n * stack) to prevent apiKey or sensitive header values from leaking into event\n * payloads via fetch errors that may embed the request init.\n * T-34-03-01 mitigation.\n */\nfunction stringifyErr(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Phase 34 — QUIRK-02 / NEG-01 / NEG-02 — Merge an xAI /v1/models sparse\n * OpenAI-shaped response with the Phase 33 registry.\n *\n * RESEARCH §A1 (INFERRED): xAI's /v1/models shape is undocumented; the\n * endpoint is assumed to return an OpenAI-compatible sparse list based on\n * the shared OpenAI-compat wire format used for chat completions.\n * LENIENT-PARSE is mandatory per Pitfall 1 (RESEARCH §Q4): if xAI changes\n * their response shape, the adapter must not crash.\n *\n * CITED: Pitfall 1 — \"When integrating with less-documented endpoints like\n * xAI's /v1/models, lenient parsing prevents runtime crashes when the\n * endpoint returns an unexpected shape.\"\n *\n * Source semantics per D-09:\n * - \"live\" when the model id is found in the response AND body.data is an array\n * - \"registry-fallback\" when body.data is not an array (unexpected shape)\n * OR when the model id is not in the response\n */\nfunction mergeXaiModelsWithRegistry(\n modelId: string,\n body: unknown,\n emitFallback: () => void,\n): NegotiatedCapabilities {\n // LENIENT-PARSE: body may be malformed or have an unexpected shape (Pitfall 1 + RESEARCH §A1).\n // If body.data is not an array, fall back to registry immediately without crashing.\n const rawData = (body as { data?: unknown } | null | undefined)?.data;\n if (!Array.isArray(rawData)) {\n // xAI body shape unexpected — emit fallback and use registry\n emitFallback();\n return synthesizeNegotiatedCapabilitiesFromRegistry(\"xai\", modelId, \"registry-fallback\");\n }\n\n const found = (rawData as Array<unknown>).find(\n (m): m is { id: string } =>\n typeof m === \"object\" && m !== null && (m as { id?: unknown }).id === modelId,\n );\n\n if (found === undefined) {\n // Model not in /models response — emit fallback and use registry.\n emitFallback();\n return synthesizeNegotiatedCapabilitiesFromRegistry(\"xai\", modelId, \"registry-fallback\");\n }\n\n // Model found in /models response — source supports.* from registry profile.\n // xAI /models is sparse (OpenAI-shaped: id, object, created, owned_by only);\n // no capabilities block. Source supports.* from the Phase 33 registry instead.\n const registryProfile = getCapabilityProfile(`xai:${modelId}`);\n if (registryProfile !== undefined) {\n return _mapProfileToNegotiatedCapabilities(registryProfile, \"live\");\n }\n\n // Model exists in org per /models but Phase 33 registry doesn't have it.\n // Use registry-fallback (no capability data available).\n return synthesizeNegotiatedCapabilitiesFromRegistry(\"xai\", modelId, \"registry-fallback\");\n}\n\n/**\n * Phase 34 — QUIRK-02 / NEG-01 / NEG-02 — xAI provider factory.\n *\n * Extends the base OpenAI-compat execution wrapper with:\n * 1. `quirks: XaiQuirks` — verified per RESEARCH §Q6 xAI vocabulary.\n * 2. `negotiateCapabilities(modelId)` — queries xAI /v1/models GET with\n * Authorization: Bearer header; LENIENT-PARSE sparse OpenAI-shaped\n * response; intersects with Phase 33 registry for supports.*.\n *\n * CITED: RESEARCH §Q4 (INFERRED) — xAI /v1/models shape is undocumented;\n * assumed OpenAI-compatible based on the chat completions wire format.\n *\n * CITED: RESEARCH §A1 — Pitfall 1 lenient parse: if xAI publishes a\n * different /models shape, only the parsing logic updates; the contract\n * (source values, NegotiatedCapabilities shape) holds.\n *\n * The negotiate() pattern mirrors Plan 34-02 (Anthropic thick reference):\n * - Per-instance TTL cache (modelsCacheTtlMs, default 300_000ms)\n * - Single-flight inflight coalescing with .finally cleanup (Pitfall 4)\n * - Retry with [0, 200, 1000]ms backoff (modelsRetryCount, default 2)\n * - 401/403 throws NegotiationAuthError with adapter: \"xai\" (D-10)\n * - 5xx/network/timeout falls back to registry + emits fallback event\n *\n * SECURITY (T-34-03-07): inflight Map MUST use .finally cleanup to prevent\n * leak on rejection. Verifiable: grep `.finally` in this file.\n */\nexport function createXaiProvider(\n options: XaiProviderOptions,\n): ProviderAdapter & {\n readonly quirks: XaiQuirks;\n readonly negotiateCapabilities: (modelId: string) => Promise<NegotiatedCapabilities>;\n} {\n const resolvedBaseUrl = (options.baseUrl ?? DEFAULT_XAI_BASE_URL).replace(/\\/$/u, \"\");\n const ttlMs = options.modelsCacheTtlMs ?? 300_000;\n const retryCount = options.modelsRetryCount ?? 2;\n const fetchImpl = options.fetch ?? fetch;\n\n // Per-instance TTL cache (D-05/D-06/D-07/D-08). One Map per factory call.\n const cache = new Map<string, { result: NegotiatedCapabilities; expiresAt: number }>();\n // Per-instance inflight coalescing Map (Q7). .finally cleanup is mandatory (Pitfall 4).\n const inflight = new Map<string, Promise<NegotiatedCapabilities>>();\n\n async function fetchAndNegotiate(modelId: string): Promise<NegotiatedCapabilities> {\n // For xAI, the baseUrl already includes \"/v1\" (default: https://api.x.ai/v1),\n // so we append \"/models\" not \"/v1/models\". This produces: https://api.x.ai/v1/models.\n const url = `${resolvedBaseUrl}/models`;\n // IN-02: omit Authorization entirely when apiKey is undefined; sending\n // \"Bearer \" literal would trigger noisy 401s and intrusion-detection flags.\n // Mirrors the OpenAI-compat execute path (adapters.ts:137).\n const headers: Record<string, string> = {\n \"accept\": \"application/json\",\n ...(options.apiKey !== undefined ? { authorization: `Bearer ${options.apiKey}` } : {}),\n };\n const attempts = retryCount + 1;\n const backoffMs = [0, 200, 1000];\n let lastErr: unknown;\n for (let i = 0; i < attempts; i += 1) {\n if (i > 0) {\n const delay = backoffMs[Math.min(i, backoffMs.length - 1)] ?? 1000;\n await new Promise<void>((r) => setTimeout(r, delay));\n }\n try {\n const resp = await fetchImpl(url, {\n method: \"GET\",\n headers,\n signal: AbortSignal.timeout(30_000),\n });\n if (resp.status === 401 || resp.status === 403) {\n throw new NegotiationAuthError(\n \"xai\",\n modelId,\n resp.status as 401 | 403,\n `xAI /v1/models returned ${resp.status}: check apiKey config.`,\n );\n }\n if (!resp.ok) {\n throw new Error(`HTTP ${resp.status}`);\n }\n const body = await resp.json() as unknown;\n return mergeXaiModelsWithRegistry(modelId, body, () => {\n emitFallbackEvent(options.runEventSink, {\n adapter: \"xai\",\n modelId,\n errorReason: \"model not found in /v1/models response or unexpected body shape\",\n fallbackSource: \"registry-fallback\",\n });\n });\n } catch (err) {\n if (err instanceof NegotiationAuthError) throw err; // D-10: auth never retries\n lastErr = err;\n }\n }\n // All retries exhausted — transient fallback + event.\n emitFallbackEvent(options.runEventSink, {\n adapter: \"xai\",\n modelId,\n errorReason: stringifyErr(lastErr),\n fallbackSource: \"registry-fallback\",\n });\n return synthesizeNegotiatedCapabilitiesFromRegistry(\"xai\", modelId, \"registry-fallback\");\n }\n\n async function negotiate(modelId: string): Promise<NegotiatedCapabilities> {\n // 1. Cache check (D-07 lazy expiry).\n const cached = cache.get(modelId);\n if (cached !== undefined && cached.expiresAt > Date.now()) return cached.result;\n\n // 2. Inflight coalesce (Q7).\n const existing = inflight.get(modelId);\n if (existing !== undefined) return existing;\n\n // 3. New fetch promise; clear inflight in .finally (Pitfall 4).\n const fetchPromise = (async () => {\n try {\n const result = await fetchAndNegotiate(modelId);\n if (ttlMs > 0) {\n cache.set(modelId, { result, expiresAt: Date.now() + ttlMs });\n }\n return result;\n } finally {\n inflight.delete(modelId);\n }\n })();\n inflight.set(modelId, fetchPromise);\n return fetchPromise;\n }\n\n const inner = createOpenAICompatibleProvider({\n ...options,\n id: options.id ?? \"xai\",\n baseUrl: resolvedBaseUrl,\n });\n const innerExecute = inner.execute;\n\n // Wrap the execute function to add xAI reasoning_tokens quirk preservation (D-07).\n const wrappedExecute =\n innerExecute === undefined\n ? undefined\n : async (request: Parameters<typeof innerExecute>[0]) => {\n const response = await innerExecute(request);\n // D-07: PRESERVE xAI's `completion_tokens_details.reasoning_tokens`\n // quirk. The default OpenAI-compat usage extractor does not surface\n // reasoning_tokens; we inspect rawResponse and augment the legacy\n // UsageRecord when the field is present. The Phase 7 normalized\n // `Usage` (promptTokens/completionTokens/costUsd) is unchanged by\n // design -- normalized usage represents billable tokens; reasoning_tokens\n // is xAI-extra-counts that consumers access via rawResponse for now.\n const raw = response.rawResponse as\n | {\n usage?: {\n completion_tokens_details?: { reasoning_tokens?: unknown };\n };\n }\n | undefined;\n const reasoningTokens = raw?.usage?.completion_tokens_details?.reasoning_tokens;\n if (typeof reasoningTokens === \"number\" && response.usage !== undefined) {\n const inputTokens = response.usage.inputTokens ?? 0;\n const outputTokens = response.usage.outputTokens ?? 0;\n return {\n ...response,\n usage: {\n ...response.usage,\n // Recompute totalTokens INCLUDING reasoning tokens (matches\n // FSB universal-provider.js:593 production behavior).\n totalTokens: inputTokens + outputTokens + reasoningTokens,\n },\n };\n }\n return response;\n };\n\n // Build the returned object without spreading the inner compat adapter (which has\n // execute?: optional and could introduce exactOptionalPropertyTypes issues). Instead\n // we compose the fields explicitly.\n const result: ProviderAdapter & {\n readonly quirks: XaiQuirks;\n readonly negotiateCapabilities: (modelId: string) => Promise<NegotiatedCapabilities>;\n } = {\n id: inner.id,\n kind: inner.kind,\n // Phase 34 — QUIRK-02 / XaiQuirks — verified per RESEARCH §Q6 xAI vocabulary.\n // CITED: xAI API docs — https://docs.x.ai/api/endpoints\n // - reasoningTokensReported: completion_tokens_details.reasoning_tokens reported\n // in xAI API responses — verified in xai.ts (D-07 carryforward from Phase 4)\n // - logprobsSupported: grok-4.20 silently ignores logprobs param per observed behavior\n // (docs.x.ai citation); flag set to false since logprobs fields are not populated\n // for current grok-4 models despite the parameter being accepted\n quirks: {\n supportsToolChoice: true,\n parallelToolCalls: true,\n structuredOutputs: true,\n responseFormatHonored: true,\n streamingDiverges: false,\n reasoningTokensReported: true,\n logprobsSupported: false,\n } satisfies XaiQuirks,\n negotiateCapabilities: negotiate,\n ...(inner.capabilities !== undefined ? { capabilities: inner.capabilities } : {}),\n ...(wrappedExecute !== undefined ? { execute: wrappedExecute } : {}),\n };\n return result;\n}\n","import type { ArtifactRef } from \"../artifacts/artifact.js\";\nimport type { OutputContractMap } from \"../outputs/contracts.js\";\nimport type {\n CapabilityModality,\n ModelCapability,\n ProviderTransportMode,\n} from \"../providers/provider.js\";\n\nexport type ExecutionPlanStatus =\n | \"stub\"\n | \"planned\"\n | \"no-route\"\n | \"running\"\n | \"completed\"\n | \"failed\";\n\nexport type ExecutionStageKind =\n | \"analysis\"\n | \"transforms\"\n | \"context-packing\"\n | \"provider-packaging\"\n | \"tool-execution\"\n | \"execution\"\n | \"validation\"\n | \"tripwire\"\n | \"persistence\"\n | \"replay\";\n\nexport type ExecutionStageStatus =\n | \"pending\"\n | \"running\"\n | \"completed\"\n | \"skipped\"\n | \"failed\";\n\nexport interface ExecutionPlanStage {\n readonly id: string;\n readonly kind: ExecutionStageKind;\n readonly status: ExecutionStageStatus;\n readonly inputArtifacts?: readonly string[];\n readonly outputArtifacts?: readonly string[];\n readonly warnings: readonly string[];\n readonly metadata?: Record<string, unknown>;\n}\n\nexport interface RouteRejectReason {\n readonly code: string;\n readonly message: string;\n}\n\nexport interface RouteCandidate {\n readonly providerId: string;\n readonly modelId: string;\n readonly capability: ModelCapability;\n readonly score: number;\n readonly accepted: boolean;\n readonly reasons: readonly RouteRejectReason[];\n readonly estimates: RouteEstimates;\n}\n\nexport interface RouteEstimates {\n readonly inputTokens: number;\n readonly outputTokens: number;\n readonly costUsd?: number;\n readonly latencyMs?: number;\n}\n\nexport interface SelectedRoute {\n readonly providerId: string;\n readonly modelId: string;\n readonly score: number;\n readonly estimates: RouteEstimates;\n readonly inputModalities: readonly CapabilityModality[];\n readonly outputModalities: readonly CapabilityModality[];\n readonly fileTransport: readonly ProviderTransportMode[];\n}\n\nexport interface FallbackRoute {\n readonly providerId: string;\n readonly modelId: string;\n readonly score: number;\n readonly reason: \"policy-preserving-fallback\";\n}\n\nexport interface RouteDecision {\n readonly catalogVersion: string;\n readonly selected?: SelectedRoute;\n readonly candidates: readonly RouteCandidate[];\n readonly rejected: readonly RouteCandidate[];\n readonly fallbackChain: readonly FallbackRoute[];\n readonly noRouteReasons: readonly RouteRejectReason[];\n}\n\nexport interface ContextPackPlan {\n readonly id: string;\n readonly tokenBudget: number;\n readonly estimatedTokens: number;\n readonly included: readonly ContextPackItemPlan[];\n readonly summarized: readonly ContextPackItemPlan[];\n readonly archived: readonly ContextPackItemPlan[];\n readonly omitted: readonly ContextPackItemPlan[];\n readonly warnings: readonly string[];\n}\n\nexport interface ContextPackItemPlan {\n readonly artifactId?: string;\n readonly sessionTurnId?: string;\n readonly reason: string;\n readonly estimatedTokens: number;\n readonly trust: \"developer\" | \"user\" | \"tool\" | \"model-summary\";\n}\n\nexport interface ProviderPackagingPlan {\n readonly providerId: string;\n readonly modelId: string;\n readonly artifacts: readonly ProviderPackagedArtifactPlan[];\n readonly warnings: readonly string[];\n}\n\nexport interface ProviderPackagedArtifactPlan {\n readonly artifactId: string;\n readonly transport: ProviderTransportMode;\n readonly mediaType?: string;\n readonly lineageTransform: \"provider-packaging\";\n readonly warnings: readonly string[];\n}\n\nexport interface ProviderAttemptRecord {\n readonly providerId: string;\n readonly modelId: string;\n readonly status: \"pending\" | \"running\" | \"succeeded\" | \"failed\" | \"cancelled\";\n readonly startedAt?: string;\n readonly completedAt?: string;\n readonly error?: string;\n readonly usage?: UsageRecord;\n}\n\nexport interface UsageRecord {\n readonly inputTokens?: number;\n readonly outputTokens?: number;\n readonly totalTokens?: number;\n readonly costUsd?: number;\n readonly latencyMs?: number;\n}\n\nexport interface ExecutionPlan {\n readonly id: string;\n readonly kind: \"execution-plan\";\n readonly version: 1;\n readonly createdAt: string;\n readonly status: ExecutionPlanStatus;\n readonly task: string;\n readonly outputNames: readonly string[];\n readonly artifactRefs: readonly ArtifactRef[];\n readonly route: RouteDecision;\n readonly stages: readonly ExecutionPlanStage[];\n readonly context?: ContextPackPlan;\n readonly providerPackaging?: ProviderPackagingPlan;\n readonly attempts: readonly ProviderAttemptRecord[];\n readonly warnings: readonly string[];\n readonly metadata?: Record<string, unknown>;\n}\n\nexport interface ExecutionPlanStub {\n readonly id: string;\n readonly kind: \"plan-stub\";\n readonly createdAt: string;\n readonly status: \"stub\";\n readonly stages: readonly [];\n readonly warnings: readonly string[];\n}\n\nexport type ResultPlan = ExecutionPlan | ExecutionPlanStub;\n\nexport interface CreateExecutionPlanInput {\n readonly task: string;\n readonly artifacts: readonly ArtifactRef[];\n readonly outputs: OutputContractMap;\n readonly route: RouteDecision;\n readonly context?: ContextPackPlan;\n readonly providerPackaging?: ProviderPackagingPlan;\n readonly warnings?: readonly string[];\n readonly metadata?: Record<string, unknown>;\n}\n\nexport function createExecutionPlan(input: CreateExecutionPlanInput): ExecutionPlan {\n const selected = input.route.selected;\n const status: ExecutionPlanStatus = selected === undefined ? \"no-route\" : \"planned\";\n const contextWarnings = input.context?.warnings ?? [];\n const packagingWarnings = input.providerPackaging?.warnings ?? [];\n const warnings = [\n ...(input.warnings ?? []),\n ...contextWarnings,\n ...packagingWarnings,\n ...input.route.noRouteReasons.map((reason) => reason.message),\n ];\n\n return {\n id: createPlanId(),\n kind: \"execution-plan\",\n version: 1,\n createdAt: new Date().toISOString(),\n status,\n task: input.task,\n outputNames: Object.keys(input.outputs),\n artifactRefs: input.artifacts,\n route: input.route,\n stages: createDefaultStages(status, input.artifacts, warnings),\n ...(input.context !== undefined ? { context: input.context } : {}),\n ...(input.providerPackaging !== undefined\n ? { providerPackaging: input.providerPackaging }\n : {}),\n attempts:\n selected === undefined\n ? []\n : [\n {\n providerId: selected.providerId,\n modelId: selected.modelId,\n status: \"pending\",\n },\n ],\n warnings,\n ...(input.metadata !== undefined ? { metadata: input.metadata } : {}),\n };\n}\n\nexport function createExecutionPlanStub(\n warnings: readonly string[] = [],\n): ExecutionPlanStub {\n return {\n id: createPlanId(),\n kind: \"plan-stub\",\n createdAt: new Date().toISOString(),\n status: \"stub\",\n stages: [],\n warnings: [...warnings],\n };\n}\n\nexport function withPlanStatus(\n plan: ExecutionPlan,\n status: ExecutionPlanStatus,\n updates: {\n readonly stages?: readonly ExecutionPlanStage[];\n readonly attempts?: readonly ProviderAttemptRecord[];\n readonly warnings?: readonly string[];\n } = {},\n): ExecutionPlan {\n return {\n ...plan,\n status,\n ...(updates.stages !== undefined ? { stages: updates.stages } : {}),\n ...(updates.attempts !== undefined ? { attempts: updates.attempts } : {}),\n ...(updates.warnings !== undefined ? { warnings: updates.warnings } : {}),\n };\n}\n\nexport function markStage(\n stages: readonly ExecutionPlanStage[],\n kind: ExecutionStageKind,\n status: ExecutionStageStatus,\n metadata?: Record<string, unknown>,\n): readonly ExecutionPlanStage[] {\n return stages.map((stage) =>\n stage.kind === kind\n ? {\n ...stage,\n status,\n ...(metadata !== undefined\n ? { metadata: { ...stage.metadata, ...metadata } }\n : {}),\n }\n : stage,\n );\n}\n\nfunction createDefaultStages(\n status: ExecutionPlanStatus,\n artifacts: readonly ArtifactRef[],\n warnings: readonly string[],\n): readonly ExecutionPlanStage[] {\n const skipped = status === \"no-route\";\n const artifactIds = artifacts.map((artifact) => artifact.id);\n\n return [\n {\n id: \"stage:analysis\",\n kind: \"analysis\",\n status: \"completed\",\n inputArtifacts: artifactIds,\n warnings: [],\n },\n {\n id: \"stage:transforms\",\n kind: \"transforms\",\n status: \"pending\",\n inputArtifacts: artifactIds,\n warnings: [],\n },\n {\n id: \"stage:context-packing\",\n kind: \"context-packing\",\n status: \"completed\",\n inputArtifacts: artifactIds,\n warnings: [],\n },\n {\n id: \"stage:provider-packaging\",\n kind: \"provider-packaging\",\n status: skipped ? \"skipped\" : \"completed\",\n inputArtifacts: artifactIds,\n warnings,\n },\n {\n id: \"stage:tool-execution\",\n kind: \"tool-execution\",\n status: \"pending\",\n warnings: [],\n },\n {\n id: \"stage:execution\",\n kind: \"execution\",\n status: skipped ? \"skipped\" : \"pending\",\n warnings: skipped ? warnings : [],\n },\n {\n id: \"stage:validation\",\n kind: \"validation\",\n status: skipped ? \"skipped\" : \"pending\",\n warnings: [],\n },\n {\n id: \"stage:tripwire\",\n kind: \"tripwire\",\n status: skipped ? \"skipped\" : \"pending\",\n warnings: [],\n },\n {\n id: \"stage:persistence\",\n kind: \"persistence\",\n status: \"pending\",\n warnings: [],\n },\n ];\n}\n\nfunction createPlanId(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return `plan:${crypto.randomUUID()}`;\n }\n\n return `plan:${Date.now()}:${Math.random().toString(16).slice(2)}`;\n}\n","export const latticeVersion = \"0.0.0\";\n","/**\n * Phase 10 — materializeReplayEnvelope.\n *\n * Reconstructs a `ReplayEnvelope` from a signed `ReceiptEnvelope` plus a\n * pluggable artifact loader. The flow is:\n *\n * 1. verifyReceipt(receipt, keySet) — REQUIRED before any other work.\n * A tampered or revoked receipt MUST short-circuit before the artifact\n * loader is invoked (no side effects on bad input).\n * 2. Parse the verified body to learn `inputHashes`.\n * 3. Invoke `artifactLoader(hash)` once per input hash, in order.\n * 4. Assemble a `ReplayEnvelope` whose `plan` reproduces the receipt's\n * route/usage fields, attach the receipt itself, and (optionally) the\n * caller-supplied contract / task / outputs / policy.\n *\n * v1.1 limitation: the receipt body does NOT carry the original task string,\n * outputs schema, or policy snapshot. Callers may supply them via the options\n * bag; when omitted, the envelope's `task` defaults to \"\" and `outputs`\n * remains undefined. Phase 11's `lattice repro` CLI accepts a sidecar JSON\n * file to populate these fields.\n *\n * Errors NEVER cross the boundary as plain `Error`. All failures surface as\n * typed `MaterializationError` values thrown from the async function so the\n * caller can pattern-match on `error.kind` (and a `MaterializationError` IS\n * a thrown object whose `kind` discriminates the failure mode).\n */\n\nimport type { ArtifactInput } from \"../artifacts/artifact.js\";\nimport { toArtifactRef } from \"../artifacts/artifact.js\";\nimport type { CapabilityContract } from \"../contract/contract.js\";\nimport type { OutputContractMap } from \"../outputs/contracts.js\";\nimport type { InferOutputMap } from \"../outputs/infer.js\";\nimport { createExecutionPlan, type ExecutionPlan, type UsageRecord } from \"../plan/plan.js\";\nimport type { PolicySpec } from \"../policy/policy.js\";\nimport type { CapabilityModality } from \"../providers/provider.js\";\nimport type {\n CapabilityReceiptBody,\n KeySet,\n ReceiptEnvelope,\n} from \"../receipts/types.js\";\nimport { verifyReceipt } from \"../receipts/verify.js\";\nimport { latticeVersion } from \"../version.js\";\n\nimport type { ReplayEnvelope } from \"./replay.js\";\n\n/**\n * Discriminated union of materialization failure modes.\n *\n * - \"verify-failed\" — receipt failed verifyReceipt (signature, key\n * missing/revoked, canonicalization mismatch).\n * - \"artifact-load-failed\" — the artifactLoader callback rejected for at\n * least one input hash.\n * - \"envelope-malformed\" — receipt verified but the verified body is\n * structurally unusable (should never happen\n * under verifyReceipt invariants, but kept as a\n * defensive third branch).\n */\nexport interface MaterializationError {\n readonly kind: \"verify-failed\" | \"artifact-load-failed\" | \"envelope-malformed\";\n readonly message: string;\n}\n\nfunction asMaterializationError(value: unknown): value is MaterializationError {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { kind?: unknown }).kind === \"string\" &&\n typeof (value as { message?: unknown }).message === \"string\"\n );\n}\n\n/** Throwable shape — `instanceof Error` is not required for typed unions, so\n * the function just throws a plain object literal that matches the\n * `MaterializationError` shape. Callers pattern-match on `err.kind`. */\nfunction fail(\n kind: MaterializationError[\"kind\"],\n message: string,\n): MaterializationError {\n return { kind, message };\n}\n\n/**\n * Async callback that resolves an artifact body from its sha256 hex digest.\n * Phase 10 ships only the in-memory variant for tests. Phase 11's CLI plugs\n * in a filesystem-backed loader reading from `.lattice/fixtures/<sha256>.bin`.\n */\nexport type ArtifactLoader = (hash: string) => Promise<ArtifactInput>;\n\nexport interface MaterializeReplayEnvelopeOptions<\n TOutputs extends OutputContractMap = OutputContractMap,\n> {\n readonly artifactLoader: ArtifactLoader;\n readonly keySet: KeySet;\n /** Optional original task string. Defaults to \"\" when omitted. */\n readonly task?: string;\n /**\n * Optional caller-supplied outputs map. When provided, the resulting\n * `ReplayEnvelope.outputs` is populated and `replayOffline` will return\n * an `ok: true` result. When omitted, `replayOffline` reports an\n * `execution_unavailable` failure (current Phase 5 semantics).\n */\n readonly outputs?: InferOutputMap<TOutputs>;\n readonly policy?: PolicySpec;\n readonly contract?: CapabilityContract;\n}\n\n/**\n * Pure async function that reconstructs a `ReplayEnvelope` from a receipt.\n *\n * Verify-FIRST ordering: `verifyReceipt` runs before `artifactLoader` is\n * touched. Tampered receipts MUST NOT cause loader side effects.\n */\nexport async function materializeReplayEnvelope<\n TOutputs extends OutputContractMap = OutputContractMap,\n>(\n receipt: ReceiptEnvelope,\n options: MaterializeReplayEnvelopeOptions<TOutputs>,\n): Promise<ReplayEnvelope<TOutputs>> {\n // Step 1: verify FIRST. No artifact loader call before this resolves.\n const verifyResult = await verifyReceipt(receipt, options.keySet);\n if (!verifyResult.ok) {\n throw fail(\n verifyResult.error.kind === \"envelope-malformed\"\n ? \"envelope-malformed\"\n : \"verify-failed\",\n verifyResult.error.message,\n );\n }\n\n const body: CapabilityReceiptBody = verifyResult.body;\n\n // Step 2: load every artifact referenced by the receipt's inputHashes.\n // We treat any loader rejection as `artifact-load-failed` and surface the\n // underlying message — the loader is the system boundary, so its error\n // text is the most informative thing we have.\n const loadedInputs: ArtifactInput[] = [];\n for (const hash of body.inputHashes) {\n if (hash === \"\") {\n // Skip empty-hash slots — Phase 9 emits \"\" for unfingerprintable\n // values (e.g., undefined artifact bodies). They have no resolvable\n // content and the replay artifacts array preserves order via the\n // remaining loaded entries.\n continue;\n }\n try {\n const input = await options.artifactLoader(hash);\n loadedInputs.push(input);\n } catch (error) {\n const message =\n error instanceof Error\n ? error.message\n : asMaterializationError(error)\n ? error.message\n : String(error);\n throw fail(\"artifact-load-failed\", message);\n }\n }\n\n // Step 3: assemble the ExecutionPlan envelope shell. The receipt does NOT\n // carry the full RouteDecision/ContextPack — we synthesize a minimal but\n // valid plan that reproduces the receipt's route + usage fields. This is\n // intentionally lossy and matches the v1.1 limitation note in 10-CONTEXT.md.\n const artifactRefs = loadedInputs.map(toArtifactRef);\n const outputsMap = (options.outputs !== undefined\n ? (Object.fromEntries(\n Object.keys(options.outputs as Record<string, unknown>).map((k) => [\n k,\n \"text\" as const,\n ]),\n ) as OutputContractMap)\n : ({} as OutputContractMap));\n\n const plan: ExecutionPlan = createExecutionPlan({\n task: options.task ?? \"\",\n artifacts: artifactRefs,\n outputs: outputsMap,\n route: {\n catalogVersion: \"materialized\",\n selected: {\n providerId: body.route.providerId,\n modelId: body.route.capabilityId,\n score: 0,\n estimates: { inputTokens: 0, outputTokens: 0 },\n inputModalities: [] as readonly CapabilityModality[],\n outputModalities: [] as readonly CapabilityModality[],\n fileTransport: [],\n },\n candidates: [],\n rejected: [],\n fallbackChain: [],\n noRouteReasons: [],\n },\n warnings: [],\n metadata: {\n materialized: true,\n receiptId: body.receiptId,\n runId: body.runId,\n contractVerdict: body.contractVerdict,\n ...(options.policy !== undefined ? { policy: { ...options.policy } } : {}),\n },\n });\n\n const usage: UsageRecord = {\n inputTokens: body.usage.promptTokens,\n outputTokens: body.usage.completionTokens,\n ...(body.usage.costUsd !== null\n ? { costUsd: Number(body.usage.costUsd) }\n : {}),\n };\n\n const envelope: ReplayEnvelope<TOutputs> = {\n kind: \"replay-envelope\",\n version: 1,\n runtimeVersion: latticeVersion,\n catalogVersion: \"materialized\",\n createdAt: new Date().toISOString(),\n plan,\n artifacts: artifactRefs,\n ...(options.outputs !== undefined ? { outputs: options.outputs } : {}),\n warnings: [],\n errors: [],\n usage,\n events: [],\n receipt,\n ...(options.contract !== undefined ? { contract: options.contract } : {}),\n };\n\n return envelope;\n}\n","import type { ArtifactRef } from \"../artifacts/artifact.js\";\nimport type { CapabilityContract } from \"../contract/contract.js\";\nimport type { OutputContractMap } from \"../outputs/contracts.js\";\nimport type { InferOutputMap } from \"../outputs/infer.js\";\nimport type { ExecutionPlan, UsageRecord } from \"../plan/plan.js\";\nimport type { Usage } from \"../providers/provider.js\";\nimport type { ReceiptEnvelope } from \"../receipts/types.js\";\nimport type { RunResult } from \"../results/result.js\";\nimport type { AI, RunIntent } from \"../runtime/create-ai.js\";\nimport type { RunEvent } from \"../tracing/tracing.js\";\nimport { latticeVersion } from \"../version.js\";\n\nexport interface ReplayEnvelope<TOutputs extends OutputContractMap = OutputContractMap> {\n readonly kind: \"replay-envelope\";\n readonly version: 1;\n readonly runtimeVersion: string;\n readonly catalogVersion: string;\n readonly createdAt: string;\n readonly plan: ExecutionPlan;\n readonly artifacts: readonly ArtifactRef[];\n readonly outputs?: InferOutputMap<TOutputs>;\n readonly warnings: readonly string[];\n readonly errors: readonly string[];\n readonly usage?: UsageRecord;\n readonly events: readonly RunEvent[];\n /**\n * Phase 10 — optional signed receipt recorded alongside the envelope so a\n * single artifact is sufficient to materialize an offline replay session\n * deterministically. Type-only import — replay.ts stays runtime-import-free\n * of the receipts builder.\n */\n readonly receipt?: ReceiptEnvelope;\n /**\n * Phase 10 — optional contract recorded so replays can re-run pre-flight\n * checks deterministically.\n */\n readonly contract?: CapabilityContract;\n}\n\nexport function createReplayEnvelope<TOutputs extends OutputContractMap>(\n result: RunResult<TOutputs>,\n): ReplayEnvelope<TOutputs> {\n if (result.plan.kind !== \"execution-plan\") {\n throw new Error(\"Replay envelopes require an execution plan.\");\n }\n\n const usage = result.plan.attempts.at(-1)?.usage;\n\n return {\n kind: \"replay-envelope\",\n version: 1,\n runtimeVersion: latticeVersion,\n catalogVersion: result.plan.route.catalogVersion,\n createdAt: new Date().toISOString(),\n plan: redactPlan(result.plan),\n artifacts: result.ok ? result.artifacts : result.plan.artifactRefs,\n ...(result.ok ? { outputs: result.outputs } : {}),\n warnings: result.plan.warnings,\n errors: result.ok ? [] : [result.error.message],\n ...(usage !== undefined ? { usage } : {}),\n events: result.events ?? [],\n };\n}\n\nexport async function replayOffline<TOutputs extends OutputContractMap>(\n envelope: ReplayEnvelope<TOutputs>,\n): Promise<RunResult<TOutputs>> {\n const replayedUsage = envelopeUsage(envelope);\n if (envelope.outputs === undefined) {\n return {\n ok: false,\n error: {\n kind: \"execution_unavailable\",\n message: \"Replay envelope does not contain successful outputs.\",\n },\n usage: replayedUsage,\n plan: envelope.plan,\n events: envelope.events,\n };\n }\n\n return {\n ok: true,\n outputs: envelope.outputs,\n artifacts: envelope.artifacts,\n usage: replayedUsage,\n plan: envelope.plan,\n events: envelope.events,\n };\n}\n\nfunction envelopeUsage(envelope: ReplayEnvelope<OutputContractMap>): Usage {\n if (envelope.usage === undefined) {\n return { promptTokens: 0, completionTokens: 0, costUsd: null };\n }\n return {\n promptTokens: envelope.usage.inputTokens ?? 0,\n completionTokens: envelope.usage.outputTokens ?? 0,\n costUsd: envelope.usage.costUsd ?? null,\n };\n}\n\nexport async function rerunLive<TOutputs extends OutputContractMap>(\n ai: AI,\n envelope: ReplayEnvelope<TOutputs>,\n intent: RunIntent<TOutputs>,\n): Promise<RunResult<TOutputs>> {\n const result = await ai.run(intent);\n\n if (result.plan.kind === \"execution-plan\") {\n return {\n ...result,\n plan: {\n ...result.plan,\n warnings: [\n ...result.plan.warnings,\n `Live rerun of ${envelope.plan.id}: provider behavior, model versions, cost, and latency may differ.`,\n ],\n },\n };\n }\n\n return result;\n}\n\nexport function redactReplayEnvelope<TOutputs extends OutputContractMap>(\n envelope: ReplayEnvelope<TOutputs>,\n): ReplayEnvelope<TOutputs> {\n return {\n ...envelope,\n plan: redactPlan(envelope.plan),\n artifacts: envelope.artifacts.map(redactArtifactRef),\n events: envelope.events.map((event) => {\n const metadata = redactRecord(event.metadata);\n\n return {\n ...event,\n ...(metadata !== undefined ? { metadata } : {}),\n };\n }),\n };\n}\n\nexport function redactPlan(plan: ExecutionPlan): ExecutionPlan {\n return {\n ...plan,\n task: redactText(plan.task),\n artifactRefs: plan.artifactRefs.map(redactArtifactRef),\n ...(plan.providerPackaging !== undefined\n ? {\n providerPackaging: {\n ...plan.providerPackaging,\n artifacts: plan.providerPackaging.artifacts.map((item) => ({\n ...item,\n warnings: item.warnings.map(redactText),\n })),\n warnings: plan.providerPackaging.warnings.map(redactText),\n },\n }\n : {}),\n warnings: plan.warnings.map(redactText),\n };\n}\n\nexport function redactArtifactRef(ref: ArtifactRef): ArtifactRef {\n const redactedMetadata = redactRecord(ref.metadata);\n\n return {\n ...ref,\n ...(redactedMetadata !== undefined ? { metadata: redactedMetadata } : {}),\n ...(ref.source === \"url\"\n ? {\n metadata: {\n ...redactedMetadata,\n redactedSource: \"url\",\n },\n }\n : {}),\n };\n}\n\nfunction redactRecord(\n record: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n if (record === undefined) {\n return undefined;\n }\n\n return Object.fromEntries(\n Object.entries(record).map(([key, value]) => [\n key,\n shouldRedactKey(key) ? \"[redacted]\" : redactValue(value),\n ]),\n );\n}\n\nfunction redactValue(value: unknown): unknown {\n if (typeof value === \"string\") {\n return redactText(value);\n }\n\n if (Array.isArray(value)) {\n return value.map(redactValue);\n }\n\n if (typeof value === \"object\" && value !== null) {\n return redactRecord(value as Record<string, unknown>);\n }\n\n return value;\n}\n\nfunction redactText(value: string): string {\n return value\n .replace(/Bearer\\s+[A-Za-z0-9._-]+/gu, \"Bearer [redacted]\")\n .replace(/https?:\\/\\/[^\\s)]+/gu, \"[redacted-url]\")\n .replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}/gu, \"[redacted-email]\");\n}\n\nfunction shouldRedactKey(key: string): boolean {\n return /api.?key|authorization|token|secret|password|credential|signed.?url|raw|body|transcript/iu.test(key);\n}\n","/**\n * AgentSpec — Phase 39 (v1.3). Sibling of defineTool; crew member\n * specification composing by value as a tree (D-03).\n *\n * `defineAgent(spec)` mirrors `defineTool` (tools/tools.ts) literally:\n * an `Omit<…, \"kind\">` factory that spreads the definition under the\n * `kind: \"agent\"` discriminant. The runtime (CrewDispatcher, 39-05)\n * branches on `kind` to route dispatch through the crew chokepoint\n * instead of `runTool` (D-01).\n *\n * `childAgents` composes by value — a crew is a literal tree of specs,\n * not a registry of ids. `summaryReturnSchema` validates the child's\n * `{ summary, artifacts, receipts }` return envelope (Standard Schema,\n * Zod-compatible). `contract` carries an optional per-agent sub-budget\n * (D-07): the effective child budget is `min(spec.contract.budget,\n * remaining crew pool)`.\n */\n\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nimport type { CapabilityContract } from \"../../contract/contract.js\";\nimport type { ToolDefinition } from \"../../tools/tools.js\";\n\n/**\n * Crew member specification. A literal sibling of `ToolDefinition`\n * discriminated by `kind: \"agent\"` (D-03).\n */\nexport interface AgentSpec {\n readonly kind: \"agent\";\n readonly id: string;\n readonly intent: string;\n readonly tools: ReadonlyArray<ToolDefinition<StandardSchemaV1>>;\n readonly childAgents?: ReadonlyArray<AgentSpec>;\n readonly summaryReturnSchema: StandardSchemaV1;\n /** Optional per-agent sub-budget (D-07). */\n readonly contract?: CapabilityContract;\n}\n\n/**\n * Factory for `AgentSpec` values. Mirrors `defineTool` exactly: spread\n * preserves input identity (no cloning, no mutation) and absent optional\n * members stay absent (`exactOptionalPropertyTypes`-safe).\n */\nexport function defineAgent(definition: Omit<AgentSpec, \"kind\">): AgentSpec {\n return {\n kind: \"agent\",\n ...definition,\n };\n}\n","/**\n * TranscriptStore — Phase 21 (v1.2).\n *\n * Records the running conversation log with filtered tail reads sized for\n * context-window management. Always preserves the FIRST user turn (the\n * original task) in tail reads so the model retains its mission.\n */\n\nimport type { ConversationTurn } from \"../format-tools.js\";\n\n/**\n * Token estimator used by `tailByTokens`. The default ~4 chars / token is\n * the OpenAI rule of thumb for English text. Callers with provider-specific\n * tokenizers can supply their own.\n */\nexport type TokenEstimator = (text: string) => number;\n\nconst DEFAULT_TOKEN_ESTIMATOR: TokenEstimator = (text) => Math.ceil(text.length / 4);\n\nexport interface TranscriptStore {\n readonly kind: \"transcript-store\";\n append(turn: ConversationTurn): void;\n all(): readonly ConversationTurn[];\n /** Returns the first user turn (if any) + the most-recent `limit` turns. */\n tail(limit: number): readonly ConversationTurn[];\n /**\n * Returns the first user turn (if any) + the most-recent turns whose\n * combined token estimate fits within `maxTokens`. The default estimator\n * is the ~4 chars / token rule; callers can override for provider-\n * specific tokenizers.\n */\n tailByTokens(maxTokens: number, estimator?: TokenEstimator): readonly ConversationTurn[];\n}\n\nexport function createTranscriptStore(): TranscriptStore {\n const turns: ConversationTurn[] = [];\n\n function firstUserTurn(): ConversationTurn | null {\n for (const turn of turns) {\n if (turn.role === \"user\") return turn;\n }\n return null;\n }\n\n return {\n kind: \"transcript-store\" as const,\n append(turn: ConversationTurn): void {\n turns.push(turn);\n },\n all(): readonly ConversationTurn[] {\n return Object.freeze([...turns]);\n },\n tail(limit: number): readonly ConversationTurn[] {\n if (limit <= 0) return Object.freeze([]);\n if (turns.length <= limit) return Object.freeze([...turns]);\n const start = turns.length - limit;\n const tail = turns.slice(start);\n const first = firstUserTurn();\n if (first === null || tail.includes(first)) {\n return Object.freeze(tail);\n }\n return Object.freeze([first, ...tail]);\n },\n tailByTokens(\n maxTokens: number,\n estimator: TokenEstimator = DEFAULT_TOKEN_ESTIMATOR,\n ): readonly ConversationTurn[] {\n if (maxTokens <= 0) return Object.freeze([]);\n const reversed = [...turns].reverse();\n const selected: ConversationTurn[] = [];\n let used = 0;\n for (const turn of reversed) {\n const cost = estimator(turn.content);\n if (used + cost > maxTokens) break;\n selected.unshift(turn);\n used += cost;\n }\n const first = firstUserTurn();\n if (first !== null && !selected.includes(first)) {\n selected.unshift(first);\n }\n return Object.freeze(selected);\n },\n };\n}\n","/**\n * GoalProgressTracker — Phase 21 (v1.2).\n *\n * Stuck-detection primitive. The caller declares a goal-satisfaction\n * score per iteration (0..1); the tracker reports a coarse status the\n * agent loop can use to back off or surface to the human.\n */\n\nexport type ProgressStatus = \"progressing\" | \"stalled\" | \"regressed\";\n\nexport interface GoalProgressOptions {\n /**\n * Window of recent steps used for stall + regression detection.\n * Default 3. The tracker waits until it has at least this many steps\n * before reporting anything other than \"progressing\".\n */\n readonly windowSize?: number;\n /** Max satisfaction delta across the window to count as \"stalled\". Default 0.02. */\n readonly stallThreshold?: number;\n /** Min drop from prior max to count as \"regressed\". Default 0.1. */\n readonly regressionThreshold?: number;\n}\n\nexport interface GoalProgressStep {\n readonly iterationIndex: number;\n readonly goalSatisfaction: number;\n}\n\nexport interface GoalProgressTracker {\n readonly kind: \"goal-progress-tracker\";\n recordStep(step: GoalProgressStep): void;\n status(): ProgressStatus;\n}\n\nexport function createGoalProgressTracker(\n options: GoalProgressOptions = {},\n): GoalProgressTracker {\n const windowSize = options.windowSize ?? 3;\n const stallThreshold = options.stallThreshold ?? 0.02;\n const regressionThreshold = options.regressionThreshold ?? 0.1;\n const steps: GoalProgressStep[] = [];\n\n return {\n kind: \"goal-progress-tracker\" as const,\n recordStep(step: GoalProgressStep): void {\n steps.push(step);\n },\n status(): ProgressStatus {\n if (steps.length < windowSize) return \"progressing\";\n const window = steps.slice(-windowSize);\n const latest = window[window.length - 1]!;\n const earlierMax = steps\n .slice(0, -1)\n .reduce((m, s) => (s.goalSatisfaction > m ? s.goalSatisfaction : m), -Infinity);\n if (latest.goalSatisfaction < earlierMax - regressionThreshold) {\n return \"regressed\";\n }\n const min = window.reduce((m, s) => (s.goalSatisfaction < m ? s.goalSatisfaction : m), Infinity);\n const max = window.reduce((m, s) => (s.goalSatisfaction > m ? s.goalSatisfaction : m), -Infinity);\n if (max - min <= stallThreshold) {\n return \"stalled\";\n }\n return \"progressing\";\n },\n };\n}\n","/**\n * PermissionContext — Phase 21 (v1.2).\n *\n * Gates tool execution per-tool / per-iteration / per-resource. Includes\n * a SAFETY-band hook helper that wires the context into the agent loop's\n * BEFORE_TOOL pipeline via the Phase 19 `controls.deny(reason)` veto.\n */\n\nimport { BAND, type HookHandler, type RegisterOptions } from \"../../contract/bands.js\";\n\nexport interface PermissionRule {\n /** Match on tool name. String = exact match; RegExp = test. Both undefined = match-any. */\n readonly toolName?: string | RegExp;\n /**\n * Optional resource matcher. The caller passes `resource` on each\n * decide() invocation; this rule fires only when the rule's resource\n * matches.\n */\n readonly resource?: string | RegExp;\n readonly verdict: \"allow\" | \"deny\";\n readonly reason?: string;\n}\n\nexport interface PermissionDecisionInput {\n readonly toolName: string;\n readonly iterationIndex: number;\n readonly resource?: string;\n readonly args?: unknown;\n}\n\nexport type PermissionVerdict =\n | { readonly allow: true }\n | { readonly allow: false; readonly reason: string };\n\nexport interface PermissionContext {\n readonly kind: \"permission-context\";\n decide(input: PermissionDecisionInput): PermissionVerdict;\n}\n\nfunction matches(matcher: string | RegExp | undefined, value: string | undefined): boolean {\n if (matcher === undefined) return true;\n if (value === undefined) return false;\n if (typeof matcher === \"string\") return matcher === value;\n return matcher.test(value);\n}\n\nexport function createPermissionContext(\n rules: readonly PermissionRule[],\n): PermissionContext {\n return {\n kind: \"permission-context\" as const,\n decide(input: PermissionDecisionInput): PermissionVerdict {\n for (const rule of rules) {\n if (!matches(rule.toolName, input.toolName)) continue;\n if (rule.resource !== undefined && !matches(rule.resource, input.resource)) continue;\n if (rule.verdict === \"allow\") return { allow: true };\n return { allow: false, reason: rule.reason ?? `denied by permission rule for ${input.toolName}` };\n }\n // Default: allow when no rule matches.\n return { allow: true };\n },\n };\n}\n\n/**\n * Hook handler shape suitable for registering on `BEFORE_TOOL` at\n * BAND.SAFETY. Reads `toolName` and `iterationIndex` from the agent\n * runtime's BEFORE_TOOL context shape (`{ iterationIndex, toolName,\n * args }`) and translates a deny verdict into `controls.deny(reason)`.\n */\nexport interface PermissionHookContext {\n readonly iterationIndex: number;\n readonly toolName: string;\n readonly resource?: string;\n readonly args?: unknown;\n}\n\nexport function createPermissionGuardHook(\n context: PermissionContext,\n): HookHandler<PermissionHookContext> {\n return (ctx, controls) => {\n const verdict = context.decide({\n iterationIndex: ctx.iterationIndex,\n toolName: ctx.toolName,\n ...(ctx.resource !== undefined ? { resource: ctx.resource } : {}),\n ...(ctx.args !== undefined ? { args: ctx.args } : {}),\n });\n if (!verdict.allow) {\n controls?.deny(verdict.reason);\n }\n };\n}\n\n/**\n * Convenience: returns RegisterOptions for the SAFETY-band registration.\n * Callers do `pipeline.register(\"BEFORE_TOOL\", hook, permissionGuardRegisterOptions())`.\n */\nexport function permissionGuardRegisterOptions(): RegisterOptions {\n return { band: BAND.SAFETY };\n}\n","/**\n * evalAgentRun — Phase 22 (v1.2).\n *\n * Pure helper that gates a baseline-relative regression on iterations-to-goal\n * and total cost for an agent run. Standalone (no I/O). Callers wire fixture\n * discovery + persistence themselves; this kernel is the comparison engine.\n *\n * The shape mirrors the existing v1.1 `lattice eval` cost-regression contract\n * so a future `lattice eval --agent` CLI subcommand can reuse the same gate.\n */\n\nimport type { Usage } from \"../providers/provider.js\";\n\n/**\n * Summary of an agent run sufficient for regression analysis. Callers\n * typically derive this from an `AgentSuccess` via `iterations.length` and\n * cumulative `usage`. The schema is intentionally minimal so callers can\n * persist + load it across runs without dragging the full ReplayEnvelope.\n */\nexport interface AgentRunSnapshot {\n readonly iterationsToGoal: number;\n readonly usage: Usage;\n}\n\nexport interface EvalOptions {\n /**\n * Maximum tolerated INCREASE in iterations-to-goal versus the baseline.\n * Default 1 (one extra iteration tolerated). Set to 0 to require parity.\n */\n readonly iterationsToGoalRegressionLimit?: number;\n /**\n * Maximum tolerated FRACTIONAL cost increase versus the baseline.\n * Default 0.10 (10% increase tolerated). Compared as\n * `(current - baseline) / baseline`. Cost regressions are only\n * considered when BOTH snapshots have a non-null `costUsd`; mixed-cost\n * snapshots emit a `mixed-cost-unknown` regression so callers can decide\n * how to handle them.\n */\n readonly costUsdRegressionLimit?: number;\n}\n\nexport type EvalRegressionKind =\n | \"iterations-to-goal\"\n | \"cost-regression\"\n | \"mixed-cost-unknown\";\n\nexport interface EvalRegression {\n readonly kind: EvalRegressionKind;\n readonly baseline: number | null;\n readonly current: number | null;\n readonly limit: number;\n readonly message: string;\n}\n\nexport interface AgentEvalResult {\n readonly ok: boolean;\n readonly regressions: ReadonlyArray<EvalRegression>;\n}\n\nexport function evalAgentRun(\n baseline: AgentRunSnapshot,\n current: AgentRunSnapshot,\n options: EvalOptions = {},\n): AgentEvalResult {\n const iterLimit = options.iterationsToGoalRegressionLimit ?? 1;\n const costLimit = options.costUsdRegressionLimit ?? 0.1;\n const regressions: EvalRegression[] = [];\n\n // Iterations-to-goal regression.\n const iterDelta = current.iterationsToGoal - baseline.iterationsToGoal;\n if (iterDelta > iterLimit) {\n regressions.push({\n kind: \"iterations-to-goal\",\n baseline: baseline.iterationsToGoal,\n current: current.iterationsToGoal,\n limit: iterLimit,\n message: `Iterations-to-goal ${current.iterationsToGoal} exceeds baseline ${baseline.iterationsToGoal} by ${iterDelta} (limit: ${iterLimit}).`,\n });\n }\n\n // Cost regression.\n const bCost = baseline.usage.costUsd;\n const cCost = current.usage.costUsd;\n if (bCost === null && cCost === null) {\n // Both unmeasured — no signal, no regression.\n } else if (bCost === null || cCost === null) {\n regressions.push({\n kind: \"mixed-cost-unknown\",\n baseline: bCost,\n current: cCost,\n limit: costLimit,\n message: `Cost mixed: baseline=${bCost} current=${cCost}; cannot compare regression.`,\n });\n } else if (bCost > 0) {\n const ratio = (cCost - bCost) / bCost;\n if (ratio > costLimit) {\n regressions.push({\n kind: \"cost-regression\",\n baseline: bCost,\n current: cCost,\n limit: costLimit,\n message: `Cost regression: $${cCost.toFixed(6)} vs baseline $${bCost.toFixed(6)} (+${(ratio * 100).toFixed(1)}%; limit ${(costLimit * 100).toFixed(1)}%).`,\n });\n }\n } else if (bCost === 0 && cCost > 0) {\n // Baseline is free; any positive cost is a regression by definition.\n regressions.push({\n kind: \"cost-regression\",\n baseline: bCost,\n current: cCost,\n limit: costLimit,\n message: `Cost regression: baseline was $0; current $${cCost.toFixed(6)}.`,\n });\n }\n\n return {\n ok: regressions.length === 0,\n regressions: Object.freeze(regressions),\n };\n}\n","import type { ArtifactInput, ArtifactRef } from \"../artifacts/artifact.js\";\nimport { toArtifactRef } from \"../artifacts/artifact.js\";\nimport type {\n ContextPackItemPlan,\n ContextPackPlan,\n SelectedRoute,\n} from \"../plan/plan.js\";\nimport type { SessionRecord } from \"../sessions/session.js\";\n\nexport type TrustLabel = \"developer\" | \"user\" | \"tool\" | \"model-summary\";\n\nexport interface ContextPack extends ContextPackPlan {\n readonly kind: \"context-pack\";\n}\n\nexport interface BuildContextPackInput {\n readonly task: string;\n readonly artifacts: readonly ArtifactInput[];\n readonly route?: SelectedRoute;\n readonly session?: SessionRecord;\n readonly tokenBudget?: number;\n}\n\nexport interface ContextSummarizer {\n summarize(input: {\n readonly artifacts: readonly ArtifactRef[];\n readonly budgetTokens: number;\n }): Promise<readonly ArtifactRef[]> | readonly ArtifactRef[];\n}\n\nexport function buildContextPack(input: BuildContextPackInput): ContextPack {\n const routeBudget =\n input.route?.estimates.inputTokens ?? input.route?.inputModalities.length ?? 0;\n const tokenBudget =\n input.tokenBudget ?? Math.max(512, Math.min(input.route?.estimates.inputTokens ?? 4_000, 16_000));\n const remainingBudget = Math.max(512, tokenBudget - estimateTokens(input.task) - routeBudget);\n const included: ContextPackItemPlan[] = [];\n const summarized: ContextPackItemPlan[] = [];\n const archived: ContextPackItemPlan[] = [];\n const omitted: ContextPackItemPlan[] = [];\n const warnings: string[] = [];\n let usedTokens = 0;\n\n for (const artifact of input.artifacts) {\n const artifactTokens = estimateArtifactTokens(artifact);\n const item: ContextPackItemPlan = {\n artifactId: artifact.id,\n reason: \"Run artifact included for provider consideration.\",\n estimatedTokens: artifactTokens,\n trust: trustForArtifact(artifact),\n };\n\n if (usedTokens + artifactTokens <= remainingBudget) {\n included.push(item);\n usedTokens += artifactTokens;\n continue;\n }\n\n if (artifact.kind === \"text\" || artifact.kind === \"document\" || artifact.kind === \"json\") {\n summarized.push({\n ...item,\n reason: \"Artifact exceeded live context budget and needs summary packaging.\",\n });\n usedTokens += Math.min(artifactTokens, 256);\n continue;\n }\n\n omitted.push({\n ...item,\n reason: \"Artifact exceeded context budget and cannot be summarized by the default packer.\",\n });\n warnings.push(`Artifact ${artifact.id} omitted from live context budget.`);\n }\n\n for (const turn of input.session?.turns ?? []) {\n const turnTokens = estimateTokens(turn.task);\n const item: ContextPackItemPlan = {\n sessionTurnId: turn.id,\n reason: \"Prior session turn retained for continuity.\",\n estimatedTokens: turnTokens,\n trust: \"user\",\n };\n\n if (usedTokens + turnTokens <= remainingBudget) {\n included.push(item);\n usedTokens += turnTokens;\n } else {\n archived.push({\n ...item,\n reason: \"Prior session turn archived because the run budget was exhausted.\",\n });\n }\n }\n\n return {\n id: createContextPackId(),\n kind: \"context-pack\",\n tokenBudget,\n estimatedTokens: usedTokens,\n included,\n summarized,\n archived,\n omitted,\n warnings,\n };\n}\n\nexport function estimateArtifactTokens(artifact: ArtifactInput | ArtifactRef): number {\n if (artifact.size?.characters !== undefined) {\n return estimateTokensFromCharacters(artifact.size.characters);\n }\n\n if (artifact.size?.bytes !== undefined) {\n return estimateTokensFromCharacters(Math.ceil(artifact.size.bytes / 2));\n }\n\n if (\"value\" in artifact && typeof artifact.value === \"string\") {\n return estimateTokens(artifact.value);\n }\n\n if (\"value\" in artifact && artifact.value !== undefined) {\n const serialized = JSON.stringify(artifact.value);\n\n return serialized === undefined ? 64 : estimateTokens(serialized);\n }\n\n return 64;\n}\n\nexport function estimateTokens(value: string): number {\n return Math.max(1, estimateTokensFromCharacters(value.length));\n}\n\nexport function toContextArtifactRefs(\n artifacts: readonly ArtifactInput[],\n): readonly ArtifactRef[] {\n return artifacts.map(toArtifactRef);\n}\n\nfunction estimateTokensFromCharacters(characters: number): number {\n return Math.ceil(characters / 4);\n}\n\nfunction trustForArtifact(artifact: ArtifactRef): TrustLabel {\n if (artifact.source === \"tool\") {\n return \"tool\";\n }\n\n if (artifact.source === \"generated\") {\n return \"model-summary\";\n }\n\n return \"user\";\n}\n\nfunction createContextPackId(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return `context-pack:${crypto.randomUUID()}`;\n }\n\n return `context-pack:${Date.now()}:${Math.random().toString(16).slice(2)}`;\n}\n","export interface PolicySpec {\n readonly maxCostUsd?: number;\n readonly latency?: \"interactive\" | \"batch\";\n readonly privacy?: \"standard\" | \"sensitive\" | \"restricted\";\n readonly providerAllowList?: readonly string[];\n readonly providerDenyList?: readonly string[];\n readonly noUpload?: boolean;\n readonly noPublicUrl?: boolean;\n readonly noLogging?: boolean;\n readonly metadata?: Record<string, unknown>;\n}\n\nexport function mergePolicy(\n defaultPolicy?: PolicySpec,\n runPolicy?: PolicySpec,\n): PolicySpec | undefined {\n if (defaultPolicy === undefined && runPolicy === undefined) {\n return undefined;\n }\n\n return {\n ...defaultPolicy,\n ...runPolicy,\n };\n}\n","import type { ArtifactInput, ArtifactRef } from \"../artifacts/artifact.js\";\nimport { artifact, toArtifactRef } from \"../artifacts/artifact.js\";\nimport type { PolicySpec } from \"../policy/policy.js\";\nimport type {\n ProviderPackagedArtifactPlan,\n ProviderPackagingPlan,\n SelectedRoute,\n} from \"../plan/plan.js\";\nimport type { ProviderTransportMode } from \"./provider.js\";\n\nexport interface ProviderPackagingResult {\n readonly plan: ProviderPackagingPlan;\n readonly packagedArtifacts: readonly ArtifactRef[];\n readonly blocked: readonly string[];\n}\n\nexport function packageArtifactsForProvider(input: {\n readonly artifacts: readonly ArtifactInput[];\n readonly route?: SelectedRoute;\n readonly policy?: PolicySpec;\n}): ProviderPackagingResult {\n const route = input.route;\n\n if (route === undefined) {\n return {\n plan: {\n providerId: \"none\",\n modelId: \"none\",\n artifacts: [],\n warnings: [\"No selected route; provider packaging skipped.\"],\n },\n packagedArtifacts: [],\n blocked: [],\n };\n }\n\n const packaged: ProviderPackagedArtifactPlan[] = [];\n const packagedArtifacts: ArtifactRef[] = [];\n const warnings: string[] = [];\n const blocked: string[] = [];\n\n for (const inputArtifact of input.artifacts) {\n const choice = chooseTransport(inputArtifact, route.fileTransport, input.policy);\n\n if (choice.blocked !== undefined) {\n blocked.push(choice.blocked);\n warnings.push(choice.blocked);\n continue;\n }\n\n packaged.push({\n artifactId: inputArtifact.id,\n transport: choice.transport,\n ...(inputArtifact.mediaType !== undefined ? { mediaType: inputArtifact.mediaType } : {}),\n lineageTransform: \"provider-packaging\",\n warnings: choice.warnings,\n });\n\n packagedArtifacts.push(\n toArtifactRef(\n artifact.derive({\n id: `${inputArtifact.id}:packaged:${route.providerId}:${route.modelId}`,\n kind: inputArtifact.kind,\n source: choice.transport === \"provider-upload\" ? \"provider-upload\" : \"generated\",\n parents: [inputArtifact],\n transform: {\n kind: \"provider-packaging\",\n name: `${route.providerId}:${choice.transport}`,\n metadata: {\n providerId: route.providerId,\n modelId: route.modelId,\n transport: choice.transport,\n },\n },\n metadata: {\n providerId: route.providerId,\n modelId: route.modelId,\n transport: choice.transport,\n },\n ...(inputArtifact.mediaType !== undefined ? { mediaType: inputArtifact.mediaType } : {}),\n privacy: inputArtifact.privacy,\n }),\n ),\n );\n }\n\n return {\n plan: {\n providerId: route.providerId,\n modelId: route.modelId,\n artifacts: packaged,\n warnings,\n },\n packagedArtifacts,\n blocked,\n };\n}\n\nfunction chooseTransport(\n inputArtifact: ArtifactInput,\n supported: readonly ProviderTransportMode[],\n policy?: PolicySpec,\n): {\n readonly transport: ProviderTransportMode;\n readonly warnings: readonly string[];\n readonly blocked?: string;\n} {\n const warnings: string[] = [];\n const preferred = preferredTransports(inputArtifact);\n\n for (const transport of preferred) {\n if (!supported.includes(transport)) {\n continue;\n }\n\n if (policy?.noUpload === true && transport === \"provider-upload\") {\n continue;\n }\n\n if (policy?.noPublicUrl === true && transport === \"url\") {\n continue;\n }\n\n if (\n inputArtifact.privacy === \"restricted\" &&\n (transport === \"provider-upload\" || transport === \"url\" || transport === \"base64\")\n ) {\n continue;\n }\n\n if (transport === \"base64\") {\n warnings.push(`Artifact ${inputArtifact.id} will be encoded as base64.`);\n }\n\n return { transport, warnings };\n }\n\n return {\n transport: \"inline\",\n warnings,\n blocked: `No policy-safe transport for artifact ${inputArtifact.id}.`,\n };\n}\n\nfunction preferredTransports(inputArtifact: ArtifactInput): readonly ProviderTransportMode[] {\n switch (inputArtifact.kind) {\n case \"text\":\n return [\"inline\", \"extracted-text\"];\n case \"json\":\n case \"tool-result\":\n return [\"json\", \"inline\"];\n case \"url\":\n return [\"url\", \"inline\"];\n case \"document\":\n return [\"extracted-text\", \"provider-upload\", \"base64\", \"url\"];\n case \"audio\":\n return [\"transcript\", \"provider-upload\", \"base64\", \"url\"];\n case \"image\":\n case \"file\":\n case \"video\":\n return [\"provider-upload\", \"base64\", \"url\"];\n }\n}\n","import type { ArtifactInput } from \"../artifacts/artifact.js\";\nimport type { CapabilityContract } from \"../contract/contract.js\";\nimport { evaluateContractAgainstRoute } from \"../contract/preflight.js\";\nimport type { OutputContract, OutputContractMap } from \"../outputs/contracts.js\";\nimport type { PolicySpec } from \"../policy/policy.js\";\nimport type {\n CapabilityModality,\n ModelCapability,\n} from \"../providers/provider.js\";\nimport type {\n RouteCandidate,\n RouteDecision,\n RouteEstimates,\n RouteRejectReason,\n} from \"../plan/plan.js\";\nimport { estimateArtifactTokens, estimateTokens } from \"../context/context-pack.js\";\nimport type { CapabilityCatalog } from \"./catalog.js\";\n\nexport interface RouteRequest {\n readonly task: string;\n readonly artifacts: readonly ArtifactInput[];\n readonly outputs: OutputContractMap;\n readonly policy?: PolicySpec;\n readonly provider?: string;\n readonly model?: string;\n readonly contract?: CapabilityContract;\n}\n\nexport function routeDeterministically(\n catalog: CapabilityCatalog,\n request: RouteRequest,\n): RouteDecision {\n const requiredInputs = requiredInputModalities(request.artifacts);\n const requiredOutputs = requiredOutputModalities(request.outputs);\n const requiresStructuredOutput = outputRequiresStructuredOutput(request.outputs);\n const estimatedInputTokens =\n estimateTokens(request.task) +\n request.artifacts.reduce((total, artifact) => total + estimateArtifactTokens(artifact), 0);\n const candidates = catalog.models\n .map((capability, index) =>\n evaluateCapability(capability, {\n requiredInputs,\n requiredOutputs,\n requiresStructuredOutput,\n estimatedInputTokens,\n ...(request.policy !== undefined ? { policy: request.policy } : {}),\n ...(request.provider !== undefined ? { provider: request.provider } : {}),\n ...(request.model !== undefined ? { model: request.model } : {}),\n ...(request.contract !== undefined ? { contract: request.contract } : {}),\n index,\n }),\n )\n .sort(compareCandidates);\n const accepted = candidates.filter((candidate) => candidate.accepted);\n const selected = accepted[0];\n\n return {\n catalogVersion: catalog.version,\n ...(selected !== undefined\n ? {\n selected: {\n providerId: selected.providerId,\n modelId: selected.modelId,\n score: selected.score,\n estimates: selected.estimates,\n inputModalities: selected.capability.inputModalities,\n outputModalities: selected.capability.outputModalities,\n fileTransport: selected.capability.fileTransport,\n },\n }\n : {}),\n candidates,\n rejected: candidates.filter((candidate) => !candidate.accepted),\n fallbackChain: accepted.slice(1).map((candidate) => ({\n providerId: candidate.providerId,\n modelId: candidate.modelId,\n score: candidate.score,\n reason: \"policy-preserving-fallback\",\n })),\n noRouteReasons:\n selected === undefined\n ? summarizeNoRouteReasons(candidates)\n : [],\n };\n}\n\nfunction evaluateCapability(\n capability: ModelCapability,\n input: {\n readonly requiredInputs: readonly CapabilityModality[];\n readonly requiredOutputs: readonly CapabilityModality[];\n readonly requiresStructuredOutput: boolean;\n readonly estimatedInputTokens: number;\n readonly policy?: PolicySpec;\n readonly provider?: string;\n readonly model?: string;\n readonly contract?: CapabilityContract;\n readonly index: number;\n },\n): RouteCandidate {\n const reasons: RouteRejectReason[] = [];\n\n if (capability.available === false) {\n reasons.push({\n code: \"provider-unavailable\",\n message: `${capability.providerId}/${capability.modelId} is not available.`,\n });\n }\n\n if (input.provider !== undefined && capability.providerId !== input.provider) {\n reasons.push({\n code: \"provider-forced-mismatch\",\n message: `Provider override requires ${input.provider}.`,\n });\n }\n\n if (input.model !== undefined && capability.modelId !== input.model) {\n reasons.push({\n code: \"model-forced-mismatch\",\n message: `Model override requires ${input.model}.`,\n });\n }\n\n for (const modality of input.requiredInputs) {\n if (!capability.inputModalities.includes(modality)) {\n reasons.push({\n code: \"input-modality-unsupported\",\n message: `${capability.modelId} does not support ${modality} input.`,\n });\n }\n }\n\n for (const modality of input.requiredOutputs) {\n if (!capability.outputModalities.includes(modality)) {\n reasons.push({\n code: \"output-modality-unsupported\",\n message: `${capability.modelId} does not support ${modality} output.`,\n });\n }\n }\n\n if (input.requiresStructuredOutput && !capability.structuredOutput) {\n reasons.push({\n code: \"structured-output-unsupported\",\n message: `${capability.modelId} does not support structured output contracts.`,\n });\n }\n\n if (input.estimatedInputTokens > capability.contextWindow) {\n reasons.push({\n code: \"context-window-exceeded\",\n message: `Estimated input ${input.estimatedInputTokens} tokens exceeds ${capability.contextWindow}.`,\n });\n }\n\n const estimates = estimateRoute(capability, input.estimatedInputTokens);\n addPolicyRejectReasons(reasons, capability, estimates, input.policy);\n\n // Phase 7 contract preflight — reuse the router's own output-token estimate\n // so preflight and the router agree on the projected output size (one source\n // of truth, consumed by Phase 9 receipts).\n const contractResult = evaluateContractAgainstRoute(input.contract, {\n capability,\n estimatedInputTokens: input.estimatedInputTokens,\n estimatedOutputTokens: estimates.outputTokens,\n });\n for (const reason of contractResult.reasons) {\n reasons.push(reason);\n }\n\n const score = scoreCapability(capability, estimates, input.index);\n\n return {\n providerId: capability.providerId,\n modelId: capability.modelId,\n capability,\n score,\n accepted: reasons.length === 0,\n reasons,\n estimates,\n };\n}\n\nfunction addPolicyRejectReasons(\n reasons: RouteRejectReason[],\n capability: ModelCapability,\n estimates: RouteEstimates,\n policy?: PolicySpec,\n): void {\n if (policy === undefined) {\n return;\n }\n\n if (\n policy.providerAllowList !== undefined &&\n !policy.providerAllowList.includes(capability.providerId)\n ) {\n reasons.push({\n code: \"provider-not-allowed\",\n message: `${capability.providerId} is not in the provider allow list.`,\n });\n }\n\n if (policy.providerDenyList?.includes(capability.providerId) === true) {\n reasons.push({\n code: \"provider-denied\",\n message: `${capability.providerId} is in the provider deny list.`,\n });\n }\n\n if (\n policy.privacy !== undefined &&\n !capability.dataPolicy.privacy.includes(policy.privacy)\n ) {\n reasons.push({\n code: \"privacy-unsupported\",\n message: `${capability.modelId} does not satisfy ${policy.privacy} privacy.`,\n });\n }\n\n if (policy.noLogging === true && capability.dataPolicy.supportsNoLogging !== true) {\n reasons.push({\n code: \"no-logging-unsupported\",\n message: `${capability.modelId} cannot satisfy noLogging.`,\n });\n }\n\n if (\n policy.noUpload === true &&\n capability.fileTransport.length > 0 &&\n capability.fileTransport.every((transport) => transport === \"provider-upload\")\n ) {\n reasons.push({\n code: \"no-upload-violated\",\n message: `${capability.modelId} requires an upload transport disallowed by policy.`,\n });\n }\n\n if (policy.latency !== undefined && capability.latency !== policy.latency) {\n reasons.push({\n code: \"latency-class-mismatch\",\n message: `${capability.modelId} latency class is ${capability.latency}, not ${policy.latency}.`,\n });\n }\n\n if (\n policy.maxCostUsd !== undefined &&\n estimates.costUsd !== undefined &&\n estimates.costUsd > policy.maxCostUsd\n ) {\n reasons.push({\n code: \"budget-exceeded\",\n message: `${capability.modelId} estimated cost ${estimates.costUsd} exceeds maxCostUsd ${policy.maxCostUsd}.`,\n });\n }\n}\n\nfunction estimateRoute(\n capability: ModelCapability,\n inputTokens: number,\n): RouteEstimates {\n const outputTokens = 512;\n const inputCost =\n capability.pricing?.inputCostPer1M === undefined\n ? undefined\n : (inputTokens / 1_000_000) * capability.pricing.inputCostPer1M;\n const outputCost =\n capability.pricing?.outputCostPer1M === undefined\n ? undefined\n : (outputTokens / 1_000_000) * capability.pricing.outputCostPer1M;\n\n return {\n inputTokens,\n outputTokens,\n ...(inputCost !== undefined || outputCost !== undefined\n ? { costUsd: (inputCost ?? 0) + (outputCost ?? 0) }\n : {}),\n latencyMs: capability.latency === \"interactive\" ? 1_000 : 10_000,\n };\n}\n\nfunction scoreCapability(\n capability: ModelCapability,\n estimates: RouteEstimates,\n index: number,\n): number {\n const costScore = Math.round((estimates.costUsd ?? 0) * 1_000_000);\n const latencyScore = capability.latency === \"interactive\" ? 0 : 100_000;\n const contextHeadroom = Math.max(0, capability.contextWindow - estimates.inputTokens);\n const contextScore = Math.max(0, 10_000 - Math.min(contextHeadroom, 10_000));\n\n return costScore + latencyScore + contextScore + index;\n}\n\nfunction compareCandidates(left: RouteCandidate, right: RouteCandidate): number {\n if (left.accepted !== right.accepted) {\n return left.accepted ? -1 : 1;\n }\n\n if (left.score !== right.score) {\n return left.score - right.score;\n }\n\n const provider = left.providerId.localeCompare(right.providerId);\n\n return provider === 0 ? left.modelId.localeCompare(right.modelId) : provider;\n}\n\nfunction requiredInputModalities(\n artifacts: readonly ArtifactInput[],\n): readonly CapabilityModality[] {\n const modalities = new Set<CapabilityModality>([\"text\"]);\n\n for (const artifact of artifacts) {\n switch (artifact.kind) {\n case \"text\":\n modalities.add(\"text\");\n break;\n case \"json\":\n modalities.add(\"json\");\n break;\n case \"image\":\n modalities.add(\"image\");\n break;\n case \"audio\":\n modalities.add(\"audio\");\n break;\n case \"video\":\n modalities.add(\"video\");\n break;\n case \"document\":\n modalities.add(\"document\");\n break;\n case \"url\":\n modalities.add(\"url\");\n break;\n case \"tool-result\":\n modalities.add(\"tool\");\n break;\n case \"file\":\n modalities.add(\"file\");\n break;\n }\n }\n\n return [...modalities];\n}\n\nfunction requiredOutputModalities(\n outputs: OutputContractMap,\n): readonly CapabilityModality[] {\n const modalities = new Set<CapabilityModality>();\n\n for (const contract of Object.values(outputs)) {\n if (contract === \"text\") {\n modalities.add(\"text\");\n continue;\n }\n\n if (isStructuredContract(contract)) {\n modalities.add(\"json\");\n continue;\n }\n\n if (isReferenceContract(contract)) {\n modalities.add(\"json\");\n }\n }\n\n return [...modalities];\n}\n\nfunction outputRequiresStructuredOutput(outputs: OutputContractMap): boolean {\n return Object.values(outputs).some(isStructuredContract);\n}\n\nfunction isStructuredContract(contract: OutputContract): boolean {\n return (\n typeof contract === \"object\" &&\n contract !== null &&\n \"~standard\" in contract\n );\n}\n\nfunction isReferenceContract(contract: OutputContract): boolean {\n return (\n typeof contract === \"object\" &&\n contract !== null &&\n \"kind\" in contract &&\n (contract.kind === \"citations\" || contract.kind === \"artifacts\")\n );\n}\n\nfunction summarizeNoRouteReasons(\n candidates: readonly RouteCandidate[],\n): readonly RouteRejectReason[] {\n if (candidates.length === 0) {\n return [\n {\n code: \"catalog-empty\",\n message: \"No provider capabilities are configured.\",\n },\n ];\n }\n\n const unique = new Map<string, RouteRejectReason>();\n\n for (const candidate of candidates) {\n for (const reason of candidate.reasons) {\n unique.set(reason.code, reason);\n }\n }\n\n return [...unique.values()];\n}\n","import type { ArtifactFingerprint } from \"../artifacts/artifact.js\";\n\nconst textEncoder = new TextEncoder();\n\nexport async function fingerprintArtifactValue(\n value: unknown,\n): Promise<ArtifactFingerprint | undefined> {\n const bytes = await valueToBytes(value);\n\n if (bytes === undefined) {\n return undefined;\n }\n\n const digest = await crypto.subtle.digest(\"SHA-256\", toArrayBuffer(bytes));\n\n return {\n algorithm: \"sha256\",\n value: toHex(new Uint8Array(digest)),\n };\n}\n\nasync function valueToBytes(value: unknown): Promise<Uint8Array | undefined> {\n if (typeof value === \"string\") {\n return textEncoder.encode(value);\n }\n\n if (value instanceof Uint8Array) {\n return value;\n }\n\n if (value instanceof ArrayBuffer) {\n return new Uint8Array(value);\n }\n\n if (isBlobLike(value)) {\n return new Uint8Array(await value.arrayBuffer());\n }\n\n const serialized = JSON.stringify(value);\n\n return serialized === undefined ? undefined : textEncoder.encode(serialized);\n}\n\nfunction isBlobLike(value: unknown): value is Blob {\n return typeof Blob !== \"undefined\" && value instanceof Blob;\n}\n\nfunction toHex(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction toArrayBuffer(bytes: Uint8Array): ArrayBuffer {\n const copy = new Uint8Array(bytes.byteLength);\n copy.set(bytes);\n\n return copy.buffer as ArrayBuffer;\n}\n","import type { PolicySpec } from \"../policy/policy.js\";\nimport type {\n ProviderAdapter,\n ProviderRef,\n ProviderRegistryInput,\n} from \"../providers/provider.js\";\nimport type { ReceiptSigner } from \"../receipts/types.js\";\nimport type { SessionStore } from \"../sessions/session.js\";\nimport type { StorageLike } from \"../storage/storage.js\";\nimport type { RunEventSink, TracerLike } from \"../tracing/tracing.js\";\n\nexport interface LatticeConfig {\n readonly providers?: ProviderRegistryInput;\n readonly storage?: StorageLike | false;\n readonly sessions?: SessionStore | false;\n readonly defaults?: { readonly policy?: PolicySpec };\n readonly tracing?: TracerLike | false;\n readonly events?: RunEventSink | readonly RunEventSink[];\n /**\n * Phase 9 — when configured, every terminal branch of `ai.run` emits a\n * signed `CapabilityReceipt` attached to `RunResult.receipt`. When absent,\n * no receipts are issued and `RunResult.receipt` is undefined.\n */\n readonly signer?: ReceiptSigner;\n}\n\nexport type NormalizedProviderEntry = ProviderRef | ProviderAdapter;\n\nexport interface NormalizedLatticeConfig {\n readonly providers: readonly NormalizedProviderEntry[];\n readonly storage?: StorageLike;\n readonly sessions?: SessionStore;\n readonly defaults: { readonly policy?: PolicySpec };\n readonly tracing?: TracerLike;\n readonly events: readonly RunEventSink[];\n readonly signer?: ReceiptSigner;\n}\n\nexport function normalizeConfig(config: LatticeConfig = {}): NormalizedLatticeConfig {\n const normalized: {\n providers: readonly NormalizedProviderEntry[];\n defaults: { readonly policy?: PolicySpec };\n storage?: StorageLike;\n sessions?: SessionStore;\n tracing?: TracerLike;\n events: readonly RunEventSink[];\n signer?: ReceiptSigner;\n } = {\n providers: normalizeProviders(config.providers),\n defaults: config.defaults ?? {},\n events: normalizeEventSinks(config.events),\n };\n\n if (config.storage !== undefined && config.storage !== false) {\n normalized.storage = config.storage;\n }\n\n if (config.sessions !== undefined && config.sessions !== false) {\n normalized.sessions = config.sessions;\n }\n\n if (config.tracing !== undefined && config.tracing !== false) {\n normalized.tracing = config.tracing;\n }\n\n if (config.signer !== undefined) {\n normalized.signer = config.signer;\n }\n\n return normalized;\n}\n\nfunction normalizeEventSinks(\n events: RunEventSink | readonly RunEventSink[] | undefined,\n): readonly RunEventSink[] {\n if (events === undefined) {\n return [];\n }\n\n return typeof events === \"function\" ? [events] : events;\n}\n\nfunction normalizeProviders(\n providers: ProviderRegistryInput = [],\n): readonly NormalizedProviderEntry[] {\n return providers.map((provider) => {\n if (typeof provider === \"string\") {\n return {\n id: provider,\n kind: \"provider-ref\",\n };\n }\n\n return provider;\n });\n}\n","import canonicalize from \"canonicalize\";\n\nimport type { ArtifactInput, ArtifactRef } from \"../artifacts/artifact.js\";\nimport { toArtifactRef } from \"../artifacts/artifact.js\";\nimport { getCapabilityProfile } from \"../capabilities/lookup.js\";\nimport type { TrainingClass } from \"../capabilities/profile.js\";\nimport type { CapabilityContract } from \"../contract/contract.js\";\nimport { evaluateTripwires, type TripwireEvidence } from \"../contract/tripwire.js\";\nimport {\n buildContextPack,\n type ContextPack,\n type ContextSummarizer,\n} from \"../context/context-pack.js\";\nimport type { OutputContractMap } from \"../outputs/contracts.js\";\nimport { validateOutputMap } from \"../outputs/validate.js\";\nimport {\n createExecutionPlan,\n markStage,\n withPlanStatus,\n type ExecutionPlan,\n type ProviderAttemptRecord,\n type RouteRejectReason,\n type SelectedRoute,\n type UsageRecord,\n} from \"../plan/plan.js\";\nimport { mergePolicy, type PolicySpec } from \"../policy/policy.js\";\nimport { packageArtifactsForProvider } from \"../providers/packaging.js\";\nimport type {\n ProviderAdapter,\n ProviderRunRequest,\n ProviderRunResponse,\n Usage,\n} from \"../providers/provider.js\";\nimport { createReceipt } from \"../receipts/receipt.js\";\nimport type {\n ContractVerdict,\n ReceiptEnvelope,\n ReceiptModel,\n ReceiptRoute,\n} from \"../receipts/types.js\";\nimport { createCapabilityCatalog } from \"../routing/catalog.js\";\nimport { routeDeterministically } from \"../routing/router.js\";\nimport type { RunResult } from \"../results/result.js\";\nimport type { SessionRecord, SessionRef } from \"../sessions/session.js\";\nimport { fingerprintArtifactValue } from \"../storage/fingerprint.js\";\nimport { runTool, type ToolCallResult, type ToolDefinition } from \"../tools/tools.js\";\nimport { createRunEvent, type RunEvent } from \"../tracing/tracing.js\";\nimport {\n normalizeConfig,\n type LatticeConfig,\n type NormalizedLatticeConfig,\n} from \"./config.js\";\n\nexport interface RuntimeOverrides {\n readonly provider?: string;\n readonly model?: string;\n readonly routingPolicy?: PolicySpec;\n readonly tokenBudget?: number;\n readonly summarizer?: ContextSummarizer;\n readonly transforms?: readonly RuntimeArtifactTransform[];\n readonly hooks?: RuntimeHooks;\n}\n\nexport interface RuntimeArtifactTransform {\n readonly name: string;\n transform(input: {\n readonly task: string;\n readonly artifacts: readonly ArtifactInput[];\n }): Promise<ArtifactInput | readonly ArtifactInput[]> | ArtifactInput | readonly ArtifactInput[];\n}\n\nexport interface RuntimeHooks {\n readonly beforeProviderCall?: (input: {\n readonly plan: ExecutionPlan;\n readonly request: ProviderRunRequest;\n }) => void | Promise<void>;\n readonly afterProviderCall?: (input: {\n readonly plan: ExecutionPlan;\n readonly response: unknown;\n }) => void | Promise<void>;\n}\n\nexport interface RunIntent<TOutputs extends OutputContractMap> {\n readonly task: string;\n readonly artifacts?: readonly ArtifactInput[];\n readonly outputs: TOutputs;\n readonly policy?: PolicySpec;\n readonly session?: SessionRef;\n readonly signal?: AbortSignal;\n readonly overrides?: RuntimeOverrides;\n readonly tools?: readonly ToolDefinition<any>[];\n readonly toolInputs?: Record<string, unknown>;\n readonly contract?: CapabilityContract;\n}\n\nconst ZERO_USAGE: Usage = { promptTokens: 0, completionTokens: 0, costUsd: 0 };\nconst UNMEASURED_USAGE: Usage = { promptTokens: 0, completionTokens: 0, costUsd: null };\n\nexport interface AI {\n session(id: string): SessionRef;\n plan<const TOutputs extends OutputContractMap>(\n intent: RunIntent<TOutputs>,\n ): Promise<ExecutionPlan>;\n run<const TOutputs extends OutputContractMap>(\n intent: RunIntent<TOutputs>,\n ): Promise<RunResult<TOutputs>>;\n /**\n * Phase 19 (v1.2): single-agent execution loop. Drives multiple provider\n * iterations under one call, dispatching tool requests between iterations.\n * Composes with the v1.2 hook pipeline (SAFETY-band veto, OBSERVABILITY-band\n * checkpoint receipts) and the v1.2 capability receipts (when\n * `intent.signer` is provided + `intent.autoRegisterCheckpoint !== false`).\n *\n * See `packages/lattice/src/agent/runtime.ts` for orchestration details.\n */\n runAgent<const TOutputs extends OutputContractMap>(\n intent: import(\"../agent/types.js\").AgentIntent<TOutputs>,\n ): Promise<import(\"../agent/types.js\").AgentResult<TOutputs>>;\n /**\n * Phase 39 (v1.3): opt-in multi-agent crew execution. Runs a literal\n * `AgentSpec` tree through the existing single-agent loop plus the crew\n * dispatcher, with shared budget/rate-limit coordination and chained\n * completion receipts.\n *\n * See `packages/lattice/src/agent/crew/run-crew.ts` for orchestration details.\n */\n runAgentCrew(\n options: import(\"../agent/crew/run-crew.js\").RunAgentCrewOptions,\n ): Promise<import(\"../agent/crew/run-crew.js\").CrewResult>;\n}\n\ninterface BuiltPlan {\n readonly plan: ExecutionPlan;\n readonly artifacts: readonly ArtifactInput[];\n readonly contextPack: ContextPack;\n readonly packagedArtifacts: readonly ArtifactRef[];\n readonly blockedPackaging: readonly string[];\n readonly toolResults: readonly ToolCallResult[];\n readonly mergedPolicy?: PolicySpec;\n readonly sessionRecord?: SessionRecord;\n}\n\nexport function createAI(config: LatticeConfig = {}): AI {\n const normalized = normalizeConfig(config);\n\n return {\n session(id: string): SessionRef {\n return {\n id,\n kind: \"session-ref\",\n };\n },\n async plan<const TOutputs extends OutputContractMap>(\n intent: RunIntent<TOutputs>,\n ): Promise<ExecutionPlan> {\n return (await buildPlan(normalized, intent)).plan;\n },\n run<const TOutputs extends OutputContractMap>(\n intent: RunIntent<TOutputs>,\n ): Promise<RunResult<TOutputs>> {\n return runWithConfig(normalized, intent);\n },\n runAgent<const TOutputs extends OutputContractMap>(\n intent: import(\"../agent/types.js\").AgentIntent<TOutputs>,\n ): Promise<import(\"../agent/types.js\").AgentResult<TOutputs>> {\n // Lazy import avoids a hard cycle (agent/runtime.ts imports from\n // ../runtime/config.js for its `LatticeConfig` parameter type only).\n return import(\"../agent/runtime.js\").then((mod) => mod.runAgent(intent, config));\n },\n runAgentCrew(\n options: import(\"../agent/crew/run-crew.js\").RunAgentCrewOptions,\n ): Promise<import(\"../agent/crew/run-crew.js\").CrewResult> {\n // Lazy import mirrors runAgent and avoids pulling the crew surface\n // into the beginner `run()` path unless explicitly used.\n return import(\"../agent/crew/run-crew.js\").then((mod) =>\n mod.runAgentCrew(options, config),\n );\n },\n };\n}\n\nasync function runWithConfig<const TOutputs extends OutputContractMap>(\n normalized: NormalizedLatticeConfig,\n intent: RunIntent<TOutputs>,\n): Promise<RunResult<TOutputs>> {\n if (intent.signal?.aborted === true) {\n throw new DOMException(\"Run aborted before execution.\", \"AbortError\");\n }\n\n const runId = createRunId();\n const events: RunEvent[] = [];\n await emitEvent(normalized, events, createRunEvent(\"run.start\", { runId }));\n\n const built = await buildPlan(normalized, intent, runId, events);\n let plan = built.plan;\n const selected = plan.route.selected;\n\n if (selected === undefined) {\n const contractReasons = plan.route.noRouteReasons.filter(\n (r) =>\n r.code === \"contract-budget-exceeded\" ||\n r.code === \"contract-quality-floor\" ||\n r.code === \"contract-modality-missing\" ||\n r.code === \"contract-privacy-mismatch\",\n );\n const isContractFailure = contractReasons.length > 0;\n const receipt = await maybeIssueReceipt(normalized, {\n runId,\n ...(intent.contract !== undefined ? { contract: intent.contract } : {}),\n artifacts: intent.artifacts ?? [],\n contractVerdict: isContractFailure\n ? \"no-contract-match\"\n : \"execution-failed\",\n model: {\n requested: intent.overrides?.model ?? \"\",\n observed: null,\n },\n route: { providerId: \"\", capabilityId: \"\", attemptNumber: 0 },\n usage: ZERO_USAGE,\n ...(isContractFailure\n ? { noRouteReasons: plan.route.noRouteReasons }\n : {}),\n });\n const failure: RunResult<TOutputs> = isContractFailure\n ? {\n ok: false as const,\n error: {\n kind: \"no-contract-match\" as const,\n message: \"No route satisfies the contract.\",\n noRouteReasons: plan.route.noRouteReasons,\n },\n usage: { ...ZERO_USAGE },\n plan,\n events,\n ...(receipt !== undefined ? { receipt } : {}),\n }\n : {\n ok: false as const,\n error: {\n kind: \"no_route\" as const,\n message: \"No route satisfied the run requirements.\",\n reasons: plan.route.noRouteReasons.map((reason) => reason.message),\n },\n usage: { ...ZERO_USAGE },\n plan,\n events,\n ...(receipt !== undefined ? { receipt } : {}),\n };\n await emitEvent(normalized, events, createRunEvent(\"run.failed\", {\n runId,\n planId: plan.id,\n metadata: { reason: isContractFailure ? \"no-contract-match\" : \"no-route\" },\n }));\n\n return failure;\n }\n\n const routes = [\n selected,\n ...plan.route.fallbackChain.map((fallback) =>\n routeFromCandidate(plan, fallback.providerId, fallback.modelId) ?? {\n providerId: fallback.providerId,\n modelId: fallback.modelId,\n score: fallback.score,\n estimates: selected.estimates,\n inputModalities: selected.inputModalities,\n outputModalities: selected.outputModalities,\n fileTransport: selected.fileTransport,\n } satisfies SelectedRoute,\n ),\n ];\n const attempts: ProviderAttemptRecord[] = [];\n let lastError: Error | undefined;\n let anyExecutableAdapter = false;\n\n for (const [index, route] of routes.entries()) {\n const adapter = findExecutableAdapter(normalized, route.providerId);\n\n if (adapter === undefined) {\n lastError = new Error(\"No Phase 1 provider adapter with execute() is configured.\");\n continue;\n }\n\n anyExecutableAdapter = true;\n\n if (index > 0) {\n await emitEvent(normalized, events, createRunEvent(\"fallback.activated\", {\n runId,\n planId: plan.id,\n providerId: route.providerId,\n modelId: route.modelId,\n }));\n }\n\n const startedAt = new Date().toISOString();\n const attemptPackaging = packageArtifactsForProvider({\n artifacts: built.artifacts,\n route,\n ...(built.mergedPolicy !== undefined ? { policy: built.mergedPolicy } : {}),\n });\n\n if (attemptPackaging.blocked.length > 0) {\n const message = attemptPackaging.blocked.join(\"; \");\n attempts.push(attemptFailed(route.providerId, route.modelId, startedAt, new Date().toISOString(), message));\n lastError = new Error(message);\n continue;\n }\n\n const request: ProviderRunRequest = {\n task: intent.task,\n artifacts: built.artifacts,\n outputs: Object.keys(intent.outputs),\n outputContracts: intent.outputs,\n ...(built.mergedPolicy !== undefined ? { policy: built.mergedPolicy } : {}),\n ...(intent.signal !== undefined ? { signal: intent.signal } : {}),\n plan,\n contextPack: built.contextPack,\n providerPackaging: attemptPackaging.plan,\n packagedArtifacts: attemptPackaging.packagedArtifacts,\n };\n\n try {\n await emitEvent(normalized, events, createRunEvent(\"provider.attempt\", {\n runId,\n planId: plan.id,\n providerId: route.providerId,\n modelId: route.modelId,\n metadata: { status: \"started\", fallback: index > 0 },\n }));\n await intent.overrides?.hooks?.beforeProviderCall?.({ plan, request });\n\n plan = withPlanStatus(plan, \"running\", {\n stages: markStage(plan.stages, \"execution\", \"running\"),\n attempts: [\n ...attempts,\n {\n providerId: route.providerId,\n modelId: route.modelId,\n status: \"running\",\n startedAt,\n },\n ],\n });\n\n const response = await adapter.execute(request);\n await intent.overrides?.hooks?.afterProviderCall?.({ plan, response });\n\n const completedAt = new Date().toISOString();\n const validation = await validateOutputMap(intent.outputs, response.rawOutputs, plan);\n const succeededAttempt = attemptSucceeded(\n route.providerId,\n route.modelId,\n startedAt,\n completedAt,\n response.usage,\n );\n\n if (!validation.ok) {\n attempts.push({\n ...succeededAttempt,\n status: \"failed\",\n error: validation.error.message,\n });\n const failedPlan = withPlanStatus(plan, \"failed\", {\n stages: markStage(plan.stages, \"validation\", \"failed\"),\n attempts,\n });\n await emitEvent(normalized, events, createRunEvent(\"validation.failed\", {\n runId,\n planId: plan.id,\n providerId: route.providerId,\n modelId: route.modelId,\n metadata: { error: validation.error.message },\n }));\n if (index === routes.length - 1) {\n const receipt = await maybeIssueReceipt(normalized, {\n runId,\n ...(intent.contract !== undefined\n ? { contract: intent.contract }\n : {}),\n artifacts: built.artifacts,\n contractVerdict: \"validation-failed\",\n model: { requested: route.modelId, observed: null },\n route: {\n providerId: route.providerId,\n capabilityId: route.modelId,\n attemptNumber: attempts.length,\n },\n usage: normalizeAdapterUsage(response),\n });\n return {\n ...validation,\n usage: normalizeAdapterUsage(response),\n plan: failedPlan,\n events,\n ...(receipt !== undefined ? { receipt } : {}),\n };\n }\n lastError = new Error(validation.error.message);\n continue;\n }\n\n // Phase 8 tripwire evaluation — TRIP-02, TRIP-03, TRIP-04, TRIP-05.\n // Runs ONLY when output schema validation succeeded (we are inside the\n // `validation.ok === true` branch). First violation aborts the run\n // and short-circuits the fallback chain (terminal by construction —\n // see the early return below).\n const invariants = intent.contract?.invariants ?? [];\n if (invariants.length > 0) {\n // validation.ok === true was just verified; narrow to the success\n // shape so we can hand the validated outputs to the evaluator.\n const validatedSuccess = validation as Extract<typeof validation, { ok: true }>;\n const tripwireResult = await evaluateTripwires(\n validatedSuccess.outputs,\n invariants,\n );\n if (!tripwireResult.ok) {\n const tripwireFailedAt = new Date().toISOString();\n attempts.push({\n ...succeededAttempt,\n status: \"failed\",\n error: tripwireResult.evidence.message,\n completedAt: tripwireFailedAt,\n });\n const failedPlan = withPlanStatus(plan, \"failed\", {\n stages: markStage(\n markStage(\n markStage(plan.stages, \"execution\", \"completed\"),\n \"validation\",\n \"completed\",\n ),\n \"tripwire\",\n \"failed\",\n { invariantId: tripwireResult.evidence.invariantId },\n ),\n attempts,\n });\n await emitEvent(\n normalized,\n events,\n createRunEvent(\"run.failed\", {\n runId,\n planId: failedPlan.id,\n providerId: route.providerId,\n modelId: route.modelId,\n metadata: {\n reason: \"tripwire-violated\",\n invariantId: tripwireResult.evidence.invariantId,\n },\n }),\n );\n const receipt = await maybeIssueReceipt(normalized, {\n runId,\n ...(intent.contract !== undefined\n ? { contract: intent.contract }\n : {}),\n artifacts: built.artifacts,\n contractVerdict: \"tripwire-violated\",\n model: { requested: route.modelId, observed: null },\n route: {\n providerId: route.providerId,\n capabilityId: route.modelId,\n attemptNumber: attempts.length,\n },\n usage: normalizeAdapterUsage(response),\n tripwireEvidence: tripwireResult.evidence,\n });\n // TERMINAL by design — isTerminal(error) === true; fallback chain\n // bypassed via early return before the `for` loop advances.\n return {\n ok: false,\n error: {\n kind: \"tripwire-violated\" as const,\n message: tripwireResult.evidence.message,\n invariantId: tripwireResult.evidence.invariantId,\n evidence: tripwireResult.evidence,\n terminal: true as const,\n },\n usage: normalizeAdapterUsage(response),\n plan: failedPlan,\n events,\n ...(receipt !== undefined ? { receipt } : {}),\n };\n }\n }\n\n attempts.push(succeededAttempt);\n const artifactRefs =\n response.artifactRefs !== undefined\n ? response.artifactRefs.map(toArtifactRef)\n : [];\n const completedPlan = withPlanStatus(plan, \"completed\", {\n stages: markStage(\n markStage(\n markStage(\n markStage(\n markStage(plan.stages, \"execution\", \"completed\"),\n \"validation\",\n \"completed\",\n ),\n \"persistence\",\n \"completed\",\n ),\n \"tool-execution\",\n built.toolResults.length > 0 ? \"completed\" : \"skipped\",\n ),\n \"tripwire\",\n invariants.length > 0 ? \"completed\" : \"skipped\",\n ),\n attempts,\n });\n\n if (built.sessionRecord !== undefined && normalized.sessions !== undefined) {\n await normalized.sessions.appendTurn({\n sessionId: built.sessionRecord.id,\n task: intent.task,\n artifactRefs: built.artifacts.map(toArtifactRef),\n outputArtifactRefs: artifactRefs,\n planId: completedPlan.id,\n });\n }\n\n await emitEvent(normalized, events, createRunEvent(\"validation.complete\", {\n runId,\n planId: completedPlan.id,\n providerId: route.providerId,\n modelId: route.modelId,\n }));\n await emitEvent(normalized, events, createRunEvent(\"run.complete\", {\n runId,\n planId: completedPlan.id,\n }));\n\n const successValidation = validation as Extract<\n typeof validation,\n { ok: true }\n >;\n const receipt = await maybeIssueReceipt(normalized, {\n runId,\n ...(intent.contract !== undefined ? { contract: intent.contract } : {}),\n artifacts: built.artifacts,\n contractVerdict: \"success\",\n model: { requested: route.modelId, observed: null },\n route: {\n providerId: route.providerId,\n capabilityId: route.modelId,\n attemptNumber: attempts.length,\n },\n usage: normalizeAdapterUsage(response),\n outputs: JSON.stringify(successValidation.outputs),\n });\n\n return {\n ...validation,\n artifacts: artifactRefs,\n usage: normalizeAdapterUsage(response),\n plan: completedPlan,\n events,\n ...(receipt !== undefined ? { receipt } : {}),\n };\n } catch (error) {\n const completedAt = new Date().toISOString();\n const message =\n error instanceof Error ? error.message : \"Provider adapter execution failed.\";\n attempts.push(attemptFailed(route.providerId, route.modelId, startedAt, completedAt, message));\n lastError = error instanceof Error ? error : new Error(message);\n await emitEvent(normalized, events, createRunEvent(\"provider.attempt\", {\n runId,\n planId: plan.id,\n providerId: route.providerId,\n modelId: route.modelId,\n metadata: { status: \"failed\", error: message },\n }));\n }\n }\n\n if (!anyExecutableAdapter) {\n const receipt = await maybeIssueReceipt(normalized, {\n runId,\n ...(intent.contract !== undefined ? { contract: intent.contract } : {}),\n artifacts: built.artifacts,\n contractVerdict: \"execution-failed\",\n model: { requested: selected.modelId, observed: null },\n route: {\n providerId: selected.providerId,\n capabilityId: selected.modelId,\n attemptNumber: 0,\n },\n usage: ZERO_USAGE,\n });\n return {\n ok: false,\n error: {\n kind: \"execution_unavailable\",\n message: \"No Phase 1 provider adapter with execute() is configured.\",\n },\n usage: { ...ZERO_USAGE },\n plan,\n events,\n ...(receipt !== undefined ? { receipt } : {}),\n };\n }\n\n const failedPlan = withPlanStatus(plan, \"failed\", {\n stages: markStage(plan.stages, \"execution\", \"failed\"),\n attempts,\n });\n await emitEvent(normalized, events, createRunEvent(\"run.failed\", {\n runId,\n planId: failedPlan.id,\n metadata: {\n error: lastError?.message ?? \"Provider adapter execution failed.\",\n },\n }));\n\n const receipt = await maybeIssueReceipt(normalized, {\n runId,\n ...(intent.contract !== undefined ? { contract: intent.contract } : {}),\n artifacts: built.artifacts,\n contractVerdict: \"execution-failed\",\n model: { requested: selected.modelId, observed: null },\n route: {\n providerId: selected.providerId,\n capabilityId: selected.modelId,\n attemptNumber: attempts.length,\n },\n usage: UNMEASURED_USAGE,\n });\n\n return {\n ok: false,\n error: {\n kind: \"provider_execution\",\n message: lastError?.message ?? \"Provider adapter execution failed.\",\n providerId: selected.providerId,\n modelId: selected.modelId,\n },\n usage: { ...UNMEASURED_USAGE },\n plan: failedPlan,\n events,\n ...(receipt !== undefined ? { receipt } : {}),\n };\n}\n\nasync function buildPlan<const TOutputs extends OutputContractMap>(\n normalized: NormalizedLatticeConfig,\n intent: RunIntent<TOutputs>,\n runId = createRunId(),\n events: RunEvent[] = [],\n): Promise<BuiltPlan> {\n const prepared = await prepareArtifacts(intent);\n const artifacts = prepared.artifacts;\n const mergedPolicy = mergePolicy(\n mergePolicy(normalized.defaults.policy, intent.policy),\n intent.overrides?.routingPolicy,\n );\n const sessionRecord =\n intent.session !== undefined && normalized.sessions !== undefined\n ? await loadOrCreateSession(normalized, intent.session)\n : undefined;\n const catalog = createCapabilityCatalog(normalized.providers);\n const route = routeDeterministically(catalog, {\n task: intent.task,\n artifacts,\n outputs: intent.outputs,\n ...(mergedPolicy !== undefined ? { policy: mergedPolicy } : {}),\n ...(intent.overrides?.provider !== undefined\n ? { provider: intent.overrides.provider }\n : {}),\n ...(intent.overrides?.model !== undefined ? { model: intent.overrides.model } : {}),\n ...(intent.contract !== undefined ? { contract: intent.contract } : {}),\n });\n const contextPack = buildContextPack({\n task: intent.task,\n artifacts,\n ...(route.selected !== undefined ? { route: route.selected } : {}),\n ...(sessionRecord !== undefined ? { session: sessionRecord } : {}),\n ...(intent.overrides?.tokenBudget !== undefined\n ? { tokenBudget: intent.overrides.tokenBudget }\n : {}),\n });\n const summaryRefs =\n contextPack.summarized.length > 0 && intent.overrides?.summarizer !== undefined\n ? await intent.overrides.summarizer.summarize({\n artifacts: artifacts.map(toArtifactRef),\n budgetTokens: contextPack.tokenBudget,\n })\n : [];\n const packaging = packageArtifactsForProvider({\n artifacts,\n ...(route.selected !== undefined ? { route: route.selected } : {}),\n ...(mergedPolicy !== undefined ? { policy: mergedPolicy } : {}),\n });\n let plan = createExecutionPlan({\n task: intent.task,\n artifacts: artifacts.map(toArtifactRef),\n outputs: intent.outputs,\n route,\n context: contextPack,\n providerPackaging: packaging.plan,\n warnings: packaging.blocked,\n metadata: {\n ...(intent.tools !== undefined\n ? { tools: intent.tools.map((tool) => tool.name) }\n : {}),\n ...(summaryRefs.length > 0\n ? { summaryArtifactIds: summaryRefs.map((summary) => summary.id) }\n : {}),\n },\n });\n plan = withPlanStatus(plan, plan.status, {\n stages: markStage(\n plan.stages,\n \"tool-execution\",\n prepared.toolResults.length > 0 ? \"completed\" : \"skipped\",\n prepared.toolResults.length > 0\n ? {\n toolNames: prepared.toolResults.map((result) => result.toolName),\n }\n : undefined,\n ),\n });\n\n for (const result of prepared.toolResults) {\n await emitEvent(normalized, events, createRunEvent(\"tool.call\", {\n runId,\n planId: plan.id,\n artifactId: result.artifact.id,\n metadata: {\n toolName: result.toolName,\n callId: result.callId,\n },\n }));\n await emitEvent(normalized, events, createRunEvent(\"artifact.created\", {\n runId,\n planId: plan.id,\n artifactId: result.artifact.id,\n metadata: {\n source: \"tool\",\n },\n }));\n }\n\n for (const artifactRef of artifacts.map(toArtifactRef)) {\n await emitEvent(normalized, events, createRunEvent(\"artifact.ingested\", {\n runId,\n planId: plan.id,\n artifactId: artifactRef.id,\n }));\n }\n\n await emitEvent(normalized, events, createRunEvent(\"context.packed\", {\n runId,\n planId: plan.id,\n metadata: {\n estimatedTokens: contextPack.estimatedTokens,\n included: contextPack.included.length,\n summarized: contextPack.summarized.length,\n omitted: contextPack.omitted.length,\n },\n }));\n await emitEvent(normalized, events, createRunEvent(\"router.candidates\", {\n runId,\n planId: plan.id,\n metadata: {\n selected: route.selected?.modelId,\n rejected: route.rejected.length,\n fallbacks: route.fallbackChain.length,\n },\n }));\n\n return {\n plan,\n artifacts,\n contextPack,\n packagedArtifacts: packaging.packagedArtifacts,\n blockedPackaging: packaging.blocked,\n toolResults: prepared.toolResults,\n ...(mergedPolicy !== undefined ? { mergedPolicy } : {}),\n ...(sessionRecord !== undefined ? { sessionRecord } : {}),\n };\n}\n\nasync function prepareArtifacts<const TOutputs extends OutputContractMap>(\n intent: RunIntent<TOutputs>,\n): Promise<{\n readonly artifacts: readonly ArtifactInput[];\n readonly toolResults: readonly ToolCallResult[];\n}> {\n let artifacts = [...(intent.artifacts ?? [])];\n\n for (const transform of intent.overrides?.transforms ?? []) {\n const transformed = await transform.transform({\n task: intent.task,\n artifacts,\n });\n artifacts = artifacts.concat(Array.isArray(transformed) ? transformed : [transformed]);\n }\n\n const toolResults: ToolCallResult[] = [];\n\n for (const tool of intent.tools ?? []) {\n const result = await runTool(tool, intent.toolInputs?.[tool.name] ?? {});\n toolResults.push(result);\n artifacts.push(result.artifact);\n }\n\n return { artifacts, toolResults };\n}\n\nasync function loadOrCreateSession(\n normalized: NormalizedLatticeConfig,\n session: SessionRef,\n): Promise<SessionRecord> {\n const existing = await normalized.sessions?.load(session.id);\n\n if (existing !== undefined) {\n return existing;\n }\n\n if (normalized.sessions === undefined) {\n throw new Error(\"Session storage is not configured.\");\n }\n\n return normalized.sessions.create({ id: session.id });\n}\n\nfunction attemptSucceeded(\n providerId: string,\n modelId: string,\n startedAt: string,\n completedAt: string,\n usage?: UsageRecord,\n): ProviderAttemptRecord {\n return {\n providerId,\n modelId,\n status: \"succeeded\",\n startedAt,\n completedAt,\n ...(usage !== undefined ? { usage } : {}),\n };\n}\n\nfunction attemptFailed(\n providerId: string,\n modelId: string,\n startedAt: string,\n completedAt: string,\n error: string,\n): ProviderAttemptRecord {\n return {\n providerId,\n modelId,\n status: \"failed\",\n startedAt,\n completedAt,\n error,\n };\n}\n\nfunction findExecutableAdapter(\n normalized: NormalizedLatticeConfig,\n providerId: string,\n): (ProviderAdapter & Required<Pick<ProviderAdapter, \"execute\">>) | undefined {\n return normalized.providers.find((provider) =>\n provider.kind === \"provider-adapter\" &&\n provider.id === providerId &&\n typeof provider.execute === \"function\",\n ) as (ProviderAdapter & Required<Pick<ProviderAdapter, \"execute\">>) | undefined;\n}\n\nfunction routeFromCandidate(\n plan: ExecutionPlan,\n providerId: string,\n modelId: string,\n): SelectedRoute | undefined {\n const candidate = plan.route.candidates.find(\n (item) => item.providerId === providerId && item.modelId === modelId,\n );\n\n if (candidate === undefined) {\n return undefined;\n }\n\n return {\n providerId,\n modelId,\n score: candidate.score,\n estimates: candidate.estimates,\n inputModalities: candidate.capability.inputModalities,\n outputModalities: candidate.capability.outputModalities,\n fileTransport: candidate.capability.fileTransport,\n };\n}\n\nasync function emitEvent(\n normalized: NormalizedLatticeConfig,\n events: RunEvent[],\n event: RunEvent,\n): Promise<void> {\n events.push(event);\n normalized.tracing?.event?.(event.kind, {\n ...event.metadata,\n planId: event.planId,\n providerId: event.providerId,\n modelId: event.modelId,\n artifactId: event.artifactId,\n });\n\n await Promise.all(normalized.events.map((sink) => sink(event)));\n}\n\nfunction createRunId(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return `run:${crypto.randomUUID()}`;\n }\n\n return `run:${Date.now()}:${Math.random().toString(16).slice(2)}`;\n}\n\n/**\n * Normalize an adapter response into the `RunResult.usage` shape.\n *\n * Prefers `ProviderRunResponse.normalizedUsage` (the Phase 7 shape emitted by\n * openai / openai-compat / ai-sdk / fake adapters). Falls back to mapping the\n * legacy `UsageRecord` (inputTokens / outputTokens) so v1.0 adapters that have\n * not yet been re-rolled still surface a usable Usage value.\n */\nfunction normalizeAdapterUsage(response: ProviderRunResponse): Usage {\n if (response.normalizedUsage !== undefined) {\n return response.normalizedUsage;\n }\n return {\n promptTokens: response.usage?.inputTokens ?? 0,\n completionTokens: response.usage?.outputTokens ?? 0,\n costUsd: response.usage?.costUsd ?? null,\n };\n}\n\n/**\n * Phase 9 — hash each artifact's canonical value via SHA-256 and return the\n * hex digests in declaration order. Missing/undefined values produce an\n * empty string so the array length matches `artifacts.length` exactly.\n */\nasync function hashInputArtifacts(\n artifacts: readonly ArtifactInput[],\n): Promise<readonly string[]> {\n const out: string[] = [];\n for (const artifact of artifacts) {\n const fp = await fingerprintArtifactValue(\n (artifact as { readonly value?: unknown }).value,\n );\n out.push(fp?.value ?? \"\");\n }\n return out;\n}\n\n/**\n * Phase 9 — SHA-256 hex of `canonicalize(contract)` for the receipt's\n * contractHash field. Returns null when no contract is attached or when\n * canonicalize cannot serialize the input.\n */\nasync function sha256HexOfCanonicalContract(\n contract: unknown,\n): Promise<string | null> {\n if (contract === undefined || contract === null) return null;\n const canonical = canonicalize(contract);\n if (canonical === undefined) return null;\n const bytes = new TextEncoder().encode(canonical);\n const ab = new Uint8Array(bytes.byteLength);\n ab.set(bytes);\n const digest = await crypto.subtle.digest(\"SHA-256\", ab.buffer as ArrayBuffer);\n return Array.from(new Uint8Array(digest))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\ninterface MaybeIssueReceiptInput {\n readonly runId: string;\n readonly contract?: CapabilityContract;\n readonly artifacts: readonly ArtifactInput[];\n readonly contractVerdict: ContractVerdict;\n readonly model: ReceiptModel;\n readonly route: ReceiptRoute;\n readonly usage: Usage;\n readonly outputs?: unknown;\n readonly noRouteReasons?: readonly RouteRejectReason[];\n readonly tripwireEvidence?: TripwireEvidence;\n}\n\nfunction resolveReceiptModelClass(\n route: ReceiptRoute,\n model: ReceiptModel,\n): TrainingClass | undefined {\n if (route.providerId === \"\" || model.requested === \"\") return undefined;\n return getCapabilityProfile(\n `${route.providerId}:${model.requested}`,\n )?.trainingClass;\n}\n\n/**\n * Phase 9 — issue a signed receipt at a terminal branch when a signer is\n * configured. Signer failures degrade gracefully to `undefined` so a faulty\n * signer never crashes `ai.run`.\n */\nasync function maybeIssueReceipt(\n normalized: NormalizedLatticeConfig,\n input: MaybeIssueReceiptInput,\n): Promise<ReceiptEnvelope | undefined> {\n if (normalized.signer === undefined) return undefined;\n try {\n const inputHashes = await hashInputArtifacts(input.artifacts);\n const outputHash =\n input.outputs === undefined\n ? null\n : ((await fingerprintArtifactValue(input.outputs))?.value ?? null);\n const contractHash = await sha256HexOfCanonicalContract(input.contract);\n const modelClass = resolveReceiptModelClass(input.route, input.model);\n return await createReceipt(\n {\n runId: input.runId,\n model: input.model,\n route: input.route,\n ...(modelClass !== undefined ? { modelClass } : {}),\n usage: input.usage,\n contractVerdict: input.contractVerdict,\n contractHash,\n inputHashes,\n outputHash,\n ...(input.noRouteReasons !== undefined\n ? { noRouteReasons: input.noRouteReasons }\n : {}),\n ...(input.tripwireEvidence !== undefined\n ? { tripwireEvidence: input.tripwireEvidence }\n : {}),\n },\n normalized.signer,\n );\n } catch {\n // Receipt emission is best-effort. A signer failure must NOT crash\n // ai.run — the run result already encodes the verdict.\n return undefined;\n }\n}\n","import type { ArtifactRef } from \"../artifacts/artifact.js\";\n\nexport interface SessionRef {\n readonly id: string;\n readonly kind?: \"session-ref\";\n}\n\nexport interface SessionTurn {\n readonly id: string;\n readonly task: string;\n readonly artifactRefs: readonly ArtifactRef[];\n readonly planId?: string;\n readonly outputArtifactRefs: readonly ArtifactRef[];\n readonly createdAt: string;\n}\n\nexport interface SessionSummary {\n readonly id: string;\n readonly artifactRef: ArtifactRef;\n readonly sourceTurnIds: readonly string[];\n readonly trust: \"model-summary\";\n readonly createdAt: string;\n}\n\nexport interface SessionRecord extends SessionRef {\n readonly kind: \"session-ref\";\n readonly parentId?: string;\n readonly branchPointRunId?: string;\n readonly turns: readonly SessionTurn[];\n readonly summaries: readonly SessionSummary[];\n readonly artifactRefs: readonly ArtifactRef[];\n readonly planIds: readonly string[];\n readonly createdAt: string;\n readonly updatedAt: string;\n}\n\nexport interface CreateSessionOptions {\n readonly id?: string;\n readonly parentId?: string;\n readonly branchPointRunId?: string;\n}\n\nexport interface AppendSessionTurnInput {\n readonly sessionId: string;\n readonly task: string;\n readonly artifactRefs: readonly ArtifactRef[];\n readonly outputArtifactRefs?: readonly ArtifactRef[];\n readonly planId?: string;\n}\n\nexport interface SessionStore {\n readonly kind: \"session-store\";\n readonly id: string;\n create(options?: CreateSessionOptions): Promise<SessionRecord>;\n load(id: string): Promise<SessionRecord | undefined>;\n save(session: SessionRecord): Promise<SessionRecord>;\n branch(parentId: string, options?: Omit<CreateSessionOptions, \"parentId\">): Promise<SessionRecord>;\n appendTurn(input: AppendSessionTurnInput): Promise<SessionRecord>;\n}\n\nexport interface MemorySessionStoreOptions {\n readonly id?: string;\n}\n\nexport function createMemorySessionStore(\n options: MemorySessionStoreOptions = {},\n): SessionStore {\n const storeId = options.id ?? \"memory-sessions\";\n const sessions = new Map<string, SessionRecord>();\n\n return {\n kind: \"session-store\",\n id: storeId,\n\n async create(createOptions = {}) {\n const now = new Date().toISOString();\n const session: SessionRecord = {\n id: createOptions.id ?? createSessionId(),\n kind: \"session-ref\",\n ...(createOptions.parentId !== undefined ? { parentId: createOptions.parentId } : {}),\n ...(createOptions.branchPointRunId !== undefined\n ? { branchPointRunId: createOptions.branchPointRunId }\n : {}),\n turns: [],\n summaries: [],\n artifactRefs: [],\n planIds: [],\n createdAt: now,\n updatedAt: now,\n };\n\n sessions.set(session.id, clone(session));\n\n return clone(session);\n },\n\n async load(id) {\n const session = sessions.get(id);\n\n return session === undefined ? undefined : clone(session);\n },\n\n async save(session) {\n sessions.set(session.id, clone(session));\n\n return clone(session);\n },\n\n async branch(parentId, branchOptions = {}) {\n const parent = sessions.get(parentId);\n const branched = await this.create({\n ...branchOptions,\n parentId,\n });\n\n if (parent === undefined) {\n return branched;\n }\n\n const inherited: SessionRecord = {\n ...branched,\n turns: clone(parent.turns),\n summaries: clone(parent.summaries),\n artifactRefs: clone(parent.artifactRefs),\n planIds: clone(parent.planIds),\n };\n\n sessions.set(inherited.id, clone(inherited));\n\n return clone(inherited);\n },\n\n async appendTurn(input) {\n const existing = sessions.get(input.sessionId) ?? await this.create({ id: input.sessionId });\n const turn: SessionTurn = {\n id: createTurnId(),\n task: input.task,\n artifactRefs: clone(input.artifactRefs),\n outputArtifactRefs: clone(input.outputArtifactRefs ?? []),\n ...(input.planId !== undefined ? { planId: input.planId } : {}),\n createdAt: new Date().toISOString(),\n };\n const artifactRefs = mergeArtifactRefs(\n existing.artifactRefs,\n input.artifactRefs,\n input.outputArtifactRefs ?? [],\n );\n const planIds =\n input.planId === undefined\n ? existing.planIds\n : [...existing.planIds, input.planId];\n const next: SessionRecord = {\n ...existing,\n turns: [...existing.turns, turn],\n artifactRefs,\n planIds,\n updatedAt: new Date().toISOString(),\n };\n\n sessions.set(next.id, clone(next));\n\n return clone(next);\n },\n };\n}\n\nfunction mergeArtifactRefs(\n current: readonly ArtifactRef[],\n ...groups: readonly (readonly ArtifactRef[])[]\n): readonly ArtifactRef[] {\n const byId = new Map(current.map((artifact) => [artifact.id, artifact]));\n\n for (const group of groups) {\n for (const artifact of group) {\n byId.set(artifact.id, artifact);\n }\n }\n\n return [...byId.values()];\n}\n\nfunction createSessionId(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return `session:${crypto.randomUUID()}`;\n }\n\n return `session:${Date.now()}:${Math.random().toString(16).slice(2)}`;\n}\n\nfunction createTurnId(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return `turn:${crypto.randomUUID()}`;\n }\n\n return `turn:${Date.now()}:${Math.random().toString(16).slice(2)}`;\n}\n\nfunction clone<T>(value: T): T {\n try {\n return structuredClone(value);\n } catch {\n return value;\n }\n}\n","import { mkdir, readFile, readdir, rm, stat, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport type { ArtifactInput, ArtifactRef } from \"../artifacts/artifact.js\";\nimport { toArtifactRef } from \"../artifacts/artifact.js\";\nimport { fingerprintArtifactValue } from \"./fingerprint.js\";\nimport type {\n ArtifactStore,\n StoredArtifactEnvelope,\n StoredArtifactPayloadDescriptor,\n} from \"./storage.js\";\n\nexport interface LocalArtifactStoreOptions {\n readonly id?: string;\n}\n\nexport function createLocalArtifactStore(\n rootDir: string | URL,\n options: LocalArtifactStoreOptions = {},\n): ArtifactStore {\n const rootPath = rootDir instanceof URL ? fileURLToPath(rootDir) : rootDir;\n const storeId = options.id ?? \"local\";\n\n return {\n kind: \"artifact-store\",\n id: storeId,\n\n async put(artifact: ArtifactInput): Promise<ArtifactRef> {\n const artifactDir = artifactDirectory(rootPath, artifact.id);\n const fingerprint =\n artifact.fingerprint ?? await fingerprintArtifactValue(artifact.value);\n const storedArtifact: ArtifactInput = {\n ...artifact,\n storage: {\n storeId,\n key: artifact.id,\n },\n ...(fingerprint !== undefined ? { fingerprint } : {}),\n };\n const ref = toArtifactRef(storedArtifact);\n\n await rm(artifactDir, { recursive: true, force: true });\n await mkdir(artifactDir, { recursive: true });\n\n const payload = await writePayload(artifactDir, artifact.value);\n const envelope: StoredArtifactEnvelope = {\n version: 1,\n ref,\n ...(payload !== undefined ? { payload } : {}),\n };\n\n await writeFile(\n metadataPath(rootPath, artifact.id),\n `${JSON.stringify(envelope, null, 2)}\\n`,\n \"utf8\",\n );\n\n return ref;\n },\n\n async get(id: string): Promise<ArtifactRef | undefined> {\n const envelope = await readEnvelope(rootPath, id);\n\n return envelope?.ref;\n },\n\n async load(id: string): Promise<ArtifactInput | undefined> {\n const envelope = await readEnvelope(rootPath, id);\n\n if (envelope === undefined) {\n return undefined;\n }\n\n if (envelope.payload === undefined) {\n return envelope.ref;\n }\n\n const value = await readPayload(artifactDirectory(rootPath, id), envelope.payload);\n\n return {\n ...envelope.ref,\n value,\n };\n },\n\n async has(id: string): Promise<boolean> {\n try {\n await stat(metadataPath(rootPath, id));\n\n return true;\n } catch (error) {\n if (isNotFoundError(error)) {\n return false;\n }\n\n throw error;\n }\n },\n\n async delete(id: string): Promise<boolean> {\n const exists = await this.has(id);\n\n if (!exists) {\n return false;\n }\n\n await rm(artifactDirectory(rootPath, id), { recursive: true, force: true });\n\n return true;\n },\n\n async list(): Promise<readonly ArtifactRef[]> {\n const artifactsPath = join(rootPath, \"artifacts\");\n let entries: readonly { isDirectory(): boolean; name: string }[];\n\n try {\n entries = await readdir(artifactsPath, { withFileTypes: true });\n } catch (error) {\n if (isNotFoundError(error)) {\n return [];\n }\n\n throw error;\n }\n\n const refs = await Promise.all(\n entries\n .filter((entry) => entry.isDirectory())\n .map(async (entry) => {\n const envelope = await readEnvelopeByDirectory(\n join(artifactsPath, entry.name),\n );\n\n return envelope.ref;\n }),\n );\n\n return refs.sort((left, right) => left.id.localeCompare(right.id));\n },\n };\n}\n\nasync function writePayload(\n artifactDir: string,\n value: unknown,\n): Promise<StoredArtifactPayloadDescriptor | undefined> {\n if (value === undefined) {\n return undefined;\n }\n\n if (value instanceof Uint8Array || value instanceof ArrayBuffer || isBlobLike(value)) {\n await writeFile(join(artifactDir, \"payload.bin\"), await toBinaryPayload(value));\n\n return {\n kind: \"binary\",\n path: \"payload.bin\",\n };\n }\n\n const serialized = JSON.stringify(value, null, 2);\n\n if (serialized === undefined) {\n return undefined;\n }\n\n await writeFile(join(artifactDir, \"payload.json\"), `${serialized}\\n`, \"utf8\");\n\n return {\n kind: \"json\",\n path: \"payload.json\",\n };\n}\n\nasync function readPayload(\n artifactDir: string,\n payload: StoredArtifactPayloadDescriptor,\n): Promise<unknown> {\n const payloadPath = join(artifactDir, payload.path);\n\n if (payload.kind === \"binary\") {\n const bytes = await readFile(payloadPath);\n\n return new Uint8Array(bytes);\n }\n\n return JSON.parse(await readFile(payloadPath, \"utf8\"));\n}\n\nasync function readEnvelope(\n rootPath: string,\n id: string,\n): Promise<StoredArtifactEnvelope | undefined> {\n try {\n return JSON.parse(await readFile(metadataPath(rootPath, id), \"utf8\"));\n } catch (error) {\n if (isNotFoundError(error)) {\n return undefined;\n }\n\n throw error;\n }\n}\n\nasync function readEnvelopeByDirectory(\n artifactDir: string,\n): Promise<StoredArtifactEnvelope> {\n return JSON.parse(await readFile(join(artifactDir, \"metadata.json\"), \"utf8\"));\n}\n\nasync function toBinaryPayload(\n value: Blob | ArrayBuffer | Uint8Array,\n): Promise<Uint8Array> {\n if (value instanceof Uint8Array) {\n return value;\n }\n\n if (value instanceof ArrayBuffer) {\n return new Uint8Array(value);\n }\n\n return new Uint8Array(await value.arrayBuffer());\n}\n\nfunction artifactDirectory(rootPath: string, id: string): string {\n return join(rootPath, \"artifacts\", encodeURIComponent(id));\n}\n\nfunction metadataPath(rootPath: string, id: string): string {\n return join(artifactDirectory(rootPath, id), \"metadata.json\");\n}\n\nfunction isBlobLike(value: unknown): value is Blob {\n return typeof Blob !== \"undefined\" && value instanceof Blob;\n}\n\nfunction isNotFoundError(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n error.code === \"ENOENT\"\n );\n}\n","import type { ArtifactInput, ArtifactRef } from \"../artifacts/artifact.js\";\nimport { toArtifactRef } from \"../artifacts/artifact.js\";\nimport { fingerprintArtifactValue } from \"./fingerprint.js\";\nimport type { ArtifactStore } from \"./storage.js\";\n\nexport interface MemoryArtifactStoreOptions {\n readonly id?: string;\n}\n\ninterface MemoryArtifactRecord {\n readonly ref: ArtifactRef;\n readonly artifact: ArtifactInput;\n}\n\nexport function createMemoryArtifactStore(\n options: MemoryArtifactStoreOptions = {},\n): ArtifactStore {\n const storeId = options.id ?? \"memory\";\n const artifacts = new Map<string, MemoryArtifactRecord>();\n\n return {\n kind: \"artifact-store\",\n id: storeId,\n\n async put(artifact) {\n const fingerprint =\n artifact.fingerprint ?? await fingerprintArtifactValue(artifact.value);\n const storedArtifact: ArtifactInput = {\n ...cloneArtifactInput(artifact),\n storage: {\n storeId,\n key: artifact.id,\n },\n ...(fingerprint !== undefined ? { fingerprint } : {}),\n };\n const ref = toArtifactRef(storedArtifact);\n\n artifacts.set(artifact.id, {\n ref: cloneArtifactRef(ref),\n artifact: cloneArtifactInput(storedArtifact),\n });\n\n return cloneArtifactRef(ref);\n },\n\n async get(id) {\n const record = artifacts.get(id);\n\n return record === undefined ? undefined : cloneArtifactRef(record.ref);\n },\n\n async load(id) {\n const record = artifacts.get(id);\n\n return record === undefined ? undefined : cloneArtifactInput(record.artifact);\n },\n\n async has(id) {\n return artifacts.has(id);\n },\n\n async delete(id) {\n return artifacts.delete(id);\n },\n\n async list() {\n return Array.from(artifacts.values(), (record) =>\n cloneArtifactRef(record.ref),\n );\n },\n };\n}\n\nfunction cloneArtifactInput(artifact: ArtifactInput): ArtifactInput {\n return cloneValue(artifact);\n}\n\nfunction cloneArtifactRef(ref: ArtifactRef): ArtifactRef {\n return cloneValue(ref);\n}\n\nfunction cloneValue<T>(value: T): T {\n try {\n return structuredClone(value);\n } catch {\n return value;\n }\n}\n","import canonicalize from \"canonicalize\";\n\nimport type { RecommendedPromptStrategy } from \"../capabilities/profile.js\";\n\nexport const PROMPT_SCAFFOLD_VERSION = \"lattice.prompt-scaffold/v1\" as const;\n\nexport const PROMPT_STRATEGIES = [\n \"frontier\",\n \"mid_tier\",\n \"open_weight\",\n \"reasoning\",\n \"local\",\n] as const satisfies readonly RecommendedPromptStrategy[];\n\ntype PromptScaffoldPurpose = \"structured-output\" | \"tool-use\";\ntype PromptScaffoldPayload = \"schema\" | \"tools\";\n\ninterface PromptStrategyInstructions {\n readonly structuredOutput: readonly string[];\n readonly toolUse: readonly string[];\n}\n\nconst JSON_SERIALIZATION_ERRORS: Record<PromptScaffoldPayload, string> = {\n schema:\n \"getStructuredOutputContract: schema must be JSON-serializable for deterministic prompt scaffolds.\",\n tools:\n \"getToolUseContract: tools must be JSON-serializable for deterministic prompt scaffolds.\",\n};\n\nconst STRATEGY_INSTRUCTIONS: Record<\n RecommendedPromptStrategy,\n PromptStrategyInstructions\n> = {\n frontier: {\n structuredOutput: [\n \"Return only content that satisfies the contract.\",\n \"Do not include prose before or after the structured output.\",\n ],\n toolUse: [\n \"Use a tool only when the task requires an external action or lookup.\",\n \"Return a normal answer when the user request can be completed without a tool.\",\n ],\n },\n mid_tier: {\n structuredOutput: [\n \"Treat the contract as instructions, not as prose to repeat.\",\n \"Return the requested answer in the shape required by the contract.\",\n ],\n toolUse: [\n \"The tool definitions are available actions, not answer text.\",\n \"Call only a listed tool, and only with arguments that match its definition.\",\n ],\n },\n open_weight: {\n structuredOutput: [\n \"The contract below is an instruction, not text to output.\",\n \"Do not answer with the schema, envelope, or any field name unless that field belongs in the final user-visible JSON.\",\n 'Bad: {\"summary\":\"Greeted the user.\"} when the user asked for a natural-language reply.',\n \"Good: Greeted the user.\",\n ],\n toolUse: [\n \"The tool list below is action metadata, not text to output.\",\n \"Do not copy the tool descriptor into the final answer.\",\n \"If no listed tool is needed, answer normally without fabricating a tool call.\",\n ],\n },\n reasoning: {\n structuredOutput: [\n \"Do not expose hidden reasoning, scratchpad text, or analysis in the final answer.\",\n \"Return only the final content that satisfies the contract.\",\n ],\n toolUse: [\n \"Keep tool selection separate from hidden reasoning.\",\n \"Do not include scratchpad text when explaining whether a tool was used.\",\n ],\n },\n local: {\n structuredOutput: [\n \"Do not copy the contract, chat template, or wrapper text into the answer.\",\n \"Return the requested answer directly in the required shape.\",\n ],\n toolUse: [\n \"Do not invent tool names or arguments.\",\n \"If the task does not require a listed tool, answer directly.\",\n ],\n },\n};\n\nfunction canonicalPromptJson(\n value: unknown,\n payload: PromptScaffoldPayload,\n): string {\n const errorMessage = JSON_SERIALIZATION_ERRORS[payload];\n let json: string | undefined;\n\n try {\n json = canonicalize(value);\n if (json === undefined) {\n throw new Error(errorMessage);\n }\n\n JSON.parse(json);\n } catch {\n throw new Error(errorMessage);\n }\n\n return json;\n}\n\nfunction renderPromptScaffold(\n strategy: RecommendedPromptStrategy,\n purpose: PromptScaffoldPurpose,\n instructions: readonly string[],\n payloadHeading: \"Contract\" | \"Tools\",\n payload: string,\n): string {\n return [\n `Lattice Prompt Scaffold: ${PROMPT_SCAFFOLD_VERSION}`,\n `Strategy: ${strategy}`,\n `Purpose: ${purpose}`,\n \"\",\n ...instructions,\n \"\",\n `${payloadHeading}:`,\n payload,\n ].join(\"\\n\");\n}\n\nexport function getStructuredOutputContract(\n strategy: RecommendedPromptStrategy,\n schema: unknown,\n): string {\n return renderPromptScaffold(\n strategy,\n \"structured-output\",\n STRATEGY_INSTRUCTIONS[strategy].structuredOutput,\n \"Contract\",\n canonicalPromptJson(schema, \"schema\"),\n );\n}\n\nexport function getToolUseContract(\n strategy: RecommendedPromptStrategy,\n tools: unknown,\n): string {\n return renderPromptScaffold(\n strategy,\n \"tool-use\",\n STRATEGY_INSTRUCTIONS[strategy].toolUse,\n \"Tools\",\n canonicalPromptJson(tools, \"tools\"),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AA0FA,SAAgB,SAAS,QAAiC,EAAE,EAAsB;AAChF,QAAO,OAAO,OAAO;EACnB,MAAM;EACN,GAAI,MAAM,WAAW,KAAA,IAAY,EAAE,QAAQ,OAAO,OAAO,EAAE,GAAG,MAAM,QAAQ,CAAC,EAAE,GAAG,EAAE;EACpF,GAAI,MAAM,eAAe,KAAA,IACrB,EAAE,YAAY,OAAO,OAAO,MAAM,WAAW,KAAK,QAAQ,OAAO,OAAO,EAAE,GAAG,KAAK,CAAC,CAAC,CAAC,EAAE,GACvF,EAAE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AAM,IAAI,MAAM,aAAa;;AAG/B,QAAO;;AAGT,SAAS,qBACP,UACA,SACA,cACA,gBACA,SACQ;AACR,QAAO;EACL,4BAA4B;EAC5B,aAAa;EACb,YAAY;EACZ;EACA,GAAG;EACH;EACA,GAAG,eAAe;EAClB;EACD,CAAC,KAAK,KAAK;;AAGd,SAAgB,4BACd,UACA,QACQ;AACR,QAAO,qBACL,UACA,qBACA,sBAAsB,UAAU,kBAChC,YACA,oBAAoB,QAAQ,SAAS,CACtC;;AAGH,SAAgB,mBACd,UACA,OACQ;AACR,QAAO,qBACL,UACA,YACA,sBAAsB,UAAU,SAChC,SACA,oBAAoB,OAAO,QAAQ,CACpC"}