@full-self-browsing/lattice 1.3.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 +78 -3234
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +365 -8434
  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-DDznbc3G.js → run-crew-B2fQLmgB.js} +16 -23
  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-BTi8lr_O.js → runtime-Dxiet5YS.js} +100 -640
  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 +105 -6
  107. package/dist/run-crew-DDznbc3G.js.map +0 -1
  108. package/dist/runtime-BTi8lr_O.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replay-CtIhpLek.js","names":["fail"],"sources":["../src/observability/otel.ts","../src/receipts/keyset.ts","../src/receipts/remote-signer.ts","../src/receipts/sign.ts","../src/receipts/verify.ts","../src/version.ts","../src/audit/external-execution.ts","../src/replay/materialize.ts","../src/replay/replay.ts"],"sourcesContent":["import { receiptCid } from \"../receipts/cid.js\";\nimport type { ReceiptEnvelope } from \"../receipts/types.js\";\nimport type { RunEvent, RunEventSink } from \"../tracing/tracing.js\";\n\nexport type OtelAttributeValue =\n | string\n | number\n | boolean\n | readonly string[]\n | readonly number[]\n | readonly boolean[];\n\nexport type OtelAttributes = Record<string, OtelAttributeValue>;\n\nexport interface OtelSpanStatus {\n readonly code: number;\n readonly message?: string;\n}\n\nexport interface OtelSpanLike {\n setAttribute?(key: string, value: OtelAttributeValue): unknown;\n setAttributes?(attributes: OtelAttributes): unknown;\n addEvent?(name: string, attributes?: OtelAttributes): unknown;\n setStatus?(status: OtelSpanStatus): unknown;\n recordException?(error: Error | string | Record<string, unknown>): unknown;\n end?(endTime?: Date | number): unknown;\n}\n\nexport interface OtelTracerLike {\n startSpan(\n name: string,\n options?: {\n readonly attributes?: OtelAttributes;\n readonly startTime?: Date | number;\n },\n ): OtelSpanLike;\n}\n\nexport type OtelContentCaptureMode = \"none\" | \"metadata\";\n\nexport interface OtelSanitizerOptions {\n readonly contentCapture?: OtelContentCaptureMode;\n}\n\nexport interface OtelRunEventSinkOptions extends OtelSanitizerOptions {\n readonly tracer: OtelTracerLike;\n readonly spanName?: string;\n}\n\nexport interface OtelHttpTraceConfig {\n readonly endpoint: string;\n readonly headers: Record<string, string>;\n}\n\nexport interface LangfuseOtlpConfigOptions {\n readonly baseUrl?: string;\n readonly publicKey?: string;\n readonly secretKey?: string;\n readonly authString?: string;\n readonly ingestionVersion?: string;\n readonly headers?: Record<string, string>;\n}\n\nexport interface PhoenixOtlpConfigOptions {\n readonly baseUrl?: string;\n readonly endpoint?: string;\n readonly apiKey?: string;\n readonly projectName?: string;\n readonly headers?: Record<string, string>;\n}\n\nconst DEFAULT_SPAN_NAME = \"lattice.run\";\nconst DEFAULT_LANGFUSE_BASE_URL = \"https://cloud.langfuse.com\";\nconst DEFAULT_PHOENIX_BASE_URL = \"http://localhost:6006\";\nconst OTEL_STATUS_OK = 1;\nconst OTEL_STATUS_ERROR = 2;\nconst SECRET_KEY_RE = /api[-_]?key|authorization|credentials?|headers?|password|secret|token/iu;\nconst CONTENT_KEY_RE = /artifact|body|content|input|inputs|message|messages|output|outputs|payload|prompt|rawOutputs|task|value/iu;\n\nexport function createOtelRunEventSink(\n options: OtelRunEventSinkOptions,\n): RunEventSink {\n const spans = new Map<string, OtelSpanLike>();\n\n return async (event) => {\n const span = getOrCreateRunSpan(event, options, spans);\n const attributes = await createRunEventAttributes(event, options);\n setSpanAttributes(span, attributes);\n span.addEvent?.(`lattice.${event.kind}`, attributes);\n\n if (event.kind === \"capabilities.negotiation.fallback\") {\n span.setStatus?.({ code: OTEL_STATUS_OK });\n span.end?.(eventTime(event));\n spans.delete(event.runId);\n return;\n }\n\n if (event.kind === \"run.complete\") {\n span.setStatus?.({ code: OTEL_STATUS_OK });\n span.end?.(eventTime(event));\n spans.delete(event.runId);\n return;\n }\n\n if (event.kind === \"run.failed\") {\n const message = metadataString(event, \"reason\");\n span.setStatus?.({\n code: OTEL_STATUS_ERROR,\n ...(message !== undefined ? { message } : {}),\n });\n if (message !== undefined) {\n span.recordException?.(message);\n }\n span.end?.(eventTime(event));\n spans.delete(event.runId);\n }\n };\n}\n\nexport function sanitizeRunEventAttributes(\n event: RunEvent,\n options: OtelSanitizerOptions = {},\n): OtelAttributes {\n const attributes: OtelAttributes = {\n \"lattice.event.kind\": event.kind,\n \"lattice.run.id\": event.runId,\n };\n\n assignString(attributes, \"lattice.plan.id\", event.planId);\n assignString(attributes, \"lattice.stage.id\", event.stageId);\n assignString(attributes, \"lattice.provider.id\", event.providerId);\n assignString(attributes, \"lattice.model.id\", event.modelId);\n assignString(attributes, \"lattice.artifact.id\", event.artifactId);\n assignString(attributes, \"gen_ai.provider.name\", event.providerId);\n assignString(attributes, \"gen_ai.request.model\", event.modelId);\n\n if (event.kind === \"stream.start\" || event.kind === \"stream.complete\" || event.kind === \"stream.failed\") {\n attributes[\"gen_ai.request.stream\"] = true;\n }\n\n const metadata = event.metadata ?? {};\n assignString(attributes, \"lattice.event.status\", metadataString(event, \"status\"));\n assignBoolean(attributes, \"lattice.error.present\", metadataString(event, \"error\") !== undefined ? true : undefined);\n assignString(attributes, \"lattice.failure.reason\", metadataString(event, \"reason\"));\n assignString(attributes, \"lattice.tripwire.invariant_id\", asString(metadata.invariantId));\n assignString(attributes, \"lattice.artifact.source\", asString(metadata.source));\n assignString(attributes, \"lattice.receipt.id\", asString(metadata.receiptId));\n assignBoolean(attributes, \"lattice.receipt.mint_error.present\", asString(metadata.mintError) !== undefined ? true : undefined);\n assignString(attributes, \"lattice.route.selected_model\", asString(metadata.selected));\n assignNumber(attributes, \"lattice.route.rejected.count\", asNumber(metadata.rejected));\n assignNumber(attributes, \"lattice.route.fallback.count\", asNumber(metadata.fallbacks));\n assignBoolean(attributes, \"lattice.provider.attempt.fallback\", asBoolean(metadata.fallback));\n assignNumber(attributes, \"lattice.context.estimated_tokens\", asNumber(metadata.estimatedTokens));\n assignNumber(attributes, \"lattice.context.included.count\", asNumber(metadata.included));\n assignNumber(attributes, \"lattice.context.summarized.count\", asNumber(metadata.summarized));\n assignNumber(attributes, \"lattice.context.omitted.count\", asNumber(metadata.omitted));\n assignString(attributes, \"lattice.tool.name\", asString(metadata.toolName));\n assignString(attributes, \"lattice.tool.call.id\", asString(metadata.callId));\n assignStringArray(attributes, \"lattice.output.names\", asStringArray(metadata.outputNames));\n assignUsage(attributes, metadata);\n assignGateway(attributes, metadata.gateway);\n captureSafeMetadata(attributes, metadata, options);\n\n return attributes;\n}\n\nexport async function createOtelReceiptAttributes(\n envelope: ReceiptEnvelope,\n): Promise<OtelAttributes> {\n const attributes: OtelAttributes = {\n \"lattice.receipt.cid\": await receiptCid(envelope),\n \"lattice.receipt.signature.count\": envelope.signatures.length,\n };\n assignString(\n attributes,\n \"lattice.receipt.signature.keyid\",\n envelope.signatures[0]?.keyid,\n );\n return attributes;\n}\n\nexport function createLangfuseOtlpConfig(\n options: LangfuseOtlpConfigOptions = {},\n): OtelHttpTraceConfig {\n const authString = langfuseAuthString(options);\n return {\n endpoint: langfuseTraceEndpoint(options.baseUrl ?? DEFAULT_LANGFUSE_BASE_URL),\n headers: {\n ...(authString !== undefined ? { Authorization: `Basic ${authString}` } : {}),\n \"x-langfuse-ingestion-version\": options.ingestionVersion ?? \"4\",\n ...(options.headers ?? {}),\n },\n };\n}\n\nexport function createPhoenixOtlpConfig(\n options: PhoenixOtlpConfigOptions = {},\n): OtelHttpTraceConfig {\n return {\n endpoint: options.endpoint ?? phoenixTraceEndpoint(options.baseUrl ?? DEFAULT_PHOENIX_BASE_URL),\n headers: {\n ...(options.apiKey !== undefined ? { Authorization: `Bearer ${options.apiKey}` } : {}),\n ...(options.projectName !== undefined ? { \"x-project-name\": options.projectName } : {}),\n ...(options.headers ?? {}),\n },\n };\n}\n\nfunction getOrCreateRunSpan(\n event: RunEvent,\n options: OtelRunEventSinkOptions,\n spans: Map<string, OtelSpanLike>,\n): OtelSpanLike {\n const existing = spans.get(event.runId);\n if (existing !== undefined) {\n return existing;\n }\n\n const span = options.tracer.startSpan(options.spanName ?? DEFAULT_SPAN_NAME, {\n attributes: sanitizeRunEventAttributes(event, options),\n startTime: eventTime(event),\n });\n spans.set(event.runId, span);\n return span;\n}\n\nfunction setSpanAttributes(span: OtelSpanLike, attributes: OtelAttributes): void {\n if (span.setAttributes !== undefined) {\n span.setAttributes(attributes);\n return;\n }\n\n for (const [key, value] of Object.entries(attributes)) {\n span.setAttribute?.(key, value);\n }\n}\n\nasync function createRunEventAttributes(\n event: RunEvent,\n options: OtelSanitizerOptions,\n): Promise<OtelAttributes> {\n const attributes = sanitizeRunEventAttributes(event, options);\n const envelope = findReceiptEnvelope(event.metadata);\n if (envelope === undefined) {\n return attributes;\n }\n\n try {\n return {\n ...attributes,\n ...(await createOtelReceiptAttributes(envelope)),\n };\n } catch {\n return attributes;\n }\n}\n\nfunction eventTime(event: RunEvent): Date {\n return new Date(event.timestamp);\n}\n\nfunction metadataString(event: RunEvent, key: string): string | undefined {\n return asString(event.metadata?.[key]);\n}\n\nfunction assignString(\n attributes: OtelAttributes,\n key: string,\n value: string | undefined,\n): void {\n if (value !== undefined) {\n attributes[key] = value;\n }\n}\n\nfunction assignNumber(\n attributes: OtelAttributes,\n key: string,\n value: number | undefined,\n): void {\n if (value !== undefined) {\n attributes[key] = value;\n }\n}\n\nfunction assignBoolean(\n attributes: OtelAttributes,\n key: string,\n value: boolean | undefined,\n): void {\n if (value !== undefined) {\n attributes[key] = value;\n }\n}\n\nfunction assignStringArray(\n attributes: OtelAttributes,\n key: string,\n value: readonly string[] | undefined,\n): void {\n if (value !== undefined && value.length > 0) {\n attributes[key] = value;\n }\n}\n\nfunction assignNumberArray(\n attributes: OtelAttributes,\n key: string,\n value: readonly number[] | undefined,\n): void {\n if (value !== undefined && value.length > 0) {\n attributes[key] = value;\n }\n}\n\nfunction assignBooleanArray(\n attributes: OtelAttributes,\n key: string,\n value: readonly boolean[] | undefined,\n): void {\n if (value !== undefined && value.length > 0) {\n attributes[key] = value;\n }\n}\n\nfunction asString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nfunction asNumber(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nfunction asBoolean(value: unknown): boolean | undefined {\n return typeof value === \"boolean\" ? value : undefined;\n}\n\nfunction asStringArray(value: unknown): readonly string[] | undefined {\n return Array.isArray(value) && value.every((item) => typeof item === \"string\")\n ? value\n : undefined;\n}\n\nfunction asNumberArray(value: unknown): readonly number[] | undefined {\n return Array.isArray(value) && value.every((item) => typeof item === \"number\" && Number.isFinite(item))\n ? value\n : undefined;\n}\n\nfunction asBooleanArray(value: unknown): readonly boolean[] | undefined {\n return Array.isArray(value) && value.every((item) => typeof item === \"boolean\")\n ? value\n : undefined;\n}\n\nfunction assignUsage(attributes: OtelAttributes, metadata: Record<string, unknown>): void {\n const usage = usageFrom(metadata.normalizedUsage)\n ?? usageFrom(metadata.usage)\n ?? usageFrom(metadata);\n\n if (usage === undefined) {\n return;\n }\n\n assignNumber(attributes, \"gen_ai.usage.input_tokens\", usage.inputTokens);\n assignNumber(attributes, \"gen_ai.usage.output_tokens\", usage.outputTokens);\n assignNumber(attributes, \"llm.token_count.prompt\", usage.inputTokens);\n assignNumber(attributes, \"llm.token_count.completion\", usage.outputTokens);\n assignNumber(attributes, \"lattice.usage.cost_usd\", usage.costUsd);\n}\n\nfunction usageFrom(value: unknown):\n | {\n readonly inputTokens?: number;\n readonly outputTokens?: number;\n readonly costUsd?: number;\n }\n | undefined {\n if (!isRecord(value)) {\n return undefined;\n }\n\n const inputTokens = asNumber(value.promptTokens) ?? asNumber(value.inputTokens);\n const outputTokens = asNumber(value.completionTokens) ?? asNumber(value.outputTokens);\n const costUsd = asNumber(value.costUsd);\n\n if (inputTokens === undefined && outputTokens === undefined && costUsd === undefined) {\n return undefined;\n }\n\n return {\n ...(inputTokens !== undefined ? { inputTokens } : {}),\n ...(outputTokens !== undefined ? { outputTokens } : {}),\n ...(costUsd !== undefined ? { costUsd } : {}),\n };\n}\n\nfunction assignGateway(attributes: OtelAttributes, value: unknown): void {\n if (!isRecord(value)) {\n return;\n }\n\n assignBoolean(attributes, \"lattice.gateway.used\", asBoolean(value.used));\n assignString(attributes, \"lattice.gateway.provider.id\", asString(value.providerId));\n assignString(attributes, \"lattice.gateway.selected_provider.id\", asString(value.selectedProviderId));\n assignString(attributes, \"lattice.gateway.requested_model\", asString(value.requestedModel));\n assignString(attributes, \"lattice.gateway.observed_model\", asString(value.observedModel));\n assignStringArray(attributes, \"lattice.gateway.fallback_models\", asStringArray(value.fallbackModels));\n\n const requestedModel = asString(value.requestedModel);\n const observedModel = asString(value.observedModel);\n if (requestedModel !== undefined && attributes[\"gen_ai.request.model\"] === undefined) {\n attributes[\"gen_ai.request.model\"] = requestedModel;\n }\n assignString(attributes, \"gen_ai.response.model\", observedModel);\n}\n\nfunction captureSafeMetadata(\n attributes: OtelAttributes,\n metadata: Record<string, unknown>,\n options: OtelSanitizerOptions,\n): void {\n if (options.contentCapture !== \"metadata\") {\n return;\n }\n\n const knownKeys = new Set([\n \"callId\",\n \"estimatedTokens\",\n \"error\",\n \"fallback\",\n \"fallbacks\",\n \"gateway\",\n \"included\",\n \"invariantId\",\n \"mintError\",\n \"normalizedUsage\",\n \"omitted\",\n \"outputNames\",\n \"reason\",\n \"receiptId\",\n \"rejected\",\n \"selected\",\n \"source\",\n \"status\",\n \"summarized\",\n \"toolName\",\n \"usage\",\n ]);\n\n for (const [key, value] of Object.entries(metadata)) {\n if (knownKeys.has(key) || isUnsafeMetadataKey(key)) {\n continue;\n }\n const attrKey = `lattice.metadata.${safeAttributeKey(key)}`;\n assignString(attributes, attrKey, asString(value));\n assignNumber(attributes, attrKey, asNumber(value));\n assignBoolean(attributes, attrKey, asBoolean(value));\n assignStringArray(attributes, attrKey, asStringArray(value));\n assignNumberArray(attributes, attrKey, asNumberArray(value));\n assignBooleanArray(attributes, attrKey, asBooleanArray(value));\n }\n}\n\nfunction isUnsafeMetadataKey(key: string): boolean {\n return SECRET_KEY_RE.test(key) || CONTENT_KEY_RE.test(key);\n}\n\nfunction safeAttributeKey(key: string): string {\n return key.replace(/[^a-zA-Z0-9_.-]+/gu, \"_\");\n}\n\nfunction findReceiptEnvelope(metadata: Record<string, unknown> | undefined): ReceiptEnvelope | undefined {\n if (metadata === undefined) {\n return undefined;\n }\n\n const candidates = [metadata.envelope, metadata.receiptEnvelope, metadata.receipt];\n return candidates.find(isReceiptEnvelope);\n}\n\nfunction isReceiptEnvelope(value: unknown): value is ReceiptEnvelope {\n return (\n isRecord(value) &&\n value.payloadType === \"application/vnd.lattice.receipt+json\" &&\n typeof value.payload === \"string\" &&\n Array.isArray(value.signatures) &&\n value.signatures.every((signature) =>\n isRecord(signature) &&\n typeof signature.keyid === \"string\" &&\n typeof signature.sig === \"string\",\n )\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction langfuseAuthString(options: LangfuseOtlpConfigOptions): string | undefined {\n if (options.authString !== undefined) {\n return options.authString;\n }\n\n if (options.publicKey === undefined && options.secretKey === undefined) {\n return undefined;\n }\n\n if (options.publicKey === undefined || options.secretKey === undefined) {\n throw new Error(\"Langfuse OTLP auth requires both publicKey and secretKey.\");\n }\n\n return base64Utf8(`${options.publicKey}:${options.secretKey}`);\n}\n\nfunction langfuseTraceEndpoint(baseUrl: string): string {\n const base = trimTrailingSlashes(baseUrl);\n if (base.endsWith(\"/api/public/otel/v1/traces\")) {\n return base;\n }\n if (base.endsWith(\"/api/public/otel\")) {\n return `${base}/v1/traces`;\n }\n return `${base}/api/public/otel/v1/traces`;\n}\n\nfunction phoenixTraceEndpoint(baseUrl: string): string {\n const base = trimTrailingSlashes(baseUrl);\n if (base.endsWith(\"/v1/traces\")) {\n return base;\n }\n return `${base}/v1/traces`;\n}\n\nfunction trimTrailingSlashes(value: string): string {\n return value.replace(/\\/+$/u, \"\");\n}\n\nfunction base64Utf8(value: string): string {\n const bytes = new TextEncoder().encode(value);\n let binary = \"\";\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary);\n}\n","import type { KeyEntry, KeySet } from \"./types.js\";\n\n/**\n * In-memory KeySet factory.\n *\n * Verification flow (plan 09-03):\n * - keySet.lookup(kid) returns undefined → VerifyError {kind: \"key-not-found\"}\n * - entry.state === \"revoked\" → VerifyError {kind: \"key-revoked\"}\n * - entry.state === \"retired\" → VerifyOk + keyState: \"retired\" (caller may warn)\n * - entry.state === \"active\" → VerifyOk + keyState: \"active\"\n *\n * Duplicate kids: last write wins (deterministic — callers control entry order).\n * Empty entries array is legal — every lookup returns undefined.\n * Returned KeySet exposes only `lookup` — no enumeration.\n *\n * See 09-CONTEXT.md \"Key Management (UNRETROFITTABLE)\".\n */\nexport function createMemoryKeySet(entries: readonly KeyEntry[]): KeySet {\n const byKid = new Map<string, KeyEntry>();\n for (const entry of entries) {\n byKid.set(entry.kid, entry);\n }\n return {\n lookup(kid: string): KeyEntry | undefined {\n return byKid.get(kid);\n },\n };\n}\n","import type { ReceiptSigner } from \"./types.js\";\n\nexport type RemoteReceiptSignerProvider =\n | \"aws-kms\"\n | \"gcp-kms\"\n | \"external-kms\"\n | (string & {});\n\nexport type RemoteReceiptPayloadFormat = \"dsse-pae\";\n\nexport interface RemoteReceiptSignRequest {\n readonly kid: string;\n readonly publicKeyJwk: JsonWebKey;\n readonly bytes: Uint8Array;\n readonly payloadFormat: RemoteReceiptPayloadFormat;\n readonly algorithm: \"Ed25519\";\n readonly provider?: RemoteReceiptSignerProvider;\n readonly keyRef?: string;\n readonly metadata?: Record<string, unknown>;\n}\n\nexport interface RemoteReceiptSignResult {\n readonly signature: Uint8Array;\n}\n\nexport interface RemoteReceiptSignerOptions {\n readonly kid: string;\n readonly publicKeyJwk: JsonWebKey;\n readonly provider?: RemoteReceiptSignerProvider;\n readonly keyRef?: string;\n readonly metadata?: Record<string, unknown>;\n sign(\n request: RemoteReceiptSignRequest,\n ): Promise<Uint8Array | RemoteReceiptSignResult>;\n}\n\n/**\n * Adapt a remote signing service to Lattice's existing ReceiptSigner contract.\n *\n * The callback receives the exact DSSE PAE bytes that createReceipt signs.\n * Cloud-specific request construction, hashing choices, credentials, retries,\n * and audit logging stay outside core.\n */\nexport function createRemoteReceiptSigner(\n options: RemoteReceiptSignerOptions,\n): ReceiptSigner {\n return {\n kid: options.kid,\n publicKeyJwk: options.publicKeyJwk,\n async sign(bytes: Uint8Array): Promise<Uint8Array> {\n const result = await options.sign({\n kid: options.kid,\n publicKeyJwk: options.publicKeyJwk,\n bytes: copyBytes(bytes),\n payloadFormat: \"dsse-pae\",\n algorithm: \"Ed25519\",\n ...(options.provider !== undefined ? { provider: options.provider } : {}),\n ...(options.keyRef !== undefined ? { keyRef: options.keyRef } : {}),\n ...(options.metadata !== undefined ? { metadata: options.metadata } : {}),\n });\n return copyBytes(result instanceof Uint8Array ? result : result.signature);\n },\n };\n}\n\nfunction copyBytes(bytes: Uint8Array): Uint8Array {\n const copy = new Uint8Array(bytes.byteLength);\n copy.set(bytes);\n return copy;\n}\n","/**\n * WebCrypto Ed25519 wrappers + in-memory signer factory.\n *\n * 09-CONTEXT.md (UNRETROFITTABLE):\n * - Algorithm name is the LITERAL string \"Ed25519\" (no params object needed\n * for sign/verify; Node 24 subtle accepts both forms).\n * - ReceiptSigner returns 64-byte Ed25519 signatures.\n * - The runtime accepts a signer reference, NEVER raw private keys.\n * - Production users plug their own signer (KMS adapter / OS keyring).\n * createInMemorySigner is the in-process default for tests and dev.\n *\n * Reconciled in plan 09-03 to import ReceiptSigner from ./types.js (plan 09-01\n * owns the spine). `ReceiptSigner_Local` retained as a deprecated alias for\n * backward compatibility with Wave 1 sibling imports.\n */\n\nimport type { ReceiptSigner } from \"./types.js\";\n\n/**\n * @deprecated Use ReceiptSigner from \"./types.js\". Retained as an alias\n * during the Wave 1 -> Wave 2 reconciliation.\n */\nexport type ReceiptSigner_Local = ReceiptSigner;\n\nconst ALG = \"Ed25519\" as const;\n\n/**\n * Copy a Uint8Array into a fresh ArrayBuffer. WebCrypto's BufferSource type\n * (under exactOptionalPropertyTypes + strict TS) rejects `Uint8Array<ArrayBufferLike>`\n * because the underlying buffer could be a SharedArrayBuffer. Matches the\n * pattern used in storage/fingerprint.ts.\n */\nfunction toArrayBuffer(bytes: Uint8Array): ArrayBuffer {\n const copy = new Uint8Array(bytes.byteLength);\n copy.set(bytes);\n return copy.buffer as ArrayBuffer;\n}\n\nexport async function importEd25519PrivateKey(\n jwk: JsonWebKey,\n): Promise<CryptoKey> {\n return crypto.subtle.importKey(\"jwk\", jwk, ALG, true, [\"sign\"]);\n}\n\nexport async function importEd25519PublicKey(\n jwk: JsonWebKey,\n): Promise<CryptoKey> {\n return crypto.subtle.importKey(\"jwk\", jwk, ALG, true, [\"verify\"]);\n}\n\nexport interface GeneratedEd25519KeyPair {\n readonly privateKeyJwk: JsonWebKey;\n readonly publicKeyJwk: JsonWebKey;\n}\n\nexport async function generateEd25519KeyPairJwk(): Promise<GeneratedEd25519KeyPair> {\n const pair = (await crypto.subtle.generateKey(ALG, true, [\n \"sign\",\n \"verify\",\n ])) as CryptoKeyPair;\n const [privateKeyJwk, publicKeyJwk] = await Promise.all([\n crypto.subtle.exportKey(\"jwk\", pair.privateKey),\n crypto.subtle.exportKey(\"jwk\", pair.publicKey),\n ]);\n return { privateKeyJwk, publicKeyJwk };\n}\n\nexport async function verifyEd25519Signature(\n publicKeyJwk: JsonWebKey,\n message: Uint8Array,\n signature: Uint8Array,\n): Promise<boolean> {\n let key: CryptoKey;\n try {\n key = await importEd25519PublicKey(publicKeyJwk);\n } catch {\n return false;\n }\n try {\n return await crypto.subtle.verify(\n ALG,\n key,\n toArrayBuffer(signature),\n toArrayBuffer(message),\n );\n } catch {\n // Malformed signature length or other subtle error — treat as invalid.\n return false;\n }\n}\n\nexport function createInMemorySigner(\n privateKeyJwk: JsonWebKey,\n options: { readonly kid: string; readonly publicKeyJwk: JsonWebKey },\n): ReceiptSigner {\n // Lazily import the key on first sign() — keeps the factory synchronous\n // and avoids touching crypto.subtle during module load.\n let cachedKey: CryptoKey | undefined;\n const ensureKey = async (): Promise<CryptoKey> => {\n if (cachedKey === undefined) {\n cachedKey = await importEd25519PrivateKey(privateKeyJwk);\n }\n return cachedKey;\n };\n return {\n kid: options.kid,\n publicKeyJwk: options.publicKeyJwk,\n async sign(bytes: Uint8Array): Promise<Uint8Array> {\n const key = await ensureKey();\n const sig = await crypto.subtle.sign(ALG, key, toArrayBuffer(bytes));\n return new Uint8Array(sig);\n },\n };\n}\n","import { canonicalizeReceiptBody } from \"./canonical.js\";\nimport {\n PAYLOAD_TYPE,\n base64Encode,\n buildPae,\n decodeEnvelope,\n} from \"./envelope.js\";\nimport { verifyEd25519Signature } from \"./sign.js\";\nimport type {\n CapabilityReceiptBody,\n KeyEntry,\n KeySet,\n ReceiptEnvelope,\n VerifyError,\n VerifyResult,\n} from \"./types.js\";\n\nfunction fail(kind: VerifyError[\"kind\"], message: string): VerifyResult {\n return { ok: false, error: { kind, message } };\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.byteLength !== b.byteLength) return false;\n for (let i = 0; i < a.byteLength; i += 1) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\n/**\n * Receipt body shape check. We trust the JSON parse — but we re-validate\n * that the required fields exist with the right primitive types before\n * canonicalizing again. Anything off -> version-mismatch (the body is\n * structurally NOT a v1 receipt, even if it parses as JSON).\n */\nfunction asReceiptBody(value: unknown): CapabilityReceiptBody | undefined {\n if (typeof value !== \"object\" || value === null) return undefined;\n const v = value as Record<string, unknown>;\n // CRYPTO-01: accept undefined / v1 / v1.1 / v1.2 / v1.3 so too-low versions all\n // reach Step 4 (the schema-version-too-low chokepoint). An unknown\n // non-undefined literal (e.g. lattice-receipt/v2 or \"garbage\") is still a\n // structural shape failure and falls through to the version-mismatch path.\n if (\n v.version !== undefined &&\n v.version !== \"lattice-receipt/v1\" &&\n v.version !== \"lattice-receipt/v1.1\" &&\n v.version !== \"lattice-receipt/v1.2\" &&\n v.version !== \"lattice-receipt/v1.3\"\n ) {\n return undefined;\n }\n if (typeof v.receiptId !== \"string\") return undefined;\n if (typeof v.runId !== \"string\") return undefined;\n if (typeof v.issuedAt !== \"string\") return undefined;\n if (typeof v.kid !== \"string\") return undefined;\n if (typeof v.model !== \"object\" || v.model === null) return undefined;\n if (typeof v.route !== \"object\" || v.route === null) return undefined;\n if (typeof v.usage !== \"object\" || v.usage === null) return undefined;\n if (typeof v.contractVerdict !== \"string\") return undefined;\n if (!Array.isArray(v.inputHashes)) return undefined;\n if (typeof v.redactionPolicyId !== \"string\") return undefined;\n if (!Array.isArray(v.redactions)) return undefined;\n return v as unknown as CapabilityReceiptBody;\n}\n\n/**\n * Pure receipt verifier.\n *\n * Returns a typed VerifyResult — never throws across the verification\n * boundary (PITFALLS.md security: \"Verifier panics on malformed receipts\n * -> DoS via crafted input\"). All parsing failures become typed errors.\n *\n * Decision tree (first match wins):\n * 1. decodeEnvelope throws OR signatures[] empty -> envelope-malformed\n * 2. payload bytes are not valid JSON -> envelope-malformed\n * 3. body shape check fails OR version unknown literal -> version-mismatch\n * 4. body.version === undefined OR \"lattice-receipt/v1\"-> schema-version-too-low (CRYPTO-01)\n * 5. keySet.lookup(keyid) === undefined -> key-not-found\n * 6. entry.state === \"revoked\" -> key-revoked\n * 7. re-canonicalized body != signed payloadBytes -> canonicalization-mismatch\n * 8. Ed25519 verification of PAE fails -> signature-invalid\n * 9. body.kid !== entry.kid (defense in depth) -> signature-invalid\n * 10. otherwise -> ok + keyState\n */\nexport async function verifyReceipt(\n envelope: ReceiptEnvelope,\n keySet: KeySet,\n): Promise<VerifyResult> {\n // Step 1: decode envelope (catches wrong payloadType, base64 errors).\n let decoded;\n try {\n decoded = decodeEnvelope(envelope);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(\"envelope-malformed\", message);\n }\n if (decoded.signatures.length === 0) {\n return fail(\"envelope-malformed\", \"envelope has no signatures\");\n }\n\n // Step 2: parse the canonical payload.\n let parsed: unknown;\n try {\n parsed = JSON.parse(new TextDecoder().decode(decoded.payloadBytes));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(\"envelope-malformed\", `payload is not valid JSON: ${message}`);\n }\n\n // Step 3: structural body check + version check.\n const body = asReceiptBody(parsed);\n if (body === undefined) {\n return fail(\n \"version-mismatch\",\n \"receipt body is not a lattice-receipt/v1.1, lattice-receipt/v1.2, or lattice-receipt/v1.3 shape\",\n );\n }\n\n // Step 4: receipt-downgrade defense (CRYPTO-01).\n // Reject receipts whose body.version is absent or equals the v1 literal.\n // v1 receipts predate the v1.1 step-marker integrity surface and the v1.2\n // modelClass audit tag; an attacker holding a valid signing key could mint a\n // v1-shaped body and submit it to bypass newer schema commitments.\n // Short-circuits before any cryptographic work (keyset lookup, canonical\n // re-check, signature verify) so the downgrade verdict is unambiguous.\n // See SECURITY.md (Phase 26 threat model) and Radicle 2026-03 precedent.\n if (body.version === undefined || body.version === \"lattice-receipt/v1\") {\n return fail(\n \"schema-version-too-low\",\n \"Receipt body.version must be 'lattice-receipt/v1.1', 'lattice-receipt/v1.2', or 'lattice-receipt/v1.3' — v1 receipts are not accepted (CRYPTO-01).\",\n );\n }\n\n // Step 5: keyset lookup (use first signature; multi-sig deferred to a future schema).\n const firstSig = decoded.signatures[0]!;\n const entry: KeyEntry | undefined = keySet.lookup(firstSig.keyid);\n if (entry === undefined) {\n return fail(\n \"key-not-found\",\n `keySet has no entry for kid \"${firstSig.keyid}\"`,\n );\n }\n if (entry.state === \"revoked\") {\n return fail(\"key-revoked\", `key \"${entry.kid}\" is revoked`);\n }\n\n // Step 6: re-canonicalize body and compare byte-for-byte against\n // decoded.payloadBytes. Catches any swap of canonical form mid-flight\n // (the signed bytes must canonicalize back to themselves).\n const reCanonical = canonicalizeReceiptBody(body);\n if (!bytesEqual(reCanonical, decoded.payloadBytes)) {\n return fail(\n \"canonicalization-mismatch\",\n \"re-canonicalized body does not match signed payload bytes\",\n );\n }\n\n // Step 7: rebuild PAE and verify Ed25519 signature.\n const payloadB64 = base64Encode(decoded.payloadBytes);\n const pae = buildPae(PAYLOAD_TYPE, payloadB64);\n const sigValid = await verifyEd25519Signature(\n entry.publicKeyJwk,\n pae,\n firstSig.sig,\n );\n if (!sigValid) {\n return fail(\"signature-invalid\", \"Ed25519 signature does not verify\");\n }\n\n // Step 8: defense-in-depth — body.kid MUST equal envelope keyid.\n if (body.kid !== entry.kid) {\n return fail(\n \"signature-invalid\",\n `body.kid \"${body.kid}\" does not match envelope keyid \"${entry.kid}\"`,\n );\n }\n\n // Step 9: success — surface the key state so callers can warn on retired.\n return { ok: true, body, keyState: entry.state };\n}\n","// AUTO-GENERATED FILE - DO NOT EDIT.\n// Source: package.json version field.\n// Regenerate with this package's stamp:version script.\nexport const latticeVersion = \"1.5.0\";\n","import canonicalize from \"canonicalize\";\n\nimport type { ArtifactInput, ArtifactRef } from \"../artifacts/artifact.js\";\nimport { toArtifactRef } from \"../artifacts/artifact.js\";\nimport type { CapabilityContract } from \"../contract/contract.js\";\nimport type { OutputContractMap } from \"../outputs/contracts.js\";\nimport type { ExecutionPlan, UsageRecord } from \"../plan/plan.js\";\nimport { createExecutionPlan, withPlanStatus } from \"../plan/plan.js\";\nimport type { PolicySpec } from \"../policy/policy.js\";\nimport type {\n ContractVerdict,\n ReceiptEnvelope,\n ReceiptModel,\n ReceiptRoute,\n ReceiptSigner,\n} from \"../receipts/types.js\";\nimport { computeArtifactLineageMerkleRoot } from \"../receipts/lineage.js\";\nimport { createReceipt } from \"../receipts/receipt.js\";\nimport type { ReplayEnvelope } from \"../replay/replay.js\";\nimport { fingerprintArtifactValue } from \"../storage/fingerprint.js\";\nimport { latticeVersion } from \"../version.js\";\n\nexport type ExternalExecutionSidecarOutputSpec =\n | \"text\"\n | { readonly kind: \"citations\" }\n | { readonly kind: \"artifacts\" };\n\nexport interface ExternalExecutionUsage {\n readonly promptTokens: number;\n readonly completionTokens: number;\n readonly costUsd: number | null;\n}\n\nexport interface ExternalExecutionAuditInput<\n TOutputs extends Record<string, unknown> = Record<string, unknown>,\n> {\n readonly task: string;\n readonly artifacts?: readonly ArtifactInput[];\n readonly outputSpecs?: Record<string, ExternalExecutionSidecarOutputSpec>;\n readonly outputs?: TOutputs;\n readonly policy: PolicySpec;\n readonly contract: CapabilityContract;\n readonly model: ReceiptModel;\n readonly route: ReceiptRoute;\n readonly usage: ExternalExecutionUsage;\n readonly rawRequest?: unknown;\n readonly rawResponse?: unknown;\n readonly contractVerdict?: ContractVerdict;\n readonly runId?: string;\n readonly receiptId?: string;\n readonly issuedAt?: string;\n readonly catalogVersion?: string;\n readonly metadata?: Record<string, unknown>;\n}\n\nexport interface ExternalExecutionMetadata {\n readonly kind: \"external-execution\";\n readonly model: ReceiptModel;\n readonly route: ReceiptRoute;\n readonly usage: ExternalExecutionUsage;\n readonly rawRequest?: unknown;\n readonly rawResponse?: unknown;\n readonly rawRequestHash?: string;\n readonly rawResponseHash?: string;\n readonly inputHashes: readonly string[];\n readonly outputHash: string | null;\n readonly metadata?: Record<string, unknown>;\n}\n\nexport interface ExternalExecutionSidecar<\n TOutputs extends Record<string, unknown> = Record<string, unknown>,\n> {\n readonly version: \"lattice-sidecar/v1\";\n readonly task: string;\n readonly outputs: Record<string, ExternalExecutionSidecarOutputSpec>;\n readonly policy: PolicySpec;\n readonly contract: CapabilityContract;\n readonly rawOutputs?: TOutputs;\n readonly externalExecution: ExternalExecutionMetadata;\n}\n\nexport interface ExternalExecutionAuditResult<\n TOutputs extends Record<string, unknown> = Record<string, unknown>,\n> {\n readonly receipt: ReceiptEnvelope;\n readonly sidecar: ExternalExecutionSidecar<TOutputs>;\n readonly replayEnvelope: ReplayEnvelope<OutputContractMap>;\n readonly inputHashes: readonly string[];\n readonly outputHash: string | null;\n}\n\nexport async function createExternalExecutionAudit<\n TOutputs extends Record<string, unknown> = Record<string, unknown>,\n>(\n input: ExternalExecutionAuditInput<TOutputs>,\n signer: ReceiptSigner,\n): Promise<ExternalExecutionAuditResult<TOutputs>> {\n const runId = input.runId ?? createId(\"external-run\");\n const receiptId = input.receiptId ?? createId(\"external-receipt\");\n const issuedAt = input.issuedAt ?? new Date().toISOString();\n const artifacts = input.artifacts ?? [];\n const artifactRefs = artifacts.map(toArtifactRef);\n const outputSpecs = input.outputSpecs ?? inferOutputSpecs(input.outputs);\n const inputHashes = await hashInputArtifacts(artifacts);\n const outputHash = input.outputs === undefined ? null : await hashUnknown(input.outputs);\n const contractHash = await hashCanonical(input.contract);\n const lineageMerkleRoot = await computeArtifactLineageMerkleRoot(artifacts);\n const rawRequestHash = input.rawRequest === undefined\n ? undefined\n : (await hashUnknown(input.rawRequest)) ?? undefined;\n const rawResponseHash = input.rawResponse === undefined\n ? undefined\n : (await hashUnknown(input.rawResponse)) ?? undefined;\n const contractVerdict = input.contractVerdict ?? \"success\";\n\n const receipt = await createReceipt(\n {\n runId,\n receiptId,\n issuedAt,\n model: input.model,\n route: input.route,\n ...(lineageMerkleRoot !== undefined ? { lineageMerkleRoot } : {}),\n usage: input.usage,\n contractVerdict,\n contractHash,\n inputHashes,\n outputHash,\n },\n signer,\n );\n\n const sidecar: ExternalExecutionSidecar<TOutputs> = {\n version: \"lattice-sidecar/v1\",\n task: input.task,\n outputs: outputSpecs,\n policy: input.policy,\n contract: input.contract,\n ...(input.outputs !== undefined ? { rawOutputs: input.outputs } : {}),\n externalExecution: {\n kind: \"external-execution\",\n model: input.model,\n route: input.route,\n usage: input.usage,\n ...(input.rawRequest !== undefined ? { rawRequest: input.rawRequest } : {}),\n ...(input.rawResponse !== undefined ? { rawResponse: input.rawResponse } : {}),\n ...(rawRequestHash !== undefined ? { rawRequestHash } : {}),\n ...(rawResponseHash !== undefined ? { rawResponseHash } : {}),\n inputHashes,\n outputHash,\n ...(input.metadata !== undefined ? { metadata: input.metadata } : {}),\n },\n };\n\n return {\n receipt,\n sidecar,\n replayEnvelope: createExternalReplayEnvelope({\n runId,\n task: input.task,\n artifacts: artifactRefs,\n outputSpecs,\n outputs: input.outputs,\n catalogVersion: input.catalogVersion ?? \"external\",\n route: input.route,\n usage: input.usage,\n receipt,\n contract: input.contract,\n contractVerdict,\n metadata: input.metadata,\n }),\n inputHashes,\n outputHash,\n };\n}\n\nfunction createExternalReplayEnvelope(input: {\n readonly runId: string;\n readonly task: string;\n readonly artifacts: readonly ArtifactRef[];\n readonly outputSpecs: Record<string, ExternalExecutionSidecarOutputSpec>;\n readonly outputs: Record<string, unknown> | undefined;\n readonly catalogVersion: string;\n readonly route: ReceiptRoute;\n readonly usage: ExternalExecutionUsage;\n readonly receipt: ReceiptEnvelope;\n readonly contract: CapabilityContract;\n readonly contractVerdict: ContractVerdict;\n readonly metadata: Record<string, unknown> | undefined;\n}): ReplayEnvelope<OutputContractMap> {\n const isSuccess = input.contractVerdict === \"success\";\n const attempt = {\n providerId: input.route.providerId,\n modelId: input.route.capabilityId,\n status: isSuccess ? \"succeeded\" as const : \"failed\" as const,\n usage: usageRecord(input.usage),\n metadata: { externalExecution: true },\n ...(!isSuccess ? { error: input.contractVerdict } : {}),\n };\n const plan = withPlanStatus(\n createExecutionPlan({\n task: input.task,\n artifacts: input.artifacts,\n outputs: input.outputSpecs as OutputContractMap,\n route: {\n catalogVersion: input.catalogVersion,\n selected: {\n providerId: input.route.providerId,\n modelId: input.route.capabilityId,\n score: 0,\n estimates: {\n inputTokens: input.usage.promptTokens,\n outputTokens: input.usage.completionTokens,\n ...(input.usage.costUsd !== null ? { costUsd: input.usage.costUsd } : {}),\n },\n inputModalities: [],\n outputModalities: [],\n fileTransport: [],\n },\n candidates: [],\n rejected: [],\n fallbackChain: [],\n noRouteReasons: [],\n },\n metadata: {\n externalExecution: true,\n runId: input.runId,\n contractVerdict: input.contractVerdict,\n ...(input.metadata !== undefined ? { external: input.metadata } : {}),\n },\n }),\n isSuccess ? \"completed\" : \"failed\",\n {\n stages: isSuccess\n ? markAllStagesCompleted\n : markExternalStagesFailed(input.contractVerdict),\n attempts: [attempt],\n },\n );\n\n return {\n kind: \"replay-envelope\",\n version: 1,\n runtimeVersion: latticeVersion,\n catalogVersion: input.catalogVersion,\n createdAt: new Date().toISOString(),\n plan,\n artifacts: input.artifacts,\n ...(isSuccess && input.outputs !== undefined ? { outputs: input.outputs } : {}),\n warnings: [],\n errors: isSuccess ? [] : [input.contractVerdict],\n usage: usageRecord(input.usage),\n events: [],\n receipt: input.receipt,\n contract: input.contract,\n };\n}\n\nfunction markExternalStagesFailed(verdict: ContractVerdict): ExecutionPlan[\"stages\"] {\n const failedStage = failedStageForVerdict(verdict);\n let hasFailed = false;\n\n return markAllStagesCompleted.map((stage) => {\n if (stage.kind === failedStage) {\n hasFailed = true;\n return {\n ...stage,\n status: \"failed\" as const,\n warnings: [...stage.warnings, verdict],\n };\n }\n\n if (hasFailed) {\n return {\n ...stage,\n status: \"skipped\" as const,\n };\n }\n\n return stage;\n });\n}\n\nfunction failedStageForVerdict(verdict: ContractVerdict): ExecutionPlan[\"stages\"][number][\"kind\"] {\n switch (verdict) {\n case \"validation-failed\":\n return \"validation\";\n case \"tripwire-violated\":\n return \"tripwire\";\n case \"no-contract-match\":\n return \"analysis\";\n case \"execution-failed\":\n case \"success\":\n return \"execution\";\n }\n}\n\nfunction usageRecord(usage: ExternalExecutionUsage): UsageRecord {\n return {\n inputTokens: usage.promptTokens,\n outputTokens: usage.completionTokens,\n totalTokens: usage.promptTokens + usage.completionTokens,\n ...(usage.costUsd !== null ? { costUsd: usage.costUsd } : {}),\n };\n}\n\nfunction inferOutputSpecs(\n outputs: Record<string, unknown> | undefined,\n): Record<string, ExternalExecutionSidecarOutputSpec> {\n if (outputs === undefined) {\n return {};\n }\n\n return Object.fromEntries(Object.keys(outputs).map((name) => [name, \"text\" as const]));\n}\n\nasync function hashInputArtifacts(\n artifacts: readonly ArtifactInput[],\n): Promise<readonly string[]> {\n const hashes: string[] = [];\n for (const artifact of artifacts) {\n hashes.push(artifact.fingerprint?.value ?? await hashUnknown(artifact.value) ?? \"\");\n }\n\n return hashes;\n}\n\nasync function hashUnknown(value: unknown): Promise<string | null> {\n return (await fingerprintArtifactValue(value))?.value ?? null;\n}\n\nasync function hashCanonical(value: unknown): Promise<string | null> {\n const canonical = canonicalize(value);\n if (canonical === undefined) {\n return null;\n }\n\n return hashUnknown(canonical);\n}\n\nfunction createId(prefix: string): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return `${prefix}:${crypto.randomUUID()}`;\n }\n\n return `${prefix}:${Date.now()}:${Math.random().toString(16).slice(2)}`;\n}\n\nconst markAllStagesCompleted: ExecutionPlan[\"stages\"] = [\n {\n id: \"stage:analysis\",\n kind: \"analysis\",\n status: \"completed\",\n warnings: [],\n },\n {\n id: \"stage:transforms\",\n kind: \"transforms\",\n status: \"completed\",\n warnings: [],\n },\n {\n id: \"stage:context-packing\",\n kind: \"context-packing\",\n status: \"completed\",\n warnings: [],\n },\n {\n id: \"stage:provider-packaging\",\n kind: \"provider-packaging\",\n status: \"completed\",\n warnings: [],\n },\n {\n id: \"stage:tool-execution\",\n kind: \"tool-execution\",\n status: \"completed\",\n warnings: [],\n },\n {\n id: \"stage:execution\",\n kind: \"execution\",\n status: \"completed\",\n warnings: [],\n },\n {\n id: \"stage:validation\",\n kind: \"validation\",\n status: \"completed\",\n warnings: [],\n },\n {\n id: \"stage:tripwire\",\n kind: \"tripwire\",\n status: \"completed\",\n warnings: [],\n },\n {\n id: \"stage:persistence\",\n kind: \"persistence\",\n status: \"completed\",\n warnings: [],\n },\n];\n","/**\n * Phase 10 — materializeReplayEnvelope.\n *\n * Reconstructs a `ReplayEnvelope` from a signed `ReceiptEnvelope` plus a\n * pluggable artifact loader. The flow is:\n *\n * 1. verifyReceipt(receipt, keySet) — REQUIRED before any other work.\n * A tampered or revoked receipt MUST short-circuit before the artifact\n * loader is invoked (no side effects on bad input).\n * 2. Parse the verified body to learn `inputHashes`.\n * 3. Invoke `artifactLoader(hash)` once per input hash, in order.\n * 4. Assemble a `ReplayEnvelope` whose `plan` reproduces the receipt's\n * route/usage fields, attach the receipt itself, and (optionally) the\n * caller-supplied contract / task / outputs / policy.\n *\n * v1.1 limitation: the receipt body does NOT carry the original task string,\n * outputs schema, or policy snapshot. Callers may supply them via the options\n * bag; when omitted, the envelope's `task` defaults to \"\" and `outputs`\n * remains undefined. Phase 11's `lattice repro` CLI accepts a sidecar JSON\n * file to populate these fields.\n *\n * Errors NEVER cross the boundary as plain `Error`. All failures surface as\n * typed `MaterializationError` values thrown from the async function so the\n * caller can pattern-match on `error.kind` (and a `MaterializationError` IS\n * a thrown object whose `kind` discriminates the failure mode).\n */\n\nimport type { ArtifactInput } from \"../artifacts/artifact.js\";\nimport { toArtifactRef } from \"../artifacts/artifact.js\";\nimport type { CapabilityContract } from \"../contract/contract.js\";\nimport type { OutputContractMap } from \"../outputs/contracts.js\";\nimport type { InferOutputMap } from \"../outputs/infer.js\";\nimport { createExecutionPlan, type ExecutionPlan, type UsageRecord } from \"../plan/plan.js\";\nimport type { PolicySpec } from \"../policy/policy.js\";\nimport type { CapabilityModality } from \"../providers/provider.js\";\nimport type {\n CapabilityReceiptBody,\n KeySet,\n ReceiptEnvelope,\n} from \"../receipts/types.js\";\nimport { verifyReceipt } from \"../receipts/verify.js\";\nimport { latticeVersion } from \"../version.js\";\n\nimport type { ReplayEnvelope } from \"./replay.js\";\n\n/**\n * Discriminated union of materialization failure modes.\n *\n * - \"verify-failed\" — receipt failed verifyReceipt (signature, key\n * missing/revoked, canonicalization mismatch).\n * - \"artifact-load-failed\" — the artifactLoader callback rejected for at\n * least one input hash.\n * - \"envelope-malformed\" — receipt verified but the verified body is\n * structurally unusable (should never happen\n * under verifyReceipt invariants, but kept as a\n * defensive third branch).\n */\nexport interface MaterializationError {\n readonly kind: \"verify-failed\" | \"artifact-load-failed\" | \"envelope-malformed\";\n readonly message: string;\n}\n\nfunction asMaterializationError(value: unknown): value is MaterializationError {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { kind?: unknown }).kind === \"string\" &&\n typeof (value as { message?: unknown }).message === \"string\"\n );\n}\n\n/** Throwable shape — `instanceof Error` is not required for typed unions, so\n * the function just throws a plain object literal that matches the\n * `MaterializationError` shape. Callers pattern-match on `err.kind`. */\nfunction fail(\n kind: MaterializationError[\"kind\"],\n message: string,\n): MaterializationError {\n return { kind, message };\n}\n\n/**\n * Async callback that resolves an artifact body from its sha256 hex digest.\n * Phase 10 ships only the in-memory variant for tests. Phase 11's CLI plugs\n * in a filesystem-backed loader reading from `.lattice/fixtures/<sha256>.bin`.\n */\nexport type ArtifactLoader = (hash: string) => Promise<ArtifactInput>;\n\nexport interface MaterializeReplayEnvelopeOptions<\n TOutputs extends OutputContractMap = OutputContractMap,\n> {\n readonly artifactLoader: ArtifactLoader;\n readonly keySet: KeySet;\n /** Optional original task string. Defaults to \"\" when omitted. */\n readonly task?: string;\n /**\n * Optional caller-supplied outputs map. When provided, the resulting\n * `ReplayEnvelope.outputs` is populated and `replayOffline` will return\n * an `ok: true` result. When omitted, `replayOffline` reports an\n * `execution_unavailable` failure (current Phase 5 semantics).\n */\n readonly outputs?: InferOutputMap<TOutputs>;\n readonly policy?: PolicySpec;\n readonly contract?: CapabilityContract;\n}\n\n/**\n * Pure async function that reconstructs a `ReplayEnvelope` from a receipt.\n *\n * Verify-FIRST ordering: `verifyReceipt` runs before `artifactLoader` is\n * touched. Tampered receipts MUST NOT cause loader side effects.\n */\nexport async function materializeReplayEnvelope<\n TOutputs extends OutputContractMap = OutputContractMap,\n>(\n receipt: ReceiptEnvelope,\n options: MaterializeReplayEnvelopeOptions<TOutputs>,\n): Promise<ReplayEnvelope<TOutputs>> {\n // Step 1: verify FIRST. No artifact loader call before this resolves.\n const verifyResult = await verifyReceipt(receipt, options.keySet);\n if (!verifyResult.ok) {\n throw fail(\n verifyResult.error.kind === \"envelope-malformed\"\n ? \"envelope-malformed\"\n : \"verify-failed\",\n verifyResult.error.message,\n );\n }\n\n const body: CapabilityReceiptBody = verifyResult.body;\n\n // Step 2: load every artifact referenced by the receipt's inputHashes.\n // We treat any loader rejection as `artifact-load-failed` and surface the\n // underlying message — the loader is the system boundary, so its error\n // text is the most informative thing we have.\n const loadedInputs: ArtifactInput[] = [];\n for (const hash of body.inputHashes) {\n if (hash === \"\") {\n // Skip empty-hash slots — Phase 9 emits \"\" for unfingerprintable\n // values (e.g., undefined artifact bodies). They have no resolvable\n // content and the replay artifacts array preserves order via the\n // remaining loaded entries.\n continue;\n }\n try {\n const input = await options.artifactLoader(hash);\n loadedInputs.push(input);\n } catch (error) {\n const message =\n error instanceof Error\n ? error.message\n : asMaterializationError(error)\n ? error.message\n : String(error);\n throw fail(\"artifact-load-failed\", message);\n }\n }\n\n // Step 3: assemble the ExecutionPlan envelope shell. The receipt does NOT\n // carry the full RouteDecision/ContextPack — we synthesize a minimal but\n // valid plan that reproduces the receipt's route + usage fields. This is\n // intentionally lossy and matches the v1.1 limitation note in 10-CONTEXT.md.\n const artifactRefs = loadedInputs.map(toArtifactRef);\n const outputsMap = (options.outputs !== undefined\n ? (Object.fromEntries(\n Object.keys(options.outputs as Record<string, unknown>).map((k) => [\n k,\n \"text\" as const,\n ]),\n ) as OutputContractMap)\n : ({} as OutputContractMap));\n\n const plan: ExecutionPlan = createExecutionPlan({\n task: options.task ?? \"\",\n artifacts: artifactRefs,\n outputs: outputsMap,\n route: {\n catalogVersion: \"materialized\",\n selected: {\n providerId: body.route.providerId,\n modelId: body.route.capabilityId,\n score: 0,\n estimates: { inputTokens: 0, outputTokens: 0 },\n inputModalities: [] as readonly CapabilityModality[],\n outputModalities: [] as readonly CapabilityModality[],\n fileTransport: [],\n },\n candidates: [],\n rejected: [],\n fallbackChain: [],\n noRouteReasons: [],\n },\n warnings: [],\n metadata: {\n materialized: true,\n receiptId: body.receiptId,\n runId: body.runId,\n contractVerdict: body.contractVerdict,\n ...(options.policy !== undefined ? { policy: { ...options.policy } } : {}),\n },\n });\n\n const usage: UsageRecord = {\n inputTokens: body.usage.promptTokens,\n outputTokens: body.usage.completionTokens,\n ...(body.usage.costUsd !== null\n ? { costUsd: Number(body.usage.costUsd) }\n : {}),\n };\n\n const envelope: ReplayEnvelope<TOutputs> = {\n kind: \"replay-envelope\",\n version: 1,\n runtimeVersion: latticeVersion,\n catalogVersion: \"materialized\",\n createdAt: new Date().toISOString(),\n plan,\n artifacts: artifactRefs,\n ...(options.outputs !== undefined ? { outputs: options.outputs } : {}),\n warnings: [],\n errors: [],\n usage,\n events: [],\n receipt,\n ...(options.contract !== undefined ? { contract: options.contract } : {}),\n };\n\n return envelope;\n}\n","import type { ArtifactRef } from \"../artifacts/artifact.js\";\nimport type { CapabilityContract } from \"../contract/contract.js\";\nimport type { OutputContractMap } from \"../outputs/contracts.js\";\nimport type { InferOutputMap } from \"../outputs/infer.js\";\nimport type { ExecutionPlan, UsageRecord } from \"../plan/plan.js\";\nimport type { Usage } from \"../providers/provider.js\";\nimport type { ReceiptEnvelope } from \"../receipts/types.js\";\nimport type { RunResult } from \"../results/result.js\";\nimport type { AI, RunIntent } from \"../runtime/create-ai.js\";\nimport type { RunEvent } from \"../tracing/tracing.js\";\nimport { latticeVersion } from \"../version.js\";\n\nexport interface ReplayEnvelope<TOutputs extends OutputContractMap = OutputContractMap> {\n readonly kind: \"replay-envelope\";\n readonly version: 1;\n readonly runtimeVersion: string;\n readonly catalogVersion: string;\n readonly createdAt: string;\n readonly plan: ExecutionPlan;\n readonly artifacts: readonly ArtifactRef[];\n readonly outputs?: InferOutputMap<TOutputs>;\n readonly warnings: readonly string[];\n readonly errors: readonly string[];\n readonly usage?: UsageRecord;\n readonly events: readonly RunEvent[];\n /**\n * Phase 10 — optional signed receipt recorded alongside the envelope so a\n * single artifact is sufficient to materialize an offline replay session\n * deterministically. Type-only import — replay.ts stays runtime-import-free\n * of the receipts builder.\n */\n readonly receipt?: ReceiptEnvelope;\n /**\n * Phase 10 — optional contract recorded so replays can re-run pre-flight\n * checks deterministically.\n */\n readonly contract?: CapabilityContract;\n}\n\nexport function createReplayEnvelope<TOutputs extends OutputContractMap>(\n result: RunResult<TOutputs>,\n): ReplayEnvelope<TOutputs> {\n if (result.plan.kind !== \"execution-plan\") {\n throw new Error(\"Replay envelopes require an execution plan.\");\n }\n\n const usage = result.plan.attempts.at(-1)?.usage;\n\n return {\n kind: \"replay-envelope\",\n version: 1,\n runtimeVersion: latticeVersion,\n catalogVersion: result.plan.route.catalogVersion,\n createdAt: new Date().toISOString(),\n plan: redactPlan(result.plan),\n artifacts: result.ok ? result.artifacts : result.plan.artifactRefs,\n ...(result.ok ? { outputs: result.outputs } : {}),\n warnings: result.plan.warnings,\n errors: result.ok ? [] : [result.error.message],\n ...(usage !== undefined ? { usage } : {}),\n events: result.events ?? [],\n };\n}\n\nexport async function replayOffline<TOutputs extends OutputContractMap>(\n envelope: ReplayEnvelope<TOutputs>,\n): Promise<RunResult<TOutputs>> {\n const replayedUsage = envelopeUsage(envelope);\n if (envelope.outputs === undefined) {\n return {\n ok: false,\n error: {\n kind: \"execution_unavailable\",\n message: \"Replay envelope does not contain successful outputs.\",\n },\n usage: replayedUsage,\n plan: envelope.plan,\n events: envelope.events,\n };\n }\n\n return {\n ok: true,\n outputs: envelope.outputs,\n artifacts: envelope.artifacts,\n usage: replayedUsage,\n plan: envelope.plan,\n events: envelope.events,\n };\n}\n\nfunction envelopeUsage(envelope: ReplayEnvelope<OutputContractMap>): Usage {\n if (envelope.usage === undefined) {\n return { promptTokens: 0, completionTokens: 0, costUsd: null };\n }\n return {\n promptTokens: envelope.usage.inputTokens ?? 0,\n completionTokens: envelope.usage.outputTokens ?? 0,\n costUsd: envelope.usage.costUsd ?? null,\n };\n}\n\nexport async function rerunLive<TOutputs extends OutputContractMap>(\n ai: AI,\n envelope: ReplayEnvelope<TOutputs>,\n intent: RunIntent<TOutputs>,\n): Promise<RunResult<TOutputs>> {\n const result = await ai.run(intent);\n\n if (result.plan.kind === \"execution-plan\") {\n return {\n ...result,\n plan: {\n ...result.plan,\n warnings: [\n ...result.plan.warnings,\n `Live rerun of ${envelope.plan.id}: provider behavior, model versions, cost, and latency may differ.`,\n ],\n },\n };\n }\n\n return result;\n}\n\nexport function redactReplayEnvelope<TOutputs extends OutputContractMap>(\n envelope: ReplayEnvelope<TOutputs>,\n): ReplayEnvelope<TOutputs> {\n return {\n ...envelope,\n plan: redactPlan(envelope.plan),\n artifacts: envelope.artifacts.map(redactArtifactRef),\n events: envelope.events.map((event) => {\n const metadata = redactRecord(event.metadata);\n\n return {\n ...event,\n ...(metadata !== undefined ? { metadata } : {}),\n };\n }),\n };\n}\n\nexport function redactPlan(plan: ExecutionPlan): ExecutionPlan {\n return {\n ...plan,\n task: redactText(plan.task),\n artifactRefs: plan.artifactRefs.map(redactArtifactRef),\n ...(plan.providerPackaging !== undefined\n ? {\n providerPackaging: {\n ...plan.providerPackaging,\n artifacts: plan.providerPackaging.artifacts.map((item) => ({\n ...item,\n warnings: item.warnings.map(redactText),\n })),\n warnings: plan.providerPackaging.warnings.map(redactText),\n },\n }\n : {}),\n warnings: plan.warnings.map(redactText),\n };\n}\n\nexport function redactArtifactRef(ref: ArtifactRef): ArtifactRef {\n const redactedMetadata = redactRecord(ref.metadata);\n\n return {\n ...ref,\n ...(redactedMetadata !== undefined ? { metadata: redactedMetadata } : {}),\n ...(ref.source === \"url\"\n ? {\n metadata: {\n ...redactedMetadata,\n redactedSource: \"url\",\n },\n }\n : {}),\n };\n}\n\nfunction redactRecord(\n record: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n if (record === undefined) {\n return undefined;\n }\n\n return Object.fromEntries(\n Object.entries(record).map(([key, value]) => [\n key,\n shouldRedactKey(key) ? \"[redacted]\" : redactValue(value),\n ]),\n );\n}\n\nfunction redactValue(value: unknown): unknown {\n if (typeof value === \"string\") {\n return redactText(value);\n }\n\n if (Array.isArray(value)) {\n return value.map(redactValue);\n }\n\n if (typeof value === \"object\" && value !== null) {\n return redactRecord(value as Record<string, unknown>);\n }\n\n return value;\n}\n\nfunction redactText(value: string): string {\n return value\n .replace(/Bearer\\s+[A-Za-z0-9._-]+/gu, \"Bearer [redacted]\")\n .replace(/https?:\\/\\/[^\\s)]+/gu, \"[redacted-url]\")\n .replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}/gu, \"[redacted-email]\");\n}\n\nfunction shouldRedactKey(key: string): boolean {\n return /api.?key|authorization|token|secret|password|credential|signed.?url|raw|body|transcript/iu.test(key);\n}\n"],"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K,UAAU;IACzD,GAAG;IACH,UAAU,KAAK,SAAS,IAAI,WAAW;IACxC,EAAE;GACH,UAAU,KAAK,kBAAkB,SAAS,IAAI,WAAW;GAC1D,EACF,GACD,EAAE;EACN,UAAU,KAAK,SAAS,IAAI,WAAW;EACxC;;AAGH,SAAgB,kBAAkB,KAA+B;CAC/D,MAAM,mBAAmB,aAAa,IAAI,SAAS;AAEnD,QAAO;EACL,GAAG;EACH,GAAI,qBAAqB,KAAA,IAAY,EAAE,UAAU,kBAAkB,GAAG,EAAE;EACxE,GAAI,IAAI,WAAW,QACf,EACE,UAAU;GACR,GAAG;GACH,gBAAgB;GACjB,EACF,GACD,EAAE;EACP;;AAGH,SAAS,aACP,QACqC;AACrC,KAAI,WAAW,KAAA,EACb;AAGF,QAAO,OAAO,YACZ,OAAO,QAAQ,OAAO,CAAC,KAAK,CAAC,KAAK,WAAW,CAC3C,KACA,gBAAgB,IAAI,GAAG,eAAe,YAAY,MAAM,CACzD,CAAC,CACH;;AAGH,SAAS,YAAY,OAAyB;AAC5C,KAAI,OAAO,UAAU,SACnB,QAAO,WAAW,MAAM;AAG1B,KAAI,MAAM,QAAQ,MAAM,CACtB,QAAO,MAAM,IAAI,YAAY;AAG/B,KAAI,OAAO,UAAU,YAAY,UAAU,KACzC,QAAO,aAAa,MAAiC;AAGvD,QAAO;;AAGT,SAAS,WAAW,OAAuB;AACzC,QAAO,MACJ,QAAQ,8BAA8B,oBAAoB,CAC1D,QAAQ,wBAAwB,iBAAiB,CACjD,QAAQ,oDAAoD,mBAAmB;;AAGpF,SAAS,gBAAgB,KAAsB;AAC7C,QAAO,4FAA4F,KAAK,IAAI"}
