@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
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/errors.ts","../src/core/session.ts","../src/server/secrets.ts","../src/core/transport.ts","../src/core/premium.ts"],"names":["facts","input","ENLITT_ERROR_CODE"],"mappings":";;;;AAgGO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EACnB,IAAA,GAAe,aAAA;AAAA,EAExB,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,eAAA,GAA2B,KAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ3B,SAAA;AAAA,EAEA,YAAA;AAAA,EACA,SAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,YAAA;AAAA,EAET,WAAA,CACE,IAAA,EACA,OAAA,EACA,KAAA,GAA0B,EAAC,EAC3B;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAEZ,IAAA,MAAM,aAAa,iBAAA,CAAkB,IAAI,CAAA,GAAI,kBAAA,CAAmB,IAAI,CAAA,GAAI,MAAA;AAIxE,IAAA,IAAA,CAAK,SAAA,GAAY,YAAY,SAAA,KAAc,WAAA,CAAY,IAAI,CAAA,GAAI,KAAA,GAAS,MAAM,SAAA,IAAa,KAAA,CAAA;AAE3F,IAAA,IAAI,KAAA,CAAM,iBAAiB,MAAA,EAAW;AACpC,MAAA,IAAA,CAAK,eAAe,KAAA,CAAM,YAAA;AAAA,IAC5B;AACA,IAAA,IAAI,KAAA,CAAM,cAAc,MAAA,EAAW;AACjC,MAAA,IAAA,CAAK,YAAY,KAAA,CAAM,SAAA;AAAA,IACzB;AAKA,IAAA,IACE,KAAA,CAAM,YAAA,KAAiB,MAAA,KACtB,UAAA,EAAY,YAAA,KAAiB,SAAA,IAAc,UAAA,KAAe,MAAA,IAAa,CAAC,WAAA,CAAY,IAAI,CAAA,CAAA,EACzF;AACA,MAAA,IAAA,CAAK,eAAe,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CAAQ,SAAA,EAAW,WAAW,CAAA;AAC9D,EAAA,MAAM,MAAA,GACJ,QAAQ,cAAA,KAAmB,MAAA,GACvB,yBAAyB,OAAA,CAAQ,cAAA,EAAgB,gBAAgB,CAAA,GACjE,MAAA;AACN,EAAA,MAAM,mBAAA,GACJ,QAAQ,mBAAA,KAAwB,MAAA,GAC5B,0BAA0B,OAAA,CAAQ,mBAAA,EAAqB,qBAAqB,CAAA,GAC5E,MAAA;AACN,EAAA,MAAM,QAAA,GACJ,QAAQ,QAAA,KAAa,MAAA,GAAY,qBAAqB,OAAA,CAAQ,QAAA,EAAU,UAAU,CAAA,GAAI,MAAA;AAExF,EAAA,OAAO,gBAAA;AAAA,IACL,MAAA;AAAA,IACA;AAAA,MACE,SAAA;AAAA,MACA,QAAA,EAAU,EAAE,EAAA,EAAI,OAAA,CAAQ,SAAS,EAAA,EAAI,KAAA,EAAO,OAAA,CAAQ,QAAA,CAAS,KAAA,EAAM;AAAA,MACnE,GAAI,MAAA,KAAW,MAAA,GAAY,EAAE,MAAA,KAAW,EAAC;AAAA,MACzC,GAAI,mBAAA,KAAwB,MAAA,GAAY,EAAE,mBAAA,KAAwB,EAAC;AAAA,MACnE,GAAI,QAAA,KAAa,MAAA,GAAY,EAAE,QAAA,KAAa,EAAC;AAAA,MAC7C,GAAI,QAAQ,MAAA,KAAW,MAAA,GAAY,EAAE,MAAA,EAAQ,OAAA,CAAQ,MAAA,EAAO,GAAI;AAAC,KACnE;AAAA,IACA;AAAA,GACF;AACF","file":"chunk-6DPBYLA5.js","sourcesContent":["/**\n * The SDK's typed error hierarchy and the single mapping from an Enlitt\n * failure to one of its classes.\n *\n * This file declares no wire code list of its own. The stable codes, their\n * OpenAI-shaped `type`, their HTTP status, their retryability, and whether\n * they may carry `authorize_url` all come from the frozen record\n * `@enlitt/protocol` exports — the same record the backend raises from. That\n * is what keeps a code, and every fact about it, declared exactly once across\n * the wire rather than asserted independently in two workspaces.\n *\n * It declares one small closed set of SDK-local codes, for the four failures\n * that never reach the wire and so can have no entry in the protocol record.\n * That set is provably disjoint from the record's codes (see\n * `_LocalCodesDisjointFromWireCodes` below), so no reader ever has to ask\n * which side of the wire a given code came from.\n *\n * No class here carries a balance, plan, service tier, period, or personal\n * identity, and none wraps a provider's own error — a provider failure that\n * passes through the premium path is rethrown unchanged by\n * `normalizeEnlittModelError` and is never an instance of `EnlittError`.\n */\n\nimport {\n classifyEnlittErrorResponse,\n ENLITT_ERROR_CODE,\n ENLITT_ERROR_CODES,\n isEnlittErrorCode,\n // The frozen record's key type. Aliased on import so every reference in\n // this file reads as \"Enlitt's stable wire code\" rather than as a type this\n // module happens to reuse; the alias carries no members of its own.\n type EnlittErrorCode as EnlittWireCode\n} from \"@enlitt/protocol\";\n\n/**\n * The only codes this module originates. They exist because these four\n * failures never reach the wire: bad or missing configuration, a request\n * that never produced an HTTP response, a response that could not be parsed,\n * and a caller-initiated abort. All four are always non-retryable and always\n * report `providerInvoked: false`, the same as every wire-originated code,\n * because none of them means a provider was ever reached either.\n */\nexport type EnlittLocalCode =\n | \"configuration_invalid\"\n | \"transport_failed\"\n | \"malformed_response\"\n | \"request_canceled\";\n\n/**\n * A type-level proof, not a runtime check: if a future edit ever gives a\n * local code the same name as a protocol code, the intersection below stops\n * being `never` and this file fails to compile. `AssertNever` exists only to\n * force that failure at the point of collision instead of letting `EnlittError`\n * silently become ambiguous about which side of the wire a code came from.\n */\ntype AssertNever<T extends never> = T;\ntype _LocalCodesDisjointFromWireCodes = AssertNever<EnlittLocalCode & EnlittWireCode>;\n\n/**\n * The bounded facts a caller may attach when constructing an error: the\n * parsed `Retry-After`, the upstream `x-request-id`, and a navigation target.\n * Every field is optional because most codes carry none of them — a local\n * code carries none at all, and `authorizeUrl` is stored only where the\n * record permits the resulting code to carry one (see `EnlittError` below).\n */\nexport interface EnlittErrorFacts {\n /** Milliseconds, converted once from the wire's `Retry-After` seconds. */\n readonly retryAfterMs?: number;\n readonly requestId?: string;\n readonly authorizeUrl?: string;\n /**\n * Only meaningful for a code the record does not contain: the protocol\n * classifier's status-derived answer for a code from a newer server. A code\n * in the record always takes its `retryable` from the record instead.\n */\n readonly retryable?: boolean;\n}\n\n/**\n * Any other string: a code this SDK version does not know. `string & {}`\n * keeps editor completion for the known codes while forcing every business\n * `switch` over `EnlittError[\"code\"]` to carry a `default` branch. Exported as\n * a type only; it adds no runtime value.\n */\nexport type EnlittUnrecognizedCode = string & {};\n\n/**\n * The base class for every Enlitt-originated failure, and the only carrier\n * of Enlitt's stable wire codes into a caller's code.\n *\n * Enlitt failures with no distinct business action of their own — invalid\n * request, unsupported capability, conflict, routing, and server failures,\n * plus a wire code newer than this SDK knows — surface as this class\n * directly, carrying their stable code. Every other wire code that does\n * imply a distinct action gets its own subclass below.\n */\nexport class EnlittError extends Error {\n override readonly name: string = \"EnlittError\";\n\n readonly code: EnlittWireCode | EnlittLocalCode | EnlittUnrecognizedCode;\n\n /**\n * Always `false`. Enlitt refuses before a provider is ever reached, so no\n * instance of this hierarchy can report otherwise — that is the one\n * question a business needs answered before it retries or bills anything.\n * A provider's own error is never wrapped in this class in the first\n * place; see `normalizeEnlittModelError`.\n */\n readonly providerInvoked: boolean = false;\n\n /**\n * Read from the frozen record for a wire code, and always `false` for a\n * local code, which has no record entry. Never decided per instance: a\n * refusal carries the non-retryable marker the pinned Vercel AI SDK reads,\n * so a configured `maxRetries` cannot turn one refusal into several.\n */\n readonly retryable: boolean;\n\n readonly retryAfterMs?: number;\n readonly requestId?: string;\n\n /**\n * Present only when the record's `authorizeUrl` field for this instance's\n * code is `\"allowed\"` and a caller supplied one. It is a navigation\n * target, never a disclosure: the actual figures live only on Enlitt's own\n * dashboard behind it.\n *\n * The record allows this on the four `insufficient_credits_error` codes and\n * no others, which is what this module's spec text says. `authorizeUrl` is\n * still read from the record rather than decided here, per this module's own\n * rule; the record simply now agrees with the spec.\n */\n readonly authorizeUrl?: string;\n\n constructor(\n code: EnlittWireCode | EnlittLocalCode | EnlittUnrecognizedCode,\n message: string,\n facts: EnlittErrorFacts = {}\n ) {\n super(message);\n this.code = code;\n\n const definition = isEnlittErrorCode(code) ? ENLITT_ERROR_CODES[code] : undefined;\n // A code in the record always reads its retryability from the record. A\n // code from a newer server (not in the record, not local) takes the\n // classifier's status-derived answer; a local code is never retryable.\n this.retryable = definition?.retryable ?? (isLocalCode(code) ? false : (facts.retryable ?? false));\n\n if (facts.retryAfterMs !== undefined) {\n this.retryAfterMs = facts.retryAfterMs;\n }\n if (facts.requestId !== undefined) {\n this.requestId = facts.requestId;\n }\n // The record decides which known codes may carry a navigation target. For\n // a code from a newer server the protocol classifier has already kept the\n // URL only for a credit refusal with an acceptable origin, so it is copied\n // as given; a local code never carries one.\n if (\n facts.authorizeUrl !== undefined &&\n (definition?.authorizeUrl === \"allowed\" || (definition === undefined && !isLocalCode(code)))\n ) {\n this.authorizeUrl = facts.authorizeUrl;\n }\n }\n}\n\nconst LOCAL_CODES: ReadonlySet<string> = new Set<EnlittLocalCode>([\n \"configuration_invalid\",\n \"transport_failed\",\n \"malformed_response\",\n \"request_canceled\"\n]);\n\nfunction isLocalCode(code: string): code is EnlittLocalCode {\n return LOCAL_CODES.has(code);\n}\n\n/**\n * Code `configuration_invalid`. Missing or invalid SDK configuration: absent\n * business secret, browser use, invalid base URL, invalid call options, an\n * invalid quote, or a missing session context. Thrown locally before any\n * network call, so a misconfigured deployment fails without touching Enlitt\n * or a provider. Audience is the business's own logs; it must never reach an\n * end user's screen.\n */\nexport class EnlittConfigurationError extends EnlittError {\n override readonly name = \"EnlittConfigurationError\";\n constructor(message: string) {\n super(\"configuration_invalid\", message);\n }\n}\n\n/**\n * Code `personal_login_required`. No usable personal session resolves for\n * this application. It belongs to both the standard and premium paths\n * identically, with the provider left uninvoked either way: the alternative\n * — letting premium proceed at the business's own cost — would mean every\n * user whose session expired silently moved their spending onto the\n * business. Audience is the end user: the business sends them through\n * Enlitt login or reauthorization.\n */\nexport class EnlittLoginRequiredError extends EnlittError {\n override readonly name = \"EnlittLoginRequiredError\";\n constructor(message: string, facts: EnlittErrorFacts = {}) {\n super(ENLITT_ERROR_CODE.personal_login_required, message, facts);\n }\n}\n\n/**\n * Code `spending_limit_exceeded`. One of the user's application limits\n * refused the call. `limitRule` copies `error.enlitt.limit_rule`\n * (`standard_per_call`, `premium_per_call`, `rate.standard`, `rate.premium`,\n * or a rule a newer server added) so the business can explain which limit refused without\n * learning its value. It carries no amount, because a user's ceiling is their\n * own financial position. An unknown future rule stays a string and is\n * rendered generically; this field is never a closed authorization decision.\n * Audience is the end user, who raises the limit at `authorizeUrl`.\n */\nexport class EnlittLimitExceededError extends EnlittError {\n override readonly name = \"EnlittLimitExceededError\";\n readonly limitRule: string;\n constructor(message: string, limitRule: string, facts: EnlittErrorFacts = {}) {\n super(ENLITT_ERROR_CODE.spending_limit_exceeded, message, facts);\n this.limitRule = limitRule;\n }\n}\n\n/**\n * Codes `premium_balance_exhausted` and `standard_balance_exhausted` (and any\n * credit-refusal code from a newer server, carried raw). The first means the\n * matching allowance plus eligible bundles cannot cover the call; the second\n * is the standard equivalent. `admissibleMaxChargeNanoUsd` is present only on\n * a premium `premium_balance_exhausted`: the largest `maxCharge` the user's\n * remaining credits would admit now, copied byte for byte. It is the protocol's\n * single disclosed figure; the SDK never retries with it on its own. No other\n * balance, plan, tier, or period fact is ever carried. The audience is the\n * end user, who tops up or upgrades at `authorizeUrl`.\n */\nexport class EnlittInsufficientCreditsError extends EnlittError {\n override readonly name = \"EnlittInsufficientCreditsError\";\n readonly admissibleMaxChargeNanoUsd?: string;\n constructor(\n code:\n | typeof ENLITT_ERROR_CODE.premium_balance_exhausted\n | typeof ENLITT_ERROR_CODE.standard_balance_exhausted\n | EnlittUnrecognizedCode,\n message: string,\n facts: EnlittErrorFacts & { readonly admissibleMaxChargeNanoUsd?: string } = {}\n ) {\n super(code, message, facts);\n if (facts.admissibleMaxChargeNanoUsd !== undefined) {\n this.admissibleMaxChargeNanoUsd = facts.admissibleMaxChargeNanoUsd;\n }\n }\n}\n\n/**\n * Code `subscription_inactive`. No subscription period covers the current\n * instant. Because every registered user holds at least the free plan, this\n * is exceptional rather than the ordinary state of a user who has not paid:\n * a user who never subscribed, lapsed, or canceled receives\n * `EnlittInsufficientCreditsError` at free-plan ceilings instead. Audience is\n * the end user, but a business seeing this at any volume should treat it as\n * a defect signal rather than a funnel step.\n */\nexport class EnlittSubscriptionInactiveError extends EnlittError {\n override readonly name = \"EnlittSubscriptionInactiveError\";\n constructor(message: string, facts: EnlittErrorFacts = {}) {\n super(ENLITT_ERROR_CODE.subscription_inactive, message, facts);\n }\n}\n\n/**\n * Code `rate_limit_exceeded`. This user has started as many standard calls as\n * their plan allows for the current minute. Only the standard path raises it:\n * a premium operation consumes no request budget. It is the only refusal-shaped\n * condition that is retryable, and the only class that carries\n * `retryAfterMs` in practice. It is emphatically not an\n * `EnlittInsufficientCreditsError`: conflating a transient wait with an\n * exhausted balance would tell users to buy credits they do not need. It\n * carries no rate, remaining request count, or plan fact, because those are\n * the user's plan details.\n */\nexport class EnlittRateLimitError extends EnlittError {\n override readonly name = \"EnlittRateLimitError\";\n constructor(message: string, facts: EnlittErrorFacts = {}) {\n super(ENLITT_ERROR_CODE.rate_limit_exceeded, message, facts);\n }\n}\n\n/**\n * Code `invalid_api_key`. The presented business key is missing, invalid, or\n * revoked. Audience is the business's own logs; never rendered to an end\n * user, and never softened into a direct provider call.\n */\nexport class EnlittAuthenticationError extends EnlittError {\n override readonly name = \"EnlittAuthenticationError\";\n constructor(message: string, facts: EnlittErrorFacts = {}) {\n super(ENLITT_ERROR_CODE.invalid_api_key, message, facts);\n }\n}\n\n/**\n * Code `insufficient_permissions`. The presented business key is valid but\n * used outside its authenticated application or scope. Audience is the\n * business's own logs; never rendered to an end user, and never softened\n * into a direct provider call.\n */\nexport class EnlittAuthorizationError extends EnlittError {\n override readonly name = \"EnlittAuthorizationError\";\n constructor(message: string, facts: EnlittErrorFacts = {}) {\n super(ENLITT_ERROR_CODE.insufficient_permissions, message, facts);\n }\n}\n\n/**\n * Per-code facts the protocol classifier extracted that only some classes\n * carry. Passed to every factory so the table stays uniform.\n */\ninterface ClassifiedExtras {\n readonly limitRule?: string;\n readonly admissibleMaxChargeNanoUsd?: string;\n}\n\n/** One wire code's constructor, uniform across every entry in the map below. */\ntype WireErrorFactory = (message: string, facts: EnlittErrorFacts, extras: ClassifiedExtras) => EnlittError;\n\n/**\n * The wire-code-to-class mapping, exhaustive over the protocol record by\n * construction: `satisfies Record<EnlittWireCode, WireErrorFactory>` rejects\n * this object literal at compile time if it is missing a key the record\n * defines, and rejects it just as loudly if it carries a key the record does\n * not, so a code added to the protocol without a class here fails the build\n * instead of falling through to the base class at runtime.\n *\n * Codes with no distinct business action of their own (dashboard-only codes,\n * validation, conflicts, server failures) use the base class carrying their\n * stable code; every other entry uses the subclass named for it.\n */\nconst WIRE_CODE_FACTORY = {\n personal_login_required: (message, facts) => new EnlittLoginRequiredError(message, facts),\n spending_limit_exceeded: (message, facts, extras) =>\n new EnlittLimitExceededError(message, extras.limitRule ?? \"unrecognized\", facts),\n premium_balance_exhausted: (message, facts, extras) =>\n new EnlittInsufficientCreditsError(ENLITT_ERROR_CODE.premium_balance_exhausted, message, {\n ...facts,\n ...(extras.admissibleMaxChargeNanoUsd !== undefined\n ? { admissibleMaxChargeNanoUsd: extras.admissibleMaxChargeNanoUsd }\n : {})\n }),\n standard_balance_exhausted: (message, facts) =>\n new EnlittInsufficientCreditsError(ENLITT_ERROR_CODE.standard_balance_exhausted, message, facts),\n subscription_inactive: (message, facts) => new EnlittSubscriptionInactiveError(message, facts),\n rate_limit_exceeded: (message, facts) => new EnlittRateLimitError(message, facts),\n invalid_api_key: (message, facts) => new EnlittAuthenticationError(message, facts),\n insufficient_permissions: (message, facts) => new EnlittAuthorizationError(message, facts),\n dashboard_login_required: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.dashboard_login_required, message, facts),\n admin_authentication_required: (message, facts) =>\n new EnlittError(ENLITT_ERROR_CODE.admin_authentication_required, message, facts),\n conflict_error: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.conflict_error, message, facts),\n operation_in_progress: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.operation_in_progress, message, facts),\n idempotency_replay_unavailable: (message, facts) =>\n new EnlittError(ENLITT_ERROR_CODE.idempotency_replay_unavailable, message, facts),\n invalid_value: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.invalid_value, message, facts),\n unsupported_parameter: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.unsupported_parameter, message, facts),\n unsupported_value: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.unsupported_value, message, facts),\n reauthentication_required: (message, facts) =>\n new EnlittError(ENLITT_ERROR_CODE.reauthentication_required, message, facts),\n payment_declined: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.payment_declined, message, facts),\n invalid_sign_in_code: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.invalid_sign_in_code, message, facts),\n not_found: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.not_found, message, facts),\n request_too_large: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.request_too_large, message, facts),\n server_error: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.server_error, message, facts),\n provider_error: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.provider_error, message, facts),\n business_selection_required: (message, facts) =>\n new EnlittError(ENLITT_ERROR_CODE.business_selection_required, message, facts),\n bot_verification_failed: (message, facts) =>\n new EnlittError(ENLITT_ERROR_CODE.bot_verification_failed, message, facts),\n phone_verification_required: (message, facts) =>\n new EnlittError(ENLITT_ERROR_CODE.phone_verification_required, message, facts),\n invalid_phone_code: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.invalid_phone_code, message, facts),\n phone_number_not_supported: (message, facts) =>\n new EnlittError(ENLITT_ERROR_CODE.phone_number_not_supported, message, facts),\n phone_number_unavailable: (message, facts) =>\n new EnlittError(ENLITT_ERROR_CODE.phone_number_unavailable, message, facts),\n business_name_unavailable: (message, facts) =>\n new EnlittError(ENLITT_ERROR_CODE.business_name_unavailable, message, facts),\n // The four CLI device-flow codes (RFC 8628). No SDK route can return them, but\n // the mapping is exhaustive over the record, so they surface as the base class.\n authorization_pending: (message, facts) =>\n new EnlittError(ENLITT_ERROR_CODE.authorization_pending, message, facts),\n slow_down: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.slow_down, message, facts),\n access_denied: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.access_denied, message, facts),\n expired_token: (message, facts) => new EnlittError(ENLITT_ERROR_CODE.expired_token, message, facts)\n} as const satisfies Record<EnlittWireCode, WireErrorFactory>;\n\n/**\n * An Enlitt HTTP error response, shaped for normalization: the HTTP status,\n * the parsed JSON body (untrusted, hence `unknown`), and the two response\n * headers normalization reads. `core/transport.ts` is the only intended\n * producer of this shape.\n */\nexport interface EnlittHttpErrorResponse {\n readonly kind: \"http_error\";\n readonly status: number;\n readonly body: unknown;\n readonly headers: Readonly<Record<string, string | undefined>>;\n}\n\n/** A request that never produced an HTTP response at all. */\nexport interface EnlittTransportFailure {\n readonly kind: \"transport_failed\";\n readonly message?: string;\n}\n\n/** A response that was received but could not be parsed as Enlitt's contract. */\nexport interface EnlittMalformedResponse {\n readonly kind: \"malformed_response\";\n readonly message?: string;\n}\n\n/** A caller-initiated abort of a request still in flight. */\nexport interface EnlittRequestCanceled {\n readonly kind: \"request_canceled\";\n readonly message?: string;\n}\n\n/**\n * Every shape `normalizeEnlittModelError` recognizes. `error` is typed\n * `unknown` at the function boundary because it is handed whatever the\n * transport or the runtime threw; this union is what it is checked against.\n */\nexport type EnlittNormalizationInput =\n | EnlittHttpErrorResponse\n | EnlittTransportFailure\n | EnlittMalformedResponse\n | EnlittRequestCanceled;\n\nfunction hasKind(value: unknown): value is { readonly kind: unknown } {\n return typeof value === \"object\" && value !== null && \"kind\" in value;\n}\n\n/**\n * Converts the wire's `Retry-After` seconds into milliseconds exactly once,\n * at the point the response is parsed. A missing or unparseable header\n * leaves the result `undefined` rather than defaulting to zero, because a\n * zero would invite an immediate retry into a limit that has not moved.\n */\nfunction parseRetryAfterMs(header: string | undefined): number | undefined {\n if (header === undefined) {\n return undefined;\n }\n const seconds = Number(header);\n if (!Number.isFinite(seconds) || seconds < 0) {\n return undefined;\n }\n return seconds * 1000;\n}\n\n/**\n * Maps an HTTP error response through the protocol's shared classifier, so\n * the SDK, the frontend, and the fixture tests classify an error the same\n * way. This function never parses the error body itself.\n */\nfunction normalizeHttpErrorResponse(input: EnlittHttpErrorResponse): EnlittError {\n const requestId = input.headers[\"x-request-id\"];\n const classified = classifyEnlittErrorResponse(input.status, input.body);\n\n // A body that is neither error envelope (an HTML gateway page, an empty\n // body, a JSON array): no code can be trusted, so it is a malformed response.\n if (classified === null) {\n return new EnlittError(\n \"malformed_response\",\n `Enlitt returned HTTP ${String(input.status)} with a body that is not an Enlitt error.`,\n requestId !== undefined ? { requestId } : {}\n );\n }\n\n const message = classified.message ?? \"Enlitt refused the request.\";\n\n if (classified.recognized && isEnlittErrorCode(classified.code)) {\n const retryAfterMs = parseRetryAfterMs(input.headers[\"retry-after\"]);\n const facts: EnlittErrorFacts = {\n ...(retryAfterMs !== undefined ? { retryAfterMs } : {}),\n ...(requestId !== undefined ? { requestId } : {}),\n ...(classified.authorizeUrl !== undefined ? { authorizeUrl: classified.authorizeUrl } : {})\n };\n return WIRE_CODE_FACTORY[classified.code](message, facts, {\n ...(classified.limitRule !== undefined ? { limitRule: classified.limitRule } : {}),\n ...(classified.admissibleMaxChargeNanoUsd !== undefined\n ? { admissibleMaxChargeNanoUsd: classified.admissibleMaxChargeNanoUsd }\n : {})\n });\n }\n\n // A code this SDK does not recognize: most likely a newer backend. It never\n // throws and never fails the build. `Retry-After` is deliberately ignored,\n // because only a code the record marks `retryAfter: \"required\"` is known to\n // mean \"wait and repeat\", and a 429 with an unknown code is never the\n // rate-limit class so it is surfaced once instead of retried blindly.\n const upgradeMessage =\n `Enlitt returned error code \"${classified.code}\" (HTTP ${String(classified.status)}, type ` +\n `\"${classified.type ?? \"none\"}\"), which this version of @enlitt/sdk does not recognize. ` +\n \"Upgrade @enlitt/sdk to handle it.\" +\n (classified.message !== null ? ` ${classified.message}` : \"\");\n const facts: EnlittErrorFacts = {\n ...(requestId !== undefined ? { requestId } : {}),\n ...(classified.authorizeUrl !== undefined ? { authorizeUrl: classified.authorizeUrl } : {}),\n retryable: classified.retryable\n };\n if (classified.creditRefusal) {\n return new EnlittInsufficientCreditsError(classified.code, upgradeMessage, facts);\n }\n return new EnlittError(classified.code, upgradeMessage, facts);\n}\n\n/**\n * Maps one Enlitt failure to exactly one class.\n *\n * `providerInvoked` is accepted for signature symmetry with callers that\n * track it across the premium path, but every value returned is an\n * `EnlittError`, whose `providerInvoked` is always `false`: Enlitt refuses\n * before a provider is reached. A provider's own error is never routed\n * through this function; the premium path rethrows it unchanged.\n *\n * The mapping is keyed on the stable code alone, never on HTTP status: a\n * `429` carrying any code other than `rate_limit_exceeded` does not become\n * `EnlittRateLimitError`.\n */\nexport function normalizeEnlittModelError(error: unknown, providerInvoked: boolean): EnlittError {\n void providerInvoked;\n\n if (hasKind(error)) {\n switch (error.kind) {\n case \"http_error\":\n return normalizeHttpErrorResponse(error as EnlittHttpErrorResponse);\n case \"transport_failed\": {\n const input = error as EnlittTransportFailure;\n return new EnlittError(\n \"transport_failed\",\n input.message ?? \"The request to Enlitt failed before a response was received.\"\n );\n }\n case \"request_canceled\": {\n const input = error as EnlittRequestCanceled;\n return new EnlittError(\"request_canceled\", input.message ?? \"The request was canceled before it completed.\");\n }\n case \"malformed_response\":\n default:\n break;\n }\n }\n\n const input = hasKind(error) && error.kind === \"malformed_response\" ? (error as EnlittMalformedResponse) : undefined;\n return new EnlittError(\"malformed_response\", input?.message ?? \"Enlitt's response could not be parsed.\");\n}\n","/**\n * The read end of the Enlitt session cookie.\n *\n * `specs/SDK-side routing.md` gives this file the session handle, the\n * middleware, and the async-context accessors. It owns \"the user logs in and\n * their credits are just used\": it carries Enlitt's opaque session token from\n * the cookie Account's login callback already set, through an\n * `AsyncLocalStorage` context, to whatever call site needs it, without ever\n * reading, parsing, or validating what the token contains. Validity is\n * Enlitt's answer to give at call time, not this file's to guess.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { EnlittConfigurationError } from \"./errors.js\";\n\n/**\n * The canonical Enlitt session cookie name, and the default of both\n * `CallbackConfig.cookieName` and `SessionMiddlewareOptions.cookieName`.\n *\n * A business that passes a custom `cookieName` to the callback must pass the\n * identical value to the middleware. That is the one case the two ends can\n * still disagree, and it is the business's own to keep consistent; the default\n * is not, which is why it is one constant rather than two literals.\n */\nexport const ENLITT_SESSION_COOKIE_NAME = \"enlitt_session\";\n\n/**\n * The longest token value `enlittSession()` accepts.\n *\n * Not a claim about Enlitt's actual token format, which this module never\n * inspects: it exists only so a business's own bug (an empty string, or\n * something that is clearly not a token, such as a whole cookie header pasted\n * in whole) fails at construction instead of being carried silently to a call\n * Enlitt then refuses for a reason the caller cannot see locally.\n */\nconst MAX_SESSION_TOKEN_LENGTH = 4096;\n\n/**\n * An opaque handle around Enlitt's session token.\n *\n * The token has no subject, expiry, or scope readable from the SDK side, and\n * every fact about the user lives on Enlitt's servers. Deliberately just a\n * string wrapper: exposing it as a bare `string` anywhere in the call surface\n * would invite a business to construct or compare tokens as ordinary strings,\n * and there is no format a business can legitimately synthesize.\n */\nexport interface EnlittSession {\n readonly token: string;\n}\n\n/**\n * The only way to construct an `EnlittSession`.\n *\n * The token is a string the SDK never parses, decodes, validates, or\n * inspects; this is what lets Enlitt rotate or restructure the underlying\n * credential without a business shipping a release, and what keeps the\n * business from ever holding an OAuth token or implementing a refresh.\n * Constructing one from a value a business stored itself is legitimate and is\n * how linked accounts and background jobs work; constructing one from a value\n * the business derived, guessed, or built from a user identifier is not a\n * session, and Enlitt rejects it at call time. The factory validates only\n * that the token is a non-empty bounded string, because anything more would\n * be inspecting a credential this module must treat as opaque.\n */\nexport function enlittSession(token: string): EnlittSession {\n if (typeof token !== \"string\" || token.length === 0 || token.length > MAX_SESSION_TOKEN_LENGTH) {\n throw new EnlittConfigurationError(\n \"enlittSession() requires a non-empty session token no longer than \" +\n `${MAX_SESSION_TOKEN_LENGTH} characters.`\n );\n }\n return { token };\n}\n\n/**\n * Options for `enlittSessionMiddleware()`.\n *\n * `cookieName` exists solely to mirror a business's own custom\n * `CallbackConfig.cookieName`; the default matches `ENLITT_SESSION_COOKIE_NAME`\n * so the common case names nothing.\n */\nexport interface SessionMiddlewareOptions {\n cookieName?: string;\n}\n\n/**\n * The shape `enlittSessionMiddleware()` returns.\n *\n * Framework-agnostic over Web `Request` and `Response`, exactly as Account's\n * callback handlers are: v1 ships no per-framework adapter, so this is the\n * one shape every framework's own middleware layer can wrap.\n */\nexport type EnlittMiddleware = (request: Request, next: () => Promise<Response>) => Promise<Response>;\n\n/**\n * The single `AsyncLocalStorage` context carrying the current request's\n * session.\n *\n * Not exported: the module boundary between \"install the context\" and \"read\n * the context\" is what lets `getEnlittSession()` distinguish a missing\n * middleware from a signed-out visitor by whether a context exists at all,\n * a distinction that leaks the moment callers can reach the storage directly.\n */\nconst sessionContext = new AsyncLocalStorage<EnlittSession | null>();\n\n/**\n * Reads the Enlitt session cookie from an incoming request, runs `next()`\n * with an `AsyncLocalStorage` context carrying the resulting `EnlittSession`\n * or an explicit `null`, and leaves the context when the request ends.\n *\n * It never rejects a request: plenty of a business's routes are for\n * signed-out visitors, and deciding the business's authentication policy is\n * not this middleware's job. It performs no network call and no validation,\n * because validity is Enlitt's answer to give at call time and pre-validating\n * here would add a round trip to every request, including the ones that never\n * call a model. The cookie lives on the business's own domain and was set by\n * Enlitt's login callback, so no cross-site cookie, third-party storage, or\n * browser-side token is involved.\n */\nexport function enlittSessionMiddleware(options?: SessionMiddlewareOptions): EnlittMiddleware {\n const cookieName = options?.cookieName ?? ENLITT_SESSION_COOKIE_NAME;\n return async function enlittMiddleware(request: Request, next: () => Promise<Response>): Promise<Response> {\n const token = readCookie(request, cookieName);\n const session = token === null ? null : enlittSession(token);\n return sessionContext.run(session, next);\n };\n}\n\n/**\n * Runs `fn` with an explicit `EnlittSession` (or `null`) bound as the ambient\n * session for its entire synchronous and asynchronous extent.\n *\n * The escape hatch for a framework whose middleware shape\n * `enlittSessionMiddleware()` cannot wrap directly: a business on such a\n * framework establishes the same context in one line instead of waiting on a\n * per-framework adapter that v1 does not ship.\n */\nexport function runWithEnlittSession<T>(session: EnlittSession | null, fn: () => T): T {\n return sessionContext.run(session, fn);\n}\n\n/**\n * Returns the ambient session for the current request context.\n *\n * Throws `EnlittConfigurationError` when there is no context at all: no\n * context means the middleware is not installed on this path, which is the\n * business's own wiring bug, and treating that as \"signed out\" would make\n * every user of a misconfigured deployment silently unauthenticated. Returns\n * `null` when there is a context and no session, which is the genuine\n * signed-out state a business checks before calling a model. These two\n * conditions must never collapse into one: a deployment bug and a\n * signed-out visitor look identical at the call site and must not be\n * reported identically. A session this returns may still be expired or\n * revoked; that is not knowable locally, so the call carries it and Enlitt\n * answers with `personal_login_required` if it must.\n */\nexport function getEnlittSession(): EnlittSession | null {\n if (!hasEnlittSessionContext()) {\n throw new EnlittConfigurationError(\n \"getEnlittSession() was called with no enlittSessionMiddleware() (or \" +\n \"runWithEnlittSession()) context installed on this request path.\"\n );\n }\n return sessionContext.getStore() ?? null;\n}\n\n/**\n * Distinguishes \"no `AsyncLocalStorage` context at all\" from \"a context\n * holding `null`\", which reading `getStore()` alone cannot do since both\n * would otherwise read back as a nullish value.\n *\n * Relies on `AsyncLocalStorage`'s own documented signal: `getStore()` returns\n * `undefined` when no `run()` scope is active, and returns the exact value\n * (including `null`) passed to the innermost active `run()` otherwise. So the\n * presence of a context is `getStore() !== undefined`, given this module\n * never stores `undefined` itself — only an `EnlittSession` or `null`.\n */\nfunction hasEnlittSessionContext(): boolean {\n return sessionContext.getStore() !== undefined;\n}\n\n/**\n * Parses the named cookie out of a Web `Request`'s `Cookie` header.\n *\n * Deliberately minimal: this reads one opaque value off the business's own\n * domain and never interprets it, so it need not implement the full cookie\n * grammar, only enough to split `name=value` pairs safely.\n */\nfunction readCookie(request: Request, name: string): string | null {\n const header = request.headers.get(\"cookie\");\n if (header === null) {\n return null;\n }\n for (const part of header.split(\";\")) {\n const separatorIndex = part.indexOf(\"=\");\n if (separatorIndex === -1) {\n continue;\n }\n const rawName = part.slice(0, separatorIndex).trim();\n if (rawName !== name) {\n continue;\n }\n const rawValue = part.slice(separatorIndex + 1).trim();\n try {\n return decodeURIComponent(rawValue);\n } catch {\n return rawValue;\n }\n }\n return null;\n}\n","/**\n * The server-only boundary that turns a business secret into an outgoing\n * authorization header.\n *\n * There is exactly one export. Resolving a key and formatting a header used to\n * be two of them, which made \"resolve the key and forget to use it\" a\n * reachable mistake at every call site; there is now no way to obtain the\n * secret through this module's public surface without obtaining the header.\n *\n * A missing or unusable secret throws locally, before any network call, and\n * never yields an unauthenticated client or a credential-free request. That\n * local failure is what stops a managed premium call from silently falling\n * through to a direct, business-funded provider call.\n *\n * The resolved value is a secret. It is never logged, never serialized into a\n * thrown error's message or fields, and never returned to a caller: the\n * `browser` condition on the `./server` subpath keeps this file out of every\n * browser bundle, and the environment assertion below is the second net for a\n * bundler or runtime that ignores that condition.\n *\n * Both local failures — a browser environment and an unusable secret — raise\n * `EnlittConfigurationError`. That is what `enlitt()` documents its callers\n * will see for a missing or invalid secret, and the type has to be right here\n * rather than at one caller's boundary: any other caller of this function\n * (`server/callback.ts`'s handlers among them) would otherwise receive a bare\n * `Error` for exactly the same misconfiguration, and a business catching the\n * package's own error class would miss it.\n */\n\nimport { EnlittConfigurationError } from \"../core/errors.js\";\n\nconst ENV_KEY = \"ENLITT_SECRET_KEY\";\n\n/**\n * A single visible-ASCII run: exactly what an HTTP header value may carry.\n *\n * A secret holding a control character, a space, or a newline is unusable\n * rather than merely unusual — pasted with a trailing newline it would either\n * be rejected by the transport or, worse, split the header. Refusing it here\n * is the same local failure as a missing key.\n */\nconst USABLE_SECRET = /^[!-~]+$/;\n\n/**\n * Refuse before any secret-related work if this looks like a browser.\n *\n * The heuristic is the simultaneous presence of `window` and `document`,\n * which is reliably absent in Node, Deno, Bun, and Cloudflare Workers and\n * present in every mainstream browser. It is deliberately not exported: a\n * caller has no reason to ask the question separately from asking for the\n * header, and an exported assertion is one more thing that can be called and\n * its answer ignored.\n */\nfunction assertServerEnvironment(): void {\n if (typeof window !== \"undefined\" && typeof document !== \"undefined\") {\n throw new EnlittConfigurationError(\n \"@enlitt/sdk: server-only module imported in a browser environment. \" +\n \"Use @enlitt/sdk/browser for code you ship to consumers.\"\n );\n }\n}\n\n// Fail on module evaluation too, so a mistaken browser import surfaces at\n// import time rather than at the first call that needed a credential.\nassertServerEnvironment();\n\n/**\n * Read the environment fallback without assuming a `process` global exists.\n *\n * Workers-style runtimes have no `process`, and reaching for it unguarded\n * would turn \"no key configured\" into a `ReferenceError` that reads like a\n * bug in the SDK rather than a missing configuration value.\n */\nfunction readEnvironmentSecret(): string | undefined {\n const runtime = globalThis as { process?: { env?: Record<string, string | undefined> } };\n return runtime.process?.env?.[ENV_KEY];\n}\n\n/**\n * Resolve the business secret and return the one header value that carries it.\n *\n * Resolution order is explicit configuration first, then the `ENLITT_SECRET_KEY`\n * environment fallback. An explicitly supplied key is never abandoned in\n * favour of the environment: a business that passed an empty or malformed\n * value has misconfigured that value, and silently authenticating as whatever\n * the environment happens to hold would be a different identity than the one\n * the call site asked for.\n *\n * @returns a single `Bearer <secret>` header value.\n * @throws {EnlittConfigurationError} in a browser environment, or when no\n * usable secret resolves. Neither the message nor any field of the thrown\n * error carries any part of the secret.\n */\nexport function resolveBusinessAuthorizationHeader(config: { secretKey?: string }): string {\n // Before resolution, not after: a browser must never reach the code that\n // reads a secret at all, let alone hold the result.\n assertServerEnvironment();\n\n const configured = config.secretKey;\n // Not `??`: that would treat a `null` from an untyped JavaScript caller as\n // \"nothing configured\" and fall through to the environment, authenticating as\n // whatever identity the environment happens to hold rather than refusing the\n // misconfigured value. Only `undefined` means the caller configured nothing.\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n const candidate: unknown = configured === undefined ? readEnvironmentSecret() : configured;\n\n if (typeof candidate !== \"string\" || !USABLE_SECRET.test(candidate)) {\n throw new EnlittConfigurationError(\n \"@enlitt/sdk: no usable Enlitt secret key. Pass one as { secretKey } or set \" +\n `the ${ENV_KEY} environment variable on the server. The value must be a ` +\n \"non-empty string of visible ASCII characters.\"\n );\n }\n\n return `Bearer ${candidate}`;\n}\n","/**\n * The module's single authenticated exit to Enlitt.\n *\n * `specs/SDK-side routing.md` gives this file three jobs that must live in\n * exactly one place: the definition of the internal client\n * (`InternalEnlittClient`, built once per factory call by\n * `createInternalClient()`), the one place a personal session is resolved\n * (`InternalEnlittClient.resolveSession`), and the one function that ever\n * issues an HTTP request to Enlitt (`requestEnlitt()`). Both the standard and\n * premium model files call through this file rather than `fetch` directly, so\n * every header, every safety check, and every retry the spec requires exists\n * exactly once instead of once per model.\n *\n * It owns exactly two internal retries and no others: the bounded, jittered\n * wait that absorbs `rate_limit_exceeded` (inside `requestEnlitt()` itself,\n * because it applies uniformly to every request this module sends), and a\n * bounded transient retry of a premium terminal report under one unchanged\n * `report_id`/`Idempotency-Key` (`reportEnlittPremiumTerminal()`, layered on\n * top of `requestEnlitt()` because it applies to exactly one call shape and\n * must never leak onto a preflight, a standard call, or a refusal). Every\n * other failure — every refusal, every conflict, every `4xx` other than `429\n * rate_limit_exceeded` — is normalized and thrown once, never retried here.\n *\n * It never accepts a personal identity as a caller-supplied parameter: the\n * only personal value that ever leaves this file is the opaque token\n * `client.resolveSession()` returns, and no argument, option, or request body\n * field can supply or override it. It never logs or returns that token,\n * prompt content, or a raw provider error, and it never runs in a browser —\n * it is reachable only through `@enlitt/sdk/server`, which the package export\n * map keeps out of the `browser` condition.\n */\n\nimport { ENLITT_API_VERSION, ENLITT_ERROR_CODE, ENLITT_VERSION_HEADER } from \"@enlitt/protocol\";\nimport {\n EnlittConfigurationError,\n EnlittError,\n normalizeEnlittModelError,\n type EnlittHttpErrorResponse,\n type EnlittMalformedResponse,\n type EnlittRequestCanceled,\n type EnlittTransportFailure\n} from \"./errors.js\";\nimport { resolveBusinessAuthorizationHeader } from \"../server/secrets.js\";\nimport { getEnlittSession, type EnlittSession } from \"./session.js\";\n\n/**\n * The SDK's own version, sent as `X-Enlitt-SDK-Version` so Enlitt's own logs\n * can tell which client behavior produced a given request without the header\n * carrying anything about the business or the user.\n *\n * A literal rather than a `package.json` import: this package ships as both\n * ESM and CJS, its `tsup` build does not embed the manifest, and a JSON\n * import here would tie a request-time value to a file layout assumption\n * this module has no other reason to make. It must be bumped by hand\n * alongside `package.json`'s `version` field.\n */\nexport const SDK_VERSION = \"0.1.0\";\n\n/** Hosts `http:` is still accepted for, matching a developer's own machine. */\nconst LOCAL_HTTP_HOSTS: ReadonlySet<string> = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"]);\n\n/**\n * The deployed default floor for a rate-limit wait when the refusal carries\n * no `Retry-After`. One second: long enough that an immediate retry cannot\n * reassemble the burst that caused the refusal, short enough that a business\n * under its own `maxRetries` does not perceive a hang.\n */\nconst DEFAULT_RATE_LIMIT_FLOOR_MS = 1_000;\n\n/**\n * The deployed default bound on rate-limit retry attempts. Chosen so a caller\n * that never configures `rateLimit` still backs off a handful of times\n * before the failure surfaces, rather than waiting on `maxTotalWaitMs` alone\n * to end an unbounded attempt count.\n */\nconst DEFAULT_RATE_LIMIT_MAX_ATTEMPTS = 3;\n\n/**\n * The deployed default wall-clock budget for a rate-limit wait, measured\n * from the first refusal. Kept comfortably under common serverless request\n * timeouts (typically 10-60s) so an exhausted budget surfaces as a typed\n * `EnlittRateLimitError` rather than the platform killing the process\n * mid-wait.\n */\nconst DEFAULT_RATE_LIMIT_MAX_TOTAL_WAIT_MS = 30_000;\n\n/**\n * The deployed bound on how many times `reportEnlittPremiumTerminal()` will\n * resend one terminal report before giving up and handing the failure to\n * `onTerminalReportError`. Small and fixed, unlike the rate-limit wait: a\n * terminal report that keeps failing after a few attempts is failing for a\n * reason a delay will not fix, and the credit hold it would otherwise\n * release already has its own deadline-driven backstop on Enlitt's side.\n */\nconst TERMINAL_REPORT_MAX_ATTEMPTS = 3;\n\n/** The floor of the delay between terminal-report retry attempts. */\nconst TERMINAL_REPORT_RETRY_DELAY_MS = 500;\n\n/**\n * The largest total byte size this module will read out of a response's\n * headers before giving up on it as malformed. Bounding it is what keeps a\n * misbehaving or compromised endpoint from making this module buffer an\n * unbounded amount of attacker-controlled data before normalization ever\n * runs.\n */\nconst MAX_RESPONSE_HEADER_BYTES = 32 * 1024;\n\n/** The largest response body this module will buffer before parsing it. */\nconst MAX_RESPONSE_BODY_BYTES = 1024 * 1024;\n\n/**\n * Caller-supplied tuning for the rate-limit wait. Every field is optional\n * because `createInternalClient()` folds it over the SDK's own defaults\n * exactly once, at construction, which is what lets every later read of\n * `client.rateLimit` assume every field but `onRateLimit` is present.\n */\nexport interface EnlittRateLimitRetryOptions {\n /** Upper bound on attempts, including the first (minimum 1). Default {@link DEFAULT_RATE_LIMIT_MAX_ATTEMPTS}. */\n readonly maxAttempts?: number;\n /** Upper bound on total time spent waiting, measured from the first refusal. Default {@link DEFAULT_RATE_LIMIT_MAX_TOTAL_WAIT_MS}. */\n readonly maxTotalWaitMs?: number;\n /**\n * Invoked once per wait, with the attempt number (1-based) about to be\n * slept and the jittered delay in milliseconds. The only way a business\n * observes a rate-limit wait without this module disclosing a plan fact.\n */\n readonly onRateLimit?: (attempt: number, delayMs: number) => void;\n}\n\n/**\n * Constructor options for `createInternalClient()`.\n *\n * `secretKey` and `baseUrl` are exactly what `resolveBusinessAuthorizationHeader()`\n * and the HTTPS assertion need and nothing more; neither this type nor the\n * client it builds ever carries a personal identity, because the only\n * personal value the transport ever sends is the token `resolveSession()`\n * (built from `session`, or from the ambient context) produces at request\n * time.\n */\nexport interface EnlittOptions {\n /** Forwarded to `resolveBusinessAuthorizationHeader()` unchanged. */\n readonly secretKey?: string;\n /**\n * Enlitt's base URL. Resolves from this option, then `ENLITT_BASE_URL`, then\n * the deployed Enlitt origin compiled into the package. Must be `https:`, or\n * `http:` on a local host. Parsed and validated once, at construction.\n */\n readonly baseUrl?: string;\n /**\n * An explicit session, for a caller that cannot rely on the ambient\n * `AsyncLocalStorage` context — a background job, or a framework\n * `enlittSessionMiddleware()` cannot wrap. When absent, every call resolves\n * the session from `getEnlittSession()` instead.\n */\n readonly session?: EnlittSession;\n readonly rateLimit?: EnlittRateLimitRetryOptions;\n /**\n * Observes a failure `reportEnlittPremiumTerminal()` could not recover\n * from after exhausting its bounded retry. There is no caller left to\n * return the error to by the time this fires — the provider call this\n * report describes has already completed — so this hook is the only way a\n * business ever learns a terminal report did not land.\n */\n readonly onTerminalReportError?: (error: EnlittError) => void;\n}\n\n/**\n * The internal client every request in this module is built from.\n *\n * Constructed once per factory call from the business's resolved secret and\n * the deployed environment, and never held as nullable: holding a client at\n * all is what makes a call managed, so there is no code path in this package\n * that represents \"no Enlitt configuration\" as a null or optional client\n * instead of failing at construction.\n */\nexport interface InternalEnlittClient {\n readonly baseUrl: string;\n /** The full `Authorization` header value, e.g. `Bearer sk_...`. Never logged or returned. */\n readonly businessAuthorization: string;\n readonly sdkVersion: string;\n /**\n * The module's single session resolution. Returns the explicit\n * `EnlittOptions.session` when one was given; otherwise defers to\n * `getEnlittSession()`, which itself distinguishes \"no middleware\n * installed\" (`EnlittConfigurationError`) from \"signed out\" (`null`,\n * raised here as `EnlittLoginRequiredError` with `providerInvoked: false`).\n * Both model files call this indirectly through `requestEnlitt()` rather\n * than resolving a session themselves, which is what keeps the three\n * outcomes from drifting apart between the standard and premium paths.\n */\n readonly resolveSession: () => EnlittSession;\n readonly rateLimit: Required<Omit<EnlittRateLimitRetryOptions, \"onRateLimit\">> &\n Pick<EnlittRateLimitRetryOptions, \"onRateLimit\">;\n readonly onTerminalReportError?: (error: EnlittError) => void;\n}\n\n/**\n * Builds the internal client from a factory call's resolved options.\n *\n * Resolves the business authorization header eagerly (through\n * `resolveBusinessAuthorizationHeader()`, the only path to that secret) so a\n * missing or unusable key fails at construction, before any network call and\n * before a provider is ever at risk of running unaccounted. Folds\n * `rateLimit` over the SDK's defaults exactly once here, so no per-request\n * code has to treat any field but `onRateLimit` as possibly absent.\n */\nexport function createInternalClient(options: EnlittOptions): InternalEnlittClient {\n // First, before secret resolution, so a bundling mistake never reaches a key.\n assertServerRuntime();\n\n const baseUrl = resolveBaseUrl(options.baseUrl);\n const businessAuthorization = resolveBusinessAuthorizationHeader(\n options.secretKey !== undefined ? { secretKey: options.secretKey } : {}\n );\n\n const rateLimitOptions = options.rateLimit;\n const maxAttempts = rateLimitOptions?.maxAttempts ?? DEFAULT_RATE_LIMIT_MAX_ATTEMPTS;\n if (!Number.isSafeInteger(maxAttempts) || maxAttempts < 1) {\n throw new EnlittConfigurationError(\"rateLimit.maxAttempts must be an integer of at least 1.\");\n }\n const rateLimit: InternalEnlittClient[\"rateLimit\"] = {\n maxAttempts,\n maxTotalWaitMs: rateLimitOptions?.maxTotalWaitMs ?? DEFAULT_RATE_LIMIT_MAX_TOTAL_WAIT_MS,\n ...(rateLimitOptions?.onRateLimit !== undefined ? { onRateLimit: rateLimitOptions.onRateLimit } : {})\n };\n\n const explicitSession = options.session;\n\n return {\n baseUrl,\n businessAuthorization,\n sdkVersion: SDK_VERSION,\n resolveSession: (): EnlittSession => {\n if (explicitSession !== undefined) {\n return explicitSession;\n }\n const session = getEnlittSession();\n if (session === null) {\n throw normalizeEnlittModelError(\n {\n kind: \"http_error\",\n status: 401,\n body: loginRequiredBody(),\n headers: {}\n },\n false\n );\n }\n return session;\n },\n rateLimit,\n ...(options.onTerminalReportError !== undefined\n ? { onTerminalReportError: options.onTerminalReportError }\n : {})\n };\n}\n\n/**\n * The deployed Enlitt origin compiled into the package, used when neither\n * `EnlittOptions.baseUrl` nor `ENLITT_BASE_URL` names one. Matches the default\n * `enlittOrigin` `server/callback.ts` falls back to; the two are the same\n * deployed origin and must not drift apart.\n */\nconst DEFAULT_ENLITT_ORIGIN = \"https://api.enlitt.com\";\n\n/** The environment variable a business may set instead of passing `baseUrl` explicitly. */\nconst BASE_URL_ENV_KEY = \"ENLITT_BASE_URL\";\n\n/**\n * Browser execution fails with `EnlittConfigurationError`. The check is\n * `typeof window !== \"undefined\" && typeof document !== \"undefined\"`,\n * matching `server/secrets.ts`'s own heuristic exactly.\n */\nfunction assertServerRuntime(): void {\n if (typeof window !== \"undefined\" && typeof document !== \"undefined\") {\n throw new EnlittConfigurationError(\n \"enlitt() was called in a browser environment. It is server-only; ship @enlitt/sdk/browser to consumers instead.\"\n );\n }\n}\n\n/**\n * Resolves `baseUrl` from the option, then `ENLITT_BASE_URL`, then the\n * deployed default, and validates the result once through the identical HTTPS\n * rule `requestEnlitt()` applies per request (`assertHttps()`). A malformed\n * URL is folded into the same `EnlittConfigurationError` rather than leaking a\n * raw `TypeError`.\n */\nfunction resolveBaseUrl(optionBaseUrl: string | undefined): string {\n const candidate = optionBaseUrl ?? readBaseUrlFromEnv() ?? DEFAULT_ENLITT_ORIGIN;\n try {\n assertHttps(candidate);\n } catch (thrown) {\n if (thrown instanceof EnlittConfigurationError) {\n throw thrown;\n }\n throw new EnlittConfigurationError(`Enlitt base URL is not a valid URL: ${String(candidate)}.`);\n }\n return candidate;\n}\n\n/** Mirrors `server/secrets.ts`'s guarded read of a `process.env` fallback, which no Workers-style runtime provides. */\nfunction readBaseUrlFromEnv(): string | undefined {\n const runtime = globalThis as { process?: { env?: Record<string, string | undefined> } };\n return runtime.process?.env?.[BASE_URL_ENV_KEY];\n}\n\n/**\n * Synthesizes the one error body `resolveSession()` needs to raise\n * `EnlittLoginRequiredError` through `normalizeEnlittModelError()` rather\n * than constructing a second error path that could disagree with the one\n * every HTTP refusal already goes through.\n */\nfunction loginRequiredBody(): unknown {\n return {\n error: {\n message: \"No Enlitt session is available for this request. Send the user through Enlitt login.\",\n type: \"authentication_error\",\n param: null,\n code: ENLITT_ERROR_CODE.personal_login_required\n }\n };\n}\n\n/** One request this module knows how to issue. */\nexport interface EnlittRequestInit {\n readonly path: string;\n /** `POST` unless a read endpoint (`GET /v1/enlitt/usage`) says otherwise. */\n readonly method?: \"POST\" | \"GET\";\n /** Ignored for `GET`, which has no body. */\n readonly body?: unknown;\n /**\n * Sent as `Idempotency-Key` (and, for a terminal report, equals the body's\n * own `report_id`). Required for `POST`; a `GET` sends no `Idempotency-Key`,\n * because `PROTOCOLS.md` forbids one on a route that does not deduplicate.\n */\n readonly callId?: string;\n readonly accept: \"application/json\" | \"text/event-stream\";\n readonly signal?: AbortSignal;\n}\n\n/**\n * Issues one `POST` to `client.baseUrl + init.path` carrying every header the\n * protocol requires and no other identity-bearing header, and returns the\n * successful `Response` unread so a caller that needs a stream can consume\n * it incrementally.\n *\n * This is the only function in the package that calls `fetch()` against\n * Enlitt. Every safety property the spec requires — HTTPS, no redirects,\n * bounded response size, normalization of every failure, and the\n * `rate_limit_exceeded` wait — lives here so no call site can accidentally\n * skip one.\n */\nexport async function requestEnlitt(client: InternalEnlittClient, init: EnlittRequestInit): Promise<Response> {\n assertHttps(client.baseUrl);\n\n const url = new URL(init.path, client.baseUrl).toString();\n const session = client.resolveSession();\n\n // The exhaustive header set. `Enlitt-Version` names the API version this\n // build was written against; it is information for the server only, and the\n // SDK never reads a version header back (forward compatibility comes from\n // tolerant parsing, not negotiation).\n const headers: Record<string, string> = {\n Authorization: client.businessAuthorization,\n \"X-Enlitt-User-Authorization\": `Bearer ${session.token}`,\n Accept: init.accept,\n \"X-Request-Id\": generateRequestId(),\n [ENLITT_VERSION_HEADER]: ENLITT_API_VERSION,\n \"X-Enlitt-SDK-Version\": client.sdkVersion\n };\n if (init.method !== \"GET\") {\n if (init.callId === undefined) {\n throw new EnlittConfigurationError(\"An Enlitt POST request requires a call ID for its Idempotency-Key.\");\n }\n headers[\"Idempotency-Key\"] = init.callId;\n headers[\"Content-Type\"] = \"application/json\";\n }\n\n const waitStartedAtMs = Date.now();\n\n for (let attempt = 1; ; attempt++) {\n const response = await sendOnce(url, headers, init);\n\n if (response.ok) {\n assertBoundedResponse(response);\n return response;\n }\n\n const error = await normalizeResponse(response);\n\n if (error.code !== ENLITT_ERROR_CODE.rate_limit_exceeded) {\n throw error;\n }\n\n const canRetry =\n attempt < client.rateLimit.maxAttempts &&\n Date.now() - waitStartedAtMs < client.rateLimit.maxTotalWaitMs;\n if (!canRetry) {\n throw error;\n }\n\n const floorMs = error.retryAfterMs ?? DEFAULT_RATE_LIMIT_FLOOR_MS;\n const delayMs = floorMs + Math.random() * (floorMs / 2);\n client.rateLimit.onRateLimit?.(attempt, delayMs);\n await sleep(delayMs, init.signal);\n }\n}\n\n/**\n * Retries a premium terminal report a bounded number of times on a\n * transient failure, resending the identical `init` — the same body (and so\n * the same `report_id`) and the same `Idempotency-Key` — on every attempt,\n * which is what makes the retry safe: Enlitt's own idempotency on that key\n * turns a duplicate send into a replay rather than a second report.\n *\n * Only a failure with no distinct business action of its own is treated as\n * transient: a transport failure that never produced a response, or one of\n * the three retryable server-side wire codes (`server_error`,\n * `provider_error`, `no_capable_route`). A refusal, a conflict, or an\n * exhausted `rate_limit_exceeded` wait (already retried once, inside\n * `requestEnlitt()`) is never retried again here — retrying a refusal a\n * second time under a different name is exactly what the spec forbids.\n *\n * Exhausting the bound reports the last error to `client.onTerminalReportError`\n * and rethrows it, rather than swallowing it: the hook exists because the\n * provider call this report describes has already finished and there is no\n * result left to withhold from a caller, not because the failure stops\n * mattering.\n */\nexport async function reportEnlittPremiumTerminal(\n client: InternalEnlittClient,\n init: EnlittRequestInit\n): Promise<Response> {\n for (let attempt = 1; ; attempt++) {\n try {\n return await requestEnlitt(client, init);\n } catch (thrown) {\n const error = thrown instanceof EnlittError ? thrown : normalizeEnlittModelError(thrown, false);\n const canRetry = isTransientTerminalReportFailure(error) && attempt < TERMINAL_REPORT_MAX_ATTEMPTS;\n if (!canRetry) {\n client.onTerminalReportError?.(error);\n throw error;\n }\n await sleep(TERMINAL_REPORT_RETRY_DELAY_MS, init.signal);\n }\n }\n}\n\n/**\n * Transient means \"a delay may fix it\": a transport failure that never\n * produced a response, or a retryable 5xx (`server_error`, `provider_error`,\n * or a newer 5xx code the classifier marked retryable). Anything else,\n * including an exhausted rate-limit wait, is not retried again here.\n */\nfunction isTransientTerminalReportFailure(error: EnlittError): boolean {\n if (error.code === \"transport_failed\") {\n return true;\n }\n return error.retryable && error.code !== ENLITT_ERROR_CODE.rate_limit_exceeded;\n}\n\n/**\n * Sends exactly one HTTP request and normalizes a network-level failure into\n * the shapes `normalizeEnlittModelError()` recognizes, so `requestEnlitt()`\n * has only one kind of thing to handle beyond a `Response`: a thrown\n * `EnlittError`.\n *\n * Redirects are never followed: no legitimate Enlitt endpoint redirects,\n * and following one would either resend a bearer credential for two\n * principals to another origin or silently retarget a financial request.\n * `redirect: \"manual\"` hands the redirect back unfollowed and\n * `isRedirectResponse()` turns it into `transport_failed`. (`redirect:\n * \"error\"` would be the natural choice, but the Cloudflare Workers runtime\n * rejects it with a `TypeError` before sending, so every call from a Worker\n * failed.)\n */\nasync function sendOnce(url: string, headers: Record<string, string>, init: EnlittRequestInit): Promise<Response> {\n let response: Response;\n try {\n response = await fetch(url, {\n method: init.method ?? \"POST\",\n headers,\n ...(init.method === \"GET\" ? {} : { body: JSON.stringify(init.body) }),\n redirect: \"manual\",\n ...(init.signal !== undefined ? { signal: init.signal } : {})\n });\n } catch (thrown) {\n const message = describeThrown(thrown);\n if (init.signal?.aborted === true) {\n throw normalizeEnlittModelError(\n { kind: \"request_canceled\", ...(message !== undefined ? { message } : {}) } satisfies EnlittRequestCanceled,\n false\n );\n }\n throw normalizeEnlittModelError(\n { kind: \"transport_failed\", ...(message !== undefined ? { message } : {}) } satisfies EnlittTransportFailure,\n false\n );\n }\n if (isRedirectResponse(response)) throw redirectRefused(response);\n return response;\n}\n\n/** The one message for a refused redirect (`specs/SDK-side routing.md`). */\nconst REDIRECT_REFUSED_MESSAGE = \"Enlitt answered with a redirect, which the SDK never follows.\";\n\n/**\n * True for an unfollowed redirect under `redirect: \"manual\"`: a `3xx` status\n * (server runtimes such as Workers and Node) or an `opaqueredirect` response\n * with status `0` (browsers, which hide the redirect's details).\n */\nexport function isRedirectResponse(response: Response): boolean {\n return response.type === \"opaqueredirect\" || (response.status >= 300 && response.status < 400);\n}\n\n/**\n * The `transport_failed` error for a refused redirect. The body is cancelled\n * unread so the connection is released; nothing from it is used.\n */\nexport function redirectRefused(response: Response): EnlittError {\n void response.body?.cancel().catch(() => undefined);\n return normalizeEnlittModelError(\n { kind: \"transport_failed\", message: REDIRECT_REFUSED_MESSAGE } satisfies EnlittTransportFailure,\n false\n );\n}\n\n/**\n * Bounds response header and body size, then parses the OpenAI-shaped error\n * body and hands it to `normalizeEnlittModelError()`. A response this\n * function cannot safely read or parse normalizes to `malformed_response`\n * rather than exposing raw bytes or a parser exception to a caller.\n */\nasync function normalizeResponse(response: Response): Promise<EnlittError> {\n if (!isBoundedHeaderSet(response.headers)) {\n return normalizeEnlittModelError(\n { kind: \"malformed_response\", message: \"Response headers exceeded the bounded size.\" } satisfies EnlittMalformedResponse,\n false\n );\n }\n\n const text = await readBoundedBody(response);\n if (text === undefined) {\n return normalizeEnlittModelError(\n { kind: \"malformed_response\", message: \"Response body exceeded the bounded size.\" } satisfies EnlittMalformedResponse,\n false\n );\n }\n\n let body: unknown;\n try {\n body = JSON.parse(text) as unknown;\n } catch {\n return normalizeEnlittModelError(\n { kind: \"malformed_response\", message: \"Response body was not valid JSON.\" } satisfies EnlittMalformedResponse,\n false\n );\n }\n\n // The body is handed to the normalizer as-is: the protocol's classifier\n // decides whether it is an Enlitt error envelope, so no second structural\n // check lives here.\n return normalizeEnlittModelError(\n {\n kind: \"http_error\",\n status: response.status,\n body,\n headers: {\n \"retry-after\": response.headers.get(\"retry-after\") ?? undefined,\n \"x-request-id\": response.headers.get(\"x-request-id\") ?? undefined\n }\n } satisfies EnlittHttpErrorResponse,\n false\n );\n}\n\n/**\n * Enforces `MAX_RESPONSE_HEADER_BYTES` over a response's own header set,\n * summing each name and value once. Cheap and approximate on purpose: this\n * exists to stop a misbehaving endpoint from making this module hold an\n * unbounded amount of attacker-controlled header data, not to bill bytes\n * exactly.\n */\nfunction isBoundedHeaderSet(headers: Headers): boolean {\n let total = 0;\n for (const [name, value] of headers.entries()) {\n total += name.length + value.length;\n if (total > MAX_RESPONSE_HEADER_BYTES) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Reads a response body up to `MAX_RESPONSE_BODY_BYTES`, returning\n * `undefined` rather than a truncated string when the bound is exceeded —\n * truncating and parsing a partial body risks succeeding on a document that\n * is not the one Enlitt actually sent.\n */\nasync function readBoundedBody(response: Response): Promise<string | undefined> {\n const contentLength = response.headers.get(\"content-length\");\n if (contentLength !== null && Number(contentLength) > MAX_RESPONSE_BODY_BYTES) {\n return undefined;\n }\n\n const body = response.body;\n if (body === null) {\n return \"\";\n }\n\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n total += value.byteLength;\n if (total > MAX_RESPONSE_BODY_BYTES) {\n await reader.cancel();\n return undefined;\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n return new TextDecoder().decode(concatChunks(chunks, total));\n}\n\n/**\n * Reads a successful response's body as JSON, bounded by the same body-size\n * limit every other read in this file uses. An oversized body or one that is\n * not valid JSON is a `malformed_response` `EnlittError`, never a raw parser\n * exception. Every JSON-bodied Enlitt response (begin, terminal report, usage,\n * non-streaming standard response) is read through here, so no caller buffers\n * an unbounded body or parses JSON on its own.\n */\nexport async function readEnlittJson(response: Response): Promise<unknown> {\n const text = await readBoundedBody(response);\n if (text === undefined) {\n throw normalizeEnlittModelError(\n { kind: \"malformed_response\", message: \"Response body exceeded the bounded size.\" } satisfies EnlittMalformedResponse,\n false\n );\n }\n try {\n return JSON.parse(text) as unknown;\n } catch {\n throw normalizeEnlittModelError(\n { kind: \"malformed_response\", message: \"Response body was not valid JSON.\" } satisfies EnlittMalformedResponse,\n false\n );\n }\n}\n\nfunction concatChunks(chunks: readonly Uint8Array[], total: number): Uint8Array {\n const merged = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n merged.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return merged;\n}\n\n/**\n * A successful response is bounded the same way a failing one is — checked\n * eagerly here so an oversized `200` fails fast rather than letting a caller\n * downstream (the standard or premium model) buffer it first.\n */\nfunction assertBoundedResponse(response: Response): void {\n if (!isBoundedHeaderSet(response.headers)) {\n throw normalizeEnlittModelError(\n { kind: \"malformed_response\", message: \"Response headers exceeded the bounded size.\" } satisfies EnlittMalformedResponse,\n false\n );\n }\n const contentLength = response.headers.get(\"content-length\");\n if (contentLength !== null && Number(contentLength) > MAX_RESPONSE_BODY_BYTES) {\n throw normalizeEnlittModelError(\n { kind: \"malformed_response\", message: \"Response body exceeded the bounded size.\" } satisfies EnlittMalformedResponse,\n false\n );\n }\n}\n\n/**\n * HTTPS is required outside local development. `http:` is accepted only for\n * the three hosts a developer's own machine can present as, and there is no\n * environment flag that relaxes this — a business misconfiguring its own\n * deployed base URL must fail loudly rather than send its business and\n * personal credentials in the clear.\n *\n * Exported (in addition to being used per-request by `requestEnlitt()`) so\n * `language-model.ts` can run the identical check once, at `enlitt()`\n * construction, against the resolved `baseUrl` before any request is made —\n * the spec requires base URL validation to happen at construction, not per\n * call, and duplicating this rule there would let the two copies drift.\n */\nexport function assertHttps(baseUrl: string): void {\n const parsed = new URL(baseUrl);\n if (parsed.protocol === \"https:\") {\n return;\n }\n if (parsed.protocol === \"http:\" && LOCAL_HTTP_HOSTS.has(parsed.hostname)) {\n return;\n }\n throw new EnlittConfigurationError(\n `Enlitt base URL must use https: outside local development (got ${parsed.protocol} for host ` +\n `${parsed.hostname}). There is no environment flag that relaxes this.`\n );\n}\n\n/** A bounded, non-authoritative caller trace ID. `crypto.randomUUID()` is 36 characters, well under any reasonable bound. */\nfunction generateRequestId(): string {\n return crypto.randomUUID();\n}\n\n/** Extracts a safe, bounded description from a caught value without ever including request content. */\nfunction describeThrown(thrown: unknown): string | undefined {\n if (thrown instanceof Error) {\n return thrown.message.slice(0, 500);\n }\n return undefined;\n}\n\n/**\n * Sleeps for `delayMs`, or rejects immediately with the signal's abort\n * reason if `signal` is aborted before the sleep completes. Used by both\n * internal retries, so a caller-initiated cancellation ends a rate-limit\n * wait or a terminal-report retry exactly as promptly as it ends an\n * in-flight request.\n */\nfunction sleep(delayMs: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted === true) {\n // The caller's abort reason must escape unchanged, not wrapped in an\n // Error this module invents, so a caller can compare it against the\n // exact value it passed to `AbortController.abort()`.\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n return Promise.reject(signal.reason as unknown);\n }\n return new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, delayMs);\n function onAbort(): void {\n clearTimeout(timer);\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- see above.\n reject(signal?.reason as unknown);\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n","/**\n * The one premium billing lifecycle, with no framework dependency.\n *\n * `specs/SDK-side routing.md` gives this file the framework-agnostic core of\n * premium mode: a business runs a model call it pays for, and Enlitt only\n * accounts for it. The call is bracketed by a content-free begin (a maximum\n * charge in NANOUSD, declared before the provider runs) and exactly one\n * terminal report (a status and the actual NANOUSD charge, sent after it).\n *\n * `runPremiumCharge()` is the single implementation of that lifecycle: one\n * begin, one status rule, one charge rule, one report path. The public\n * `withPremiumCharge()` in this file and the Vercel adapter in\n * `vercel/premium-language-model.ts` are both thin layers over it, so moving a\n * call between the two changes how the charge is computed and nothing about how\n * it is settled.\n *\n * This file imports nothing from the Vercel AI SDK, and it never sends prompts,\n * messages, outputs, files, tools, provider options, provider keys, raw errors,\n * or content hashes to Enlitt: every body it builds is assembled field by field\n * from bounded named inputs, never by forwarding a caller-supplied object.\n *\n * Every NANOUSD amount is a canonical base-10 integer string and is compared\n * only as a `bigint`; none is ever converted to `number`, rounded, or displayed.\n */\n\nimport {\n CanonicalIntegerError,\n IDEMPOTENCY_KEY_MAX_LENGTH,\n IDEMPOTENCY_KEY_MIN_LENGTH,\n IdempotencyKeyError,\n assertIdempotencyKey,\n parseCanonicalInteger,\n validateBeginPremiumOperationRequest,\n validateBeginPremiumOperationResponse,\n validateCallerMetadata,\n validateReportPremiumTerminalRequest,\n validateReportPremiumTerminalResponse\n} from \"@enlitt/protocol\";\nimport { EnlittConfigurationError, EnlittError, normalizeEnlittModelError } from \"./errors.js\";\nimport {\n createInternalClient,\n readEnlittJson,\n reportEnlittPremiumTerminal,\n requestEnlitt,\n type EnlittOptions,\n type InternalEnlittClient\n} from \"./transport.js\";\n\n// --- Public types ----------------------------------------------------------\n\n/**\n * Records the NANOUSD amount to report for the call. Callable any number of\n * times; the last call wins. Throws `EnlittConfigurationError` synchronously\n * for an amount that is not a canonical nonnegative integer string, and for a\n * call made after the report has been sent.\n */\nexport type PremiumChargeFunction = (amountNanoUsd: string) => void;\n\n/**\n * The optional content-free facts a business may attach to the terminal\n * report. None is required and none has a financial effect.\n */\nexport interface PremiumTerminalFacts {\n readonly usage?: {\n inputTokens?: number;\n outputTokens?: number;\n cachedInputTokens?: number;\n reasoningTokens?: number;\n };\n readonly finishReason?: string;\n readonly providerResponseId?: string;\n readonly delivery?: { outputStarted: boolean; outputCompleted: boolean };\n readonly timing?: { startedAt: string; endedAt: string };\n readonly errorCategory?: \"provider\" | \"timeout\" | \"network\" | \"invalid_request\" | \"canceled\" | \"unknown\";\n}\n\n/** The admitted operation, as handed to a `withPremiumCharge()` callback. */\nexport interface PremiumChargeHandle {\n readonly operationId: string;\n /** The most the report can charge: the declared maximum, lowered by the server to this user's per-call limit. */\n readonly effectiveMaxChargeNanoUsd: string;\n readonly terminalDeadline: string;\n /** Records safe facts for the terminal report; the last call wins. */\n describe(facts: PremiumTerminalFacts): void;\n}\n\n/** What one premium operation declares at begin. */\nexport interface PremiumChargeRequest {\n readonly maxCharge: string;\n readonly provider: { id: string; model: string };\n readonly callId?: string;\n readonly reportingDeadlineMs?: number;\n readonly metadata?: Record<string, string>;\n readonly signal?: AbortSignal;\n}\n\n/**\n * The admitted operation as returned by Enlitt, carried opaquely to the\n * terminal report. The response's equal `reserved_nano_usd` is validated and\n * otherwise not exposed; no credit or pricing-version field exists on the wire.\n */\nexport interface PremiumOperation {\n readonly operationId: string;\n readonly effectiveMaxChargeNanoUsd: string;\n readonly terminalDeadline: string;\n}\n\n/** One terminal report in the TypeScript shape this module works in. */\nexport interface PremiumTerminalReport extends PremiumTerminalFacts {\n readonly reportId: string;\n readonly status: \"completed\" | \"failed\" | \"canceled\";\n readonly chargeNanoUsd: string;\n}\n\n/** Options for {@link withPremiumCharge}: the shared construction options plus one premium call's declaration. */\nexport interface WithPremiumChargeOptions extends EnlittOptions {\n /** NANOUSD, a canonical nonnegative integer string. */\n maxCharge: string;\n /** Bounded labels, as on the premium begin request. */\n provider: { id: string; model: string };\n /** The call ID; default a fresh random one. */\n idempotencyKey?: string;\n reportingDeadlineMs?: number;\n metadata?: Record<string, string>;\n signal?: AbortSignal;\n}\n\n// --- Shared option validation ----------------------------------------------\n//\n// `withPremiumCharge()` and the Vercel `readEnlittCallOptions()` apply the same\n// rules, so the rules live here once. Every failure is an\n// `EnlittConfigurationError` raised before any Enlitt or provider request.\n\n/** Visible ASCII, matching the protocol's own `Idempotency-Key` character rule. */\nconst VISIBLE_ASCII = /^[\\x21-\\x7e]+$/;\n\n/**\n * A supplied idempotency key is a base, not the call identity: the Vercel\n * adapter appends `.<prompt item count>`. The floor is the protocol's own\n * 16-character floor, imported rather than restated, so every derived ID\n * satisfies the wire bound by construction; the ceiling stays well under 255\n * so the appended suffix can never push a derived ID over it.\n */\nexport const IDEMPOTENCY_KEY_OPTION_MIN_LENGTH = IDEMPOTENCY_KEY_MIN_LENGTH;\nexport const IDEMPOTENCY_KEY_OPTION_MAX_LENGTH = 200;\n\n/**\n * Validates a NANOUSD amount: a canonical nonnegative base-10 integer string\n * with no sign, fraction, exponent, whitespace, or noncanonical leading zero.\n * `\"0\"` is valid. Parsed as `bigint` (so values beyond the safe-integer range\n * keep full precision) and returned as the exact string the caller supplied.\n */\nexport function assertNanoUsd(value: unknown, label: string): string {\n try {\n parseCanonicalInteger(value, label);\n } catch (thrown) {\n if (thrown instanceof CanonicalIntegerError) {\n throw new EnlittConfigurationError(thrown.message);\n }\n throw thrown;\n }\n return value as string;\n}\n\n/** Validates a business-supplied idempotency key base (16-200 visible ASCII characters). */\nexport function assertIdempotencyKeyBase(value: unknown, label: string): string {\n if (\n typeof value !== \"string\" ||\n value.length < IDEMPOTENCY_KEY_OPTION_MIN_LENGTH ||\n value.length > IDEMPOTENCY_KEY_OPTION_MAX_LENGTH ||\n !VISIBLE_ASCII.test(value)\n ) {\n throw new EnlittConfigurationError(\n `${label} must be ${IDEMPOTENCY_KEY_OPTION_MIN_LENGTH}-${IDEMPOTENCY_KEY_OPTION_MAX_LENGTH} visible ASCII characters.`\n );\n }\n return value;\n}\n\n/**\n * Validates a requested reporting deadline as a positive safe integer. The\n * deployed maximum is server policy and is not knowable locally, so no local\n * maximum is applied; the server bounds it and its returned deadline is\n * authoritative.\n */\nexport function assertReportingDeadlineMs(value: unknown, label: string): number {\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value <= 0) {\n throw new EnlittConfigurationError(`${label} must be a positive safe integer.`);\n }\n return value;\n}\n\n/**\n * Validates caller metadata with the protocol's own `Record<string, string>`\n * rule (at most 16 entries, bounded keys and values, no `enlitt_` prefix): one\n * rule and one validator rather than a per-mode type.\n */\nexport function assertCallerMetadata(value: unknown, label: string): Record<string, string> {\n const validated = validateCallerMetadata(value, label);\n if (!validated.ok) {\n throw new EnlittConfigurationError(`${validated.error.message} (${validated.error.param})`);\n }\n return validated.value;\n}\n\n/** Validates a call ID against the protocol's 16-255 visible-ASCII `Idempotency-Key` bound. */\nexport function assertCallId(callId: string): string {\n try {\n return assertIdempotencyKey(callId);\n } catch (thrown) {\n if (thrown instanceof IdempotencyKeyError) {\n throw new EnlittConfigurationError(\n `The call ID \"${callId}\" is not a valid Idempotency-Key (must be ` +\n `${IDEMPOTENCY_KEY_MIN_LENGTH}-${IDEMPOTENCY_KEY_MAX_LENGTH} visible ASCII characters).`\n );\n }\n throw thrown;\n }\n}\n\n/** A freshly generated, unique-per-operation random value of at least 16 visible ASCII characters (a UUID is 36). */\nexport function generateRandomCallId(): string {\n return crypto.randomUUID();\n}\n\n// --- Wire paths ------------------------------------------------------------\n\n/** The one relative path an operation is begun at, per `specs/PROTOCOLS.md` \"Begin premium operation\". */\nconst BEGIN_PREMIUM_OPERATION_PATH = \"/v1/enlitt/operations\";\n\n/** The one relative path a terminal outcome is reported to, per \"Report premium terminal state\". */\nfunction terminalReportPath(operationId: string): string {\n return `/v1/enlitt/operations/${encodeURIComponent(operationId)}/terminal`;\n}\n\n// --- Begin -----------------------------------------------------------------\n\n/**\n * Calls **Begin premium operation** before the provider ever runs.\n *\n * Sends `mode: \"premium\"`, `max_charge_nano_usd` exactly as the business\n * declared it, `reporting_deadline_ms` when supplied, the bounded `provider`\n * labels, and `metadata`. The call ID travels as the request's\n * `Idempotency-Key`, never as a body field: the protocol lists no such field.\n * Enlitt performs the conversion to credit units; this function sends no credit\n * figure and reads no balance figure.\n *\n * The body is validated with the protocol's strict request validator before it\n * is sent (strict out). The response is parsed in tolerant mode (tolerant in):\n * an extra field or an unknown `billing` value still admits the operation. The\n * returned `effective_max_charge_nano_usd` and `terminal_deadline` are\n * authoritative regardless of what was requested.\n *\n * A refusal, a business authentication failure, or a transport failure\n * surfaces as the corresponding typed error with `providerInvoked: false`;\n * there is no path from a refusal to a provider invocation, including a\n * `rate_limit_exceeded` whose transport wait was exhausted (defensive: the\n * server never sends it on the premium path).\n */\nexport async function beginPremiumOperation(\n client: InternalEnlittClient,\n request: PremiumChargeRequest,\n callId: string\n): Promise<PremiumOperation> {\n const body: Record<string, unknown> = {\n mode: \"premium\",\n max_charge_nano_usd: request.maxCharge,\n provider: { id: request.provider.id, model: request.provider.model }\n };\n if (request.reportingDeadlineMs !== undefined) {\n body.reporting_deadline_ms = request.reportingDeadlineMs;\n }\n if (request.metadata !== undefined) {\n body.metadata = request.metadata;\n }\n\n const validated = validateBeginPremiumOperationRequest(body);\n if (!validated.ok) {\n throw new EnlittConfigurationError(\n `The premium operation request is invalid: ${validated.error.message} (${validated.error.param}).`\n );\n }\n\n const response = await requestEnlitt(client, {\n path: BEGIN_PREMIUM_OPERATION_PATH,\n body: validated.value,\n callId,\n accept: \"application/json\",\n ...(request.signal !== undefined ? { signal: request.signal } : {})\n });\n\n const parsed = validateBeginPremiumOperationResponse(await readEnlittJson(response), { mode: \"tolerant\" });\n if (!parsed.ok) {\n throw new EnlittError(\n \"malformed_response\",\n `Enlitt's premium operation response could not be validated: ${parsed.error.message} (${parsed.error.param}).`\n );\n }\n\n return {\n operationId: parsed.value.operation_id,\n effectiveMaxChargeNanoUsd: parsed.value.effective_max_charge_nano_usd,\n terminalDeadline: parsed.value.terminal_deadline\n };\n}\n\n// --- Terminal report -------------------------------------------------------\n\n/**\n * Sends one idempotent content-free terminal report to **Report premium\n * terminal state**, through the transport's bounded transient retry, which\n * resends the identical body and `Idempotency-Key` so a retry is a replay and\n * never a second report. `report.reportId` is generated once per operation.\n *\n * Never propagates a delivery failure into its caller. When the transport's\n * retries are exhausted, or Enlitt answers `409`, the typed error has already\n * been handed to `client.onTerminalReportError` (by the transport) and is\n * dropped here: a delivered provider output is a fact the business already\n * paid for, and turning an unrelated reporting failure into a thrown error\n * would make it discard output it already has. An undelivered report instead\n * lets the operation expire at its deadline, charging nothing.\n *\n * The response is parsed tolerantly. A report whose `status` reads as `\"other\"`\n * is still a delivered report: it is neither retried nor passed to\n * `onTerminalReportError`.\n */\nexport async function reportPremiumTerminalState(\n client: InternalEnlittClient,\n operation: PremiumOperation,\n report: PremiumTerminalReport\n): Promise<void> {\n const body: Record<string, unknown> = {\n report_id: report.reportId,\n status: report.status,\n charge_nano_usd: report.chargeNanoUsd\n };\n\n if (report.usage !== undefined) {\n const usage: Record<string, number> = {};\n if (report.usage.inputTokens !== undefined) usage.input_tokens = report.usage.inputTokens;\n if (report.usage.outputTokens !== undefined) usage.output_tokens = report.usage.outputTokens;\n if (report.usage.cachedInputTokens !== undefined) usage.cached_input_tokens = report.usage.cachedInputTokens;\n if (report.usage.reasoningTokens !== undefined) usage.reasoning_tokens = report.usage.reasoningTokens;\n body.usage = usage;\n }\n if (report.finishReason !== undefined) body.finish_reason = report.finishReason;\n if (report.providerResponseId !== undefined) body.provider_response_id = report.providerResponseId;\n if (report.delivery !== undefined) {\n body.delivery = { output_started: report.delivery.outputStarted, output_completed: report.delivery.outputCompleted };\n }\n if (report.timing !== undefined) {\n body.timing = { started_at: report.timing.startedAt, ended_at: report.timing.endedAt };\n }\n if (report.errorCategory !== undefined) body.error_category = report.errorCategory;\n\n // Strict out. A report the SDK built wrongly is observed like any other\n // undeliverable report: the operation will simply expire, charging nothing.\n const validated = validateReportPremiumTerminalRequest(body);\n if (!validated.ok) {\n client.onTerminalReportError?.(\n new EnlittConfigurationError(\n `The premium terminal report is invalid and was not sent: ${validated.error.message} (${validated.error.param}).`\n )\n );\n return;\n }\n\n try {\n const response = await reportEnlittPremiumTerminal(client, {\n path: terminalReportPath(operation.operationId),\n body: validated.value,\n callId: report.reportId,\n accept: \"application/json\"\n });\n const parsed = validateReportPremiumTerminalResponse(await readEnlittJson(response), { mode: \"tolerant\" });\n if (!parsed.ok) {\n client.onTerminalReportError?.(\n new EnlittError(\n \"malformed_response\",\n `Enlitt's terminal report response could not be validated: ${parsed.error.message} (${parsed.error.param}).`\n )\n );\n }\n } catch (thrown) {\n // `reportEnlittPremiumTerminal()` already delivered a transport or refusal\n // failure to `client.onTerminalReportError` before rethrowing it; a body\n // that could not be read is reported here. Neither reaches the caller.\n if (thrown instanceof EnlittError && thrown.code === \"malformed_response\") {\n client.onTerminalReportError?.(thrown);\n } else if (!(thrown instanceof EnlittError)) {\n client.onTerminalReportError?.(normalizeEnlittModelError(thrown, false));\n }\n }\n}\n\n// --- The lifecycle ---------------------------------------------------------\n\n/**\n * Whether `run` rejected because the call was canceled: the request's own\n * signal is aborted, or the error is an `AbortError`.\n */\nexport function isCancellation(thrown: unknown, signal: AbortSignal | undefined): boolean {\n if (signal?.aborted === true) {\n return true;\n }\n return typeof thrown === \"object\" && thrown !== null && (thrown as { name?: unknown }).name === \"AbortError\";\n}\n\n/**\n * Wraps exactly one model call: begins one operation, runs `run` only after\n * admission, and sends exactly one terminal report.\n *\n * - **Begin.** `request.callId` when supplied (validated against the protocol's\n * `Idempotency-Key` bounds), otherwise a fresh random ID. A refusal,\n * authentication failure, or transport failure rejects with the typed error\n * and `run` is never called.\n * - **Run.** `run` receives a `charge` function and the admitted operation.\n * `charge(amount)` records the amount to report; the last call wins.\n * - **Status.** `run` resolving is `completed`. `run` rejecting while\n * `request.signal` is aborted, or with an `AbortError`, is `canceled`. Any\n * other rejection is `failed`. The status is decided by how `run` settles,\n * never by the caller naming one, so a caller cannot report a failure as a\n * charged cancellation.\n * - **Charge.** `\"0\"` for `failed`, whatever `charge()` received (a failed call\n * is always free). For `completed` and `canceled`, the last amount passed to\n * `charge()`, or `\"0\"` if never called, lowered to the effective maximum\n * without an error.\n * - **Report.** One `PremiumTerminalReport` with a `reportId` generated once,\n * awaited before settling so a serverless process cannot end between the\n * call and its report.\n * - **Result.** `run`'s value, or `run`'s own error unchanged.\n */\nexport async function runPremiumCharge<T>(\n client: InternalEnlittClient,\n request: PremiumChargeRequest,\n run: (charge: PremiumChargeFunction, operation: PremiumChargeHandle) => Promise<T>\n): Promise<T> {\n const callId = assertCallId(request.callId ?? generateRandomCallId());\n const operation = await beginPremiumOperation(client, request, callId);\n\n const startedAt = new Date();\n let recordedChargeNanoUsd = \"0\";\n let facts: PremiumTerminalFacts = {};\n let reportSent = false;\n\n const charge: PremiumChargeFunction = (amountNanoUsd) => {\n if (reportSent) {\n throw new EnlittConfigurationError(\"charge() was called after the terminal report was sent.\");\n }\n recordedChargeNanoUsd = assertNanoUsd(amountNanoUsd, \"charge amount\");\n };\n\n const handle: PremiumChargeHandle = {\n operationId: operation.operationId,\n effectiveMaxChargeNanoUsd: operation.effectiveMaxChargeNanoUsd,\n terminalDeadline: operation.terminalDeadline,\n describe: (next) => {\n facts = next;\n }\n };\n\n /** Builds and sends the one report for the status `run` settled with. */\n const report = async (status: PremiumTerminalReport[\"status\"]): Promise<void> => {\n reportSent = true;\n const effective = BigInt(operation.effectiveMaxChargeNanoUsd);\n const recorded = BigInt(recordedChargeNanoUsd);\n const chargeNanoUsd =\n status === \"failed\" ? \"0\" : recorded > effective ? operation.effectiveMaxChargeNanoUsd : recordedChargeNanoUsd;\n\n await reportPremiumTerminalState(client, operation, {\n // The describe() timing wins when the business supplied one; otherwise\n // the lifecycle's own bracket around `run` is the best content-free fact.\n timing: { startedAt: startedAt.toISOString(), endedAt: new Date().toISOString() },\n ...facts,\n reportId: crypto.randomUUID(),\n status,\n chargeNanoUsd\n });\n };\n\n let value: T;\n try {\n value = await run(charge, handle);\n } catch (thrown) {\n await report(isCancellation(thrown, request.signal) ? \"canceled\" : \"failed\");\n // Rethrown unchanged: Enlitt adds nothing to, and wraps nothing of, what\n // the business's code threw.\n throw thrown;\n }\n\n await report(\"completed\");\n return value;\n}\n\n/**\n * Accounts one premium model call made by code outside the Vercel AI SDK: a\n * direct provider SDK call, a raw `fetch`, anything the business runs itself.\n *\n * It performs `enlitt()`'s construction checks (server runtime, business\n * secret, base URL) by building one internal client from the `EnlittOptions`\n * fields, validates `maxCharge`, `idempotencyKey`, `reportingDeadlineMs`, and\n * `metadata` under the same rules the Vercel adapter applies, and delegates to\n * {@link runPremiumCharge} with `idempotencyKey` as the call ID. Every failure\n * of those checks is an `EnlittConfigurationError` before any request.\n *\n * It is one model call. A loop of calls is a loop of `withPremiumCharge()`\n * calls; retrying the same call with the same `idempotencyKey` replays that\n * operation instead of charging again.\n */\nexport async function withPremiumCharge<T>(\n options: WithPremiumChargeOptions,\n run: (charge: PremiumChargeFunction, operation: PremiumChargeHandle) => Promise<T>\n): Promise<T> {\n const client = createInternalClient({\n ...(options.secretKey !== undefined ? { secretKey: options.secretKey } : {}),\n ...(options.baseUrl !== undefined ? { baseUrl: options.baseUrl } : {}),\n ...(options.session !== undefined ? { session: options.session } : {}),\n ...(options.rateLimit !== undefined ? { rateLimit: options.rateLimit } : {}),\n ...(options.onTerminalReportError !== undefined ? { onTerminalReportError: options.onTerminalReportError } : {})\n });\n\n const maxCharge = assertNanoUsd(options.maxCharge, \"maxCharge\");\n const callId =\n options.idempotencyKey !== undefined\n ? assertIdempotencyKeyBase(options.idempotencyKey, \"idempotencyKey\")\n : undefined;\n const reportingDeadlineMs =\n options.reportingDeadlineMs !== undefined\n ? assertReportingDeadlineMs(options.reportingDeadlineMs, \"reportingDeadlineMs\")\n : undefined;\n const metadata =\n options.metadata !== undefined ? assertCallerMetadata(options.metadata, \"metadata\") : undefined;\n\n return runPremiumCharge(\n client,\n {\n maxCharge,\n provider: { id: options.provider.id, model: options.provider.model },\n ...(callId !== undefined ? { callId } : {}),\n ...(reportingDeadlineMs !== undefined ? { reportingDeadlineMs } : {}),\n ...(metadata !== undefined ? { metadata } : {}),\n ...(options.signal !== undefined ? { signal: options.signal } : {})\n },\n run\n );\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/vercel/standard-language-model.ts","../src/vercel/premium-language-model.ts","../src/vercel/language-model.ts"],"names":["ENLITT_STANDARD_MODEL","requestEnlitt","validateOpenAIResponse","readEnlittJson","EnlittError","createSseEventStream","EnlittConfigurationError","validateEnlittStandardRequest","isTerminalResponseStreamEventType","SseFramingError","validateResponseStreamEvent","assertNanoUsd","runPremiumCharge","isCancellation","endedAt","createInternalClient","assertIdempotencyKeyBase","assertCallerMetadata","assertReportingDeadlineMs","generate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CAAA,EAAG;AACzE,IAAA,MAAM,IAAIA,0CAAA;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,IAAkBa,sCAAA,EAAqB;AAK5D,EAAA,OAAOC,+BAAa,CAAA,EAAG,IAAI,IAAI,MAAA,CAAO,MAAA,CAAO,MAAM,CAAA,CAAE,CAAA;AACvD","file":"chunk-C76K6HLL.cjs","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 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 */\nexport function createPremiumLanguageModel(client: InternalEnlittClient, model: LanguageModelV3): LanguageModelV3 {\n return {\n specificationVersion: \"v3\",\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\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.\n */\nasync function evaluatePrice(\n client: InternalEnlittClient,\n price: EnlittPrice | undefined,\n context: PremiumPriceContext\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. */\nfunction 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","import type {\n LanguageModelV3,\n LanguageModelV3CallOptions,\n LanguageModelV3Content,\n LanguageModelV3FinishReason,\n LanguageModelV3StreamPart,\n LanguageModelV3Usage,\n SharedV3ProviderMetadata,\n SharedV3ProviderOptions\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\";\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 */\nexport type EnlittTarget = typeof ENLITT_STANDARD_MODEL | LanguageModelV3;\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. 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 {\n const client = createInternalClient(options);\n\n if (target === ENLITT_STANDARD_MODEL) {\n return createStandardLanguageModel(client);\n }\n return createPremiumLanguageModel(client, target);\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"]}