@full-self-browsing/lattice 1.4.0 → 1.5.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.
Files changed (108) hide show
  1. package/dist/agent-run-C6miAzwI.d.ts +45 -0
  2. package/dist/agent-run-C6miAzwI.d.ts.map +1 -0
  3. package/dist/agent-run-CgPVFl0Z.js +47 -0
  4. package/dist/agent-run-CgPVFl0Z.js.map +1 -0
  5. package/dist/agents.d.ts +5 -0
  6. package/dist/agents.js +6 -0
  7. package/dist/artifact-Bg6mJGnm.d.ts +125 -0
  8. package/dist/artifact-Bg6mJGnm.d.ts.map +1 -0
  9. package/dist/artifact-DOfpeXLb.js +140 -0
  10. package/dist/artifact-DOfpeXLb.js.map +1 -0
  11. package/dist/artifacts.d.ts +2 -0
  12. package/dist/artifacts.js +2 -0
  13. package/dist/audit.d.ts +3 -0
  14. package/dist/audit.js +4 -0
  15. package/dist/catalog-CAfYwB_-.js +91 -0
  16. package/dist/catalog-CAfYwB_-.js.map +1 -0
  17. package/dist/context-pack-Bz3GXmjv.js +99 -0
  18. package/dist/context-pack-Bz3GXmjv.js.map +1 -0
  19. package/dist/context.d.ts +2 -0
  20. package/dist/context.js +2 -0
  21. package/dist/contract-S3oJGlc9.d.ts +74 -0
  22. package/dist/contract-S3oJGlc9.d.ts.map +1 -0
  23. package/dist/core.d.ts +48 -0
  24. package/dist/core.d.ts.map +1 -0
  25. package/dist/core.js +95 -0
  26. package/dist/core.js.map +1 -0
  27. package/dist/errors-eEuEIx6X.js +407 -0
  28. package/dist/errors-eEuEIx6X.js.map +1 -0
  29. package/dist/eval.d.ts +2 -0
  30. package/dist/eval.js +2 -0
  31. package/dist/fingerprint-DodDbQKN.js +34 -0
  32. package/dist/fingerprint-DodDbQKN.js.map +1 -0
  33. package/dist/index-DpnHGHVL.d.ts +53 -0
  34. package/dist/index-DpnHGHVL.d.ts.map +1 -0
  35. package/dist/index.d.ts +90 -3533
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +26 -15968
  38. package/dist/index.js.map +1 -1
  39. package/dist/infer-DLqp5QIM.d.ts +96 -0
  40. package/dist/infer-DLqp5QIM.d.ts.map +1 -0
  41. package/dist/lineage-DBgoPWAZ.js +137 -0
  42. package/dist/lineage-DBgoPWAZ.js.map +1 -0
  43. package/dist/local-CXOGPJ1f.js +139 -0
  44. package/dist/local-CXOGPJ1f.js.map +1 -0
  45. package/dist/local-Dy--7peL.d.ts +10 -0
  46. package/dist/local-Dy--7peL.d.ts.map +1 -0
  47. package/dist/memory-CkQEW6m5.js +62 -0
  48. package/dist/memory-CkQEW6m5.js.map +1 -0
  49. package/dist/memory-DRig5EHV.d.ts +10 -0
  50. package/dist/memory-DRig5EHV.d.ts.map +1 -0
  51. package/dist/negotiate-ClD88hkc.js +10967 -0
  52. package/dist/negotiate-ClD88hkc.js.map +1 -0
  53. package/dist/otel-BgM4e55_.d.ts +421 -0
  54. package/dist/otel-BgM4e55_.d.ts.map +1 -0
  55. package/dist/permission-context-CUKMo79F.js +134 -0
  56. package/dist/permission-context-CUKMo79F.js.map +1 -0
  57. package/dist/plan-DFm8Llep.js +125 -0
  58. package/dist/plan-DFm8Llep.js.map +1 -0
  59. package/dist/preflight-DNHWuJ46.d.ts +64 -0
  60. package/dist/preflight-DNHWuJ46.d.ts.map +1 -0
  61. package/dist/provider-C2IfKsvz.d.ts +1178 -0
  62. package/dist/provider-C2IfKsvz.d.ts.map +1 -0
  63. package/dist/providers.d.ts +4 -0
  64. package/dist/providers.js +4 -0
  65. package/dist/rate-limit-group-nDsBJqSu.d.ts +235 -0
  66. package/dist/rate-limit-group-nDsBJqSu.d.ts.map +1 -0
  67. package/dist/receipt-FYouoPHv.js +205 -0
  68. package/dist/receipt-FYouoPHv.js.map +1 -0
  69. package/dist/replay-CtIhpLek.js +964 -0
  70. package/dist/replay-CtIhpLek.js.map +1 -0
  71. package/dist/result-DLEx2WvU.d.ts +38 -0
  72. package/dist/result-DLEx2WvU.d.ts.map +1 -0
  73. package/dist/router-DU4Z3pTd.js +314 -0
  74. package/dist/router-DU4Z3pTd.js.map +1 -0
  75. package/dist/router-Yo1-aDOv.d.ts +42 -0
  76. package/dist/router-Yo1-aDOv.d.ts.map +1 -0
  77. package/dist/routing.d.ts +6 -0
  78. package/dist/routing.js +4 -0
  79. package/dist/{run-crew-CKdBjh5P.js → run-crew-B2fQLmgB.js} +7 -136
  80. package/dist/run-crew-B2fQLmgB.js.map +1 -0
  81. package/dist/run-crew-Bnve5dyI.d.ts +721 -0
  82. package/dist/run-crew-Bnve5dyI.d.ts.map +1 -0
  83. package/dist/{runtime-D25ehzCj.js → runtime-Dxiet5YS.js} +98 -641
  84. package/dist/runtime-Dxiet5YS.js.map +1 -0
  85. package/dist/scaffolds-DKQrCRqh.d.ts +535 -0
  86. package/dist/scaffolds-DKQrCRqh.d.ts.map +1 -0
  87. package/dist/scaffolds-ekPIlBeU.js +3139 -0
  88. package/dist/scaffolds-ekPIlBeU.js.map +1 -0
  89. package/dist/schema-CNfa_VEy.d.ts +15 -0
  90. package/dist/schema-CNfa_VEy.d.ts.map +1 -0
  91. package/dist/storage-DJKmsaEI.d.ts +26 -0
  92. package/dist/storage-DJKmsaEI.d.ts.map +1 -0
  93. package/dist/storage.d.ts +10 -0
  94. package/dist/storage.d.ts.map +1 -0
  95. package/dist/storage.js +4 -0
  96. package/dist/tool-call-validation-BFoXkwbf.js +107 -0
  97. package/dist/tool-call-validation-BFoXkwbf.js.map +1 -0
  98. package/dist/tools-C4wHgGKQ.js +49 -0
  99. package/dist/tools-C4wHgGKQ.js.map +1 -0
  100. package/dist/tools.d.ts +46 -0
  101. package/dist/tools.d.ts.map +1 -0
  102. package/dist/tools.js +106 -0
  103. package/dist/tools.js.map +1 -0
  104. package/dist/validate-c7EL5uuH.js +224 -0
  105. package/dist/validate-c7EL5uuH.js.map +1 -0
  106. package/package.json +99 -2
  107. package/dist/run-crew-CKdBjh5P.js.map +0 -1
  108. package/dist/runtime-D25ehzCj.js.map +0 -1
