@full-self-browsing/lattice 1.3.0-rc.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,15 @@
1
1
  import { StandardSchemaV1 } from "@standard-schema/spec";
2
2
 
3
3
  //#region src/policy/policy.d.ts
4
+ type GatewayMetadataValue = string | number | boolean | null | readonly GatewayMetadataValue[] | {
5
+ readonly [key: string]: GatewayMetadataValue;
6
+ };
7
+ interface GatewayPolicy {
8
+ readonly routeTags?: readonly string[];
9
+ readonly providerPreferences?: readonly string[];
10
+ readonly metadata?: Record<string, GatewayMetadataValue>;
11
+ readonly allowFallbacks?: boolean;
12
+ }
4
13
  interface PolicySpec {
5
14
  readonly maxCostUsd?: number;
6
15
  readonly latency?: "interactive" | "batch";
@@ -10,6 +19,8 @@ interface PolicySpec {
10
19
  readonly noUpload?: boolean;
11
20
  readonly noPublicUrl?: boolean;
12
21
  readonly noLogging?: boolean;
22
+ readonly stream?: boolean;
23
+ readonly gateway?: GatewayPolicy;
13
24
  readonly metadata?: Record<string, unknown>;
14
25
  }
15
26
  //#endregion
@@ -115,7 +126,7 @@ interface TracerLike {
115
126
  readonly span?: <T>(name: string, fn: () => T | Promise<T>, attributes?: Record<string, unknown>) => T | Promise<T>;
116
127
  readonly event?: (name: string, attributes?: Record<string, unknown>) => void;
117
128
  }
118
- type RunEventKind = "run.start" | "artifact.ingested" | "context.packed" | "router.candidates" | "stage.start" | "stage.complete" | "provider.attempt" | "fallback.activated" | "validation.complete" | "validation.failed" | "artifact.created" | "run.complete" | "run.failed" | "tool.call" | "replay.offline" | "replay.live" | "step.transition" | "recovery.start" | "recovery.complete" | "recovery.failed";
129
+ type RunEventKind = "run.start" | "artifact.ingested" | "context.packed" | "router.candidates" | "stage.start" | "stage.complete" | "provider.attempt" | "stream.start" | "stream.complete" | "stream.failed" | "fallback.activated" | "validation.complete" | "validation.failed" | "artifact.created" | "run.complete" | "run.failed" | "tool.call" | "replay.offline" | "replay.live" | "step.transition" | "recovery.start" | "recovery.complete" | "recovery.failed" | "capabilities.negotiation.fallback";
119
130
  interface RunEvent {
120
131
  readonly kind: RunEventKind;
121
132
  readonly timestamp: string;
@@ -373,6 +384,137 @@ type TripwireResult = {
373
384
  */
374
385
  declare function evaluateTripwires(output: unknown, invariants: readonly InvariantDeclaration[], detectors?: readonly PiiDetector[]): Promise<TripwireResult>;
375
386
  //#endregion
387
+ //#region src/capabilities/profile.d.ts
388
+ /**
389
+ * Closed enum of the 8 Lattice transport adapters (D-06). Adding a new
390
+ * adapter is a typed breaking change. Phase 34 quirk dispatch reads this
391
+ * field.
392
+ */
393
+ type CapabilityAdapter = "openrouter" | "anthropic" | "openai" | "openai-compat" | "xai" | "gemini" | "lm-studio" | "litellm";
394
+ /**
395
+ * Closed enum of the 5 training-lineage buckets (D-14). Receipt v1.2
396
+ * (Phase 38) carries this value verbatim via the `modelClass` field.
397
+ * Stable across model patches — gpt-4o-2024-05-13 and gpt-4o-2024-08-06
398
+ * share a trainingClass so receipts remain comparable across rebuilds.
399
+ */
400
+ type TrainingClass = "frontier_rlhf" | "mid_tier_rlhf" | "open_weight_instruct" | "open_weight_base" | "local_quantized";
401
+ /**
402
+ * Closed enum of the 5 recommended prompt-tuning buckets (research open
403
+ * question 2). DISTINCT from `TrainingClass`: `reasoning` is orthogonal
404
+ * to lineage (a frontier RLHF model with hidden_cot routes to the
405
+ * `reasoning` strategy bucket); `local` is the granularity boundary
406
+ * for the deployed-locally strategy bucket (vs the `local_quantized`
407
+ * lineage signal). Phase 35 prompt-scaffold dispatch reads this field.
408
+ */
409
+ type RecommendedPromptStrategy = "frontier" | "mid_tier" | "open_weight" | "reasoning" | "local";
410
+ /**
411
+ * Closed enum of the 7 known model-class output-shape failure modes at
412
+ * v1.3.0 (D-12). Adding a member in v1.4+ is an intentional typed
413
+ * breaking change — Phase 36 sanitizer dispatch enforces exhaustiveness
414
+ * via a `_exhaustive: never` switch (see test-d/capabilities.test-d.ts).
415
+ */
416
+ type KnownFailureMode = "internal_envelope_leak" | "reasoning_tag_leak" | "system_prompt_echo" | "template_artifact_leak" | "hallucinated_tool_name" | "malformed_tool_arguments" | "premature_termination";
417
+ /**
418
+ * Closed enum of the 5 reasoning-surface shapes a model exposes. Drives
419
+ * the Phase 36 sanitizer's choice of leak-cleanup pass (e.g., `<think>`
420
+ * tag stripping for `inlined_tags`).
421
+ */
422
+ type ReasoningSurface = "none" | "hidden_cot" | "inlined_tags" | "interleaved_thinking" | "streamed_reasoning";
423
+ /**
424
+ * Closed enum of the 5 tool-call surface shapes a model exposes. Drives
425
+ * the Phase 37 tool-call validator's choice of arguments parser.
426
+ */
427
+ type ToolCallSurface = "none" | "native_strict" | "native_lenient" | "json_only" | "text_only";
428
+ type ModelCapabilityProfilePricingKey = "prompt" | "completion" | "image" | "audio" | "web_search" | "internal_reasoning" | "input_cache_read" | "input_cache_write";
429
+ type ModelCapabilityProfilePricing = Partial<Record<ModelCapabilityProfilePricingKey, string>>;
430
+ type ModelCapabilityProfileModality = "text" | "image" | "audio" | "video" | "file" | "embeddings";
431
+ /**
432
+ * Phase 33 — D-05 / D-08 — Capability profile for one (adapter, model)
433
+ * pair. Sibling to `ModelCapability`, not a replacement. Built-time baked
434
+ * via the OpenRouter snapshot generator (Phase 33-03) plus hand-edited
435
+ * supplemental static profiles (Phase 33-04).
436
+ *
437
+ * Canonical key: `${adapter}:${modelId}` — one profile per (adapter,
438
+ * model) pair. `openrouter:openai/gpt-oss-120b` and `openai:gpt-oss-120b`
439
+ * are two distinct entries with the same `originFamily: "openai"`.
440
+ */
441
+ interface ModelCapabilityProfile {
442
+ /**
443
+ * The model identifier as the adapter sees it. For OpenRouter this is
444
+ * the `vendor/model` shape (e.g., `openai/gpt-oss-120b`); for direct
445
+ * adapters this is the provider's native id (e.g., `claude-opus-4`).
446
+ * Combined with `adapter` to form the canonical lookup key `${adapter}:${id}` (D-08).
447
+ */
448
+ readonly id: string;
449
+ /**
450
+ * The Lattice transport adapter that ships this profile (D-05 /
451
+ * D-06). Phase 34 adapter-quirk dispatch reads this field. Closed
452
+ * union of 8 values.
453
+ */
454
+ readonly adapter: CapabilityAdapter;
455
+ /**
456
+ * The model creator (D-07). Open extensible string — new orgs emerge
457
+ * frequently and should not break the type. Examples: `openai`,
458
+ * `anthropic`, `meta`, `mistral`, `google`, `xai`, `deepseek`, `qwen`.
459
+ * Phase 35 prompt-scaffold dispatch falls back to
460
+ * `recommendedPromptStrategy` for unknown originFamily values.
461
+ */
462
+ readonly originFamily: string;
463
+ /**
464
+ * Training-lineage classification (D-14). Receipt v1.2 `modelClass`
465
+ * (Phase 38) carries this value verbatim. Drives the failure-mode
466
+ * default set in the classifier.
467
+ */
468
+ readonly trainingClass: TrainingClass;
469
+ /**
470
+ * Shape of the model's reasoning output. Drives the Phase 36
471
+ * sanitizer's reasoning-leak cleanup pass.
472
+ */
473
+ readonly reasoningSurface: ReasoningSurface;
474
+ /**
475
+ * Shape of the model's tool-call output. Drives the Phase 37
476
+ * tool-call validator's arguments parser.
477
+ */
478
+ readonly toolCallSurface: ToolCallSurface;
479
+ /**
480
+ * The actual context window the adapter will accept on a request, in
481
+ * tokens. For OpenRouter this is `top_provider.context_length ?? context_length`
482
+ * (Phase 33 Pitfall 2) — what OpenRouter routing actually offers, not
483
+ * the model card's aspirational maximum.
484
+ */
485
+ readonly contextWindow: number;
486
+ readonly pricing?: ModelCapabilityProfilePricing;
487
+ readonly inputModalities?: readonly ModelCapabilityProfileModality[];
488
+ readonly outputModalities?: readonly ModelCapabilityProfileModality[];
489
+ readonly supportedParameters?: readonly string[];
490
+ /**
491
+ * Failure modes this model class is known to exhibit (D-14). Class-
492
+ * derived defaults plus per-family overrides. Phase 36 sanitizer
493
+ * dispatch exhaustively switches on each entry.
494
+ */
495
+ readonly knownFailureModes: readonly KnownFailureMode[];
496
+ /**
497
+ * Recommended prompt-tuning bucket (research open question 2). Phase
498
+ * 35 prompt-scaffold dispatch reads this field. Distinct from
499
+ * `trainingClass` — see `RecommendedPromptStrategy` JSDoc.
500
+ */
501
+ readonly recommendedPromptStrategy: RecommendedPromptStrategy;
502
+ }
503
+ /**
504
+ * Frozen list of every `KnownFailureMode` member. Useful for exhaustive
505
+ * iteration in downstream tests and Phase 36 sanitizer registration.
506
+ * Adding a new mode requires updating this array AND the
507
+ * `KnownFailureMode` union AND the Phase 36 exhaustive switch — the
508
+ * `satisfies` clause enforces array-vs-union parity at compile time.
509
+ */
510
+ declare const ALL_KNOWN_FAILURE_MODES: readonly ["internal_envelope_leak", "reasoning_tag_leak", "system_prompt_echo", "template_artifact_leak", "hallucinated_tool_name", "malformed_tool_arguments", "premature_termination"];
511
+ /**
512
+ * Frozen list of every `TrainingClass` member. Useful for exhaustive
513
+ * iteration when constructing the failure-mode defaults table (D-14)
514
+ * and for Phase 38 receipt-class enumeration.
515
+ */
516
+ declare const ALL_TRAINING_CLASSES: readonly ["frontier_rlhf", "mid_tier_rlhf", "open_weight_instruct", "open_weight_base", "local_quantized"];
517
+ //#endregion
376
518
  //#region src/outputs/contracts.d.ts
377
519
  type TextOutputContract = "text";
378
520
  interface CitationRef {
@@ -469,1478 +611,2322 @@ interface ContextSummarizer {
469
611
  }): Promise<readonly ArtifactRef[]> | readonly ArtifactRef[];
470
612
  }
471
613
  //#endregion
472
- //#region src/providers/provider.d.ts
473
- type CapabilityModality = "text" | "json" | "image" | "audio" | "video" | "document" | "file" | "url" | "tool";
474
- type ProviderTransportMode = "inline" | "json" | "url" | "base64" | "provider-upload" | "file-id" | "extracted-text" | "transcript";
475
- type ProviderLatencyClass = "interactive" | "batch";
476
- interface ProviderPricingHint {
477
- /** @deprecated prefer `inputPer1kTokens` — kept for backward compatibility */
478
- readonly inputCostPer1M?: number;
479
- /** @deprecated prefer `outputPer1kTokens` — kept for backward compatibility */
480
- readonly outputCostPer1M?: number;
481
- /** Per-1000-prompt-token cost in USD. Preferred field for Phase 7+ pricing. */
482
- readonly inputPer1kTokens?: number;
483
- /** Per-1000-completion-token cost in USD. Preferred field for Phase 7+ pricing. */
484
- readonly outputPer1kTokens?: number;
485
- }
614
+ //#region src/runtime/survivability.d.ts
486
615
  /**
487
- * Normalized per-run usage at the result layer.
616
+ * MV3-survivability adapter contract -- Phase 5 (FSB v0.10.0-attempt-2).
488
617
  *
489
- * `costUsd` is `number | null` (not optional, not `0`) so downstream
490
- * consumers can distinguish "free" (`0`) from "unmeasured" (`null`) when
491
- * provider pricing is unknown — see 07-CONTEXT.md "Cost Normalization & Usage".
618
+ * This module is a SIBLING of create-ai.ts (the Lattice runtime facade) and
619
+ * a SIBLING of contract/bands.ts (the hook pipeline factory) and
620
+ * contract/checkpoint.ts (the per-step receipt hook). It does NOT modify
621
+ * any of them; the SurvivabilityAdapter contract is composed from those
622
+ * surfaces by the consumer (FSB's lattice-runtime-adapter.js in Plan 05-05).
492
623
  *
493
- * Distinct from `UsageRecord` on `ProviderAttemptRecord`: `UsageRecord`
494
- * is the per-attempt record, `Usage` is the per-run normalized shape
495
- * surfaced on `RunSuccess` / `RunFailure`.
624
+ * What is the survivability problem?
625
+ * Some host runtimes can evict the execution context mid-flow with no
626
+ * synchronous shutdown signal:
627
+ * - Chrome MV3 service workers: evicted after 30s silence OR 5min idle.
628
+ * - Cloudflare Workers: evicted at end of each request unless waitUntil.
629
+ * - AWS Lambda: process freeze + thaw across invocations.
630
+ * Lattice's existing runtime (create-ai.ts) assumes the process stays
631
+ * live for the duration of a run. The SurvivabilityAdapter contract is
632
+ * the seam where a host runtime tells Lattice "here is how to serialize
633
+ * my state, here is how to deserialize it back, here is how to resume
634
+ * work after I get evicted and recreated."
635
+ *
636
+ * What this module SHIPS:
637
+ * - SurvivabilityAdapter<TState> interface (4 methods)
638
+ * - SerializedSnapshot type (string-encodable opaque envelope)
639
+ * - EvictionHook<TState> type (pre-eviction callback signature)
640
+ * - ResumePolicy literal-union (post-restore reconstruction verdict)
641
+ * - UnsubscribeFn type
642
+ * - createNoopSurvivabilityAdapter() reference implementation
643
+ *
644
+ * What this module DOES NOT ship:
645
+ * - chrome.storage.session integration (FSB-side; Plan 05-05).
646
+ * - offscreen-document message bus (FSB-side; Plan 05-04).
647
+ * - Auto-wiring into create-ai.ts runtime (deferred indefinitely; the
648
+ * contract is consumer-controlled).
649
+ * - Mid-API-request / mid-tool-dispatch recovery dispatcher (CONSERVATIVE
650
+ * recovery wiring is deferred to a follow-on FSB milestone per
651
+ * CONTEXT.md D-22; only the ResumePolicy taxonomy lands here).
652
+ *
653
+ * Composition conventions (NOT enforced; documented for callers):
654
+ * D-09: onEviction hooks SHOULD register in BAND.SAFETY band on the
655
+ * caller's HookPipeline so they run FIRST per Phase 2 priority
656
+ * ordering. This module does NOT auto-register; it ships the
657
+ * contract only.
658
+ * D-10: serialize(state) MAY include the latest checkpoint receipt
659
+ * envelope (Phase 3 createCheckpointHook output) inside the
660
+ * SerializedSnapshot.payload; deserialize() reconstructs session
661
+ * identifiers from the v1.1 receipt body's step-marker fields
662
+ * (stepName, stepIndex, parentStepName, previousStepName,
663
+ * sessionId, timestamp). The payload is opaque to Lattice -- the
664
+ * host runtime defines the shape.
665
+ *
666
+ * ResumePolicy taxonomy (CD-E resolution per attempt-1 02-04-PLAN.md):
667
+ * - SAFE: the snapshot was captured at a safe boundary (BEFORE_ITERATION
668
+ * or BEFORE_NEXT_ITERATION_SCHEDULE step markers) and can be replayed
669
+ * deterministically. The host runtime may re-arm the loop.
670
+ * - RECOVERY_AMBIGUOUS: the snapshot was captured during a tool dispatch
671
+ * where re-execution risk is non-zero (file write, network POST without
672
+ * Idempotency-Key, side-effecting browser action). Host should escalate
673
+ * to the user before deciding.
674
+ * - ON_ERROR_SW_EVICTION_MID_REQUEST: the eviction happened mid-API-call
675
+ * (the provider request was in flight). 6 of 7 FSB providers do NOT
676
+ * document Idempotency-Key headers; replay risks duplicate charges +
677
+ * duplicate responses. Host should treat the run as failed and surface
678
+ * the error to the user.
679
+ * - ON_ERROR_SW_EVICTION_MID_TOOL_DISPATCH: the eviction happened mid-
680
+ * tool-dispatch (a browser action was in progress). Re-execution risk
681
+ * is similar to mid-API-call but lands in a different recovery branch
682
+ * (the host may inspect the page state before deciding).
683
+ *
684
+ * SerializedSnapshot is intentionally opaque + string-encodable. The
685
+ * host runtime defines the payload shape; Lattice's only requirement
686
+ * is that serialize() followed by deserialize() round-trips the state.
687
+ *
688
+ * Ed25519 receipt envelope contract (carries forward from Phase 1-3):
689
+ * Callers MAY embed a v1.1 ReceiptEnvelope inside SerializedSnapshot.payload
690
+ * for signed checkpoint round-trip. verifyReceipt against the embedded
691
+ * envelope MUST return result.ok === true after a serialize -> deserialize
692
+ * cycle (Test 12). This validates that JSON.stringify + JSON.parse over
693
+ * the envelope preserves the JCS-canonical body bytes used by DSSE PAE.
694
+ *
695
+ * Threat model (Phase 5 CONTEXT.md security block):
696
+ * - PII via serialized state: callers MUST ensure SerializedSnapshot.payload
697
+ * contains only stable identifiers + user-controlled state the user has
698
+ * already consented to persist. Mirrors Phase 2 D-04 receipt-body contract
699
+ * (step-marker fields are stable identifiers, not free-form user input).
700
+ * - Snapshot tampering: the noop adapter does NOT sign the snapshot.
701
+ * Callers that need cryptographic integrity SHOULD embed a signed
702
+ * ReceiptEnvelope inside the payload + verify it on deserialize.
703
+ * Phase 5 ships the contract; signature wrapping is a follow-on.
704
+ *
705
+ * Vocabulary separation (carries forward Phase 2 D-12 + Phase 3 D-02):
706
+ * ResumePolicy is the survivability vocabulary -- separate from
707
+ * RunEventKind (tracing) AND separate from HookLifecycleEvent (bands).
708
+ * The three vocabularies meet only when a host runtime composes them.
496
709
  */
497
- interface Usage {
498
- readonly promptTokens: number;
499
- readonly completionTokens: number;
500
- readonly costUsd: number | null;
501
- }
502
- interface ProviderDataPolicyHints {
503
- readonly privacy: readonly ("standard" | "sensitive" | "restricted")[];
504
- readonly uploadRetention?: "none" | "ephemeral" | "provider-default";
505
- readonly supportsNoLogging?: boolean;
506
- readonly supportsNoTraining?: boolean;
507
- }
508
- interface ModelCapability {
509
- readonly providerId: string;
510
- readonly modelId: string;
511
- readonly inputModalities: readonly CapabilityModality[];
512
- readonly outputModalities: readonly CapabilityModality[];
513
- readonly fileTransport: readonly ProviderTransportMode[];
514
- readonly contextWindow: number;
515
- readonly structuredOutput: boolean;
516
- readonly toolUse: boolean;
517
- readonly streaming: boolean;
518
- readonly pricing?: ProviderPricingHint;
519
- readonly latency: ProviderLatencyClass;
520
- readonly dataPolicy: ProviderDataPolicyHints;
521
- readonly available?: boolean;
710
+ /**
711
+ * String-encodable opaque snapshot. The host runtime defines the payload
712
+ * shape; Lattice's only requirement is that serialize() followed by
713
+ * deserialize() round-trips the original state object.
714
+ *
715
+ * Why string-encodable? MV3's chrome.storage.session and most cross-process
716
+ * storage layers accept structured-clone-safe values. JSON-string payloads
717
+ * are the lowest-common-denominator that survives MV3 SW eviction +
718
+ * Cloudflare Worker freeze + Lambda thaw. Callers MAY use a richer payload
719
+ * shape (Uint8Array, Blob) IF the host runtime supports it; the contract
720
+ * does not constrain payload format beyond "deserialize round-trips it".
721
+ */
722
+ interface SerializedSnapshot {
723
+ readonly kind: "survivability-snapshot";
724
+ readonly version: "lattice-survivability/v1";
725
+ readonly payload: string;
726
+ readonly capturedAt: string;
522
727
  }
523
- interface ProviderRef {
728
+ /**
729
+ * Pre-eviction callback. The host runtime CAN attempt to call this hook
730
+ * before the execution context is evicted, but MAY NOT be able to in
731
+ * every case (MV3 eviction has no synchronous signal -- the SW just
732
+ * stops). Callers should treat onEviction as best-effort: useful for
733
+ * gathering final state when the eviction is announced (e.g., user-
734
+ * initiated stop) but not load-bearing for involuntary eviction.
735
+ *
736
+ * The hook receives the current TState by reference. Mutations on the
737
+ * hook side leak to the caller's state -- this is deliberate (the hook
738
+ * is the LAST chance to update state before eviction). Callers who want
739
+ * structuredClone semantics SHOULD wrap state in their own freeze layer.
740
+ */
741
+ type EvictionHook<TState> = (state: TState) => void | Promise<void>;
742
+ /**
743
+ * Return value of onEviction(); calling unsubscribes the hook.
744
+ *
745
+ * Idempotent -- calling twice has the same effect as calling once.
746
+ */
747
+ type UnsubscribeFn = () => void;
748
+ /**
749
+ * Resume policy taxonomy. The host runtime calls adapter.resume(snapshot)
750
+ * after eviction + restore; the returned policy tells the host runtime
751
+ * how to react.
752
+ *
753
+ * The 4 literal members carry forward from FSB v0.10.0-attempt-1's
754
+ * 02-04-PLAN.md CONSERVATIVE recovery dispatch (preserved at
755
+ * .planning/milestones/v0.10.0-attempt-1-pre-pivot/02-state-inspectability-
756
+ * carve-out/02-04-PLAN.md). Per CONTEXT.md CD-E this is the locked union.
757
+ */
758
+ type ResumePolicy = "SAFE" | "RECOVERY_AMBIGUOUS" | "ON_ERROR_SW_EVICTION_MID_REQUEST" | "ON_ERROR_SW_EVICTION_MID_TOOL_DISPATCH";
759
+ /**
760
+ * The SurvivabilityAdapter contract. Host runtimes implement this; Lattice
761
+ * runs against the interface.
762
+ *
763
+ * 4 methods (D-08 locked):
764
+ * - serialize(state): convert in-memory state to SerializedSnapshot
765
+ * - deserialize(snapshot): inverse of serialize
766
+ * - onEviction(hook): register a best-effort pre-eviction callback
767
+ * - resume(snapshot): return ResumePolicy verdict for the post-restore
768
+ * reconstruction. The host runtime acts on the policy.
769
+ *
770
+ * Adapters are POLYMORPHIC over TState -- the host runtime parameterizes
771
+ * the type. Lattice's vitest covers the contract surface with a noop
772
+ * adapter where TState = Record<string, unknown> for ergonomics.
773
+ */
774
+ interface SurvivabilityAdapter<TState> {
775
+ readonly kind: "survivability-adapter";
524
776
  readonly id: string;
525
- readonly kind?: "provider-ref";
777
+ serialize(state: TState): SerializedSnapshot;
778
+ deserialize(snapshot: SerializedSnapshot): TState;
779
+ onEviction(hook: EvictionHook<TState>): UnsubscribeFn;
780
+ resume(snapshot: SerializedSnapshot): Promise<ResumePolicy>;
526
781
  }
527
- interface ProviderRunRequest {
528
- readonly task: string;
529
- readonly artifacts: readonly ArtifactInput[];
530
- readonly outputs: readonly string[];
531
- readonly outputContracts?: OutputContractMap;
532
- readonly policy?: unknown;
782
+ /**
783
+ * Factory options for the reference noop adapter.
784
+ *
785
+ * - id: optional. Defaults to "noop-survivability". Useful when callers
786
+ * want to distinguish multiple adapter instances in test fixtures.
787
+ * - policy: optional. Sets the default ResumePolicy returned by resume().
788
+ * Defaults to "SAFE" (matches noop adapter semantics: no recovery
789
+ * ambiguity if nothing was ever persisted).
790
+ */
791
+ interface NoopSurvivabilityAdapterOptions {
792
+ readonly id?: string;
793
+ readonly policy?: ResumePolicy;
794
+ }
795
+ /**
796
+ * Reference implementation of SurvivabilityAdapter<TState>. Records
797
+ * eviction events but does NOT persist; serialize / deserialize round-
798
+ * trip via JSON.stringify / JSON.parse. Analog to createFakeProvider
799
+ * in the providers/ module -- gives Lattice's vitest a complete shape-
800
+ * conformance target before the real (FSB-side) adapter ships in
801
+ * Plan 05-05.
802
+ *
803
+ * Per CONTEXT.md D-11 the noop adapter ships in Lattice (not FSB)
804
+ * because it covers the contract surface in Lattice's own test suite;
805
+ * FSB's real chrome.storage.session-backed adapter is glue layer.
806
+ */
807
+ declare function createNoopSurvivabilityAdapter<TState = Record<string, unknown>>(options?: NoopSurvivabilityAdapterOptions): SurvivabilityAdapter<TState>;
808
+ //#endregion
809
+ //#region src/tools/tools.d.ts
810
+ interface ToolExecutionContext {
533
811
  readonly signal?: AbortSignal;
534
- readonly plan?: ExecutionPlan;
535
- readonly contextPack?: ContextPack;
536
- readonly providerPackaging?: ProviderPackagingPlan;
537
- readonly packagedArtifacts?: readonly ArtifactRef[];
812
+ readonly emit?: RunEventSink;
538
813
  }
539
- interface ProviderRunResponse {
540
- readonly rawOutputs: Record<string, unknown>;
541
- readonly artifactRefs?: readonly (ArtifactInput | ArtifactRef)[];
814
+ interface ToolDefinition<TSchema extends StandardSchemaV1 = StandardSchemaV1> {
815
+ readonly kind: "tool";
816
+ readonly name: string;
817
+ readonly description?: string;
818
+ readonly inputSchema: TSchema;
819
+ readonly execute: (input: StandardSchemaV1.InferOutput<TSchema>, context: ToolExecutionContext) => Promise<unknown> | unknown;
820
+ }
821
+ interface ToolCallResult {
822
+ readonly callId: string;
823
+ readonly toolName: string;
824
+ readonly artifact: ArtifactInput;
825
+ }
826
+ declare function defineTool<TSchema extends StandardSchemaV1>(definition: Omit<ToolDefinition<TSchema>, "kind">): ToolDefinition<TSchema>;
827
+ declare function runTool<TSchema extends StandardSchemaV1>(tool: ToolDefinition<TSchema>, input: unknown, context?: ToolExecutionContext): Promise<ToolCallResult>;
828
+ interface McpLikeClient {
829
+ readonly listTools?: () => Promise<readonly McpToolDescriptor[]> | readonly McpToolDescriptor[];
830
+ readonly callTool: (input: {
831
+ readonly name: string;
832
+ readonly arguments: unknown;
833
+ }) => Promise<unknown> | unknown;
834
+ }
835
+ interface McpToolDescriptor {
836
+ readonly name: string;
837
+ readonly description?: string;
838
+ readonly inputSchema: StandardSchemaV1;
839
+ }
840
+ declare function importMcpTools(client: McpLikeClient, toolNames?: readonly string[]): Promise<readonly ToolDefinition[]>;
841
+ declare function toolArtifactRef(result: ToolCallResult): ArtifactRef;
842
+ //#endregion
843
+ //#region src/agent/format-tools.d.ts
844
+ /**
845
+ * One turn in the running conversation.
846
+ *
847
+ * `role: "tool"` is used for tool-result turns; `toolCallId` and `toolName`
848
+ * are populated so the model can correlate the result with its prior
849
+ * `tool_call` envelope.
850
+ */
851
+ interface ConversationTurn {
852
+ readonly role: "user" | "assistant" | "tool";
853
+ readonly content: string;
854
+ readonly toolCallId?: string;
855
+ readonly toolName?: string;
856
+ }
857
+ type FormatToolsMode = "native" | "prompt-reencoded" | "auto";
858
+ interface FormatToolsOptions {
542
859
  /**
543
- * @deprecated Legacy per-attempt usage shape. Phase 7+ adapters should
544
- * populate `normalizedUsage` instead Plan 04 will prefer `normalizedUsage`
545
- * when wiring `RunResult.usage`. Kept here for backward compatibility with
546
- * v1.0 adapters that already report this field.
860
+ * Tool-use protocol mode. Defaults to `"auto"`, which currently resolves
861
+ * to `"prompt-reencoded"` for ALL 7 providers (Phase 19 simplification —
862
+ * native tool_use deferred to a follow-on milestone). Reserved for
863
+ * forward compatibility.
547
864
  */
548
- readonly usage?: UsageRecord;
865
+ readonly mode?: FormatToolsMode;
549
866
  /**
550
- * Phase 7 normalized usage shape for `RunResult.usage`. Populated by all
551
- * Phase 7+ adapters (openai, openai-compat, ai-sdk, fake). `costUsd` is
552
- * `null` when pricing is unknown (per the cost-normalization decision in
553
- * 07-CONTEXT.md — distinguishes "free" from "unmeasured").
867
+ * Optional system prompt to prepend. Useful for setting persona /
868
+ * domain-specific instructions on top of the tool-use envelope.
554
869
  */
555
- readonly normalizedUsage?: Usage;
556
- readonly rawResponse?: unknown;
870
+ readonly system?: string;
557
871
  }
558
- interface ProviderAdapter {
559
- readonly id: string;
560
- readonly kind: "provider-adapter";
561
- readonly capabilities?: readonly ModelCapability[];
562
- readonly execute?: (request: ProviderRunRequest) => Promise<ProviderRunResponse>;
872
+ interface FormattedToolsHandle {
873
+ /**
874
+ * Builds the single `task` string passed to `ProviderAdapter.execute()`.
875
+ * Encodes the conversation, available tools, and response-envelope
876
+ * instructions.
877
+ */
878
+ readonly buildTask: (conversation: readonly ConversationTurn[]) => string;
879
+ /**
880
+ * Phase 39 (v1.3): body-only sibling of `buildTask` — identical turn
881
+ * rendering minus the leading system block, so the byte-stable
882
+ * `describeForSystem()` prefix can be hoisted once per crew for
883
+ * prompt-cache sharing without duplication (39-05).
884
+ *
885
+ * Invariant: `describeForSystem() + "\n" + buildTaskBody(conversation)`
886
+ * reconstructs `buildTask(conversation)` byte-for-byte.
887
+ */
888
+ readonly buildTaskBody: (conversation: readonly ConversationTurn[]) => string;
889
+ /**
890
+ * Parses the assistant's response text. Returns:
891
+ * - `ToolUseRequest[]` when the response contains one or more tool-call
892
+ * envelopes (parsed in declaration order).
893
+ * - `null` when the response is a final answer (no tool-call envelopes
894
+ * detected).
895
+ *
896
+ * The parser is forgiving: it tolerates extra prose around the JSON
897
+ * envelope (markdown fences, leading explanations) and the model
898
+ * occasionally drifting on whitespace.
899
+ */
900
+ readonly parseToolUse: (responseText: string) => ReadonlyArray<ToolUseRequest> | null;
901
+ /**
902
+ * Returns the static system block describing available tools. Useful for
903
+ * tracing / logging the exact tool-description text fed to the model.
904
+ */
905
+ readonly describeForSystem: () => string;
906
+ /**
907
+ * Effective mode this handle resolved to (`"prompt-reencoded"` for all
908
+ * v1.2 providers). Exposed for inspectability.
909
+ */
910
+ readonly mode: "prompt-reencoded";
563
911
  }
564
- type ProviderRegistryInput = readonly (ProviderRef | ProviderAdapter | string)[];
912
+ /**
913
+ * Convert a Standard Schema to a JSON Schema-shaped descriptor suitable for
914
+ * inclusion in an LLM tool description. Standard Schema vendors can
915
+ * optionally expose `toJSONSchema` on their schema objects; when absent,
916
+ * we fall back to a minimal structural description that lists the schema
917
+ * vendor + version + a placeholder. Models tolerate placeholder schemas in
918
+ * practice because the tool description is supplementary — what matters
919
+ * is the envelope contract (`{tool_call: {name, args}}`).
920
+ */
921
+ declare function toolSchemaToJsonSchema(schema: StandardSchemaV1): unknown;
922
+ /**
923
+ * Builds the prompt-reencoded tool-use protocol handle for any provider.
924
+ *
925
+ * Phase 19 ships a uniform implementation across all 7 logical providers
926
+ * (openai, openai-compat, anthropic, gemini, xai, openrouter, lm-studio).
927
+ * The `providerName` argument is accepted for forward compatibility but
928
+ * does not branch the implementation in v1.2.
929
+ */
930
+ declare function formatToolsForProvider(providerName: string, tools: ReadonlyArray<ToolDefinition<StandardSchemaV1>>, options?: FormatToolsOptions): FormattedToolsHandle;
931
+ declare function parseToolUseEnvelope(responseText: string): ReadonlyArray<ToolUseRequest> | null;
565
932
  //#endregion
566
- //#region src/plan/plan.d.ts
567
- type ExecutionPlanStatus = "stub" | "planned" | "no-route" | "running" | "completed" | "failed";
568
- type ExecutionStageKind = "analysis" | "transforms" | "context-packing" | "provider-packaging" | "tool-execution" | "execution" | "validation" | "tripwire" | "persistence" | "replay";
569
- type ExecutionStageStatus = "pending" | "running" | "completed" | "skipped" | "failed";
570
- interface ExecutionPlanStage {
571
- readonly id: string;
572
- readonly kind: ExecutionStageKind;
573
- readonly status: ExecutionStageStatus;
574
- readonly inputArtifacts?: readonly string[];
575
- readonly outputArtifacts?: readonly string[];
576
- readonly warnings: readonly string[];
577
- readonly metadata?: Record<string, unknown>;
933
+ //#region src/agent/host.d.ts
934
+ /**
935
+ * Snapshot shape the agent loop serializes between iterations. The full
936
+ * shape is opaque to callers (they only see it through SerializedSnapshot
937
+ * via the configured SurvivabilityAdapter) but it's exported so reference
938
+ * implementations and tests can inspect the round-trip.
939
+ */
940
+ interface AgentSnapshot {
941
+ readonly version: "agent-snapshot/v1";
942
+ readonly iterationIndex: number;
943
+ readonly conversation: readonly ConversationTurn[];
944
+ readonly cumulativeUsage: Usage;
945
+ readonly providerName: string;
946
+ readonly capturedAt: string;
947
+ /**
948
+ * Phase 39 (v1.3): dispatch ancestry chain of crew `AgentSpec` ids
949
+ * (root-first). Absent = root agent (single-agent runs never set it).
950
+ * Optional so existing serialized `agent-snapshot/v1` snapshots
951
+ * deserialize unchanged — the version literal stays `"agent-snapshot/v1"`
952
+ * (D-05; Pitfall 8). The crew dispatcher threads the chain through
953
+ * dispatch context in 39-05; cycle prevention rejects any dispatch whose
954
+ * target id already appears in the chain.
955
+ */
956
+ readonly ancestry?: readonly string[];
578
957
  }
579
- interface RouteRejectReason {
580
- readonly code: string;
581
- readonly message: string;
958
+ /**
959
+ * Scheduler seam — controls how the agent loop yields between iterations.
960
+ *
961
+ * `scheduleNext(iterationIndex)` is called AFTER an AFTER_AGENT_ITERATION
962
+ * emission and BEFORE the next iteration's BEFORE_AGENT_ITERATION. The
963
+ * scheduler decides when to resume — synchronously (sync loop), on next
964
+ * tick (setTimeout/queueMicrotask), via a queue (Durable Object), or any
965
+ * other strategy.
966
+ *
967
+ * Default (noop): resolves immediately.
968
+ */
969
+ interface AgentScheduler {
970
+ scheduleNext(iterationIndex: number): Promise<void>;
582
971
  }
583
- interface RouteCandidate {
584
- readonly providerId: string;
585
- readonly modelId: string;
586
- readonly capability: ModelCapability;
587
- readonly score: number;
588
- readonly accepted: boolean;
589
- readonly reasons: readonly RouteRejectReason[];
590
- readonly estimates: RouteEstimates;
972
+ /**
973
+ * Transport seam — controls how a provider call is dispatched.
974
+ *
975
+ * `call(provider, request)` wraps the provider's `execute()` invocation.
976
+ * Default (noop): pass-through (`provider.execute!(request)`). Cross-process
977
+ * bridges (FSB's offscreen-document host) override to dispatch via
978
+ * `chrome.runtime.sendMessage`.
979
+ *
980
+ * Per the Phase 19 INV-03 parity invariant, the transport seam does NOT
981
+ * modify the `ProviderAdapter` interface — it operates on top of the
982
+ * existing `execute()` method.
983
+ */
984
+ interface AgentTransport {
985
+ call(provider: ProviderAdapter, request: ProviderRunRequest): Promise<ProviderRunResponse>;
591
986
  }
592
- interface RouteEstimates {
593
- readonly inputTokens: number;
594
- readonly outputTokens: number;
595
- readonly costUsd?: number;
596
- readonly latencyMs?: number;
987
+ /**
988
+ * Storage seam — controls how agent state persists between iterations for
989
+ * resume after host eviction.
990
+ *
991
+ * Phase 20 composes this with the Phase 18 `SurvivabilityAdapter`:
992
+ * - The adapter serializes `AgentSnapshot` to `SerializedSnapshot` on
993
+ * each AFTER_AGENT_ITERATION; storage.save() persists the snapshot.
994
+ * - On run start, the agent loop calls storage.load(). If a non-null
995
+ * snapshot is returned, the adapter deserializes it; the loop resumes
996
+ * at the recorded iteration index.
997
+ * - On success, the loop calls storage.clear() so the next run starts
998
+ * fresh.
999
+ *
1000
+ * Default (noop): save() is a no-op, load() returns null, clear() is a
1001
+ * no-op. Suitable for Node tests where eviction never occurs.
1002
+ */
1003
+ interface AgentStorage {
1004
+ save(snapshot: SerializedSnapshot): Promise<void>;
1005
+ load(): Promise<SerializedSnapshot | null>;
1006
+ clear(): Promise<void>;
597
1007
  }
598
- interface SelectedRoute {
599
- readonly providerId: string;
600
- readonly modelId: string;
601
- readonly score: number;
602
- readonly estimates: RouteEstimates;
603
- readonly inputModalities: readonly CapabilityModality[];
604
- readonly outputModalities: readonly CapabilityModality[];
605
- readonly fileTransport: readonly ProviderTransportMode[];
606
- }
607
- interface FallbackRoute {
608
- readonly providerId: string;
609
- readonly modelId: string;
610
- readonly score: number;
611
- readonly reason: "policy-preserving-fallback";
612
- }
613
- interface RouteDecision {
614
- readonly catalogVersion: string;
615
- readonly selected?: SelectedRoute;
616
- readonly candidates: readonly RouteCandidate[];
617
- readonly rejected: readonly RouteCandidate[];
618
- readonly fallbackChain: readonly FallbackRoute[];
619
- readonly noRouteReasons: readonly RouteRejectReason[];
1008
+ /**
1009
+ * The host adapter — three optional seams, all swappable independently.
1010
+ *
1011
+ * Callers pass `host` on `AgentIntent`. The agent runtime falls back to
1012
+ * `createNoopAgentHost()` when `intent.host` is absent (so Phase 19
1013
+ * single-shot Node usage continues to work without explicit configuration).
1014
+ */
1015
+ interface AgentHost {
1016
+ readonly kind: "agent-host";
1017
+ readonly scheduler?: AgentScheduler;
1018
+ readonly transport?: AgentTransport;
1019
+ readonly storage?: AgentStorage;
620
1020
  }
621
- interface ContextPackPlan {
622
- readonly id: string;
623
- readonly tokenBudget: number;
624
- readonly estimatedTokens: number;
625
- readonly included: readonly ContextPackItemPlan[];
626
- readonly summarized: readonly ContextPackItemPlan[];
627
- readonly archived: readonly ContextPackItemPlan[];
628
- readonly omitted: readonly ContextPackItemPlan[];
629
- readonly warnings: readonly string[];
1021
+ /**
1022
+ * Reference implementation suitable for Node tests + the Phase 19 default
1023
+ * behavior.
1024
+ *
1025
+ * - scheduler: resolves immediately (no yield between iterations).
1026
+ * - transport: pass-through to provider.execute().
1027
+ * - storage: save() / clear() are no-ops; load() always returns null.
1028
+ *
1029
+ * Equivalent to passing no host at all.
1030
+ */
1031
+ declare function createNoopAgentHost(): AgentHost;
1032
+ //#endregion
1033
+ //#region src/contract/contract.d.ts
1034
+ /**
1035
+ * Budget invariant declaration attached to a CapabilityContract.
1036
+ *
1037
+ * Phase 7 implements `maxCostUsd` enforcement at pre-flight. The
1038
+ * `p95LatencyMs` field is declared per CONTRACT-02 but is informational
1039
+ * only in Phase 7 — latency observations are wired in a later phase.
1040
+ *
1041
+ * Phase 19 (v1.2) adds `maxIterations` and `maxWallTimeMs` for the agent
1042
+ * runtime. Both are additive and optional; non-agent callers ignore them.
1043
+ * `maxIterations` caps the number of `runAgent` iterations; `maxWallTimeMs`
1044
+ * caps wall-clock duration per `runAgent` invocation. Both are enforced
1045
+ * pre-iteration in the agent loop.
1046
+ */
1047
+ interface BudgetInvariant {
1048
+ readonly maxCostUsd?: number;
1049
+ readonly maxIterations?: number;
1050
+ readonly maxWallTimeMs?: number;
1051
+ readonly p95LatencyMs?: number;
630
1052
  }
631
- interface ContextPackItemPlan {
632
- readonly artifactId?: string;
633
- readonly sessionTurnId?: string;
634
- readonly reason: string;
635
- readonly estimatedTokens: number;
636
- readonly trust: "developer" | "user" | "tool" | "model-summary";
1053
+ /**
1054
+ * Quality-floor invariant.
1055
+ *
1056
+ * `suite` is a fixture-directory path string; `minScore` is in 0..1.
1057
+ * Phase 7 forwards this into the pre-flight evaluator but only enforces
1058
+ * capability-side rejects. Full enforcement lives in Phase 12 (`lattice eval`).
1059
+ */
1060
+ interface QualityFloorInvariant {
1061
+ readonly suite: string;
1062
+ readonly minScore: number;
637
1063
  }
638
- interface ProviderPackagingPlan {
639
- readonly providerId: string;
640
- readonly modelId: string;
641
- readonly artifacts: readonly ProviderPackagedArtifactPlan[];
642
- readonly warnings: readonly string[];
1064
+ /**
1065
+ * The full Capability Contract attached to `RunIntent.contract`.
1066
+ *
1067
+ * All fields are optional. v1.0 callers compile and run unchanged when
1068
+ * the field is omitted entirely. PROJECT.md explicitly rejects mandatory
1069
+ * contracts.
1070
+ */
1071
+ interface CapabilityContract {
1072
+ readonly kind: "capability-contract";
1073
+ readonly budget?: BudgetInvariant;
1074
+ readonly invariants?: readonly InvariantDeclaration[];
1075
+ readonly qualityFloor?: QualityFloorInvariant;
1076
+ readonly requiredModalities?: readonly CapabilityModality[];
1077
+ readonly requiredPrivacy?: "standard" | "sensitive" | "restricted";
643
1078
  }
644
- interface ProviderPackagedArtifactPlan {
645
- readonly artifactId: string;
646
- readonly transport: ProviderTransportMode;
647
- readonly mediaType?: string;
648
- readonly lineageTransform: "provider-packaging";
649
- readonly warnings: readonly string[];
1079
+ /**
1080
+ * Reject-reason taxonomy added to `RouteRejectReason.code` by Phase 7's
1081
+ * pre-flight evaluator. Closed four-value union per the locked decisions
1082
+ * in 07-CONTEXT.md.
1083
+ */
1084
+ type ContractRejectReasonCode = "contract-budget-exceeded" | "contract-quality-floor" | "contract-modality-missing" | "contract-privacy-mismatch";
1085
+ /** Input shape accepted by `contract()`. Mirrors `CapabilityContract` minus `kind`. */
1086
+ interface CapabilityContractInput {
1087
+ readonly budget?: BudgetInvariant;
1088
+ readonly invariants?: readonly InvariantDeclaration[];
1089
+ readonly qualityFloor?: QualityFloorInvariant;
1090
+ readonly requiredModalities?: readonly CapabilityModality[];
1091
+ readonly requiredPrivacy?: "standard" | "sensitive" | "restricted";
650
1092
  }
651
- interface ProviderAttemptRecord {
652
- readonly providerId: string;
653
- readonly modelId: string;
654
- readonly status: "pending" | "running" | "succeeded" | "failed" | "cancelled";
655
- readonly startedAt?: string;
656
- readonly completedAt?: string;
657
- readonly error?: string;
658
- readonly usage?: UsageRecord;
1093
+ /**
1094
+ * Factory for `CapabilityContract` values.
1095
+ *
1096
+ * Mirrors the `output()` and adapter factory style exact-optional safe
1097
+ * (does not emit `field: undefined` properties under `exactOptionalPropertyTypes`).
1098
+ * Returns a frozen value with frozen nested objects so downstream code can
1099
+ * rely on structural immutability when canonicalizing in Phase 9.
1100
+ */
1101
+ declare function contract(input?: CapabilityContractInput): CapabilityContract;
1102
+ //#endregion
1103
+ //#region src/outputs/infer.d.ts
1104
+ type InferOutput<C> = C extends "text" ? string : C extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<C> : C extends CitationsOutputContract ? readonly CitationRef[] : C extends ArtifactRefsOutputContract ? readonly ArtifactRef[] : never;
1105
+ type InferOutputMap<T extends OutputContractMap> = { readonly [K in keyof T]: InferOutput<T[K]> };
1106
+ //#endregion
1107
+ //#region src/results/errors.d.ts
1108
+ interface ValidationIssue {
1109
+ readonly message: string;
1110
+ readonly path?: readonly (string | number | symbol)[];
659
1111
  }
660
- interface UsageRecord {
661
- readonly inputTokens?: number;
662
- readonly outputTokens?: number;
663
- readonly totalTokens?: number;
664
- readonly costUsd?: number;
665
- readonly latencyMs?: number;
1112
+ interface ValidationError {
1113
+ readonly kind: "validation";
1114
+ readonly message: string;
1115
+ readonly output?: string;
1116
+ readonly issues: readonly ValidationIssue[];
666
1117
  }
667
- interface ExecutionPlan {
668
- readonly id: string;
669
- readonly kind: "execution-plan";
670
- readonly version: 1;
671
- readonly createdAt: string;
672
- readonly status: ExecutionPlanStatus;
673
- readonly task: string;
674
- readonly outputNames: readonly string[];
675
- readonly artifactRefs: readonly ArtifactRef[];
676
- readonly route: RouteDecision;
677
- readonly stages: readonly ExecutionPlanStage[];
678
- readonly context?: ContextPackPlan;
679
- readonly providerPackaging?: ProviderPackagingPlan;
680
- readonly attempts: readonly ProviderAttemptRecord[];
681
- readonly warnings: readonly string[];
682
- readonly metadata?: Record<string, unknown>;
1118
+ interface ExecutionUnavailableError {
1119
+ readonly kind: "execution_unavailable";
1120
+ readonly message: string;
683
1121
  }
684
- interface ExecutionPlanStub {
685
- readonly id: string;
686
- readonly kind: "plan-stub";
687
- readonly createdAt: string;
688
- readonly status: "stub";
689
- readonly stages: readonly [];
690
- readonly warnings: readonly string[];
1122
+ interface NoRouteError {
1123
+ readonly kind: "no_route";
1124
+ readonly message: string;
1125
+ readonly reasons: readonly string[];
691
1126
  }
692
- type ResultPlan = ExecutionPlan | ExecutionPlanStub;
693
- //#endregion
694
- //#region src/receipts/types.d.ts
695
- type ContractVerdict = "success" | "tripwire-violated" | "no-contract-match" | "execution-failed" | "validation-failed";
696
- interface ReceiptUsageCanonical {
697
- readonly promptTokens: number;
698
- readonly completionTokens: number;
699
- readonly costUsd: string | null;
1127
+ interface ProviderExecutionError {
1128
+ readonly kind: "provider_execution";
1129
+ readonly message: string;
1130
+ readonly providerId?: string;
1131
+ readonly modelId?: string;
700
1132
  }
701
- interface ReceiptModel {
702
- readonly requested: string;
703
- readonly observed: string | null;
1133
+ interface TimeoutError {
1134
+ readonly kind: "timeout";
1135
+ readonly message: string;
704
1136
  }
705
- interface ReceiptRoute {
706
- readonly providerId: string;
707
- readonly capabilityId: string;
708
- readonly attemptNumber: number;
1137
+ /**
1138
+ * Phase 7 addition: emitted by the runtime when no candidate route can
1139
+ * satisfy the caller-supplied `CapabilityContract` (budget, modality,
1140
+ * privacy, or quality-floor invariants).
1141
+ *
1142
+ * `noRouteReasons` carries the full deterministic-router rejection list
1143
+ * so callers can inspect per-candidate detail. Phase 9 (receipts) will
1144
+ * persist this array for deterministic verdict reconstruction.
1145
+ */
1146
+ interface NoContractMatchError {
1147
+ readonly kind: "no-contract-match";
1148
+ readonly message: string;
1149
+ readonly noRouteReasons: readonly RouteRejectReason[];
709
1150
  }
710
- interface ReceiptRedaction {
711
- readonly path: string;
712
- readonly reason: string;
1151
+ /**
1152
+ * Phase 8 addition: emitted when a `CapabilityContract.invariants` tripwire
1153
+ * fires after the provider returned a schema-valid output. Carries the
1154
+ * `TripwireEvidence` produced by `evaluateTripwires`.
1155
+ *
1156
+ * `terminal: true` is a structural marker — combined with the `isTerminal()`
1157
+ * predicate it tells the fallback chain in `runWithConfig` to refuse retry.
1158
+ * `NoContractMatchError` does NOT carry the field (to avoid breaking Phase 7
1159
+ * callers) but `isTerminal()` still returns true for it via the kind check.
1160
+ */
1161
+ interface TripwireViolationError {
1162
+ readonly kind: "tripwire-violated";
1163
+ readonly message: string;
1164
+ readonly invariantId: string;
1165
+ readonly evidence: TripwireEvidence;
1166
+ readonly terminal: true;
713
1167
  }
714
- interface CapabilityReceiptBody {
715
- readonly version: "lattice-receipt/v1" | "lattice-receipt/v1.1";
716
- readonly receiptId: string;
717
- readonly runId: string;
718
- readonly issuedAt: string;
719
- readonly kid: string;
720
- readonly model: ReceiptModel;
721
- readonly route: ReceiptRoute;
722
- readonly usage: ReceiptUsageCanonical;
723
- readonly contractVerdict: ContractVerdict;
724
- readonly contractHash: string | null;
725
- readonly inputHashes: readonly string[];
726
- readonly outputHash: string | null;
727
- readonly redactionPolicyId: string;
728
- readonly redactions: readonly ReceiptRedaction[];
729
- readonly noRouteReasons?: readonly RouteRejectReason[];
730
- readonly tripwireEvidence?: TripwireEvidence;
731
- readonly stepName?: string;
732
- readonly stepIndex?: number;
733
- readonly parentStepName?: string;
734
- readonly previousStepName?: string;
735
- readonly sessionId?: string;
736
- readonly timestamp?: string;
1168
+ type LatticeRunError = ValidationError | ExecutionUnavailableError | NoRouteError | ProviderExecutionError | TimeoutError | NoContractMatchError | TripwireViolationError;
1169
+ /**
1170
+ * Returns `true` for run errors that MUST NOT be retried by the fallback
1171
+ * chain. Phase 8 covers two kinds:
1172
+ *
1173
+ * - `tripwire-violated` — the contract's invariants rejected the output;
1174
+ * a different provider will not change the verdict, so retry burns
1175
+ * budget for no gain (T-08-06 in 08-02-PLAN threat register).
1176
+ * - `no-contract-match` — no route satisfies the contract at all; the
1177
+ * run never executed and no retry will help.
1178
+ *
1179
+ * All other error kinds return `false` and remain eligible for fallback.
1180
+ * The predicate is exported so Phase 12's eval gate and any user-side
1181
+ * retry wrappers can share one source of truth.
1182
+ */
1183
+ declare function isTerminal(error: LatticeRunError): boolean;
1184
+ //#endregion
1185
+ //#region src/agent/types.d.ts
1186
+ /**
1187
+ * Per-iteration record stored on `AgentSuccess.iterations` for inspectability.
1188
+ *
1189
+ * `toolCalls` carries content-addressed args/result hashes (sha256) so
1190
+ * downstream receipts can reference them without inlining the bodies.
1191
+ *
1192
+ * `deniedReason` is populated on iterations whose `BEFORE_AGENT_ITERATION`
1193
+ * SAFETY-band handler set `controls.deny(...)`.
1194
+ */
1195
+ interface IterationRecord {
1196
+ readonly index: number;
1197
+ readonly provider: string;
1198
+ readonly promptTokens: number;
1199
+ readonly completionTokens: number;
1200
+ readonly costUsd: number | null;
1201
+ readonly durationMs: number;
1202
+ readonly toolCalls: ReadonlyArray<{
1203
+ readonly id: string;
1204
+ readonly name: string;
1205
+ readonly argsHash: string;
1206
+ readonly resultHash: string;
1207
+ }>;
1208
+ readonly deniedReason?: string;
1209
+ readonly receipt?: ReceiptEnvelope;
737
1210
  }
738
- interface ReceiptSignature {
739
- readonly keyid: string;
740
- readonly sig: string;
1211
+ /**
1212
+ * Input shape accepted by `ai.runAgent(intent)`.
1213
+ *
1214
+ * All fields except `task` and `tools` are optional. The runtime supplies
1215
+ * sensible defaults (in-process host, fresh pipeline, no signer, no tracer).
1216
+ *
1217
+ * `TOutputs` parameterizes the final-answer schema map; defaults to a free-form
1218
+ * `{ answer: "text" }` shape when the field is omitted. Validation runs once
1219
+ * against the final assistant message (no intermediate iteration validation).
1220
+ */
1221
+ interface AgentIntent<TOutputs extends OutputContractMap = OutputContractMap> {
1222
+ readonly task: string;
1223
+ readonly tools: ReadonlyArray<ToolDefinition<StandardSchemaV1>>;
1224
+ readonly host?: AgentHost;
1225
+ /**
1226
+ * Phase 20 (v1.2): when the agent loop resumes from a host.storage snapshot,
1227
+ * the configured SurvivabilityAdapter handles the serialize/deserialize
1228
+ * round-trip. When absent, runtime defaults to
1229
+ * `createNoopSurvivabilityAdapter<AgentSnapshot>()`.
1230
+ */
1231
+ readonly survivabilityAdapter?: SurvivabilityAdapter<AgentSnapshot>;
1232
+ readonly contract?: CapabilityContract;
1233
+ readonly policy?: PolicySpec;
1234
+ readonly outputs?: TOutputs;
1235
+ readonly pipeline?: HookPipeline;
1236
+ readonly signer?: ReceiptSigner;
1237
+ readonly tracer?: TracerLike;
1238
+ /**
1239
+ * When `false`, the runtime will NOT auto-register `createCheckpointHook`
1240
+ * even if `signer` is provided. Callers who want full manual control over
1241
+ * receipt minting set this to `false` and register their own hook.
1242
+ * Defaults to `true` (auto-register when signer present).
1243
+ */
1244
+ readonly autoRegisterCheckpoint?: boolean;
741
1245
  }
742
- interface ReceiptEnvelope {
743
- readonly payloadType: "application/vnd.lattice.receipt+json";
744
- readonly payload: string;
745
- readonly signatures: readonly ReceiptSignature[];
1246
+ /**
1247
+ * Success result returned by `ai.runAgent` when the loop reaches a final
1248
+ * answer and (when `outputs` is declared) the final answer validates.
1249
+ *
1250
+ * `iterations[]` records every iteration that ran — including the one that
1251
+ * produced the final answer. `receipt` is the outermost receipt minted at
1252
+ * loop close when `signer` is configured (separate from per-iteration
1253
+ * receipts on `iterations[i].receipt`).
1254
+ */
1255
+ interface AgentSuccess<TOutputs extends OutputContractMap = OutputContractMap> {
1256
+ readonly kind: "success";
1257
+ readonly output: InferOutputMap<TOutputs>;
1258
+ readonly artifacts?: readonly ArtifactRef[];
1259
+ readonly usage: Usage;
1260
+ readonly iterations: ReadonlyArray<IterationRecord>;
1261
+ readonly receipt?: ReceiptEnvelope;
746
1262
  }
747
- interface ReceiptSigner {
748
- readonly kid: string;
749
- sign(bytes: Uint8Array): Promise<Uint8Array>;
750
- readonly publicKeyJwk: JsonWebKey;
1263
+ /**
1264
+ * Failure kinds specific to the agent loop. v1.1 `LatticeRunError.kind`
1265
+ * values remain valid (provider errors, no-contract-match, validation-failed,
1266
+ * tripwire-violated) and are reused verbatim. Phase 19 adds three
1267
+ * agent-specific kinds. Phase 39 (v1.3) adds `crew-budget-exceeded` —
1268
+ * crew-level shared-pool exhaustion, terminal across the parent/child
1269
+ * boundary (D-10).
1270
+ */
1271
+ type AgentFailureKind = LatticeRunError["kind"] | "agent-iteration-denied" | "agent-max-iterations" | "agent-wall-time-exceeded" | "crew-budget-exceeded";
1272
+ /**
1273
+ * Failure result returned by `ai.runAgent`. Discriminates via `kind`.
1274
+ *
1275
+ * `iterations[]` carries any iterations that completed before the failure
1276
+ * (empty if the failure occurred pre-iteration). For `agent-iteration-denied`,
1277
+ * the failing iteration is the LAST entry and carries `deniedReason`.
1278
+ */
1279
+ interface AgentFailure {
1280
+ readonly kind: AgentFailureKind;
1281
+ readonly usage: Usage;
1282
+ readonly iterations: ReadonlyArray<IterationRecord>;
1283
+ readonly reason?: string;
1284
+ readonly cause?: unknown;
1285
+ readonly receipt?: ReceiptEnvelope;
751
1286
  }
752
- type KeyState = "active" | "retired" | "revoked";
753
- interface KeyEntry {
754
- readonly kid: string;
755
- readonly publicKeyJwk: JsonWebKey;
756
- readonly state: KeyState;
1287
+ /**
1288
+ * Discriminated union returned by `ai.runAgent`.
1289
+ */
1290
+ type AgentResult<TOutputs extends OutputContractMap = OutputContractMap> = AgentSuccess<TOutputs> | AgentFailure;
1291
+ /**
1292
+ * Typed error raised when a SAFETY-band handler sets `controls.deny(reason)`
1293
+ * during `BEFORE_AGENT_ITERATION`. Carries `terminal: true` semantics to
1294
+ * align with v1.1 `TripwireViolationError`: the failure is NOT retried by
1295
+ * the fallback chain.
1296
+ *
1297
+ * Surfaced via `AgentFailure { kind: "agent-iteration-denied", reason, ... }`
1298
+ * — callers can also catch the typed error if they prefer.
1299
+ */
1300
+ declare class AgentDeniedError extends Error {
1301
+ readonly kind: "agent-iteration-denied";
1302
+ readonly terminal: true;
1303
+ readonly reason: string;
1304
+ readonly iterationIndex: number;
1305
+ constructor(reason: string, iterationIndex: number);
757
1306
  }
758
- interface KeySet {
759
- lookup(kid: string): KeyEntry | undefined;
1307
+ /**
1308
+ * Returned by `formatToolsForProvider` (Phase 19 Plan 19-03). Re-exported
1309
+ * here for convenience; the canonical declaration lives in format-tools.ts.
1310
+ */
1311
+ interface ToolUseRequest {
1312
+ readonly id: string;
1313
+ readonly name: string;
1314
+ readonly args: unknown;
760
1315
  }
761
- type VerifyErrorKind = "key-not-found" | "key-revoked" | "canonicalization-mismatch" | "signature-invalid" | "envelope-malformed" | "version-mismatch" | "schema-version-too-low";
762
- interface VerifyError {
763
- readonly kind: VerifyErrorKind;
764
- readonly message: string;
1316
+ //#endregion
1317
+ //#region src/tools/tool-call-validation.d.ts
1318
+ type ToolCallValidationFailureReason = "unknown_tool" | "invalid_args" | "extra_fields";
1319
+ interface ValidatedToolCall {
1320
+ readonly id: string;
1321
+ readonly name: string;
1322
+ readonly args: unknown;
765
1323
  }
766
- interface VerifyOk {
767
- readonly ok: true;
768
- readonly body: CapabilityReceiptBody;
769
- readonly keyState: KeyState;
1324
+ type ToolCallValidationTool = Pick<ToolDefinition, "name" | "inputSchema">;
1325
+ interface ValidateToolCallsOption {
1326
+ readonly tools: readonly ToolCallValidationTool[];
1327
+ readonly onFailure?: "throw" | "drop" | "callback";
1328
+ readonly onValidationFailure?: (error: ToolCallValidationError) => void | Promise<void>;
1329
+ readonly allowExtraFields?: boolean;
770
1330
  }
771
- interface VerifyFail {
772
- readonly ok: false;
773
- readonly error: VerifyError;
1331
+ declare class ToolCallValidationError extends Error {
1332
+ readonly kind: "tool-call-validation";
1333
+ readonly reason: ToolCallValidationFailureReason;
1334
+ readonly toolName: string;
1335
+ readonly attemptedArgs: unknown;
1336
+ readonly validationIssues: readonly ValidationIssue[];
1337
+ readonly requestId: string;
1338
+ constructor(input: {
1339
+ readonly reason: ToolCallValidationFailureReason;
1340
+ readonly toolName: string;
1341
+ readonly attemptedArgs: unknown;
1342
+ readonly validationIssues?: readonly ValidationIssue[];
1343
+ readonly requestId: string;
1344
+ });
774
1345
  }
775
- type VerifyResult = VerifyOk | VerifyFail;
776
1346
  //#endregion
777
- //#region src/receipts/receipt.d.ts
1347
+ //#region src/providers/quirks.d.ts
778
1348
  /**
779
- * Public input to createReceipt. Mirrors CapabilityReceiptBody minus:
780
- * - `version` (forced to "lattice-receipt/v1.1" per CRYPTO-01)
781
- * - `kid` (forced from signer.kid — caller cannot mismatch)
782
- * - `redactions[]` (populated by redactReceiptBody)
783
- * - `usage.costUsd` (converted to canonical string by usageToCanonical)
1349
+ * Universal 5-boolean shape every first-party adapter populates (SC-1 / D-03).
784
1350
  *
785
- * receiptId and issuedAt default to runtime-generated values when omitted.
786
- * redactionPolicyId defaults to DEFAULT_REDACTION_POLICY_ID.
1351
+ * - `supportsToolChoice` — adapter supports tool_choice / forced-tool-call mode
1352
+ * - `parallelToolCalls` — adapter supports parallel (multi-tool) calls in one turn
1353
+ * - `structuredOutputs` — adapter honors response_format JSON schema binding
1354
+ * - `responseFormatHonored` — adapter treats response_format as authoritative (false
1355
+ * for vanilla openai-compat servers; true for OpenAI/Anthropic/Gemini)
1356
+ * - `streamingDiverges` — streamed output differs from buffered output (true for
1357
+ * some self-hosted servers; false for OpenAI/Anthropic/Gemini)
787
1358
  */
788
- interface CreateReceiptInput {
789
- readonly runId: string;
790
- readonly issuedAt?: string;
791
- readonly receiptId?: string;
792
- readonly model: ReceiptModel;
793
- readonly route: ReceiptRoute;
794
- readonly usage: Usage;
795
- readonly contractVerdict: ContractVerdict;
796
- readonly contractHash: string | null;
797
- readonly inputHashes: readonly string[];
798
- readonly outputHash: string | null;
799
- readonly redactionPolicyId?: string;
800
- readonly noRouteReasons?: readonly RouteRejectReason[];
801
- readonly tripwireEvidence?: TripwireEvidence;
802
- readonly stepName?: string;
803
- readonly stepIndex?: number;
804
- readonly parentStepName?: string;
805
- readonly previousStepName?: string;
806
- readonly sessionId?: string;
807
- readonly timestamp?: string;
1359
+ interface AdapterQuirks {
1360
+ readonly supportsToolChoice: boolean;
1361
+ readonly parallelToolCalls: boolean;
1362
+ readonly structuredOutputs: boolean;
1363
+ readonly responseFormatHonored: boolean;
1364
+ readonly streamingDiverges: boolean;
808
1365
  }
809
1366
  /**
810
- * Build, redact, canonicalize, sign, and envelope a CapabilityReceipt.
811
- *
812
- * Ordering INVARIANT (09-CONTEXT.md, PITFALLS.md Pitfall #1):
813
- * redact -> canonicalize -> PAE -> sign -> encode
1367
+ * Anthropic adapter quirks (extends AdapterQuirks with 3 Anthropic-specific flags).
814
1368
  *
815
- * The signed digest commits to canonicalize(redact(body)). The function
816
- * structure makes any other ordering impossible to write by accident —
817
- * canonicalizeReceiptBody is ONLY called on the output of redactReceiptBody.
1369
+ * CITED: Anthropic prompt caching docs — https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
1370
+ * - `promptCachingSupported`: cache_control on system and user turns is supported on
1371
+ * all active Claude models (claude-3-* and claude-*-4 families).
818
1372
  *
819
- * Defense in depth:
820
- * - body.kid is assigned from signer.kid, never from input (input has no
821
- * kid field). The signed body and the envelope keyid CANNOT disagree by
822
- * construction.
823
- * - signer.kid is also written to envelope.signatures[0].keyid, so the
824
- * verifier can cross-check (Step 7 of verifyReceipt).
1373
+ * CITED: Anthropic extended thinking docs — https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking
1374
+ * - `extendedThinkingSupported`: thinking blocks (claude-3-7-sonnet+ and claude-*-4) available
1375
+ * via the "thinking" request parameter.
825
1376
  *
826
- * I-JSON guarantees: usage.costUsd is converted to string (or null) via
827
- * usageToCanonical. Receipts NEVER carry raw floats in the canonical form.
1377
+ * CITED: Anthropic tool use docs https://docs.anthropic.com/en/docs/build-with-claude/tool-use
1378
+ * - `toolUseInputSchemaStrict`: Anthropic tool_use blocks require strict JSON Schema in
1379
+ * the input_schema field; the adapter enforces this at call time.
828
1380
  */
829
- declare function createReceipt(input: CreateReceiptInput, signer: ReceiptSigner): Promise<ReceiptEnvelope>;
830
- //#endregion
831
- //#region src/contract/checkpoint.d.ts
1381
+ interface AnthropicQuirks extends AdapterQuirks {
1382
+ readonly promptCachingSupported: boolean;
1383
+ readonly extendedThinkingSupported: boolean;
1384
+ readonly toolUseInputSchemaStrict: boolean;
1385
+ }
832
1386
  /**
833
- * The tracer event name Lattice's checkpoint hook emits per step transition.
834
- * Identical to the literal added to RunEventKind in tracing.ts.
1387
+ * OpenAI adapter quirks (extends AdapterQuirks with 2 OpenAI-specific flags).
1388
+ *
1389
+ * CITED: OpenAI structured outputs docs — https://platform.openai.com/docs/guides/structured-outputs
1390
+ * - `strictModeSupported`: function-calling strict:true mode available on
1391
+ * gpt-4o-2024-08-06+ and o1+ series.
1392
+ * - `structuredOutputsTier2`: json_schema response_format mode (tier-2 structured outputs)
1393
+ * available on gpt-4o and gpt-4o-mini series.
835
1394
  */
836
- declare const STEP_TRANSITION_EVENT_NAME: "step.transition";
1395
+ interface OpenAIQuirks extends AdapterQuirks {
1396
+ readonly strictModeSupported: boolean;
1397
+ readonly structuredOutputsTier2: boolean;
1398
+ }
837
1399
  /**
838
- * Default band convention for the checkpoint hook (D-06). The caller is
839
- * free to register in a different band but the documented convention is
840
- * OBSERVABILITY -- between SAFETY (runs first) and EXTENSION (runs last).
1400
+ * OpenAI-compatible adapter quirks (same 5 base booleans, no new fields).
1401
+ *
1402
+ * Conservative defaults: openai-compat servers (vLLM, TGI, Ollama, custom)
1403
+ * vary widely in which response_format and tool_choice features they implement.
1404
+ * The factory populates the base fields conservatively (responseFormatHonored:
1405
+ * false, structuredOutputs: false) because the endpoint could be anything.
1406
+ * Consumers pointing at a known-good server should verify quirk values manually.
841
1407
  */
842
- declare const DEFAULT_CHECKPOINT_BAND: Band;
1408
+ interface OpenAICompatQuirks extends AdapterQuirks {}
843
1409
  /**
844
- * Per-step context the caller passes through the hook pipeline.
1410
+ * Gemini adapter quirks (extends AdapterQuirks with 3 Gemini-specific flags).
845
1411
  *
846
- * Fields are stable identifiers (D-04 carryforward); do NOT populate with
847
- * user content -- they appear cleartext in the signed receipt body.
1412
+ * CITED: Gemini API docs — https://ai.google.dev/api/generate-content#v1beta.GenerationConfig
1413
+ * - `responseSchemaSupported`: responseSchema / responseJsonSchema on generateContent
1414
+ * is available on gemini-1.5-pro+ and gemini-2.x models.
1415
+ * - `safetySettingsConfigurable`: all 4 harm categories (HARASSMENT, HATE_SPEECH,
1416
+ * SEXUALLY_EXPLICIT, DANGEROUS_CONTENT) can be set to BLOCK_NONE — verified in
1417
+ * gemini.ts:50-55.
848
1418
  *
849
- * - stepName: required. Stable identifier for this step.
850
- * - stepIndex: required. Monotonically increasing ordinal; caller-owned.
851
- * - parentStepName: optional. Names the enclosing step when nested.
852
- * - previousStepName: optional. Names the immediately-prior step in the
853
- * linked-list timeline (D-09 linked-list threading).
854
- * - timestamp: required. ISO-8601 RFC 3339.
1419
+ * CITED: Gemini API system instruction docs — https://ai.google.dev/api/generate-content#v1beta.GenerateContentRequest
1420
+ * - `systemInstructionSupported`: systemInstruction field on GenerateContentRequest
1421
+ * available on gemini-1.5+ series and later.
855
1422
  */
856
- interface CheckpointHookContext {
857
- readonly stepName: string;
858
- readonly stepIndex: number;
859
- readonly parentStepName?: string;
860
- readonly previousStepName?: string;
861
- readonly timestamp: string;
1423
+ interface GeminiQuirks extends AdapterQuirks {
1424
+ readonly responseSchemaSupported: boolean;
1425
+ readonly safetySettingsConfigurable: boolean;
1426
+ readonly systemInstructionSupported: boolean;
862
1427
  }
863
1428
  /**
864
- * The factory's options.
1429
+ * xAI adapter quirks (extends AdapterQuirks with 2 xAI-specific flags).
865
1430
  *
866
- * - runId: required. Threaded into every receipt body + every tracer event.
867
- * - tracer: optional. When omitted, the handler still mints (when signer
868
- * present) but does NOT emit a tracer event. When provided, the handler
869
- * ALWAYS emits exactly one event per invocation (independent of mint
870
- * success/failure per D-10).
871
- * - signer: optional. When omitted, the handler emits a tracer event only
872
- * (no mint attempted). When provided, the handler attempts to mint via
873
- * createReceipt(...) inside a try/catch (D-07 best-effort).
874
- * - sessionId: optional. Threaded into receipt body and event metadata.
875
- * - model: optional. ReceiptModel descriptor for the receipt body; the
876
- * factory provides a sensible "step" default when omitted.
877
- * - route: optional. ReceiptRoute descriptor for the receipt body; the
878
- * factory provides a sensible "step" default when omitted.
879
- * - contractVerdict: optional. Defaults to "success" -- step transitions
880
- * are observability events, not contract evaluations.
1431
+ * CITED: xAI API docs https://docs.x.ai/api/endpoints
1432
+ * - `reasoningTokensReported`: completion_tokens_details.reasoning_tokens reported
1433
+ * in xAI API responses verified in xai.ts:46-72.
1434
+ * - `logprobsSupported`: grok-4.20 silently ignores logprobs param per observed
1435
+ * behavior; flag indicates whether logprobs fields will be populated.
881
1436
  */
882
- interface CheckpointHookOptions {
883
- readonly runId: string;
884
- readonly tracer?: TracerLike;
885
- readonly signer?: ReceiptSigner;
886
- readonly sessionId?: string;
887
- readonly model?: ReceiptModel;
888
- readonly route?: ReceiptRoute;
889
- readonly contractVerdict?: CreateReceiptInput["contractVerdict"];
1437
+ interface XaiQuirks extends AdapterQuirks {
1438
+ readonly reasoningTokensReported: boolean;
1439
+ readonly logprobsSupported: boolean;
890
1440
  }
891
1441
  /**
892
- * Build a checkpoint hook handler.
893
- *
894
- * The returned handler is suitable for registration on a HookPipeline
895
- * created via createHookPipeline (see ./bands.ts). The handler does not
896
- * auto-register; the caller passes it to pipeline.register(...) with the
897
- * desired lifecycle event (typically AFTER_TOOL or BEFORE_TOOL) and band
898
- * (typically BAND.OBSERVABILITY, exported as DEFAULT_CHECKPOINT_BAND).
899
- *
900
- * Per-invocation behavior:
901
- * 1. Build event metadata from options + per-call context.
902
- * 2. If signer is configured, attempt createReceipt(...) inside a
903
- * try/catch. On success, set metadata.receiptId + metadata.envelope.
904
- * On failure, set metadata.mintError (string from caught error).
905
- * 3. If tracer is configured, emit exactly one tracer.event?.(
906
- * STEP_TRANSITION_EVENT_NAME, metadata) call.
907
- * 4. Return void.
1442
+ * OpenRouter adapter quirks (extends AdapterQuirks with 3 OpenRouter-specific flags).
908
1443
  *
909
- * NO upstream throw (D-07). NO global mutation (D-05).
1444
+ * CITED: OpenRouter provider routing docs https://openrouter.ai/docs/provider-routing
1445
+ * - `providerRoutingArraySupported`: the `provider.order` / `provider.only` /
1446
+ * `provider.ignore` arrays are supported for explicit routing control.
1447
+ * - `floorPricingHints`: `max_price`, `sort: "throughput" | "price"` hints on
1448
+ * GenerationConfig for cost-aware routing.
1449
+ * - `allowFallbacks`: `provider.allow_fallbacks: boolean` controls whether OpenRouter
1450
+ * retries with a different upstream provider on failure.
910
1451
  */
911
- declare function createCheckpointHook(options: CheckpointHookOptions): HookHandler<CheckpointHookContext>;
912
- //#endregion
913
- //#region src/contract/contract.d.ts
1452
+ interface OpenRouterQuirks extends AdapterQuirks {
1453
+ readonly providerRoutingArraySupported: boolean;
1454
+ readonly floorPricingHints: boolean;
1455
+ readonly allowFallbacks: boolean;
1456
+ }
914
1457
  /**
915
- * Budget invariant declaration attached to a CapabilityContract.
1458
+ * LM Studio adapter quirks (extends AdapterQuirks with 2 LM Studio-specific flags).
916
1459
  *
917
- * Phase 7 implements `maxCostUsd` enforcement at pre-flight. The
918
- * `p95LatencyMs` field is declared per CONTRACT-02 but is informational
919
- * only in Phase 7 latency observations are wired in a later phase.
1460
+ * CITED: lmstudio-bug-tracker Jinja template mismatches between model training and
1461
+ * LM Studio server defaults cause output format corruption.
1462
+ * - `customChatTemplateRiskFlag`: LM Studio servers can ship with broken chat templates
1463
+ * that don't match the model's training template; flag signals this risk.
920
1464
  *
921
- * Phase 19 (v1.2) adds `maxIterations` and `maxWallTimeMs` for the agent
922
- * runtime. Both are additive and optional; non-agent callers ignore them.
923
- * `maxIterations` caps the number of `runAgent` iterations; `maxWallTimeMs`
924
- * caps wall-clock duration per `runAgent` invocation. Both are enforced
925
- * pre-iteration in the agent loop.
1465
+ * VERIFIED: lm-studio.ts:35-37 apiKey is optional for LM Studio local servers.
1466
+ * - `noAuthRequired`: apiKey is NOT required for local LM Studio instances (no
1467
+ * authentication by default on localhost:1234).
926
1468
  */
927
- interface BudgetInvariant {
928
- readonly maxCostUsd?: number;
929
- readonly maxIterations?: number;
930
- readonly maxWallTimeMs?: number;
931
- readonly p95LatencyMs?: number;
1469
+ interface LmStudioQuirks extends AdapterQuirks {
1470
+ readonly customChatTemplateRiskFlag: boolean;
1471
+ readonly noAuthRequired: boolean;
932
1472
  }
933
1473
  /**
934
- * Quality-floor invariant.
1474
+ * LiteLLM adapter quirks (extends AdapterQuirks with gateway-specific flags).
935
1475
  *
936
- * `suite` is a fixture-directory path string; `minScore` is in 0..1.
937
- * Phase 7 forwards this into the pre-flight evaluator but only enforces
938
- * capability-side rejects. Full enforcement lives in Phase 12 (`lattice eval`).
1476
+ * LiteLLM is consumed as an OpenAI-compatible gateway. Lattice does not start,
1477
+ * embed, or depend on a LiteLLM gateway process; these flags describe the
1478
+ * helper's supported gateway metadata contract over HTTP.
939
1479
  */
940
- interface QualityFloorInvariant {
941
- readonly suite: string;
942
- readonly minScore: number;
1480
+ interface LiteLLMQuirks extends AdapterQuirks {
1481
+ readonly gatewayMetadataSupported: boolean;
1482
+ readonly gatewayFallbacksSupported: boolean;
1483
+ readonly openAIErrorMapping: boolean;
943
1484
  }
1485
+ //#endregion
1486
+ //#region src/capabilities/sanitizer-recommendations.d.ts
944
1487
  /**
945
- * The full Capability Contract attached to `RunIntent.contract`.
1488
+ * D-13 Phase 36 sanitizer registration keys. Closed string-literal union;
1489
+ * adding a 4th sanitizer in v1.4 is an intentional typed breaking change
1490
+ * that mirrors the `KnownFailureMode` discipline.
946
1491
  *
947
- * All fields are optional. v1.0 callers compile and run unchanged when
948
- * the field is omitted entirely. PROJECT.md explicitly rejects mandatory
949
- * contracts.
950
- */
951
- interface CapabilityContract {
952
- readonly kind: "capability-contract";
953
- readonly budget?: BudgetInvariant;
954
- readonly invariants?: readonly InvariantDeclaration[];
955
- readonly qualityFloor?: QualityFloorInvariant;
956
- readonly requiredModalities?: readonly CapabilityModality[];
957
- readonly requiredPrivacy?: "standard" | "sensitive" | "restricted";
958
- }
959
- /**
960
- * Reject-reason taxonomy added to `RouteRejectReason.code` by Phase 7's
961
- * pre-flight evaluator. Closed four-value union per the locked decisions
962
- * in 07-CONTEXT.md.
1492
+ * Phase 36 registers implementations under EXACTLY these 3 ids:
1493
+ * - "stripReasoningTags" — strips <think>/</think> (and model-specific) reasoning tags
1494
+ * - "stripChatTemplateArtifacts" — removes chat-template artifact leaks from output
1495
+ * - "unwrapInternalEnvelope" — extracts the user-visible payload from internal wrapper
963
1496
  */
964
- type ContractRejectReasonCode = "contract-budget-exceeded" | "contract-quality-floor" | "contract-modality-missing" | "contract-privacy-mismatch";
965
- /** Input shape accepted by `contract()`. Mirrors `CapabilityContract` minus `kind`. */
966
- interface CapabilityContractInput {
967
- readonly budget?: BudgetInvariant;
968
- readonly invariants?: readonly InvariantDeclaration[];
969
- readonly qualityFloor?: QualityFloorInvariant;
970
- readonly requiredModalities?: readonly CapabilityModality[];
971
- readonly requiredPrivacy?: "standard" | "sensitive" | "restricted";
972
- }
1497
+ type SanitizerKey = "stripReasoningTags" | "stripChatTemplateArtifacts" | "unwrapInternalEnvelope";
973
1498
  /**
974
- * Factory for `CapabilityContract` values.
1499
+ * D-14 + D-16 — Exhaustive mapping from KnownFailureMode to SanitizerKey
1500
+ * (or null when the failure mode is not a sanitizer concern). The
1501
+ * `Record<KnownFailureMode, ...>` annotation enforces compile-time
1502
+ * exhaustiveness — adding a new mode to KnownFailureMode in v1.4+ will
1503
+ * cause a type-check failure here until the planner decides on a mapping.
975
1504
  *
976
- * Mirrors the `output()` and adapter factory style — exact-optional safe
977
- * (does not emit `field: undefined` properties under `exactOptionalPropertyTypes`).
978
- * Returns a frozen value with frozen nested objects so downstream code can
979
- * rely on structural immutability when canonicalizing in Phase 9.
1505
+ * Null semantics per D-16:
1506
+ * - system_prompt_echo -> null (consumer-side prompt engineering, not a sanitizer)
1507
+ * - hallucinated_tool_name -> null (Phase 37 tool-call validator territory)
1508
+ * - malformed_tool_arguments -> null (Phase 37 tool-call validator territory)
1509
+ * - premature_termination -> null (consumer-side max_tokens config)
980
1510
  */
981
- declare function contract(input?: CapabilityContractInput): CapabilityContract;
982
- //#endregion
983
- //#region src/contract/preflight.d.ts
1511
+ declare const SANITIZER_BY_FAILURE_MODE: Record<KnownFailureMode, SanitizerKey | null>;
984
1512
  /**
985
- * Result of a single pre-flight contract evaluation against a candidate
986
- * capability. `reasons` is empty when `ok` is true and contains one or more
987
- * `RouteRejectReason` entries when `ok` is false.
1513
+ * D-14 / D-15 — Maps a list of known failure modes through the recommendation
1514
+ * table and filters nulls. `recommendedSanitizers` always contains real keys.
988
1515
  *
989
- * The evaluator surfaces ALL failing reasons in a single pass — not the
990
- * first-failing only so the deterministic router can aggregate per-candidate
991
- * rejection detail (CONTEXT.md "Pre-flight surfaces ALL failed candidates
992
- * with per-candidate rejection reasons").
993
- */
994
- interface ContractPreflightResult {
995
- readonly ok: boolean;
996
- readonly reasons: readonly RouteRejectReason[];
997
- }
998
- /**
999
- * Input for the pure cost estimator. Token counts come from the router's
1000
- * existing `estimateRoute()` helper so preflight and router agree on the
1001
- * projected output size (one source of truth — see `evaluateContractAgainstRoute`).
1516
+ * Implementation:
1517
+ * - Iterates modes in input order (Set insertion order)
1518
+ * - Skips null entries (D-16)
1519
+ * - Deduplicates via Set (so repeated modes yield one key)
1520
+ * - Returns a readonly array (frozen via spread)
1521
+ *
1522
+ * Consumers use this to populate `NegotiatedCapabilities.recommendedSanitizers`.
1523
+ * Phase 36 registers implementations under the same key ids.
1002
1524
  */
1003
- interface EstimateRouteCostInput {
1004
- readonly capability: ModelCapability;
1005
- readonly estimatedInputTokens: number;
1006
- readonly estimatedOutputTokens: number;
1525
+ declare function getRecommendedSanitizers(modes: readonly KnownFailureMode[]): readonly SanitizerKey[];
1526
+ //#endregion
1527
+ //#region src/capabilities/negotiate.d.ts
1528
+ /**
1529
+ * Phase 34 — SC-3 — Consumer-facing capability shape returned by
1530
+ * `adapter.negotiateCapabilities()` and the top-level `negotiateCapabilities()`
1531
+ * helper. Simplified relative to `ModelCapabilityProfile` (the registry
1532
+ * profile); consumers needing the full enum (e.g., native_strict vs
1533
+ * native_lenient) should look up the profile directly via `getCapabilityProfile`.
1534
+ *
1535
+ * Source values (D-09):
1536
+ * - "live" — /models endpoint hit, registry profile intersected
1537
+ * - "registry-fallback" — /models hit failed transiently (5xx/network/timeout),
1538
+ * fell back to Phase 33 static registry (D-09)
1539
+ * - "registry" — adapter intentionally has no /models endpoint
1540
+ * (LM Studio, openai-compat), OR consumer-adapter
1541
+ * fallback path (D-04)
1542
+ */
1543
+ interface NegotiatedCapabilities {
1544
+ readonly modelId: string;
1545
+ readonly contextWindow: number;
1546
+ readonly supports: {
1547
+ readonly nativeToolCalling: boolean;
1548
+ readonly structuredOutputs: boolean;
1549
+ readonly parallelToolCalls: boolean;
1550
+ readonly extendedThinking: boolean;
1551
+ readonly streaming: boolean;
1552
+ };
1553
+ readonly knownFailureModes: readonly KnownFailureMode[];
1554
+ readonly recommendedSanitizers: readonly SanitizerKey[];
1555
+ readonly source: "live" | "registry-fallback" | "registry";
1007
1556
  }
1008
1557
  /**
1009
- * Pure cost estimator. Returns `null` when pricing is unknown (so downstream
1010
- * gates can distinguish "free / zero" from "unmeasured" per the Phase 7
1011
- * cost-normalization decision). Uses static catalog metadata only no probes,
1012
- * no external pricing APIs.
1558
+ * D-10 Typed error thrown by `negotiateCapabilities` when the adapter's
1559
+ * /models endpoint returns 401 or 403. Mirrors `AgentDeniedError` shape
1560
+ * (the only existing v1.2 `class extends Error` precedent in agent/types.ts).
1561
+ *
1562
+ * Why throw (vs return-as-error-union):
1563
+ * - Auth errors indicate a broken apiKey config — it is the caller's bug
1564
+ * - Silently falling back would hide the misconfiguration
1565
+ * - `try/catch` ergonomics work cleanly with `class extends Error`
1566
+ * - `instanceof NegotiationAuthError` is the consumer ergonomic
1567
+ *
1568
+ * IMPORTANT: `NegotiationAuthError` is throwable from `negotiateCapabilities`
1569
+ * ONLY — never from `execute()`. Auth errors from /models do NOT contaminate
1570
+ * the request path.
1571
+ *
1572
+ * T-34-01-02: message field set by adapter implementations in Plans 02-04
1573
+ * MUST NOT include the apiKey. Only adapter, modelId, and httpStatus are carried.
1013
1574
  */
1014
- declare function estimateRouteCost(input: EstimateRouteCostInput): number | null;
1015
- /** Input for the pre-flight evaluator. */
1016
- interface EvaluateContractInput {
1017
- readonly capability: ModelCapability;
1018
- readonly estimatedInputTokens: number;
1019
- readonly estimatedOutputTokens: number;
1575
+ declare class NegotiationAuthError extends Error {
1576
+ readonly kind: "negotiation-auth-failed";
1577
+ readonly adapter: CapabilityAdapter;
1578
+ readonly modelId: string;
1579
+ readonly httpStatus: 401 | 403;
1580
+ constructor(adapter: CapabilityAdapter, modelId: string, httpStatus: 401 | 403, message: string);
1020
1581
  }
1021
1582
  /**
1022
- * Pure pre-flight evaluator. Phase 9 receipts will reuse this for deterministic
1023
- * verdict reconstruction.
1583
+ * Phase 34 D-02 / D-04 Top-level helper for capability negotiation.
1024
1584
  *
1025
- * Token estimation: Phase 7 does NOT define a separate token estimator. Output-
1026
- * token projection is the canonical responsibility of the router's existing
1027
- * `estimateRoute()` helper (in `routing/router.ts`), which already produces an
1028
- * `estimatedOutputTokens` value. The router passes that same value into this
1029
- * evaluator via `EvaluateContractInput.estimatedOutputTokens`, so preflight
1030
- * and the router always agree on the projected output size. Phase 9 receipts
1031
- * will pin the router's estimate as the deterministic input — intentionally
1032
- * one source of truth.
1585
+ * Pitfall 5 (zero live-path logic): delegates verbatim to
1586
+ * `adapter.negotiateCapabilities(modelId)` when the adapter implements it.
1587
+ * No inflight-coalescing, no cache, no source value transformation. The
1588
+ * adapter owns all of that.
1033
1589
  *
1034
- * Reject taxonomy (Phase 7 emits three of four codes):
1035
- * - `contract-budget-exceeded` (CONTRACT-04 + COST-03)
1036
- * - `contract-modality-missing` (CONTRACT-06)
1037
- * - `contract-privacy-mismatch` (CONTRACT-06)
1038
- * - `contract-quality-floor` (reserved for Phase 12 `lattice eval`; NEVER emitted here)
1590
+ * When the adapter has NO `negotiateCapabilities` (consumer-provided v1.2
1591
+ * adapters, third-party adapters), falls back to the Phase 33 registry
1592
+ * via `synthesizeNegotiatedCapabilitiesFromRegistry` with source "registry"
1593
+ * (D-04). Consumer adapters get useful behavior out of the box without any
1594
+ * migration code.
1595
+ *
1596
+ * Verifiable per Pitfall 5: grep for `new Map<` in this function body should
1597
+ * return zero matches; LOC count of the function body is < 10 lines.
1039
1598
  */
1040
- declare function evaluateContractAgainstRoute(contract: CapabilityContract | undefined, input: EvaluateContractInput): ContractPreflightResult;
1041
- //#endregion
1042
- //#region src/receipts/keyset.d.ts
1599
+ declare function negotiateCapabilities(adapter: ProviderAdapter, modelId: string): Promise<NegotiatedCapabilities>;
1043
1600
  /**
1044
- * In-memory KeySet factory.
1601
+ * Phase 34 — D-04 / D-09 — Synthesizes a `NegotiatedCapabilities` shape from
1602
+ * the Phase 33 static registry. Used by:
1603
+ * 1. The top-level helper (above) for consumer-adapter fallback (D-04).
1604
+ * 2. Per-adapter negotiate() implementations (Plans 02-05) when /models
1605
+ * fails transiently (D-09, source "registry-fallback").
1045
1606
  *
1046
- * Verification flow (plan 09-03):
1047
- * - keySet.lookup(kid) returns undefined → VerifyError {kind: "key-not-found"}
1048
- * - entry.state === "revoked" → VerifyError {kind: "key-revoked"}
1049
- * - entry.state === "retired" → VerifyOk + keyState: "retired" (caller may warn)
1050
- * - entry.state === "active" → VerifyOk + keyState: "active"
1607
+ * Exported as a named export so Plans 02-05 can reuse the fallback synthesis
1608
+ * without duplicating the mapping logic.
1051
1609
  *
1052
- * Duplicate kids: last write wins (deterministic callers control entry order).
1053
- * Empty entries array is legal every lookup returns undefined.
1054
- * Returned KeySet exposes only `lookup` no enumeration.
1610
+ * Implementation note: the boolean derivations are intentionally minimal
1611
+ * (heuristic, not definitive). The per-adapter negotiate() implementations
1612
+ * in Plans 02-05 own the richer derivation from live /models data.
1613
+ * This helper is a SAFETY NET for adapters without /models endpoints and
1614
+ * for transient-fallback cases.
1055
1615
  *
1056
- * See 09-CONTEXT.md "Key Management (UNRETROFITTABLE)".
1616
+ * Anti-shape (documented in CONTEXT.md <specifics>): boolean `nativeToolCalling`
1617
+ * loses the strict-vs-lenient distinction in `toolCallSurface`. Consumers
1618
+ * needing the enum should look up the profile directly via `getCapabilityProfile`.
1057
1619
  */
1058
- declare function createMemoryKeySet(entries: readonly KeyEntry[]): KeySet;
1620
+ declare function synthesizeNegotiatedCapabilitiesFromRegistry(adapter: CapabilityAdapter, modelId: string, source: "registry" | "registry-fallback"): NegotiatedCapabilities;
1059
1621
  //#endregion
1060
- //#region src/receipts/sign.d.ts
1061
- interface GeneratedEd25519KeyPair {
1062
- readonly privateKeyJwk: JsonWebKey;
1063
- readonly publicKeyJwk: JsonWebKey;
1622
+ //#region src/providers/provider.d.ts
1623
+ type CapabilityModality = "text" | "json" | "image" | "audio" | "video" | "document" | "file" | "url" | "tool";
1624
+ type ProviderTransportMode = "inline" | "json" | "url" | "base64" | "provider-upload" | "file-id" | "extracted-text" | "transcript";
1625
+ type ProviderLatencyClass = "interactive" | "batch";
1626
+ interface ProviderPricingHint {
1627
+ /** @deprecated prefer `inputPer1kTokens` — kept for backward compatibility */
1628
+ readonly inputCostPer1M?: number;
1629
+ /** @deprecated prefer `outputPer1kTokens` — kept for backward compatibility */
1630
+ readonly outputCostPer1M?: number;
1631
+ /** Per-1000-prompt-token cost in USD. Preferred field for Phase 7+ pricing. */
1632
+ readonly inputPer1kTokens?: number;
1633
+ /** Per-1000-completion-token cost in USD. Preferred field for Phase 7+ pricing. */
1634
+ readonly outputPer1kTokens?: number;
1064
1635
  }
1065
- declare function generateEd25519KeyPairJwk(): Promise<GeneratedEd25519KeyPair>;
1066
- declare function createInMemorySigner(privateKeyJwk: JsonWebKey, options: {
1067
- readonly kid: string;
1068
- readonly publicKeyJwk: JsonWebKey;
1069
- }): ReceiptSigner;
1070
- //#endregion
1071
- //#region src/receipts/verify.d.ts
1072
1636
  /**
1073
- * Pure receipt verifier.
1637
+ * Normalized per-run usage at the result layer.
1074
1638
  *
1075
- * Returns a typed VerifyResult never throws across the verification
1076
- * boundary (PITFALLS.md security: "Verifier panics on malformed receipts
1077
- * -> DoS via crafted input"). All parsing failures become typed errors.
1639
+ * `costUsd` is `number | null` (not optional, not `0`) so downstream
1640
+ * consumers can distinguish "free" (`0`) from "unmeasured" (`null`) when
1641
+ * provider pricing is unknown see 07-CONTEXT.md "Cost Normalization & Usage".
1078
1642
  *
1079
- * Decision tree (first match wins):
1080
- * 1. decodeEnvelope throws OR signatures[] empty -> envelope-malformed
1081
- * 2. payload bytes are not valid JSON -> envelope-malformed
1082
- * 3. body shape check fails OR version unknown literal -> version-mismatch
1083
- * 4. body.version === undefined OR "lattice-receipt/v1"-> schema-version-too-low (CRYPTO-01)
1084
- * 5. keySet.lookup(keyid) === undefined -> key-not-found
1085
- * 6. entry.state === "revoked" -> key-revoked
1086
- * 7. re-canonicalized body != signed payloadBytes -> canonicalization-mismatch
1087
- * 8. Ed25519 verification of PAE fails -> signature-invalid
1088
- * 9. body.kid !== entry.kid (defense in depth) -> signature-invalid
1089
- * 10. otherwise -> ok + keyState
1643
+ * Distinct from `UsageRecord` on `ProviderAttemptRecord`: `UsageRecord`
1644
+ * is the per-attempt record, `Usage` is the per-run normalized shape
1645
+ * surfaced on `RunSuccess` / `RunFailure`.
1090
1646
  */
1091
- declare function verifyReceipt(envelope: ReceiptEnvelope, keySet: KeySet): Promise<VerifyResult>;
1092
- //#endregion
1093
- //#region src/results/errors.d.ts
1094
- interface ValidationIssue {
1095
- readonly message: string;
1096
- readonly path?: readonly (string | number | symbol)[];
1097
- }
1098
- interface ValidationError {
1099
- readonly kind: "validation";
1100
- readonly message: string;
1101
- readonly output?: string;
1102
- readonly issues: readonly ValidationIssue[];
1647
+ interface Usage {
1648
+ readonly promptTokens: number;
1649
+ readonly completionTokens: number;
1650
+ readonly costUsd: number | null;
1103
1651
  }
1104
- interface ExecutionUnavailableError {
1105
- readonly kind: "execution_unavailable";
1106
- readonly message: string;
1652
+ interface ProviderDataPolicyHints {
1653
+ readonly privacy: readonly ("standard" | "sensitive" | "restricted")[];
1654
+ readonly uploadRetention?: "none" | "ephemeral" | "provider-default";
1655
+ readonly supportsNoLogging?: boolean;
1656
+ readonly supportsNoTraining?: boolean;
1107
1657
  }
1108
- interface NoRouteError {
1109
- readonly kind: "no_route";
1110
- readonly message: string;
1111
- readonly reasons: readonly string[];
1658
+ interface ModelCapability {
1659
+ readonly providerId: string;
1660
+ readonly modelId: string;
1661
+ readonly inputModalities: readonly CapabilityModality[];
1662
+ readonly outputModalities: readonly CapabilityModality[];
1663
+ readonly fileTransport: readonly ProviderTransportMode[];
1664
+ readonly contextWindow: number;
1665
+ readonly structuredOutput: boolean;
1666
+ readonly toolUse: boolean;
1667
+ readonly streaming: boolean;
1668
+ readonly pricing?: ProviderPricingHint;
1669
+ readonly latency: ProviderLatencyClass;
1670
+ readonly dataPolicy: ProviderDataPolicyHints;
1671
+ readonly available?: boolean;
1112
1672
  }
1113
- interface ProviderExecutionError {
1114
- readonly kind: "provider_execution";
1115
- readonly message: string;
1116
- readonly providerId?: string;
1117
- readonly modelId?: string;
1118
- }
1119
- interface TimeoutError {
1120
- readonly kind: "timeout";
1121
- readonly message: string;
1673
+ interface ProviderRef {
1674
+ readonly id: string;
1675
+ readonly kind?: "provider-ref";
1122
1676
  }
1123
- /**
1124
- * Phase 7 addition: emitted by the runtime when no candidate route can
1125
- * satisfy the caller-supplied `CapabilityContract` (budget, modality,
1126
- * privacy, or quality-floor invariants).
1127
- *
1128
- * `noRouteReasons` carries the full deterministic-router rejection list
1129
- * so callers can inspect per-candidate detail. Phase 9 (receipts) will
1130
- * persist this array for deterministic verdict reconstruction.
1131
- */
1132
- interface NoContractMatchError {
1133
- readonly kind: "no-contract-match";
1134
- readonly message: string;
1135
- readonly noRouteReasons: readonly RouteRejectReason[];
1677
+ interface ProviderRunRequest {
1678
+ readonly task: string;
1679
+ readonly artifacts: readonly ArtifactInput[];
1680
+ readonly outputs: readonly string[];
1681
+ readonly outputContracts?: OutputContractMap;
1682
+ readonly policy?: unknown;
1683
+ readonly signal?: AbortSignal;
1684
+ readonly plan?: ExecutionPlan;
1685
+ readonly contextPack?: ContextPack;
1686
+ readonly providerPackaging?: ProviderPackagingPlan;
1687
+ readonly packagedArtifacts?: readonly ArtifactRef[];
1688
+ /**
1689
+ * Phase 39 — opt-in prompt-cache prefix (DELEG-04). Adapters that support
1690
+ * block-granular caching (Anthropic) hoist this to a `cache_control`-marked
1691
+ * system content block; adapters that ignore it MUST receive the prefix
1692
+ * folded into `task` by the caller instead (the crew dispatcher gates on
1693
+ * `quirks.promptCachingSupported`). The field is advisory, additive, and
1694
+ * absent for all existing callers — follows the Phase 37 `toolCalls`
1695
+ * additive-field precedent (request/response additive fields accepted;
1696
+ * `ProviderAdapter` METHODS frozen per INV-03).
1697
+ */
1698
+ readonly cacheSystemPrefix?: string;
1136
1699
  }
1137
- /**
1138
- * Phase 8 addition: emitted when a `CapabilityContract.invariants` tripwire
1139
- * fires after the provider returned a schema-valid output. Carries the
1140
- * `TripwireEvidence` produced by `evaluateTripwires`.
1141
- *
1142
- * `terminal: true` is a structural marker — combined with the `isTerminal()`
1143
- * predicate it tells the fallback chain in `runWithConfig` to refuse retry.
1144
- * `NoContractMatchError` does NOT carry the field (to avoid breaking Phase 7
1145
- * callers) but `isTerminal()` still returns true for it via the kind check.
1146
- */
1147
- interface TripwireViolationError {
1148
- readonly kind: "tripwire-violated";
1149
- readonly message: string;
1150
- readonly invariantId: string;
1151
- readonly evidence: TripwireEvidence;
1152
- readonly terminal: true;
1700
+ interface ProviderGatewayMetadata {
1701
+ readonly used: boolean;
1702
+ readonly requestedModel?: string;
1703
+ readonly observedModel?: string;
1704
+ readonly fallbackModels?: readonly string[];
1705
+ readonly policy?: Record<string, unknown>;
1153
1706
  }
1154
- type LatticeRunError = ValidationError | ExecutionUnavailableError | NoRouteError | ProviderExecutionError | TimeoutError | NoContractMatchError | TripwireViolationError;
1155
- /**
1156
- * Returns `true` for run errors that MUST NOT be retried by the fallback
1157
- * chain. Phase 8 covers two kinds:
1158
- *
1159
- * - `tripwire-violated` — the contract's invariants rejected the output;
1160
- * a different provider will not change the verdict, so retry burns
1161
- * budget for no gain (T-08-06 in 08-02-PLAN threat register).
1162
- * - `no-contract-match` — no route satisfies the contract at all; the
1163
- * run never executed and no retry will help.
1164
- *
1165
- * All other error kinds return `false` and remain eligible for fallback.
1166
- * The predicate is exported so Phase 12's eval gate and any user-side
1167
- * retry wrappers can share one source of truth.
1168
- */
1169
- declare function isTerminal(error: LatticeRunError): boolean;
1170
- //#endregion
1171
- //#region src/providers/adapters.d.ts
1172
- interface OpenAICompatibleProviderOptions {
1173
- readonly id?: string;
1174
- readonly model: string;
1175
- readonly baseUrl: string;
1176
- readonly apiKey?: string;
1177
- readonly fetch?: typeof fetch;
1707
+ interface ProviderRunResponse {
1708
+ readonly rawOutputs: Record<string, unknown>;
1709
+ readonly artifactRefs?: readonly (ArtifactInput | ArtifactRef)[];
1178
1710
  /**
1179
- * Phase 7 addition: caller-supplied per-1k pricing. When provided, the
1180
- * adapter computes `normalizedUsage.costUsd` from the API-reported token
1181
- * counts. When omitted, `normalizedUsage.costUsd` is `null` so downstream
1182
- * consumers can distinguish "unmeasured" from "free" (per 07-CONTEXT.md).
1711
+ * @deprecated Legacy per-attempt usage shape. Phase 7+ adapters should
1712
+ * populate `normalizedUsage` instead Plan 04 will prefer `normalizedUsage`
1713
+ * when wiring `RunResult.usage`. Kept here for backward compatibility with
1714
+ * v1.0 adapters that already report this field.
1183
1715
  */
1184
- readonly pricing?: {
1185
- readonly inputPer1kTokens?: number;
1186
- readonly outputPer1kTokens?: number;
1187
- };
1716
+ readonly usage?: UsageRecord;
1717
+ /**
1718
+ * Phase 7 normalized usage shape for `RunResult.usage`. Populated by all
1719
+ * Phase 7+ adapters (openai, openai-compat, ai-sdk, fake). `costUsd` is
1720
+ * `null` when pricing is unknown (per the cost-normalization decision in
1721
+ * 07-CONTEXT.md — distinguishes "free" from "unmeasured").
1722
+ */
1723
+ readonly normalizedUsage?: Usage;
1724
+ readonly toolCalls?: readonly ValidatedToolCall[];
1725
+ readonly gateway?: ProviderGatewayMetadata;
1726
+ readonly rawResponse?: unknown;
1188
1727
  }
1189
- interface SdkLikeProviderOptions {
1190
- readonly id?: string;
1191
- readonly model: string;
1192
- readonly generate: (input: {
1193
- readonly task: string;
1194
- readonly outputNames: readonly string[];
1195
- }) => Promise<ProviderRunResponse> | ProviderRunResponse;
1728
+ interface ProviderStreamTextDeltaChunk {
1729
+ readonly kind: "text-delta";
1730
+ readonly output?: string;
1731
+ readonly text: string;
1196
1732
  }
1197
- declare function createOpenAICompatibleProvider(options: OpenAICompatibleProviderOptions): ProviderAdapter;
1198
- declare function createOpenAIProvider(options: OpenAICompatibleProviderOptions): ProviderAdapter;
1199
- declare function createAISdkProvider(options: SdkLikeProviderOptions): ProviderAdapter;
1200
- //#endregion
1201
- //#region src/providers/anthropic.d.ts
1202
- /**
1203
- * Options for {@link createAnthropicProvider}.
1204
- *
1205
- * Mirrors `OpenAICompatibleProviderOptions` ergonomics (Phase 7 pattern) but
1206
- * for the Anthropic Messages API at `/v1/messages` -- which uses a top-level
1207
- * `system` field and a `content[0].text` response shape that diverges from
1208
- * the OpenAI Chat Completions schema (see FSB v0.9.x `extension/ai/universal-provider.js`
1209
- * lines 280-297 + 566-573 for the production reference).
1210
- *
1211
- * SECURITY: `apiKey` is a runtime parameter -- do NOT hardcode or log it.
1212
- *
1213
- * DEFERRED (Phase 4 carryforward notes):
1214
- * - prompt caching (deferred to a follow-on phase)
1215
- * - streaming (deferred; this adapter is single-shot Promise -- per CONTEXT.md D-06)
1216
- * - tool use (Anthropic tool_use blocks are deferred)
1217
- * - resume-from-eviction -- see Phase 5 (MV3-survivability adapter contract)
1218
- *
1219
- * Ref: FSB v0.10.0-attempt-2 Phase 4 (D-02 + D-07: full custom adapter; preserve top-level `system`).
1220
- */
1221
- interface AnthropicProviderOptions {
1222
- readonly id?: string;
1223
- readonly model: string;
1224
- readonly apiKey: string;
1225
- /** Defaults to `https://api.anthropic.com`. Override for proxies. */
1226
- readonly baseUrl?: string;
1227
- /** Defaults to `2023-06-01`. Override only if the consumer has tested a newer pinned version. */
1228
- readonly anthropicVersion?: string;
1229
- readonly fetch?: typeof fetch;
1230
- readonly pricing?: {
1231
- readonly inputPer1kTokens?: number;
1232
- readonly outputPer1kTokens?: number;
1233
- };
1733
+ interface ProviderStreamOutputChunk {
1734
+ readonly kind: "output";
1735
+ readonly output: string;
1736
+ readonly value: unknown;
1234
1737
  }
1235
- declare function createAnthropicProvider(options: AnthropicProviderOptions): ProviderAdapter;
1236
- //#endregion
1237
- //#region src/providers/fake.d.ts
1238
- interface FakeProviderOptions {
1239
- readonly id?: string;
1240
- readonly modelId?: string;
1241
- readonly response?: ProviderRunResponse | ((request: ProviderRunRequest) => ProviderRunResponse | Promise<ProviderRunResponse>);
1242
- readonly artifacts?: readonly ArtifactInput[];
1738
+ interface ProviderStreamUsageChunk {
1739
+ readonly kind: "usage";
1740
+ readonly usage?: UsageRecord;
1741
+ readonly normalizedUsage?: Usage;
1742
+ }
1743
+ interface ProviderStreamGatewayChunk {
1744
+ readonly kind: "gateway";
1745
+ readonly gateway: ProviderGatewayMetadata;
1746
+ }
1747
+ interface ProviderStreamToolCallChunk {
1748
+ readonly kind: "tool-call";
1749
+ readonly toolCall: ValidatedToolCall;
1750
+ }
1751
+ interface ProviderStreamCompleteChunk {
1752
+ readonly kind: "complete";
1753
+ readonly rawOutputs?: Record<string, unknown>;
1754
+ readonly artifactRefs?: readonly (ArtifactInput | ArtifactRef)[];
1755
+ readonly usage?: UsageRecord;
1756
+ readonly normalizedUsage?: Usage;
1757
+ readonly gateway?: ProviderGatewayMetadata;
1758
+ readonly toolCalls?: readonly ValidatedToolCall[];
1759
+ readonly rawResponse?: unknown;
1760
+ }
1761
+ type ProviderStreamChunk = ProviderStreamTextDeltaChunk | ProviderStreamOutputChunk | ProviderStreamUsageChunk | ProviderStreamGatewayChunk | ProviderStreamToolCallChunk | ProviderStreamCompleteChunk;
1762
+ type ProviderStream = AsyncIterable<ProviderStreamChunk>;
1763
+ interface ProviderAdapter {
1764
+ readonly id: string;
1765
+ readonly kind: "provider-adapter";
1766
+ readonly capabilities?: readonly ModelCapability[];
1767
+ readonly execute?: (request: ProviderRunRequest) => Promise<ProviderRunResponse>;
1768
+ readonly executeStream?: (request: ProviderRunRequest) => ProviderStream | Promise<ProviderStream>;
1243
1769
  /**
1244
- * Phase 7 addition: when provided, REPLACES the default single-capability
1245
- * array so callers (notably Plan 07-04's modality/privacy reject tests)
1246
- * can construct a fake adapter with arbitrary
1247
- * `inputModalities` / `outputModalities` / `dataPolicy` / `pricing`
1248
- * without mutating the returned adapter's readonly `capabilities` array.
1249
- * When omitted, the existing default capability is used.
1770
+ * Phase 34 D-01 Per-adapter behavioral deviation flags. OPTIONAL on the
1771
+ * base interface so v1.2 consumer adapters (4-field literals) continue to work
1772
+ * without modification (non-breaking). First-party adapter factories narrow the
1773
+ * return type to require `quirks` with the specific sub-interface for their adapter.
1774
+ *
1775
+ * D-03 discriminant-narrowing contract: consumers reading this field get
1776
+ * `AdapterQuirks` autocomplete. To access adapter-specific flags, cast after
1777
+ * an `adapter.id` discriminant check OR use the typed factory return directly.
1778
+ * Example: `(adapter.quirks as AnthropicQuirks).promptCachingSupported`.
1250
1779
  */
1251
- readonly capabilities?: readonly ModelCapability[];
1780
+ readonly quirks?: AdapterQuirks;
1781
+ /**
1782
+ * Phase 34 — D-02 — Capability negotiation via the provider's /models endpoint.
1783
+ * OPTIONAL on the base interface (non-breaking for v1.2 consumer adapters).
1784
+ * First-party adapters that have a /models endpoint implement this; adapters
1785
+ * without one (LM Studio, openai-compat) fall back to the Phase 33 registry.
1786
+ *
1787
+ * The top-level `negotiateCapabilities(adapter, modelId)` helper in
1788
+ * `capabilities/negotiate.ts` delegates to this method when present and
1789
+ * synthesizes from the registry otherwise (D-04).
1790
+ */
1791
+ readonly negotiateCapabilities?: (modelId: string) => Promise<NegotiatedCapabilities>;
1252
1792
  }
1253
- declare function createFakeProvider(options?: FakeProviderOptions): ProviderAdapter;
1793
+ type ProviderRegistryInput = readonly (ProviderRef | ProviderAdapter | string)[];
1254
1794
  //#endregion
1255
- //#region src/providers/gemini.d.ts
1256
- /**
1257
- * Options for {@link createGeminiProvider}.
1258
- *
1259
- * Mirrors `OpenAICompatibleProviderOptions` ergonomics (Phase 7 pattern) but
1260
- * for Google's Generative Language API at
1261
- * `/v1beta/models/{model}:generateContent` -- which uses `contents[].parts[].text`
1262
- * (NOT OpenAI's `messages[]`), `role: "model"` for assistant turns (NOT
1263
- * `"assistant"`), authenticates via `?key=` query string, and applies a
1264
- * 4-category `safetySettings` block at `BLOCK_NONE` thresholds (FSB convention
1265
- * mirrored from `extension/ai/universal-provider.js:255-272`).
1266
- *
1267
- * SECURITY: `apiKey` is a runtime parameter -- do NOT hardcode or log it.
1268
- *
1269
- * DEFERRED (Phase 4 carryforward notes):
1270
- * - multimodal (vision) -- deferred
1271
- * - streaming -- deferred (single-shot Promise per CONTEXT.md D-06)
1272
- * - tool use -- deferred
1273
- * - resume-from-eviction -- see Phase 5 (MV3-survivability adapter contract)
1274
- *
1275
- * Ref: FSB v0.10.0-attempt-2 Phase 4 (D-02 + D-07: full custom adapter; preserve role:"model").
1276
- */
1277
- interface GeminiProviderOptions {
1278
- readonly id?: string;
1279
- readonly model: string;
1280
- readonly apiKey: string;
1281
- /** Defaults to `https://generativelanguage.googleapis.com`. */
1282
- readonly baseUrl?: string;
1283
- readonly fetch?: typeof fetch;
1284
- readonly pricing?: {
1285
- readonly inputPer1kTokens?: number;
1286
- readonly outputPer1kTokens?: number;
1287
- };
1795
+ //#region src/plan/plan.d.ts
1796
+ type ExecutionPlanStatus = "stub" | "planned" | "no-route" | "running" | "completed" | "failed";
1797
+ type ExecutionStageKind = "analysis" | "transforms" | "context-packing" | "provider-packaging" | "tool-execution" | "execution" | "validation" | "tripwire" | "persistence" | "replay";
1798
+ type ExecutionStageStatus = "pending" | "running" | "completed" | "skipped" | "failed";
1799
+ interface ExecutionPlanStage {
1800
+ readonly id: string;
1801
+ readonly kind: ExecutionStageKind;
1802
+ readonly status: ExecutionStageStatus;
1803
+ readonly inputArtifacts?: readonly string[];
1804
+ readonly outputArtifacts?: readonly string[];
1805
+ readonly warnings: readonly string[];
1806
+ readonly metadata?: Record<string, unknown>;
1807
+ }
1808
+ interface RouteRejectReason {
1809
+ readonly code: string;
1810
+ readonly message: string;
1811
+ }
1812
+ interface RouteCandidate {
1813
+ readonly providerId: string;
1814
+ readonly modelId: string;
1815
+ readonly capability: ModelCapability;
1816
+ readonly score: number;
1817
+ readonly accepted: boolean;
1818
+ readonly reasons: readonly RouteRejectReason[];
1819
+ readonly estimates: RouteEstimates;
1820
+ }
1821
+ interface RouteEstimates {
1822
+ readonly inputTokens: number;
1823
+ readonly outputTokens: number;
1824
+ readonly costUsd?: number;
1825
+ readonly latencyMs?: number;
1826
+ }
1827
+ interface SelectedRoute {
1828
+ readonly providerId: string;
1829
+ readonly modelId: string;
1830
+ readonly score: number;
1831
+ readonly estimates: RouteEstimates;
1832
+ readonly inputModalities: readonly CapabilityModality[];
1833
+ readonly outputModalities: readonly CapabilityModality[];
1834
+ readonly fileTransport: readonly ProviderTransportMode[];
1835
+ }
1836
+ interface FallbackRoute {
1837
+ readonly providerId: string;
1838
+ readonly modelId: string;
1839
+ readonly score: number;
1840
+ readonly reason: "policy-preserving-fallback";
1841
+ }
1842
+ interface RouteDecision {
1843
+ readonly catalogVersion: string;
1844
+ readonly selected?: SelectedRoute;
1845
+ readonly candidates: readonly RouteCandidate[];
1846
+ readonly rejected: readonly RouteCandidate[];
1847
+ readonly fallbackChain: readonly FallbackRoute[];
1848
+ readonly noRouteReasons: readonly RouteRejectReason[];
1849
+ }
1850
+ interface ContextPackPlan {
1851
+ readonly id: string;
1852
+ readonly tokenBudget: number;
1853
+ readonly estimatedTokens: number;
1854
+ readonly included: readonly ContextPackItemPlan[];
1855
+ readonly summarized: readonly ContextPackItemPlan[];
1856
+ readonly archived: readonly ContextPackItemPlan[];
1857
+ readonly omitted: readonly ContextPackItemPlan[];
1858
+ readonly warnings: readonly string[];
1859
+ }
1860
+ interface ContextPackItemPlan {
1861
+ readonly artifactId?: string;
1862
+ readonly sessionTurnId?: string;
1863
+ readonly reason: string;
1864
+ readonly estimatedTokens: number;
1865
+ readonly trust: "developer" | "user" | "tool" | "model-summary";
1866
+ }
1867
+ interface ProviderPackagingPlan {
1868
+ readonly providerId: string;
1869
+ readonly modelId: string;
1870
+ readonly artifacts: readonly ProviderPackagedArtifactPlan[];
1871
+ readonly warnings: readonly string[];
1872
+ }
1873
+ interface ProviderPackagedArtifactPlan {
1874
+ readonly artifactId: string;
1875
+ readonly transport: ProviderTransportMode;
1876
+ readonly mediaType?: string;
1877
+ readonly lineageTransform: "provider-packaging";
1878
+ readonly providerRequest?: ProviderPackagedArtifactRequestPlan;
1879
+ readonly warnings: readonly string[];
1880
+ }
1881
+ type ProviderPackagedArtifactSourceType = ProviderTransportMode | "file-reference";
1882
+ interface ProviderPackagedArtifactRequestPlan {
1883
+ readonly shape: string;
1884
+ readonly sourceType: ProviderPackagedArtifactSourceType;
1885
+ readonly reason: string;
1886
+ readonly mediaType?: string;
1887
+ readonly sizeBytes?: number;
1888
+ readonly reference?: ProviderPackagedArtifactReferencePlan;
1889
+ }
1890
+ interface ProviderPackagedArtifactReferencePlan {
1891
+ readonly kind: "url" | "file-id" | "file-uri" | "storage";
1892
+ readonly metadataKey?: string;
1893
+ }
1894
+ interface ProviderAttemptRecord {
1895
+ readonly providerId: string;
1896
+ readonly modelId: string;
1897
+ readonly status: "pending" | "running" | "succeeded" | "failed" | "cancelled";
1898
+ readonly startedAt?: string;
1899
+ readonly completedAt?: string;
1900
+ readonly error?: string;
1901
+ readonly usage?: UsageRecord;
1902
+ readonly metadata?: Record<string, unknown>;
1903
+ }
1904
+ interface UsageRecord {
1905
+ readonly inputTokens?: number;
1906
+ readonly outputTokens?: number;
1907
+ readonly totalTokens?: number;
1908
+ readonly costUsd?: number;
1909
+ readonly latencyMs?: number;
1910
+ }
1911
+ interface ExecutionPlan {
1912
+ readonly id: string;
1913
+ readonly kind: "execution-plan";
1914
+ readonly version: 1;
1915
+ readonly createdAt: string;
1916
+ readonly status: ExecutionPlanStatus;
1917
+ readonly task: string;
1918
+ readonly outputNames: readonly string[];
1919
+ readonly artifactRefs: readonly ArtifactRef[];
1920
+ readonly route: RouteDecision;
1921
+ readonly stages: readonly ExecutionPlanStage[];
1922
+ readonly context?: ContextPackPlan;
1923
+ readonly providerPackaging?: ProviderPackagingPlan;
1924
+ readonly attempts: readonly ProviderAttemptRecord[];
1925
+ readonly warnings: readonly string[];
1926
+ readonly metadata?: Record<string, unknown>;
1927
+ }
1928
+ interface ExecutionPlanStub {
1929
+ readonly id: string;
1930
+ readonly kind: "plan-stub";
1931
+ readonly createdAt: string;
1932
+ readonly status: "stub";
1933
+ readonly stages: readonly [];
1934
+ readonly warnings: readonly string[];
1288
1935
  }
1289
- declare function createGeminiProvider(options: GeminiProviderOptions): ProviderAdapter;
1936
+ type ResultPlan = ExecutionPlan | ExecutionPlanStub;
1290
1937
  //#endregion
1291
- //#region src/providers/lm-studio.d.ts
1292
- /**
1293
- * Options for {@link createLmStudioProvider}.
1294
- *
1295
- * Thin wrapper around {@link createOpenAICompatibleProvider} pinned to
1296
- * LM Studio's default local server URL `http://localhost:1234/v1`. Wire
1297
- * shape is OpenAI Chat Completions. LM Studio is no-auth by convention
1298
- * (CD-03): `apiKey` is OPTIONAL; when omitted, the underlying factory
1299
- * sends no `Authorization` header (see
1300
- * `lattice/packages/lattice/src/providers/adapters.ts:53` for the
1301
- * conditional auth-header wiring).
1302
- *
1303
- * DEFERRED (D-16 carryforward):
1304
- * - latency-tail diagnostics -- observability concern; LM Studio is
1305
- * the canary for latency tails (INV-03);
1306
- * diagnostics module deferred to a
1307
- * follow-on observability phase.
1308
- * - streaming -- deferred (single-shot per D-06).
1309
- * - resume-from-eviction -- see Phase 5 (MV3-survivability adapter).
1310
- *
1311
- * Ref: FSB v0.10.0-attempt-2 Phase 4 (D-03: thin wrapper; D-16: latency-tail deferred; CD-03 no-opt-out).
1312
- */
1313
- interface LmStudioProviderOptions extends Omit<OpenAICompatibleProviderOptions, "id" | "baseUrl" | "apiKey"> {
1314
- readonly id?: string;
1315
- /** Defaults to `http://localhost:1234/v1`. Override for non-localhost deployments. */
1316
- readonly baseUrl?: string;
1317
- /**
1318
- * Optional. LM Studio is no-auth by convention (CD-03 default).
1319
- * When provided, sent as `Authorization: Bearer <apiKey>` (matches the
1320
- * underlying OpenAI-compat factory). Use only for proxied LM Studio
1321
- * deployments that have a token gate in front.
1322
- */
1323
- readonly apiKey?: string;
1938
+ //#region src/receipts/types.d.ts
1939
+ type ContractVerdict = "success" | "tripwire-violated" | "no-contract-match" | "execution-failed" | "validation-failed";
1940
+ interface ReceiptUsageCanonical {
1941
+ readonly promptTokens: number;
1942
+ readonly completionTokens: number;
1943
+ readonly costUsd: string | null;
1944
+ }
1945
+ interface ReceiptModel {
1946
+ readonly requested: string;
1947
+ readonly observed: string | null;
1948
+ }
1949
+ interface ReceiptRoute {
1950
+ readonly providerId: string;
1951
+ readonly capabilityId: string;
1952
+ readonly attemptNumber: number;
1953
+ }
1954
+ interface ReceiptRedaction {
1955
+ readonly path: string;
1956
+ readonly reason: string;
1957
+ }
1958
+ interface CapabilityReceiptBody {
1959
+ readonly version: "lattice-receipt/v1" | "lattice-receipt/v1.1" | "lattice-receipt/v1.2" | "lattice-receipt/v1.3";
1960
+ readonly receiptId: string;
1961
+ readonly runId: string;
1962
+ readonly issuedAt: string;
1963
+ readonly kid: string;
1964
+ readonly model: ReceiptModel;
1965
+ readonly route: ReceiptRoute;
1966
+ readonly modelClass?: TrainingClass;
1967
+ readonly parentReceiptCid?: string;
1968
+ readonly lineageMerkleRoot?: string;
1969
+ readonly usage: ReceiptUsageCanonical;
1970
+ readonly contractVerdict: ContractVerdict;
1971
+ readonly contractHash: string | null;
1972
+ readonly inputHashes: readonly string[];
1973
+ readonly outputHash: string | null;
1974
+ readonly redactionPolicyId: string;
1975
+ readonly redactions: readonly ReceiptRedaction[];
1976
+ readonly noRouteReasons?: readonly RouteRejectReason[];
1977
+ readonly tripwireEvidence?: TripwireEvidence;
1978
+ readonly stepName?: string;
1979
+ readonly stepIndex?: number;
1980
+ readonly parentStepName?: string;
1981
+ readonly previousStepName?: string;
1982
+ readonly sessionId?: string;
1983
+ readonly timestamp?: string;
1984
+ }
1985
+ interface ReceiptSignature {
1986
+ readonly keyid: string;
1987
+ readonly sig: string;
1988
+ }
1989
+ interface ReceiptEnvelope {
1990
+ readonly payloadType: "application/vnd.lattice.receipt+json";
1991
+ readonly payload: string;
1992
+ readonly signatures: readonly ReceiptSignature[];
1993
+ }
1994
+ interface ReceiptSigner {
1995
+ readonly kid: string;
1996
+ sign(bytes: Uint8Array): Promise<Uint8Array>;
1997
+ readonly publicKeyJwk: JsonWebKey;
1998
+ }
1999
+ type KeyState = "active" | "retired" | "revoked";
2000
+ interface KeyEntry {
2001
+ readonly kid: string;
2002
+ readonly publicKeyJwk: JsonWebKey;
2003
+ readonly state: KeyState;
2004
+ }
2005
+ interface KeySet {
2006
+ lookup(kid: string): KeyEntry | undefined;
2007
+ }
2008
+ type VerifyErrorKind = "key-not-found" | "key-revoked" | "canonicalization-mismatch" | "signature-invalid" | "envelope-malformed" | "version-mismatch" | "schema-version-too-low";
2009
+ interface VerifyError {
2010
+ readonly kind: VerifyErrorKind;
2011
+ readonly message: string;
2012
+ }
2013
+ interface VerifyOk {
2014
+ readonly ok: true;
2015
+ readonly body: CapabilityReceiptBody;
2016
+ readonly keyState: KeyState;
2017
+ }
2018
+ interface VerifyFail {
2019
+ readonly ok: false;
2020
+ readonly error: VerifyError;
1324
2021
  }
1325
- declare function createLmStudioProvider(options: LmStudioProviderOptions): ProviderAdapter;
2022
+ type VerifyResult = VerifyOk | VerifyFail;
1326
2023
  //#endregion
1327
- //#region src/providers/openrouter.d.ts
2024
+ //#region src/receipts/receipt.d.ts
1328
2025
  /**
1329
- * Options for {@link createOpenRouterProvider}.
1330
- *
1331
- * Thin wrapper around {@link createOpenAICompatibleProvider} pinned to
1332
- * OpenRouter's base URL `https://openrouter.ai/api/v1`. Wire shape is
1333
- * OpenAI Chat Completions; no provider-specific quirks at the
1334
- * single-shot Promise contract level.
1335
- *
1336
- * SECURITY: `apiKey` is a runtime parameter -- do NOT hardcode or log it.
1337
- *
1338
- * DEFERRED (D-17 carryforward; Phase 4 ships the named adapter as a
1339
- * first-class OpenAI-compat wrapper):
1340
- * - model-routing array -- caller supplies `model` (single id); OpenRouter's
1341
- * `models: [primary, fallback, ...]` array
1342
- * feature is deferred to a follow-on phase.
1343
- * - fallback-array -- deferred (same phase as model-routing).
1344
- * - per-message routing -- deferred.
1345
- * - streaming -- deferred (single-shot per CONTEXT.md D-06).
1346
- * - resume-from-eviction -- see Phase 5 (MV3-survivability adapter).
2026
+ * Public input to createReceipt. Mirrors CapabilityReceiptBody minus:
2027
+ * - `version` (forced to "lattice-receipt/v1.3" per Phase 46)
2028
+ * - `kid` (forced from signer.kid caller cannot mismatch)
2029
+ * - `redactions[]` (populated by redactReceiptBody)
2030
+ * - `usage.costUsd` (converted to canonical string by usageToCanonical)
1347
2031
  *
1348
- * Ref: FSB v0.10.0-attempt-2 Phase 4 (D-03: thin wrapper; D-17: model-routing deferred).
2032
+ * receiptId and issuedAt default to runtime-generated values when omitted.
2033
+ * redactionPolicyId defaults to DEFAULT_REDACTION_POLICY_ID.
1349
2034
  */
1350
- interface OpenRouterProviderOptions extends Omit<OpenAICompatibleProviderOptions, "id" | "baseUrl"> {
1351
- readonly id?: string;
1352
- /** Defaults to `https://openrouter.ai/api/v1`. Override for proxies. */
1353
- readonly baseUrl?: string;
2035
+ interface CreateReceiptInput {
2036
+ readonly runId: string;
2037
+ readonly issuedAt?: string;
2038
+ readonly receiptId?: string;
2039
+ readonly model: ReceiptModel;
2040
+ readonly route: ReceiptRoute;
2041
+ readonly modelClass?: TrainingClass;
2042
+ readonly parentReceiptCid?: string;
2043
+ readonly lineageMerkleRoot?: string;
2044
+ readonly usage: Usage;
2045
+ readonly contractVerdict: ContractVerdict;
2046
+ readonly contractHash: string | null;
2047
+ readonly inputHashes: readonly string[];
2048
+ readonly outputHash: string | null;
2049
+ readonly redactionPolicyId?: string;
2050
+ readonly noRouteReasons?: readonly RouteRejectReason[];
2051
+ readonly tripwireEvidence?: TripwireEvidence;
2052
+ readonly stepName?: string;
2053
+ readonly stepIndex?: number;
2054
+ readonly parentStepName?: string;
2055
+ readonly previousStepName?: string;
2056
+ readonly sessionId?: string;
2057
+ readonly timestamp?: string;
1354
2058
  }
1355
- declare function createOpenRouterProvider(options: OpenRouterProviderOptions): ProviderAdapter;
1356
- //#endregion
1357
- //#region src/providers/xai.d.ts
1358
2059
  /**
1359
- * Options for {@link createXaiProvider}.
2060
+ * Build, redact, canonicalize, sign, and envelope a CapabilityReceipt.
1360
2061
  *
1361
- * Thin wrapper around {@link createOpenAICompatibleProvider} pinned to
1362
- * xAI's base URL `https://api.x.ai/v1`. The wire shape is identical to
1363
- * OpenAI Chat Completions, with one provider-specific quirk preserved:
1364
- * `response.usage.completion_tokens_details.reasoning_tokens` (xAI's
1365
- * separate reasoning-token accounting; see FSB
1366
- * `extension/ai/universal-provider.js:585-594` for the production reference).
2062
+ * Ordering INVARIANT (09-CONTEXT.md, PITFALLS.md Pitfall #1):
2063
+ * redact -> canonicalize -> PAE -> sign -> encode
1367
2064
  *
1368
- * SECURITY: `apiKey` is a runtime parameter -- do NOT hardcode or log it.
2065
+ * The signed digest commits to canonicalize(redact(body)). The function
2066
+ * structure makes any other ordering impossible to write by accident —
2067
+ * canonicalizeReceiptBody is ONLY called on the output of redactReceiptBody.
1369
2068
  *
1370
- * DEFERRED (Phase 4 carryforward notes):
1371
- * - tool-streaming -- deferred
1372
- * - streaming -- deferred (single-shot Promise per CONTEXT.md D-06)
1373
- * - resume-from-eviction -- see Phase 5 (MV3-survivability adapter contract)
2069
+ * Defense in depth:
2070
+ * - body.kid is assigned from signer.kid, never from input (input has no
2071
+ * kid field). The signed body and the envelope keyid CANNOT disagree by
2072
+ * construction.
2073
+ * - signer.kid is also written to envelope.signatures[0].keyid, so the
2074
+ * verifier can cross-check (Step 7 of verifyReceipt).
1374
2075
  *
1375
- * Ref: FSB v0.10.0-attempt-2 Phase 4 (D-03 + D-07: thin wrapper; reasoning_tokens quirk preserved).
2076
+ * I-JSON guarantees: usage.costUsd is converted to string (or null) via
2077
+ * usageToCanonical. Receipts NEVER carry raw floats in the canonical form.
1376
2078
  */
1377
- interface XaiProviderOptions extends Omit<OpenAICompatibleProviderOptions, "id" | "baseUrl"> {
1378
- readonly id?: string;
1379
- /** Defaults to `https://api.x.ai/v1`. Override for proxies. */
1380
- readonly baseUrl?: string;
1381
- }
1382
- declare function createXaiProvider(options: XaiProviderOptions): ProviderAdapter;
1383
- //#endregion
1384
- //#region src/outputs/infer.d.ts
1385
- type InferOutput<C> = C extends "text" ? string : C extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<C> : C extends CitationsOutputContract ? readonly CitationRef[] : C extends ArtifactRefsOutputContract ? readonly ArtifactRef[] : never;
1386
- type InferOutputMap<T extends OutputContractMap> = { readonly [K in keyof T]: InferOutput<T[K]> };
1387
- //#endregion
1388
- //#region src/results/result.d.ts
1389
- interface RunSuccess<TOutputs extends OutputContractMap> {
1390
- readonly ok: true;
1391
- readonly outputs: InferOutputMap<TOutputs>;
1392
- readonly artifacts: readonly ArtifactRef[];
1393
- readonly usage: Usage;
1394
- readonly plan: ResultPlan;
1395
- readonly events?: readonly RunEvent[];
1396
- /**
1397
- * Phase 9 — signed capability receipt issued when `LatticeConfig.signer`
1398
- * is configured. Undefined when no signer is set.
1399
- */
1400
- readonly receipt?: ReceiptEnvelope;
1401
- }
1402
- interface RunFailure {
1403
- readonly ok: false;
1404
- readonly error: LatticeRunError;
1405
- readonly usage: Usage;
1406
- readonly raw?: unknown;
1407
- readonly partialOutputs?: Record<string, unknown>;
1408
- readonly plan: ResultPlan;
1409
- readonly events?: readonly RunEvent[];
1410
- /**
1411
- * Phase 9 — signed capability receipt issued when `LatticeConfig.signer`
1412
- * is configured. Undefined when no signer is set.
1413
- */
1414
- readonly receipt?: ReceiptEnvelope;
1415
- }
1416
- type RunResult<TOutputs extends OutputContractMap> = RunSuccess<TOutputs> | RunFailure;
2079
+ declare function createReceipt(input: CreateReceiptInput, signer: ReceiptSigner): Promise<ReceiptEnvelope>;
1417
2080
  //#endregion
1418
- //#region src/runtime/survivability.d.ts
2081
+ //#region src/contract/checkpoint.d.ts
1419
2082
  /**
1420
- * MV3-survivability adapter contract -- Phase 5 (FSB v0.10.0-attempt-2).
1421
- *
1422
- * This module is a SIBLING of create-ai.ts (the Lattice runtime facade) and
1423
- * a SIBLING of contract/bands.ts (the hook pipeline factory) and
1424
- * contract/checkpoint.ts (the per-step receipt hook). It does NOT modify
1425
- * any of them; the SurvivabilityAdapter contract is composed from those
1426
- * surfaces by the consumer (FSB's lattice-runtime-adapter.js in Plan 05-05).
1427
- *
1428
- * What is the survivability problem?
1429
- * Some host runtimes can evict the execution context mid-flow with no
1430
- * synchronous shutdown signal:
1431
- * - Chrome MV3 service workers: evicted after 30s silence OR 5min idle.
1432
- * - Cloudflare Workers: evicted at end of each request unless waitUntil.
1433
- * - AWS Lambda: process freeze + thaw across invocations.
1434
- * Lattice's existing runtime (create-ai.ts) assumes the process stays
1435
- * live for the duration of a run. The SurvivabilityAdapter contract is
1436
- * the seam where a host runtime tells Lattice "here is how to serialize
1437
- * my state, here is how to deserialize it back, here is how to resume
1438
- * work after I get evicted and recreated."
1439
- *
1440
- * What this module SHIPS:
1441
- * - SurvivabilityAdapter<TState> interface (4 methods)
1442
- * - SerializedSnapshot type (string-encodable opaque envelope)
1443
- * - EvictionHook<TState> type (pre-eviction callback signature)
1444
- * - ResumePolicy literal-union (post-restore reconstruction verdict)
1445
- * - UnsubscribeFn type
1446
- * - createNoopSurvivabilityAdapter() reference implementation
1447
- *
1448
- * What this module DOES NOT ship:
1449
- * - chrome.storage.session integration (FSB-side; Plan 05-05).
1450
- * - offscreen-document message bus (FSB-side; Plan 05-04).
1451
- * - Auto-wiring into create-ai.ts runtime (deferred indefinitely; the
1452
- * contract is consumer-controlled).
1453
- * - Mid-API-request / mid-tool-dispatch recovery dispatcher (CONSERVATIVE
1454
- * recovery wiring is deferred to a follow-on FSB milestone per
1455
- * CONTEXT.md D-22; only the ResumePolicy taxonomy lands here).
2083
+ * The tracer event name Lattice's checkpoint hook emits per step transition.
2084
+ * Identical to the literal added to RunEventKind in tracing.ts.
2085
+ */
2086
+ declare const STEP_TRANSITION_EVENT_NAME: "step.transition";
2087
+ /**
2088
+ * Default band convention for the checkpoint hook (D-06). The caller is
2089
+ * free to register in a different band but the documented convention is
2090
+ * OBSERVABILITY -- between SAFETY (runs first) and EXTENSION (runs last).
2091
+ */
2092
+ declare const DEFAULT_CHECKPOINT_BAND: Band;
2093
+ /**
2094
+ * Per-step context the caller passes through the hook pipeline.
1456
2095
  *
1457
- * Composition conventions (NOT enforced; documented for callers):
1458
- * D-09: onEviction hooks SHOULD register in BAND.SAFETY band on the
1459
- * caller's HookPipeline so they run FIRST per Phase 2 priority
1460
- * ordering. This module does NOT auto-register; it ships the
1461
- * contract only.
1462
- * D-10: serialize(state) MAY include the latest checkpoint receipt
1463
- * envelope (Phase 3 createCheckpointHook output) inside the
1464
- * SerializedSnapshot.payload; deserialize() reconstructs session
1465
- * identifiers from the v1.1 receipt body's step-marker fields
1466
- * (stepName, stepIndex, parentStepName, previousStepName,
1467
- * sessionId, timestamp). The payload is opaque to Lattice -- the
1468
- * host runtime defines the shape.
2096
+ * Fields are stable identifiers (D-04 carryforward); do NOT populate with
2097
+ * user content -- they appear cleartext in the signed receipt body.
1469
2098
  *
1470
- * ResumePolicy taxonomy (CD-E resolution per attempt-1 02-04-PLAN.md):
1471
- * - SAFE: the snapshot was captured at a safe boundary (BEFORE_ITERATION
1472
- * or BEFORE_NEXT_ITERATION_SCHEDULE step markers) and can be replayed
1473
- * deterministically. The host runtime may re-arm the loop.
1474
- * - RECOVERY_AMBIGUOUS: the snapshot was captured during a tool dispatch
1475
- * where re-execution risk is non-zero (file write, network POST without
1476
- * Idempotency-Key, side-effecting browser action). Host should escalate
1477
- * to the user before deciding.
1478
- * - ON_ERROR_SW_EVICTION_MID_REQUEST: the eviction happened mid-API-call
1479
- * (the provider request was in flight). 6 of 7 FSB providers do NOT
1480
- * document Idempotency-Key headers; replay risks duplicate charges +
1481
- * duplicate responses. Host should treat the run as failed and surface
1482
- * the error to the user.
1483
- * - ON_ERROR_SW_EVICTION_MID_TOOL_DISPATCH: the eviction happened mid-
1484
- * tool-dispatch (a browser action was in progress). Re-execution risk
1485
- * is similar to mid-API-call but lands in a different recovery branch
1486
- * (the host may inspect the page state before deciding).
2099
+ * - stepName: required. Stable identifier for this step.
2100
+ * - stepIndex: required. Monotonically increasing ordinal; caller-owned.
2101
+ * - parentStepName: optional. Names the enclosing step when nested.
2102
+ * - previousStepName: optional. Names the immediately-prior step in the
2103
+ * linked-list timeline (D-09 linked-list threading).
2104
+ * - timestamp: required. ISO-8601 RFC 3339.
2105
+ */
2106
+ interface CheckpointHookContext {
2107
+ readonly stepName: string;
2108
+ readonly stepIndex: number;
2109
+ readonly parentStepName?: string;
2110
+ readonly previousStepName?: string;
2111
+ readonly timestamp: string;
2112
+ }
2113
+ /**
2114
+ * The factory's options.
1487
2115
  *
1488
- * SerializedSnapshot is intentionally opaque + string-encodable. The
1489
- * host runtime defines the payload shape; Lattice's only requirement
1490
- * is that serialize() followed by deserialize() round-trips the state.
2116
+ * - runId: required. Threaded into every receipt body + every tracer event.
2117
+ * - tracer: optional. When omitted, the handler still mints (when signer
2118
+ * present) but does NOT emit a tracer event. When provided, the handler
2119
+ * ALWAYS emits exactly one event per invocation (independent of mint
2120
+ * success/failure per D-10).
2121
+ * - signer: optional. When omitted, the handler emits a tracer event only
2122
+ * (no mint attempted). When provided, the handler attempts to mint via
2123
+ * createReceipt(...) inside a try/catch (D-07 best-effort).
2124
+ * - sessionId: optional. Threaded into receipt body and event metadata.
2125
+ * - model: optional. ReceiptModel descriptor for the receipt body; the
2126
+ * factory provides a sensible "step" default when omitted.
2127
+ * - route: optional. ReceiptRoute descriptor for the receipt body; the
2128
+ * factory provides a sensible "step" default when omitted.
2129
+ * - contractVerdict: optional. Defaults to "success" -- step transitions
2130
+ * are observability events, not contract evaluations.
2131
+ */
2132
+ interface CheckpointHookOptions {
2133
+ readonly runId: string;
2134
+ readonly tracer?: TracerLike;
2135
+ readonly signer?: ReceiptSigner;
2136
+ readonly sessionId?: string;
2137
+ readonly model?: ReceiptModel;
2138
+ readonly route?: ReceiptRoute;
2139
+ readonly contractVerdict?: CreateReceiptInput["contractVerdict"];
2140
+ }
2141
+ /**
2142
+ * Build a checkpoint hook handler.
1491
2143
  *
1492
- * Ed25519 receipt envelope contract (carries forward from Phase 1-3):
1493
- * Callers MAY embed a v1.1 ReceiptEnvelope inside SerializedSnapshot.payload
1494
- * for signed checkpoint round-trip. verifyReceipt against the embedded
1495
- * envelope MUST return result.ok === true after a serialize -> deserialize
1496
- * cycle (Test 12). This validates that JSON.stringify + JSON.parse over
1497
- * the envelope preserves the JCS-canonical body bytes used by DSSE PAE.
2144
+ * The returned handler is suitable for registration on a HookPipeline
2145
+ * created via createHookPipeline (see ./bands.ts). The handler does not
2146
+ * auto-register; the caller passes it to pipeline.register(...) with the
2147
+ * desired lifecycle event (typically AFTER_TOOL or BEFORE_TOOL) and band
2148
+ * (typically BAND.OBSERVABILITY, exported as DEFAULT_CHECKPOINT_BAND).
1498
2149
  *
1499
- * Threat model (Phase 5 CONTEXT.md security block):
1500
- * - PII via serialized state: callers MUST ensure SerializedSnapshot.payload
1501
- * contains only stable identifiers + user-controlled state the user has
1502
- * already consented to persist. Mirrors Phase 2 D-04 receipt-body contract
1503
- * (step-marker fields are stable identifiers, not free-form user input).
1504
- * - Snapshot tampering: the noop adapter does NOT sign the snapshot.
1505
- * Callers that need cryptographic integrity SHOULD embed a signed
1506
- * ReceiptEnvelope inside the payload + verify it on deserialize.
1507
- * Phase 5 ships the contract; signature wrapping is a follow-on.
2150
+ * Per-invocation behavior:
2151
+ * 1. Build event metadata from options + per-call context.
2152
+ * 2. If signer is configured, attempt createReceipt(...) inside a
2153
+ * try/catch. On success, set metadata.receiptId + metadata.envelope.
2154
+ * On failure, set metadata.mintError (string from caught error).
2155
+ * 3. If tracer is configured, emit exactly one tracer.event?.(
2156
+ * STEP_TRANSITION_EVENT_NAME, metadata) call.
2157
+ * 4. Return void.
1508
2158
  *
1509
- * Vocabulary separation (carries forward Phase 2 D-12 + Phase 3 D-02):
1510
- * ResumePolicy is the survivability vocabulary -- separate from
1511
- * RunEventKind (tracing) AND separate from HookLifecycleEvent (bands).
1512
- * The three vocabularies meet only when a host runtime composes them.
2159
+ * NO upstream throw (D-07). NO global mutation (D-05).
1513
2160
  */
2161
+ declare function createCheckpointHook(options: CheckpointHookOptions): HookHandler<CheckpointHookContext>;
2162
+ //#endregion
2163
+ //#region src/contract/preflight.d.ts
1514
2164
  /**
1515
- * String-encodable opaque snapshot. The host runtime defines the payload
1516
- * shape; Lattice's only requirement is that serialize() followed by
1517
- * deserialize() round-trips the original state object.
2165
+ * Result of a single pre-flight contract evaluation against a candidate
2166
+ * capability. `reasons` is empty when `ok` is true and contains one or more
2167
+ * `RouteRejectReason` entries when `ok` is false.
1518
2168
  *
1519
- * Why string-encodable? MV3's chrome.storage.session and most cross-process
1520
- * storage layers accept structured-clone-safe values. JSON-string payloads
1521
- * are the lowest-common-denominator that survives MV3 SW eviction +
1522
- * Cloudflare Worker freeze + Lambda thaw. Callers MAY use a richer payload
1523
- * shape (Uint8Array, Blob) IF the host runtime supports it; the contract
1524
- * does not constrain payload format beyond "deserialize round-trips it".
2169
+ * The evaluator surfaces ALL failing reasons in a single pass — not the
2170
+ * first-failing only so the deterministic router can aggregate per-candidate
2171
+ * rejection detail (CONTEXT.md "Pre-flight surfaces ALL failed candidates
2172
+ * with per-candidate rejection reasons").
1525
2173
  */
1526
- interface SerializedSnapshot {
1527
- readonly kind: "survivability-snapshot";
1528
- readonly version: "lattice-survivability/v1";
1529
- readonly payload: string;
1530
- readonly capturedAt: string;
2174
+ interface ContractPreflightResult {
2175
+ readonly ok: boolean;
2176
+ readonly reasons: readonly RouteRejectReason[];
1531
2177
  }
1532
2178
  /**
1533
- * Pre-eviction callback. The host runtime CAN attempt to call this hook
1534
- * before the execution context is evicted, but MAY NOT be able to in
1535
- * every case (MV3 eviction has no synchronous signal -- the SW just
1536
- * stops). Callers should treat onEviction as best-effort: useful for
1537
- * gathering final state when the eviction is announced (e.g., user-
1538
- * initiated stop) but not load-bearing for involuntary eviction.
1539
- *
1540
- * The hook receives the current TState by reference. Mutations on the
1541
- * hook side leak to the caller's state -- this is deliberate (the hook
1542
- * is the LAST chance to update state before eviction). Callers who want
1543
- * structuredClone semantics SHOULD wrap state in their own freeze layer.
2179
+ * Input for the pure cost estimator. Token counts come from the router's
2180
+ * existing `estimateRoute()` helper so preflight and router agree on the
2181
+ * projected output size (one source of truth see `evaluateContractAgainstRoute`).
1544
2182
  */
1545
- type EvictionHook<TState> = (state: TState) => void | Promise<void>;
2183
+ interface EstimateRouteCostInput {
2184
+ readonly capability: ModelCapability;
2185
+ readonly estimatedInputTokens: number;
2186
+ readonly estimatedOutputTokens: number;
2187
+ }
1546
2188
  /**
1547
- * Return value of onEviction(); calling unsubscribes the hook.
1548
- *
1549
- * Idempotent -- calling twice has the same effect as calling once.
2189
+ * Pure cost estimator. Returns `null` when pricing is unknown (so downstream
2190
+ * gates can distinguish "free / zero" from "unmeasured" per the Phase 7
2191
+ * cost-normalization decision). Uses static catalog metadata only no probes,
2192
+ * no external pricing APIs.
1550
2193
  */
1551
- type UnsubscribeFn = () => void;
2194
+ declare function estimateRouteCost(input: EstimateRouteCostInput): number | null;
2195
+ /** Input for the pre-flight evaluator. */
2196
+ interface EvaluateContractInput {
2197
+ readonly capability: ModelCapability;
2198
+ readonly estimatedInputTokens: number;
2199
+ readonly estimatedOutputTokens: number;
2200
+ }
1552
2201
  /**
1553
- * Resume policy taxonomy. The host runtime calls adapter.resume(snapshot)
1554
- * after eviction + restore; the returned policy tells the host runtime
1555
- * how to react.
2202
+ * Pure pre-flight evaluator. Phase 9 receipts will reuse this for deterministic
2203
+ * verdict reconstruction.
1556
2204
  *
1557
- * The 4 literal members carry forward from FSB v0.10.0-attempt-1's
1558
- * 02-04-PLAN.md CONSERVATIVE recovery dispatch (preserved at
1559
- * .planning/milestones/v0.10.0-attempt-1-pre-pivot/02-state-inspectability-
1560
- * carve-out/02-04-PLAN.md). Per CONTEXT.md CD-E this is the locked union.
2205
+ * Token estimation: Phase 7 does NOT define a separate token estimator. Output-
2206
+ * token projection is the canonical responsibility of the router's existing
2207
+ * `estimateRoute()` helper (in `routing/router.ts`), which already produces an
2208
+ * `estimatedOutputTokens` value. The router passes that same value into this
2209
+ * evaluator via `EvaluateContractInput.estimatedOutputTokens`, so preflight
2210
+ * and the router always agree on the projected output size. Phase 9 receipts
2211
+ * will pin the router's estimate as the deterministic input — intentionally
2212
+ * one source of truth.
2213
+ *
2214
+ * Reject taxonomy (Phase 7 emits three of four codes):
2215
+ * - `contract-budget-exceeded` (CONTRACT-04 + COST-03)
2216
+ * - `contract-modality-missing` (CONTRACT-06)
2217
+ * - `contract-privacy-mismatch` (CONTRACT-06)
2218
+ * - `contract-quality-floor` (reserved for Phase 12 `lattice eval`; NEVER emitted here)
1561
2219
  */
1562
- type ResumePolicy = "SAFE" | "RECOVERY_AMBIGUOUS" | "ON_ERROR_SW_EVICTION_MID_REQUEST" | "ON_ERROR_SW_EVICTION_MID_TOOL_DISPATCH";
2220
+ declare function evaluateContractAgainstRoute(contract: CapabilityContract | undefined, input: EvaluateContractInput): ContractPreflightResult;
2221
+ //#endregion
2222
+ //#region src/observability/otel.d.ts
2223
+ type OtelAttributeValue = string | number | boolean | readonly string[] | readonly number[] | readonly boolean[];
2224
+ type OtelAttributes = Record<string, OtelAttributeValue>;
2225
+ interface OtelSpanStatus {
2226
+ readonly code: number;
2227
+ readonly message?: string;
2228
+ }
2229
+ interface OtelSpanLike {
2230
+ setAttribute?(key: string, value: OtelAttributeValue): unknown;
2231
+ setAttributes?(attributes: OtelAttributes): unknown;
2232
+ addEvent?(name: string, attributes?: OtelAttributes): unknown;
2233
+ setStatus?(status: OtelSpanStatus): unknown;
2234
+ recordException?(error: Error | string | Record<string, unknown>): unknown;
2235
+ end?(endTime?: Date | number): unknown;
2236
+ }
2237
+ interface OtelTracerLike {
2238
+ startSpan(name: string, options?: {
2239
+ readonly attributes?: OtelAttributes;
2240
+ readonly startTime?: Date | number;
2241
+ }): OtelSpanLike;
2242
+ }
2243
+ type OtelContentCaptureMode = "none" | "metadata";
2244
+ interface OtelSanitizerOptions {
2245
+ readonly contentCapture?: OtelContentCaptureMode;
2246
+ }
2247
+ interface OtelRunEventSinkOptions extends OtelSanitizerOptions {
2248
+ readonly tracer: OtelTracerLike;
2249
+ readonly spanName?: string;
2250
+ }
2251
+ interface OtelHttpTraceConfig {
2252
+ readonly endpoint: string;
2253
+ readonly headers: Record<string, string>;
2254
+ }
2255
+ interface LangfuseOtlpConfigOptions {
2256
+ readonly baseUrl?: string;
2257
+ readonly publicKey?: string;
2258
+ readonly secretKey?: string;
2259
+ readonly authString?: string;
2260
+ readonly ingestionVersion?: string;
2261
+ readonly headers?: Record<string, string>;
2262
+ }
2263
+ interface PhoenixOtlpConfigOptions {
2264
+ readonly baseUrl?: string;
2265
+ readonly endpoint?: string;
2266
+ readonly apiKey?: string;
2267
+ readonly projectName?: string;
2268
+ readonly headers?: Record<string, string>;
2269
+ }
2270
+ declare function createOtelRunEventSink(options: OtelRunEventSinkOptions): RunEventSink;
2271
+ declare function sanitizeRunEventAttributes(event: RunEvent, options?: OtelSanitizerOptions): OtelAttributes;
2272
+ declare function createOtelReceiptAttributes(envelope: ReceiptEnvelope): Promise<OtelAttributes>;
2273
+ declare function createLangfuseOtlpConfig(options?: LangfuseOtlpConfigOptions): OtelHttpTraceConfig;
2274
+ declare function createPhoenixOtlpConfig(options?: PhoenixOtlpConfigOptions): OtelHttpTraceConfig;
2275
+ //#endregion
2276
+ //#region src/receipts/keyset.d.ts
1563
2277
  /**
1564
- * The SurvivabilityAdapter contract. Host runtimes implement this; Lattice
1565
- * runs against the interface.
2278
+ * In-memory KeySet factory.
1566
2279
  *
1567
- * 4 methods (D-08 locked):
1568
- * - serialize(state): convert in-memory state to SerializedSnapshot
1569
- * - deserialize(snapshot): inverse of serialize
1570
- * - onEviction(hook): register a best-effort pre-eviction callback
1571
- * - resume(snapshot): return ResumePolicy verdict for the post-restore
1572
- * reconstruction. The host runtime acts on the policy.
2280
+ * Verification flow (plan 09-03):
2281
+ * - keySet.lookup(kid) returns undefined → VerifyError {kind: "key-not-found"}
2282
+ * - entry.state === "revoked" → VerifyError {kind: "key-revoked"}
2283
+ * - entry.state === "retired" → VerifyOk + keyState: "retired" (caller may warn)
2284
+ * - entry.state === "active" → VerifyOk + keyState: "active"
1573
2285
  *
1574
- * Adapters are POLYMORPHIC over TState -- the host runtime parameterizes
1575
- * the type. Lattice's vitest covers the contract surface with a noop
1576
- * adapter where TState = Record<string, unknown> for ergonomics.
2286
+ * Duplicate kids: last write wins (deterministic callers control entry order).
2287
+ * Empty entries array is legal every lookup returns undefined.
2288
+ * Returned KeySet exposes only `lookup` no enumeration.
2289
+ *
2290
+ * See 09-CONTEXT.md "Key Management (UNRETROFITTABLE)".
1577
2291
  */
1578
- interface SurvivabilityAdapter<TState> {
1579
- readonly kind: "survivability-adapter";
1580
- readonly id: string;
1581
- serialize(state: TState): SerializedSnapshot;
1582
- deserialize(snapshot: SerializedSnapshot): TState;
1583
- onEviction(hook: EvictionHook<TState>): UnsubscribeFn;
1584
- resume(snapshot: SerializedSnapshot): Promise<ResumePolicy>;
2292
+ declare function createMemoryKeySet(entries: readonly KeyEntry[]): KeySet;
2293
+ //#endregion
2294
+ //#region src/receipts/remote-signer.d.ts
2295
+ type RemoteReceiptSignerProvider = "aws-kms" | "gcp-kms" | "external-kms" | (string & {});
2296
+ type RemoteReceiptPayloadFormat = "dsse-pae";
2297
+ interface RemoteReceiptSignRequest {
2298
+ readonly kid: string;
2299
+ readonly publicKeyJwk: JsonWebKey;
2300
+ readonly bytes: Uint8Array;
2301
+ readonly payloadFormat: RemoteReceiptPayloadFormat;
2302
+ readonly algorithm: "Ed25519";
2303
+ readonly provider?: RemoteReceiptSignerProvider;
2304
+ readonly keyRef?: string;
2305
+ readonly metadata?: Record<string, unknown>;
2306
+ }
2307
+ interface RemoteReceiptSignResult {
2308
+ readonly signature: Uint8Array;
2309
+ }
2310
+ interface RemoteReceiptSignerOptions {
2311
+ readonly kid: string;
2312
+ readonly publicKeyJwk: JsonWebKey;
2313
+ readonly provider?: RemoteReceiptSignerProvider;
2314
+ readonly keyRef?: string;
2315
+ readonly metadata?: Record<string, unknown>;
2316
+ sign(request: RemoteReceiptSignRequest): Promise<Uint8Array | RemoteReceiptSignResult>;
1585
2317
  }
1586
2318
  /**
1587
- * Factory options for the reference noop adapter.
2319
+ * Adapt a remote signing service to Lattice's existing ReceiptSigner contract.
1588
2320
  *
1589
- * - id: optional. Defaults to "noop-survivability". Useful when callers
1590
- * want to distinguish multiple adapter instances in test fixtures.
1591
- * - policy: optional. Sets the default ResumePolicy returned by resume().
1592
- * Defaults to "SAFE" (matches noop adapter semantics: no recovery
1593
- * ambiguity if nothing was ever persisted).
2321
+ * The callback receives the exact DSSE PAE bytes that createReceipt signs.
2322
+ * Cloud-specific request construction, hashing choices, credentials, retries,
2323
+ * and audit logging stay outside core.
1594
2324
  */
1595
- interface NoopSurvivabilityAdapterOptions {
1596
- readonly id?: string;
1597
- readonly policy?: ResumePolicy;
2325
+ declare function createRemoteReceiptSigner(options: RemoteReceiptSignerOptions): ReceiptSigner;
2326
+ //#endregion
2327
+ //#region src/receipts/sign.d.ts
2328
+ interface GeneratedEd25519KeyPair {
2329
+ readonly privateKeyJwk: JsonWebKey;
2330
+ readonly publicKeyJwk: JsonWebKey;
1598
2331
  }
2332
+ declare function generateEd25519KeyPairJwk(): Promise<GeneratedEd25519KeyPair>;
2333
+ declare function createInMemorySigner(privateKeyJwk: JsonWebKey, options: {
2334
+ readonly kid: string;
2335
+ readonly publicKeyJwk: JsonWebKey;
2336
+ }): ReceiptSigner;
2337
+ //#endregion
2338
+ //#region src/receipts/verify.d.ts
1599
2339
  /**
1600
- * Reference implementation of SurvivabilityAdapter<TState>. Records
1601
- * eviction events but does NOT persist; serialize / deserialize round-
1602
- * trip via JSON.stringify / JSON.parse. Analog to createFakeProvider
1603
- * in the providers/ module -- gives Lattice's vitest a complete shape-
1604
- * conformance target before the real (FSB-side) adapter ships in
1605
- * Plan 05-05.
2340
+ * Pure receipt verifier.
1606
2341
  *
1607
- * Per CONTEXT.md D-11 the noop adapter ships in Lattice (not FSB)
1608
- * because it covers the contract surface in Lattice's own test suite;
1609
- * FSB's real chrome.storage.session-backed adapter is glue layer.
2342
+ * Returns a typed VerifyResult never throws across the verification
2343
+ * boundary (PITFALLS.md security: "Verifier panics on malformed receipts
2344
+ * -> DoS via crafted input"). All parsing failures become typed errors.
2345
+ *
2346
+ * Decision tree (first match wins):
2347
+ * 1. decodeEnvelope throws OR signatures[] empty -> envelope-malformed
2348
+ * 2. payload bytes are not valid JSON -> envelope-malformed
2349
+ * 3. body shape check fails OR version unknown literal -> version-mismatch
2350
+ * 4. body.version === undefined OR "lattice-receipt/v1"-> schema-version-too-low (CRYPTO-01)
2351
+ * 5. keySet.lookup(keyid) === undefined -> key-not-found
2352
+ * 6. entry.state === "revoked" -> key-revoked
2353
+ * 7. re-canonicalized body != signed payloadBytes -> canonicalization-mismatch
2354
+ * 8. Ed25519 verification of PAE fails -> signature-invalid
2355
+ * 9. body.kid !== entry.kid (defense in depth) -> signature-invalid
2356
+ * 10. otherwise -> ok + keyState
1610
2357
  */
1611
- declare function createNoopSurvivabilityAdapter<TState = Record<string, unknown>>(options?: NoopSurvivabilityAdapterOptions): SurvivabilityAdapter<TState>;
1612
- //#endregion
1613
- //#region src/tools/tools.d.ts
1614
- interface ToolExecutionContext {
1615
- readonly signal?: AbortSignal;
1616
- readonly emit?: RunEventSink;
1617
- }
1618
- interface ToolDefinition<TSchema extends StandardSchemaV1 = StandardSchemaV1> {
1619
- readonly kind: "tool";
1620
- readonly name: string;
1621
- readonly description?: string;
1622
- readonly inputSchema: TSchema;
1623
- readonly execute: (input: StandardSchemaV1.InferOutput<TSchema>, context: ToolExecutionContext) => Promise<unknown> | unknown;
1624
- }
1625
- interface ToolCallResult {
1626
- readonly callId: string;
1627
- readonly toolName: string;
1628
- readonly artifact: ArtifactInput;
1629
- }
1630
- declare function defineTool<TSchema extends StandardSchemaV1>(definition: Omit<ToolDefinition<TSchema>, "kind">): ToolDefinition<TSchema>;
1631
- declare function runTool<TSchema extends StandardSchemaV1>(tool: ToolDefinition<TSchema>, input: unknown, context?: ToolExecutionContext): Promise<ToolCallResult>;
1632
- interface McpLikeClient {
1633
- readonly listTools?: () => Promise<readonly McpToolDescriptor[]> | readonly McpToolDescriptor[];
1634
- readonly callTool: (input: {
1635
- readonly name: string;
1636
- readonly arguments: unknown;
1637
- }) => Promise<unknown> | unknown;
1638
- }
1639
- interface McpToolDescriptor {
1640
- readonly name: string;
1641
- readonly description?: string;
1642
- readonly inputSchema: StandardSchemaV1;
1643
- }
1644
- declare function importMcpTools(client: McpLikeClient, toolNames?: readonly string[]): Promise<readonly ToolDefinition[]>;
1645
- declare function toolArtifactRef(result: ToolCallResult): ArtifactRef;
2358
+ declare function verifyReceipt(envelope: ReceiptEnvelope, keySet: KeySet): Promise<VerifyResult>;
1646
2359
  //#endregion
1647
- //#region src/agent/format-tools.d.ts
2360
+ //#region src/providers/no-public-url.d.ts
1648
2361
  /**
1649
- * One turn in the running conversation.
2362
+ * Thrown when a run with `policy.noPublicUrl: true` is about to dispatch a
2363
+ * request whose serialized body still contains a public http(s) URL derived
2364
+ * from `request.artifacts` (value or string metadata entry).
1650
2365
  *
1651
- * `role: "tool"` is used for tool-result turns; `toolCallId` and `toolName`
1652
- * are populated so the model can correlate the result with its prior
1653
- * `tool_call` envelope.
2366
+ * This is the single shared egress error class for all three adapter families
2367
+ * (OpenAI-compatible, Anthropic, Gemini). Callers may `instanceof`-check it.
1654
2368
  */
1655
- interface ConversationTurn {
1656
- readonly role: "user" | "assistant" | "tool";
1657
- readonly content: string;
1658
- readonly toolCallId?: string;
1659
- readonly toolName?: string;
2369
+ declare class NoPublicUrlEgressError extends Error {
2370
+ readonly providerId: string;
2371
+ readonly artifactId: string;
2372
+ readonly offendingUrl: string;
2373
+ constructor(providerId: string, artifactId: string, offendingUrl: string);
1660
2374
  }
1661
- type FormatToolsMode = "native" | "prompt-reencoded" | "auto";
1662
- interface FormatToolsOptions {
2375
+ //#endregion
2376
+ //#region src/sanitizers/sanitizers.d.ts
2377
+ interface SanitizerContext {
2378
+ readonly providerId: string;
2379
+ readonly modelId?: string;
2380
+ readonly outputName: string;
2381
+ }
2382
+ type SanitizerFn = (text: string, context: SanitizerContext) => string | Promise<string>;
2383
+ type SanitizeOutputOption = SanitizerFn | readonly SanitizerFn[];
2384
+ interface InternalEnvelopeOptions {
2385
+ readonly field?: string;
2386
+ readonly path?: string;
2387
+ readonly schema?: StandardSchemaV1;
2388
+ }
2389
+ declare function stripReasoningTags(): SanitizerFn;
2390
+ declare function stripChatTemplateArtifacts(): SanitizerFn;
2391
+ declare function unwrapInternalEnvelope(schemaOrPath: string | InternalEnvelopeOptions | StandardSchemaV1): SanitizerFn;
2392
+ //#endregion
2393
+ //#region src/providers/adapters.d.ts
2394
+ interface OpenAICompatibleProviderOptions {
2395
+ readonly id?: string;
2396
+ readonly model: string;
2397
+ readonly baseUrl: string;
2398
+ readonly apiKey?: string;
2399
+ readonly gateway?: GatewayPolicy;
2400
+ readonly fetch?: typeof fetch;
1663
2401
  /**
1664
- * Tool-use protocol mode. Defaults to `"auto"`, which currently resolves
1665
- * to `"prompt-reencoded"` for ALL 7 providers (Phase 19 simplification —
1666
- * native tool_use deferred to a follow-on milestone). Reserved for
1667
- * forward compatibility.
2402
+ * Phase 7 addition: caller-supplied per-1k pricing. When provided, the
2403
+ * adapter computes `normalizedUsage.costUsd` from the API-reported token
2404
+ * counts. When omitted, `normalizedUsage.costUsd` is `null` so downstream
2405
+ * consumers can distinguish "unmeasured" from "free" (per 07-CONTEXT.md).
1668
2406
  */
1669
- readonly mode?: FormatToolsMode;
2407
+ readonly pricing?: {
2408
+ readonly inputPer1kTokens?: number;
2409
+ readonly outputPer1kTokens?: number;
2410
+ };
1670
2411
  /**
1671
- * Optional system prompt to prepend. Useful for setting persona /
1672
- * domain-specific instructions on top of the tool-use envelope.
2412
+ * Phase 34 D-05/D-06/D-08 TTL for the per-instance models cache.
2413
+ * Default 300_000ms (5 minutes). Set to 0 to disable caching.
2414
+ * Set to Infinity for process-lifetime caching.
2415
+ *
2416
+ * NOTE: for createOpenAICompatibleProvider, this option is accepted for
2417
+ * option-bag uniformity but is NOT USED — openai-compat has no /models
2418
+ * endpoint (D-04). Document in JSDoc for consumers pointing at known servers.
1673
2419
  */
1674
- readonly system?: string;
1675
- }
1676
- interface FormattedToolsHandle {
2420
+ readonly modelsCacheTtlMs?: number;
1677
2421
  /**
1678
- * Builds the single `task` string passed to `ProviderAdapter.execute()`.
1679
- * Encodes the conversation, available tools, and response-envelope
1680
- * instructions.
2422
+ * Phase 34 D-11 Number of retry attempts on transient /models errors
2423
+ * (5xx, network, timeout). Default 2. Set to 0 to disable retries.
2424
+ *
2425
+ * NOTE: for createOpenAICompatibleProvider, this option is accepted for
2426
+ * option-bag uniformity but is NOT USED — openai-compat has no /models
2427
+ * endpoint (D-04).
1681
2428
  */
1682
- readonly buildTask: (conversation: readonly ConversationTurn[]) => string;
2429
+ readonly modelsRetryCount?: number;
1683
2430
  /**
1684
- * Parses the assistant's response text. Returns:
1685
- * - `ToolUseRequest[]` when the response contains one or more tool-call
1686
- * envelopes (parsed in declaration order).
1687
- * - `null` when the response is a final answer (no tool-call envelopes
1688
- * detected).
2431
+ * Phase 34 D-12 — Optional RunEventSink for capability negotiation events.
2432
+ * When provided, emits the "capabilities.negotiation.fallback" event on
2433
+ * transient /models errors (5xx, network, timeout).
1689
2434
  *
1690
- * The parser is forgiving: it tolerates extra prose around the JSON
1691
- * envelope (markdown fences, leading explanations) and the model
1692
- * occasionally drifting on whitespace.
2435
+ * NOTE: for createOpenAICompatibleProvider, this option is accepted for
2436
+ * option-bag uniformity but the event is NOT FIRED for source: "registry"
2437
+ * (the documented happy path for openai-compat). Emitting events for the
2438
+ * intentional no-endpoint path would produce noisy false-positives.
1693
2439
  */
1694
- readonly parseToolUse: (responseText: string) => ReadonlyArray<ToolUseRequest> | null;
2440
+ readonly runEventSink?: RunEventSink;
1695
2441
  /**
1696
- * Returns the static system block describing available tools. Useful for
1697
- * tracing / logging the exact tool-description text fed to the model.
2442
+ * Phase 36 Optional output sanitizer pipeline. When provided, string
2443
+ * rawOutputs are transformed in order after provider text extraction and
2444
+ * before the adapter returns.
1698
2445
  */
1699
- readonly describeForSystem: () => string;
2446
+ readonly sanitizeOutput?: SanitizeOutputOption;
1700
2447
  /**
1701
- * Effective mode this handle resolved to (`"prompt-reencoded"` for all
1702
- * v1.2 providers). Exposed for inspectability.
2448
+ * Phase 37 Optional returned tool-call validator. When provided, the
2449
+ * adapter parses prompt-reencoded tool_calls envelopes and returns
2450
+ * normalized validated calls without mutating rawOutputs or rawResponse.
1703
2451
  */
1704
- readonly mode: "prompt-reencoded";
2452
+ readonly validateToolCalls?: ValidateToolCallsOption;
2453
+ }
2454
+ interface SdkLikeProviderOptions {
2455
+ readonly id?: string;
2456
+ readonly model: string;
2457
+ readonly generate: (input: {
2458
+ readonly task: string;
2459
+ readonly outputNames: readonly string[];
2460
+ }) => Promise<ProviderRunResponse> | ProviderRunResponse;
1705
2461
  }
1706
2462
  /**
1707
- * Convert a Standard Schema to a JSON Schema-shaped descriptor suitable for
1708
- * inclusion in an LLM tool description. Standard Schema vendors can
1709
- * optionally expose `toJSONSchema` on their schema objects; when absent,
1710
- * we fall back to a minimal structural description that lists the schema
1711
- * vendor + version + a placeholder. Models tolerate placeholder schemas in
1712
- * practice because the tool description is supplementary — what matters
1713
- * is the envelope contract (`{tool_call: {name, args}}`).
1714
- */
1715
- declare function toolSchemaToJsonSchema(schema: StandardSchemaV1): unknown;
1716
- /**
1717
- * Builds the prompt-reencoded tool-use protocol handle for any provider.
2463
+ * Phase 34 D-04 / QUIRK-02 OpenAI-compatible provider factory.
1718
2464
  *
1719
- * Phase 19 ships a uniform implementation across all 7 logical providers
1720
- * (openai, openai-compat, anthropic, gemini, xai, openrouter, lm-studio).
1721
- * The `providerName` argument is accepted for forward compatibility but
1722
- * does not branch the implementation in v1.2.
2465
+ * This factory is the prototypical "intentional no remote /models endpoint"
2466
+ * adapter per D-04. The consumer points this adapter at any OpenAI-shaped
2467
+ * endpoint (vLLM, TGI, Ollama, custom), and the factory returns conservative
2468
+ * defaults for the quirks block because the server could be anything.
2469
+ *
2470
+ * The `negotiateCapabilities` method performs NO fetch; it returns
2471
+ * synthesizeNegotiatedCapabilitiesFromRegistry with source: "registry"
2472
+ * (the intentional-no-endpoint signal, as distinct from "registry-fallback"
2473
+ * which signals a transient failure). Plan 34-05 (LM Studio) reuses this
2474
+ * same pattern.
2475
+ *
2476
+ * D-04 citation: "consumer adapters without a /models endpoint skip the
2477
+ * fetch layer entirely and delegate to synthesizeNegotiatedCapabilitiesFromRegistry."
1723
2478
  */
1724
- declare function formatToolsForProvider(providerName: string, tools: ReadonlyArray<ToolDefinition<StandardSchemaV1>>, options?: FormatToolsOptions): FormattedToolsHandle;
2479
+ declare function createOpenAICompatibleProvider(options: OpenAICompatibleProviderOptions): ProviderAdapter & {
2480
+ readonly quirks: OpenAICompatQuirks;
2481
+ readonly negotiateCapabilities: (modelId: string) => Promise<NegotiatedCapabilities>;
2482
+ };
2483
+ /**
2484
+ * Phase 34 — QUIRK-02 / NEG-01 / NEG-02 — OpenAI provider factory.
2485
+ *
2486
+ * Extends the base OpenAI-compat factory with:
2487
+ * 1. `quirks: OpenAIQuirks` — verified per RESEARCH §Q6 OpenAI vocabulary.
2488
+ * 2. `negotiateCapabilities(modelId)` — queries OpenAI /v1/models GET with
2489
+ * Authorization: Bearer header; SPARSE response; intersects with Phase 33
2490
+ * registry for supports.* (per RESEARCH §Anti-patterns — don't assume
2491
+ * OpenAI /v1/models returns capability flags, it doesn't).
2492
+ *
2493
+ * The negotiate() pattern mirrors Plan 34-02 (Anthropic thick reference):
2494
+ * - Per-instance TTL cache (modelsCacheTtlMs, default 300_000ms)
2495
+ * - Single-flight inflight coalescing with .finally cleanup (Pitfall 4)
2496
+ * - Retry with [0, 200, 1000]ms backoff (modelsRetryCount, default 2)
2497
+ * - 401/403 throws NegotiationAuthError (D-10: no retry, no fallback, no event)
2498
+ * - 5xx/network/timeout falls back to registry with source: "registry-fallback"
2499
+ * - emitFallbackEvent fires the "capabilities.negotiation.fallback" RunEvent
2500
+ *
2501
+ * SECURITY (T-34-03-07): inflight Map MUST use .finally cleanup to prevent
2502
+ * leak on rejection. Verifiable: grep `.finally` in this file.
2503
+ */
2504
+ declare function createOpenAIProvider(options: OpenAICompatibleProviderOptions): ProviderAdapter & {
2505
+ readonly quirks: OpenAIQuirks;
2506
+ readonly negotiateCapabilities: (modelId: string) => Promise<NegotiatedCapabilities>;
2507
+ };
2508
+ declare function createAISdkProvider(options: SdkLikeProviderOptions): ProviderAdapter;
1725
2509
  //#endregion
1726
- //#region src/agent/host.d.ts
2510
+ //#region src/providers/anthropic.d.ts
1727
2511
  /**
1728
- * Snapshot shape the agent loop serializes between iterations. The full
1729
- * shape is opaque to callers (they only see it through SerializedSnapshot
1730
- * via the configured SurvivabilityAdapter) but it's exported so reference
1731
- * implementations and tests can inspect the round-trip.
2512
+ * Options for {@link createAnthropicProvider}.
2513
+ *
2514
+ * Mirrors `OpenAICompatibleProviderOptions` ergonomics (Phase 7 pattern) but
2515
+ * for the Anthropic Messages API at `/v1/messages` -- which uses a top-level
2516
+ * `system` field and a `content[0].text` response shape that diverges from
2517
+ * the OpenAI Chat Completions schema (see FSB v0.9.x `extension/ai/universal-provider.js`
2518
+ * lines 280-297 + 566-573 for the production reference).
2519
+ *
2520
+ * SECURITY: `apiKey` is a runtime parameter -- do NOT hardcode or log it.
2521
+ *
2522
+ * STREAMING (Phase 44): supported through native Anthropic Messages SSE events.
2523
+ *
2524
+ * DEFERRED (Phase 4 carryforward notes):
2525
+ * - prompt caching (Phase 39: opt-in via `ProviderRunRequest.cacheSystemPrefix` —
2526
+ * emitted as a cache_control-marked system block when present)
2527
+ * - resume-from-eviction -- see Phase 5 (MV3-survivability adapter contract)
2528
+ *
2529
+ * Ref: FSB v0.10.0-attempt-2 Phase 4 (D-02 + D-07: full custom adapter; preserve top-level `system`).
1732
2530
  */
1733
- interface AgentSnapshot {
1734
- readonly version: "agent-snapshot/v1";
1735
- readonly iterationIndex: number;
1736
- readonly conversation: readonly ConversationTurn[];
1737
- readonly cumulativeUsage: Usage;
1738
- readonly providerName: string;
1739
- readonly capturedAt: string;
2531
+ interface AnthropicProviderOptions {
2532
+ readonly id?: string;
2533
+ readonly model: string;
2534
+ readonly apiKey: string;
2535
+ /** Defaults to `https://api.anthropic.com`. Override for proxies. */
2536
+ readonly baseUrl?: string;
2537
+ /** Defaults to `2023-06-01`. Override only if the consumer has tested a newer pinned version. */
2538
+ readonly anthropicVersion?: string;
2539
+ readonly fetch?: typeof fetch;
2540
+ readonly pricing?: {
2541
+ readonly inputPer1kTokens?: number;
2542
+ readonly outputPer1kTokens?: number;
2543
+ };
2544
+ /**
2545
+ * D-08: Per-instance TTL for the /v1/models response cache (milliseconds).
2546
+ * Default 300_000 (5 minutes). `0` disables caching (always re-fetch -- for testing).
2547
+ * `Infinity` disables expiry (process-lifetime for the instance).
2548
+ */
2549
+ readonly modelsCacheTtlMs?: number;
2550
+ /**
2551
+ * D-11: Number of retries for transient /v1/models fetch failures (5xx, network,
2552
+ * timeout). Default 2 (3 total attempts). `0` disables retries.
2553
+ * Backoff schedule: [0ms, 200ms, 1000ms].
2554
+ */
2555
+ readonly modelsRetryCount?: number;
2556
+ /**
2557
+ * D-12: Optional RunEventSink for emitting `capabilities.negotiation.fallback`
2558
+ * events when the /v1/models fetch falls back to the Phase 33 static registry.
2559
+ * If absent, fallback emits no event (no-op). Auth errors (401/403) never emit
2560
+ * the fallback event -- they throw `NegotiationAuthError` instead.
2561
+ */
2562
+ readonly runEventSink?: RunEventSink;
2563
+ readonly sanitizeOutput?: SanitizeOutputOption;
2564
+ readonly validateToolCalls?: ValidateToolCallsOption;
2565
+ }
2566
+ declare function createAnthropicProvider(options: AnthropicProviderOptions): ProviderAdapter & {
2567
+ readonly quirks: AnthropicQuirks;
2568
+ readonly negotiateCapabilities: (modelId: string) => Promise<NegotiatedCapabilities>;
2569
+ };
2570
+ //#endregion
2571
+ //#region src/providers/fake.d.ts
2572
+ interface FakeProviderOptions {
2573
+ readonly id?: string;
2574
+ readonly modelId?: string;
2575
+ readonly response?: ProviderRunResponse | ((request: ProviderRunRequest) => ProviderRunResponse | Promise<ProviderRunResponse>);
2576
+ readonly artifacts?: readonly ArtifactInput[];
2577
+ /**
2578
+ * Phase 7 addition: when provided, REPLACES the default single-capability
2579
+ * array so callers (notably Plan 07-04's modality/privacy reject tests)
2580
+ * can construct a fake adapter with arbitrary
2581
+ * `inputModalities` / `outputModalities` / `dataPolicy` / `pricing`
2582
+ * without mutating the returned adapter's readonly `capabilities` array.
2583
+ * When omitted, the existing default capability is used.
2584
+ */
2585
+ readonly capabilities?: readonly ModelCapability[];
1740
2586
  }
2587
+ declare function createFakeProvider(options?: FakeProviderOptions): ProviderAdapter;
2588
+ //#endregion
2589
+ //#region src/providers/gemini.d.ts
1741
2590
  /**
1742
- * Scheduler seam controls how the agent loop yields between iterations.
2591
+ * Options for {@link createGeminiProvider}.
1743
2592
  *
1744
- * `scheduleNext(iterationIndex)` is called AFTER an AFTER_AGENT_ITERATION
1745
- * emission and BEFORE the next iteration's BEFORE_AGENT_ITERATION. The
1746
- * scheduler decides when to resume — synchronously (sync loop), on next
1747
- * tick (setTimeout/queueMicrotask), via a queue (Durable Object), or any
1748
- * other strategy.
2593
+ * Mirrors `OpenAICompatibleProviderOptions` ergonomics (Phase 7 pattern) but
2594
+ * for Google's Generative Language API at
2595
+ * `/v1beta/models/{model}:generateContent` -- which uses `contents[].parts[].text`
2596
+ * (NOT OpenAI's `messages[]`), `role: "model"` for assistant turns (NOT
2597
+ * `"assistant"`), authenticates via `?key=` query string for execute(), and applies a
2598
+ * 4-category `safetySettings` block at `BLOCK_NONE` thresholds (FSB convention
2599
+ * mirrored from `extension/ai/universal-provider.js:255-272`).
1749
2600
  *
1750
- * Default (noop): resolves immediately.
2601
+ * SECURITY: `apiKey` is a runtime parameter -- do NOT hardcode or log it.
2602
+ *
2603
+ * STREAMING (Phase 44): supported through native `streamGenerateContent` SSE events.
2604
+ *
2605
+ * DEFERRED (Phase 4 carryforward notes):
2606
+ * - multimodal (vision) -- deferred
2607
+ * - resume-from-eviction -- see Phase 5 (MV3-survivability adapter contract)
2608
+ *
2609
+ * NOTE (Phase 34): negotiate() uses x-goog-api-key HEADER (preferred per RESEARCH §Q3).
2610
+ * The existing execute() path uses ?key= query string -- execute() migration is out-of-scope
2611
+ * for Phase 34 (additive only; T-34-04-01).
2612
+ *
2613
+ * Ref: FSB v0.10.0-attempt-2 Phase 4 (D-02 + D-07: full custom adapter; preserve role:"model").
1751
2614
  */
1752
- interface AgentScheduler {
1753
- scheduleNext(iterationIndex: number): Promise<void>;
2615
+ interface GeminiProviderOptions {
2616
+ readonly id?: string;
2617
+ readonly model: string;
2618
+ readonly apiKey: string;
2619
+ /** Defaults to `https://generativelanguage.googleapis.com`. */
2620
+ readonly baseUrl?: string;
2621
+ readonly fetch?: typeof fetch;
2622
+ readonly pricing?: {
2623
+ readonly inputPer1kTokens?: number;
2624
+ readonly outputPer1kTokens?: number;
2625
+ };
2626
+ /**
2627
+ * D-08: TTL for per-instance /models response cache, in milliseconds.
2628
+ * Default: 300_000ms (5 minutes). 0 = always refetch (tests). Infinity = process-lifetime.
2629
+ */
2630
+ readonly modelsCacheTtlMs?: number;
2631
+ /**
2632
+ * D-11: Number of retries on transient /models fetch errors. Default: 2.
2633
+ * Retry schedule: immediate + 200ms + 1000ms (3 total attempts at retryCount=2).
2634
+ * 0 = no retries (1 attempt total).
2635
+ */
2636
+ readonly modelsRetryCount?: number;
2637
+ /**
2638
+ * D-12: Optional event sink for observability. When provided, the adapter
2639
+ * emits a "capabilities.negotiation.fallback" RunEvent on transient /models failure.
2640
+ * If absent, no event is emitted (silent fallback).
2641
+ */
2642
+ readonly runEventSink?: RunEventSink;
2643
+ readonly sanitizeOutput?: SanitizeOutputOption;
2644
+ readonly validateToolCalls?: ValidateToolCallsOption;
1754
2645
  }
1755
2646
  /**
1756
- * Transport seamcontrols how a provider call is dispatched.
2647
+ * Phase 34D-03 / D-05..D-12 Extended Gemini provider factory.
1757
2648
  *
1758
- * `call(provider, request)` wraps the provider's `execute()` invocation.
1759
- * Default (noop): pass-through (`provider.execute!(request)`). Cross-process
1760
- * bridges (FSB's offscreen-document host) override to dispatch via
1761
- * `chrome.runtime.sendMessage`.
2649
+ * Returns a `ProviderAdapter` narrowed to expose:
2650
+ * - `quirks: GeminiQuirks` — static adapter capability flags
2651
+ * - `negotiateCapabilities(modelId)` live /v1beta/models fetch with medium-thick
2652
+ * derivation (inputTokenLimit + thinking + supportedGenerationMethods from upstream)
2653
+ * intersected with Phase 33 registry; TTL cache + inflight coalescing + retry +
2654
+ * auth-throw + transient-fallback + event.
1762
2655
  *
1763
- * Per the Phase 19 INV-03 parity invariant, the transport seam does NOT
1764
- * modify the `ProviderAdapter` interface it operates on top of the
1765
- * existing `execute()` method.
2656
+ * NOTE on auth strategy (T-34-04-01): negotiate() uses x-goog-api-key HEADER
2657
+ * (preferred per RESEARCH §Q3 -- avoids leaking the key in server-side logs that
2658
+ * capture URL query strings). The existing execute() path uses ?key= query string
2659
+ * and is NOT changed by Phase 34 (out-of-scope migration).
1766
2660
  */
1767
- interface AgentTransport {
1768
- call(provider: ProviderAdapter, request: ProviderRunRequest): Promise<ProviderRunResponse>;
1769
- }
2661
+ declare function createGeminiProvider(options: GeminiProviderOptions): ProviderAdapter & {
2662
+ readonly quirks: GeminiQuirks;
2663
+ readonly negotiateCapabilities: (modelId: string) => Promise<NegotiatedCapabilities>;
2664
+ };
2665
+ //#endregion
2666
+ //#region src/providers/litellm.d.ts
1770
2667
  /**
1771
- * Storage seam controls how agent state persists between iterations for
1772
- * resume after host eviction.
1773
- *
1774
- * Phase 20 composes this with the Phase 18 `SurvivabilityAdapter`:
1775
- * - The adapter serializes `AgentSnapshot` to `SerializedSnapshot` on
1776
- * each AFTER_AGENT_ITERATION; storage.save() persists the snapshot.
1777
- * - On run start, the agent loop calls storage.load(). If a non-null
1778
- * snapshot is returned, the adapter deserializes it; the loop resumes
1779
- * at the recorded iteration index.
1780
- * - On success, the loop calls storage.clear() so the next run starts
1781
- * fresh.
2668
+ * Options for {@link createLiteLLMProvider}.
1782
2669
  *
1783
- * Default (noop): save() is a no-op, load() returns null, clear() is a
1784
- * no-op. Suitable for Node tests where eviction never occurs.
2670
+ * Thin wrapper around {@link createOpenAICompatibleProvider} pinned to the
2671
+ * documented local LiteLLM proxy URL. LiteLLM is treated as an
2672
+ * OpenAI-compatible gateway over HTTP; this helper does not start, embed, or
2673
+ * depend on a LiteLLM gateway process.
1785
2674
  */
1786
- interface AgentStorage {
1787
- save(snapshot: SerializedSnapshot): Promise<void>;
1788
- load(): Promise<SerializedSnapshot | null>;
1789
- clear(): Promise<void>;
2675
+ interface LiteLLMProviderOptions extends Omit<OpenAICompatibleProviderOptions, "id" | "baseUrl" | "gateway"> {
2676
+ readonly id?: string;
2677
+ /** Defaults to `http://localhost:4000`. Override for hosted proxies or `/v1` deployments. */
2678
+ readonly baseUrl?: string;
2679
+ readonly gateway?: GatewayPolicy;
1790
2680
  }
2681
+ declare function createLiteLLMProvider(options: LiteLLMProviderOptions): ProviderAdapter & {
2682
+ readonly quirks: LiteLLMQuirks;
2683
+ readonly negotiateCapabilities: (modelId: string) => Promise<NegotiatedCapabilities>;
2684
+ };
2685
+ //#endregion
2686
+ //#region src/providers/lm-studio.d.ts
1791
2687
  /**
1792
- * The host adapter — three optional seams, all swappable independently.
2688
+ * Options for {@link createLmStudioProvider}.
1793
2689
  *
1794
- * Callers pass `host` on `AgentIntent`. The agent runtime falls back to
1795
- * `createNoopAgentHost()` when `intent.host` is absent (so Phase 19
1796
- * single-shot Node usage continues to work without explicit configuration).
2690
+ * Thin wrapper around {@link createOpenAICompatibleProvider} pinned to
2691
+ * LM Studio's default local server URL `http://localhost:1234/v1`. Wire
2692
+ * shape is OpenAI Chat Completions. LM Studio is no-auth by convention
2693
+ * (CD-03): `apiKey` is OPTIONAL; when omitted, the underlying factory
2694
+ * sends no `Authorization` header (see
2695
+ * `lattice/packages/lattice/src/providers/adapters.ts:53` for the
2696
+ * conditional auth-header wiring).
2697
+ *
2698
+ * Phase 34 additions:
2699
+ * - `modelsCacheTtlMs` -- Reserved for future /models discovery; LM Studio
2700
+ * currently has no remote /models endpoint. Accepted for option-bag
2701
+ * uniformity but NOT USED (D-04 intentional no-endpoint pattern).
2702
+ * - `runEventSink` -- Accepted for option-bag uniformity but NEVER fired
2703
+ * because source: "registry" is the documented happy path for LM Studio
2704
+ * (no event for intentional no-endpoint per RESEARCH Open Question 5).
2705
+ *
2706
+ * STREAMING (Phase 44): supported through the OpenAI-compatible stream path.
2707
+ *
2708
+ * DEFERRED (D-16 carryforward):
2709
+ * - latency-tail diagnostics -- observability concern; LM Studio is
2710
+ * the canary for latency tails (INV-03);
2711
+ * diagnostics module deferred to a
2712
+ * follow-on observability phase.
2713
+ * - resume-from-eviction -- see Phase 5 (MV3-survivability adapter).
2714
+ *
2715
+ * Ref: FSB v0.10.0-attempt-2 Phase 4 (D-03: thin wrapper; D-16: latency-tail deferred; CD-03 no-opt-out).
1797
2716
  */
1798
- interface AgentHost {
1799
- readonly kind: "agent-host";
1800
- readonly scheduler?: AgentScheduler;
1801
- readonly transport?: AgentTransport;
1802
- readonly storage?: AgentStorage;
2717
+ interface LmStudioProviderOptions extends Omit<OpenAICompatibleProviderOptions, "id" | "baseUrl" | "apiKey"> {
2718
+ readonly id?: string;
2719
+ /** Defaults to `http://localhost:1234/v1`. Override for non-localhost deployments. */
2720
+ readonly baseUrl?: string;
2721
+ /**
2722
+ * Optional. LM Studio is no-auth by convention (CD-03 default).
2723
+ * When provided, sent as `Authorization: Bearer <apiKey>` (matches the
2724
+ * underlying OpenAI-compat factory). Use only for proxied LM Studio
2725
+ * deployments that have a token gate in front.
2726
+ */
2727
+ readonly apiKey?: string;
1803
2728
  }
1804
2729
  /**
1805
- * Reference implementation suitable for Node tests + the Phase 19 default
1806
- * behavior.
2730
+ * Phase 34 D-04 / QUIRK-02 LM Studio provider factory.
1807
2731
  *
1808
- * - scheduler: resolves immediately (no yield between iterations).
1809
- * - transport: pass-through to provider.execute().
1810
- * - storage: save() / clear() are no-ops; load() always returns null.
2732
+ * LM Studio is the prototypical "intentional no remote /models endpoint"
2733
+ * adapter per D-04 (alongside OpenAI-compat). The factory returns conservative
2734
+ * defaults for the quirks block because LM Studio runs LOCAL quantized models
2735
+ * whose capabilities vary wildly by chat template + model file.
1811
2736
  *
1812
- * Equivalent to passing no host at all.
2737
+ * The `negotiateCapabilities` method performs NO fetch; it returns
2738
+ * `synthesizeNegotiatedCapabilitiesFromRegistry` with source: "registry"
2739
+ * (the intentional-no-endpoint signal, distinct from "registry-fallback"
2740
+ * which signals a transient failure). Mirrors Plan 34-03 Task 2 (OpenAI-compat
2741
+ * registry-only pattern) verbatim.
2742
+ *
2743
+ * D-04 citation: "consumer adapters without a /models endpoint skip the
2744
+ * fetch layer entirely and delegate to synthesizeNegotiatedCapabilitiesFromRegistry."
2745
+ *
2746
+ * Open Question 5 (RESEARCH §): no event emitted for source: "registry" because
2747
+ * this is the intentional happy path for LM Studio -- emitting a "fallback" event
2748
+ * would produce false-positive noise for consumers monitoring the event stream.
1813
2749
  */
1814
- declare function createNoopAgentHost(): AgentHost;
2750
+ declare function createLmStudioProvider(options: LmStudioProviderOptions): ProviderAdapter & {
2751
+ readonly quirks: LmStudioQuirks;
2752
+ readonly negotiateCapabilities: (modelId: string) => Promise<NegotiatedCapabilities>;
2753
+ };
1815
2754
  //#endregion
1816
- //#region src/agent/types.d.ts
2755
+ //#region src/providers/openrouter.d.ts
1817
2756
  /**
1818
- * Per-iteration record stored on `AgentSuccess.iterations` for inspectability.
2757
+ * Options for {@link createOpenRouterProvider}.
1819
2758
  *
1820
- * `toolCalls` carries content-addressed args/result hashes (sha256) so
1821
- * downstream receipts can reference them without inlining the bodies.
2759
+ * Thin wrapper around {@link createOpenAICompatibleProvider} pinned to
2760
+ * OpenRouter's base URL `https://openrouter.ai/api/v1`. Wire shape is
2761
+ * OpenAI Chat Completions; no provider-specific quirks at the
2762
+ * single-shot Promise contract level.
1822
2763
  *
1823
- * `deniedReason` is populated on iterations whose `BEFORE_AGENT_ITERATION`
1824
- * SAFETY-band handler set `controls.deny(...)`.
1825
- */
1826
- interface IterationRecord {
1827
- readonly index: number;
1828
- readonly provider: string;
1829
- readonly promptTokens: number;
1830
- readonly completionTokens: number;
1831
- readonly costUsd: number | null;
1832
- readonly durationMs: number;
1833
- readonly toolCalls: ReadonlyArray<{
1834
- readonly id: string;
1835
- readonly name: string;
1836
- readonly argsHash: string;
1837
- readonly resultHash: string;
1838
- }>;
1839
- readonly deniedReason?: string;
1840
- readonly receipt?: ReceiptEnvelope;
1841
- }
1842
- /**
1843
- * Input shape accepted by `ai.runAgent(intent)`.
2764
+ * SECURITY: `apiKey` is a runtime parameter -- do NOT hardcode or log it.
1844
2765
  *
1845
- * All fields except `task` and `tools` are optional. The runtime supplies
1846
- * sensible defaults (in-process host, fresh pipeline, no signer, no tracer).
2766
+ * STREAMING (Phase 44): supported through the OpenAI-compatible stream path.
1847
2767
  *
1848
- * `TOutputs` parameterizes the final-answer schema map; defaults to a free-form
1849
- * `{ answer: "text" }` shape when the field is omitted. Validation runs once
1850
- * against the final assistant message (no intermediate iteration validation).
2768
+ * DEFERRED (D-17 carryforward; Phase 4 ships the named adapter as a
2769
+ * first-class OpenAI-compat wrapper):
2770
+ * - per-message routing -- deferred.
2771
+ * - resume-from-eviction -- see Phase 5 (MV3-survivability adapter).
2772
+ *
2773
+ * Ref: FSB v0.10.0-attempt-2 Phase 4 (D-03: thin wrapper; D-17: model-routing deferred).
1851
2774
  */
1852
- interface AgentIntent<TOutputs extends OutputContractMap = OutputContractMap> {
1853
- readonly task: string;
1854
- readonly tools: ReadonlyArray<ToolDefinition<StandardSchemaV1>>;
1855
- readonly host?: AgentHost;
2775
+ interface OpenRouterProviderOptions extends Omit<OpenAICompatibleProviderOptions, "id" | "baseUrl"> {
2776
+ readonly id?: string;
2777
+ /** Defaults to `https://openrouter.ai/api/v1`. Override for proxies. */
2778
+ readonly baseUrl?: string;
1856
2779
  /**
1857
- * Phase 20 (v1.2): when the agent loop resumes from a host.storage snapshot,
1858
- * the configured SurvivabilityAdapter handles the serialize/deserialize
1859
- * round-trip. When absent, runtime defaults to
1860
- * `createNoopSurvivabilityAdapter<AgentSnapshot>()`.
2780
+ * D-08: TTL for per-instance /models response cache, in milliseconds.
2781
+ * Default: 300_000ms (5 minutes). 0 = always refetch (tests). Infinity = process-lifetime.
1861
2782
  */
1862
- readonly survivabilityAdapter?: SurvivabilityAdapter<AgentSnapshot>;
1863
- readonly contract?: CapabilityContract;
1864
- readonly policy?: PolicySpec;
1865
- readonly outputs?: TOutputs;
1866
- readonly pipeline?: HookPipeline;
1867
- readonly signer?: ReceiptSigner;
1868
- readonly tracer?: TracerLike;
2783
+ readonly modelsCacheTtlMs?: number;
1869
2784
  /**
1870
- * When `false`, the runtime will NOT auto-register `createCheckpointHook`
1871
- * even if `signer` is provided. Callers who want full manual control over
1872
- * receipt minting set this to `false` and register their own hook.
1873
- * Defaults to `true` (auto-register when signer present).
2785
+ * D-11: Number of retries on transient /models fetch errors. Default: 2.
2786
+ * Retry schedule: immediate + 200ms + 1000ms (3 total attempts at retryCount=2).
2787
+ * 0 = no retries (1 attempt total).
1874
2788
  */
1875
- readonly autoRegisterCheckpoint?: boolean;
1876
- }
2789
+ readonly modelsRetryCount?: number;
2790
+ /**
2791
+ * D-12: Optional event sink for observability. When provided, the adapter
2792
+ * emits a "capabilities.negotiation.fallback" RunEvent on transient /models failure.
2793
+ * If absent, no event is emitted (silent fallback).
2794
+ */
2795
+ readonly runEventSink?: RunEventSink;
2796
+ /**
2797
+ * Ordered OpenRouter model fallback candidates. The primary `model` remains
2798
+ * the Lattice-selected route; these candidates serialize as OpenRouter's
2799
+ * top-level `models` request field when non-empty.
2800
+ */
2801
+ readonly fallbackModels?: readonly string[];
2802
+ }
2803
+ /**
2804
+ * Phase 34 — D-03 / D-05..D-12 — Extended OpenRouter provider factory.
2805
+ *
2806
+ * Returns a `ProviderAdapter` narrowed to expose:
2807
+ * - `quirks: OpenRouterQuirks` — static adapter capability flags (8 booleans)
2808
+ * - `negotiateCapabilities(modelId)` — live /api/v1/models fetch with rich /models
2809
+ * intersection (supported_parameters -> nativeToolCalling + structuredOutputs,
2810
+ * top_provider.context_length -> contextWindow) intersected with Phase 33 registry
2811
+ * for knownFailureModes + recommendedSanitizers.
2812
+ *
2813
+ * CRITICAL for ANCHOR CASE STUDY (session_1780792387779):
2814
+ * negotiate("openai/gpt-oss-120b:free") MUST resolve to:
2815
+ * - result.knownFailureModes.includes("internal_envelope_leak") -> TRUE
2816
+ * - result.recommendedSanitizers.includes("unwrapInternalEnvelope") -> TRUE
2817
+ * - result.source === "live" -> TRUE
2818
+ * This proves: live-fetch -> id suffix-strip via stripOpenRouterVariant
2819
+ * -> registry intersection -> getRecommendedSanitizers derivation.
2820
+ *
2821
+ * Anti-pattern (RESEARCH §Anti-pattern, lines 534-535):
2822
+ * The /api/v1/models endpoint is UNAUTHENTICATED (public discovery surface verified
2823
+ * Phase 33). Do NOT send Authorization Bearer to this endpoint -- it is NOT required
2824
+ * and would add unnecessary API key exposure surface in transit logs.
2825
+ */
2826
+ declare function createOpenRouterProvider(options: OpenRouterProviderOptions): ProviderAdapter & {
2827
+ readonly quirks: OpenRouterQuirks;
2828
+ readonly negotiateCapabilities: (modelId: string) => Promise<NegotiatedCapabilities>;
2829
+ };
2830
+ //#endregion
2831
+ //#region src/providers/xai.d.ts
1877
2832
  /**
1878
- * Success result returned by `ai.runAgent` when the loop reaches a final
1879
- * answer and (when `outputs` is declared) the final answer validates.
2833
+ * Options for {@link createXaiProvider}.
1880
2834
  *
1881
- * `iterations[]` records every iteration that ran — including the one that
1882
- * produced the final answer. `receipt` is the outermost receipt minted at
1883
- * loop close when `signer` is configured (separate from per-iteration
1884
- * receipts on `iterations[i].receipt`).
2835
+ * Thin wrapper around {@link createOpenAICompatibleProvider} pinned to
2836
+ * xAI's base URL `https://api.x.ai/v1`. The wire shape is identical to
2837
+ * OpenAI Chat Completions, with one provider-specific quirk preserved:
2838
+ * `response.usage.completion_tokens_details.reasoning_tokens` (xAI's
2839
+ * separate reasoning-token accounting; see FSB
2840
+ * `extension/ai/universal-provider.js:585-594` for the production reference).
2841
+ *
2842
+ * SECURITY: `apiKey` is a runtime parameter -- do NOT hardcode or log it.
2843
+ *
2844
+ * STREAMING (Phase 44): supported through the OpenAI-compatible stream path.
2845
+ *
2846
+ * DEFERRED (Phase 4 carryforward notes):
2847
+ * - tool-streaming -- deferred
2848
+ * - resume-from-eviction -- see Phase 5 (MV3-survivability adapter contract)
2849
+ *
2850
+ * Ref: FSB v0.10.0-attempt-2 Phase 4 (D-03 + D-07: thin wrapper; reasoning_tokens quirk preserved).
2851
+ *
2852
+ * Phase 34 additions:
2853
+ * - `modelsCacheTtlMs?` — D-05/D-06/D-08; default 300_000ms; 0 disables; Infinity = process-lifetime
2854
+ * - `modelsRetryCount?` — D-11; default 2; 0 disables retry
2855
+ * - `runEventSink?` — D-12; fires "capabilities.negotiation.fallback" on transient errors
1885
2856
  */
1886
- interface AgentSuccess<TOutputs extends OutputContractMap = OutputContractMap> {
1887
- readonly kind: "success";
1888
- readonly output: InferOutputMap<TOutputs>;
1889
- readonly usage: Usage;
1890
- readonly iterations: ReadonlyArray<IterationRecord>;
1891
- readonly receipt?: ReceiptEnvelope;
2857
+ interface XaiProviderOptions extends Omit<OpenAICompatibleProviderOptions, "id" | "baseUrl"> {
2858
+ readonly id?: string;
2859
+ /** Defaults to `https://api.x.ai/v1`. Override for proxies. */
2860
+ readonly baseUrl?: string;
1892
2861
  }
1893
2862
  /**
1894
- * Failure kinds specific to the agent loop. v1.1 `LatticeRunError.kind`
1895
- * values remain valid (provider errors, no-contract-match, validation-failed,
1896
- * tripwire-violated) and are reused verbatim. Phase 19 adds three
1897
- * agent-specific kinds.
1898
- */
1899
- type AgentFailureKind = LatticeRunError["kind"] | "agent-iteration-denied" | "agent-max-iterations" | "agent-wall-time-exceeded";
1900
- /**
1901
- * Failure result returned by `ai.runAgent`. Discriminates via `kind`.
2863
+ * Phase 34 QUIRK-02 / NEG-01 / NEG-02 — xAI provider factory.
1902
2864
  *
1903
- * `iterations[]` carries any iterations that completed before the failure
1904
- * (empty if the failure occurred pre-iteration). For `agent-iteration-denied`,
1905
- * the failing iteration is the LAST entry and carries `deniedReason`.
2865
+ * Extends the base OpenAI-compat execution wrapper with:
2866
+ * 1. `quirks: XaiQuirks` verified per RESEARCH §Q6 xAI vocabulary.
2867
+ * 2. `negotiateCapabilities(modelId)` queries xAI /v1/models GET with
2868
+ * Authorization: Bearer header; LENIENT-PARSE sparse OpenAI-shaped
2869
+ * response; intersects with Phase 33 registry for supports.*.
2870
+ *
2871
+ * CITED: RESEARCH §Q4 (INFERRED) — xAI /v1/models shape is undocumented;
2872
+ * assumed OpenAI-compatible based on the chat completions wire format.
2873
+ *
2874
+ * CITED: RESEARCH §A1 — Pitfall 1 lenient parse: if xAI publishes a
2875
+ * different /models shape, only the parsing logic updates; the contract
2876
+ * (source values, NegotiatedCapabilities shape) holds.
2877
+ *
2878
+ * The negotiate() pattern mirrors Plan 34-02 (Anthropic thick reference):
2879
+ * - Per-instance TTL cache (modelsCacheTtlMs, default 300_000ms)
2880
+ * - Single-flight inflight coalescing with .finally cleanup (Pitfall 4)
2881
+ * - Retry with [0, 200, 1000]ms backoff (modelsRetryCount, default 2)
2882
+ * - 401/403 throws NegotiationAuthError with adapter: "xai" (D-10)
2883
+ * - 5xx/network/timeout falls back to registry + emits fallback event
2884
+ *
2885
+ * SECURITY (T-34-03-07): inflight Map MUST use .finally cleanup to prevent
2886
+ * leak on rejection. Verifiable: grep `.finally` in this file.
1906
2887
  */
1907
- interface AgentFailure {
1908
- readonly kind: AgentFailureKind;
2888
+ declare function createXaiProvider(options: XaiProviderOptions): ProviderAdapter & {
2889
+ readonly quirks: XaiQuirks;
2890
+ readonly negotiateCapabilities: (modelId: string) => Promise<NegotiatedCapabilities>;
2891
+ };
2892
+ //#endregion
2893
+ //#region src/providers/streaming.d.ts
2894
+ interface CollectStreamOptions {
2895
+ readonly defaultOutput?: string;
2896
+ }
2897
+ declare function collectStream(stream: ProviderStream, options?: CollectStreamOptions): Promise<ProviderRunResponse>;
2898
+ //#endregion
2899
+ //#region src/results/result.d.ts
2900
+ interface RunSuccess<TOutputs extends OutputContractMap> {
2901
+ readonly ok: true;
2902
+ readonly outputs: InferOutputMap<TOutputs>;
2903
+ readonly artifacts: readonly ArtifactRef[];
1909
2904
  readonly usage: Usage;
1910
- readonly iterations: ReadonlyArray<IterationRecord>;
1911
- readonly reason?: string;
1912
- readonly cause?: unknown;
2905
+ readonly plan: ResultPlan;
2906
+ readonly events?: readonly RunEvent[];
2907
+ readonly gateway?: ProviderGatewayMetadata;
2908
+ /**
2909
+ * Phase 9 — signed capability receipt issued when `LatticeConfig.signer`
2910
+ * is configured. Undefined when no signer is set.
2911
+ */
1913
2912
  readonly receipt?: ReceiptEnvelope;
1914
2913
  }
1915
- /**
1916
- * Discriminated union returned by `ai.runAgent`.
1917
- */
1918
- type AgentResult<TOutputs extends OutputContractMap = OutputContractMap> = AgentSuccess<TOutputs> | AgentFailure;
1919
- /**
1920
- * Typed error raised when a SAFETY-band handler sets `controls.deny(reason)`
1921
- * during `BEFORE_AGENT_ITERATION`. Carries `terminal: true` semantics to
1922
- * align with v1.1 `TripwireViolationError`: the failure is NOT retried by
1923
- * the fallback chain.
1924
- *
1925
- * Surfaced via `AgentFailure { kind: "agent-iteration-denied", reason, ... }`
1926
- * callers can also catch the typed error if they prefer.
1927
- */
1928
- declare class AgentDeniedError extends Error {
1929
- readonly kind: "agent-iteration-denied";
1930
- readonly terminal: true;
1931
- readonly reason: string;
1932
- readonly iterationIndex: number;
1933
- constructor(reason: string, iterationIndex: number);
1934
- }
1935
- /**
1936
- * Returned by `formatToolsForProvider` (Phase 19 Plan 19-03). Re-exported
1937
- * here for convenience; the canonical declaration lives in format-tools.ts.
1938
- */
1939
- interface ToolUseRequest {
1940
- readonly id: string;
1941
- readonly name: string;
1942
- readonly args: unknown;
2914
+ interface RunFailure {
2915
+ readonly ok: false;
2916
+ readonly error: LatticeRunError;
2917
+ readonly usage: Usage;
2918
+ readonly raw?: unknown;
2919
+ readonly partialOutputs?: Record<string, unknown>;
2920
+ readonly plan: ResultPlan;
2921
+ readonly events?: readonly RunEvent[];
2922
+ readonly gateway?: ProviderGatewayMetadata;
2923
+ /**
2924
+ * Phase 9 signed capability receipt issued when `LatticeConfig.signer`
2925
+ * is configured. Undefined when no signer is set.
2926
+ */
2927
+ readonly receipt?: ReceiptEnvelope;
1943
2928
  }
2929
+ type RunResult<TOutputs extends OutputContractMap> = RunSuccess<TOutputs> | RunFailure;
1944
2930
  //#endregion
1945
2931
  //#region src/storage/storage.d.ts
1946
2932
  interface ArtifactStore {
@@ -1994,6 +2980,88 @@ interface NormalizedLatticeConfig {
1994
2980
  readonly signer?: ReceiptSigner;
1995
2981
  }
1996
2982
  //#endregion
2983
+ //#region src/agent/crew/agent-spec.d.ts
2984
+ /**
2985
+ * Crew member specification. A literal sibling of `ToolDefinition`
2986
+ * discriminated by `kind: "agent"` (D-03).
2987
+ */
2988
+ interface AgentSpec {
2989
+ readonly kind: "agent";
2990
+ readonly id: string;
2991
+ readonly intent: string;
2992
+ readonly tools: ReadonlyArray<ToolDefinition<StandardSchemaV1>>;
2993
+ readonly childAgents?: ReadonlyArray<AgentSpec>;
2994
+ readonly summaryReturnSchema: StandardSchemaV1;
2995
+ /** Optional per-agent sub-budget (D-07). */
2996
+ readonly contract?: CapabilityContract;
2997
+ }
2998
+ /**
2999
+ * Factory for `AgentSpec` values. Mirrors `defineTool` exactly: spread
3000
+ * preserves input identity (no cloning, no mutation) and absent optional
3001
+ * members stay absent (`exactOptionalPropertyTypes`-safe).
3002
+ */
3003
+ declare function defineAgent(definition: Omit<AgentSpec, "kind">): AgentSpec;
3004
+ //#endregion
3005
+ //#region src/agent/crew/crew-policy.d.ts
3006
+ /** Per-adapter rate-limit override (keyed by `adapter.id` in `limits`). */
3007
+ interface CrewRateLimitOverride {
3008
+ readonly requestsPerMinute?: number;
3009
+ readonly tokensPerMinute?: number;
3010
+ }
3011
+ /** Crew-level policy contract (D-06, D-11, D-16). */
3012
+ interface CrewPolicy {
3013
+ /** Crew-level shared budget pool — `BudgetInvariant` reused verbatim. */
3014
+ readonly budget?: BudgetInvariant;
3015
+ readonly maxTotalIterations?: number;
3016
+ readonly maxIterationsPerAgent?: number;
3017
+ /** Forward-compat field; the v1.3 runtime rejects values > 1 (D-11). */
3018
+ readonly maxConcurrentChildren?: number;
3019
+ /** Delegation depth cap; defaults to 1 (parent→child only, D-05). */
3020
+ readonly maxDepth?: number;
3021
+ /** Per-adapter-id rate-limit overrides (D-16). */
3022
+ readonly limits?: Readonly<Record<string, CrewRateLimitOverride>>;
3023
+ /** "managed" (default) wraps transports in the rate-limit group; "unmanaged" skips it. */
3024
+ readonly coordination?: "managed" | "unmanaged";
3025
+ }
3026
+ //#endregion
3027
+ //#region src/agent/crew/run-crew.d.ts
3028
+ interface RunAgentCrewOptions {
3029
+ readonly root: AgentSpec;
3030
+ readonly hosts: {
3031
+ readonly childHost: AgentHost;
3032
+ };
3033
+ readonly policy?: CrewPolicy;
3034
+ /** Crew-level signer threaded into member loops and completion receipts. */
3035
+ readonly signer?: ReceiptSigner;
3036
+ /** Crew-level tracer threaded into member loops. */
3037
+ readonly tracer?: TracerLike;
3038
+ /** Crew-level hook pipeline threaded into member loops. */
3039
+ readonly pipeline?: HookPipeline;
3040
+ }
3041
+ interface CrewAgentResult {
3042
+ readonly id: string;
3043
+ readonly usage: Usage;
3044
+ readonly iterations: number;
3045
+ readonly receiptCids: readonly string[];
3046
+ }
3047
+ interface CrewResult {
3048
+ /** Parent result, with parent output untouched on success. */
3049
+ readonly result: AgentResult;
3050
+ /** Per-agent accounting records, including root parent and completed children. */
3051
+ readonly perAgent: ReadonlyArray<CrewAgentResult>;
3052
+ /** Crew aggregate usage: parent total + sum(child totals), no double-counting. */
3053
+ readonly usage: Usage;
3054
+ /** Total iterations across every recorded agent. */
3055
+ readonly totalIterations: number;
3056
+ /** All crew completion receipts, including the crew-root envelope. */
3057
+ readonly receipts: ReadonlyArray<ReceiptEnvelope>;
3058
+ readonly crewRootCid?: string;
3059
+ }
3060
+ /**
3061
+ * Execute a crew rooted at `options.root`.
3062
+ */
3063
+ declare function runAgentCrew(options: RunAgentCrewOptions, config?: LatticeConfig): Promise<CrewResult>;
3064
+ //#endregion
1997
3065
  //#region src/runtime/create-ai.d.ts
1998
3066
  interface RuntimeOverrides {
1999
3067
  readonly provider?: string;
@@ -2041,12 +3109,21 @@ interface AI {
2041
3109
  * Phase 19 (v1.2): single-agent execution loop. Drives multiple provider
2042
3110
  * iterations under one call, dispatching tool requests between iterations.
2043
3111
  * Composes with the v1.2 hook pipeline (SAFETY-band veto, OBSERVABILITY-band
2044
- * checkpoint receipts) and the v1.1 capability receipts (when
3112
+ * checkpoint receipts) and the v1.2 capability receipts (when
2045
3113
  * `intent.signer` is provided + `intent.autoRegisterCheckpoint !== false`).
2046
3114
  *
2047
3115
  * See `packages/lattice/src/agent/runtime.ts` for orchestration details.
2048
3116
  */
2049
3117
  runAgent<const TOutputs extends OutputContractMap>(intent: AgentIntent<TOutputs>): Promise<AgentResult<TOutputs>>;
3118
+ /**
3119
+ * Phase 39 (v1.3): opt-in multi-agent crew execution. Runs a literal
3120
+ * `AgentSpec` tree through the existing single-agent loop plus the crew
3121
+ * dispatcher, with shared budget/rate-limit coordination and chained
3122
+ * completion receipts.
3123
+ *
3124
+ * See `packages/lattice/src/agent/crew/run-crew.ts` for orchestration details.
3125
+ */
3126
+ runAgentCrew(options: RunAgentCrewOptions): Promise<CrewResult>;
2050
3127
  }
2051
3128
  declare function createAI(config?: LatticeConfig): AI;
2052
3129
  //#endregion
@@ -2138,6 +3215,10 @@ declare function materializeReplayEnvelope<TOutputs extends OutputContractMap =
2138
3215
  * calling Promise), direct transport (provider.execute()), and in-memory
2139
3216
  * transcript (the `conversation` array). Phase 20 promotes scheduler /
2140
3217
  * transport / storage to the pluggable `AgentHost` adapter.
3218
+ *
3219
+ * Phase 39: `runAgent` is a thin public wrapper over `runAgentInternal`
3220
+ * with no internal options — the public signature and behavior are
3221
+ * unchanged.
2141
3222
  */
2142
3223
  declare function runAgent<TOutputs extends OutputContractMap = OutputContractMap>(intent: AgentIntent<TOutputs>, config?: LatticeConfig): Promise<AgentResult<TOutputs>>;
2143
3224
  //#endregion
@@ -2299,6 +3380,131 @@ declare function createPermissionGuardHook(context: PermissionContext): HookHand
2299
3380
  */
2300
3381
  declare function permissionGuardRegisterOptions(): RegisterOptions;
2301
3382
  //#endregion
3383
+ //#region src/agent/infra/rate-limit-group.d.ts
3384
+ interface RateLimitGroupOptions {
3385
+ /** Requests per minute. Defaults to 50 (Anthropic Tier 1). */
3386
+ readonly requestsPerMinute?: number;
3387
+ /** Input tokens per minute. Defaults to 30_000 (Anthropic Tier 1). */
3388
+ readonly tokensPerMinute?: number;
3389
+ /** Injectable clock for tests (defaults to `Date.now`). */
3390
+ readonly now?: () => number;
3391
+ }
3392
+ interface RateLimitLease {
3393
+ /**
3394
+ * Reconcile the reservation against actual usage. Refunds
3395
+ * `estimate - actual.promptTokens` to the token bucket when positive,
3396
+ * debits the difference when negative. Idempotent — only the first call
3397
+ * has an effect. Requests are never refunded.
3398
+ */
3399
+ release(actual: {
3400
+ promptTokens: number;
3401
+ }): void;
3402
+ }
3403
+ interface RateLimitGroup {
3404
+ readonly kind: "rate-limit-group";
3405
+ /**
3406
+ * Reserve 1 request + `estimate.inputTokens` tokens. Resolves immediately
3407
+ * when both dimensions have capacity; otherwise the caller waits (FIFO)
3408
+ * until continuous drain refills the deficit.
3409
+ */
3410
+ acquire(estimate: {
3411
+ inputTokens: number;
3412
+ }): Promise<RateLimitLease>;
3413
+ }
3414
+ declare function createRateLimitGroup(options?: RateLimitGroupOptions): RateLimitGroup;
3415
+ /**
3416
+ * Wrap an `AgentTransport` so every provider call is gated through `group`.
3417
+ *
3418
+ * Every transport wrapped with the SAME group instance shares one bucket —
3419
+ * `runAgentCrew` (39-06) wraps parent + child hosts with one shared group per
3420
+ * adapter instance, structurally guaranteeing crew-wide coordination (D-13).
3421
+ * `ProviderAdapter` is never modified (INV-03 parity invariant intact).
3422
+ *
3423
+ * - `inner` provided → dispatch nests through `inner.call(provider, request)`,
3424
+ * composing with consumer transports (e.g. cross-process bridges).
3425
+ * - `inner` undefined → falls through to `provider.execute(request)`, guarded
3426
+ * the same way as `createNoopAgentHost` (error names the provider id only).
3427
+ *
3428
+ * Release policy:
3429
+ * - Success → release with `normalizedUsage.promptTokens`; when usage is
3430
+ * missing or non-finite, fall back to the estimate (no NaN arithmetic —
3431
+ * the `costUsd: null` "unmeasured" discipline analog).
3432
+ * - Throw → release with the ORIGINAL estimate (burn — no refund; the
3433
+ * provider may have consumed quota despite the error) and rethrow the
3434
+ * same error unchanged. Request objects and headers are never serialized
3435
+ * into error paths.
3436
+ */
3437
+ declare function withRateLimit(group: RateLimitGroup, inner?: AgentTransport): AgentTransport;
3438
+ //#endregion
3439
+ //#region src/receipts/cid.d.ts
3440
+ /**
3441
+ * Derive the content-addressed CID of a receipt envelope.
3442
+ *
3443
+ * Returns `sha256:<hex>` where `<hex>` is the 64-char lowercase SHA-256
3444
+ * digest of the decoded DSSE payload bytes. No KeySet, signer, or other
3445
+ * key material is required — callers chaining receipts (parentReceiptCid)
3446
+ * compute this from the parent envelope alone.
3447
+ */
3448
+ declare function receiptCid(envelope: ReceiptEnvelope): Promise<string>;
3449
+ //#endregion
3450
+ //#region src/realtime/realtime.d.ts
3451
+ declare const REALTIME_DIRECTION_SUPPORT_LEVEL: "direction-only";
3452
+ type RealtimeSupportLevel = typeof REALTIME_DIRECTION_SUPPORT_LEVEL;
3453
+ type RealtimeProviderKind = "openai-realtime" | "gemini-live";
3454
+ type RealtimeTransportKind = "websocket" | "webrtc" | "sip";
3455
+ type RealtimeSessionMode = "voice-agent" | "transcription" | "translation" | "live-multimodal";
3456
+ type RealtimeInputModality = "text" | "audio" | "image" | "video";
3457
+ type RealtimeOutputModality = "text" | "audio" | "tool";
3458
+ type RealtimeCheckpointKind = "session.start" | "client.frame" | "server.frame" | "session.summary" | "session.close";
3459
+ interface OpenAIRealtimeTarget {
3460
+ readonly provider: "openai-realtime";
3461
+ readonly model: string;
3462
+ readonly transport: RealtimeTransportKind;
3463
+ readonly endpoint: "/v1/realtime" | "/v1/realtime/translations" | "/v1/realtime/transcription_sessions";
3464
+ }
3465
+ interface GeminiLiveTarget {
3466
+ readonly provider: "gemini-live";
3467
+ readonly model: string;
3468
+ readonly transport: "websocket";
3469
+ readonly endpoint: "wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent";
3470
+ readonly preview: true;
3471
+ }
3472
+ type RealtimeProviderTarget = OpenAIRealtimeTarget | GeminiLiveTarget;
3473
+ interface RealtimeSessionSpec {
3474
+ readonly kind: "realtime-session-spec";
3475
+ readonly supportLevel: RealtimeSupportLevel;
3476
+ readonly sessionId: string;
3477
+ readonly target: RealtimeProviderTarget;
3478
+ readonly mode: RealtimeSessionMode;
3479
+ readonly inputModalities: readonly RealtimeInputModality[];
3480
+ readonly outputModalities: readonly RealtimeOutputModality[];
3481
+ readonly artifactRefs?: readonly ArtifactRef[];
3482
+ readonly policy?: PolicySpec;
3483
+ readonly checkpointing?: RealtimeCheckpointingSpec;
3484
+ }
3485
+ interface RealtimeCheckpointingSpec {
3486
+ readonly receiptThreading: "step-linked-list";
3487
+ readonly summaryCheckpoints: "manual" | "session-close" | "interval";
3488
+ readonly note: "direction-only";
3489
+ }
3490
+ interface RealtimeCheckpointInput {
3491
+ readonly sessionId: string;
3492
+ readonly provider: RealtimeProviderKind;
3493
+ readonly checkpoint: RealtimeCheckpointKind;
3494
+ readonly stepIndex: number;
3495
+ readonly timestamp?: string;
3496
+ readonly parentStepName?: string;
3497
+ readonly previousStepName?: string;
3498
+ }
3499
+ interface RealtimeReceiptDescriptors {
3500
+ readonly sessionId: string;
3501
+ readonly model: ReceiptModel;
3502
+ readonly route: ReceiptRoute;
3503
+ }
3504
+ declare function createRealtimeCheckpointContext(input: RealtimeCheckpointInput): CheckpointHookContext;
3505
+ declare function createRealtimeReceiptDescriptors(spec: RealtimeSessionSpec): RealtimeReceiptDescriptors;
3506
+ declare function realtimeStepName(provider: RealtimeProviderKind, checkpoint: RealtimeCheckpointKind): string;
3507
+ //#endregion
2302
3508
  //#region src/agent/eval.d.ts
2303
3509
  /**
2304
3510
  * Summary of an agent run sufficient for regression analysis. Callers
@@ -2353,7 +3559,62 @@ interface MemoryArtifactStoreOptions {
2353
3559
  declare function createMemoryArtifactStore(options?: MemoryArtifactStoreOptions): ArtifactStore;
2354
3560
  //#endregion
2355
3561
  //#region src/version.d.ts
2356
- declare const latticeVersion = "0.0.0";
3562
+ declare const latticeVersion = "1.4.0";
3563
+ //#endregion
3564
+ //#region src/capabilities/lookup.d.ts
3565
+ /**
3566
+ * Strip the OpenRouter variant suffix (`:free` or `:thinking`) from an
3567
+ * OpenRouter-shaped id (`vendor/model:variant`). Other adapter id shapes
3568
+ * pass through verbatim — does not, for example, alter
3569
+ * `anthropic:claude-opus-4` (direct-adapter canonical key) or
3570
+ * `openai/gpt-4o:beta` (unrecognized variant per Pitfall 4).
3571
+ *
3572
+ * Exported because Phase 34 (adapter quirks) and Phase 36 (output
3573
+ * sanitizers) need the same normalization. Phase 33 D-11 scope.
3574
+ */
3575
+ declare function stripOpenRouterVariant(id: string): string;
3576
+ /**
3577
+ * D-09 strict lookup — return the capability profile for the exact
3578
+ * `${adapter}:${modelId}` canonical key. Returns `undefined` if the key
3579
+ * is not registered. No fuzzy matching — use `findCapabilityProfile`
3580
+ * for that.
3581
+ *
3582
+ * Examples:
3583
+ * getCapabilityProfile("openrouter:openai/gpt-oss-120b") -> profile
3584
+ * getCapabilityProfile("anthropic:claude-opus-4") -> profile
3585
+ * getCapabilityProfile("not-a-real-key") -> undefined
3586
+ *
3587
+ * The lookup is case-sensitive on the canonical key. Threat T-33-02-01
3588
+ * mitigation: backing store is `Map<string, ModelCapabilityProfile>`,
3589
+ * not a plain object literal, so `__proto__` and other prototype-chain
3590
+ * keys are safe (Map uses SameValueZero, not property lookup).
3591
+ */
3592
+ declare function getCapabilityProfile(canonicalKey: string): ModelCapabilityProfile | undefined;
3593
+ /**
3594
+ * D-10 fuzzy lookup — strip the OpenRouter variant suffix (if any) and
3595
+ * return ALL matching profiles across every adapter, in deterministic
3596
+ * order: direct adapters first (anthropic, openai, gemini, xai,
3597
+ * openai-compat, lm-studio), then OpenRouter.
3598
+ *
3599
+ * Useful for pre-routing capability inspection where the adapter has
3600
+ * not yet been chosen — the consumer can iterate the returned list
3601
+ * and pick the first compatible one. Returns `[]` when no match is
3602
+ * found across any adapter.
3603
+ *
3604
+ * Suffix-strip is OpenRouter-shape-only per D-11. Direct-adapter ids
3605
+ * pass through verbatim:
3606
+ * findCapabilityProfile("openai/gpt-oss-120b:free")
3607
+ * -> [openrouter:openai/gpt-oss-120b]
3608
+ * findCapabilityProfile("claude-opus-4")
3609
+ * -> [anthropic:claude-opus-4, ...] (no suffix-strip)
3610
+ */
3611
+ declare function findCapabilityProfile(id: string): ModelCapabilityProfile[];
3612
+ //#endregion
3613
+ //#region src/prompts/scaffolds.d.ts
3614
+ declare const PROMPT_SCAFFOLD_VERSION: "lattice.prompt-scaffold/v1";
3615
+ declare const PROMPT_STRATEGIES: readonly ["frontier", "mid_tier", "open_weight", "reasoning", "local"];
3616
+ declare function getStructuredOutputContract(strategy: RecommendedPromptStrategy, schema: unknown): string;
3617
+ declare function getToolUseContract(strategy: RecommendedPromptStrategy, tools: unknown): string;
2357
3618
  //#endregion
2358
- export { type AI, type ActionHistory, type ActionHistoryOptions, type ActionRecord, AgentDeniedError, type AgentEvalResult, type AgentFailure, type AgentFailureKind, type AgentHost, type AgentIntent, type AgentResult, type AgentRunSnapshot, type AgentScheduler, type AgentSnapshot, type AgentStorage, type AgentSuccess, type AgentTransport, type AnthropicProviderOptions, type ArtifactFingerprint, type ArtifactInput, type ArtifactKind, type ArtifactLineage, type ArtifactOptions, type ArtifactParentRef, type ArtifactPrivacy, type ArtifactRef, type ArtifactSize, type ArtifactSource, type ArtifactStorageRef, type ArtifactStore, type ArtifactTransformDescriptor, type ArtifactTransformKind, BAND, type BudgetInvariant, type CapabilityContract, type CapabilityContractInput, type CapabilityReceiptBody, type CheckpointHookContext, type CheckpointHookOptions, type ContractRejectReasonCode, type ContractVerdict, type ConversationTurn, type CostBudgetStatus, type CostTracker, type CreateReceiptInput, DEFAULT_CHECKPOINT_BAND, type EvalOptions, type EvalRegression, type EvalRegressionKind, type EvictionHook, type ExecutionPlanStub, type FieldFromTableInvariant, type FormatToolsMode, type FormatToolsOptions, type FormattedToolsHandle, type GeminiProviderOptions, type GoalProgressOptions, type GoalProgressStep, type GoalProgressTracker, type HookControls, type HookDenyDirective, type HookLifecycleEvent, type HookPipeline, type InferOutput, type InferOutputMap, type InvariantDeclaration, type InvariantOptions, type IterationRecord, type KeyEntry, type KeySet, type KeyState, type LatticeConfig, type LatticeRunError, type LmStudioProviderOptions, type MatchesInvariant, type MaterializationError, type MaterializeReplayEnvelopeOptions, type MustCiteInvariant, type NoPiiInvariant, type NormalizedLatticeConfig, type OpenRouterProviderOptions, type OutputContract, type OutputContractMap, type PermissionContext, type PermissionDecisionInput, type PermissionHookContext, type PermissionRule, type PermissionVerdict, type PiiDetector, type PiiDetectorResult, type PolicySpec, type ProgressStatus, type ProviderAdapter, type ProviderRef, type ProviderRunRequest, type ProviderRunResponse, type QualityFloorInvariant, type ReceiptEnvelope, type ReceiptModel, type ReceiptRedaction, type ReceiptRoute, type ReceiptSignature, type ReceiptSigner, type ReceiptUsageCanonical, type ReplayEnvelope, type ResumePolicy, type RunFailure, type RunIntent, type RunResult, type RunSuccess, STEP_TRANSITION_EVENT_NAME, STUCK_REASONS, type SerializedSnapshot, type SessionRef, type StorageLike, type StoredArtifactEnvelope, type StoredArtifactPayloadDescriptor, type StuckReason, type SurvivabilityAdapter, type TokenEstimator, type ToolUseRequest, type TracerLike, type TranscriptStore, type TripwireEvidence, type TripwireResult, type TripwireViolationError, type UnsubscribeFn, type Usage, type ValidationIssue, type VerifyError, type VerifyErrorKind, type VerifyFail, type VerifyOk, type VerifyResult, type XaiProviderOptions, artifact, contract, createAI, createAISdkProvider, createActionHistory, createAnthropicProvider, createCheckpointHook, createCostTracker, createFakeProvider, createGeminiProvider, createGoalProgressTracker, createHookPipeline, createInMemorySigner, createLmStudioProvider, createLocalArtifactStore, createMemoryArtifactStore, createMemoryKeySet, createMemorySessionStore, createNoopAgentHost, createNoopSurvivabilityAdapter, createOpenAICompatibleProvider, createOpenAIProvider, createOpenRouterProvider, createPermissionContext, createPermissionGuardHook, createReceipt, createReplayEnvelope, createTranscriptStore, createXaiProvider, defaultPiiDetectors, defineTool, estimateRouteCost, evalAgentRun, evaluateContractAgainstRoute, evaluateTripwires, formatToolsForProvider, generateEd25519KeyPairJwk, importMcpTools, inv, isTerminal, latticeVersion, materializeReplayEnvelope, output, permissionGuardRegisterOptions, redactArtifactRef, redactPlan, redactReplayEnvelope, replayOffline, rerunLive, runAgent, runTool, toolArtifactRef, toolSchemaToJsonSchema, verifyReceipt };
3619
+ export { type AI, ALL_KNOWN_FAILURE_MODES, ALL_TRAINING_CLASSES, type ActionHistory, type ActionHistoryOptions, type ActionRecord, type AdapterQuirks, AgentDeniedError, type AgentEvalResult, type AgentFailure, type AgentFailureKind, type AgentHost, type AgentIntent, type AgentResult, type AgentRunSnapshot, type AgentScheduler, type AgentSnapshot, type AgentSpec, type AgentStorage, type AgentSuccess, type AgentTransport, type AnthropicProviderOptions, type AnthropicQuirks, type ArtifactFingerprint, type ArtifactInput, type ArtifactKind, type ArtifactLineage, type ArtifactOptions, type ArtifactParentRef, type ArtifactPrivacy, type ArtifactRef, type ArtifactSize, type ArtifactSource, type ArtifactStorageRef, type ArtifactStore, type ArtifactTransformDescriptor, type ArtifactTransformKind, BAND, type BudgetInvariant, type CapabilityAdapter, type CapabilityContract, type CapabilityContractInput, type CapabilityReceiptBody, type CheckpointHookContext, type CheckpointHookOptions, type CollectStreamOptions, type ContractRejectReasonCode, type ContractVerdict, type ConversationTurn, type CostBudgetStatus, type CostTracker, type CreateReceiptInput, type CrewAgentResult, type CrewPolicy, type CrewRateLimitOverride, type CrewResult, DEFAULT_CHECKPOINT_BAND, type EvalOptions, type EvalRegression, type EvalRegressionKind, type EvictionHook, type ExecutionPlanStub, type FieldFromTableInvariant, type FormatToolsMode, type FormatToolsOptions, type FormattedToolsHandle, type GatewayMetadataValue, type GatewayPolicy, type GeminiLiveTarget, type GeminiProviderOptions, type GeminiQuirks, type GoalProgressOptions, type GoalProgressStep, type GoalProgressTracker, type HookControls, type HookDenyDirective, type HookLifecycleEvent, type HookPipeline, type InferOutput, type InferOutputMap, type InternalEnvelopeOptions, type InvariantDeclaration, type InvariantOptions, type IterationRecord, type KeyEntry, type KeySet, type KeyState, type KnownFailureMode, type LangfuseOtlpConfigOptions, type LatticeConfig, type LatticeRunError, type LiteLLMProviderOptions, type LiteLLMQuirks, type LmStudioProviderOptions, type LmStudioQuirks, type MatchesInvariant, type MaterializationError, type MaterializeReplayEnvelopeOptions, type ModelCapabilityProfile, type ModelCapabilityProfileModality, type ModelCapabilityProfilePricing, type ModelCapabilityProfilePricingKey, type MustCiteInvariant, type NegotiatedCapabilities, NegotiationAuthError, type NoPiiInvariant, NoPublicUrlEgressError, type NormalizedLatticeConfig, type OpenAICompatQuirks, type OpenAIQuirks, type OpenAIRealtimeTarget, type OpenRouterProviderOptions, type OpenRouterQuirks, type OtelAttributeValue, type OtelAttributes, type OtelContentCaptureMode, type OtelHttpTraceConfig, type OtelRunEventSinkOptions, type OtelSanitizerOptions, type OtelSpanLike, type OtelSpanStatus, type OtelTracerLike, type OutputContract, type OutputContractMap, PROMPT_SCAFFOLD_VERSION, PROMPT_STRATEGIES, type PermissionContext, type PermissionDecisionInput, type PermissionHookContext, type PermissionRule, type PermissionVerdict, type PhoenixOtlpConfigOptions, type PiiDetector, type PiiDetectorResult, type PolicySpec, type ProgressStatus, type ProviderAdapter, type ProviderGatewayMetadata, type ProviderRef, type ProviderRunRequest, type ProviderRunResponse, type ProviderStream, type ProviderStreamChunk, type ProviderStreamCompleteChunk, type ProviderStreamGatewayChunk, type ProviderStreamOutputChunk, type ProviderStreamTextDeltaChunk, type ProviderStreamToolCallChunk, type ProviderStreamUsageChunk, type QualityFloorInvariant, REALTIME_DIRECTION_SUPPORT_LEVEL, type RateLimitGroup, type RateLimitGroupOptions, type RateLimitLease, type RealtimeCheckpointInput, type RealtimeCheckpointKind, type RealtimeCheckpointingSpec, type RealtimeInputModality, type RealtimeOutputModality, type RealtimeProviderKind, type RealtimeProviderTarget, type RealtimeReceiptDescriptors, type RealtimeSessionMode, type RealtimeSessionSpec, type RealtimeSupportLevel, type RealtimeTransportKind, type ReasoningSurface, type ReceiptEnvelope, type ReceiptModel, type ReceiptRedaction, type ReceiptRoute, type ReceiptSignature, type ReceiptSigner, type ReceiptUsageCanonical, type RecommendedPromptStrategy, type RemoteReceiptPayloadFormat, type RemoteReceiptSignRequest, type RemoteReceiptSignResult, type RemoteReceiptSignerOptions, type RemoteReceiptSignerProvider, type ReplayEnvelope, type ResumePolicy, type RunAgentCrewOptions, type RunEvent, type RunEventKind, type RunEventSink, type RunFailure, type RunIntent, type RunResult, type RunSuccess, SANITIZER_BY_FAILURE_MODE, STEP_TRANSITION_EVENT_NAME, STUCK_REASONS, type SanitizeOutputOption, type SanitizerContext, type SanitizerFn, type SanitizerKey, type SerializedSnapshot, type SessionRef, type StorageLike, type StoredArtifactEnvelope, type StoredArtifactPayloadDescriptor, type StuckReason, type SurvivabilityAdapter, type TokenEstimator, type ToolCallSurface, ToolCallValidationError, type ToolCallValidationFailureReason, type ToolUseRequest, type TracerLike, type TrainingClass, type TranscriptStore, type TripwireEvidence, type TripwireResult, type TripwireViolationError, type UnsubscribeFn, type Usage, type ValidateToolCallsOption, type ValidatedToolCall, type ValidationIssue, type VerifyError, type VerifyErrorKind, type VerifyFail, type VerifyOk, type VerifyResult, type XaiProviderOptions, type XaiQuirks, artifact, collectStream, contract, createAI, createAISdkProvider, createActionHistory, createAnthropicProvider, createCheckpointHook, createCostTracker, createFakeProvider, createGeminiProvider, createGoalProgressTracker, createHookPipeline, createInMemorySigner, createLangfuseOtlpConfig, createLiteLLMProvider, createLmStudioProvider, createLocalArtifactStore, createMemoryArtifactStore, createMemoryKeySet, createMemorySessionStore, createNoopAgentHost, createNoopSurvivabilityAdapter, createOpenAICompatibleProvider, createOpenAIProvider, createOpenRouterProvider, createOtelReceiptAttributes, createOtelRunEventSink, createPermissionContext, createPermissionGuardHook, createPhoenixOtlpConfig, createRateLimitGroup, createRealtimeCheckpointContext, createRealtimeReceiptDescriptors, createReceipt, createRemoteReceiptSigner, createReplayEnvelope, createTranscriptStore, createXaiProvider, defaultPiiDetectors, defineAgent, defineTool, estimateRouteCost, evalAgentRun, evaluateContractAgainstRoute, evaluateTripwires, findCapabilityProfile, formatToolsForProvider, generateEd25519KeyPairJwk, getCapabilityProfile, getRecommendedSanitizers, getStructuredOutputContract, getToolUseContract, importMcpTools, inv, isTerminal, latticeVersion, materializeReplayEnvelope, negotiateCapabilities, output, parseToolUseEnvelope, permissionGuardRegisterOptions, realtimeStepName, receiptCid, redactArtifactRef, redactPlan, redactReplayEnvelope, replayOffline, rerunLive, runAgent, runAgentCrew, runTool, sanitizeRunEventAttributes, stripChatTemplateArtifacts, stripOpenRouterVariant, stripReasoningTags, synthesizeNegotiatedCapabilitiesFromRegistry, toolArtifactRef, toolSchemaToJsonSchema, unwrapInternalEnvelope, verifyReceipt, withRateLimit };
2359
3620
  //# sourceMappingURL=index.d.ts.map