@@ -0,0 +1,38 @@
1
+ import { T as Usage, gt as LatticeRunError, mn as OutputContractMap, o as ProviderGatewayMetadata, rn as ResultPlan, vn as RunEvent } from "./provider-C2IfKsvz.js";
2
+ import { s as ArtifactRef } from "./artifact-Bg6mJGnm.js";
3
+ import { c as ReceiptEnvelope, n as InferOutputMap } from "./infer-DLqp5QIM.js";
4
+
5
+ //#region src/results/result.d.ts
6
+ interface RunSuccess<TOutputs extends OutputContractMap> {
7
+ readonly ok: true;
8
+ readonly outputs: InferOutputMap<TOutputs>;
9
+ readonly artifacts: readonly ArtifactRef[];
10
+ readonly usage: Usage;
11
+ readonly plan: ResultPlan;
12
+ readonly events?: readonly RunEvent[];
13
+ readonly gateway?: ProviderGatewayMetadata;
14
+ /**
15
+ * Phase 9 — signed capability receipt issued when `LatticeConfig.signer`
16
+ * is configured. Undefined when no signer is set.
17
+ */
18
+ readonly receipt?: ReceiptEnvelope;
19
+ }
20
+ interface RunFailure {
21
+ readonly ok: false;
22
+ readonly error: LatticeRunError;
23
+ readonly usage: Usage;
24
+ readonly raw?: unknown;
25
+ readonly partialOutputs?: Record<string, unknown>;
26
+ readonly plan: ResultPlan;
27
+ readonly events?: readonly RunEvent[];
28
+ readonly gateway?: ProviderGatewayMetadata;
29
+ /**
30
+ * Phase 9 — signed capability receipt issued when `LatticeConfig.signer`
31
+ * is configured. Undefined when no signer is set.
32
+ */
33
+ readonly receipt?: ReceiptEnvelope;
34
+ }
35
+ type RunResult<TOutputs extends OutputContractMap> = RunSuccess<TOutputs> | RunFailure;
36
+ //#endregion
37
+ export { RunResult as n, RunSuccess as r, RunFailure as t };
38
+ //# sourceMappingURL=result-DLEx2WvU.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"result-DLEx2WvU.d.ts","names":[],"sources":["../src/results/result.ts"],"mappings":";;;;;UASiB,UAAA,kBAA4B,iBAAA;EAAA,SAClC,EAAA;EAAA,SACA,OAAA,EAAS,cAAA,CAAe,QAAA;EAAA,SACxB,SAAA,WAAoB,WAAA;EAAA,SACpB,KAAA,EAAO,KAAA;EAAA,SACP,IAAA,EAAM,UAAA;EAAA,SACN,MAAA,YAAkB,QAAA;EAAA,SAClB,OAAA,GAAU,uBAAA;EAKA;;;;EAAA,SAAV,OAAA,GAAU,eAAA;AAAA;AAAA,UAGJ,UAAA;EAAA,SACN,EAAA;EAAA,SACA,KAAA,EAAO,eAAA;EAAA,SACP,KAAA,EAAO,KAAA;EAAA,SACP,GAAA;EAAA,SACA,cAAA,GAAiB,MAAA;EAAA,SACjB,IAAA,EAAM,UAAA;EAAA,SACN,MAAA,YAAkB,QAAA;EAAA,SAClB,OAAA,GAAU,uBAAA;EAjBV;;;;EAAA,SAsBA,OAAA,GAAU,eAAA;AAAA;AAAA,KAGT,SAAA,kBAA2B,iBAAA,IACnC,UAAA,CAAW,QAAA,IACX,UAAA"}
@@ -0,0 +1,314 @@
1
+ import { i as effectivePer1kPricing } from "./catalog-CAfYwB_-.js";
2
+ import { n as estimateArtifactTokens, r as estimateTokens } from "./context-pack-Bz3GXmjv.js";
3
+ //#region src/contract/preflight.ts
4
+ /**
5
+ * Pure cost estimator. Returns `null` when pricing is unknown (so downstream
6
+ * gates can distinguish "free / zero" from "unmeasured" per the Phase 7
7
+ * cost-normalization decision). Uses static catalog metadata only — no probes,
8
+ * no external pricing APIs.
9
+ */
10
+ function estimateRouteCost(input) {
11
+ const { inputPer1kTokens, outputPer1kTokens } = effectivePer1kPricing(input.capability.pricing);
12
+ if (inputPer1kTokens === void 0 && outputPer1kTokens === void 0) return null;
13
+ return (inputPer1kTokens ?? 0) * input.estimatedInputTokens / 1e3 + (outputPer1kTokens ?? 0) * input.estimatedOutputTokens / 1e3;
14
+ }
15
+ /**
16
+ * Pure pre-flight evaluator. Phase 9 receipts will reuse this for deterministic
17
+ * verdict reconstruction.
18
+ *
19
+ * Token estimation: Phase 7 does NOT define a separate token estimator. Output-
20
+ * token projection is the canonical responsibility of the router's existing
21
+ * `estimateRoute()` helper (in `routing/router.ts`), which already produces an
22
+ * `estimatedOutputTokens` value. The router passes that same value into this
23
+ * evaluator via `EvaluateContractInput.estimatedOutputTokens`, so preflight
24
+ * and the router always agree on the projected output size. Phase 9 receipts
25
+ * will pin the router's estimate as the deterministic input — intentionally
26
+ * one source of truth.
27
+ *
28
+ * Reject taxonomy (Phase 7 emits three of four codes):
29
+ * - `contract-budget-exceeded` (CONTRACT-04 + COST-03)
30
+ * - `contract-modality-missing` (CONTRACT-06)
31
+ * - `contract-privacy-mismatch` (CONTRACT-06)
32
+ * - `contract-quality-floor` (reserved for Phase 12 `lattice eval`; NEVER emitted here)
33
+ */
34
+ function evaluateContractAgainstRoute(contract, input) {
35
+ if (contract === void 0) return {
36
+ ok: true,
37
+ reasons: []
38
+ };
39
+ const reasons = [];
40
+ if (contract.budget?.maxCostUsd !== void 0) {
41
+ const estimatedCost = estimateRouteCost({
42
+ capability: input.capability,
43
+ estimatedInputTokens: input.estimatedInputTokens,
44
+ estimatedOutputTokens: input.estimatedOutputTokens
45
+ });
46
+ if (estimatedCost === null) reasons.push({
47
+ code: "contract-budget-exceeded",
48
+ message: `${input.capability.modelId} pricing unknown; contract budget declared (maxCostUsd=${contract.budget.maxCostUsd}).`
49
+ });
50
+ else if (estimatedCost > contract.budget.maxCostUsd) reasons.push({
51
+ code: "contract-budget-exceeded",
52
+ message: `${input.capability.modelId} estimated ${estimatedCost.toFixed(6)} exceeds contract budget ${contract.budget.maxCostUsd}.`
53
+ });
54
+ }
55
+ if (contract.requiredModalities !== void 0) {
56
+ for (const modality of contract.requiredModalities) if (!input.capability.inputModalities.includes(modality) && !input.capability.outputModalities.includes(modality)) reasons.push({
57
+ code: "contract-modality-missing",
58
+ message: `${input.capability.modelId} does not support required modality ${modality}.`
59
+ });
60
+ }
61
+ if (contract.requiredPrivacy !== void 0) {
62
+ if (!input.capability.dataPolicy.privacy.includes(contract.requiredPrivacy)) reasons.push({
63
+ code: "contract-privacy-mismatch",
64
+ message: `${input.capability.modelId} does not satisfy contract privacy ${contract.requiredPrivacy}.`
65
+ });
66
+ }
67
+ return {
68
+ ok: reasons.length === 0,
69
+ reasons
70
+ };
71
+ }
72
+ //#endregion
73
+ //#region src/policy/policy.ts
74
+ function mergePolicy(defaultPolicy, runPolicy) {
75
+ if (defaultPolicy === void 0 && runPolicy === void 0) return;
76
+ const gateway = mergeGatewayPolicy(defaultPolicy?.gateway, runPolicy?.gateway);
77
+ return {
78
+ ...defaultPolicy,
79
+ ...runPolicy,
80
+ ...gateway !== void 0 ? { gateway } : {}
81
+ };
82
+ }
83
+ function mergeGatewayPolicy(defaultGateway, runGateway) {
84
+ if (defaultGateway === void 0 && runGateway === void 0) return;
85
+ const metadata = defaultGateway?.metadata !== void 0 || runGateway?.metadata !== void 0 ? {
86
+ ...defaultGateway?.metadata,
87
+ ...runGateway?.metadata
88
+ } : void 0;
89
+ return {
90
+ ...defaultGateway,
91
+ ...runGateway,
92
+ ...metadata !== void 0 ? { metadata } : {}
93
+ };
94
+ }
95
+ //#endregion
96
+ //#region src/routing/router.ts
97
+ function routeDeterministically(catalog, request) {
98
+ const requiredInputs = requiredInputModalities(request.artifacts);
99
+ const requiredOutputs = requiredOutputModalities(request.outputs);
100
+ const requiresStructuredOutput = outputRequiresStructuredOutput(request.outputs);
101
+ const estimatedInputTokens = estimateTokens(request.task) + request.artifacts.reduce((total, artifact) => total + estimateArtifactTokens(artifact), 0);
102
+ const candidates = catalog.models.map((capability, index) => evaluateCapability(capability, {
103
+ requiredInputs,
104
+ requiredOutputs,
105
+ requiresStructuredOutput,
106
+ estimatedInputTokens,
107
+ ...request.policy !== void 0 ? { policy: request.policy } : {},
108
+ ...request.provider !== void 0 ? { provider: request.provider } : {},
109
+ ...request.model !== void 0 ? { model: request.model } : {},
110
+ ...request.contract !== void 0 ? { contract: request.contract } : {},
111
+ index
112
+ })).sort(compareCandidates);
113
+ const accepted = candidates.filter((candidate) => candidate.accepted);
114
+ const selected = accepted[0];
115
+ return {
116
+ catalogVersion: catalog.version,
117
+ ...selected !== void 0 ? { selected: {
118
+ providerId: selected.providerId,
119
+ modelId: selected.modelId,
120
+ score: selected.score,
121
+ estimates: selected.estimates,
122
+ inputModalities: selected.capability.inputModalities,
123
+ outputModalities: selected.capability.outputModalities,
124
+ fileTransport: selected.capability.fileTransport
125
+ } } : {},
126
+ candidates,
127
+ rejected: candidates.filter((candidate) => !candidate.accepted),
128
+ fallbackChain: accepted.slice(1).map((candidate) => ({
129
+ providerId: candidate.providerId,
130
+ modelId: candidate.modelId,
131
+ score: candidate.score,
132
+ reason: "policy-preserving-fallback"
133
+ })),
134
+ noRouteReasons: selected === void 0 ? summarizeNoRouteReasons(candidates) : []
135
+ };
136
+ }
137
+ function evaluateCapability(capability, input) {
138
+ const reasons = [];
139
+ if (capability.available === false) reasons.push({
140
+ code: "provider-unavailable",
141
+ message: `${capability.providerId}/${capability.modelId} is not available.`
142
+ });
143
+ if (input.provider !== void 0 && capability.providerId !== input.provider) reasons.push({
144
+ code: "provider-forced-mismatch",
145
+ message: `Provider override requires ${input.provider}.`
146
+ });
147
+ if (input.model !== void 0 && capability.modelId !== input.model) reasons.push({
148
+ code: "model-forced-mismatch",
149
+ message: `Model override requires ${input.model}.`
150
+ });
151
+ for (const modality of input.requiredInputs) if (!capability.inputModalities.includes(modality)) reasons.push({
152
+ code: "input-modality-unsupported",
153
+ message: `${capability.modelId} does not support ${modality} input.`
154
+ });
155
+ for (const modality of input.requiredOutputs) if (!capability.outputModalities.includes(modality)) reasons.push({
156
+ code: "output-modality-unsupported",
157
+ message: `${capability.modelId} does not support ${modality} output.`
158
+ });
159
+ if (input.requiresStructuredOutput && !capability.structuredOutput) reasons.push({
160
+ code: "structured-output-unsupported",
161
+ message: `${capability.modelId} does not support structured output contracts.`
162
+ });
163
+ if (input.estimatedInputTokens > capability.contextWindow) reasons.push({
164
+ code: "context-window-exceeded",
165
+ message: `Estimated input ${input.estimatedInputTokens} tokens exceeds ${capability.contextWindow}.`
166
+ });
167
+ const estimates = estimateRoute(capability, input.estimatedInputTokens);
168
+ addPolicyRejectReasons(reasons, capability, estimates, input.policy);
169
+ const contractResult = evaluateContractAgainstRoute(input.contract, {
170
+ capability,
171
+ estimatedInputTokens: input.estimatedInputTokens,
172
+ estimatedOutputTokens: estimates.outputTokens
173
+ });
174
+ for (const reason of contractResult.reasons) reasons.push(reason);
175
+ const score = scoreCapability(capability, estimates, input.index);
176
+ return {
177
+ providerId: capability.providerId,
178
+ modelId: capability.modelId,
179
+ capability,
180
+ score,
181
+ accepted: reasons.length === 0,
182
+ reasons,
183
+ estimates
184
+ };
185
+ }
186
+ function addPolicyRejectReasons(reasons, capability, estimates, policy) {
187
+ if (policy === void 0) return;
188
+ if (policy.providerAllowList !== void 0 && !policy.providerAllowList.includes(capability.providerId)) reasons.push({
189
+ code: "provider-not-allowed",
190
+ message: `${capability.providerId} is not in the provider allow list.`
191
+ });
192
+ if (policy.providerDenyList?.includes(capability.providerId) === true) reasons.push({
193
+ code: "provider-denied",
194
+ message: `${capability.providerId} is in the provider deny list.`
195
+ });
196
+ if (policy.privacy !== void 0 && !capability.dataPolicy.privacy.includes(policy.privacy)) reasons.push({
197
+ code: "privacy-unsupported",
198
+ message: `${capability.modelId} does not satisfy ${policy.privacy} privacy.`
199
+ });
200
+ if (policy.noLogging === true && capability.dataPolicy.supportsNoLogging !== true) reasons.push({
201
+ code: "no-logging-unsupported",
202
+ message: `${capability.modelId} cannot satisfy noLogging.`
203
+ });
204
+ if (policy.stream === true && capability.streaming !== true) reasons.push({
205
+ code: "streaming-unsupported",
206
+ message: `${capability.modelId} does not support streaming.`
207
+ });
208
+ if (policy.noUpload === true && capability.fileTransport.length > 0 && capability.fileTransport.every((transport) => transport === "provider-upload")) reasons.push({
209
+ code: "no-upload-violated",
210
+ message: `${capability.modelId} requires an upload transport disallowed by policy.`
211
+ });
212
+ if (policy.latency !== void 0 && capability.latency !== policy.latency) reasons.push({
213
+ code: "latency-class-mismatch",
214
+ message: `${capability.modelId} latency class is ${capability.latency}, not ${policy.latency}.`
215
+ });
216
+ if (policy.maxCostUsd !== void 0 && estimates.costUsd !== void 0 && estimates.costUsd > policy.maxCostUsd) reasons.push({
217
+ code: "budget-exceeded",
218
+ message: `${capability.modelId} estimated cost ${estimates.costUsd} exceeds maxCostUsd ${policy.maxCostUsd}.`
219
+ });
220
+ }
221
+ function estimateRoute(capability, inputTokens) {
222
+ const outputTokens = 512;
223
+ const inputCost = capability.pricing?.inputCostPer1M === void 0 ? void 0 : inputTokens / 1e6 * capability.pricing.inputCostPer1M;
224
+ const outputCost = capability.pricing?.outputCostPer1M === void 0 ? void 0 : outputTokens / 1e6 * capability.pricing.outputCostPer1M;
225
+ return {
226
+ inputTokens,
227
+ outputTokens,
228
+ ...inputCost !== void 0 || outputCost !== void 0 ? { costUsd: (inputCost ?? 0) + (outputCost ?? 0) } : {},
229
+ latencyMs: capability.latency === "interactive" ? 1e3 : 1e4
230
+ };
231
+ }
232
+ function scoreCapability(capability, estimates, index) {
233
+ const costScore = Math.round((estimates.costUsd ?? 0) * 1e6);
234
+ const latencyScore = capability.latency === "interactive" ? 0 : 1e5;
235
+ const contextHeadroom = Math.max(0, capability.contextWindow - estimates.inputTokens);
236
+ const contextScore = Math.max(0, 1e4 - Math.min(contextHeadroom, 1e4));
237
+ return costScore + latencyScore + contextScore + index;
238
+ }
239
+ function compareCandidates(left, right) {
240
+ if (left.accepted !== right.accepted) return left.accepted ? -1 : 1;
241
+ if (left.score !== right.score) return left.score - right.score;
242
+ const provider = left.providerId.localeCompare(right.providerId);
243
+ return provider === 0 ? left.modelId.localeCompare(right.modelId) : provider;
244
+ }
245
+ function requiredInputModalities(artifacts) {
246
+ const modalities = new Set(["text"]);
247
+ for (const artifact of artifacts) switch (artifact.kind) {
248
+ case "text":
249
+ modalities.add("text");
250
+ break;
251
+ case "json":
252
+ modalities.add("json");
253
+ break;
254
+ case "image":
255
+ modalities.add("image");
256
+ break;
257
+ case "audio":
258
+ modalities.add("audio");
259
+ break;
260
+ case "video":
261
+ modalities.add("video");
262
+ break;
263
+ case "document":
264
+ modalities.add("document");
265
+ break;
266
+ case "url":
267
+ modalities.add("url");
268
+ break;
269
+ case "tool-result":
270
+ modalities.add("tool");
271
+ break;
272
+ case "file":
273
+ modalities.add("file");
274
+ break;
275
+ }
276
+ return [...modalities];
277
+ }
278
+ function requiredOutputModalities(outputs) {
279
+ const modalities = /* @__PURE__ */ new Set();
280
+ for (const contract of Object.values(outputs)) {
281
+ if (contract === "text") {
282
+ modalities.add("text");
283
+ continue;
284
+ }
285
+ if (isStructuredContract(contract)) {
286
+ modalities.add("json");
287
+ continue;
288
+ }
289
+ if (isReferenceContract(contract)) modalities.add("json");
290
+ }
291
+ return [...modalities];
292
+ }
293
+ function outputRequiresStructuredOutput(outputs) {
294
+ return Object.values(outputs).some(isStructuredContract);
295
+ }
296
+ function isStructuredContract(contract) {
297
+ return typeof contract === "object" && contract !== null && "~standard" in contract;
298
+ }
299
+ function isReferenceContract(contract) {
300
+ return typeof contract === "object" && contract !== null && "kind" in contract && (contract.kind === "citations" || contract.kind === "artifacts");
301
+ }
302
+ function summarizeNoRouteReasons(candidates) {
303
+ if (candidates.length === 0) return [{
304
+ code: "catalog-empty",
305
+ message: "No provider capabilities are configured."
306
+ }];
307
+ const unique = /* @__PURE__ */ new Map();
308
+ for (const candidate of candidates) for (const reason of candidate.reasons) unique.set(reason.code, reason);
309
+ return [...unique.values()];
310
+ }
311
+ //#endregion
312
+ export { evaluateContractAgainstRoute as i, mergePolicy as n, estimateRouteCost as r, routeDeterministically as t };
313
+
314
+ //# sourceMappingURL=router-DU4Z3pTd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"router-DU4Z3pTd.js","names":[],"sources":["../src/contract/preflight.ts","../src/policy/policy.ts","../src/routing/router.ts"],"sourcesContent":["import type { RouteRejectReason } from \"../plan/plan.js\";\nimport type { ModelCapability } from \"../providers/provider.js\";\nimport { effectivePer1kPricing } from \"../routing/catalog.js\";\nimport type { CapabilityContract } from \"./contract.js\";\n\n/**\n * Result of a single pre-flight contract evaluation against a candidate\n * capability. `reasons` is empty when `ok` is true and contains one or more\n * `RouteRejectReason` entries when `ok` is false.\n *\n * The evaluator surfaces ALL failing reasons in a single pass — not the\n * first-failing only — so the deterministic router can aggregate per-candidate\n * rejection detail (CONTEXT.md \"Pre-flight surfaces ALL failed candidates\n * with per-candidate rejection reasons\").\n */\nexport interface ContractPreflightResult {\n readonly ok: boolean;\n readonly reasons: readonly RouteRejectReason[];\n}\n\n/**\n * Input for the pure cost estimator. Token counts come from the router's\n * existing `estimateRoute()` helper so preflight and router agree on the\n * projected output size (one source of truth — see `evaluateContractAgainstRoute`).\n */\nexport interface EstimateRouteCostInput {\n readonly capability: ModelCapability;\n readonly estimatedInputTokens: number;\n readonly estimatedOutputTokens: number;\n}\n\n/**\n * Pure cost estimator. Returns `null` when pricing is unknown (so downstream\n * gates can distinguish \"free / zero\" from \"unmeasured\" per the Phase 7\n * cost-normalization decision). Uses static catalog metadata only — no probes,\n * no external pricing APIs.\n */\nexport function estimateRouteCost(input: EstimateRouteCostInput): number | null {\n const { inputPer1kTokens, outputPer1kTokens } = effectivePer1kPricing(\n input.capability.pricing,\n );\n if (inputPer1kTokens === undefined && outputPer1kTokens === undefined) {\n return null;\n }\n const inputCost = ((inputPer1kTokens ?? 0) * input.estimatedInputTokens) / 1000;\n const outputCost = ((outputPer1kTokens ?? 0) * input.estimatedOutputTokens) / 1000;\n return inputCost + outputCost;\n}\n\n/** Input for the pre-flight evaluator. */\nexport interface EvaluateContractInput {\n readonly capability: ModelCapability;\n readonly estimatedInputTokens: number;\n readonly estimatedOutputTokens: number;\n}\n\n/**\n * Pure pre-flight evaluator. Phase 9 receipts will reuse this for deterministic\n * verdict reconstruction.\n *\n * Token estimation: Phase 7 does NOT define a separate token estimator. Output-\n * token projection is the canonical responsibility of the router's existing\n * `estimateRoute()` helper (in `routing/router.ts`), which already produces an\n * `estimatedOutputTokens` value. The router passes that same value into this\n * evaluator via `EvaluateContractInput.estimatedOutputTokens`, so preflight\n * and the router always agree on the projected output size. Phase 9 receipts\n * will pin the router's estimate as the deterministic input — intentionally\n * one source of truth.\n *\n * Reject taxonomy (Phase 7 emits three of four codes):\n * - `contract-budget-exceeded` (CONTRACT-04 + COST-03)\n * - `contract-modality-missing` (CONTRACT-06)\n * - `contract-privacy-mismatch` (CONTRACT-06)\n * - `contract-quality-floor` (reserved for Phase 12 `lattice eval`; NEVER emitted here)\n */\nexport function evaluateContractAgainstRoute(\n contract: CapabilityContract | undefined,\n input: EvaluateContractInput,\n): ContractPreflightResult {\n if (contract === undefined) {\n return { ok: true, reasons: [] };\n }\n const reasons: RouteRejectReason[] = [];\n\n // BUDGET — CONTRACT-04 + COST-03\n if (contract.budget?.maxCostUsd !== undefined) {\n const estimatedCost = estimateRouteCost({\n capability: input.capability,\n estimatedInputTokens: input.estimatedInputTokens,\n estimatedOutputTokens: input.estimatedOutputTokens,\n });\n if (estimatedCost === null) {\n reasons.push({\n code: \"contract-budget-exceeded\",\n message: `${input.capability.modelId} pricing unknown; contract budget declared (maxCostUsd=${contract.budget.maxCostUsd}).`,\n });\n } else if (estimatedCost > contract.budget.maxCostUsd) {\n reasons.push({\n code: \"contract-budget-exceeded\",\n message: `${input.capability.modelId} estimated ${estimatedCost.toFixed(6)} exceeds contract budget ${contract.budget.maxCostUsd}.`,\n });\n }\n }\n\n // MODALITY — CONTRACT-06 (contract-modality-missing)\n if (contract.requiredModalities !== undefined) {\n for (const modality of contract.requiredModalities) {\n if (\n !input.capability.inputModalities.includes(modality) &&\n !input.capability.outputModalities.includes(modality)\n ) {\n reasons.push({\n code: \"contract-modality-missing\",\n message: `${input.capability.modelId} does not support required modality ${modality}.`,\n });\n }\n }\n }\n\n // PRIVACY — CONTRACT-06 (contract-privacy-mismatch)\n if (contract.requiredPrivacy !== undefined) {\n if (!input.capability.dataPolicy.privacy.includes(contract.requiredPrivacy)) {\n reasons.push({\n code: \"contract-privacy-mismatch\",\n message: `${input.capability.modelId} does not satisfy contract privacy ${contract.requiredPrivacy}.`,\n });\n }\n }\n\n // QUALITY FLOOR — declared but NOT enforced on the capability side in Phase 7.\n // CONTEXT.md: \"qualityFloor is parsed and forwarded into the pre-flight\n // evaluator but only enforced by Phase 12's lattice eval\".\n // The reject code \"contract-quality-floor\" stays reserved for Phase 12.\n\n return { ok: reasons.length === 0, reasons };\n}\n","export type GatewayMetadataValue =\n | string\n | number\n | boolean\n | null\n | readonly GatewayMetadataValue[]\n | { readonly [key: string]: GatewayMetadataValue };\n\nexport interface GatewayPolicy {\n readonly routeTags?: readonly string[];\n readonly providerPreferences?: readonly string[];\n readonly metadata?: Record<string, GatewayMetadataValue>;\n readonly allowFallbacks?: boolean;\n}\n\nexport interface PolicySpec {\n readonly maxCostUsd?: number;\n readonly latency?: \"interactive\" | \"batch\";\n readonly privacy?: \"standard\" | \"sensitive\" | \"restricted\";\n readonly providerAllowList?: readonly string[];\n readonly providerDenyList?: readonly string[];\n readonly noUpload?: boolean;\n readonly noPublicUrl?: boolean;\n readonly noLogging?: boolean;\n readonly stream?: boolean;\n readonly gateway?: GatewayPolicy;\n readonly metadata?: Record<string, unknown>;\n}\n\nexport function mergePolicy(\n defaultPolicy?: PolicySpec,\n runPolicy?: PolicySpec,\n): PolicySpec | undefined {\n if (defaultPolicy === undefined && runPolicy === undefined) {\n return undefined;\n }\n\n const gateway = mergeGatewayPolicy(defaultPolicy?.gateway, runPolicy?.gateway);\n\n return {\n ...defaultPolicy,\n ...runPolicy,\n ...(gateway !== undefined ? { gateway } : {}),\n };\n}\n\nfunction mergeGatewayPolicy(\n defaultGateway?: GatewayPolicy,\n runGateway?: GatewayPolicy,\n): GatewayPolicy | undefined {\n if (defaultGateway === undefined && runGateway === undefined) {\n return undefined;\n }\n\n const metadata =\n defaultGateway?.metadata !== undefined || runGateway?.metadata !== undefined\n ? {\n ...defaultGateway?.metadata,\n ...runGateway?.metadata,\n }\n : undefined;\n\n return {\n ...defaultGateway,\n ...runGateway,\n ...(metadata !== undefined ? { metadata } : {}),\n };\n}\n","import type { ArtifactInput } from \"../artifacts/artifact.js\";\nimport type { CapabilityContract } from \"../contract/contract.js\";\nimport { evaluateContractAgainstRoute } from \"../contract/preflight.js\";\nimport type { OutputContract, OutputContractMap } from \"../outputs/contracts.js\";\nimport type { PolicySpec } from \"../policy/policy.js\";\nimport type {\n CapabilityModality,\n ModelCapability,\n} from \"../providers/provider.js\";\nimport type {\n RouteCandidate,\n RouteDecision,\n RouteEstimates,\n RouteRejectReason,\n} from \"../plan/plan.js\";\nimport { estimateArtifactTokens, estimateTokens } from \"../context/context-pack.js\";\nimport type { CapabilityCatalog } from \"./catalog.js\";\n\nexport interface RouteRequest {\n readonly task: string;\n readonly artifacts: readonly ArtifactInput[];\n readonly outputs: OutputContractMap;\n readonly policy?: PolicySpec;\n readonly provider?: string;\n readonly model?: string;\n readonly contract?: CapabilityContract;\n}\n\nexport function routeDeterministically(\n catalog: CapabilityCatalog,\n request: RouteRequest,\n): RouteDecision {\n const requiredInputs = requiredInputModalities(request.artifacts);\n const requiredOutputs = requiredOutputModalities(request.outputs);\n const requiresStructuredOutput = outputRequiresStructuredOutput(request.outputs);\n const estimatedInputTokens =\n estimateTokens(request.task) +\n request.artifacts.reduce((total, artifact) => total + estimateArtifactTokens(artifact), 0);\n const candidates = catalog.models\n .map((capability, index) =>\n evaluateCapability(capability, {\n requiredInputs,\n requiredOutputs,\n requiresStructuredOutput,\n estimatedInputTokens,\n ...(request.policy !== undefined ? { policy: request.policy } : {}),\n ...(request.provider !== undefined ? { provider: request.provider } : {}),\n ...(request.model !== undefined ? { model: request.model } : {}),\n ...(request.contract !== undefined ? { contract: request.contract } : {}),\n index,\n }),\n )\n .sort(compareCandidates);\n const accepted = candidates.filter((candidate) => candidate.accepted);\n const selected = accepted[0];\n\n return {\n catalogVersion: catalog.version,\n ...(selected !== undefined\n ? {\n selected: {\n providerId: selected.providerId,\n modelId: selected.modelId,\n score: selected.score,\n estimates: selected.estimates,\n inputModalities: selected.capability.inputModalities,\n outputModalities: selected.capability.outputModalities,\n fileTransport: selected.capability.fileTransport,\n },\n }\n : {}),\n candidates,\n rejected: candidates.filter((candidate) => !candidate.accepted),\n fallbackChain: accepted.slice(1).map((candidate) => ({\n providerId: candidate.providerId,\n modelId: candidate.modelId,\n score: candidate.score,\n reason: \"policy-preserving-fallback\",\n })),\n noRouteReasons:\n selected === undefined\n ? summarizeNoRouteReasons(candidates)\n : [],\n };\n}\n\nfunction evaluateCapability(\n capability: ModelCapability,\n input: {\n readonly requiredInputs: readonly CapabilityModality[];\n readonly requiredOutputs: readonly CapabilityModality[];\n readonly requiresStructuredOutput: boolean;\n readonly estimatedInputTokens: number;\n readonly policy?: PolicySpec;\n readonly provider?: string;\n readonly model?: string;\n readonly contract?: CapabilityContract;\n readonly index: number;\n },\n): RouteCandidate {\n const reasons: RouteRejectReason[] = [];\n\n if (capability.available === false) {\n reasons.push({\n code: \"provider-unavailable\",\n message: `${capability.providerId}/${capability.modelId} is not available.`,\n });\n }\n\n if (input.provider !== undefined && capability.providerId !== input.provider) {\n reasons.push({\n code: \"provider-forced-mismatch\",\n message: `Provider override requires ${input.provider}.`,\n });\n }\n\n if (input.model !== undefined && capability.modelId !== input.model) {\n reasons.push({\n code: \"model-forced-mismatch\",\n message: `Model override requires ${input.model}.`,\n });\n }\n\n for (const modality of input.requiredInputs) {\n if (!capability.inputModalities.includes(modality)) {\n reasons.push({\n code: \"input-modality-unsupported\",\n message: `${capability.modelId} does not support ${modality} input.`,\n });\n }\n }\n\n for (const modality of input.requiredOutputs) {\n if (!capability.outputModalities.includes(modality)) {\n reasons.push({\n code: \"output-modality-unsupported\",\n message: `${capability.modelId} does not support ${modality} output.`,\n });\n }\n }\n\n if (input.requiresStructuredOutput && !capability.structuredOutput) {\n reasons.push({\n code: \"structured-output-unsupported\",\n message: `${capability.modelId} does not support structured output contracts.`,\n });\n }\n\n if (input.estimatedInputTokens > capability.contextWindow) {\n reasons.push({\n code: \"context-window-exceeded\",\n message: `Estimated input ${input.estimatedInputTokens} tokens exceeds ${capability.contextWindow}.`,\n });\n }\n\n const estimates = estimateRoute(capability, input.estimatedInputTokens);\n addPolicyRejectReasons(reasons, capability, estimates, input.policy);\n\n // Phase 7 contract preflight — reuse the router's own output-token estimate\n // so preflight and the router agree on the projected output size (one source\n // of truth, consumed by Phase 9 receipts).\n const contractResult = evaluateContractAgainstRoute(input.contract, {\n capability,\n estimatedInputTokens: input.estimatedInputTokens,\n estimatedOutputTokens: estimates.outputTokens,\n });\n for (const reason of contractResult.reasons) {\n reasons.push(reason);\n }\n\n const score = scoreCapability(capability, estimates, input.index);\n\n return {\n providerId: capability.providerId,\n modelId: capability.modelId,\n capability,\n score,\n accepted: reasons.length === 0,\n reasons,\n estimates,\n };\n}\n\nfunction addPolicyRejectReasons(\n reasons: RouteRejectReason[],\n capability: ModelCapability,\n estimates: RouteEstimates,\n policy?: PolicySpec,\n): void {\n if (policy === undefined) {\n return;\n }\n\n if (\n policy.providerAllowList !== undefined &&\n !policy.providerAllowList.includes(capability.providerId)\n ) {\n reasons.push({\n code: \"provider-not-allowed\",\n message: `${capability.providerId} is not in the provider allow list.`,\n });\n }\n\n if (policy.providerDenyList?.includes(capability.providerId) === true) {\n reasons.push({\n code: \"provider-denied\",\n message: `${capability.providerId} is in the provider deny list.`,\n });\n }\n\n if (\n policy.privacy !== undefined &&\n !capability.dataPolicy.privacy.includes(policy.privacy)\n ) {\n reasons.push({\n code: \"privacy-unsupported\",\n message: `${capability.modelId} does not satisfy ${policy.privacy} privacy.`,\n });\n }\n\n if (policy.noLogging === true && capability.dataPolicy.supportsNoLogging !== true) {\n reasons.push({\n code: \"no-logging-unsupported\",\n message: `${capability.modelId} cannot satisfy noLogging.`,\n });\n }\n\n if (policy.stream === true && capability.streaming !== true) {\n reasons.push({\n code: \"streaming-unsupported\",\n message: `${capability.modelId} does not support streaming.`,\n });\n }\n\n if (\n policy.noUpload === true &&\n capability.fileTransport.length > 0 &&\n capability.fileTransport.every((transport) => transport === \"provider-upload\")\n ) {\n reasons.push({\n code: \"no-upload-violated\",\n message: `${capability.modelId} requires an upload transport disallowed by policy.`,\n });\n }\n\n if (policy.latency !== undefined && capability.latency !== policy.latency) {\n reasons.push({\n code: \"latency-class-mismatch\",\n message: `${capability.modelId} latency class is ${capability.latency}, not ${policy.latency}.`,\n });\n }\n\n if (\n policy.maxCostUsd !== undefined &&\n estimates.costUsd !== undefined &&\n estimates.costUsd > policy.maxCostUsd\n ) {\n reasons.push({\n code: \"budget-exceeded\",\n message: `${capability.modelId} estimated cost ${estimates.costUsd} exceeds maxCostUsd ${policy.maxCostUsd}.`,\n });\n }\n}\n\nfunction estimateRoute(\n capability: ModelCapability,\n inputTokens: number,\n): RouteEstimates {\n const outputTokens = 512;\n const inputCost =\n capability.pricing?.inputCostPer1M === undefined\n ? undefined\n : (inputTokens / 1_000_000) * capability.pricing.inputCostPer1M;\n const outputCost =\n capability.pricing?.outputCostPer1M === undefined\n ? undefined\n : (outputTokens / 1_000_000) * capability.pricing.outputCostPer1M;\n\n return {\n inputTokens,\n outputTokens,\n ...(inputCost !== undefined || outputCost !== undefined\n ? { costUsd: (inputCost ?? 0) + (outputCost ?? 0) }\n : {}),\n latencyMs: capability.latency === \"interactive\" ? 1_000 : 10_000,\n };\n}\n\nfunction scoreCapability(\n capability: ModelCapability,\n estimates: RouteEstimates,\n index: number,\n): number {\n const costScore = Math.round((estimates.costUsd ?? 0) * 1_000_000);\n const latencyScore = capability.latency === \"interactive\" ? 0 : 100_000;\n const contextHeadroom = Math.max(0, capability.contextWindow - estimates.inputTokens);\n const contextScore = Math.max(0, 10_000 - Math.min(contextHeadroom, 10_000));\n\n return costScore + latencyScore + contextScore + index;\n}\n\nfunction compareCandidates(left: RouteCandidate, right: RouteCandidate): number {\n if (left.accepted !== right.accepted) {\n return left.accepted ? -1 : 1;\n }\n\n if (left.score !== right.score) {\n return left.score - right.score;\n }\n\n const provider = left.providerId.localeCompare(right.providerId);\n\n return provider === 0 ? left.modelId.localeCompare(right.modelId) : provider;\n}\n\nfunction requiredInputModalities(\n artifacts: readonly ArtifactInput[],\n): readonly CapabilityModality[] {\n const modalities = new Set<CapabilityModality>([\"text\"]);\n\n for (const artifact of artifacts) {\n switch (artifact.kind) {\n case \"text\":\n modalities.add(\"text\");\n break;\n case \"json\":\n modalities.add(\"json\");\n break;\n case \"image\":\n modalities.add(\"image\");\n break;\n case \"audio\":\n modalities.add(\"audio\");\n break;\n case \"video\":\n modalities.add(\"video\");\n break;\n case \"document\":\n modalities.add(\"document\");\n break;\n case \"url\":\n modalities.add(\"url\");\n break;\n case \"tool-result\":\n modalities.add(\"tool\");\n break;\n case \"file\":\n modalities.add(\"file\");\n break;\n }\n }\n\n return [...modalities];\n}\n\nfunction requiredOutputModalities(\n outputs: OutputContractMap,\n): readonly CapabilityModality[] {\n const modalities = new Set<CapabilityModality>();\n\n for (const contract of Object.values(outputs)) {\n if (contract === \"text\") {\n modalities.add(\"text\");\n continue;\n }\n\n if (isStructuredContract(contract)) {\n modalities.add(\"json\");\n continue;\n }\n\n if (isReferenceContract(contract)) {\n modalities.add(\"json\");\n }\n }\n\n return [...modalities];\n}\n\nfunction outputRequiresStructuredOutput(outputs: OutputContractMap): boolean {\n return Object.values(outputs).some(isStructuredContract);\n}\n\nfunction isStructuredContract(contract: OutputContract): boolean {\n return (\n typeof contract === \"object\" &&\n contract !== null &&\n \"~standard\" in contract\n );\n}\n\nfunction isReferenceContract(contract: OutputContract): boolean {\n return (\n typeof contract === \"object\" &&\n contract !== null &&\n \"kind\" in contract &&\n (contract.kind === \"citations\" || contract.kind === \"artifacts\")\n );\n}\n\nfunction summarizeNoRouteReasons(\n candidates: readonly RouteCandidate[],\n): readonly RouteRejectReason[] {\n if (candidates.length === 0) {\n return [\n {\n code: \"catalog-empty\",\n message: \"No provider capabilities are configured.\",\n },\n ];\n }\n\n const unique = new Map<string, RouteRejectReason>();\n\n for (const candidate of candidates) {\n for (const reason of candidate.reasons) {\n unique.set(reason.code, reason);\n }\n }\n\n return [...unique.values()];\n}\n"],"mappings":";;;;;;;;;AAqCA,SAAgB,kBAAkB,OAA8C;CAC9E,MAAM,EAAE,kBAAkB,sBAAsB,sBAC9C,MAAM,WAAW,QAClB;AACD,KAAI,qBAAqB,KAAA,KAAa,sBAAsB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