package/dist/index.d.ts CHANGED
@@ -1,3451 +1,116 @@
1
- import { StandardSchemaV1 } from "@standard-schema/spec";
1
+ import { $ as XaiQuirks, $t as ExecutionPlanStub, A as SANITIZER_BY_FAILURE_MODE, At as defaultPiiDetectors, B as ModelCapabilityProfilePricingKey, Ct as ValidationIssue, D as NegotiationAuthError, Dt as evaluateTripwires, E as NegotiatedCapabilities, Et as TripwireResult, F as CapabilityAdapter, Ft as MustCiteInvariant, G as AdapterQuirks, H as RecommendedPromptStrategy, I as KnownFailureMode, It as NoPiiInvariant, J as LiteLLMQuirks, K as AnthropicQuirks, L as ModelCapabilityProfile, Lt as inv, M as getRecommendedSanitizers, Mt as InvariantDeclaration, N as ALL_KNOWN_FAILURE_MODES, Nt as InvariantOptions, O as negotiateCapabilities, Ot as PiiDetector, P as ALL_TRAINING_CLASSES, Pt as MatchesInvariant, Q as OpenRouterQuirks, R as ModelCapabilityProfileModality, T as Usage, Tt as TripwireEvidence, U as ToolCallSurface, V as ReasoningSurface, W as TrainingClass, X as OpenAICompatQuirks, Y as LmStudioQuirks, Yt as createMemorySessionStore, Z as OpenAIQuirks, _ as ProviderStreamOutputChunk, _n as output, b as ProviderStreamUsageChunk, bn as RunEventSink, d as ProviderRunRequest, dt as importMcpTools, et as ToolCallValidationError, f as ProviderRunResponse, ft as runTool, g as ProviderStreamGatewayChunk, gt as LatticeRunError, h as ProviderStreamCompleteChunk, ht as parseToolUseEnvelope, j as SanitizerKey, jt as FieldFromTableInvariant, k as synthesizeNegotiatedCapabilitiesFromRegistry, kt as PiiDetectorResult, l as ProviderRef, m as ProviderStreamChunk, mn as OutputContractMap, mt as ToolUseRequest, nt as ValidateToolCallsOption, o as ProviderGatewayMetadata, p as ProviderStream, pn as OutputContract, pt as toolArtifactRef, q as GeminiQuirks, qt as SessionRef, r as ProviderAdapter, rt as ValidatedToolCall, tt as ToolCallValidationFailureReason, ut as defineTool, v as ProviderStreamTextDeltaChunk, vn as RunEvent, wt as isTerminal, xn as TracerLike, xt as TripwireViolationError, y as ProviderStreamToolCallChunk, yn as RunEventKind, z as ModelCapabilityProfilePricing } from "./provider-C2IfKsvz.js";
2
+ import { A as FormatToolsMode, B as HookDenyDirective, C as EvictionHook, D as UnsubscribeFn, E as SurvivabilityAdapter, F as LatticeConfig, G as createHookPipeline, H as HookLifecycleEvent, I as NormalizedLatticeConfig, L as BAND, M as FormattedToolsHandle, N as formatToolsForProvider, O as createNoopSurvivabilityAdapter, P as toolSchemaToJsonSchema, R as Band, S as createNoopAgentHost, T as SerializedSnapshot, U as HookPipeline, V as HookHandler, _ as AgentHost, a as CrewPolicy, b as AgentStorage, c as defineAgent, d as AgentFailureKind, f as AgentIntent, g as IterationRecord, i as runAgentCrew, j as FormatToolsOptions, k as ConversationTurn, l as AgentDeniedError, m as AgentSuccess, n as CrewResult, o as CrewRateLimitOverride, p as AgentResult, r as RunAgentCrewOptions, s as AgentSpec, t as CrewAgentResult, u as AgentFailure, v as AgentScheduler, w as ResumePolicy, x as AgentTransport, y as AgentSnapshot, z as HookControls } from "./run-crew-Bnve5dyI.js";
3
+ import { _ as ArtifactTransformDescriptor, a as ArtifactOptions, b as GatewayPolicy, c as ArtifactSize, f as artifact, g as ArtifactParentRef, h as ArtifactLineage, i as ArtifactKind, l as ArtifactSource, n as ArtifactFingerprint, o as ArtifactPrivacy, r as ArtifactInput, s as ArtifactRef, u as ArtifactStorageRef, v as ArtifactTransformKind, x as PolicySpec, y as GatewayMetadataValue } from "./artifact-Bg6mJGnm.js";
4
+ import { _ as VerifyFail, a as KeyEntry, c as ReceiptEnvelope, d as ReceiptRoute, f as ReceiptSignature, g as VerifyErrorKind, h as VerifyError, i as ContractVerdict, l as ReceiptModel, m as ReceiptUsageCanonical, n as InferOutputMap, o as KeySet, p as ReceiptSigner, r as CapabilityReceiptBody, s as KeyState, t as InferOutput, u as ReceiptRedaction, v as VerifyOk, y as VerifyResult } from "./infer-DLqp5QIM.js";
5
+ import { i as StoredArtifactPayloadDescriptor, n as StorageLike, r as StoredArtifactEnvelope, t as ArtifactStore } from "./storage-DJKmsaEI.js";
6
+ import { a as QualityFloorInvariant, i as ContractRejectReasonCode, n as CapabilityContract, o as contract, r as CapabilityContractInput, t as BudgetInvariant } from "./contract-S3oJGlc9.js";
7
+ import { A as createCostTracker, C as ProgressStatus, D as createTranscriptStore, E as TranscriptStore, O as CostBudgetStatus, S as GoalProgressTracker, T as TokenEstimator, _ as STUCK_REASONS, a as withRateLimit, b as GoalProgressOptions, c as PermissionHookContext, d as createPermissionContext, f as createPermissionGuardHook, g as ActionRecord, h as ActionHistoryOptions, i as createRateLimitGroup, j as runAgent, k as CostTracker, l as PermissionRule, m as ActionHistory, n as RateLimitGroupOptions, o as PermissionContext, p as permissionGuardRegisterOptions, r as RateLimitLease, s as PermissionDecisionInput, t as RateLimitGroup, u as PermissionVerdict, v as StuckReason, w as createGoalProgressTracker, x as GoalProgressStep, y as createActionHistory } from "./rate-limit-group-nDsBJqSu.js";
8
+ import { a as EvalRegressionKind, i as EvalRegression, n as AgentRunSnapshot, o as evalAgentRun, r as EvalOptions, t as AgentEvalResult } from "./agent-run-C6miAzwI.js";
9
+ import { A as RemoteReceiptSignerProvider, B as ReplayEnvelope, D as RemoteReceiptSignRequest, E as RemoteReceiptPayloadFormat, F as ExternalExecutionMetadata, G as replayOffline, H as redactArtifactRef, I as ExternalExecutionSidecar, J as RunIntent, K as rerunLive, L as ExternalExecutionSidecarOutputSpec, M as createMemoryKeySet, N as ExternalExecutionAuditInput, O as RemoteReceiptSignResult, P as ExternalExecutionAuditResult, R as ExternalExecutionUsage, S as verifyReceipt, T as generateEd25519KeyPairJwk, U as redactPlan, V as createReplayEnvelope, W as redactReplayEnvelope, X as CreateReceiptInput, Y as createAI, Z as createReceipt, a as OtelHttpTraceConfig, b as materializeReplayEnvelope, c as OtelSpanLike, d as PhoenixOtlpConfigOptions, f as createLangfuseOtlpConfig, g as sanitizeRunEventAttributes, h as createPhoenixOtlpConfig, i as OtelContentCaptureMode, j as createRemoteReceiptSigner, k as RemoteReceiptSignerOptions, l as OtelSpanStatus, m as createOtelRunEventSink, n as OtelAttributeValue, o as OtelRunEventSinkOptions, p as createOtelReceiptAttributes, q as AI, r as OtelAttributes, s as OtelSanitizerOptions, t as LangfuseOtlpConfigOptions, u as OtelTracerLike, v as MaterializationError, w as createInMemorySigner, x as receiptCid, y as MaterializeReplayEnvelopeOptions, z as createExternalExecutionAudit } from "./otel-BgM4e55_.js";
10
+ import { n as RunResult, r as RunSuccess, t as RunFailure } from "./result-DLEx2WvU.js";
11
+ import { a as evaluateContractAgainstRoute, i as estimateRouteCost } from "./preflight-DNHWuJ46.js";
12
+ import { n as createMemoryArtifactStore } from "./memory-DRig5EHV.js";
13
+ import { A as stripChatTemplateArtifacts, C as createAISdkProvider, D as SanitizeOutputOption, E as InternalEnvelopeOptions, M as unwrapInternalEnvelope, O as SanitizerContext, T as createOpenAIProvider, a as CollectStreamOptions, b as createAnthropicProvider, c as createXaiProvider, d as LmStudioProviderOptions, f as createLmStudioProvider, g as createGeminiProvider, h as GeminiProviderOptions, i as getToolUseContract, j as stripReasoningTags, k as SanitizerFn, l as OpenRouterProviderOptions, m as createLiteLLMProvider, n as PROMPT_STRATEGIES, o as collectStream, p as LiteLLMProviderOptions, r as getStructuredOutputContract, s as XaiProviderOptions, t as PROMPT_SCAFFOLD_VERSION, u as createOpenRouterProvider, v as createFakeProvider, w as createOpenAICompatibleProvider, y as AnthropicProviderOptions } from "./scaffolds-DKQrCRqh.js";
14
+ import { n as createLocalArtifactStore } from "./local-Dy--7peL.js";
15
+ import { n as getCapabilityProfile, r as stripOpenRouterVariant, t as findCapabilityProfile } from "./index-DpnHGHVL.js";
2
16
 
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
- }
13
- interface PolicySpec {
14
- readonly maxCostUsd?: number;
15
- readonly latency?: "interactive" | "batch";
16
- readonly privacy?: "standard" | "sensitive" | "restricted";
17
- readonly providerAllowList?: readonly string[];
18
- readonly providerDenyList?: readonly string[];
19
- readonly noUpload?: boolean;
20
- readonly noPublicUrl?: boolean;
21
- readonly noLogging?: boolean;
22
- readonly stream?: boolean;
23
- readonly gateway?: GatewayPolicy;
24
- readonly metadata?: Record<string, unknown>;
25
- }
26
- //#endregion
27
- //#region src/artifacts/lineage.d.ts
28
- type ArtifactTransformKind = "manual" | "generated" | "extraction" | "chunking" | "transcription" | "resizing" | "provider-packaging" | "tool-result" | "model-output";
29
- interface ArtifactTransformDescriptor {
30
- readonly kind: ArtifactTransformKind;
31
- readonly name?: string;
32
- readonly metadata?: Record<string, unknown>;
33
- }
34
- interface ArtifactParentRef {
35
- readonly id: string;
36
- readonly kind: ArtifactKind;
37
- readonly mediaType?: string;
38
- readonly source: ArtifactSource;
39
- readonly label?: string;
40
- readonly metadata?: Record<string, unknown>;
41
- readonly privacy: ArtifactPrivacy;
42
- readonly size?: ArtifactSize;
43
- readonly fingerprint?: ArtifactFingerprint;
44
- readonly storage?: ArtifactStorageRef;
45
- readonly lineage?: ArtifactLineage;
46
- }
47
- interface ArtifactLineage {
48
- readonly parents: readonly ArtifactParentRef[];
49
- readonly transform: ArtifactTransformDescriptor;
50
- }
51
- //#endregion
52
- //#region src/artifacts/artifact.d.ts
53
- type ArtifactKind = "text" | "json" | "file" | "image" | "audio" | "video" | "document" | "url" | "tool-result";
54
- type ProviderUploadArtifactSource = `provider-${"up"}${"load"}`;
55
- type ArtifactSource = "inline" | "file" | "url" | "generated" | ProviderUploadArtifactSource | "tool";
56
- type ArtifactPrivacy = NonNullable<PolicySpec["privacy"]>;
57
- interface ArtifactSize {
58
- readonly bytes?: number;
59
- readonly characters?: number;
60
- readonly pages?: number;
61
- readonly width?: number;
62
- readonly height?: number;
63
- readonly durationMs?: number;
64
- }
65
- interface ArtifactFingerprint {
66
- readonly algorithm: "sha256";
67
- readonly value: string;
68
- }
69
- interface ArtifactStorageRef {
70
- readonly storeId: string;
71
- readonly key: string;
72
- }
73
- interface ArtifactOptions {
74
- readonly id?: string;
75
- readonly mediaType?: string;
76
- readonly label?: string;
77
- readonly metadata?: Record<string, unknown>;
78
- readonly privacy?: ArtifactPrivacy;
79
- readonly size?: ArtifactSize;
80
- readonly fingerprint?: ArtifactFingerprint;
81
- readonly storage?: ArtifactStorageRef;
82
- readonly lineage?: ArtifactLineage;
83
- }
84
- interface ArtifactToolResultOptions extends ArtifactOptions {
85
- readonly toolName: string;
86
- readonly callId?: string;
87
- }
88
- interface ArtifactDerivedOptions extends ArtifactOptions {
89
- readonly kind: ArtifactKind;
90
- readonly source?: ArtifactSource;
91
- readonly value?: unknown;
92
- readonly parents: readonly ArtifactRef[];
93
- readonly transform: ArtifactTransformDescriptor;
94
- }
95
- interface ArtifactRef {
96
- readonly id: string;
97
- readonly kind: ArtifactKind;
98
- readonly mediaType?: string;
99
- readonly source: ArtifactSource;
100
- readonly label?: string;
101
- readonly metadata?: Record<string, unknown>;
102
- readonly privacy: ArtifactPrivacy;
103
- readonly size?: ArtifactSize;
104
- readonly fingerprint?: ArtifactFingerprint;
105
- readonly storage?: ArtifactStorageRef;
106
- readonly lineage?: ArtifactLineage;
107
- }
108
- type ArtifactInput = ArtifactRef & {
109
- readonly value?: unknown;
110
- };
111
- declare const artifact: {
112
- text(value: string, options?: ArtifactOptions): ArtifactInput;
113
- json(value: unknown, options?: ArtifactOptions): ArtifactInput;
114
- file(value: Blob | File | string, options?: ArtifactOptions): ArtifactInput;
115
- image(value: Blob | File | string, options?: ArtifactOptions): ArtifactInput;
116
- audio(value: Blob | File | string, options?: ArtifactOptions): ArtifactInput;
117
- document(value: Blob | File | string, options?: ArtifactOptions): ArtifactInput;
118
- url(value: string | URL, options?: ArtifactOptions): ArtifactInput;
119
- toolResult(value: unknown, options: ArtifactToolResultOptions): ArtifactInput;
120
- derive(input: ArtifactDerivedOptions): ArtifactInput;
121
- };
122
- //#endregion
123
- //#region src/tracing/tracing.d.ts
124
- interface TracerLike {
125
- readonly kind: "tracer";
126
- readonly span?: <T>(name: string, fn: () => T | Promise<T>, attributes?: Record<string, unknown>) => T | Promise<T>;
127
- readonly event?: (name: string, attributes?: Record<string, unknown>) => void;
128
- }
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";
130
- interface RunEvent {
131
- readonly kind: RunEventKind;
132
- readonly timestamp: string;
133
- readonly runId: string;
134
- readonly planId?: string;
135
- readonly stageId?: string;
136
- readonly providerId?: string;
137
- readonly modelId?: string;
138
- readonly artifactId?: string;
139
- readonly metadata?: Record<string, unknown>;
140
- }
141
- type RunEventSink = (event: RunEvent) => void | Promise<void>;
142
- //#endregion
143
- //#region src/contract/bands.d.ts
144
- /**
145
- * Hook lifecycle event vocabulary -- separate from RunEventKind by design.
146
- *
147
- * Phase 19 (v1.2) additively extends with BEFORE_AGENT_ITERATION and
148
- * AFTER_AGENT_ITERATION — emitted by `runAgent` around each iteration's
149
- * provider call. Existing four events continue to fire inside each
150
- * iteration (BEFORE/AFTER_PROVIDER per native call; BEFORE/AFTER_TOOL
151
- * per dispatched tool).
152
- */
153
- type HookLifecycleEvent = "BEFORE_PROVIDER" | "AFTER_PROVIDER" | "BEFORE_TOOL" | "AFTER_TOOL" | "BEFORE_AGENT_ITERATION" | "AFTER_AGENT_ITERATION";
154
- /**
155
- * SAFETY-band veto mechanism — Phase 19.
156
- *
157
- * Handlers can deny an iteration by calling `controls.deny(reason)`. The
158
- * pipeline records the latest reason and exposes it via `lastDenialReason()`.
159
- * The reason resets at the start of each `run()` call.
160
- *
161
- * Composition convention: the agent runtime invokes BEFORE_AGENT_ITERATION
162
- * before provider call, then checks `pipeline.lastDenialReason()`. If set,
163
- * the iteration aborts with `agent-iteration-denied` failure.
164
- */
165
- interface HookDenyDirective {
166
- readonly reason: string;
167
- }
168
- /**
169
- * Controls passed to each handler as an optional second argument.
170
- *
171
- * Backward compat: existing single-argument handlers (Phase 15 + Phase 16)
172
- * ignore this and continue to work unchanged.
173
- */
174
- interface HookControls {
175
- /** Set a denial reason; the latest call wins per `run()`. */
176
- readonly deny: (reason: string) => void;
177
- }
178
- /**
179
- * Priority bands. Lower number = higher priority (runs first).
180
- *
181
- * SAFETY (0) -- safety / breaker hooks; cannot be overridden by lower bands
182
- * OBSERVABILITY (1) -- logging, metrics, audit; runs after safety, before extension
183
- * EXTENSION (2) -- user-supplied hooks; runs last
184
- *
185
- * Within a band, handlers run in registration order.
186
- */
187
- declare const BAND: {
188
- readonly SAFETY: 0;
189
- readonly OBSERVABILITY: 1;
190
- readonly EXTENSION: 2;
191
- };
192
- type Band = typeof BAND[keyof typeof BAND];
193
- /**
194
- * Handler input -- frozen snapshot of the caller's context at run() time.
195
- *
196
- * structuredClone-then-Object.freeze: handlers receive a deep-cloned,
197
- * surface-frozen view. Mutations on the handler side do NOT leak back to
198
- * the calling site.
199
- *
200
- * The handler's return value is currently ignored; future revisions may
201
- * add a typed return that downstream bands consume.
202
- */
203
- interface HookHandler<TContext = unknown> {
204
- (context: Readonly<TContext>, controls?: HookControls): void | Promise<void>;
205
- }
206
- interface RegisterOptions {
207
- readonly band: Band;
208
- readonly matcher?: RegExp;
209
- readonly budgetMs?: number;
210
- }
211
- /**
212
- * The HookPipeline interface returned by createHookPipeline().
213
- *
214
- * IMMUTABILITY: once freeze() is called, register() throws an Error whose
215
- * .name === "PIPELINE_FROZEN". freeze() is irreversible by design --
216
- * protects against late-binding hook injection mid-session.
217
- */
218
- interface HookPipeline {
219
- readonly kind: "hook-pipeline";
220
- register<TContext = unknown>(event: HookLifecycleEvent, handler: HookHandler<TContext>, options: RegisterOptions): void;
221
- freeze(): void;
222
- isFrozen(): boolean;
223
- run<TContext = unknown>(event: HookLifecycleEvent, context: TContext): Promise<void>;
224
- /**
225
- * Phase 19: returns the latest denial reason set by any handler during
226
- * the most recent `run()` call. Resets to `null` at the start of each run.
227
- * Read by the agent runtime to detect SAFETY-band veto.
228
- */
229
- lastDenialReason(): string | null;
230
- }
231
- interface CreateHookPipelineOptions {
232
- readonly tracer?: TracerLike;
233
- readonly sessionId?: string;
234
- readonly defaultBudgetMs?: number;
235
- }
236
- /**
237
- * Factory: build a fresh hook pipeline.
238
- */
239
- declare function createHookPipeline(options?: CreateHookPipelineOptions): HookPipeline;
240
- //#endregion
241
- //#region src/contract/invariants.d.ts
242
- /**
243
- * Tripwire invariant declaration variants produced by the `inv` fluent
244
- * builder. Each variant is a frozen value carrying a discriminant `kind`
245
- * and an `id` (auto-generated or caller-supplied).
246
- *
247
- * Phase 8 reshapes the Phase 7 placeholder `{ kind: "policy"|"semantic"|"schema" }`
248
- * into this discriminated union. Phase 7 never populated `invariants`
249
- * (see 07-04-SUMMARY decisions), so the change is additive in practice
250
- * but technically a breaking type change for any external caller that
251
- * authored a literal of the old shape.
252
- */
253
- interface MustCiteInvariant {
254
- readonly id: string;
255
- readonly kind: "must-cite";
256
- readonly artifactName: string;
257
- }
258
- interface FieldFromTableInvariant {
259
- readonly id: string;
260
- readonly kind: "field-from-table";
261
- readonly path: string;
262
- readonly allowedValues: readonly string[];
263
- }
264
- interface NoPiiInvariant {
265
- readonly id: string;
266
- readonly kind: "no-pii";
267
- readonly path: string;
268
- }
269
- interface MatchesInvariant<T = unknown> {
270
- readonly id: string;
271
- readonly kind: "matches";
272
- readonly path: string;
273
- readonly schema: StandardSchemaV1<unknown, T>;
274
- }
275
- type InvariantDeclaration = MustCiteInvariant | FieldFromTableInvariant | NoPiiInvariant | MatchesInvariant;
276
- interface InvariantOptions {
277
- readonly id?: string;
278
- }
279
- /**
280
- * Fluent builder for tripwire invariants.
281
- *
282
- * Each helper returns a frozen `InvariantDeclaration` with an auto-generated
283
- * id of the form `${kind}-${counter}`. Callers may override the id via the
284
- * second-positional `options.id` arg.
285
- *
286
- * The counter is monotonic across kinds — calling `inv.mustCite("a")` then
287
- * `inv.fieldFromTable("x", ["y"])` yields ids `must-cite-1` then
288
- * `field-from-table-2`. This keeps ids globally unique within a process.
289
- *
290
- * Note on `inv.matches`: the caller supplies the StandardSchema validator,
291
- * and the tripwire evaluator trusts whatever `~standard.validate` returns.
292
- * This is by design — `matches` is the caller-driven escape hatch (see
293
- * T-08-05 in the 08-01-PLAN threat register).
294
- */
295
- declare const inv: {
296
- readonly mustCite: (artifactName: string, options?: InvariantOptions) => MustCiteInvariant;
297
- readonly fieldFromTable: (path: string, allowedValues: readonly string[], options?: InvariantOptions) => FieldFromTableInvariant;
298
- readonly noPII: (path: string, options?: InvariantOptions) => NoPiiInvariant;
299
- readonly matches: <T>(path: string, schema: StandardSchemaV1<unknown, T>, options?: InvariantOptions) => MatchesInvariant<T>;
300
- /**
301
- * Test-only: reset the auto-id counter. NOT exported from the package
302
- * root barrel — callers must import `inv` directly from this module if
303
- * they ever need it, which is intentional friction.
304
- */
305
- readonly __resetCounterForTests: () => void;
306
- };
307
- //#endregion
308
- //#region src/contract/pii-detectors.d.ts
309
- /**
310
- * Regex-based PII detectors used by the `no-pii` tripwire invariant.
311
- *
312
- * Phase 8 ships four detectors (email, US SSN, Luhn-valid credit card,
313
- * US phone). They are intentionally regex-only — zero new dependencies —
314
- * per the v1.1 scope locked in 08-CONTEXT.md.
315
- *
316
- * Each detector returns either `{ matched: true, substring }` carrying
317
- * ONLY the matched fragment, or `{ matched: false }`. The substring shape
318
- * is required so the tripwire evaluator can emit redacted evidence
319
- * (Phase 9 receipts must not leak the full input).
320
- *
321
- * Detector order in `defaultPiiDetectors` is deterministic so the
322
- * evaluator's first-violation semantics produce stable receipts.
323
- */
324
- type PiiDetectorResult = {
325
- readonly matched: true;
326
- readonly substring: string;
327
- } | {
328
- readonly matched: false;
329
- };
330
- interface PiiDetector {
331
- readonly name: string;
332
- detect(input: string): PiiDetectorResult;
333
- }
334
- /**
335
- * Default PII detectors used by `evaluateTripwires` for `no-pii` invariants.
336
- *
337
- * Order is deterministic: email, us-ssn, credit-card, us-phone. Callers who
338
- * need a different set can pass their own list to `evaluateTripwires`.
339
- */
340
- declare const defaultPiiDetectors: readonly PiiDetector[];
341
- //#endregion
342
- //#region src/contract/tripwire.d.ts
343
- /**
344
- * Evidence emitted when a tripwire invariant fires.
345
- *
346
- * `observed` is the SHAPE-MATCHED redacted payload, not the raw output:
347
- * - for `must-cite`: the citations array as found at the located path
348
- * - for `field-from-table`: the actual value at `path`
349
- * - for `no-pii`: ONLY `{ detector, substring }` — never the full input
350
- * (T-08-01 in the 08-01-PLAN threat register)
351
- * - for `matches`: the value at `path`
352
- *
353
- * Phase 9 receipts will sign this evidence, so leaking the full PII into
354
- * `observed` would defeat redact-before-sign.
355
- */
356
- interface TripwireEvidence {
357
- readonly invariantId: string;
358
- readonly kind: "must-cite" | "field-from-table" | "no-pii" | "matches";
359
- readonly path: string;
360
- readonly observed: unknown;
361
- readonly message: string;
362
- }
363
- type TripwireResult = {
364
- readonly ok: true;
365
- } | {
366
- readonly ok: false;
367
- readonly evidence: TripwireEvidence;
368
- };
369
- /**
370
- * Pure tripwire evaluator.
371
- *
372
- * No I/O, no Date.now, no random — same `(output, invariants)` always
373
- * returns the same `TripwireResult`. Phase 9 receipts can reconstruct the
374
- * verdict deterministically (T-08-04).
375
- *
376
- * Evaluates invariants in declaration order; the FIRST failing invariant
377
- * aborts and returns its evidence. Subsequent invariants are not evaluated.
378
- *
379
- * @param output The provider output to inspect.
380
- * @param invariants Invariants to evaluate, in declaration order.
381
- * @param detectors PII detectors used for `no-pii` invariants. Defaults
382
- * to `defaultPiiDetectors`. Callers can pass a custom
383
- * list to override.
384
- */
385
- declare function evaluateTripwires(output: unknown, invariants: readonly InvariantDeclaration[], detectors?: readonly PiiDetector[]): Promise<TripwireResult>;
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
518
- //#region src/outputs/contracts.d.ts
519
- type TextOutputContract = "text";
520
- interface CitationRef {
521
- readonly artifactId: string;
522
- readonly label?: string;
523
- readonly span?: {
524
- readonly start?: number;
525
- readonly end?: number;
526
- };
527
- readonly metadata?: Record<string, unknown>;
528
- }
529
- interface CitationsOutputContract {
530
- readonly kind: "citations";
531
- }
532
- interface ArtifactRefsOutputContract {
533
- readonly kind: "artifacts";
534
- readonly artifactKind?: ArtifactKind | string;
535
- }
536
- type SchemaOutputContract = StandardSchemaV1;
537
- type OutputContract = TextOutputContract | SchemaOutputContract | CitationsOutputContract | ArtifactRefsOutputContract;
538
- type OutputContractMap = Record<string, OutputContract>;
539
- declare const output: {
540
- citations(): CitationsOutputContract;
541
- artifacts(options?: {
542
- readonly artifactKind?: ArtifactKind | string;
543
- }): ArtifactRefsOutputContract;
544
- };
545
- //#endregion
546
- //#region src/sessions/session.d.ts
547
- interface SessionRef {
548
- readonly id: string;
549
- readonly kind?: "session-ref";
550
- }
551
- interface SessionTurn {
552
- readonly id: string;
553
- readonly task: string;
554
- readonly artifactRefs: readonly ArtifactRef[];
555
- readonly planId?: string;
556
- readonly outputArtifactRefs: readonly ArtifactRef[];
557
- readonly createdAt: string;
558
- }
559
- interface SessionSummary {
560
- readonly id: string;
561
- readonly artifactRef: ArtifactRef;
562
- readonly sourceTurnIds: readonly string[];
563
- readonly trust: "model-summary";
564
- readonly createdAt: string;
565
- }
566
- interface SessionRecord extends SessionRef {
567
- readonly kind: "session-ref";
568
- readonly parentId?: string;
569
- readonly branchPointRunId?: string;
570
- readonly turns: readonly SessionTurn[];
571
- readonly summaries: readonly SessionSummary[];
572
- readonly artifactRefs: readonly ArtifactRef[];
573
- readonly planIds: readonly string[];
574
- readonly createdAt: string;
575
- readonly updatedAt: string;
576
- }
577
- interface CreateSessionOptions {
578
- readonly id?: string;
579
- readonly parentId?: string;
580
- readonly branchPointRunId?: string;
581
- }
582
- interface AppendSessionTurnInput {
583
- readonly sessionId: string;
584
- readonly task: string;
585
- readonly artifactRefs: readonly ArtifactRef[];
586
- readonly outputArtifactRefs?: readonly ArtifactRef[];
587
- readonly planId?: string;
588
- }
589
- interface SessionStore {
590
- readonly kind: "session-store";
591
- readonly id: string;
592
- create(options?: CreateSessionOptions): Promise<SessionRecord>;
593
- load(id: string): Promise<SessionRecord | undefined>;
594
- save(session: SessionRecord): Promise<SessionRecord>;
595
- branch(parentId: string, options?: Omit<CreateSessionOptions, "parentId">): Promise<SessionRecord>;
596
- appendTurn(input: AppendSessionTurnInput): Promise<SessionRecord>;
597
- }
598
- interface MemorySessionStoreOptions {
599
- readonly id?: string;
600
- }
601
- declare function createMemorySessionStore(options?: MemorySessionStoreOptions): SessionStore;
602
- //#endregion
603
- //#region src/context/context-pack.d.ts
604
- interface ContextPack extends ContextPackPlan {
605
- readonly kind: "context-pack";
606
- }
607
- interface ContextSummarizer {
608
- summarize(input: {
609
- readonly artifacts: readonly ArtifactRef[];
610
- readonly budgetTokens: number;
611
- }): Promise<readonly ArtifactRef[]> | readonly ArtifactRef[];
612
- }
613
- //#endregion
614
- //#region src/runtime/survivability.d.ts
615
- /**
616
- * MV3-survivability adapter contract -- Phase 5 (FSB v0.10.0-attempt-2).
617
- *
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).
623
- *
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.
709
- */
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;
727
- }
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";
776
- readonly id: string;
777
- serialize(state: TState): SerializedSnapshot;
778
- deserialize(snapshot: SerializedSnapshot): TState;
779
- onEviction(hook: EvictionHook<TState>): UnsubscribeFn;
780
- resume(snapshot: SerializedSnapshot): Promise<ResumePolicy>;
781
- }
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 {
811
- readonly signal?: AbortSignal;
812
- readonly emit?: RunEventSink;
813
- }
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 {
859
- /**
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.
864
- */
865
- readonly mode?: FormatToolsMode;
866
- /**
867
- * Optional system prompt to prepend. Useful for setting persona /
868
- * domain-specific instructions on top of the tool-use envelope.
869
- */
870
- readonly system?: string;
871
- }
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";
911
- }
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;
932
- //#endregion
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[];
957
- }
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>;
971
- }
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>;
986
- }
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>;
1007
- }
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;
1020
- }
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;
1052
- }
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;
1063
- }
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";
1078
- }
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";
1092
- }
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)[];
1111
- }
1112
- interface ValidationError {
1113
- readonly kind: "validation";
1114
- readonly message: string;
1115
- readonly output?: string;
1116
- readonly issues: readonly ValidationIssue[];
1117
- }
1118
- interface ExecutionUnavailableError {
1119
- readonly kind: "execution_unavailable";
1120
- readonly message: string;
1121
- }
1122
- interface NoRouteError {
1123
- readonly kind: "no_route";
1124
- readonly message: string;
1125
- readonly reasons: readonly string[];
1126
- }
1127
- interface ProviderExecutionError {
1128
- readonly kind: "provider_execution";
1129
- readonly message: string;
1130
- readonly providerId?: string;
1131
- readonly modelId?: string;
1132
- }
1133
- interface TimeoutError {
1134
- readonly kind: "timeout";
1135
- readonly message: string;
1136
- }
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[];
1150
- }
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;
1167
- }
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;
1210
- }
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;
1245
- }
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;
1262
- }
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;
1286
- }
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);
1306
- }
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;
1315
- }
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;
1323
- }
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;
1330
- }
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
- });
1345
- }
1346
- //#endregion
1347
- //#region src/providers/quirks.d.ts
1348
- /**
1349
- * Universal 5-boolean shape every first-party adapter populates (SC-1 / D-03).
1350
- *
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)
1358
- */
1359
- interface AdapterQuirks {
1360
- readonly supportsToolChoice: boolean;
1361
- readonly parallelToolCalls: boolean;
1362
- readonly structuredOutputs: boolean;
1363
- readonly responseFormatHonored: boolean;
1364
- readonly streamingDiverges: boolean;
1365
- }
1366
- /**
1367
- * Anthropic adapter quirks (extends AdapterQuirks with 3 Anthropic-specific flags).
1368
- *
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).
1372
- *
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.
1376
- *
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.
1380
- */
1381
- interface AnthropicQuirks extends AdapterQuirks {
1382
- readonly promptCachingSupported: boolean;
1383
- readonly extendedThinkingSupported: boolean;
1384
- readonly toolUseInputSchemaStrict: boolean;
1385
- }
1386
- /**
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.
1394
- */
1395
- interface OpenAIQuirks extends AdapterQuirks {
1396
- readonly strictModeSupported: boolean;
1397
- readonly structuredOutputsTier2: boolean;
1398
- }
1399
- /**
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.
1407
- */
1408
- interface OpenAICompatQuirks extends AdapterQuirks {}
1409
- /**
1410
- * Gemini adapter quirks (extends AdapterQuirks with 3 Gemini-specific flags).
1411
- *
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.
1418
- *
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.
1422
- */
1423
- interface GeminiQuirks extends AdapterQuirks {
1424
- readonly responseSchemaSupported: boolean;
1425
- readonly safetySettingsConfigurable: boolean;
1426
- readonly systemInstructionSupported: boolean;
1427
- }
1428
- /**
1429
- * xAI adapter quirks (extends AdapterQuirks with 2 xAI-specific flags).
1430
- *
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.
1436
- */
1437
- interface XaiQuirks extends AdapterQuirks {
1438
- readonly reasoningTokensReported: boolean;
1439
- readonly logprobsSupported: boolean;
1440
- }
1441
- /**
1442
- * OpenRouter adapter quirks (extends AdapterQuirks with 3 OpenRouter-specific flags).
1443
- *
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.
1451
- */
1452
- interface OpenRouterQuirks extends AdapterQuirks {
1453
- readonly providerRoutingArraySupported: boolean;
1454
- readonly floorPricingHints: boolean;
1455
- readonly allowFallbacks: boolean;
1456
- }
1457
- /**
1458
- * LM Studio adapter quirks (extends AdapterQuirks with 2 LM Studio-specific flags).
1459
- *
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.
1464
- *
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).
1468
- */
1469
- interface LmStudioQuirks extends AdapterQuirks {
1470
- readonly customChatTemplateRiskFlag: boolean;
1471
- readonly noAuthRequired: boolean;
1472
- }
1473
- /**
1474
- * LiteLLM adapter quirks (extends AdapterQuirks with gateway-specific flags).
1475
- *
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.
1479
- */
1480
- interface LiteLLMQuirks extends AdapterQuirks {
1481
- readonly gatewayMetadataSupported: boolean;
1482
- readonly gatewayFallbacksSupported: boolean;
1483
- readonly openAIErrorMapping: boolean;
1484
- }
1485
- //#endregion
1486
- //#region src/capabilities/sanitizer-recommendations.d.ts
1487
- /**
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.
1491
- *
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
1496
- */
1497
- type SanitizerKey = "stripReasoningTags" | "stripChatTemplateArtifacts" | "unwrapInternalEnvelope";
1498
- /**
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.
1504
- *
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)
1510
- */
1511
- declare const SANITIZER_BY_FAILURE_MODE: Record<KnownFailureMode, SanitizerKey | null>;
1512
- /**
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.
1515
- *
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.
1524
- */
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";
1556
- }
1557
- /**
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.
1574
- */
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);
1581
- }
1582
- /**
1583
- * Phase 34 — D-02 / D-04 — Top-level helper for capability negotiation.
1584
- *
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.
1589
- *
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.
1598
- */
1599
- declare function negotiateCapabilities(adapter: ProviderAdapter, modelId: string): Promise<NegotiatedCapabilities>;
1600
- /**
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").
1606
- *
1607
- * Exported as a named export so Plans 02-05 can reuse the fallback synthesis
1608
- * without duplicating the mapping logic.
1609
- *
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.
1615
- *
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`.
1619
- */
1620
- declare function synthesizeNegotiatedCapabilitiesFromRegistry(adapter: CapabilityAdapter, modelId: string, source: "registry" | "registry-fallback"): NegotiatedCapabilities;
1621
- //#endregion
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;
1635
- }
1636
- /**
1637
- * Normalized per-run usage at the result layer.
1638
- *
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".
1642
- *
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`.
1646
- */
1647
- interface Usage {
1648
- readonly promptTokens: number;
1649
- readonly completionTokens: number;
1650
- readonly costUsd: number | null;
1651
- }
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;
1657
- }
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;
1672
- }
1673
- interface ProviderRef {
1674
- readonly id: string;
1675
- readonly kind?: "provider-ref";
1676
- }
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;
1699
- }
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>;
1706
- }
1707
- interface ProviderRunResponse {
1708
- readonly rawOutputs: Record<string, unknown>;
1709
- readonly artifactRefs?: readonly (ArtifactInput | ArtifactRef)[];
1710
- /**
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.
1715
- */
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;
1727
- }
1728
- interface ProviderStreamTextDeltaChunk {
1729
- readonly kind: "text-delta";
1730
- readonly output?: string;
1731
- readonly text: string;
1732
- }
1733
- interface ProviderStreamOutputChunk {
1734
- readonly kind: "output";
1735
- readonly output: string;
1736
- readonly value: unknown;
1737
- }
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>;
1769
- /**
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`.
1779
- */
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>;
1792
- }
1793
- type ProviderRegistryInput = readonly (ProviderRef | ProviderAdapter | string)[];
1794
- //#endregion
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[];
1935
- }
1936
- type ResultPlan = ExecutionPlan | ExecutionPlanStub;
1937
- //#endregion
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;
2021
- }
2022
- type VerifyResult = VerifyOk | VerifyFail;
2023
- //#endregion
2024
- //#region src/receipts/receipt.d.ts
2025
- /**
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)
2031
- *
2032
- * receiptId and issuedAt default to runtime-generated values when omitted.
2033
- * redactionPolicyId defaults to DEFAULT_REDACTION_POLICY_ID.
2034
- */
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;
2058
- }
2059
- /**
2060
- * Build, redact, canonicalize, sign, and envelope a CapabilityReceipt.
2061
- *
2062
- * Ordering INVARIANT (09-CONTEXT.md, PITFALLS.md Pitfall #1):
2063
- * redact -> canonicalize -> PAE -> sign -> encode
2064
- *
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.
2068
- *
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).
2075
- *
2076
- * I-JSON guarantees: usage.costUsd is converted to string (or null) via
2077
- * usageToCanonical. Receipts NEVER carry raw floats in the canonical form.
2078
- */
2079
- declare function createReceipt(input: CreateReceiptInput, signer: ReceiptSigner): Promise<ReceiptEnvelope>;
2080
- //#endregion
2081
- //#region src/contract/checkpoint.d.ts
2082
- /**
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.
2095
- *
2096
- * Fields are stable identifiers (D-04 carryforward); do NOT populate with
2097
- * user content -- they appear cleartext in the signed receipt body.
2098
- *
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.
2115
- *
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.
2143
- *
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).
2149
- *
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.
2158
- *
2159
- * NO upstream throw (D-07). NO global mutation (D-05).
2160
- */
2161
- declare function createCheckpointHook(options: CheckpointHookOptions): HookHandler<CheckpointHookContext>;
2162
- //#endregion
2163
- //#region src/contract/preflight.d.ts
2164
- /**
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.
2168
- *
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").
2173
- */
2174
- interface ContractPreflightResult {
2175
- readonly ok: boolean;
2176
- readonly reasons: readonly RouteRejectReason[];
2177
- }
2178
- /**
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`).
2182
- */
2183
- interface EstimateRouteCostInput {
2184
- readonly capability: ModelCapability;
2185
- readonly estimatedInputTokens: number;
2186
- readonly estimatedOutputTokens: number;
2187
- }
2188
- /**
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.
2193
- */
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
- }
2201
- /**
2202
- * Pure pre-flight evaluator. Phase 9 receipts will reuse this for deterministic
2203
- * verdict reconstruction.
2204
- *
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)
2219
- */
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
2277
- /**
2278
- * In-memory KeySet factory.
2279
- *
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"
2285
- *
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)".
2291
- */
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>;
2317
- }
2318
- /**
2319
- * Adapt a remote signing service to Lattice's existing ReceiptSigner contract.
2320
- *
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.
2324
- */
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;
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
2339
- /**
2340
- * Pure receipt verifier.
2341
- *
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
2357
- */
2358
- declare function verifyReceipt(envelope: ReceiptEnvelope, keySet: KeySet): Promise<VerifyResult>;
2359
- //#endregion
2360
- //#region src/providers/no-public-url.d.ts
2361
- /**
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).
2365
- *
2366
- * This is the single shared egress error class for all three adapter families
2367
- * (OpenAI-compatible, Anthropic, Gemini). Callers may `instanceof`-check it.
2368
- */
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);
2374
- }
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;
2401
- /**
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).
2406
- */
2407
- readonly pricing?: {
2408
- readonly inputPer1kTokens?: number;
2409
- readonly outputPer1kTokens?: number;
2410
- };
2411
- /**
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.
2419
- */
2420
- readonly modelsCacheTtlMs?: number;
2421
- /**
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).
2428
- */
2429
- readonly modelsRetryCount?: number;
2430
- /**
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).
2434
- *
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.
2439
- */
2440
- readonly runEventSink?: RunEventSink;
2441
- /**
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.
2445
- */
2446
- readonly sanitizeOutput?: SanitizeOutputOption;
2447
- /**
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.
2451
- */
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;
2461
- }
2462
- /**
2463
- * Phase 34 — D-04 / QUIRK-02 — OpenAI-compatible provider factory.
2464
- *
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."
2478
- */
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;
2509
- //#endregion
2510
- //#region src/providers/anthropic.d.ts
2511
- /**
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`).
2530
- */
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[];
2586
- }
2587
- declare function createFakeProvider(options?: FakeProviderOptions): ProviderAdapter;
2588
- //#endregion
2589
- //#region src/providers/gemini.d.ts
2590
- /**
2591
- * Options for {@link createGeminiProvider}.
2592
- *
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`).
2600
- *
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").
2614
- */
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;
2645
- }
2646
- /**
2647
- * Phase 34 — D-03 / D-05..D-12 — Extended Gemini provider factory.
2648
- *
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.
2655
- *
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).
2660
- */
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
2667
- /**
2668
- * Options for {@link createLiteLLMProvider}.
2669
- *
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.
2674
- */
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;
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
2687
- /**
2688
- * Options for {@link createLmStudioProvider}.
2689
- *
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).
2716
- */
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;
2728
- }
2729
- /**
2730
- * Phase 34 — D-04 / QUIRK-02 — LM Studio provider factory.
2731
- *
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.
2736
- *
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.
2749
- */
2750
- declare function createLmStudioProvider(options: LmStudioProviderOptions): ProviderAdapter & {
2751
- readonly quirks: LmStudioQuirks;
2752
- readonly negotiateCapabilities: (modelId: string) => Promise<NegotiatedCapabilities>;
2753
- };
2754
- //#endregion
2755
- //#region src/providers/openrouter.d.ts
17
+ //#region src/contract/checkpoint.d.ts
2756
18
  /**
2757
- * Options for {@link createOpenRouterProvider}.
2758
- *
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.
2763
- *
2764
- * SECURITY: `apiKey` is a runtime parameter -- do NOT hardcode or log it.
2765
- *
2766
- * STREAMING (Phase 44): supported through the OpenAI-compatible stream path.
2767
- *
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).
19
+ * The tracer event name Lattice's checkpoint hook emits per step transition.
20
+ * Identical to the literal added to RunEventKind in tracing.ts.
2774
21
  */
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;
2779
- /**
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.
2782
- */
2783
- readonly modelsCacheTtlMs?: number;
2784
- /**
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).
2788
- */
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
- }
22
+ declare const STEP_TRANSITION_EVENT_NAME: "step.transition";
2803
23
  /**
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.
24
+ * Default band convention for the checkpoint hook (D-06). The caller is
25
+ * free to register in a different band but the documented convention is
26
+ * OBSERVABILITY -- between SAFETY (runs first) and EXTENSION (runs last).
2825
27
  */
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
28
+ declare const DEFAULT_CHECKPOINT_BAND: Band;
2832
29
  /**
2833
- * Options for {@link createXaiProvider}.
2834
- *
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)
30
+ * Per-step context the caller passes through the hook pipeline.
2849
31
  *
2850
- * Ref: FSB v0.10.0-attempt-2 Phase 4 (D-03 + D-07: thin wrapper; reasoning_tokens quirk preserved).
32
+ * Fields are stable identifiers (D-04 carryforward); do NOT populate with
33
+ * user content -- they appear cleartext in the signed receipt body.
2851
34
  *
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
35
+ * - stepName: required. Stable identifier for this step.
36
+ * - stepIndex: required. Monotonically increasing ordinal; caller-owned.
37
+ * - parentStepName: optional. Names the enclosing step when nested.
38
+ * - previousStepName: optional. Names the immediately-prior step in the
39
+ * linked-list timeline (D-09 linked-list threading).
40
+ * - timestamp: required. ISO-8601 RFC 3339.
2856
41
  */
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;
42
+ interface CheckpointHookContext {
43
+ readonly stepName: string;
44
+ readonly stepIndex: number;
45
+ readonly parentStepName?: string;
46
+ readonly previousStepName?: string;
47
+ readonly timestamp: string;
2861
48
  }
