@enlitt/sdk 0.1.0 → 0.1.1

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 (72) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +3 -1
  3. package/dist/{chunk-C76K6HLL.cjs → chunk-2BGWYTJM.cjs} +240 -49
  4. package/dist/chunk-2BGWYTJM.cjs.map +1 -0
  5. package/dist/{chunk-VNVMEU34.js → chunk-NI6WH5FI.js} +3 -3
  6. package/dist/{chunk-VNVMEU34.js.map → chunk-NI6WH5FI.js.map} +1 -1
  7. package/dist/{chunk-6DPBYLA5.js → chunk-O6ASIA3X.js} +19 -8
  8. package/dist/chunk-O6ASIA3X.js.map +1 -0
  9. package/dist/{chunk-26SW63P5.cjs → chunk-PPOUNWNA.cjs} +19 -7
  10. package/dist/chunk-PPOUNWNA.cjs.map +1 -0
  11. package/dist/{chunk-SFI4RLNN.js → chunk-UVZMKGIL.js} +198 -7
  12. package/dist/chunk-UVZMKGIL.js.map +1 -0
  13. package/dist/{chunk-G4DTTV5E.cjs → chunk-YPA4R65T.cjs} +7 -7
  14. package/dist/{chunk-G4DTTV5E.cjs.map → chunk-YPA4R65T.cjs.map} +1 -1
  15. package/dist/core/errors.d.cts +13 -5
  16. package/dist/core/errors.d.ts +13 -5
  17. package/dist/core/errors.d.ts.map +1 -1
  18. package/dist/core/index.d.cts +1 -1
  19. package/dist/core/index.d.ts +1 -1
  20. package/dist/core/index.d.ts.map +1 -1
  21. package/dist/core/session.d.cts +15 -0
  22. package/dist/core/session.d.ts +15 -0
  23. package/dist/core/session.d.ts.map +1 -1
  24. package/dist/core/transport.d.cts +1 -1
  25. package/dist/core/transport.d.ts +1 -1
  26. package/dist/core.cjs +22 -18
  27. package/dist/core.js +2 -2
  28. package/dist/openai/client.d.cts +25 -1
  29. package/dist/openai/client.d.ts +25 -1
  30. package/dist/openai/client.d.ts.map +1 -1
  31. package/dist/openai/index.d.cts +1 -0
  32. package/dist/openai/index.d.ts +1 -0
  33. package/dist/openai/index.d.ts.map +1 -1
  34. package/dist/openai/media.d.cts +108 -0
  35. package/dist/openai/media.d.ts +109 -0
  36. package/dist/openai/media.d.ts.map +1 -0
  37. package/dist/openai.cjs +191 -47
  38. package/dist/openai.cjs.map +1 -1
  39. package/dist/openai.js +145 -1
  40. package/dist/openai.js.map +1 -1
  41. package/dist/server/callback.d.cts +2 -1
  42. package/dist/server/callback.d.ts +2 -1
  43. package/dist/server/callback.d.ts.map +1 -1
  44. package/dist/server/client-sign-in.d.cts +77 -0
  45. package/dist/server/client-sign-in.d.ts +78 -0
  46. package/dist/server/client-sign-in.d.ts.map +1 -0
  47. package/dist/server/index.d.cts +2 -1
  48. package/dist/server/index.d.ts +2 -1
  49. package/dist/server/index.d.ts.map +1 -1
  50. package/dist/server.cjs +555 -29
  51. package/dist/server.cjs.map +1 -1
  52. package/dist/server.js +529 -9
  53. package/dist/server.js.map +1 -1
  54. package/dist/vercel/index.d.cts +4 -2
  55. package/dist/vercel/index.d.ts +4 -2
  56. package/dist/vercel/index.d.ts.map +1 -1
  57. package/dist/vercel/language-model.d.cts +17 -2
  58. package/dist/vercel/language-model.d.ts +17 -2
  59. package/dist/vercel/language-model.d.ts.map +1 -1
  60. package/dist/vercel/premium-language-model.d.cts +30 -1
  61. package/dist/vercel/premium-language-model.d.ts +30 -1
  62. package/dist/vercel/premium-language-model.d.ts.map +1 -1
  63. package/dist/vercel/premium-media-model.d.cts +101 -0
  64. package/dist/vercel/premium-media-model.d.ts +102 -0
  65. package/dist/vercel/premium-media-model.d.ts.map +1 -0
  66. package/dist/vercel.cjs +5 -5
  67. package/dist/vercel.js +2 -2
  68. package/package.json +12 -2
  69. package/dist/chunk-26SW63P5.cjs.map +0 -1
  70. package/dist/chunk-6DPBYLA5.js.map +0 -1
  71. package/dist/chunk-C76K6HLL.cjs.map +0 -1
  72. package/dist/chunk-SFI4RLNN.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/vercel/standard-language-model.ts","../src/vercel/premium-language-model.ts","../src/vercel/premium-media-model.ts","../src/vercel/language-model.ts"],"names":["endedAt","wrapped","ENLITT_STANDARD_MODEL"],"mappings":";;;;;AAsEA,IAAM,cAAA,GAAiB,eAAA;AAQvB,IAAM,oBAAA,GAAuB;AAAA,EAC3B,WAAA,EAAa,qBAAA;AAAA,EACb,cAAA,EAAgB,wBAAA;AAAA,EAChB,WAAA,EAAa,qBAAA;AAAA,EACb,aAAA,EAAe;AACjB,CAAA;AA0BO,SAAS,4BAA4B,MAAA,EAA+C;AACzF,EAAA,OAAO;AAAA,IACL,oBAAA,EAAsB,IAAA;AAAA,IACtB,QAAA,EAAU,QAAA;AAAA,IACV,OAAA,EAAS,qBAAA;AAAA;AAAA;AAAA,IAGT,eAAe,EAAC;AAAA,IAEhB,MAAM,WAAW,MAAA,EAA6D;AAC5E,MAAA,MAAM,OAAA,GAAU,qBAAA,CAAsB,MAAA,CAAO,eAAA,EAAiB,UAAU,CAAA;AACxE,MAAA,MAAM,MAAA,GAAS,aAAA,CAAc,OAAA,EAAS,MAAM,CAAA;AAC5C,MAAA,MAAM,IAAA,GAAO,oBAAA,CAAqB,MAAA,EAAQ,OAAe,CAAA;AAEzD,MAAA,MAAM,QAAA,GAAW,MAAM,aAAA,CAAc,MAAA,EAAQ;AAAA,QAC3C,IAAA,EAAM,cAAA;AAAA,QACN,IAAA;AAAA,QACA,MAAA;AAAA,QACA,MAAA,EAAQ,kBAAA;AAAA,QACR,GAAI,OAAO,WAAA,KAAgB,MAAA,GAAY,EAAE,MAAA,EAAQ,MAAA,CAAO,WAAA,EAAY,GAAI;AAAC,OAC1E,CAAA;AAGD,MAAA,MAAM,SAAA,GAAY,uBAAuB,MAAM,cAAA,CAAe,QAAQ,CAAA,EAAG,EAAE,IAAA,EAAM,UAAA,EAAY,CAAA;AAC7F,MAAA,IAAI,CAAC,UAAU,EAAA,EAAI;AACjB,QAAA,MAAM,IAAI,WAAA;AAA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AAAA,OACF;AAAA,IACF,CAAA,MAAO;AACL,MAAA,MAAM,IAAI,wBAAA;AAAA,QACR;AAAA,OACF;AAAA,IACF;AAAA,EACF,CAAA,MAAA,IAAW,OAAO,KAAA,KAAU,QAAA,IAAY,OAAO,KAAK,CAAA,GAAI,MAAA,CAAO,SAAS,CAAA,EAAG;AACzE,IAAA,MAAM,IAAI,wBAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AAEA,EAAA,OAAO,EAAE,WAAW,KAAA,EAAM;AAC5B;AA0BO,SAAS,aAAA,CAAc,SAAgC,MAAA,EAA4C;AACxG,EAAA,MAAM,IAAA,GAAO,OAAA,CAAQ,cAAA,IAAkB,oBAAA,EAAqB;AAK5D,EAAA,OAAO,aAAa,CAAA,EAAG,IAAI,IAAI,MAAA,CAAO,MAAA,CAAO,MAAM,CAAA,CAAE,CAAA;AACvD","file":"chunk-UVZMKGIL.js","sourcesContent":["/**\n * Implements the whole-request path, where Enlitt is the model provider.\n *\n * `specs/SDK-side routing.md` gives this file the job of mapping a pinned\n * Vercel AI SDK call into Enlitt's standard request (`EnlittStandardRequest`),\n * sending the complete request to Enlitt over `core/transport.ts`, and mapping\n * the response or event stream back into provider-interface parts. It is kept\n * separate from `premium-language-model.ts` because the two paths send Enlitt\n * fundamentally different things (a whole request here, a content-free billing\n * lifecycle there), and conflating them would make it possible for a change to\n * one to leak a field into the other.\n *\n * The business supplies no provider model: `model: \"enlitt-standard\"` is the\n * only value this file ever sends, and no parameter anywhere here can override\n * it. `buildStandardRequest()` is also the standard framework-normalization\n * boundary: anything the standard capability floor does not carry is rejected\n * there with `EnlittConfigurationError`, before any request, and never silently\n * dropped or deferred to route selection.\n *\n * Responses and stream events are read in tolerant mode, so a newer server's\n * additions (an unknown enum member, output item, content part, or stream event)\n * degrade into `\"other\"`, a skipped item, or a skipped event instead of an\n * error. Nothing here ever receives or displays a credit, balance, or tier\n * fact: the wire schemas carry none.\n */\n\nimport {\n ENLITT_STANDARD_MODEL,\n isTerminalResponseStreamEventType,\n validateEnlittStandardRequest,\n validateOpenAIResponse,\n validateResponseStreamEvent,\n type EnlittAssistantMessage,\n type EnlittFunctionTool,\n type EnlittStandardMessage,\n type EnlittStandardRequest,\n type EnlittToolCall,\n type EnlittUserPart,\n type OpenAIResponse,\n type ResponseOutputItem,\n type ResponseStreamEvent,\n type UnknownResponseStreamEvent,\n type UnknownVariant\n} from \"@enlitt/protocol\";\nimport type {\n LanguageModelV3,\n LanguageModelV3CallOptions,\n LanguageModelV3Content,\n LanguageModelV3FinishReason,\n LanguageModelV3StreamPart,\n LanguageModelV3Usage,\n SharedV3Warning\n} from \"@ai-sdk/provider\";\nimport { EnlittConfigurationError, EnlittError } from \"../core/errors.js\";\nimport { readEnlittJson, requestEnlitt, type InternalEnlittClient } from \"../core/transport.js\";\nimport { createSseEventStream, SseFramingError, type SseEvent } from \"../core/sse.js\";\nimport { readEnlittCallOptions, resolveCallId, type EnlittProviderOptions } from \"./language-model.js\";\n\n/**\n * Derived rather than invented, per the shared type conventions: the pinned\n * package exports no name for what `doGenerate()` returns, so this alias is the\n * only place that fact is stated, and it can never drift from the interface it\n * claims to implement.\n */\ntype GenerateResult = Awaited<ReturnType<LanguageModelV3[\"doGenerate\"]>>;\n\n/** Same reasoning as {@link GenerateResult}, for `doStream()`. */\ntype StreamResult = Awaited<ReturnType<LanguageModelV3[\"doStream\"]>>;\n\n/** The one relative path this file ever calls, from `specs/PROTOCOLS.md` \"Create model response\". */\nconst RESPONSES_PATH = \"/v1/responses\";\n\n/**\n * Enlitt's own reserved response metadata keys, mapped one-to-one onto\n * `providerMetadata.enlitt`. Reading exactly these four and nothing else keeps\n * a future reserved key (say, a plan fact) from silently reaching a caller just\n * because it showed up in the same map.\n */\nconst ENLITT_METADATA_KEYS = {\n operationId: \"enlitt_operation_id\",\n routedProvider: \"enlitt_routed_provider\",\n routedModel: \"enlitt_routed_model\",\n policyVersion: \"enlitt_policy_version\"\n} as const;\n\n/**\n * The `providerMetadata.enlitt` shape this module ever produces. Never a\n * credit, balance, limit, tier, or period fact. The index signature is what\n * lets it satisfy `SharedV3ProviderMetadata` structurally.\n */\ninterface EnlittRoutingMetadata {\n readonly operationId?: string;\n readonly routedProvider?: string;\n readonly routedModel?: string;\n readonly policyVersion?: string;\n readonly [key: string]: string | undefined;\n}\n\n/**\n * Implements `doGenerate()` and `doStream()` for the pinned Vercel AI SDK\n * provider interface, with `modelId` `\"enlitt-standard\"`.\n *\n * Every invocation follows the sequence the spec names:\n * `readEnlittCallOptions()`, `resolveCallId()`, `buildStandardRequest()`,\n * `requestEnlitt()`. The call ID used for `Idempotency-Key` is therefore derived\n * before the body it protects is built, and a caller's options are read exactly\n * once. This function contains no session logic and no error classification of\n * its own: both live in `transport.ts` and `errors.ts`.\n */\nexport function createStandardLanguageModel(client: InternalEnlittClient): LanguageModelV3 {\n return {\n specificationVersion: \"v3\",\n provider: \"enlitt\",\n modelId: ENLITT_STANDARD_MODEL,\n // Every URL is downloaded by the caller or sent as an image URL rather than\n // referenced natively: no pattern is claimed because none can be verified.\n supportedUrls: {},\n\n async doGenerate(params: LanguageModelV3CallOptions): Promise<GenerateResult> {\n const options = readEnlittCallOptions(params.providerOptions, \"standard\");\n const callId = resolveCallId(options, params);\n const body = buildStandardRequest(params, options, callId);\n\n const response = await requestEnlitt(client, {\n path: RESPONSES_PATH,\n body,\n callId,\n accept: \"application/json\",\n ...(params.abortSignal !== undefined ? { signal: params.abortSignal } : {})\n });\n\n // Tolerant in: unknown fields are dropped and unknown enum members read as \"other\".\n const validated = validateOpenAIResponse(await readEnlittJson(response), { mode: \"tolerant\" });\n if (!validated.ok) {\n throw new EnlittError(\n \"malformed_response\",\n `Enlitt's response could not be validated: ${validated.error.message} (${validated.error.param}).`\n );\n }\n return mapStandardGenerateResponse(validated.value);\n },\n\n async doStream(params: LanguageModelV3CallOptions): Promise<StreamResult> {\n const options = readEnlittCallOptions(params.providerOptions, \"standard\");\n const callId = resolveCallId(options, params);\n const body = buildStandardRequest(params, options, callId, true);\n\n const response = await requestEnlitt(client, {\n path: RESPONSES_PATH,\n body,\n callId,\n accept: \"text/event-stream\",\n ...(params.abortSignal !== undefined ? { signal: params.abortSignal } : {})\n });\n if (response.body === null) {\n throw new EnlittError(\"malformed_response\", \"Enlitt's streaming response carried no body.\");\n }\n const events = createSseEventStream(response.body);\n return { stream: mapStandardStream(events, params.abortSignal) };\n }\n };\n}\n\n// --- Request mapping --------------------------------------------------\n\n/**\n * True when a prompt-level, part-level, or tool-level `providerOptions` object\n * carries anything: standard has no provider-specific per-item controls (an\n * image detail level, a cache hint), so none can be honored and none is dropped.\n */\nfunction hasProviderOptions(value: unknown): boolean {\n return typeof value === \"object\" && value !== null && Object.keys(value).length > 0;\n}\n\n/** Rejects a per-item `providerOptions` instead of silently ignoring it. */\nfunction rejectItemProviderOptions(value: unknown, where: string): void {\n if (hasProviderOptions(value)) {\n throw new EnlittConfigurationError(\n `Enlitt's standard route does not support provider-specific options on ${where}; remove its providerOptions.`\n );\n }\n}\n\n/**\n * Maps supported Vercel input into an `EnlittStandardRequest` and validates it\n * with the protocol's strict validator, so a body built here can never diverge\n * from what the wire accepts.\n *\n * Uses `model: \"enlitt-standard\"` unconditionally. It never sends a provider or\n * model override, `conversation`, `previous_response_id`, `store`, `background`,\n * `include`, `service_tier`, or any other field the protocol rejects, and it\n * raises `EnlittConfigurationError` for each unsupported capability instead of\n * dropping it: structured response formats, sampling controls (temperature,\n * topP, topK, penalties, seed, stop sequences), required or named tool choice,\n * provider-defined tools, file/audio/video parts, reasoning, and\n * provider-specific options.\n *\n * `stream` is the fourth, optional argument because the call site, not the\n * prompt, decides it; it defaults to `false` and is omitted from the body then.\n */\nexport function buildStandardRequest(\n params: LanguageModelV3CallOptions,\n options: EnlittProviderOptions,\n callId: string,\n stream = false\n): EnlittStandardRequest {\n void callId; // The call ID travels as `Idempotency-Key`, not as a body field.\n\n rejectUnsupportedCallControls(params);\n\n const draft: Record<string, unknown> = {\n model: ENLITT_STANDARD_MODEL,\n messages: mapPromptToMessages(params.prompt)\n };\n\n // Unset or \"auto\" sends the tools and relies on automatic selection; \"none\"\n // omits them; required or a named tool cannot be honored and fails locally.\n const choice = params.toolChoice?.type;\n if (choice === \"required\" || choice === \"tool\") {\n throw new EnlittConfigurationError(\n \"Enlitt's standard route supports only automatic tool choice; remove `toolChoice` or set it to auto or none.\"\n );\n }\n if (choice !== \"none\" && params.tools !== undefined && params.tools.length > 0) {\n draft.tools = mapTools(params.tools);\n }\n\n if (params.maxOutputTokens !== undefined) {\n draft.max_output_tokens = params.maxOutputTokens;\n }\n if (stream) {\n draft.stream = true;\n }\n if (options.metadata !== undefined) {\n draft.metadata = options.metadata;\n }\n\n const validated = validateEnlittStandardRequest(draft);\n if (!validated.ok) {\n throw new EnlittConfigurationError(\n `The call could not be mapped to Enlitt's standard request shape: ${validated.error.message} (${validated.error.param}).`\n );\n }\n return validated.value;\n}\n\n/** Rejects every call-level control the standard capability floor does not carry. */\nfunction rejectUnsupportedCallControls(params: LanguageModelV3CallOptions): void {\n const unsupported: [string, boolean][] = [\n [\"temperature\", params.temperature !== undefined],\n [\"topP\", params.topP !== undefined],\n [\"topK\", params.topK !== undefined],\n [\"presencePenalty\", params.presencePenalty !== undefined],\n [\"frequencyPenalty\", params.frequencyPenalty !== undefined],\n [\"seed\", params.seed !== undefined],\n [\"stopSequences\", params.stopSequences !== undefined && params.stopSequences.length > 0],\n // A \"text\" response format is the default and carries nothing; \"json\" is structured output.\n [\"responseFormat\", params.responseFormat !== undefined && params.responseFormat.type !== \"text\"]\n ];\n for (const [name, present] of unsupported) {\n if (present) {\n throw new EnlittConfigurationError(\n `Enlitt's standard route does not support \\`${name}\\`; remove it from the call.`\n );\n }\n }\n\n // Everything other than the Enlitt namespace is provider-specific (reasoning\n // controls, parallel-tool settings, image detail, and so on) and unsupported.\n for (const namespace of Object.keys(params.providerOptions ?? {})) {\n if (namespace !== \"enlitt\") {\n throw new EnlittConfigurationError(\n `Enlitt's standard route does not support provider-specific options (providerOptions.${namespace}); remove them.`\n );\n }\n }\n}\n\n/**\n * Maps the pinned prompt array to the protocol's ordered `messages`. A `tool`\n * role message's results each become their own tool message, in order.\n */\nfunction mapPromptToMessages(prompt: LanguageModelV3CallOptions[\"prompt\"]): EnlittStandardMessage[] {\n const messages: EnlittStandardMessage[] = [];\n for (const message of prompt) {\n rejectItemProviderOptions(message.providerOptions, `a ${message.role} message`);\n switch (message.role) {\n case \"system\": {\n messages.push({ role: \"system\", content: message.content });\n break;\n }\n case \"user\": {\n messages.push({ role: \"user\", content: message.content.map(mapUserPart) });\n break;\n }\n case \"assistant\": {\n messages.push(mapAssistantMessage(message.content));\n break;\n }\n case \"tool\": {\n for (const part of message.content) {\n if (part.type === \"tool-approval-response\") {\n throw new EnlittConfigurationError(\n \"Enlitt's standard route does not support tool approval responses; remove the approval response.\"\n );\n }\n rejectItemProviderOptions(part.providerOptions, \"a tool result\");\n messages.push({ role: \"tool\", tool_call_id: part.toolCallId, content: mapToolResultOutput(part.output) });\n }\n break;\n }\n }\n }\n return messages;\n}\n\n/** Maps one user part: text stays text, an image keeps its position, anything else is rejected. */\nfunction mapUserPart(\n part: Extract<LanguageModelV3CallOptions[\"prompt\"][number], { role: \"user\" }>[\"content\"][number]\n): EnlittUserPart {\n rejectItemProviderOptions(part.providerOptions, `a user ${part.type} part`);\n if (part.type === \"text\") {\n return { type: \"text\", text: part.text };\n }\n if (!part.mediaType.startsWith(\"image/\")) {\n throw new EnlittConfigurationError(\n `Enlitt's standard route supports only text and image parts; \"${part.mediaType}\" files are not supported.`\n );\n }\n if (part.data instanceof URL) {\n return { type: \"image\", source: { type: \"url\", url: part.data.toString() } };\n }\n const data = typeof part.data === \"string\" ? part.data : Buffer.from(part.data).toString(\"base64\");\n // The protocol validator is the authority on which media types are accepted.\n return { type: \"image\", source: { type: \"base64\", media_type: part.mediaType as \"image/png\", data } };\n}\n\n/** Maps an assistant message's text and tool calls; reasoning, files, and provider-run tools are rejected. */\nfunction mapAssistantMessage(\n content: Extract<LanguageModelV3CallOptions[\"prompt\"][number], { role: \"assistant\" }>[\"content\"]\n): EnlittAssistantMessage {\n let text = \"\";\n const toolCalls: EnlittToolCall[] = [];\n for (const part of content) {\n rejectItemProviderOptions(part.providerOptions, `an assistant ${part.type} part`);\n switch (part.type) {\n case \"text\":\n text += part.text;\n break;\n case \"tool-call\": {\n if (part.providerExecuted === true) {\n throw new EnlittConfigurationError(\n \"Enlitt's standard route does not support provider-executed tool calls in history.\"\n );\n }\n toolCalls.push({\n id: part.toolCallId,\n name: part.toolName,\n arguments: typeof part.input === \"string\" ? part.input : JSON.stringify(part.input)\n });\n break;\n }\n case \"file\":\n case \"reasoning\":\n case \"tool-result\":\n throw new EnlittConfigurationError(\n `Enlitt's standard route does not support an assistant \"${part.type}\" part in history.`\n );\n }\n }\n return {\n role: \"assistant\",\n ...(text.length > 0 ? { content: text } : {}),\n ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {})\n };\n}\n\n/** Renders a tool result's output as the string the protocol's tool message carries. */\nfunction mapToolResultOutput(output: { readonly type: string; readonly value?: unknown }): string {\n switch (output.type) {\n case \"text\":\n case \"error-text\":\n return String(output.value);\n case \"json\":\n case \"error-json\":\n return JSON.stringify(output.value);\n default:\n throw new EnlittConfigurationError(\n `Enlitt's standard route does not support a tool result output of type \"${output.type}\".`\n );\n }\n}\n\n/** Maps application-defined function tools; provider-defined tools are rejected. */\nfunction mapTools(tools: NonNullable<LanguageModelV3CallOptions[\"tools\"]>): EnlittFunctionTool[] {\n return tools.map((tool) => {\n if (tool.type !== \"function\") {\n throw new EnlittConfigurationError(\n \"Enlitt's standard route accepts only application-defined function tools, not provider-defined tools.\"\n );\n }\n rejectItemProviderOptions(tool.providerOptions, `the tool \"${tool.name}\"`);\n if (tool.strict !== undefined) {\n throw new EnlittConfigurationError(\n `Enlitt's standard route does not support strict tool schemas; remove \\`strict\\` from the tool \"${tool.name}\".`\n );\n }\n return {\n name: tool.name,\n ...(tool.description !== undefined ? { description: tool.description } : {}),\n input_schema: tool.inputSchema as Record<string, unknown>\n };\n });\n}\n\n// --- Non-streaming response mapping ------------------------------------\n\n/** True for a future output item or content part the protocol reader could not interpret. */\nfunction isUnknownVariant(value: object): value is UnknownVariant {\n return \"unknown\" in value && (value as { unknown?: unknown }).unknown === true;\n}\n\n/**\n * Maps `OpenAIResponse` back into `GenerateResult`, preserving text, function\n * calls, finish reason, and exact usage.\n *\n * An output item or content part that is an `UnknownVariant` is skipped and\n * contributes no content. Each distinct unknown `type` adds exactly one `other`\n * warning telling the business to upgrade the SDK, so a newer server never\n * produces a silent gap.\n */\nexport function mapStandardGenerateResponse(response: OpenAIResponse): GenerateResult {\n const content: LanguageModelV3Content[] = [];\n const skippedTypes = new Set<string>();\n\n for (const item of response.output) {\n if (isUnknownVariant(item)) {\n skippedTypes.add(item.type);\n } else if (item.type === \"message\") {\n for (const part of item.content) {\n if (isUnknownVariant(part)) {\n skippedTypes.add(part.type);\n } else {\n content.push({ type: \"text\", text: part.text });\n }\n }\n } else {\n content.push({ type: \"tool-call\", toolCallId: item.call_id, toolName: item.name, input: item.arguments });\n }\n }\n\n const warnings: SharedV3Warning[] = [...skippedTypes].map((type) => ({\n type: \"other\",\n message:\n `Enlitt returned an output item of type \"${type}\" that this version of @enlitt/sdk does not recognize ` +\n \"and skipped it. Upgrade @enlitt/sdk to receive it.\"\n }));\n\n return {\n content,\n finishReason: mapFinishReason(response),\n usage: mapUsage(response),\n warnings,\n ...(hasRoutingMetadata(response) ? { providerMetadata: { enlitt: routingMetadata(response) } } : {})\n };\n}\n\n/**\n * Maps a response's terminal facts to the unified finish reason. A status or an\n * incomplete reason read as `\"other\"` (a newer server's member) is never\n * mapped to `\"stop\"` and never triggers the tool-call or length branch.\n */\nfunction mapFinishReason(response: OpenAIResponse): LanguageModelV3FinishReason {\n switch (response.status) {\n case \"other\":\n return { unified: \"other\", raw: undefined };\n case \"failed\":\n return { unified: \"error\", raw: response.error?.code };\n case \"incomplete\": {\n const reason = response.incomplete_details?.reason;\n if (reason === \"max_output_tokens\") {\n return { unified: \"length\", raw: reason };\n }\n return { unified: \"other\", raw: reason === \"other\" ? undefined : reason };\n }\n case \"completed\":\n return response.output.some((item) => !isUnknownVariant(item) && item.type === \"function_call\")\n ? { unified: \"tool-calls\", raw: response.status }\n : { unified: \"stop\", raw: response.status };\n case \"in_progress\":\n case \"queued\":\n case \"cancelled\":\n // Not a finished answer, so not \"stop\".\n return { unified: \"other\", raw: response.status };\n }\n}\n\n/**\n * Passes `OpenAIResponse.usage` through exactly: no derived figure beyond the\n * documented subtractions, and no default when a token count is absent.\n * `undefined` stays `undefined` rather than becoming `0`, because a zero the\n * provider never reported is a fabricated fact.\n */\nfunction mapUsage(response: OpenAIResponse): LanguageModelV3Usage {\n const usage = response.usage;\n const cachedTokens = usage?.input_tokens_details?.cached_tokens;\n const reasoningTokens = usage?.output_tokens_details?.reasoning_tokens;\n return {\n inputTokens: {\n total: usage?.input_tokens,\n noCache: usage !== undefined && cachedTokens !== undefined ? usage.input_tokens - cachedTokens : undefined,\n cacheRead: cachedTokens,\n cacheWrite: undefined\n },\n outputTokens: {\n total: usage?.output_tokens,\n text:\n usage?.output_tokens !== undefined && reasoningTokens !== undefined\n ? usage.output_tokens - reasoningTokens\n : usage?.output_tokens,\n reasoning: reasoningTokens\n }\n };\n}\n\nfunction hasRoutingMetadata(response: OpenAIResponse): boolean {\n return Object.values(ENLITT_METADATA_KEYS).some((key) => response.metadata[key] !== undefined);\n}\n\n/**\n * Reads exactly the four documented `enlitt_*` keys off `response.metadata` by\n * name, never wholesale, so a caller-supplied entry or a future reserved key\n * cannot leak into `providerMetadata.enlitt`.\n */\nfunction routingMetadata(response: OpenAIResponse): EnlittRoutingMetadata {\n const metadata = response.metadata;\n const pick = <K extends keyof typeof ENLITT_METADATA_KEYS>(name: K): Partial<Record<K, string>> => {\n const value = metadata[ENLITT_METADATA_KEYS[name]];\n return value !== undefined ? ({ [name]: value } as Partial<Record<K, string>>) : {};\n };\n return {\n ...pick(\"operationId\"),\n ...pick(\"routedProvider\"),\n ...pick(\"routedModel\"),\n ...pick(\"policyVersion\")\n };\n}\n\n// --- Streaming response mapping -----------------------------------------\n\n/** A parsed stream event that may be a future, skipped one. */\ntype ParsedEvent = ResponseStreamEvent | UnknownResponseStreamEvent;\n\n/** True for an event this version knows (an unknown event has no `response`/`item` payload kept). */\nfunction isKnownEvent(event: ParsedEvent): event is ResponseStreamEvent {\n return !isUnknownVariant(event);\n}\n\n/** A known terminal event; an unknown event is never terminal. */\nfunction isTerminalEvent(event: ParsedEvent): boolean {\n return isKnownEvent(event) && isTerminalResponseStreamEventType(event.type);\n}\n\n/** Structural equality over parsed events, to tell an identical repeat from a conflicting duplicate. */\nfunction sameEvent(a: ParsedEvent, b: ParsedEvent): boolean {\n return JSON.stringify(a) === JSON.stringify(b);\n}\n\n/**\n * Consumes the events `createSseEventStream()` produces, parses each `data`\n * payload in tolerant mode, enforces the ordering rule incrementally, and emits\n * provider-interface stream parts one event at a time.\n *\n * Ordering: the first event must be `response.created`; each next event's\n * `sequence_number` must be exactly one more than the previous (a gap or a\n * lower number is rejected), except an identical repeat of the last event,\n * which is absorbed; nothing may follow the terminal event; and a stream that\n * ends without a known terminal event is rejected. An unknown event takes part\n * in the sequence check but emits nothing and is never terminal.\n *\n * Every protocol violation (bad JSON, a bad shape, a gap, an out-of-order or\n * conflicting event, a missing or trailing terminal) ends the stream with one\n * `error` part carrying a `malformed_response` `EnlittError`, then closes it.\n * A failed response terminates with a single `finish` part whose reason is\n * `\"error\"`. Abort and source read failures error the stream with the\n * underlying reason.\n *\n * Backpressure and cancellation are preserved: `pull` reads and enqueues at\n * most one batch of parts per consumer pull, so the consumer's read rate\n * governs how far the HTTP read runs ahead, and `cancel` and `signal` abort the\n * same in-flight request. No event content is buffered whole, copied, hashed,\n * or logged.\n */\nexport function mapStandardStream(\n events: ReadableStream<SseEvent>,\n signal?: AbortSignal\n): ReadableStream<LanguageModelV3StreamPart> {\n const reader = events.getReader();\n let lastEvent: ParsedEvent | undefined;\n let terminated = false;\n // Set once the terminal part has been emitted but before `terminated`: data\n // after the terminal event can only be detected by reading one event past it.\n let sawTerminal = false;\n const openText = new Set<string>();\n // Function-call items announced by `output_item.added`, keyed by item ID, so\n // later deltas and the done event can recover the call ID and tool name.\n const toolItems = new Map<string, { callId: string; name: string }>();\n\n function onAbort(controller: ReadableStreamDefaultController<LanguageModelV3StreamPart>): void {\n if (!terminated) {\n terminated = true;\n controller.error(signal?.reason);\n void reader.cancel(signal?.reason).catch(() => undefined);\n }\n }\n\n /** Ends the stream with one malformed-response error part, then closes and cancels the source. */\n function reject(controller: ReadableStreamDefaultController<LanguageModelV3StreamPart>, message: string): void {\n terminated = true;\n controller.enqueue({ type: \"error\", error: new EnlittError(\"malformed_response\", message) });\n controller.close();\n void reader.cancel().catch(() => undefined);\n }\n\n return new ReadableStream<LanguageModelV3StreamPart>({\n start(controller) {\n if (signal !== undefined) {\n if (signal.aborted) {\n onAbort(controller);\n } else {\n signal.addEventListener(\"abort\", () => onAbort(controller), { once: true });\n }\n }\n },\n async pull(controller) {\n // A loop, not one pass: Web Streams re-invoke `pull()` only after it\n // enqueues something, and several events translate to zero parts on\n // purpose (an absorbed repeat, an unknown event, bookkeeping events).\n for (;;) {\n if (terminated) {\n return;\n }\n\n let raw: ReadableStreamReadResult<SseEvent>;\n try {\n raw = await reader.read();\n } catch (thrown) {\n if (thrown instanceof SseFramingError) {\n reject(controller, thrown.message);\n } else {\n terminated = true;\n controller.error(thrown);\n }\n return;\n }\n\n if (sawTerminal) {\n // This cycle exists only to confirm nothing followed the terminal event.\n if (raw.done) {\n terminated = true;\n controller.close();\n } else {\n reject(controller, \"A stream event was received after the terminal event.\");\n }\n return;\n }\n\n if (raw.done) {\n reject(controller, \"The stream ended before a terminal event was received.\");\n return;\n }\n\n let json: unknown;\n try {\n json = JSON.parse(raw.value.data) as unknown;\n } catch {\n reject(controller, \"A stream event's data payload was not valid JSON.\");\n return;\n }\n\n const validated = validateResponseStreamEvent(json, { mode: \"tolerant\" });\n if (!validated.ok) {\n reject(controller, `A stream event failed validation: ${validated.error.message} (${validated.error.param}).`);\n return;\n }\n\n const event = validated.value;\n const orderingError = checkIncrementalOrdering(lastEvent, event);\n if (orderingError !== undefined) {\n reject(controller, orderingError);\n return;\n }\n\n // An identical repeat carries no new information and is absorbed.\n const isIdenticalRepeat = lastEvent !== undefined && sameEvent(lastEvent, event);\n lastEvent = event;\n if (isIdenticalRepeat) {\n continue;\n }\n\n const parts = isKnownEvent(event) ? translateEvent(event, openText, toolItems) : [];\n\n if (isTerminalEvent(event)) {\n sawTerminal = true;\n }\n\n if (parts.length === 0) {\n continue;\n }\n for (const part of parts) {\n controller.enqueue(part);\n }\n return;\n }\n },\n async cancel(reason) {\n terminated = true;\n await reader.cancel(reason);\n }\n });\n}\n\n/**\n * The incremental form of the protocol's ordering rule: `response.created`\n * first, then sequence numbers advancing by exactly one (an identical repeat of\n * the previous event excepted), and nothing after the terminal event.\n */\nfunction checkIncrementalOrdering(previous: ParsedEvent | undefined, next: ParsedEvent): string | undefined {\n if (previous === undefined) {\n return next.type === \"response.created\"\n ? undefined\n : `The first stream event must be \"response.created\", got \"${next.type}\".`;\n }\n if (isTerminalEvent(previous)) {\n return \"A stream event was received after the terminal event.\";\n }\n if (next.sequence_number === previous.sequence_number) {\n return sameEvent(previous, next)\n ? undefined\n : \"Two stream events carried the same sequence_number with conflicting payloads.\";\n }\n if (next.sequence_number < previous.sequence_number) {\n return \"A stream event arrived out of order (its sequence_number was lower than a prior event's).\";\n }\n if (next.sequence_number !== previous.sequence_number + 1) {\n return \"A stream event's sequence_number skipped a value (a gap in the sequence).\";\n }\n return undefined;\n}\n\n/**\n * Translates one known stream event into zero or more provider-interface parts.\n * Each event maps to at most a handful of parts and none needs anything beyond\n * the single event just received, plus the small ID bookkeeping, which is what\n * keeps the stream from ever buffering a complete output.\n */\nfunction translateEvent(\n event: ResponseStreamEvent,\n openText: Set<string>,\n toolItems: Map<string, { callId: string; name: string }>\n): LanguageModelV3StreamPart[] {\n switch (event.type) {\n case \"response.created\":\n return [{ type: \"stream-start\", warnings: [] }];\n\n case \"response.output_item.added\": {\n // An unknown item emits nothing; a function call announces its tool input.\n const item: ResponseOutputItem = event.item;\n if (isUnknownVariant(item) || item.type !== \"function_call\") {\n return [];\n }\n toolItems.set(item.id, { callId: item.call_id, name: item.name });\n return [{ type: \"tool-input-start\", id: item.call_id, toolName: item.name }];\n }\n\n case \"response.output_text.delta\": {\n const parts: LanguageModelV3StreamPart[] = [];\n if (!openText.has(event.item_id)) {\n openText.add(event.item_id);\n parts.push({ type: \"text-start\", id: event.item_id });\n }\n parts.push({ type: \"text-delta\", id: event.item_id, delta: event.delta });\n return parts;\n }\n\n case \"response.output_text.done\": {\n const parts: LanguageModelV3StreamPart[] = [];\n if (!openText.has(event.item_id)) {\n parts.push({ type: \"text-start\", id: event.item_id });\n }\n openText.delete(event.item_id);\n parts.push({ type: \"text-end\", id: event.item_id });\n return parts;\n }\n\n case \"response.function_call_arguments.delta\": {\n const tool = toolItems.get(event.item_id);\n return [{ type: \"tool-input-delta\", id: tool?.callId ?? event.item_id, delta: event.delta }];\n }\n\n case \"response.function_call_arguments.done\": {\n const tool = toolItems.get(event.item_id);\n const callId = tool?.callId ?? event.item_id;\n return [\n { type: \"tool-input-end\", id: callId },\n { type: \"tool-call\", toolCallId: callId, toolName: tool?.name ?? event.item_id, input: event.arguments }\n ];\n }\n\n case \"response.completed\":\n case \"response.incomplete\":\n case \"response.failed\":\n // A failure ends in a single finish part whose reason is \"error\"; this\n // keeps \"exactly one finish or error part\" true on every terminal path.\n // A terminal response may carry an empty `output` after streaming, so a\n // completed stream that emitted tool calls finishes as \"tool-calls\".\n return [\n {\n type: \"finish\",\n finishReason:\n event.type === \"response.completed\" && toolItems.size > 0 && event.response.status === \"completed\"\n ? { unified: \"tool-calls\", raw: event.response.status }\n : mapFinishReason(event.response),\n usage: mapUsage(event.response),\n ...(hasRoutingMetadata(event.response) ? { providerMetadata: { enlitt: routingMetadata(event.response) } } : {})\n }\n ];\n\n // Bookkeeping events carry nothing a consumer needs.\n case \"response.in_progress\":\n case \"response.output_item.done\":\n case \"response.content_part.added\":\n case \"response.content_part.done\":\n return [];\n }\n}\n","/**\n * The Vercel AI SDK adapter over the framework-neutral premium lifecycle.\n *\n * `specs/SDK-side routing.md` gives this file only the provider mapping around\n * `core/premium.ts`: it wraps the provider model a business selected and pays\n * for, maps each provider-interface outcome onto the core's status and charge,\n * collects the price context, and offers `perToken()`. It contains no begin, no\n * status rule, no clamp, and no report of its own; all of those are\n * `runPremiumCharge()`'s, so a business moving a call between this wrapper and\n * `withPremiumCharge()` changes how the charge is computed and nothing about how\n * it is settled.\n *\n * The internal client is never null: an SDK holding no Enlitt configuration\n * fails at construction (`createInternalClient()`), before any model exists, so\n * there is no premium model that can reach a provider without Enlitt having\n * admitted the call first. A session that is absent, expired, or revoked fails\n * the call with the provider uninvoked, because letting a rejected session fall\n * through would silently move that user's spend onto the business.\n *\n * Nothing about a call's content is ever sent to Enlitt: the price context lives\n * and dies in the business's own process.\n */\n\nimport type {\n LanguageModelV3,\n LanguageModelV4,\n LanguageModelV3CallOptions,\n LanguageModelV3StreamPart,\n LanguageModelV3Usage\n} from \"@ai-sdk/provider\";\nimport { EnlittConfigurationError } from \"../core/errors.js\";\nimport {\n assertNanoUsd,\n isCancellation,\n runPremiumCharge,\n type PremiumChargeRequest,\n type PremiumChargeHandle,\n type PremiumChargeFunction,\n type PremiumTerminalFacts\n} from \"../core/premium.js\";\nimport type { InternalEnlittClient } from \"../core/transport.js\";\nimport {\n readEnlittCallOptions,\n resolveCallId,\n type EnlittPrice,\n type PremiumPriceContext\n} from \"./language-model.js\";\n\n/**\n * Derived rather than invented, per the shared type conventions: the pinned\n * package exports no name for what `doGenerate()` returns, so this alias is the\n * only place that fact is stated and it can never drift from the interface it\n * claims to implement.\n */\ntype GenerateResult = Awaited<ReturnType<LanguageModelV3[\"doGenerate\"]>>;\n\n/** Same reasoning as {@link GenerateResult}, for `doStream()`. */\ntype StreamResult = Awaited<ReturnType<LanguageModelV3[\"doStream\"]>>;\n\n// --- perToken ----------------------------------------------------------------\n\n/**\n * Returns a price function: `input x usage.inputTokens.total + output x\n * usage.outputTokens.total`, both rates in NANOUSD per token as canonical\n * strings, computed exactly in `bigint`. A missing total counts as zero, so a\n * canceled call with no usage charges nothing for that side. Cached and\n * reasoning tokens are priced as ordinary input and output tokens, as they are\n * already inside the totals; a business that prices them differently writes its\n * own function. Non-canonical rates are rejected as `EnlittConfigurationError`\n * when the function is created, not when it runs.\n */\nexport function perToken(rates: { input: string; output: string }): (context: PremiumPriceContext) => string {\n const inputRate = BigInt(assertNanoUsd(rates.input, \"perToken input rate\"));\n const outputRate = BigInt(assertNanoUsd(rates.output, \"perToken output rate\"));\n\n return (context) => {\n const inputTokens = BigInt(context.usage?.inputTokens.total ?? 0);\n const outputTokens = BigInt(context.usage?.outputTokens.total ?? 0);\n return (inputRate * inputTokens + outputRate * outputTokens).toString();\n };\n}\n\n// --- The wrapping model --------------------------------------------------------\n\n/**\n * Transparently wraps the business's own provider model with the premium\n * billing lifecycle.\n *\n * Preserves every request, provider option, result, warning, error, response ID,\n * and stream part `model` itself produces, adding only `providerMetadata.enlitt`\n * (`{ operationId, effectiveMaxChargeNanoUsd }` and nothing else) to the\n * non-streaming result and to a stream's `finish` part. `provider` and\n * `modelId` pass straight through, because this middleware changes nothing\n * about which provider or model identity a caller sees.\n *\n * One model invocation is one operation. A Vercel agent loop invokes the model\n * once per step, so each step has its own maximum, price, and report; an\n * automatic retry of the same step re-presents the same prompt, resolves the\n * same call ID, and replays the same operation instead of beginning a second.\n *\n * A `v4` model (`ai@7`, Bug #28) is wrapped as a `v4` model. Its extra call\n * options, result fields, part types, and finish reasons pass through by\n * identity; the lifecycle below reads only members `v3` and `v4` share, which\n * is why the body is written once against the `v3` types.\n */\nexport function createPremiumLanguageModel(client: InternalEnlittClient, model: LanguageModelV3): LanguageModelV3;\nexport function createPremiumLanguageModel(client: InternalEnlittClient, model: LanguageModelV4): LanguageModelV4;\nexport function createPremiumLanguageModel(\n client: InternalEnlittClient,\n model: LanguageModelV3 | LanguageModelV4\n): LanguageModelV3 | LanguageModelV4;\nexport function createPremiumLanguageModel(\n client: InternalEnlittClient,\n wrappedModel: LanguageModelV3 | LanguageModelV4\n): LanguageModelV3 | LanguageModelV4 {\n // Read through the `v3` shape; see the doc comment for why that is safe.\n const model = wrappedModel as LanguageModelV3;\n const wrapper = {\n specificationVersion: wrappedModel.specificationVersion,\n provider: model.provider,\n modelId: model.modelId,\n supportedUrls: model.supportedUrls,\n\n doGenerate(params: LanguageModelV3CallOptions): Promise<GenerateResult> {\n return invoke(params, (request, price) =>\n wrapPremiumGenerate(client, request, price, () => Promise.resolve(model.doGenerate(params)))\n );\n },\n\n doStream(params: LanguageModelV3CallOptions): Promise<StreamResult> {\n return invoke(params, (request, price) =>\n wrapPremiumStream(client, request, price, () => Promise.resolve(model.doStream(params)))\n );\n }\n };\n return wrapper as LanguageModelV3 | LanguageModelV4;\n\n /**\n * Reads this invocation's options and call identity, then hands the wrapper a\n * request carrying the provider labels read from the wrapped model itself.\n * Option errors are thrown synchronously inside the returned promise, before\n * any Enlitt or provider request.\n */\n async function invoke<T>(\n params: LanguageModelV3CallOptions,\n wrap: (request: PremiumChargeRequest, price: EnlittPrice | undefined) => Promise<T>\n ): Promise<T> {\n const options = readEnlittCallOptions(params.providerOptions, \"premium\");\n const callId = resolveCallId(options, params);\n // `maxCharge` is always present for a premium call: `readEnlittCallOptions`\n // resolves it from the declared value or a constant price.\n const request: PremiumChargeRequest = {\n maxCharge: options.maxCharge!,\n provider: { id: model.provider, model: model.modelId },\n callId,\n ...(options.reportingDeadlineMs !== undefined ? { reportingDeadlineMs: options.reportingDeadlineMs } : {}),\n ...(options.metadata !== undefined ? { metadata: options.metadata } : {}),\n ...(params.abortSignal !== undefined ? { signal: params.abortSignal } : {})\n };\n return wrap(request, options.price);\n }\n}\n\n// --- Price evaluation ------------------------------------------------------\n\n/**\n * Resolves what the call charges, for a status of `completed` or `canceled`.\n *\n * - No `price`: `\"0\"` (a call with only `maxCharge` is free).\n * - A constant: that constant, on both statuses.\n * - A function: awaited exactly once, with no timeout of its own (a price that\n * misses the terminal deadline only costs the business, because the call then\n * expires and charges nothing). A throw, a rejection, or a result that is not\n * a canonical nonnegative NANOUSD string charges `\"0\"` and is passed to\n * `onTerminalReportError` as an `EnlittConfigurationError`; the call's own\n * result or stream is unaffected.\n *\n * It never lowers the result to the effective maximum: that is the core's rule,\n * applied when it reports. Generic over the context so the media wrappers\n * (`premium-media-model.ts`) share this one rule rather than copying it.\n */\nexport async function evaluatePrice<Context = PremiumPriceContext>(\n client: InternalEnlittClient,\n price: string | ((context: Context) => string | Promise<string>) | undefined,\n context: Context\n): Promise<string> {\n if (price === undefined) {\n return \"0\";\n }\n if (typeof price === \"string\") {\n return price;\n }\n try {\n return assertNanoUsd(await price(context), \"price() result\");\n } catch (thrown) {\n const detail = thrown instanceof Error ? thrown.message : \"the price function failed\";\n client.onTerminalReportError?.(\n thrown instanceof EnlittConfigurationError\n ? thrown\n : new EnlittConfigurationError(`The price function failed, so the call was charged \"0\": ${detail}`)\n );\n return \"0\";\n }\n}\n\n// --- Generate --------------------------------------------------------------\n\n/**\n * The Vercel adapter over `runPremiumCharge()` for a non-streaming call.\n *\n * A result is `completed`, a `length` finish included. A rejection while the\n * call is canceled evaluates `price` with `status: \"canceled\"`, no usage, and\n * empty content before rethrowing. Any other provider error is `failed`, is\n * rethrown unchanged, and never calls `price`.\n */\nexport function wrapPremiumGenerate(\n client: InternalEnlittClient,\n request: PremiumChargeRequest,\n price: EnlittPrice | undefined,\n run: () => Promise<GenerateResult>\n): Promise<GenerateResult> {\n return runPremiumCharge(client, request, async (charge, operation) => {\n const startedAt = new Date();\n let result: GenerateResult;\n try {\n result = await run();\n } catch (thrown) {\n if (isCancellation(thrown, request.signal)) {\n const endedAt = new Date();\n charge(\n await evaluatePrice(client, price, {\n status: \"canceled\",\n output: { kind: \"generate\", content: [] },\n startedAt,\n endedAt,\n durationMs: endedAt.getTime() - startedAt.getTime(),\n effectiveMaxChargeNanoUsd: operation.effectiveMaxChargeNanoUsd\n })\n );\n operation.describe({\n timing: timingFacts(startedAt, endedAt),\n delivery: { outputStarted: false, outputCompleted: false },\n errorCategory: \"canceled\"\n });\n } else {\n operation.describe({\n timing: timingFacts(startedAt, new Date()),\n delivery: { outputStarted: false, outputCompleted: false },\n errorCategory: \"provider\"\n });\n }\n // Rethrown completely unchanged: a provider's own error must never become\n // an `EnlittError`, and the core rethrows exactly what it is given.\n throw thrown;\n }\n\n const endedAt = new Date();\n charge(\n await evaluatePrice(client, price, {\n status: \"completed\",\n output: { kind: \"generate\", content: result.content },\n usage: result.usage,\n finishReason: result.finishReason,\n ...(result.providerMetadata !== undefined ? { providerMetadata: result.providerMetadata } : {}),\n startedAt,\n endedAt,\n durationMs: endedAt.getTime() - startedAt.getTime(),\n effectiveMaxChargeNanoUsd: operation.effectiveMaxChargeNanoUsd\n })\n );\n operation.describe({\n timing: timingFacts(startedAt, endedAt),\n delivery: { outputStarted: true, outputCompleted: true },\n finishReason: result.finishReason.unified,\n ...(result.response?.id !== undefined ? { providerResponseId: result.response.id } : {}),\n ...usageFacts(result.usage)\n });\n\n return attachEnlittMetadataToGenerateResult(result, operation);\n });\n}\n\n// --- Stream ----------------------------------------------------------------\n\n/** The stream parts that count as the model having started producing content (for time to first token). */\nconst CONTENT_PART_TYPES: ReadonlySet<string> = new Set([\n \"text-delta\",\n \"reasoning-delta\",\n \"tool-input-delta\",\n \"tool-call\",\n \"file\",\n \"source\"\n]);\n\n/** How a wrapped stream ended, decided exactly once by its settle latch. */\ntype StreamOutcome = \"completed\" | \"failed\" | \"canceled\";\n\n/** The two ends of the promise the core's `run` is parked on while a stream is open. */\ninterface RunSettler {\n resolve: () => void;\n reject: (reason: unknown) => void;\n}\n\n/**\n * The Vercel adapter over `runPremiumCharge()` for a streaming call.\n *\n * The returned promise resolves with the wrapped `StreamResult` as soon as the\n * provider's `doStream` resolves, while the core's `run` stays pending until\n * the stream terminates, so `doStream` returns as early as the unwrapped model\n * would. A begin refusal rejects `doStream` before the provider is invoked, and\n * a provider that rejects outright is reported `failed` and rethrown unchanged.\n *\n * The returned stream passes every part through unchanged, unbuffered, and with\n * backpressure preserved (it reads one source chunk per consumer pull),\n * collecting parts only when `price` is a function. A finish part (a `length`\n * finish included) settles the operation `completed`; an error part, a source\n * error, or a source that ends with no finish settles it `failed`; consumer\n * cancellation or an aborted `request.signal` settles it `canceled`. Creating a\n * stream reports nothing; the report is sent when the stream terminates, and\n * the stream is not closed until it has been sent, so a serverless process\n * cannot end between the last part and its report. A rejection the core raises\n * after the stream was returned is observed here and never becomes an\n * unhandled rejection.\n */\nexport function wrapPremiumStream(\n client: InternalEnlittClient,\n request: PremiumChargeRequest,\n price: EnlittPrice | undefined,\n run: () => Promise<StreamResult>\n): Promise<StreamResult> {\n return new Promise<StreamResult>((resolveStreamResult, rejectStreamResult) => {\n const settler = {} as RunSettler;\n\n const lifecycle: Promise<void> = runPremiumCharge(client, request, async (charge, operation) => {\n const startedAt = new Date();\n let result: StreamResult;\n try {\n result = await run();\n } catch (thrown) {\n operation.describe({\n timing: timingFacts(startedAt, new Date()),\n delivery: { outputStarted: false, outputCompleted: false },\n errorCategory: isCancellation(thrown, request.signal) ? \"canceled\" : \"provider\"\n });\n throw thrown;\n }\n\n const parked = new Promise<void>((resolve, reject) => {\n settler.resolve = resolve;\n settler.reject = reject;\n });\n resolveStreamResult(wrapStream(client, request, price, result, charge, operation, startedAt, settler, lifecycle));\n return parked;\n });\n\n // Before the stream is returned this rejection is `doStream`'s own (a begin\n // refusal or a provider rejection, rethrown unchanged). Afterwards the\n // outer promise has already resolved, so this is a no-op that only observes\n // the rejection a failed or canceled stream's report path ends with.\n lifecycle.catch(rejectStreamResult);\n });\n}\n\n/**\n * Builds the pass-through stream and its settle latch for one operation.\n * Split out of {@link wrapPremiumStream} so the latch reads top to bottom.\n */\nfunction wrapStream(\n client: InternalEnlittClient,\n request: PremiumChargeRequest,\n price: EnlittPrice | undefined,\n result: StreamResult,\n charge: PremiumChargeFunction,\n operation: PremiumChargeHandle,\n startedAt: Date,\n settler: RunSettler,\n lifecycle: Promise<unknown>\n): StreamResult {\n const collectParts = typeof price === \"function\";\n const parts: LanguageModelV3StreamPart[] = [];\n const reader = result.stream.getReader();\n\n let outputStarted = false;\n let firstContentAt: Date | undefined;\n let finish: Extract<LanguageModelV3StreamPart, { type: \"finish\" }> | undefined;\n let sawErrorPart = false;\n let responseId: string | undefined;\n\n /** The latch: the first caller decides the outcome; every later caller awaits the same settlement. */\n let settlement: Promise<void> | undefined;\n const settle = (outcome: StreamOutcome): Promise<void> => {\n settlement ??= (async () => {\n const endedAt = new Date();\n const facts = {\n timing: timingFacts(startedAt, endedAt),\n delivery: { outputStarted, outputCompleted: outcome === \"completed\" }\n };\n\n if (outcome === \"failed\") {\n // `price` is never called for a failure, and the core reports \"0\".\n operation.describe({ ...facts, errorCategory: \"provider\" });\n settler.reject(new Error(\"The provider stream failed.\"));\n } else {\n charge(\n await evaluatePrice(client, price, {\n status: outcome,\n output: { kind: \"stream\", parts },\n ...(finish !== undefined ? { usage: finish.usage, finishReason: finish.finishReason } : {}),\n ...(finish?.providerMetadata !== undefined ? { providerMetadata: finish.providerMetadata } : {}),\n startedAt,\n endedAt,\n durationMs: endedAt.getTime() - startedAt.getTime(),\n ...(firstContentAt !== undefined\n ? { timeToFirstTokenMs: firstContentAt.getTime() - startedAt.getTime() }\n : {}),\n effectiveMaxChargeNanoUsd: operation.effectiveMaxChargeNanoUsd\n })\n );\n operation.describe({\n ...facts,\n ...(finish !== undefined ? { finishReason: finish.finishReason.unified, ...usageFacts(finish.usage) } : {}),\n ...(responseId !== undefined ? { providerResponseId: responseId } : {}),\n ...(outcome === \"canceled\" ? { errorCategory: \"canceled\" as const } : {})\n });\n if (outcome === \"completed\") {\n settler.resolve();\n } else {\n // The core classifies a rejection named AbortError as canceled.\n settler.reject(Object.assign(new Error(\"The stream was canceled.\"), { name: \"AbortError\" }));\n }\n }\n // Wait for the one terminal report so the stream never closes before it.\n await lifecycle.catch(() => undefined);\n })();\n return settlement;\n };\n\n const stream = new ReadableStream<LanguageModelV3StreamPart>({\n async pull(controller) {\n let chunk: ReadableStreamReadResult<LanguageModelV3StreamPart>;\n try {\n chunk = await reader.read();\n } catch (thrown) {\n await settle(isCancellation(thrown, request.signal) ? \"canceled\" : \"failed\");\n controller.error(thrown);\n return;\n }\n\n if (chunk.done) {\n await settle(finish !== undefined && !sawErrorPart ? \"completed\" : \"failed\");\n controller.close();\n return;\n }\n\n const part = chunk.value;\n if (collectParts) parts.push(part);\n if (part.type === \"response-metadata\" && part.id !== undefined) responseId = part.id;\n if (CONTENT_PART_TYPES.has(part.type)) {\n outputStarted = true;\n firstContentAt ??= new Date();\n }\n if (part.type === \"error\") sawErrorPart = true;\n\n if (part.type === \"finish\") {\n finish = part;\n controller.enqueue({\n ...part,\n providerMetadata: {\n ...part.providerMetadata,\n enlitt: {\n operationId: operation.operationId,\n effectiveMaxChargeNanoUsd: operation.effectiveMaxChargeNanoUsd\n }\n }\n });\n } else {\n controller.enqueue(part);\n }\n },\n\n async cancel(reason) {\n // Consumer cancellation: stop the source, then settle as canceled.\n await reader.cancel(reason).catch(() => undefined);\n await settle(\"canceled\");\n }\n });\n\n return { ...result, stream };\n}\n\n// --- Small shared helpers ----------------------------------------------------\n\n/** The content-free timing bracket as the wire reports it. */\nexport function timingFacts(startedAt: Date, endedAt: Date): { startedAt: string; endedAt: string } {\n return { startedAt: startedAt.toISOString(), endedAt: endedAt.toISOString() };\n}\n\n/** Token counts for the terminal report, omitting any total the provider did not report. */\nfunction usageFacts(usage: LanguageModelV3Usage): Pick<PremiumTerminalFacts, \"usage\"> {\n const counts: NonNullable<PremiumTerminalFacts[\"usage\"]> = {\n ...(usage.inputTokens.total !== undefined ? { inputTokens: usage.inputTokens.total } : {}),\n ...(usage.outputTokens.total !== undefined ? { outputTokens: usage.outputTokens.total } : {}),\n ...(usage.inputTokens.cacheRead !== undefined ? { cachedInputTokens: usage.inputTokens.cacheRead } : {}),\n ...(usage.outputTokens.reasoning !== undefined ? { reasoningTokens: usage.outputTokens.reasoning } : {})\n };\n return Object.keys(counts).length > 0 ? { usage: counts } : {};\n}\n\n/** Adds `providerMetadata.enlitt` to a non-streaming result without touching anything else. */\nfunction attachEnlittMetadataToGenerateResult(result: GenerateResult, operation: PremiumChargeHandle): GenerateResult {\n return {\n ...result,\n providerMetadata: {\n ...result.providerMetadata,\n enlitt: {\n operationId: operation.operationId,\n effectiveMaxChargeNanoUsd: operation.effectiveMaxChargeNanoUsd\n }\n }\n };\n}\n","/**\n * Premium for non-language Vercel models: image generation, text-to-speech, and\n * speech-to-text (owner decision 2026-11-15).\n *\n * An image, speech, or transcription call is one provider `doGenerate()`, so it\n * is the language wrapper's non-streaming path with a different result shape.\n * This file reuses `readEnlittCallOptions()`, `runPremiumCharge()`, the shared\n * price evaluation, and the core's clamp exactly. What it adds is only:\n *\n * - the call identity (the supplied `idempotencyKey` itself, or a fresh random\n * ID; a media call has no growing prompt to count),\n * - the per-kind price context, and\n * - the result mapping (images untouched; speech and transcription gain\n * `providerMetadata.enlitt`).\n *\n * The begin and terminal requests are byte for byte the language wrapper's:\n * there is no modality field on the wire. Nothing about the call's content\n * (prompt, text, audio, images) is ever sent to Enlitt; the price context\n * lives and dies in the business's own process.\n */\n\nimport type {\n ImageModelV3,\n ImageModelV3CallOptions,\n ImageModelV4,\n SpeechModelV3,\n SpeechModelV3CallOptions,\n SpeechModelV4,\n TranscriptionModelV3,\n TranscriptionModelV3CallOptions,\n TranscriptionModelV4\n} from \"@ai-sdk/provider\";\nimport { EnlittConfigurationError } from \"../core/errors.js\";\nimport {\n assertCallId,\n generateRandomCallId,\n isCancellation,\n runPremiumCharge,\n type PremiumChargeHandle,\n type PremiumChargeRequest,\n type PremiumTerminalFacts\n} from \"../core/premium.js\";\nimport type { InternalEnlittClient } from \"../core/transport.js\";\nimport { readEnlittCallOptions } from \"./language-model.js\";\nimport { evaluatePrice, timingFacts } from \"./premium-language-model.js\";\n\n// --- Public types ------------------------------------------------------------\n\n/** What an image model's `doGenerate()` resolves with, derived rather than invented. */\nexport type ImageGenerateResult = Awaited<ReturnType<ImageModelV3[\"doGenerate\"]>>;\n/** What a speech model's `doGenerate()` resolves with. */\nexport type SpeechGenerateResult = Awaited<ReturnType<SpeechModelV3[\"doGenerate\"]>>;\n/** What a transcription model's `doGenerate()` resolves with. */\nexport type TranscriptionGenerateResult = Awaited<ReturnType<TranscriptionModelV3[\"doGenerate\"]>>;\n\n/** The fields every media price context shares. */\nexport interface PremiumMediaPriceBase {\n readonly status: \"completed\" | \"canceled\";\n /** When the provider was invoked. */\n readonly startedAt: Date;\n /** When the provider resolved, or when the call was canceled. */\n readonly endedAt: Date;\n readonly durationMs: number;\n /** The most this call can charge; any price above it is lowered to it. */\n readonly effectiveMaxChargeNanoUsd: string;\n}\n\n/**\n * Everything the SDK knows when a media call ends, discriminated by `kind`.\n * `result` is the provider's own result on `completed` and absent on\n * `canceled`. `request` holds only a few facts read from the call options.\n */\nexport type PremiumMediaPriceContext =\n | (PremiumMediaPriceBase & {\n readonly kind: \"image\";\n readonly request: { readonly n: number; readonly size?: string; readonly aspectRatio?: string };\n readonly result?: ImageGenerateResult;\n })\n | (PremiumMediaPriceBase & {\n readonly kind: \"speech\";\n /** `characters` is the number of Unicode code points in the text to speak. */\n readonly request: { readonly characters: number; readonly voice?: string; readonly outputFormat?: string };\n readonly result?: SpeechGenerateResult;\n })\n | (PremiumMediaPriceBase & {\n readonly kind: \"transcription\";\n readonly request: { readonly mediaType: string };\n readonly result?: TranscriptionGenerateResult;\n });\n\n/**\n * What a premium media call states it costs. Same rules as `EnlittPrice`: a\n * constant is charged on `completed` and `canceled`; a function runs once on\n * either, may be async, and is never called on `failed`.\n */\nexport type EnlittMediaPrice = string | ((context: PremiumMediaPriceContext) => string | Promise<string>);\n\n/** Any of the three media model interfaces the wrapper accepts. */\nexport type PremiumMediaModel =\n | ImageModelV3\n | ImageModelV4\n | SpeechModelV3\n | SpeechModelV4\n | TranscriptionModelV3\n | TranscriptionModelV4;\n\n// --- The wrapper ---------------------------------------------------------------\n\n/**\n * Wraps an image model (`kind: \"image\"`), or a speech or transcription model\n * (`kind: \"audio\"`), with the premium billing lifecycle.\n *\n * Returns a new object carrying the wrapped model's `specificationVersion`,\n * `provider`, and `modelId`, plus an image model's `maxImagesPerCall` forwarded\n * by reference (a function stays a function, called with the wrapped model as\n * `this`). Only `doGenerate` is replaced. The provider is never invoked before\n * Enlitt admits the call: every session and refusal path is\n * `runPremiumCharge()`'s.\n *\n * Speech and transcription models have the same structural shape, so for\n * `kind: \"audio\"` each call decides which it is from its own options.\n *\n * A `v4` model (`ai@7`, Bug #28) is wrapped as a `v4` model. The call options\n * and results this file reads exist in both versions, so the body is written\n * once against the `v3` types. A v4 image model's `supportsFileInputs` and\n * `supportsMaskInputs` are forwarded; a v4 transcription model's\n * `doGenerateFromUrl` and `doStream`, and a streaming speech model's\n * `doStream`, are deliberately not exposed, because they would call the\n * provider without an Enlitt operation. `ai` then downloads a URL itself and\n * calls `doGenerate`, and reports streaming as unsupported by the model.\n */\nexport function createPremiumMediaModel(\n client: InternalEnlittClient,\n model: ImageModelV3 | ImageModelV4,\n kind: \"image\"\n): ImageModelV3 | ImageModelV4;\nexport function createPremiumMediaModel(\n client: InternalEnlittClient,\n model: SpeechModelV3 | SpeechModelV4 | TranscriptionModelV3 | TranscriptionModelV4,\n kind: \"audio\"\n): SpeechModelV3 | SpeechModelV4 | TranscriptionModelV3 | TranscriptionModelV4;\nexport function createPremiumMediaModel(\n client: InternalEnlittClient,\n model: PremiumMediaModel,\n kind: \"image\" | \"audio\"\n): PremiumMediaModel {\n const labels = { id: model.provider, model: model.modelId };\n\n if (kind === \"image\") {\n const image = model as ImageModelV3;\n const maxImagesPerCall = image.maxImagesPerCall;\n const wrapped = {\n specificationVersion: model.specificationVersion,\n provider: image.provider,\n modelId: image.modelId,\n // Forwarded by reference. A function is bound so that a provider\n // implementation reading `this` still sees its own model.\n maxImagesPerCall:\n typeof maxImagesPerCall === \"function\" ? maxImagesPerCall.bind(image) : maxImagesPerCall,\n doGenerate: (options: ImageModelV3CallOptions) =>\n runMediaCall(client, labels, options.providerOptions, options.abortSignal, {\n kind: \"image\",\n request: {\n n: options.n,\n ...(options.size !== undefined ? { size: options.size } : {}),\n ...(options.aspectRatio !== undefined ? { aspectRatio: options.aspectRatio } : {})\n },\n invoke: () => Promise.resolve(image.doGenerate(options)),\n // `generateImage` keeps only an `images` array from each\n // `providerMetadata` namespace, so an `enlitt` namespace would be\n // dropped and, lacking `images`, would break its merge. The image\n // result is therefore returned by identity.\n mapResult: (result) => result,\n facts: (result) => imageUsageFacts(result)\n }),\n // v4 only: whether the model accepts input files and masks. Forwarded\n // by reference when present, like `maxImagesPerCall`.\n ...forwardOptional(model, \"supportsFileInputs\"),\n ...forwardOptional(model, \"supportsMaskInputs\")\n };\n return wrapped as ImageModelV3 | ImageModelV4;\n }\n\n // Speech and transcription share every member but `doGenerate`'s options,\n // so the wrapper accepts either and decides per call.\n const audio = model as SpeechModelV3 & TranscriptionModelV3;\n const wrapped = {\n specificationVersion: model.specificationVersion,\n provider: audio.provider,\n modelId: audio.modelId,\n doGenerate(options: SpeechModelV3CallOptions | TranscriptionModelV3CallOptions) {\n if (isSpeechOptions(options)) {\n return runMediaCall(client, labels, options.providerOptions, options.abortSignal, {\n kind: \"speech\",\n request: {\n characters: [...options.text].length,\n ...(options.voice !== undefined ? { voice: options.voice } : {}),\n ...(options.outputFormat !== undefined ? { outputFormat: options.outputFormat } : {})\n },\n invoke: () => Promise.resolve((audio as SpeechModelV3).doGenerate(options)),\n mapResult: attachEnlittMetadata,\n facts: () => ({})\n });\n }\n if (isTranscriptionOptions(options)) {\n return runMediaCall(client, labels, options.providerOptions, options.abortSignal, {\n kind: \"transcription\",\n request: { mediaType: options.mediaType },\n invoke: () => Promise.resolve((audio as TranscriptionModelV3).doGenerate(options)),\n mapResult: attachEnlittMetadata,\n facts: () => ({})\n });\n }\n return Promise.reject(\n new EnlittConfigurationError(\n \"A premium audio call needs either a string `text` (speech) or `audio` with a string `mediaType` (transcription).\"\n )\n );\n }\n };\n return wrapped as SpeechModelV3 | SpeechModelV4 | TranscriptionModelV3 | TranscriptionModelV4;\n}\n\n/** `{ [key]: model[key] }` when the model has that member, else `{}`. */\nfunction forwardOptional(model: PremiumMediaModel, key: \"supportsFileInputs\" | \"supportsMaskInputs\") {\n return key in model ? { [key]: (model as Partial<Record<typeof key, unknown>>)[key] } : {};\n}\n\n/** Speech call options carry the text to speak. */\nfunction isSpeechOptions(options: object): options is SpeechModelV3CallOptions {\n return typeof (options as { text?: unknown }).text === \"string\";\n}\n\n/** Transcription call options carry audio (base64 string or bytes) and its media type. */\nfunction isTranscriptionOptions(options: object): options is TranscriptionModelV3CallOptions {\n const audio = (options as { audio?: unknown }).audio;\n return (\n (typeof audio === \"string\" || audio instanceof Uint8Array) &&\n typeof (options as { mediaType?: unknown }).mediaType === \"string\"\n );\n}\n\n// --- One media call ------------------------------------------------------------\n\n/**\n * The per-kind pieces `runMediaCall` needs. `Kind` and `Result` tie the\n * request facts, the provider call, and the result mapping to one media kind\n * so the price context is always internally consistent.\n */\ntype MediaCallSpec<Result> =\n | {\n readonly kind: \"image\";\n readonly request: Extract<PremiumMediaPriceContext, { kind: \"image\" }>[\"request\"];\n readonly invoke: () => Promise<Result>;\n readonly mapResult: (result: Result, operation: PremiumChargeHandle) => Result;\n readonly facts: (result: Result) => Pick<PremiumTerminalFacts, \"usage\">;\n }\n | {\n readonly kind: \"speech\";\n readonly request: Extract<PremiumMediaPriceContext, { kind: \"speech\" }>[\"request\"];\n readonly invoke: () => Promise<Result>;\n readonly mapResult: (result: Result, operation: PremiumChargeHandle) => Result;\n readonly facts: (result: Result) => Pick<PremiumTerminalFacts, \"usage\">;\n }\n | {\n readonly kind: \"transcription\";\n readonly request: Extract<PremiumMediaPriceContext, { kind: \"transcription\" }>[\"request\"];\n readonly invoke: () => Promise<Result>;\n readonly mapResult: (result: Result, operation: PremiumChargeHandle) => Result;\n readonly facts: (result: Result) => Pick<PremiumTerminalFacts, \"usage\">;\n };\n\n/**\n * Runs one media provider call inside `runPremiumCharge()`.\n *\n * - Options are read with the language wrapper's own `readEnlittCallOptions()`;\n * every failure is an `EnlittConfigurationError` before any request.\n * - A resolved call is `completed`: the price is evaluated with the provider's\n * result and the safe facts are recorded.\n * - A rejection while canceled evaluates the price with no result, then\n * rethrows unchanged; the core reports `canceled`.\n * - Any other rejection is rethrown unchanged without calling the price; the\n * core reports `failed` at `\"0\"`.\n */\nasync function runMediaCall<Result>(\n client: InternalEnlittClient,\n labels: { id: string; model: string },\n providerOptions: Parameters<typeof readEnlittCallOptions>[0],\n signal: AbortSignal | undefined,\n spec: MediaCallSpec<Result>\n): Promise<Result> {\n const options = readEnlittCallOptions(providerOptions, \"premium\");\n const price = options.price as EnlittMediaPrice | undefined;\n const request: PremiumChargeRequest = {\n // Always present for a premium call: `readEnlittCallOptions` resolves it\n // from the declared value or a constant price.\n maxCharge: options.maxCharge!,\n provider: labels,\n // One media call is one provider invocation, so a supplied key is the\n // call ID itself (the OpenAI adapter's rule), and otherwise a fresh one.\n callId: assertCallId(options.idempotencyKey ?? generateRandomCallId()),\n ...(options.reportingDeadlineMs !== undefined ? { reportingDeadlineMs: options.reportingDeadlineMs } : {}),\n ...(options.metadata !== undefined ? { metadata: options.metadata } : {}),\n ...(signal !== undefined ? { signal } : {})\n };\n\n return runPremiumCharge(client, request, async (charge, operation) => {\n const startedAt = new Date();\n let result: Result;\n try {\n result = await spec.invoke();\n } catch (thrown) {\n const endedAt = new Date();\n if (isCancellation(thrown, signal)) {\n charge(\n await evaluatePrice(client, price, buildContext(spec, \"canceled\", undefined, startedAt, endedAt, operation))\n );\n operation.describe({\n timing: timingFacts(startedAt, endedAt),\n delivery: { outputStarted: false, outputCompleted: false },\n errorCategory: \"canceled\"\n });\n } else {\n operation.describe({\n timing: timingFacts(startedAt, endedAt),\n delivery: { outputStarted: false, outputCompleted: false },\n errorCategory: \"provider\"\n });\n }\n // Rethrown completely unchanged: a provider's own error never becomes an\n // `EnlittError`.\n throw thrown;\n }\n\n const endedAt = new Date();\n charge(await evaluatePrice(client, price, buildContext(spec, \"completed\", result, startedAt, endedAt, operation)));\n operation.describe({\n timing: timingFacts(startedAt, endedAt),\n delivery: { outputStarted: true, outputCompleted: true },\n ...spec.facts(result)\n });\n return spec.mapResult(result, operation);\n });\n}\n\n/** Assembles the price context for one media call. */\nfunction buildContext<Result>(\n spec: MediaCallSpec<Result>,\n status: \"completed\" | \"canceled\",\n result: Result | undefined,\n startedAt: Date,\n endedAt: Date,\n operation: PremiumChargeHandle\n): PremiumMediaPriceContext {\n const base: PremiumMediaPriceBase = {\n status,\n startedAt,\n endedAt,\n durationMs: endedAt.getTime() - startedAt.getTime(),\n effectiveMaxChargeNanoUsd: operation.effectiveMaxChargeNanoUsd\n };\n // The cast is sound: `spec.kind` fixes which provider result `Result` is.\n return {\n ...base,\n kind: spec.kind,\n request: spec.request,\n ...(result !== undefined ? { result } : {})\n } as PremiumMediaPriceContext;\n}\n\n/** An image result's token usage for the terminal report, when the provider gave any. */\nfunction imageUsageFacts(result: ImageGenerateResult): Pick<PremiumTerminalFacts, \"usage\"> {\n const usage = result.usage;\n if (usage === undefined) return {};\n const counts: NonNullable<PremiumTerminalFacts[\"usage\"]> = {\n ...(usage.inputTokens !== undefined ? { inputTokens: usage.inputTokens } : {}),\n ...(usage.outputTokens !== undefined ? { outputTokens: usage.outputTokens } : {})\n };\n return Object.keys(counts).length > 0 ? { usage: counts } : {};\n}\n\n/**\n * Returns a shallow copy of a speech or transcription result whose\n * `providerMetadata` adds `enlitt: { operationId, effectiveMaxChargeNanoUsd }`\n * beside the provider's own namespaces, exactly as the language wrapper does.\n */\nfunction attachEnlittMetadata<Result>(result: Result, operation: PremiumChargeHandle): Result {\n const withMetadata = result as Result & { providerMetadata?: Record<string, unknown> };\n return {\n ...withMetadata,\n providerMetadata: {\n ...withMetadata.providerMetadata,\n enlitt: {\n operationId: operation.operationId,\n effectiveMaxChargeNanoUsd: operation.effectiveMaxChargeNanoUsd\n }\n }\n };\n}\n","import type {\n ImageModelV3,\n ImageModelV4,\n LanguageModelV3,\n LanguageModelV4,\n LanguageModelV3CallOptions,\n LanguageModelV3Content,\n LanguageModelV3FinishReason,\n LanguageModelV3StreamPart,\n LanguageModelV3Usage,\n SharedV3ProviderMetadata,\n SharedV3ProviderOptions,\n SpeechModelV3,\n SpeechModelV4,\n TranscriptionModelV3,\n TranscriptionModelV4\n} from \"@ai-sdk/provider\";\nimport { ENLITT_STANDARD_MODEL } from \"@enlitt/protocol\";\nimport { EnlittConfigurationError } from \"../core/errors.js\";\nimport {\n assertCallId,\n assertCallerMetadata,\n assertIdempotencyKeyBase,\n assertNanoUsd,\n assertReportingDeadlineMs,\n generateRandomCallId\n} from \"../core/premium.js\";\nimport { createInternalClient, type EnlittOptions } from \"../core/transport.js\";\nimport { createStandardLanguageModel } from \"./standard-language-model.js\";\nimport { createPremiumLanguageModel } from \"./premium-language-model.js\";\nimport { createPremiumMediaModel } from \"./premium-media-model.js\";\n\n/**\n * The only standard model string. There is no second public factory, client\n * class, or model string in v1: this is a re-export of `@enlitt/protocol`'s\n * own constant rather than a second literal, so the string a business passes\n * to `enlitt()` and the `model` field the wire actually sees can never drift\n * apart.\n */\nexport { ENLITT_STANDARD_MODEL };\n\n/**\n * What `enlitt()` accepts as its first argument: Enlitt's own standard model\n * string, or a provider model the business selected and pays for. The mode\n * is the argument's type, not a separate field, so there is no \"unknown\n * mode\" case and no \"premium model missing\" case; both are unrepresentable.\n *\n * It names the `v3` language model only, as it did before `v4` support (Bug\n * #28): widening it would turn a business's `Exclude<EnlittTarget, string>`\n * into a union that `ai@6`'s `generateText` rejects. A `v4` model has its own\n * `enlitt()` overload instead, and `enlitt()` itself accepts either.\n */\nexport type EnlittTarget = typeof ENLITT_STANDARD_MODEL | LanguageModelV3;\n\n/** Every provider model `enlitt()` wraps in premium mode, of either supported specification. */\ntype ProviderModel =\n | LanguageModelV3\n | LanguageModelV4\n | ImageModelV3\n | ImageModelV4\n | SpeechModelV3\n | SpeechModelV4\n | TranscriptionModelV3\n | TranscriptionModelV4;\n\n/**\n * The only public model factory in this package.\n *\n * `enlitt(\"enlitt-standard\")` returns Enlitt's own standard model;\n * `enlitt(myProviderModel)` returns transparent middleware around it in\n * premium mode. A provider model may be a language, image, speech, or\n * transcription model, and the result has the same interface as the model\n * passed in, including its specification version: `v3` for `ai@6`, `v4` for\n * `ai@7` (Bug #28). Standard is a language model only. Both modes require the business's application secret, resolved\n * once here by `createInternalClient()`, which also asserts a server runtime\n * (before any secret is touched) and resolves and validates the base URL once.\n * A missing or invalid secret is an `EnlittConfigurationError` thrown before the\n * first request, in premium exactly as in standard. There is no configuration\n * under which this function returns a model that would reach a provider without\n * Enlitt: a business whose configuration silently degraded would pay for its\n * users' premium calls and see nothing wrong until the provider bill arrived.\n *\n * It builds exactly one internal client per call and hands it to whichever\n * model it returns. `EnlittOptions` is declared once, in core, and shared with\n * `withPremiumCharge()` and `usage()`.\n */\nexport function enlitt(target: EnlittTarget, options?: EnlittOptions): LanguageModelV3;\nexport function enlitt(target: LanguageModelV4, options?: EnlittOptions): LanguageModelV4;\nexport function enlitt(target: ImageModelV3, options?: EnlittOptions): ImageModelV3;\nexport function enlitt(target: ImageModelV4, options?: EnlittOptions): ImageModelV4;\nexport function enlitt(target: SpeechModelV3, options?: EnlittOptions): SpeechModelV3;\nexport function enlitt(target: SpeechModelV4, options?: EnlittOptions): SpeechModelV4;\nexport function enlitt(target: TranscriptionModelV3, options?: EnlittOptions): TranscriptionModelV3;\nexport function enlitt(target: TranscriptionModelV4, options?: EnlittOptions): TranscriptionModelV4;\nexport function enlitt(\n target: EnlittTarget | ProviderModel,\n options: EnlittOptions = {}\n): ProviderModel {\n const client = createInternalClient(options);\n\n if (target === ENLITT_STANDARD_MODEL) {\n return createStandardLanguageModel(client);\n }\n\n // Only the v3 (`ai@6`) and v4 (`ai@7`) provider specifications are wrapped.\n // Anything else is refused here, before any request, so a model from a\n // specification the wrappers do not account for can never reach a provider.\n const model = target as Partial<Record<string, unknown>>;\n if (!isSupportedModel(model)) {\n throw new EnlittConfigurationError(\n \"enlitt() accepts \\\"enlitt-standard\\\" or a Vercel AI SDK v3 or v4 language, image, speech, or transcription model.\"\n );\n }\n\n // The model interfaces of each version share `specificationVersion`,\n // `provider`, `modelId`, and `doGenerate`, so the kind is read from the\n // members each adds, in this order (premium for non-language models: owner\n // decision 2026-11-15). A language model is `doStream` *with*\n // `supportedUrls`: `doStream` alone is not enough, because a v4\n // transcription model and a v4 streaming speech model also have one.\n // Speech and transcription are otherwise structurally identical; the media\n // wrapper tells them apart per call from the call options.\n if (typeof model.doStream === \"function\" && \"supportedUrls\" in model) {\n return createPremiumLanguageModel(client, target as LanguageModelV3 | LanguageModelV4);\n }\n if (\"maxImagesPerCall\" in model) {\n return createPremiumMediaModel(client, target as ImageModelV3 | ImageModelV4, \"image\");\n }\n return createPremiumMediaModel(\n client,\n target as SpeechModelV3 | SpeechModelV4 | TranscriptionModelV3 | TranscriptionModelV4,\n \"audio\"\n );\n}\n\n/** The members every supported (`v3` or `v4`) provider model has. */\nfunction isSupportedModel(model: Partial<Record<string, unknown>>): boolean {\n return (\n (model.specificationVersion === \"v3\" || model.specificationVersion === \"v4\") &&\n typeof model.provider === \"string\" &&\n typeof model.modelId === \"string\" &&\n typeof model.doGenerate === \"function\"\n );\n}\n\n// --- Per-call provider options ---------------------------------------------\n\n/**\n * What a premium call states it costs: a constant NANOUSD amount, or a\n * function that computes one once the call has ended. A function runs exactly\n * once per operation, only when the call ends `completed` or `canceled`, may be\n * async, and is never called for `failed`, which reports `\"0\"`.\n */\nexport type EnlittPrice = string | ((context: PremiumPriceContext) => string | Promise<string>);\n\n/**\n * Everything the SDK knows when a premium call ends, and nothing it does not.\n * It never leaves the business's process.\n */\nexport interface PremiumPriceContext {\n readonly status: \"completed\" | \"canceled\";\n /**\n * For `doGenerate`, the result's content. For `doStream`, every part the\n * provider emitted up to its end or the cancellation, in order. Stream parts\n * are collected only when `price` is a function.\n */\n readonly output:\n | { readonly kind: \"generate\"; readonly content: readonly LanguageModelV3Content[] }\n | { readonly kind: \"stream\"; readonly parts: readonly LanguageModelV3StreamPart[] };\n /** Possibly absent on a cancellation. */\n readonly usage?: LanguageModelV3Usage;\n /** Absent on a cancellation before a finish part. */\n readonly finishReason?: LanguageModelV3FinishReason;\n readonly providerMetadata?: SharedV3ProviderMetadata;\n /** Provider invocation start. */\n readonly startedAt: Date;\n /** The end or cancellation instant. */\n readonly endedAt: Date;\n readonly durationMs: number;\n /** Present only for a stream that emitted a content part. */\n readonly timeToFirstTokenMs?: number;\n /** The bound every price for this call is lowered to; it may be below the declared `maxCharge`. */\n readonly effectiveMaxChargeNanoUsd: string;\n}\n\n/**\n * The validated result of `readEnlittCallOptions()`: `providerOptions.enlitt`\n * as the SDK works with it. Every field is optional at the type level because\n * validity depends on `mode`; `readEnlittCallOptions()` is the one place that\n * mode-dependent shape is enforced.\n */\nexport interface EnlittProviderOptions {\n /** A base for the call identity, not the identity itself; see `resolveCallId()`. 16-200 visible ASCII characters. */\n idempotencyKey?: string;\n /** NANOUSD, premium only. Required unless `price` is a constant, in which case it defaults to that constant. */\n maxCharge?: string;\n /** Premium only. Without it a call charges `\"0\"` for every status. */\n price?: EnlittPrice;\n /** Premium only. How long the business needs before it will report the terminal outcome. */\n reportingDeadlineMs?: number;\n /** At most 16 entries, keys at most 64 characters, values at most 512, no key beginning with `enlitt_`. */\n metadata?: Record<string, string>;\n}\n\n/**\n * The closed set of keys `providerOptions.enlitt` accepts. Anything else\n * (including the former `charge` option, and any attempt to name a personal\n * user by token, ID, email, subject, or hint) is rejected as unknown, which is\n * what makes it impossible to pass a user through this surface: there is no\n * field name under which one would be accepted.\n */\nconst KNOWN_ENLITT_OPTION_KEYS: ReadonlySet<string> = new Set([\n \"idempotencyKey\",\n \"maxCharge\",\n \"price\",\n \"reportingDeadlineMs\",\n \"metadata\"\n]);\n\n/**\n * Runtime-validates `providerOptions.enlitt` on every invocation. There is no\n * `managed` parameter and no unmanaged case: every call in either mode is\n * managed. Every failure is an `EnlittConfigurationError` raised before any\n * Enlitt or provider request, and other provider namespaces are never touched.\n *\n * Premium combinations: a constant `price` alone sets `maxCharge` to it;\n * `maxCharge` alone charges `\"0\"`; a function `price` without `maxCharge` is\n * rejected (a function's result is only known after the provider has run and\n * the maximum must be known before); a constant `price` above `maxCharge` is\n * rejected (it could never be charged in full); neither is rejected.\n */\nexport function readEnlittCallOptions(\n providerOptions: SharedV3ProviderOptions | undefined,\n mode: \"standard\" | \"premium\"\n): EnlittProviderOptions {\n // Read as `unknown` rather than through `SharedV3ProviderOptions`'s declared\n // `JSONObject` type: that type is this package's promise about what it sends,\n // not a guarantee about what an untyped or misbehaving caller passes at\n // runtime, and a `price` function is deliberately not JSON.\n const raw: unknown = providerOptions?.enlitt;\n if (raw === undefined) {\n if (mode === \"premium\") {\n throw new EnlittConfigurationError(\n \"A premium call requires providerOptions.enlitt.maxCharge, or a constant providerOptions.enlitt.price.\"\n );\n }\n return {};\n }\n\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n throw new EnlittConfigurationError(\"providerOptions.enlitt must be an object.\");\n }\n const input = raw as Record<string, unknown>;\n\n for (const key of Object.keys(input)) {\n if (!KNOWN_ENLITT_OPTION_KEYS.has(key)) {\n throw new EnlittConfigurationError(`providerOptions.enlitt.${key} is not a recognized Enlitt option.`);\n }\n }\n\n if (mode === \"standard\") {\n for (const key of [\"maxCharge\", \"price\", \"reportingDeadlineMs\"]) {\n if (input[key] !== undefined) {\n throw new EnlittConfigurationError(\n `providerOptions.enlitt.${key} is a premium-only option; Enlitt's standard route chooses its own model and charges nothing the business declares.`\n );\n }\n }\n }\n\n const idempotencyKey =\n input.idempotencyKey !== undefined\n ? assertIdempotencyKeyBase(input.idempotencyKey, \"providerOptions.enlitt.idempotencyKey\")\n : undefined;\n const metadata =\n input.metadata !== undefined ? assertCallerMetadata(input.metadata, \"providerOptions.enlitt.metadata\") : undefined;\n\n let maxCharge: string | undefined;\n let price: EnlittPrice | undefined;\n let reportingDeadlineMs: number | undefined;\n\n if (mode === \"premium\") {\n ({ maxCharge, price } = readPremiumPricing(input));\n if (input.reportingDeadlineMs !== undefined) {\n reportingDeadlineMs = assertReportingDeadlineMs(\n input.reportingDeadlineMs,\n \"providerOptions.enlitt.reportingDeadlineMs\"\n );\n }\n }\n\n return {\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(maxCharge !== undefined ? { maxCharge } : {}),\n ...(price !== undefined ? { price } : {}),\n ...(reportingDeadlineMs !== undefined ? { reportingDeadlineMs } : {}),\n ...(metadata !== undefined ? { metadata } : {})\n };\n}\n\n/**\n * Validates `maxCharge` and `price` together for a premium call and resolves\n * the maximum the call declares at begin. Both are NANOUSD amounts, never\n * counts of credit units: canonical nonnegative integer strings parsed as\n * `bigint`, with `\"0\"` valid for both.\n */\nfunction readPremiumPricing(input: Record<string, unknown>): { maxCharge: string; price: EnlittPrice | undefined } {\n const rawPrice = input.price;\n let price: EnlittPrice | undefined;\n if (rawPrice !== undefined) {\n price =\n typeof rawPrice === \"function\"\n ? (rawPrice as Extract<EnlittPrice, (...args: never[]) => unknown>)\n : assertNanoUsd(rawPrice, \"providerOptions.enlitt.price\");\n }\n\n let maxCharge: string | undefined;\n if (input.maxCharge !== undefined) {\n maxCharge = assertNanoUsd(input.maxCharge, \"providerOptions.enlitt.maxCharge\");\n }\n\n if (maxCharge === undefined) {\n // `maxCharge` is required unless `price` is a constant, in which case it\n // defaults to that constant. A function's result is only known after the\n // provider has run; the maximum must be known before.\n if (typeof price === \"string\") {\n maxCharge = price;\n } else if (typeof price === \"function\") {\n throw new EnlittConfigurationError(\n \"providerOptions.enlitt.maxCharge is required when providerOptions.enlitt.price is a function.\"\n );\n } else {\n throw new EnlittConfigurationError(\n \"A premium call requires providerOptions.enlitt.maxCharge, or a constant providerOptions.enlitt.price.\"\n );\n }\n } else if (typeof price === \"string\" && BigInt(price) > BigInt(maxCharge)) {\n throw new EnlittConfigurationError(\n \"providerOptions.enlitt.price is above providerOptions.enlitt.maxCharge and could never be charged in full.\"\n );\n }\n\n return { maxCharge, price };\n}\n\n// --- Call identity -----------------------------------------------------\n\n/**\n * Derives the one identity of a single underlying model invocation. Sent as\n * `Idempotency-Key` on both paths and as `call_id` (via the same\n * `Idempotency-Key`) on the premium preflight; there is no second identifier.\n *\n * `callId` is `` `${base}.${params.prompt.length}` ``, where `base` is\n * `options.idempotencyKey` when supplied and otherwise a freshly generated\n * random value unique per invocation. The suffix — the count of prompt items,\n * never a hash or any other read of content — is what makes the identity\n * behave correctly in a tool loop: within one `generateText` loop the prompt\n * grows by at least one item before each subsequent provider invocation, so\n * distinct steps get distinct IDs, while a retry of the same step\n * re-presents the identical prompt and so reuses the ID.\n *\n * The resulting ID is validated against the protocol's own 16-255\n * visible-ASCII `Idempotency-Key` bound before it is returned, converting a\n * violation into `EnlittConfigurationError` rather than sending an\n * out-of-bounds header. With `idempotencyKey` bounded at the protocol's own\n * floor by `readEnlittCallOptions()`, no reachable input violates that bound;\n * the check stays as the one place the wire rule is enforced, so a future\n * change to either end cannot ship an out-of-bounds header silently.\n */\nexport function resolveCallId(options: EnlittProviderOptions, params: LanguageModelV3CallOptions): string {\n const base = options.idempotencyKey ?? generateRandomCallId();\n // `assertCallId` enforces the protocol's 16-255 visible-ASCII bound and\n // raises `EnlittConfigurationError`; with the base already at the protocol's\n // own floor no reachable input violates it, so the check only guards a\n // future change to either end.\n return assertCallId(`${base}.${params.prompt.length}`);\n}\n"]}
