@full-self-browsing/lattice 0.0.0-bootstrap.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.
@@ -0,0 +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;EAC1F,CAAC;;;;ACtDJ,IA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