2862
49
  /**
2863
- * Phase 34 — QUIRK-02 / NEG-01 / NEG-02 — xAI provider factory.
2864
- *
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
50
+ * The factory's options.
2884
51
  *
2885
- * SECURITY (T-34-03-07): inflight Map MUST use .finally cleanup to prevent
2886
- * leak on rejection. Verifiable: grep `.finally` in this file.
2887
- */
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[];
2904
- readonly usage: Usage;
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
- */
2912
- readonly receipt?: ReceiptEnvelope;
2913
- }
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;
2928
- }
2929
- type RunResult<TOutputs extends OutputContractMap> = RunSuccess<TOutputs> | RunFailure;
2930
- //#endregion
2931
- //#region src/storage/storage.d.ts
2932
- interface ArtifactStore {
2933
- readonly kind: "artifact-store";
2934
- readonly id: string;
2935
- put(artifact: ArtifactInput): Promise<ArtifactRef>;
2936
- get(id: string): Promise<ArtifactRef | undefined>;
2937
- load(id: string): Promise<ArtifactInput | undefined>;
2938
- has(id: string): Promise<boolean>;
2939
- delete(id: string): Promise<boolean>;
2940
- list(): Promise<readonly ArtifactRef[]>;
2941
- }
2942
- type StorageLike = ArtifactStore;
2943
- interface StoredArtifactPayloadDescriptor {
2944
- readonly kind: "json" | "binary";
2945
- readonly path: string;
2946
- }
2947
- interface StoredArtifactEnvelope {
2948
- readonly version: 1;
2949
- readonly ref: ArtifactRef;
2950
- readonly payload?: StoredArtifactPayloadDescriptor;
2951
- }
2952
- //#endregion
2953
- //#region src/runtime/config.d.ts
2954
- interface LatticeConfig {
2955
- readonly providers?: ProviderRegistryInput;
2956
- readonly storage?: StorageLike | false;
2957
- readonly sessions?: SessionStore | false;
2958
- readonly defaults?: {
2959
- readonly policy?: PolicySpec;
2960
- };
2961
- readonly tracing?: TracerLike | false;
2962
- readonly events?: RunEventSink | readonly RunEventSink[];
2963
- /**
2964
- * Phase 9 — when configured, every terminal branch of `ai.run` emits a
2965
- * signed `CapabilityReceipt` attached to `RunResult.receipt`. When absent,
2966
- * no receipts are issued and `RunResult.receipt` is undefined.
2967
- */
2968
- readonly signer?: ReceiptSigner;
2969
- }
2970
- type NormalizedProviderEntry = ProviderRef | ProviderAdapter;
2971
- interface NormalizedLatticeConfig {
2972
- readonly providers: readonly NormalizedProviderEntry[];
2973
- readonly storage?: StorageLike;
2974
- readonly sessions?: SessionStore;
2975
- readonly defaults: {
2976
- readonly policy?: PolicySpec;
2977
- };
2978
- readonly tracing?: TracerLike;
2979
- readonly events: readonly RunEventSink[];
2980
- readonly signer?: ReceiptSigner;
2981
- }
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).
52
+ * - runId: required. Threaded into every receipt body + every tracer event.
53
+ * - tracer: optional. When omitted, the handler still mints (when signer
54
+ * present) but does NOT emit a tracer event. When provided, the handler
55
+ * ALWAYS emits exactly one event per invocation (independent of mint
56
+ * success/failure per D-10).
57
+ * - signer: optional. When omitted, the handler emits a tracer event only
58
+ * (no mint attempted). When provided, the handler attempts to mint via
59
+ * createReceipt(...) inside a try/catch (D-07 best-effort).
60
+ * - sessionId: optional. Threaded into receipt body and event metadata.
61
+ * - model: optional. ReceiptModel descriptor for the receipt body; the
62
+ * factory provides a sensible "step" default when omitted.
63
+ * - route: optional. ReceiptRoute descriptor for the receipt body; the
64
+ * factory provides a sensible "step" default when omitted.
65
+ * - contractVerdict: optional. Defaults to "success" -- step transitions
66
+ * are observability events, not contract evaluations.
3002
67
  */
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. */
68
+ interface CheckpointHookOptions {
69
+ readonly runId: string;
3037
70
  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
3065
- //#region src/runtime/create-ai.d.ts
3066
- interface RuntimeOverrides {
3067
- readonly provider?: string;
3068
- readonly model?: string;
3069
- readonly routingPolicy?: PolicySpec;
3070
- readonly tokenBudget?: number;
3071
- readonly summarizer?: ContextSummarizer;
3072
- readonly transforms?: readonly RuntimeArtifactTransform[];
3073
- readonly hooks?: RuntimeHooks;
3074
- }
3075
- interface RuntimeArtifactTransform {
3076
- readonly name: string;
3077
- transform(input: {
3078
- readonly task: string;
3079
- readonly artifacts: readonly ArtifactInput[];
3080
- }): Promise<ArtifactInput | readonly ArtifactInput[]> | ArtifactInput | readonly ArtifactInput[];
3081
- }
3082
- interface RuntimeHooks {
3083
- readonly beforeProviderCall?: (input: {
3084
- readonly plan: ExecutionPlan;
3085
- readonly request: ProviderRunRequest;
3086
- }) => void | Promise<void>;
3087
- readonly afterProviderCall?: (input: {
3088
- readonly plan: ExecutionPlan;
3089
- readonly response: unknown;
3090
- }) => void | Promise<void>;
3091
- }
3092
- interface RunIntent<TOutputs extends OutputContractMap> {
3093
- readonly task: string;
3094
- readonly artifacts?: readonly ArtifactInput[];
3095
- readonly outputs: TOutputs;
3096
- readonly policy?: PolicySpec;
3097
- readonly session?: SessionRef;
3098
- readonly signal?: AbortSignal;
3099
- readonly overrides?: RuntimeOverrides;
3100
- readonly tools?: readonly ToolDefinition<any>[];
3101
- readonly toolInputs?: Record<string, unknown>;
3102
- readonly contract?: CapabilityContract;
3103
- }
3104
- interface AI {
3105
- session(id: string): SessionRef;
3106
- plan<const TOutputs extends OutputContractMap>(intent: RunIntent<TOutputs>): Promise<ExecutionPlan>;
3107
- run<const TOutputs extends OutputContractMap>(intent: RunIntent<TOutputs>): Promise<RunResult<TOutputs>>;
3108
- /**
3109
- * Phase 19 (v1.2): single-agent execution loop. Drives multiple provider
3110
- * iterations under one call, dispatching tool requests between iterations.
3111
- * Composes with the v1.2 hook pipeline (SAFETY-band veto, OBSERVABILITY-band
3112
- * checkpoint receipts) and the v1.2 capability receipts (when
3113
- * `intent.signer` is provided + `intent.autoRegisterCheckpoint !== false`).
3114
- *
3115
- * See `packages/lattice/src/agent/runtime.ts` for orchestration details.
3116
- */
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>;
3127
- }
3128
- declare function createAI(config?: LatticeConfig): AI;
3129
- //#endregion
3130
- //#region src/replay/replay.d.ts
3131
- interface ReplayEnvelope<TOutputs extends OutputContractMap = OutputContractMap> {
3132
- readonly kind: "replay-envelope";
3133
- readonly version: 1;
3134
- readonly runtimeVersion: string;
3135
- readonly catalogVersion: string;
3136
- readonly createdAt: string;
3137
- readonly plan: ExecutionPlan;
3138
- readonly artifacts: readonly ArtifactRef[];
3139
- readonly outputs?: InferOutputMap<TOutputs>;
3140
- readonly warnings: readonly string[];
3141
- readonly errors: readonly string[];
3142
- readonly usage?: UsageRecord;
3143
- readonly events: readonly RunEvent[];
3144
- /**
3145
- * Phase 10 — optional signed receipt recorded alongside the envelope so a
3146
- * single artifact is sufficient to materialize an offline replay session
3147
- * deterministically. Type-only import — replay.ts stays runtime-import-free
3148
- * of the receipts builder.
3149
- */
3150
- readonly receipt?: ReceiptEnvelope;
3151
- /**
3152
- * Phase 10 — optional contract recorded so replays can re-run pre-flight
3153
- * checks deterministically.
3154
- */
3155
- readonly contract?: CapabilityContract;
3156
- }
3157
- declare function createReplayEnvelope<TOutputs extends OutputContractMap>(result: RunResult<TOutputs>): ReplayEnvelope<TOutputs>;
3158
- declare function replayOffline<TOutputs extends OutputContractMap>(envelope: ReplayEnvelope<TOutputs>): Promise<RunResult<TOutputs>>;
3159
- declare function rerunLive<TOutputs extends OutputContractMap>(ai: AI, envelope: ReplayEnvelope<TOutputs>, intent: RunIntent<TOutputs>): Promise<RunResult<TOutputs>>;
3160
- declare function redactReplayEnvelope<TOutputs extends OutputContractMap>(envelope: ReplayEnvelope<TOutputs>): ReplayEnvelope<TOutputs>;
3161
- declare function redactPlan(plan: ExecutionPlan): ExecutionPlan;
3162
- declare function redactArtifactRef(ref: ArtifactRef): ArtifactRef;
3163
- //#endregion
3164
- //#region src/replay/materialize.d.ts
3165
- /**
3166
- * Discriminated union of materialization failure modes.
3167
- *
3168
- * - "verify-failed" — receipt failed verifyReceipt (signature, key
3169
- * missing/revoked, canonicalization mismatch).
3170
- * - "artifact-load-failed" — the artifactLoader callback rejected for at
3171
- * least one input hash.
3172
- * - "envelope-malformed" — receipt verified but the verified body is
3173
- * structurally unusable (should never happen
3174
- * under verifyReceipt invariants, but kept as a
3175
- * defensive third branch).
3176
- */
3177
- interface MaterializationError {
3178
- readonly kind: "verify-failed" | "artifact-load-failed" | "envelope-malformed";
3179
- readonly message: string;
3180
- }
3181
- /**
3182
- * Async callback that resolves an artifact body from its sha256 hex digest.
3183
- * Phase 10 ships only the in-memory variant for tests. Phase 11's CLI plugs
3184
- * in a filesystem-backed loader reading from `.lattice/fixtures/<sha256>.bin`.
3185
- */
3186
- type ArtifactLoader = (hash: string) => Promise<ArtifactInput>;
3187
- interface MaterializeReplayEnvelopeOptions<TOutputs extends OutputContractMap = OutputContractMap> {
3188
- readonly artifactLoader: ArtifactLoader;
3189
- readonly keySet: KeySet;
3190
- /** Optional original task string. Defaults to "" when omitted. */
3191
- readonly task?: string;
3192
- /**
3193
- * Optional caller-supplied outputs map. When provided, the resulting
3194
- * `ReplayEnvelope.outputs` is populated and `replayOffline` will return
3195
- * an `ok: true` result. When omitted, `replayOffline` reports an
3196
- * `execution_unavailable` failure (current Phase 5 semantics).
3197
- */
3198
- readonly outputs?: InferOutputMap<TOutputs>;
3199
- readonly policy?: PolicySpec;
3200
- readonly contract?: CapabilityContract;
71
+ readonly signer?: ReceiptSigner;
72
+ readonly sessionId?: string;
73
+ readonly model?: ReceiptModel;
74
+ readonly route?: ReceiptRoute;
75
+ readonly contractVerdict?: CreateReceiptInput["contractVerdict"];
3201
76
  }
3202
77
  /**
3203
- * Pure async function that reconstructs a `ReplayEnvelope` from a receipt.
3204
- *
3205
- * Verify-FIRST ordering: `verifyReceipt` runs before `artifactLoader` is
3206
- * touched. Tampered receipts MUST NOT cause loader side effects.
3207
- */
3208
- declare function materializeReplayEnvelope<TOutputs extends OutputContractMap = OutputContractMap>(receipt: ReceiptEnvelope, options: MaterializeReplayEnvelopeOptions<TOutputs>): Promise<ReplayEnvelope<TOutputs>>;
3209
- //#endregion
3210
- //#region src/agent/runtime.d.ts
3211
- /**
3212
- * Resolves the runtime's behaviour for a single `ai.runAgent(intent)` call.
78
+ * Build a checkpoint hook handler.
3213
79
  *
3214
- * Phase 19 ships an in-process default scheduler (the loop runs in the
3215
- * calling Promise), direct transport (provider.execute()), and in-memory
3216
- * transcript (the `conversation` array). Phase 20 promotes scheduler /
3217
- * transport / storage to the pluggable `AgentHost` adapter.
80
+ * The returned handler is suitable for registration on a HookPipeline
81
+ * created via createHookPipeline (see ./bands.ts). The handler does not
82
+ * auto-register; the caller passes it to pipeline.register(...) with the
83
+ * desired lifecycle event (typically AFTER_TOOL or BEFORE_TOOL) and band
84
+ * (typically BAND.OBSERVABILITY, exported as DEFAULT_CHECKPOINT_BAND).
3218
85
  *
3219
- * Phase 39: `runAgent` is a thin public wrapper over `runAgentInternal`
3220
- * with no internal options the public signature and behavior are
3221
- * unchanged.
3222
- */
3223
- declare function runAgent<TOutputs extends OutputContractMap = OutputContractMap>(intent: AgentIntent<TOutputs>, config?: LatticeConfig): Promise<AgentResult<TOutputs>>;
3224
- //#endregion
3225
- //#region src/agent/infra/cost-tracker.d.ts
3226
- type CostBudgetStatus = "ok" | "warning" | "exceeded";
3227
- interface CostTracker {
3228
- readonly kind: "cost-tracker";
3229
- /** Append a per-iteration Usage record. Mutates internal state. */
3230
- recordIteration(usage: Usage): void;
3231
- /** Returns the running sum across all recorded iterations. */
3232
- total(): Usage;
3233
- /**
3234
- * Reports budget status against `contract.budget`:
3235
- * - "ok" — under 80% of maxCostUsd.
3236
- * - "warning" — at or over 80% but under 100%.
3237
- * - "exceeded" — at or over 100% of maxCostUsd.
3238
- * Returns "ok" when no budget is declared or when cumulative cost is null.
3239
- */
3240
- budgetStatus(budget?: BudgetInvariant): CostBudgetStatus;
3241
- }
3242
- declare function createCostTracker(): CostTracker;
3243
- //#endregion
3244
- //#region src/agent/infra/transcript-store.d.ts
3245
- /**
3246
- * Token estimator used by `tailByTokens`. The default ~4 chars / token is
3247
- * the OpenAI rule of thumb for English text. Callers with provider-specific
3248
- * tokenizers can supply their own.
3249
- */
3250
- type TokenEstimator = (text: string) => number;
3251
- interface TranscriptStore {
3252
- readonly kind: "transcript-store";
3253
- append(turn: ConversationTurn): void;
3254
- all(): readonly ConversationTurn[];
3255
- /** Returns the first user turn (if any) + the most-recent `limit` turns. */
3256
- tail(limit: number): readonly ConversationTurn[];
3257
- /**
3258
- * Returns the first user turn (if any) + the most-recent turns whose
3259
- * combined token estimate fits within `maxTokens`. The default estimator
3260
- * is the ~4 chars / token rule; callers can override for provider-
3261
- * specific tokenizers.
3262
- */
3263
- tailByTokens(maxTokens: number, estimator?: TokenEstimator): readonly ConversationTurn[];
3264
- }
3265
- declare function createTranscriptStore(): TranscriptStore;
3266
- //#endregion
3267
- //#region src/agent/infra/goal-progress.d.ts
3268
- /**
3269
- * GoalProgressTracker — Phase 21 (v1.2).
86
+ * Per-invocation behavior:
87
+ * 1. Build event metadata from options + per-call context.
88
+ * 2. If signer is configured, attempt createReceipt(...) inside a
89
+ * try/catch. On success, set metadata.receiptId + metadata.envelope.
90
+ * On failure, set metadata.mintError (string from caught error).
91
+ * 3. If tracer is configured, emit exactly one tracer.event?.(
92
+ * STEP_TRANSITION_EVENT_NAME, metadata) call.
93
+ * 4. Return void.
3270
94
  *
3271
- * Stuck-detection primitive. The caller declares a goal-satisfaction
3272
- * score per iteration (0..1); the tracker reports a coarse status the
3273
- * agent loop can use to back off or surface to the human.
95
+ * NO upstream throw (D-07). NO global mutation (D-05).
3274
96
  */
3275
- type ProgressStatus = "progressing" | "stalled" | "regressed";
3276
- interface GoalProgressOptions {
3277
- /**
3278
- * Window of recent steps used for stall + regression detection.
3279
- * Default 3. The tracker waits until it has at least this many steps
3280
- * before reporting anything other than "progressing".
3281
- */
3282
- readonly windowSize?: number;
3283
- /** Max satisfaction delta across the window to count as "stalled". Default 0.02. */
3284
- readonly stallThreshold?: number;
3285
- /** Min drop from prior max to count as "regressed". Default 0.1. */
3286
- readonly regressionThreshold?: number;
3287
- }
3288
- interface GoalProgressStep {
3289
- readonly iterationIndex: number;
3290
- readonly goalSatisfaction: number;
3291
- }
3292
- interface GoalProgressTracker {
3293
- readonly kind: "goal-progress-tracker";
3294
- recordStep(step: GoalProgressStep): void;
3295
- status(): ProgressStatus;
3296
- }
3297
- declare function createGoalProgressTracker(options?: GoalProgressOptions): GoalProgressTracker;
97
+ declare function createCheckpointHook(options: CheckpointHookOptions): HookHandler<CheckpointHookContext>;
3298
98
  //#endregion
3299
- //#region src/agent/infra/action-history.d.ts
99
+ //#region src/providers/no-public-url.d.ts
3300
100
  /**
3301
- * ActionHistory Phase 21 (v1.2).
3302
- *
3303
- * Detects stuck patterns in the agent loop's tool-call sequence:
3304
- * - "consecutive-identical-tool-call" — same (toolName, argsHash) N+ times in a row
3305
- * - "ping-pong" — last 4 records alternate between 2 distinct (toolName, argsHash) pairs
3306
- * - "no-progress" — reserved for callers wiring goal-progress feedback here
101
+ * Thrown when a run with `policy.noPublicUrl: true` is about to dispatch a
102
+ * request whose serialized body still contains a public http(s) URL derived
103
+ * from `request.artifacts` (value or string metadata entry).
3307
104
  *
3308
- * Standalone (no dependency on the agent runtime); callers register the
3309
- * primitive externally and pump `recordAction` from their loop or hook.
3310
- */
3311
- declare const STUCK_REASONS: readonly ["consecutive-identical-tool-call", "no-progress", "ping-pong"];
3312
- type StuckReason = typeof STUCK_REASONS[number];
3313
- interface ActionRecord {
3314
- readonly iterationIndex: number;
3315
- readonly toolName: string;
3316
- readonly argsHash: string;
3317
- }
3318
- interface ActionHistoryOptions {
3319
- /** Number of consecutive identical records that triggers the consecutive detector. Default 3. */
3320
- readonly consecutiveLimit?: number;
3321
- }
3322
- interface ActionHistory {
3323
- readonly kind: "action-history";
3324
- /**
3325
- * Append a record. Returns the latest StuckReason triggered by this
3326
- * record, or null when no detector fires. The most recent reason wins
3327
- * when multiple apply.
3328
- */
3329
- recordAction(action: ActionRecord): StuckReason | null;
3330
- history(): readonly ActionRecord[];
3331
- }
3332
- declare function createActionHistory(options?: ActionHistoryOptions): ActionHistory;
3333
- //#endregion
3334
- //#region src/agent/infra/permission-context.d.ts
3335
- interface PermissionRule {
3336
- /** Match on tool name. String = exact match; RegExp = test. Both undefined = match-any. */
3337
- readonly toolName?: string | RegExp;
3338
- /**
3339
- * Optional resource matcher. The caller passes `resource` on each
3340
- * decide() invocation; this rule fires only when the rule's resource
3341
- * matches.
3342
- */
3343
- readonly resource?: string | RegExp;
3344
- readonly verdict: "allow" | "deny";
3345
- readonly reason?: string;
3346
- }
3347
- interface PermissionDecisionInput {
3348
- readonly toolName: string;
3349
- readonly iterationIndex: number;
3350
- readonly resource?: string;
3351
- readonly args?: unknown;
3352
- }
3353
- type PermissionVerdict = {
3354
- readonly allow: true;
3355
- } | {
3356
- readonly allow: false;
3357
- readonly reason: string;
3358
- };
3359
- interface PermissionContext {
3360
- readonly kind: "permission-context";
3361
- decide(input: PermissionDecisionInput): PermissionVerdict;
3362
- }
3363
- declare function createPermissionContext(rules: readonly PermissionRule[]): PermissionContext;
3364
- /**
3365
- * Hook handler shape suitable for registering on `BEFORE_TOOL` at
3366
- * BAND.SAFETY. Reads `toolName` and `iterationIndex` from the agent
3367
- * runtime's BEFORE_TOOL context shape (`{ iterationIndex, toolName,
3368
- * args }`) and translates a deny verdict into `controls.deny(reason)`.
3369
- */
3370
- interface PermissionHookContext {
3371
- readonly iterationIndex: number;
3372
- readonly toolName: string;
3373
- readonly resource?: string;
3374
- readonly args?: unknown;
3375
- }
3376
- declare function createPermissionGuardHook(context: PermissionContext): HookHandler<PermissionHookContext>;
3377
- /**
3378
- * Convenience: returns RegisterOptions for the SAFETY-band registration.
3379
- * Callers do `pipeline.register("BEFORE_TOOL", hook, permissionGuardRegisterOptions())`.
105
+ * This is the single shared egress error class for all three adapter families
106
+ * (OpenAI-compatible, Anthropic, Gemini). Callers may `instanceof`-check it.
3380
107
  */
3381
- declare function permissionGuardRegisterOptions(): RegisterOptions;
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>;
108
+ declare class NoPublicUrlEgressError extends Error {
109
+ readonly providerId: string;
110
+ readonly artifactId: string;
111
+ readonly offendingUrl: string;
112
+ constructor(providerId: string, artifactId: string, offendingUrl: string);
3413
113
  }
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
114
  //#endregion
3450
115
  //#region src/realtime/realtime.d.ts
3451
116
  declare const REALTIME_DIRECTION_SUPPORT_LEVEL: "direction-only";
@@ -3505,116 +170,8 @@ declare function createRealtimeCheckpointContext(input: RealtimeCheckpointInput)
3505
170
  declare function createRealtimeReceiptDescriptors(spec: RealtimeSessionSpec): RealtimeReceiptDescriptors;
3506
171
  declare function realtimeStepName(provider: RealtimeProviderKind, checkpoint: RealtimeCheckpointKind): string;
3507
172
  //#endregion
3508
- //#region src/agent/eval.d.ts
3509
- /**
3510
- * Summary of an agent run sufficient for regression analysis. Callers
3511
- * typically derive this from an `AgentSuccess` via `iterations.length` and
3512
- * cumulative `usage`. The schema is intentionally minimal so callers can
3513
- * persist + load it across runs without dragging the full ReplayEnvelope.
3514
- */
3515
- interface AgentRunSnapshot {
3516
- readonly iterationsToGoal: number;
3517
- readonly usage: Usage;
3518
- }
3519
- interface EvalOptions {
3520
- /**
3521
- * Maximum tolerated INCREASE in iterations-to-goal versus the baseline.
3522
- * Default 1 (one extra iteration tolerated). Set to 0 to require parity.
3523
- */
3524
- readonly iterationsToGoalRegressionLimit?: number;
3525
- /**
3526
- * Maximum tolerated FRACTIONAL cost increase versus the baseline.
3527
- * Default 0.10 (10% increase tolerated). Compared as
3528
- * `(current - baseline) / baseline`. Cost regressions are only
3529
- * considered when BOTH snapshots have a non-null `costUsd`; mixed-cost
3530
- * snapshots emit a `mixed-cost-unknown` regression so callers can decide
3531
- * how to handle them.
3532
- */
3533
- readonly costUsdRegressionLimit?: number;
3534
- }
3535
- type EvalRegressionKind = "iterations-to-goal" | "cost-regression" | "mixed-cost-unknown";
3536
- interface EvalRegression {
3537
- readonly kind: EvalRegressionKind;
3538
- readonly baseline: number | null;
3539
- readonly current: number | null;
3540
- readonly limit: number;
3541
- readonly message: string;
3542
- }
3543
- interface AgentEvalResult {
3544
- readonly ok: boolean;
3545
- readonly regressions: ReadonlyArray<EvalRegression>;
3546
- }
3547
- declare function evalAgentRun(baseline: AgentRunSnapshot, current: AgentRunSnapshot, options?: EvalOptions): AgentEvalResult;
3548
- //#endregion
3549
- //#region src/storage/local.d.ts
3550
- interface LocalArtifactStoreOptions {
3551
- readonly id?: string;
3552
- }
3553
- declare function createLocalArtifactStore(rootDir: string | URL, options?: LocalArtifactStoreOptions): ArtifactStore;
3554
- //#endregion
3555
- //#region src/storage/memory.d.ts
3556
- interface MemoryArtifactStoreOptions {
3557
- readonly id?: string;
3558
- }
3559
- declare function createMemoryArtifactStore(options?: MemoryArtifactStoreOptions): ArtifactStore;
3560
- //#endregion
3561
173
  //#region src/version.d.ts
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;
174
+ declare const latticeVersion = "1.5.0";
3618
175
  //#endregion
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 };
176
+ 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 ExternalExecutionAuditInput, type ExternalExecutionAuditResult, type ExternalExecutionMetadata, type ExternalExecutionSidecar, type ExternalExecutionSidecarOutputSpec, type ExternalExecutionUsage, 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, createExternalExecutionAudit, 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 };
3620
177
  //# sourceMappingURL=index.d.ts.map