@@ -1,19 +1,19 @@
1
1
  'use strict';
2
2
 
3
- var chunk26SW63P5_cjs = require('./chunk-26SW63P5.cjs');
3
+ var chunkPPOUNWNA_cjs = require('./chunk-PPOUNWNA.cjs');
4
4
  var protocol = require('@enlitt/protocol');
5
5
 
6
6
  var USAGE_PATH = "/v1/enlitt/usage";
7
7
  async function usage(options = {}) {
8
- const client = chunk26SW63P5_cjs.createInternalClient(options);
9
- const response = await chunk26SW63P5_cjs.requestEnlitt(client, {
8
+ const client = chunkPPOUNWNA_cjs.createInternalClient(options);
9
+ const response = await chunkPPOUNWNA_cjs.requestEnlitt(client, {
10
10
  path: USAGE_PATH,
11
11
  method: "GET",
12
12
  accept: "application/json"
13
13
  });
14
- const parsed = protocol.validateUsageResponse(await chunk26SW63P5_cjs.readEnlittJson(response), { mode: "tolerant" });
14
+ const parsed = protocol.validateUsageResponse(await chunkPPOUNWNA_cjs.readEnlittJson(response), { mode: "tolerant" });
15
15
  if (!parsed.ok) {
16
- throw new chunk26SW63P5_cjs.EnlittError(
16
+ throw new chunkPPOUNWNA_cjs.EnlittError(
17
17
  "malformed_response",
18
18
  `Enlitt's usage response could not be validated: ${parsed.error.message} (${parsed.error.param}).`
19
19
  );
@@ -31,5 +31,5 @@ async function usage(options = {}) {
31
31
  }
32
32
 
33
33
  exports.usage = usage;
34
- //# sourceMappingURL=chunk-G4DTTV5E.cjs.map
35
- //# sourceMappingURL=chunk-G4DTTV5E.cjs.map
34
+ //# sourceMappingURL=chunk-YPA4R65T.cjs.map
35
+ //# sourceMappingURL=chunk-YPA4R65T.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/usage.ts"],"names":["createInternalClient","requestEnlitt","validateUsageResponse","readEnlittJson","EnlittError"],"mappings":";;;;;AA4BA,IAAM,UAAA,GAAa,kBAAA;AAWnB,eAAsB,KAAA,CAAM,OAAA,GAAyB,EAAC,EAA2F;AAC/I,EAAA,MAAM,MAAA,GAASA,uCAAqB,OAAO,CAAA;AAE3C,EAAA,MAAM,QAAA,GAAW,MAAMC,+BAAA,CAAc,MAAA,EAAQ;AAAA,IAC3C,IAAA,EAAM,UAAA;AAAA,IACN,MAAA,EAAQ,KAAA;AAAA,IACR,MAAA,EAAQ;AAAA,GACT,CAAA;AAID,EAAA,MAAM,MAAA,GAASC,+BAAsB,MAAMC,gCAAA,CAAe,QAAQ,CAAA,EAAG,EAAE,IAAA,EAAM,UAAA,EAAY,CAAA;AACzF,EAAA,IAAI,CAAC,OAAO,EAAA,EAAI;AACd,IAAA,MAAM,IAAIC,6BAAA;AAAA,MACR,oBAAA;AAAA,MACA,mDAAmD,MAAA,CAAO,KAAA,CAAM,OAAO,CAAA,EAAA,EAAK,MAAA,CAAO,MAAM,KAAK,CAAA,EAAA;AAAA,KAChG;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,QAAA,EAAU;AAAA,MACR,gBAAA,EAAkB,MAAA,CAAO,KAAA,CAAM,QAAA,CAAS,iBAAA;AAAA,MACxC,eAAA,EAAiB,MAAA,CAAO,KAAA,CAAM,QAAA,CAAS;AAAA,KACzC;AAAA,IACA,OAAA,EAAS;AAAA,MACP,gBAAA,EAAkB,MAAA,CAAO,KAAA,CAAM,OAAA,CAAQ,iBAAA;AAAA,MACvC,eAAA,EAAiB,MAAA,CAAO,KAAA,CAAM,OAAA,CAAQ;AAAA;AACxC,GACF;AACF","file":"chunk-G4DTTV5E.cjs","sourcesContent":["/**\n * The framework-neutral `usage()` helper over `GET /v1/enlitt/usage`.\n *\n * It builds the same internal client as `withPremiumCharge()`, resolves the\n * same personal session (explicit, or ambient from the middleware), performs\n * one authenticated read, and tolerant-parses the response. It returns the two\n * integer percentages and the canonical NANOUSD caps unchanged: no conversion,\n * caching, retry beyond transport policy, or admission inference.\n *\n * The result is advisory. A concurrent call can consume capacity before the\n * caller acts, so it is guidance and never a reservation or quote. It exposes\n * no credit unit, plan, balance, period, rate tuple, or user identity; the wire\n * response carries none and this file adds none.\n */\n\nimport { EnlittError } from \"./errors.js\";\nimport { createInternalClient, readEnlittJson, requestEnlitt, type EnlittOptions } from \"./transport.js\";\nimport { validateUsageResponse } from \"@enlitt/protocol\";\n\n/** One pool's availability, exactly as the wire reports it. */\nexport interface UsageAvailability {\n /** An integer from 0 through 100: the floor of the share of this pool still available. */\n readonly remainingPercent: number;\n /** The most this application could reserve for one call right now, as a canonical NANOUSD string. */\n readonly limitCapNanoUsd: string;\n}\n\n/** The one relative path this helper reads, per `specs/PROTOCOLS.md`. */\nconst USAGE_PATH = \"/v1/enlitt/usage\";\n\n/**\n * Reads the signed-in user's current availability for this application.\n *\n * A missing ambient context raises `EnlittConfigurationError`, a context with\n * no session raises `EnlittLoginRequiredError`, and every refusal (including an\n * unknown error code from a newer server) goes through the shared normalizer,\n * exactly as for a model call. It never raises `spending_limit_exceeded`: the\n * read starts no request-rate budget and reserves nothing.\n */\nexport async function usage(options: EnlittOptions = {}): Promise<{ readonly standard: UsageAvailability; readonly premium: UsageAvailability }> {\n const client = createInternalClient(options);\n\n const response = await requestEnlitt(client, {\n path: USAGE_PATH,\n method: \"GET\",\n accept: \"application/json\"\n });\n\n // Tolerant in: unknown response fields are dropped, so a newer server that\n // adds one changes nothing here.\n const parsed = validateUsageResponse(await readEnlittJson(response), { mode: \"tolerant\" });\n if (!parsed.ok) {\n throw new EnlittError(\n \"malformed_response\",\n `Enlitt's usage response could not be validated: ${parsed.error.message} (${parsed.error.param}).`\n );\n }\n\n return {\n standard: {\n remainingPercent: parsed.value.standard.remaining_percent,\n limitCapNanoUsd: parsed.value.standard.limit_cap_nano_usd\n },\n premium: {\n remainingPercent: parsed.value.premium.remaining_percent,\n limitCapNanoUsd: parsed.value.premium.limit_cap_nano_usd\n }\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/core/usage.ts"],"names":["createInternalClient","requestEnlitt","validateUsageResponse","readEnlittJson","EnlittError"],"mappings":";;;;;AA4BA,IAAM,UAAA,GAAa,kBAAA;AAWnB,eAAsB,KAAA,CAAM,OAAA,GAAyB,EAAC,EAA2F;AAC/I,EAAA,MAAM,MAAA,GAASA,uCAAqB,OAAO,CAAA;AAE3C,EAAA,MAAM,QAAA,GAAW,MAAMC,+BAAA,CAAc,MAAA,EAAQ;AAAA,IAC3C,IAAA,EAAM,UAAA;AAAA,IACN,MAAA,EAAQ,KAAA;AAAA,IACR,MAAA,EAAQ;AAAA,GACT,CAAA;AAID,EAAA,MAAM,MAAA,GAASC,+BAAsB,MAAMC,gCAAA,CAAe,QAAQ,CAAA,EAAG,EAAE,IAAA,EAAM,UAAA,EAAY,CAAA;AACzF,EAAA,IAAI,CAAC,OAAO,EAAA,EAAI;AACd,IAAA,MAAM,IAAIC,6BAAA;AAAA,MACR,oBAAA;AAAA,MACA,mDAAmD,MAAA,CAAO,KAAA,CAAM,OAAO,CAAA,EAAA,EAAK,MAAA,CAAO,MAAM,KAAK,CAAA,EAAA;AAAA,KAChG;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,QAAA,EAAU;AAAA,MACR,gBAAA,EAAkB,MAAA,CAAO,KAAA,CAAM,QAAA,CAAS,iBAAA;AAAA,MACxC,eAAA,EAAiB,MAAA,CAAO,KAAA,CAAM,QAAA,CAAS;AAAA,KACzC;AAAA,IACA,OAAA,EAAS;AAAA,MACP,gBAAA,EAAkB,MAAA,CAAO,KAAA,CAAM,OAAA,CAAQ,iBAAA;AAAA,MACvC,eAAA,EAAiB,MAAA,CAAO,KAAA,CAAM,OAAA,CAAQ;AAAA;AACxC,GACF;AACF","file":"chunk-YPA4R65T.cjs","sourcesContent":["/**\n * The framework-neutral `usage()` helper over `GET /v1/enlitt/usage`.\n *\n * It builds the same internal client as `withPremiumCharge()`, resolves the\n * same personal session (explicit, or ambient from the middleware), performs\n * one authenticated read, and tolerant-parses the response. It returns the two\n * integer percentages and the canonical NANOUSD caps unchanged: no conversion,\n * caching, retry beyond transport policy, or admission inference.\n *\n * The result is advisory. A concurrent call can consume capacity before the\n * caller acts, so it is guidance and never a reservation or quote. It exposes\n * no credit unit, plan, balance, period, rate tuple, or user identity; the wire\n * response carries none and this file adds none.\n */\n\nimport { EnlittError } from \"./errors.js\";\nimport { createInternalClient, readEnlittJson, requestEnlitt, type EnlittOptions } from \"./transport.js\";\nimport { validateUsageResponse } from \"@enlitt/protocol\";\n\n/** One pool's availability, exactly as the wire reports it. */\nexport interface UsageAvailability {\n /** An integer from 0 through 100: the floor of the share of this pool still available. */\n readonly remainingPercent: number;\n /** The most this application could reserve for one call right now, as a canonical NANOUSD string. */\n readonly limitCapNanoUsd: string;\n}\n\n/** The one relative path this helper reads, per `specs/PROTOCOLS.md`. */\nconst USAGE_PATH = \"/v1/enlitt/usage\";\n\n/**\n * Reads the signed-in user's current availability for this application.\n *\n * A missing ambient context raises `EnlittConfigurationError`, a context with\n * no session raises `EnlittLoginRequiredError`, and every refusal (including an\n * unknown error code from a newer server) goes through the shared normalizer,\n * exactly as for a model call. It never raises `spending_limit_exceeded`: the\n * read starts no request-rate budget and reserves nothing.\n */\nexport async function usage(options: EnlittOptions = {}): Promise<{ readonly standard: UsageAvailability; readonly premium: UsageAvailability }> {\n const client = createInternalClient(options);\n\n const response = await requestEnlitt(client, {\n path: USAGE_PATH,\n method: \"GET\",\n accept: \"application/json\"\n });\n\n // Tolerant in: unknown response fields are dropped, so a newer server that\n // adds one changes nothing here.\n const parsed = validateUsageResponse(await readEnlittJson(response), { mode: \"tolerant\" });\n if (!parsed.ok) {\n throw new EnlittError(\n \"malformed_response\",\n `Enlitt's usage response could not be validated: ${parsed.error.message} (${parsed.error.param}).`\n );\n }\n\n return {\n standard: {\n remainingPercent: parsed.value.standard.remaining_percent,\n limitCapNanoUsd: parsed.value.standard.limit_cap_nano_usd\n },\n premium: {\n remainingPercent: parsed.value.premium.remaining_percent,\n limitCapNanoUsd: parsed.value.premium.limit_cap_nano_usd\n }\n };\n}\n"]}
@@ -195,15 +195,23 @@ export declare class EnlittAuthenticationError extends EnlittError {
195
195
  readonly name = "EnlittAuthenticationError";
196
196
  constructor(message: string, facts?: EnlittErrorFacts);
197
197
  }
198
+ /** The two wire codes `EnlittAuthorizationError` carries. */
199
+ export type EnlittAuthorizationCode = typeof ENLITT_ERROR_CODE.insufficient_permissions | typeof ENLITT_ERROR_CODE.premium_not_enabled;
198
200
  /**
199
- * Code `insufficient_permissions`. The presented business key is valid but
200
- * used outside its authenticated application or scope. Audience is the
201
- * business's own logs; never rendered to an end user, and never softened
202
- * into a direct provider call.
201
+ * A business credential or configuration problem. Audience is the business's
202
+ * own logs; never rendered to an end user, and never softened into a direct
203
+ * provider call. Two codes:
204
+ *
205
+ * - `insufficient_permissions` (the default): the presented business key is
206
+ * valid but used outside its authenticated application or scope.
207
+ * - `premium_not_enabled` (owner decision 2026-10-25): the application's
208
+ * premium switch is off, or changed during the call. On a refused premium
209
+ * start no provider was invoked; on a refused terminal report the provider
210
+ * already ran and the call was not charged.
203
211
  */
204
212
  export declare class EnlittAuthorizationError extends EnlittError {
205
213
  readonly name = "EnlittAuthorizationError";
206
- constructor(message: string, facts?: EnlittErrorFacts);
214
+ constructor(message: string, facts?: EnlittErrorFacts, code?: EnlittAuthorizationCode);
207
215
  }
208
216
  /**
209
217
  * An Enlitt HTTP error response, shaped for normalization: the HTTP status,
@@ -195,15 +195,23 @@ export declare class EnlittAuthenticationError extends EnlittError {
195
195
  readonly name = "EnlittAuthenticationError";
196
196
  constructor(message: string, facts?: EnlittErrorFacts);
197
197
  }
198
+ /** The two wire codes `EnlittAuthorizationError` carries. */
199
+ export type EnlittAuthorizationCode = typeof ENLITT_ERROR_CODE.insufficient_permissions | typeof ENLITT_ERROR_CODE.premium_not_enabled;
198
200
  /**
199
- * Code `insufficient_permissions`. The presented business key is valid but
200
- * used outside its authenticated application or scope. Audience is the
201
- * business's own logs; never rendered to an end user, and never softened
202
- * into a direct provider call.
201
+ * A business credential or configuration problem. Audience is the business's
202
+ * own logs; never rendered to an end user, and never softened into a direct
203
+ * provider call. Two codes:
204
+ *
205
+ * - `insufficient_permissions` (the default): the presented business key is
206
+ * valid but used outside its authenticated application or scope.
207
+ * - `premium_not_enabled` (owner decision 2026-10-25): the application's
208
+ * premium switch is off, or changed during the call. On a refused premium
209
+ * start no provider was invoked; on a refused terminal report the provider
210
+ * already ran and the call was not charged.
203
211
  */
204
212
  export declare class EnlittAuthorizationError extends EnlittError {
205
213
  readonly name = "EnlittAuthorizationError";
206
- constructor(message: string, facts?: EnlittErrorFacts);
214
+ constructor(message: string, facts?: EnlittErrorFacts, code?: EnlittAuthorizationCode);
207
215
  }
208
216
  /**
209
217
  * An Enlitt HTTP error response, shaped for normalization: the HTTP status,
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/core/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAEL,iBAAiB,EAMjB,KAAK,eAAe,IAAI,cAAc,EACvC,MAAM,kBAAkB,CAAC;AAE1B;;;;;;;GAOG;AACH,MAAM,MAAM,eAAe,GACvB,uBAAuB,GACvB,kBAAkB,GAClB,oBAAoB,GACpB,kBAAkB,CAAC;AAYvB;;;;;;GAMG;AACH,MAAM,WAAW,gBAAgB;IAC/B,0EAA0E;IAC1E,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B;;;;OAIG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,OAAO,CAAC;CAC9B;AAED;;;;;GAKG;AACH,MAAM,MAAM,sBAAsB,GAAG,MAAM,GAAG,EAAE,CAAC;AAEjD;;;;;;;;;GASG;AACH,qBAAa,WAAY,SAAQ,KAAK;IACpC,SAAkB,IAAI,EAAE,MAAM,CAAiB;IAE/C,QAAQ,CAAC,IAAI,EAAE,cAAc,GAAG,eAAe,GAAG,sBAAsB,CAAC;IAEzE;;;;;;OAMG;IACH,QAAQ,CAAC,eAAe,EAAE,OAAO,CAAS;IAE1C;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qB;IACpC,QAAQ,CAAC,IAAI,EAAE,kBAAkB,CAAC;IAClC,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED;;;;GAIG;AACH,MAAM,MAAM,wBAAwB,GAChC,uBAAuB,GACvB,sBAAsB,GACtB,uBAAuB,GACvB,qBAAqB,CAAC;AAgF1B;;;;;;;;;;;;GAYG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,OAAO,EAAE,eAAe,EAAE,OAAO,GAAG,WAAW,CA0B/F"}
@@ -20,5 +20,5 @@
20
20
  export { withPremiumCharge, type PremiumChargeFunction, type PremiumChargeHandle, type PremiumTerminalFacts, type WithPremiumChargeOptions } from "./premium.cjs";
21
21
  export { usage, type UsageAvailability } from "./usage.cjs";
22
22
  export type { EnlittOptions, EnlittRateLimitRetryOptions } from "./transport.cjs";
23
- export { ENLITT_SESSION_COOKIE_NAME, enlittSession, enlittSessionMiddleware, getEnlittSession, runWithEnlittSession, type EnlittMiddleware, type EnlittSession, type SessionMiddlewareOptions } from "./session.cjs";
23
+ export { ENLITT_SESSION_COOKIE_NAME, ENLITT_SESSION_HEADER_NAME, enlittSession, enlittSessionMiddleware, getEnlittSession, runWithEnlittSession, type EnlittMiddleware, type EnlittSession, type SessionMiddlewareOptions } from "./session.cjs";
24
24
  export { EnlittAuthenticationError, EnlittAuthorizationError, EnlittConfigurationError, EnlittError, EnlittInsufficientCreditsError, EnlittLimitExceededError, EnlittLoginRequiredError, EnlittRateLimitError, EnlittSubscriptionInactiveError, type EnlittLocalCode, type EnlittUnrecognizedCode } from "./errors.cjs";
@@ -20,6 +20,6 @@
20
20
  export { withPremiumCharge, type PremiumChargeFunction, type PremiumChargeHandle, type PremiumTerminalFacts, type WithPremiumChargeOptions } from "./premium.js";
21
21
  export { usage, type UsageAvailability } from "./usage.js";
22
22
  export type { EnlittOptions, EnlittRateLimitRetryOptions } from "./transport.js";
23
- export { ENLITT_SESSION_COOKIE_NAME, enlittSession, enlittSessionMiddleware, getEnlittSession, runWithEnlittSession, type EnlittMiddleware, type EnlittSession, type SessionMiddlewareOptions } from "./session.js";
23
+ export { ENLITT_SESSION_COOKIE_NAME, ENLITT_SESSION_HEADER_NAME, enlittSession, enlittSessionMiddleware, getEnlittSession, runWithEnlittSession, type EnlittMiddleware, type EnlittSession, type SessionMiddlewareOptions } from "./session.js";
24
24
  export { EnlittAuthenticationError, EnlittAuthorizationError, EnlittConfigurationError, EnlittError, EnlittInsufficientCreditsError, EnlittLimitExceededError, EnlittLoginRequiredError, EnlittRateLimitError, EnlittSubscriptionInactiveError, type EnlittLocalCode, type EnlittUnrecognizedCode } from "./errors.js";
25
25
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EACL,iBAAiB,EACjB,KAAK,qBAAqB,EAC1B,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,EACzB,KAAK,wBAAwB,EAC9B,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,KAAK,EAAE,KAAK,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAE3D,YAAY,EAAE,aAAa,EAAE,2BAA2B,EAAE,MAAM,gBAAgB,CAAC;AAEjF,OAAO,EACL,0BAA0B,EAC1B,aAAa,EACb,uBAAuB,EACvB,gBAAgB,EAChB,oBAAoB,EACpB,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAClB,KAAK,wBAAwB,EAC9B,MAAM,cAAc,CAAC;AAEtB,OAAO,EACL,yBAAyB,EACzB,wBAAwB,EACxB,wBAAwB,EACxB,WAAW,EACX,8BAA8B,EAC9B,wBAAwB,EACxB,wBAAwB,EACxB,oBAAoB,EACpB,+BAA+B,EAC/B,KAAK,eAAe,EACpB,KAAK,sBAAsB,EAC5B,MAAM,aAAa,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EACL,iBAAiB,EACjB,KAAK,qBAAqB,EAC1B,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,EACzB,KAAK,wBAAwB,EAC9B,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,KAAK,EAAE,KAAK,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAE3D,YAAY,EAAE,aAAa,EAAE,2BAA2B,EAAE,MAAM,gBAAgB,CAAC;AAEjF,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,EAC1B,aAAa,EACb,uBAAuB,EACvB,gBAAgB,EAChB,oBAAoB,EACpB,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAClB,KAAK,wBAAwB,EAC9B,MAAM,cAAc,CAAC;AAEtB,OAAO,EACL,yBAAyB,EACzB,wBAAwB,EACxB,wBAAwB,EACxB,WAAW,EACX,8BAA8B,EAC9B,wBAAwB,EACxB,wBAAwB,EACxB,oBAAoB,EACpB,+BAA+B,EAC/B,KAAK,eAAe,EACpB,KAAK,sBAAsB,EAC5B,MAAM,aAAa,CAAC"}
@@ -19,6 +19,13 @@
19
19
  * is not, which is why it is one constant rather than two literals.
20
20
  */
21
21
  export declare const ENLITT_SESSION_COOKIE_NAME = "enlitt_session";
22
+ /**
23
+ * The request header that carries a session token from a game or native client
24
+ * with no cookie jar. Account's "Client sign-in handoff" gives the client the
25
+ * token, and the client sends it here on every request to the business backend.
26
+ * `enlittSessionMiddleware()` reads it only when `header: true` is passed.
27
+ */
28
+ export declare const ENLITT_SESSION_HEADER_NAME = "Enlitt-Session";
22
29
  /**
23
30
  * An opaque handle around Enlitt's session token.
24
31
  *
@@ -52,9 +59,17 @@ export declare function enlittSession(token: string): EnlittSession;
52
59
  * `cookieName` exists solely to mirror a business's own custom
53
60
  * `CallbackConfig.cookieName`; the default matches `ENLITT_SESSION_COOKIE_NAME`
54
61
  * so the common case names nothing.
62
+ *
63
+ * `header` opts in to the `Enlitt-Session` header as the session source for
64
+ * clients without a cookie jar. It defaults to `false` so a browser-only
65
+ * business never accepts a token from a header it does not expect. The header
66
+ * is a bearer credential like the cookie: serve these routes over https and
67
+ * keep it out of logs. It is not CSRF-relevant, since a browser never attaches
68
+ * it on its own.
55
69
  */
56
70
  export interface SessionMiddlewareOptions {
57
71
  cookieName?: string;
72
+ header?: boolean;
58
73
  }
59
74
  /**
60
75
  * The shape `enlittSessionMiddleware()` returns.
@@ -19,6 +19,13 @@
19
19
  * is not, which is why it is one constant rather than two literals.
20
20
  */
21
21
  export declare const ENLITT_SESSION_COOKIE_NAME = "enlitt_session";
22
+ /**
23
+ * The request header that carries a session token from a game or native client
24
+ * with no cookie jar. Account's "Client sign-in handoff" gives the client the
25
+ * token, and the client sends it here on every request to the business backend.
26
+ * `enlittSessionMiddleware()` reads it only when `header: true` is passed.
27
+ */
28
+ export declare const ENLITT_SESSION_HEADER_NAME = "Enlitt-Session";
22
29
  /**
23
30
  * An opaque handle around Enlitt's session token.
24
31
  *
@@ -52,9 +59,17 @@ export declare function enlittSession(token: string): EnlittSession;
52
59
  * `cookieName` exists solely to mirror a business's own custom
53
60
  * `CallbackConfig.cookieName`; the default matches `ENLITT_SESSION_COOKIE_NAME`
54
61
  * so the common case names nothing.
62
+ *
63
+ * `header` opts in to the `Enlitt-Session` header as the session source for
64
+ * clients without a cookie jar. It defaults to `false` so a browser-only
65
+ * business never accepts a token from a header it does not expect. The header
66
+ * is a bearer credential like the cookie: serve these routes over https and
67
+ * keep it out of logs. It is not CSRF-relevant, since a browser never attaches
68
+ * it on its own.
55
69
  */
56
70
  export interface SessionMiddlewareOptions {
57
71
  cookieName?: string;
72
+ header?: boolean;
58
73
  }
59
74
  /**
60
75
  * The shape `enlittSessionMiddleware()` returns.
@@ -1 +1 @@
1
- {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../src/core/session.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAKH;;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AAW,wBAAwB;IACvC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED;;;;;;GAMG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAC7B,OAAO,EAAE,OAAO,EAChB,IAAI,EAAE,MAAM,OAAO,CAAC,QAAQ,CAAC,KAC1B,OAAO,CAAC,QAAQ,CAAC,CAAC;AAavB;;;;;;;;;;;;;GAaG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,CAAC,EAAE,wBAAwB,GAAG,gBAAgB,CAwB5F;AAED;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAAC,CAAC,EAAE,OAAO,EAAE,aAAa,GAAG,IAAI,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,CAErF;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,gBAAgB,IAAI,aAAa,GAAG,IAAI,CAQvD"}
@@ -42,7 +42,7 @@ import { type EnlittSession } from "./session.cjs";
42
42
  * this module has no other reason to make. It must be bumped by hand
43
43
  * alongside `package.json`'s `version` field.
44
44
  */
45
- export declare const SDK_VERSION = "0.1.0";
45
+ export declare const SDK_VERSION = "0.1.1";
46
46
  /**
47
47
  * Caller-supplied tuning for the rate-limit wait. Every field is optional
48
48
  * because `createInternalClient()` folds it over the SDK's own defaults
@@ -42,7 +42,7 @@ import { type EnlittSession } from "./session.js";
42
42
  * this module has no other reason to make. It must be bumped by hand
43
43
  * alongside `package.json`'s `version` field.
44
44
  */
45
- export declare const SDK_VERSION = "0.1.0";
45
+ export declare const SDK_VERSION = "0.1.1";
46
46
  /**
47
47
  * Caller-supplied tuning for the rate-limit wait. Every field is optional
48
48
  * because `createInternalClient()` folds it over the SDK's own defaults