@buildanagent/gateway 0.1.0-alpha.0 → 0.1.0-alpha.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.
package/README.md CHANGED
@@ -18,7 +18,7 @@ Name the tag. A plain `pnpm add @buildanagent/gateway` installs `0.0.0-bootstrap
18
18
 
19
19
  A conversation is a list of `Message`s: user messages, assistant messages and tool results. Their content is a short list of blocks (`text`, `reasoning`, `image` and `tool_call`), so your code never handles a provider's wire format. A reasoning block may carry a signature that only the model that wrote it accepts.
20
20
 
21
- Every `AssistantMessage` records its model, why it stopped (`stopReason`), any typed `error`, its `Usage` and its `Cost`. `Usage` has no field named `input`, because providers disagree on whether input includes cached tokens. The uncached part is `uncachedInput`, and `totalInput()` adds the cache reads and cache writes to it. `Cost.total` is `null` when the price is unknown, never a guessed zero.
21
+ Every `AssistantMessage` records its model, why it stopped (`stopReason`), any typed `error`, its `Usage` and its `Cost`. `Usage` has no field named `input`, because providers disagree on whether input includes cached tokens. The uncached part is `uncachedInput`, and `totalInput()` adds the cache reads and cache writes to it. `Cost.total` is `null` when the price is unknown, never a guessed zero. When a provider sends no usage for a response, its `Usage` has `unreported: true`: the counts are then incomplete, and the gateway prices the response as unknown. An adapter you write can build such a record with `unreportedUsage()`.
22
22
 
23
23
  ## A transcript recorded on one model replays on another
24
24
 
@@ -78,7 +78,7 @@ The gateway prices each response from the price catalog, so every `AssistantMess
78
78
 
79
79
  - `"provider"`: the adapter reported a total the provider billed, and that total wins over the catalog.
80
80
  - `"catalog"`: the gateway multiplied each token class by its catalog rate, and `catalogAsOf` gives the date those rates were copied.
81
- - `"unknown"`: the catalog doesn't list the model, or an attempt's stream threw before it reported usage, so `total` is `null`. The gateway never guesses a zero, because a budget that counts an unknown price as free never stops.
81
+ - `"unknown"`: the catalog doesn't list the model, or the provider never reported the usage, so `total` is `null`. Usage goes unreported when a request fails before any response arrives, when a stream throws or breaks off before its usage arrives, and when a reply ends without the usage chunk a server should send. A failed request's usage is unreported because the request may have reached the provider before the connection broke. The gateway never guesses a zero, because a budget that counts an unknown price as free never stops. An HTTP error response is the one failure that counts as zero tokens, because the provider sent an error instead of a reply.
82
82
 
83
83
  A retried call's cost sums its attempts, and the sum takes the weakest basis among them. It is `"unknown"` if any attempt's cost is unknown, and `"catalog"`, with `catalogAsOf`, if any attempt was priced from the catalog. It is `"provider"` only when the provider billed every attempt.
84
84
 
@@ -158,7 +158,7 @@ The [Messages API reference](https://platform.claude.com/docs/en/api/messages/cr
158
158
  | `output_tokens` | `output` |
159
159
  | `output_tokens_details.thinking_tokens` | `reasoning` |
160
160
 
161
- Reasoning is counted inside output. The reference calls `output_tokens` "the inclusive, authoritative total used for billing" and says `thinking_tokens` is "always ≤ `output_tokens`". When streaming, `thinking_tokens` arrives only on the final `message_delta` ([extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking), as of November 2026), and the adapter reads it there. A response that reports cache writes without the TTL split counts them at the TTL the request asked for.
161
+ Reasoning is counted inside output. The reference calls `output_tokens` "the inclusive, authoritative total used for billing" and says `thinking_tokens` is "always ≤ `output_tokens`". When streaming, `thinking_tokens` arrives only on the final `message_delta` ([extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking), as of November 2026), and the adapter reads it there. A response that reports cache writes without the TTL split counts them at the TTL the request asked for. A stream that sends no usage at all has unreported usage. So does a reply that streams content but never gets a `message_delta` with `output_tokens`, whether it finishes, breaks off or ends in an `error` event. The reason is that `message_start` reports only the first few output tokens, and the final count arrives on `message_delta` ([streaming](https://platform.claude.com/docs/en/build-with-claude/streaming), as of November 2026). A stream that fails before any content block keeps the counts `message_start` reported, because the model produced no output after them.
162
162
 
163
163
  Responses carry no billed price, as of November 2026: the reference's `usage` object holds token counts only. The adapter therefore reports an unknown cost, and `createModel()` prices the usage from the catalog.
164
164
 
@@ -221,7 +221,7 @@ A schema strict mode cannot express goes out unchanged without `strict`. Three k
221
221
  | --- | --- | --- |
222
222
  | `maxTokensField` | `"max_completion_tokens"` | the server reads only `max_tokens` |
223
223
  | `systemRole` | `"system"` | the model wants the system prompt as a `developer` message |
224
- | `streamUsage` | `true` | the server rejects `stream_options`; its replies then report no usage |
224
+ | `streamUsage` | `true` | the server rejects `stream_options`; its replies then report no usage, so their cost is unknown |
225
225
  | `strictTools` | `true` | the server rejects `strict` tools |
226
226
  | `temperature` | `true` | the model rejects `temperature`; a `temperature` you set then streams a `warning` instead |
227
227
  | `cacheBreakpoints` | `false` | the model takes explicit cache breakpoints, as OpenAI's do from `gpt-5.6` |
@@ -247,6 +247,8 @@ A chat completion's `usage` counts the whole prompt in `prompt_tokens`, with the
247
247
 
248
248
  Reasoning is counted inside output: `max_completion_tokens` bounds "visible output tokens and reasoning tokens" together, and the reference says rejected prediction tokens are, "like reasoning tokens", counted in the completion tokens for billing.
249
249
 
250
+ A reply that ends without the usage chunk has unreported usage, so `createModel()` prices it as unknown. That happens when a server ignores `stream_options`, when `streamUsage` is off, or when a stream fails before the chunk arrives.
251
+
250
252
  Chat Completions writes only 30-minute cache entries, so every write counts under `"5m"`, the key for the short cache-write rate, and an OpenAI catalog entry stores its 30-minute rate there. Models before `gpt-5.6` add no cache-write charge, so for `gpt-5.4-mini` that rate is the uncached input rate.
251
253
 
252
254
  Responses carry no billed price, as of November 2026: the usage object holds token counts only. The adapter therefore reports an unknown cost, and `createModel()` prices the usage from the catalog.
@@ -267,9 +269,13 @@ Every adapter takes a `ProviderConfig` whose `apiKey` you pass in. The gateway n
267
269
 
268
270
  A call that fails before the model has streamed any content is retried twice by default. The first retry waits 2 seconds and the second waits 4, and each retry streams a `retry` event with the attempt number, the delay and the error. Each wait doubles and is capped at 60 seconds. Set `retries` to change the count, or to 0 to turn retries off.
269
271
 
272
+ When the provider says how long to wait, the gateway waits at least that long, up to the same 60-second cap. Both adapters read the error response's `retry-after` header, in seconds or as an HTTP date counted from the response's `date` header. They also read `retry-after-ms`, in milliseconds, which the official TypeScript SDKs read first. The hint goes on the message as `error.retryAfterMs`. Before a retry, the gateway waits for the longer of its backoff and the hint, and the `retry` event's `delayMs` shows that wait. Anthropic sends `retry-after` on some 429s ([rate limits](https://platform.claude.com/docs/en/api/rate-limits), as of November 2026). OpenAI sends it on 429s for a temporary rate limit and on 503s for an overloaded model. A hint never makes a `quota`, `overflow` or `fatal` error retryable.
273
+
274
+ A hint longer than the 60-second cap gets no retry. The call ends at once with the `retryable` error and its `retryAfterMs`, and streams no `retry` event, so your code can wait and call again. OpenAI's guide asks for this: when a server delay exceeds your maximum, stop retrying rather than retry sooner ([rate limits](https://developers.openai.com/api/docs/guides/rate-limits), as of November 2026).
275
+
270
276
  Three rules keep a retry from doing harm. First, once a content event has reached you, the gateway never retries, because a second attempt would replay text you have already seen. Second, only errors of kind `retryable` are retried, such as a rate limit or an overloaded server. A `quota` error, a context `overflow` or a `fatal` error ends the call at once, because waiting will not fix it. Third, aborting the signal during a wait ends the stream at once with `stopReason: "aborted"`.
271
277
 
272
- A failed attempt still costs tokens, so the final message's `usage` and `cost` add up every attempt, not only the last, and `lastAttemptUsage` keeps the last attempt's usage on its own. If any attempt's cost is unknown, the total is unknown too. An attempt whose stream threw reported no usage, so it adds no tokens, but its cost is unknown, because the request may have reached the provider and been billed before the stream failed.
278
+ A failed attempt still costs tokens, so the final message's `usage` and `cost` add up every attempt, not only the last, and `lastAttemptUsage` keeps the last attempt's usage on its own. If any attempt's cost is unknown, the total is unknown too, and if any attempt's usage is unreported, the summed usage is unreported as well. An attempt whose stream threw reported no usage, so it adds no tokens, but its cost is unknown, because the request may have reached the provider and been billed before the stream failed.
273
279
 
274
280
  An adapter whose stream throws, for example on a dropped connection, is treated like one that ends with an error. A failed fetch, or a response body cut off mid-stream, is retried, and any other throw ends the call with a `fatal` error event, so an adapter's failure never makes `stream()` throw. A throwing `onRequest` hook runs inside the attempt, so it also ends the call with a `fatal` error. A middleware that throws runs outside the call, so its error makes `stream()` throw.
275
281
 
@@ -4,13 +4,20 @@
4
4
  * November 2026). An error body is `{ "type": "error", "error": { "type", "message" }, "request_id" }`, and some
5
5
  * errors add `error.details.error_code`. A stream that already returned 200 reports a later error as an `error`
6
6
  * event with the same `error` object and no status of its own.
7
+ *
8
+ * A 429 may carry a `retry-after` header that gives the number of seconds to wait before a retry; the
9
+ * spend-cap 429 never does (Rate limits, response headers, https://platform.claude.com/docs/en/api/rate-limits, as of
10
+ * November 2026). The adapter puts the hint on the error as `retryAfterMs`.
7
11
  */
8
12
  import type { ModelEvent } from "../../spec.js";
9
13
  import type { ModelRef } from "../../types.js";
10
14
  import { type PartialReply, type WireFailure } from "../wire.js";
11
15
  /** Reads an error object, from an HTTP error body or an `error` stream event. */
12
16
  export declare function failureFrom(body: unknown, status: number | undefined, fallback: string): WireFailure;
13
- /** Reads a failed HTTP response's error body; a body that is not JSON keeps its text as the message. */
17
+ /**
18
+ * Reads a failed HTTP response's error body and its retry-after hint; a body that is not JSON keeps its text as the
19
+ * message.
20
+ */
14
21
  export declare function failureFromResponse(response: Response): Promise<WireFailure>;
15
22
  /** True for the prefix-check 400, which the adapter answers by retrying with `drop_block`. */
16
23
  export declare function isPrefixMismatch(failure: WireFailure): boolean;
@@ -1,4 +1,4 @@
1
- import { failureTerminal, isObject, readErrorBody } from "../wire.js";
1
+ import { failureTerminal, isObject, readErrorBody, retryAfterMs, } from "../wire.js";
2
2
  // The HTTP status each error type stands for, so a stream error classifies like the HTTP error it would have been.
3
3
  const STATUS_OF_TYPE = {
4
4
  invalid_request_error: 400,
@@ -29,10 +29,17 @@ export function failureFrom(body, status, fallback) {
29
29
  message: typeof error?.message === "string" ? error.message : fallback,
30
30
  };
31
31
  }
32
- /** Reads a failed HTTP response's error body; a body that is not JSON keeps its text as the message. */
32
+ /**
33
+ * Reads a failed HTTP response's error body and its retry-after hint; a body that is not JSON keeps its text as the
34
+ * message.
35
+ */
33
36
  export async function failureFromResponse(response) {
34
37
  const { body, text } = await readErrorBody(response);
35
- return failureFrom(body, response.status, text || `HTTP ${response.status}`);
38
+ const wait = retryAfterMs(response.headers);
39
+ return {
40
+ ...failureFrom(body, response.status, text || `HTTP ${response.status}`),
41
+ ...(wait === undefined ? {} : { retryAfterMs: wait }),
42
+ };
36
43
  }
37
44
  /** True for the prefix-check 400, which the adapter answers by retrying with `drop_block`. */
38
45
  export function isPrefixMismatch(failure) {
@@ -1 +1 @@
1
- {"version":3,"file":"failure.js","sourceRoot":"","sources":["../../../src/adapters/anthropic/failure.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAqB,aAAa,EAAoB,MAAM,YAAY,CAAC;AAE3G,mHAAmH;AACnH,MAAM,cAAc,GAAqC;IACvD,qBAAqB,EAAE,GAAG;IAC1B,oBAAoB,EAAE,GAAG;IACzB,aAAa,EAAE,GAAG;IAClB,gBAAgB,EAAE,GAAG;IACrB,eAAe,EAAE,GAAG;IACpB,cAAc,EAAE,GAAG;IACnB,iBAAiB,EAAE,GAAG;IACtB,gBAAgB,EAAE,GAAG;IACrB,SAAS,EAAE,GAAG;IACd,aAAa,EAAE,GAAG;IAClB,gBAAgB,EAAE,GAAG;CACtB,CAAC;AAEF,kHAAkH;AAClH,gFAAgF;AAChF,kHAAkH;AAClH,wBAAwB;AACxB,MAAM,eAAe,GAAG,gDAAgD,CAAC;AAEzE,iFAAiF;AACjF,MAAM,UAAU,WAAW,CAAC,IAAa,EAAE,MAA0B,EAAE,QAAgB;IACrF,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,IAAI,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;IAC9E,MAAM,OAAO,GAAG,KAAK,IAAI,QAAQ,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;IAC7E,OAAO;QACL,GAAG,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EA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AO,EAAE,cAAc,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;AACxE,CAAC","sourcesContent":["/**\n * Failed requests and streams, as `error` terminals (Errors, https://platform.claude.com/docs/en/api/errors, and\n * the Messages API reference's error codes, https://platform.claude.com/docs/en/api/messages/create, both as of\n * November 2026). An error body is `{ \"type\": \"error\", \"error\": { \"type\", \"message\" }, \"request_id\" }`, and some\n * errors add `error.details.error_code`. A stream that already returned 200 reports a later error as an `error`\n * event with the same `error` object and no status of its own.\n */\nimport type { ModelEvent } from \"../../spec.js\";\nimport type { ModelRef } from \"../../types.js\";\nimport { failureTerminal, isObject, type PartialReply, readErrorBody, type WireFailure } from \"../wire.js\";\n\n// The HTTP status each error type stands for, so a stream error classifies like the HTTP error it would have been.\nconst STATUS_OF_TYPE: Readonly<Record<string, number>> = {\n invalid_request_error: 400,\n authentication_error: 401,\n billing_error: 402,\n permission_error: 403,\n not_found_error: 404,\n conflict_error: 409,\n request_too_large: 413,\n rate_limit_error: 429,\n api_error: 500,\n timeout_error: 504,\n overloaded_error: 529,\n};\n\n// The fix page says to match this error on this sentence alone, because the rest of the message can change (Fix a\n// thinking block bound to a different conversation, \"Handle the error in code\",\n// https://platform.claude.com/docs/en/build-with-claude/preserved-thinking/fix-bound-to-a-different-conversation,\n// as of November 2026).\nconst PREFIX_MISMATCH = \"The block is bound to a different conversation\";\n\n/** Reads an error object, from an HTTP error body or an `error` stream event. */\nexport function failureFrom(body: unknown, status: number | undefined, fallback: string): WireFailure {\n const error = isObject(body) && isObject(body.error) ? body.error : undefined;\n const details = error && isObject(error.details) ? error.details : undefined;\n return {\n ...(status === undefined ? {} : { status }),\n ...(typeof error?.type === \"string\" ? { type: error.type } : {}),\n ...(typeof details?.error_code === \"string\" ? { errorCode: details.error_code } : {}),\n message: typeof error?.message === \"string\" ? error.message : fallback,\n };\n}\n\n/** Reads a failed HTTP response's error body; a body that is not JSON keeps its text as the message. */\nexport async function failureFromResponse(response: Response): Promise<WireFailure> {\n const { body, text } = await readErrorBody(response);\n return failureFrom(body, response.status, text || `HTTP ${response.status}`);\n}\n\n/** True for the prefix-check 400, which the adapter answers by retrying with `drop_block`. */\nexport function isPrefixMismatch(failure: WireFailure): boolean {\n return (failure.status ?? STATUS_OF_TYPE[failure.type ?? \"\"]) === 400 && failure.message.includes(PREFIX_MISMATCH);\n}\n\n/** The `error` terminal for a failure, with any partial content and usage the attempt reached. */\nexport function failureEvent(\n model: ModelRef,\n failure: WireFailure,\n partial: PartialReply = {},\n): Extract<ModelEvent, { type: \"error\" }> {\n const code = isPrefixMismatch(failure) ? \"thinking_prefix_mismatch\" : undefined;\n return failureTerminal(model, failure, STATUS_OF_TYPE, partial, code);\n}\n"]}
1
+ {"version":3,"file":"failure.js","sourceRoot":"","sources":["../../../src/adapters/anthropic/failure.ts"],"names":[],"mappings":"AAaA,OAAO,EACL,eAAe,EACf,QAAQ,EAER,aAAa,EACb,YAAY,GAEb,MAAM,YAAY,CAAC;AAEpB,mHAAmH;AACnH,MAAM,cAAc,GAAqC;IACvD,qBAAqB,EAAE,GAAG;IAC1B,oBAAoB,EAAE,GAAG;IACzB,aAAa,EAAE,GAAG;IAClB,gBAAgB,EAAE,GAAG;IACrB,eAAe,EAAE,GAAG;IACpB,cAAc,EAAE,GAAG;IACnB,iBAAiB,EAAE,GAAG;IACtB,gBAAgB,EAAE,GAAG;IACrB,SAAS,EAAE,GAAG;IACd,aAAa,EAAE,GAAG;IAClB,gBAAgB,EAAE,GAAG;CACtB,CAAC;AAEF,kHAAkH;AAClH,gFAAgF;AAChF,kHAAkH;AAClH,wBAAwB;AACxB,MAAM,eAAe,GAAG,gDAAgD,CAAC;AAEzE,iFAAiF;AACjF,MAAM,UAAU,WAAW,CAAC,IAAa,EAAE,MAA0B,EAAE,QAAgB;IACrF,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,IAAI,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,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BAAgB,CAAC,OAAoB;IACnD,OAAO,CAAC,OAAO,CAAC,MAAM,IAAI,cAAc,CAAC,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,KAAK,GAAG,IAAI,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAC,CAAC;AACrH,CAAC;AAED,kGAAkG;AAClG,MAAM,UAAU,YAAY,CAC1B,KAAe,EACf,OAAoB,EACpB,OAAO,GAAiB,EAAE;IAE1B,MAAM,IAAI,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,0BAA0B,CAAC,CAAC,CAAC,SAAS,CAAC;IAChF,OAAO,eAAe,CAAC,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;AACxE,CAAC","sourcesContent":["/**\n * Failed requests and streams, as `error` terminals (Errors, https://platform.claude.com/docs/en/api/errors, and\n * the Messages API reference's error codes, https://platform.claude.com/docs/en/api/messages/create, both as of\n * November 2026). An error body is `{ \"type\": \"error\", \"error\": { \"type\", \"message\" }, \"request_id\" }`, and some\n * errors add `error.details.error_code`. A stream that already returned 200 reports a later error as an `error`\n * event with the same `error` object and no status of its own.\n *\n * A 429 may carry a `retry-after` header that gives the number of seconds to wait before a retry; the\n * spend-cap 429 never does (Rate limits, response headers, https://platform.claude.com/docs/en/api/rate-limits, as of\n * November 2026). The adapter puts the hint on the error as `retryAfterMs`.\n */\nimport type { ModelEvent } from \"../../spec.js\";\nimport type { ModelRef } from \"../../types.js\";\nimport {\n failureTerminal,\n isObject,\n type PartialReply,\n readErrorBody,\n retryAfterMs,\n type WireFailure,\n} from \"../wire.js\";\n\n// The HTTP status each error type stands for, so a stream error classifies like the HTTP error it would have been.\nconst STATUS_OF_TYPE: Readonly<Record<string, number>> = {\n invalid_request_error: 400,\n authentication_error: 401,\n billing_error: 402,\n permission_error: 403,\n not_found_error: 404,\n conflict_error: 409,\n request_too_large: 413,\n rate_limit_error: 429,\n api_error: 500,\n timeout_error: 504,\n overloaded_error: 529,\n};\n\n// The fix page says to match this error on this sentence alone, because the rest of the message can change (Fix a\n// thinking block bound to a different conversation, \"Handle the error in code\",\n// https://platform.claude.com/docs/en/build-with-claude/preserved-thinking/fix-bound-to-a-different-conversation,\n// as of November 2026).\nconst PREFIX_MISMATCH = \"The block is bound to a different conversation\";\n\n/** Reads an error object, from an HTTP error body or an `error` stream event. */\nexport function failureFrom(body: unknown, status: number | undefined, fallback: string): WireFailure {\n const error = isObject(body) && isObject(body.error) ? body.error : undefined;\n const details = error && isObject(error.details) ? error.details : undefined;\n return {\n ...(status === undefined ? {} : { status }),\n ...(typeof error?.type === \"string\" ? { type: error.type } : {}),\n ...(typeof details?.error_code === \"string\" ? { errorCode: details.error_code } : {}),\n message: typeof error?.message === \"string\" ? error.message : fallback,\n };\n}\n\n/**\n * Reads a failed HTTP response's error body and its retry-after hint; a body that is not JSON keeps its text as the\n * message.\n */\nexport async function failureFromResponse(response: Response): Promise<WireFailure> {\n const { body, text } = await readErrorBody(response);\n const wait = retryAfterMs(response.headers);\n return {\n ...failureFrom(body, response.status, text || `HTTP ${response.status}`),\n ...(wait === undefined ? {} : { retryAfterMs: wait }),\n };\n}\n\n/** True for the prefix-check 400, which the adapter answers by retrying with `drop_block`. */\nexport function isPrefixMismatch(failure: WireFailure): boolean {\n return (failure.status ?? STATUS_OF_TYPE[failure.type ?? \"\"]) === 400 && failure.message.includes(PREFIX_MISMATCH);\n}\n\n/** The `error` terminal for a failure, with any partial content and usage the attempt reached. */\nexport function failureEvent(\n model: ModelRef,\n failure: WireFailure,\n partial: PartialReply = {},\n): Extract<ModelEvent, { type: \"error\" }> {\n const code = isPrefixMismatch(failure) ? \"thinking_prefix_mismatch\" : undefined;\n return failureTerminal(model, failure, STATUS_OF_TYPE, partial, code);\n}\n"]}
@@ -8,6 +8,12 @@
8
8
  * Text blocks become text, `thinking` and `redacted_thinking` blocks become reasoning with an Anthropic signature,
9
9
  * and `tool_use` blocks become tool calls. Server-tool blocks carry nothing this transcript can replay, so they are
10
10
  * skipped.
11
+ *
12
+ * Usage arrives on `message_start` and, with the authoritative output count, on the final `message_delta`. The usage
13
+ * is `unreported` when that count is missing: for a stream that sent no usage, for a finished reply whose
14
+ * `message_delta`s reported no `output_tokens`, and for a stream that breaks off or sends an `error` event after a
15
+ * content block began. Such usage keeps the counts `message_start` reported. A stream that fails before any content
16
+ * block keeps those counts as reported, because no output was made after them.
11
17
  */
12
18
  import type { ToolNameMap } from "../../names.js";
13
19
  import type { ModelEvent } from "../../spec.js";
@@ -27,5 +33,6 @@ export declare class MessageAssembler implements StreamReader {
27
33
  content: ContentBlock[];
28
34
  usage: Usage;
29
35
  };
36
+ /** The usage so far: `unreported` when output began and no `message_delta` has reported its final count yet. */
30
37
  usage(): Usage;
31
38
  }
@@ -1,3 +1,4 @@
1
+ import { unreportedUsage } from "../../usage.js";
1
2
  import { isObject, parseToolInput, str, terminalMessage } from "../wire.js";
2
3
  import { failureEvent, failureFrom } from "./failure.js";
3
4
  import { REDACTED_THINKING_PREFIX } from "./request.js";
@@ -20,6 +21,11 @@ export class MessageAssembler {
20
21
  #closed = new Map();
21
22
  #transformations = new Set();
22
23
  #usage = {};
24
+ // Whether any event carried a usage object, whether a content block began after `message_start`'s output count,
25
+ // and whether a `message_delta` reported the final output count.
26
+ #usageSeen = false;
27
+ #outputSeen = false;
28
+ #finalUsageSeen = false;
23
29
  #stopReason = "";
24
30
  #stopDetails;
25
31
  constructor(model, names, cacheTtl) {
@@ -39,6 +45,8 @@ export class MessageAssembler {
39
45
  return [failureEvent(this.#model, { message: "the stream ended before message_stop" }, this.partial())];
40
46
  }
41
47
  #dispatch(type, data) {
48
+ if (type === "content_block_start" || type === "content_block_delta")
49
+ this.#outputSeen = true;
42
50
  switch (type) {
43
51
  case "message_start":
44
52
  return this.#messageStart(data);
@@ -64,11 +72,21 @@ export class MessageAssembler {
64
72
  const content = [...this.#closed, ...open].sort(([a], [b]) => a - b).map(([, block]) => block);
65
73
  return { content, usage: this.usage() };
66
74
  }
75
+ /** The usage so far: `unreported` when output began and no `message_delta` has reported its final count yet. */
67
76
  usage() {
68
- return anthropicUsage(this.#usage, this.#cacheTtl);
77
+ return this.#usageWith(this.#outputSeen);
78
+ }
79
+ #usageWith(outputMade) {
80
+ if (!this.#usageSeen)
81
+ return unreportedUsage();
82
+ const counted = anthropicUsage(this.#usage, this.#cacheTtl);
83
+ // Without the final count, the output is the one `message_start` sent before any output was made.
84
+ return this.#finalUsageSeen || !outputMade ? counted : { ...counted, unreported: true };
69
85
  }
70
86
  #messageStart(data) {
71
87
  const message = isObject(data.message) ? data.message : {};
88
+ if (isObject(message.usage))
89
+ this.#usageSeen = true;
72
90
  this.#usage = mergeUsage({}, message.usage);
73
91
  return this.#transformationWarnings(message.input_transformations);
74
92
  }
@@ -178,6 +196,11 @@ export class MessageAssembler {
178
196
  this.#stopReason = delta.stop_reason;
179
197
  if (delta.stop_details !== undefined)
180
198
  this.#stopDetails = delta.stop_details;
199
+ if (isObject(data.usage)) {
200
+ this.#usageSeen = true;
201
+ if (typeof data.usage.output_tokens === "number")
202
+ this.#finalUsageSeen = true;
203
+ }
181
204
  this.#usage = mergeUsage(this.#usage, data.usage);
182
205
  return this.#transformationWarnings(data.input_transformations ?? delta.input_transformations);
183
206
  }
@@ -187,7 +210,9 @@ export class MessageAssembler {
187
210
  return [...closing, ...this.#terminal()];
188
211
  }
189
212
  #terminal() {
190
- const { content, usage } = this.partial();
213
+ // A finished reply always needs the final count, even one that streamed no content block.
214
+ const { content } = this.partial();
215
+ const usage = this.#usageWith(true);
191
216
  if (this.#stopReason === "refusal") {
192
217
  const details = isObject(this.#stopDetails) ? this.#stopDetails : {};
193
218
  const category = str(details.category) || "no category";
@@ -1 +1 @@
1
- {"version":3,"file":"response.js","sourceRoot":"","sources":["../../../src/adapters/anthropic/response.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,QAAQ,EAAa,cAAc,EAAqB,GAAG,EAAE,eAAe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AO,EAAE,CAAC;QAC1C,IAAI,IAAI,CAAC,WAAW,KAAK,SAAS,EAAE,CAAC;YACnC,MAAM,OAAO,GAAG,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,CAAC;YACrE,MAAM,QAAQ,GAAG,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,aAAa,CAAC;YACxD,MAAM,OAAO,GAAG,YAAY,QAAQ,MAAM,GAAG,CAAC,OAAO,CAAC,WAAW,CAAC,IAAI,gCAAgC,EAAE,CAAC;YACzG,iGAAiG;YACjG,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;QACrF,CAAC;QACD,MAAM,UAAU,GAAG,YAAY,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,MAAM,CAAC;QAC5D,MAAM,QAAQ,GACZ,IAAI,CAAC,WAAW,KAAK,YAAY;YAC/B,CAAC,CAAC;gBACE;oBACE,IAAI,EAAE,SAAS;oBACf,IAAI,EAAE,YAAY;oBAClB,OAAO,EACL,mGAAmG;wBACnG,iGAAiG;iBACpG;aACF;YACH,CAAC,CAAC,EAAE,CAAC;QACT,OAAO,CAAC,GAAG,QAAQ,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,eAAe,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,UAAU,CAAC,EAAE,CAAC,CAAC;IAChH,CAAC;CACF","sourcesContent":["/**\n * Turns the Messages API's stream events into `ModelEvent`s (Streaming messages,\n * https://platform.claude.com/docs/en/build-with-claude/streaming, as of November 2026). A stream runs\n * `message_start`, then each content block as `content_block_start`, its `content_block_delta`s and\n * `content_block_stop`, then one or more `message_delta`s with cumulative usage, then `message_stop`. `ping` events\n * and event types the adapter does not know are skipped, as the versioning policy asks.\n *\n * Text blocks become text, `thinking` and `redacted_thinking` blocks become reasoning with an Anthropic signature,\n * and `tool_use` blocks become tool calls. Server-tool blocks carry nothing this transcript can replay, so they are\n * skipped.\n */\nimport type { ToolNameMap } from \"../../names.js\";\nimport type { ModelEvent } from \"../../spec.js\";\nimport type { ServerSentEvent } from \"../../sse.js\";\nimport type { AssistantMessage, ContentBlock, ModelRef, Usage } from \"../../types.js\";\nimport { isObject, type Json, parseToolInput, type StreamReader, str, terminalMessage } from \"../wire.js\";\nimport { failureEvent, failureFrom } from \"./failure.js\";\nimport { REDACTED_THINKING_PREFIX } from \"./request.js\";\nimport { anthropicUsage, mergeUsage } from \"./usage.js\";\n\ntype Warning = Extract<ModelEvent, { type: \"warning\" }>;\n\ninterface OpenBlock {\n readonly kind: \"text\" | \"reasoning\" | \"tool_input\";\n text: string;\n signature?: string;\n redacted?: string;\n callId?: string;\n name?: string;\n startInput?: unknown;\n}\n\n// Each wire stop reason as the gateway's. `refusal` is handled apart, as a failure.\nconst STOP_REASONS: Readonly<Record<string, AssistantMessage[\"stopReason\"]>> = {\n end_turn: \"stop\",\n stop_sequence: \"stop\",\n pause_turn: \"stop\",\n tool_use: \"tool_calls\",\n max_tokens: \"length\",\n model_context_window_exceeded: \"length\",\n};\n\n/** One stream's state: the blocks so far, the usage and the stop reason. */\nexport class MessageAssembler implements StreamReader {\n readonly #model: ModelRef;\n readonly #names: ToolNameMap;\n readonly #cacheTtl: \"5m\" | \"1h\";\n readonly #open = new Map<number, OpenBlock>();\n readonly #closed = new Map<number, ContentBlock>();\n readonly #transformations = new Set<string>();\n #usage: Json = {};\n #stopReason = \"\";\n #stopDetails: unknown;\n\n constructor(model: ModelRef, names: ToolNameMap, cacheTtl: \"5m\" | \"1h\") {\n this.#model = model;\n this.#names = names;\n this.#cacheTtl = cacheTtl;\n }\n\n /** The events one server-sent event produces. The last one is the terminal when the stream has ended. */\n handle(sse: ServerSentEvent): ModelEvent[] {\n const data: unknown = JSON.parse(sse.data);\n if (!isObject(data)) return [];\n return this.#dispatch(typeof data.type === \"string\" ? data.type : sse.event, data);\n }\n\n /** No status and no terminal: the connection closed early, which a retry may fix. */\n ended(): ModelEvent[] {\n return [failureEvent(this.#model, { message: \"the stream ended before message_stop\" }, this.partial())];\n }\n\n #dispatch(type: string, data: Json): ModelEvent[] {\n switch (type) {\n case \"message_start\":\n return this.#messageStart(data);\n case \"content_block_start\":\n return this.#blockStart(data);\n case \"content_block_delta\":\n return this.#blockDelta(data);\n case \"content_block_stop\":\n return this.#blockStop(data);\n case \"message_delta\":\n return this.#messageDelta(data);\n case \"message_stop\":\n return this.#messageStop();\n case \"error\":\n return [failureEvent(this.#model, failureFrom(data, undefined, \"stream error\"), this.partial())];\n default:\n return [];\n }\n }\n\n /** The content and usage so far, open blocks included, for an `error` terminal. */\n partial(): { content: ContentBlock[]; usage: Usage } {\n const open = [...this.#open].map(([index, block]) => [index, this.#finish(block)] as const);\n const content = [...this.#closed, ...open].sort(([a], [b]) => a - b).map(([, block]) => block);\n return { content, usage: this.usage() };\n }\n\n usage(): Usage {\n return anthropicUsage(this.#usage, this.#cacheTtl);\n }\n\n #messageStart(data: Json): ModelEvent[] {\n const message = isObject(data.message) ? data.message : {};\n this.#usage = mergeUsage({}, message.usage);\n return this.#transformationWarnings(message.input_transformations);\n }\n\n // Under the thinking-binding beta, `message_start` carries `input_transformations`, and the final `message_delta`\n // carries it again after a mid-stream fallback (Streaming, \"Event types\"). Each entry is warned about once.\n #transformationWarnings(entries: unknown): Warning[] {\n if (!Array.isArray(entries)) return [];\n return entries.flatMap((entry): Warning[] => {\n if (!isObject(entry) || entry.type !== \"thinking_mismatch_allowed\") return [];\n const key = `${str(entry.path)}|${str(entry.reason)}`;\n if (this.#transformations.has(key)) return [];\n this.#transformations.add(key);\n return [\n {\n type: \"warning\",\n code: \"thinking_mismatch_allowed\",\n message: `${str(entry.path)}: a thinking block failed the prefix check (${str(entry.reason)}) and reached the model`,\n },\n ];\n });\n }\n\n #blockStart(data: Json): ModelEvent[] {\n const index = typeof data.index === \"number\" ? data.index : -1;\n const block = isObject(data.content_block) ? data.content_block : {};\n const open = this.#openBlock(block);\n if (open === undefined || index < 0 || this.#open.has(index) || this.#closed.has(index)) return [];\n this.#open.set(index, open);\n const startEvent: ModelEvent = { type: `${open.kind}_start`, index };\n // A redacted block arrives whole, with no deltas, so it ends where it starts.\n return open.redacted === undefined ? [startEvent] : [startEvent, ...this.#close(index)];\n }\n\n #openBlock(block: Json): OpenBlock | undefined {\n switch (block.type) {\n case \"text\":\n return { kind: \"text\", text: str(block.text) };\n case \"thinking\":\n return { kind: \"reasoning\", text: str(block.thinking), signature: str(block.signature) };\n case \"redacted_thinking\":\n return { kind: \"reasoning\", text: \"\", redacted: str(block.data) };\n case \"tool_use\":\n return { kind: \"tool_input\", text: \"\", callId: str(block.id), name: str(block.name), startInput: block.input };\n default:\n return undefined;\n }\n }\n\n #blockDelta(data: Json): ModelEvent[] {\n const index = typeof data.index === \"number\" ? data.index : -1;\n const open = this.#open.get(index);\n const delta = isObject(data.delta) ? data.delta : {};\n if (open === undefined) return [];\n if (delta.type === \"signature_delta\") {\n open.signature = (open.signature ?? \"\") + str(delta.signature);\n return [];\n }\n const text = str(\n delta.type === \"thinking_delta\"\n ? delta.thinking\n : delta.type === \"input_json_delta\"\n ? delta.partial_json\n : delta.text,\n );\n const fits =\n (open.kind === \"text\" && delta.type === \"text_delta\") ||\n (open.kind === \"reasoning\" && delta.type === \"thinking_delta\") ||\n (open.kind === \"tool_input\" && delta.type === \"input_json_delta\");\n // An empty delta adds nothing; a citations delta or another kind of delta has no place in this transcript.\n if (!fits || text === \"\") return [];\n open.text += text;\n return [{ type: `${open.kind}_delta`, index, delta: text }];\n }\n\n #blockStop(data: Json): ModelEvent[] {\n return typeof data.index === \"number\" ? this.#close(data.index) : [];\n }\n\n #close(index: number): ModelEvent[] {\n const open = this.#open.get(index);\n if (open === undefined) return [];\n this.#open.delete(index);\n const block = this.#finish(open);\n this.#closed.set(index, block);\n return [{ type: `${open.kind}_end`, index, block }];\n }\n\n #finish(open: OpenBlock): ContentBlock {\n if (open.kind === \"text\") return { type: \"text\", text: open.text };\n if (open.kind === \"tool_input\") {\n const wire = open.name ?? \"\";\n return {\n type: \"tool_call\",\n callId: open.callId ?? \"\",\n name: this.#names.restore(wire) ?? wire,\n input: parseToolInput(open.text, open.startInput ?? {}),\n };\n }\n const value = open.redacted === undefined ? open.signature : `${REDACTED_THINKING_PREFIX}${open.redacted}`;\n const { api, provider, id } = this.#model;\n return value\n ? { type: \"reasoning\", text: open.text, signature: { api, provider, model: id, value } }\n : { type: \"reasoning\", text: open.text };\n }\n\n #messageDelta(data: Json): ModelEvent[] {\n const delta = isObject(data.delta) ? data.delta : {};\n if (typeof delta.stop_reason === \"string\") this.#stopReason = delta.stop_reason;\n if (delta.stop_details !== undefined) this.#stopDetails = delta.stop_details;\n this.#usage = mergeUsage(this.#usage, data.usage);\n return this.#transformationWarnings(data.input_transformations ?? delta.input_transformations);\n }\n\n #messageStop(): ModelEvent[] {\n // The output limit can end a stream with a block still open; the block ends here with what arrived.\n const closing = [...this.#open.keys()].sort((a, b) => a - b).flatMap((index) => this.#close(index));\n return [...closing, ...this.#terminal()];\n }\n\n #terminal(): ModelEvent[] {\n const { content, usage } = this.partial();\n if (this.#stopReason === \"refusal\") {\n const details = isObject(this.#stopDetails) ? this.#stopDetails : {};\n const category = str(details.category) || \"no category\";\n const message = `refusal (${category}): ${str(details.explanation) || \"the model declined the request\"}`;\n // No `type`: failureEvent prefixes the type to the message, which already starts with \"refusal\".\n return [failureEvent(this.#model, { message, kind: \"fatal\" }, { content, usage })];\n }\n const stopReason = STOP_REASONS[this.#stopReason] ?? \"stop\";\n const warnings: Warning[] =\n this.#stopReason === \"pause_turn\"\n ? [\n {\n type: \"warning\",\n code: \"pause_turn\",\n message:\n \"The provider paused a long-running server-tool turn. This adapter dropped the turn's server-tool \" +\n \"blocks, so it cannot resume the paused turn; the reply holds only the content before the pause.\",\n },\n ]\n : [];\n return [...warnings, { type: \"done\", message: terminalMessage(this.#model, { content, usage }, stopReason) }];\n }\n}\n"]}
1
+ {"version":3,"file":"response.js","sourceRoot":"","sources":["../../../src/adapters/anthropic/response.ts"],"names":[],"mappings":"AAqBA,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,QAAQ,EAAa,cAAc,EAAqB,GAAG,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC1G,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAcxD,oFAAoF;AACpF,MAAM,YAAY,GAA6D;IAC7E,QAAQ,EAAE,MAAM;IAChB,aAAa,EAAE,MAAM;IACrB,UAAU,EAAE,MAAM;IAClB,QAAQ,EAAE,YAAY;IACtB,UAAU,EAAE,QAAQ;IACpB,6BAA6B,EAAE,QAAQ;CACxC,CAAC;AAEF,4EAA4E;AAC5E,MAAM,OAAO,gBAAgB;IAClB,MAAM,CAAW;IACjB,MAAM,CAAc;IACpB,SAAS,CAAc;IACvB,KAAK,GAAG,IAAI,GAAG,EAAqB,CAAC;IACrC,OAAO,GAAG,IAAI,GAAG,EAAwB,CAAC;IAC1C,gBAAgB,GAAG,IAAI,GAAG,EAAU,CAAC;IAC9C,MAAM,GAAS,EAAE,CAAC;IAClB,gHAAgH;IAChH,iEAAiE;IACjE,UAAU,GAAG,KAAK,CAAC;IACnB,WAAW,GAAG,KAAK,CAAC;IACpB,eAAe,GAAG,KAAK,CAAC;IACxB,WAAW,GAAG,EAAE,CAAC;IACjB,YAAY,CAAU;IAEtB,YAAY,KAAe,EAAE,KAAkB,EAAE,QAAqB;QACpE,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;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AAM,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;QACpC,IAAI,IAAI,CAAC,WAAW,KAAK,SAAS,EAAE,CAAC;YACnC,MAAM,OAAO,GAAG,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,CAAC;YACrE,MAAM,QAAQ,GAAG,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,aAAa,CAAC;YACxD,MAAM,OAAO,GAAG,YAAY,QAAQ,MAAM,GAAG,CAAC,OAAO,CAAC,WAAW,CAAC,IAAI,gCAAgC,EAAE,CAAC;YACzG,iGAAiG;YACjG,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;QACrF,CAAC;QACD,MAAM,UAAU,GAAG,YAAY,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,MAAM,CAAC;QAC5D,MAAM,QAAQ,GACZ,IAAI,CAAC,WAAW,KAAK,YAAY;YAC/B,CAAC,CAAC;gBACE;oBACE,IAAI,EAAE,SAAS;oBACf,IAAI,EAAE,YAAY;oBAClB,OAAO,EACL,mGAAmG;wBACnG,iGAAiG;iBACpG;aACF;YACH,CAAC,CAAC,EAAE,CAAC;QACT,OAAO,CAAC,GAAG,QAAQ,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,eAAe,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,UAAU,CAAC,EAAE,CAAC,CAAC;IAChH,CAAC;CACF","sourcesContent":["/**\n * Turns the Messages API's stream events into `ModelEvent`s (Streaming messages,\n * https://platform.claude.com/docs/en/build-with-claude/streaming, as of November 2026). A stream runs\n * `message_start`, then each content block as `content_block_start`, its `content_block_delta`s and\n * `content_block_stop`, then one or more `message_delta`s with cumulative usage, then `message_stop`. `ping` events\n * and event types the adapter does not know are skipped, as the versioning policy asks.\n *\n * Text blocks become text, `thinking` and `redacted_thinking` blocks become reasoning with an Anthropic signature,\n * and `tool_use` blocks become tool calls. Server-tool blocks carry nothing this transcript can replay, so they are\n * skipped.\n *\n * Usage arrives on `message_start` and, with the authoritative output count, on the final `message_delta`. The usage\n * is `unreported` when that count is missing: for a stream that sent no usage, for a finished reply whose\n * `message_delta`s reported no `output_tokens`, and for a stream that breaks off or sends an `error` event after a\n * content block began. Such usage keeps the counts `message_start` reported. A stream that fails before any content\n * block keeps those counts as reported, because no output was made after them.\n */\nimport type { ToolNameMap } from \"../../names.js\";\nimport type { ModelEvent } from \"../../spec.js\";\nimport type { ServerSentEvent } from \"../../sse.js\";\nimport type { AssistantMessage, ContentBlock, ModelRef, Usage } from \"../../types.js\";\nimport { unreportedUsage } from \"../../usage.js\";\nimport { isObject, type Json, parseToolInput, type StreamReader, str, terminalMessage } from \"../wire.js\";\nimport { failureEvent, failureFrom } from \"./failure.js\";\nimport { REDACTED_THINKING_PREFIX } from \"./request.js\";\nimport { anthropicUsage, mergeUsage } from \"./usage.js\";\n\ntype Warning = Extract<ModelEvent, { type: \"warning\" }>;\n\ninterface OpenBlock {\n readonly kind: \"text\" | \"reasoning\" | \"tool_input\";\n text: string;\n signature?: string;\n redacted?: string;\n callId?: string;\n name?: string;\n startInput?: unknown;\n}\n\n// Each wire stop reason as the gateway's. `refusal` is handled apart, as a failure.\nconst STOP_REASONS: Readonly<Record<string, AssistantMessage[\"stopReason\"]>> = {\n end_turn: \"stop\",\n stop_sequence: \"stop\",\n pause_turn: \"stop\",\n tool_use: \"tool_calls\",\n max_tokens: \"length\",\n model_context_window_exceeded: \"length\",\n};\n\n/** One stream's state: the blocks so far, the usage and the stop reason. */\nexport class MessageAssembler implements StreamReader {\n readonly #model: ModelRef;\n readonly #names: ToolNameMap;\n readonly #cacheTtl: \"5m\" | \"1h\";\n readonly #open = new Map<number, OpenBlock>();\n readonly #closed = new Map<number, ContentBlock>();\n readonly #transformations = new Set<string>();\n #usage: Json = {};\n // Whether any event carried a usage object, whether a content block began after `message_start`'s output count,\n // and whether a `message_delta` reported the final output count.\n #usageSeen = false;\n #outputSeen = false;\n #finalUsageSeen = false;\n #stopReason = \"\";\n #stopDetails: unknown;\n\n constructor(model: ModelRef, names: ToolNameMap, cacheTtl: \"5m\" | \"1h\") {\n this.#model = model;\n this.#names = names;\n this.#cacheTtl = cacheTtl;\n }\n\n /** The events one server-sent event produces. The last one is the terminal when the stream has ended. */\n handle(sse: ServerSentEvent): ModelEvent[] {\n const data: unknown = JSON.parse(sse.data);\n if (!isObject(data)) return [];\n return this.#dispatch(typeof data.type === \"string\" ? data.type : sse.event, data);\n }\n\n /** No status and no terminal: the connection closed early, which a retry may fix. */\n ended(): ModelEvent[] {\n return [failureEvent(this.#model, { message: \"the stream ended before message_stop\" }, this.partial())];\n }\n\n #dispatch(type: string, data: Json): ModelEvent[] {\n if (type === \"content_block_start\" || type === \"content_block_delta\") this.#outputSeen = true;\n switch (type) {\n case \"message_start\":\n return this.#messageStart(data);\n case \"content_block_start\":\n return this.#blockStart(data);\n case \"content_block_delta\":\n return this.#blockDelta(data);\n case \"content_block_stop\":\n return this.#blockStop(data);\n case \"message_delta\":\n return this.#messageDelta(data);\n case \"message_stop\":\n return this.#messageStop();\n case \"error\":\n return [failureEvent(this.#model, failureFrom(data, undefined, \"stream error\"), this.partial())];\n default:\n return [];\n }\n }\n\n /** The content and usage so far, open blocks included, for an `error` terminal. */\n partial(): { content: ContentBlock[]; usage: Usage } {\n const open = [...this.#open].map(([index, block]) => [index, this.#finish(block)] as const);\n const content = [...this.#closed, ...open].sort(([a], [b]) => a - b).map(([, block]) => block);\n return { content, usage: this.usage() };\n }\n\n /** The usage so far: `unreported` when output began and no `message_delta` has reported its final count yet. */\n usage(): Usage {\n return this.#usageWith(this.#outputSeen);\n }\n\n #usageWith(outputMade: boolean): Usage {\n if (!this.#usageSeen) return unreportedUsage();\n const counted = anthropicUsage(this.#usage, this.#cacheTtl);\n // Without the final count, the output is the one `message_start` sent before any output was made.\n return this.#finalUsageSeen || !outputMade ? counted : { ...counted, unreported: true };\n }\n\n #messageStart(data: Json): ModelEvent[] {\n const message = isObject(data.message) ? data.message : {};\n if (isObject(message.usage)) this.#usageSeen = true;\n this.#usage = mergeUsage({}, message.usage);\n return this.#transformationWarnings(message.input_transformations);\n }\n\n // Under the thinking-binding beta, `message_start` carries `input_transformations`, and the final `message_delta`\n // carries it again after a mid-stream fallback (Streaming, \"Event types\"). Each entry is warned about once.\n #transformationWarnings(entries: unknown): Warning[] {\n if (!Array.isArray(entries)) return [];\n return entries.flatMap((entry): Warning[] => {\n if (!isObject(entry) || entry.type !== \"thinking_mismatch_allowed\") return [];\n const key = `${str(entry.path)}|${str(entry.reason)}`;\n if (this.#transformations.has(key)) return [];\n this.#transformations.add(key);\n return [\n {\n type: \"warning\",\n code: \"thinking_mismatch_allowed\",\n message: `${str(entry.path)}: a thinking block failed the prefix check (${str(entry.reason)}) and reached the model`,\n },\n ];\n });\n }\n\n #blockStart(data: Json): ModelEvent[] {\n const index = typeof data.index === \"number\" ? data.index : -1;\n const block = isObject(data.content_block) ? data.content_block : {};\n const open = this.#openBlock(block);\n if (open === undefined || index < 0 || this.#open.has(index) || this.#closed.has(index)) return [];\n this.#open.set(index, open);\n const startEvent: ModelEvent = { type: `${open.kind}_start`, index };\n // A redacted block arrives whole, with no deltas, so it ends where it starts.\n return open.redacted === undefined ? [startEvent] : [startEvent, ...this.#close(index)];\n }\n\n #openBlock(block: Json): OpenBlock | undefined {\n switch (block.type) {\n case \"text\":\n return { kind: \"text\", text: str(block.text) };\n case \"thinking\":\n return { kind: \"reasoning\", text: str(block.thinking), signature: str(block.signature) };\n case \"redacted_thinking\":\n return { kind: \"reasoning\", text: \"\", redacted: str(block.data) };\n case \"tool_use\":\n return { kind: \"tool_input\", text: \"\", callId: str(block.id), name: str(block.name), startInput: block.input };\n default:\n return undefined;\n }\n }\n\n #blockDelta(data: Json): ModelEvent[] {\n const index = typeof data.index === \"number\" ? data.index : -1;\n const open = this.#open.get(index);\n const delta = isObject(data.delta) ? data.delta : {};\n if (open === undefined) return [];\n if (delta.type === \"signature_delta\") {\n open.signature = (open.signature ?? \"\") + str(delta.signature);\n return [];\n }\n const text = str(\n delta.type === \"thinking_delta\"\n ? delta.thinking\n : delta.type === \"input_json_delta\"\n ? delta.partial_json\n : delta.text,\n );\n const fits =\n (open.kind === \"text\" && delta.type === \"text_delta\") ||\n (open.kind === \"reasoning\" && delta.type === \"thinking_delta\") ||\n (open.kind === \"tool_input\" && delta.type === \"input_json_delta\");\n // An empty delta adds nothing; a citations delta or another kind of delta has no place in this transcript.\n if (!fits || text === \"\") return [];\n open.text += text;\n return [{ type: `${open.kind}_delta`, index, delta: text }];\n }\n\n #blockStop(data: Json): ModelEvent[] {\n return typeof data.index === \"number\" ? this.#close(data.index) : [];\n }\n\n #close(index: number): ModelEvent[] {\n const open = this.#open.get(index);\n if (open === undefined) return [];\n this.#open.delete(index);\n const block = this.#finish(open);\n this.#closed.set(index, block);\n return [{ type: `${open.kind}_end`, index, block }];\n }\n\n #finish(open: OpenBlock): ContentBlock {\n if (open.kind === \"text\") return { type: \"text\", text: open.text };\n if (open.kind === \"tool_input\") {\n const wire = open.name ?? \"\";\n return {\n type: \"tool_call\",\n callId: open.callId ?? \"\",\n name: this.#names.restore(wire) ?? wire,\n input: parseToolInput(open.text, open.startInput ?? {}),\n };\n }\n const value = open.redacted === undefined ? open.signature : `${REDACTED_THINKING_PREFIX}${open.redacted}`;\n const { api, provider, id } = this.#model;\n return value\n ? { type: \"reasoning\", text: open.text, signature: { api, provider, model: id, value } }\n : { type: \"reasoning\", text: open.text };\n }\n\n #messageDelta(data: Json): ModelEvent[] {\n const delta = isObject(data.delta) ? data.delta : {};\n if (typeof delta.stop_reason === \"string\") this.#stopReason = delta.stop_reason;\n if (delta.stop_details !== undefined) this.#stopDetails = delta.stop_details;\n if (isObject(data.usage)) {\n this.#usageSeen = true;\n if (typeof data.usage.output_tokens === \"number\") this.#finalUsageSeen = true;\n }\n this.#usage = mergeUsage(this.#usage, data.usage);\n return this.#transformationWarnings(data.input_transformations ?? delta.input_transformations);\n }\n\n #messageStop(): ModelEvent[] {\n // The output limit can end a stream with a block still open; the block ends here with what arrived.\n const closing = [...this.#open.keys()].sort((a, b) => a - b).flatMap((index) => this.#close(index));\n return [...closing, ...this.#terminal()];\n }\n\n #terminal(): ModelEvent[] {\n // A finished reply always needs the final count, even one that streamed no content block.\n const { content } = this.partial();\n const usage = this.#usageWith(true);\n if (this.#stopReason === \"refusal\") {\n const details = isObject(this.#stopDetails) ? this.#stopDetails : {};\n const category = str(details.category) || \"no category\";\n const message = `refusal (${category}): ${str(details.explanation) || \"the model declined the request\"}`;\n // No `type`: failureEvent prefixes the type to the message, which already starts with \"refusal\".\n return [failureEvent(this.#model, { message, kind: \"fatal\" }, { content, usage })];\n }\n const stopReason = STOP_REASONS[this.#stopReason] ?? \"stop\";\n const warnings: Warning[] =\n this.#stopReason === \"pause_turn\"\n ? [\n {\n type: \"warning\",\n code: \"pause_turn\",\n message:\n \"The provider paused a long-running server-tool turn. This adapter dropped the turn's server-tool \" +\n \"blocks, so it cannot resume the paused turn; the reply holds only the content before the pause.\",\n },\n ]\n : [];\n return [...warnings, { type: \"done\", message: terminalMessage(this.#model, { content, usage }, stopReason) }];\n }\n}\n"]}
@@ -11,13 +11,20 @@
11
11
  * retryable. `context_length_exceeded`, which the fixtures use for
12
12
  * an over-long prompt, is not on that page, so its wording is unverified; the classifier also matches the phrase
13
13
  * "maximum context".
14
+ *
15
+ * A 429 for a temporary rate limit and a 503 for an overloaded model may carry `Retry-After`, "the minimum number of
16
+ * seconds to wait before retrying" (Rate limits, https://developers.openai.com/api/docs/guides/rate-limits, as of
17
+ * November 2026). The adapter puts the hint on the error as `retryAfterMs`.
14
18
  */
15
19
  import type { ModelEvent } from "../../spec.js";
16
20
  import type { ModelRef } from "../../types.js";
17
21
  import { type PartialReply, type WireFailure } from "../wire.js";
18
22
  /** Reads an error object, from an HTTP error body or an error chunk in a stream. */
19
23
  export declare function failureFrom(body: unknown, status: number | undefined, fallback: string): WireFailure;
20
- /** Reads a failed HTTP response's error body; a body that is not JSON keeps its text as the message. */
24
+ /**
25
+ * Reads a failed HTTP response's error body and its retry-after hint; a body that is not JSON keeps its text as the
26
+ * message.
27
+ */
21
28
  export declare function failureFromResponse(response: Response): Promise<WireFailure>;
22
29
  /** The `error` terminal for a failure, with any partial content and usage the attempt reached. */
23
30
  export declare function failureEvent(model: ModelRef, failure: WireFailure, partial?: PartialReply): Extract<ModelEvent, {
@@ -1,4 +1,4 @@
1
- import { failureTerminal, isObject, readErrorBody } from "../wire.js";
1
+ import { failureTerminal, isObject, readErrorBody, retryAfterMs, } from "../wire.js";
2
2
  // The HTTP status each error type stands for, so a stream error, which has no status, classifies like the HTTP error
3
3
  // it would have been. A type not listed here classifies as a failure in transit, which is retryable.
4
4
  const STATUS_OF_TYPE = {
@@ -21,10 +21,17 @@ export function failureFrom(body, status, fallback) {
21
21
  message: typeof error?.message === "string" && error.message !== "" ? error.message : fallback,
22
22
  };
23
23
  }
24
- /** Reads a failed HTTP response's error body; a body that is not JSON keeps its text as the message. */
24
+ /**
25
+ * Reads a failed HTTP response's error body and its retry-after hint; a body that is not JSON keeps its text as the
26
+ * message.
27
+ */
25
28
  export async function failureFromResponse(response) {
26
29
  const { body, text } = await readErrorBody(response);
27
- return failureFrom(body, response.status, text || `HTTP ${response.status}`);
30
+ const wait = retryAfterMs(response.headers);
31
+ return {
32
+ ...failureFrom(body, response.status, text || `HTTP ${response.status}`),
33
+ ...(wait === undefined ? {} : { retryAfterMs: wait }),
34
+ };
28
35
  }
29
36
  /** The `error` terminal for a failure, with any partial content and usage the attempt reached. */
30
37
  export function failureEvent(model, failure, partial = {}) {
@@ -1 +1 @@
1
- {"version":3,"file":"failure.js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AC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ;KAC/F,CAAC;AACJ,CAAC;AAED,wGAAwG;AACxG,MAAM,CAAC,KAAK,UAAU,mBAAmB,CAAC,QAAkB;IAC1D,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,MAAM,aAAa,CAAC,QAAQ,CAAC,CAAC;IACrD,OAAO,WAAW,CAAC,IAAI,EAAE,QAAQ,CAAC,MAAM,EAAE,IAAI,IAAI,QAAQ,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;AAC/E,CAAC;AAED,kGAAkG;AAClG,MAAM,UAAU,YAAY,CAC1B,KAAe,EACf,OAAoB,EACpB,OAAO,GAAiB,EAAE;IAE1B,OAAO,eAAe,CAAC,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,OAAO,CAAC,CAAC;AAClE,CAAC","sourcesContent":["/**\n * Failed requests and streams, as `error` terminals. A failed response's body is\n * `{ \"error\": { \"message\", \"type\", \"param\", \"code\" } }`, as openai-node v7.49.0 reads it (`src/core/error.ts`). A\n * stream that already returned 200 reports a later error as a chunk whose `error` field holds the same object, or as\n * an SSE event named `error` (`src/core/streaming.ts`); both as of November 2026.\n *\n * OpenAI sends billing, spend and usage limits as 429s, and retrying them \"won't restore API access\" (Error codes,\n * https://developers.openai.com/api/docs/guides/error-codes, as of November 2026). Their `code` names the cause, such\n * as `credit_balance_exhausted`, and their `type` can be `insufficient_quota`. `classifyError()` reads the code and\n * the type, so these are `quota` errors even at 429, while a 429 `rate_limit_error` such as `slow_down` stays\n * retryable. `context_length_exceeded`, which the fixtures use for\n * an over-long prompt, is not on that page, so its wording is unverified; the classifier also matches the phrase\n * \"maximum context\".\n */\nimport type { ModelEvent } from \"../../spec.js\";\nimport type { ModelRef } from \"../../types.js\";\nimport { failureTerminal, isObject, type PartialReply, readErrorBody, type WireFailure } from \"../wire.js\";\n\n// The HTTP status each error type stands for, so a stream error, which has no status, classifies like the HTTP error\n// it would have been. A type not listed here classifies as a failure in transit, which is retryable.\nconst STATUS_OF_TYPE: Readonly<Record<string, number>> = {\n invalid_request_error: 400,\n authentication_error: 401,\n permission_error: 403,\n not_found_error: 404,\n insufficient_quota: 429,\n rate_limit_error: 429,\n server_error: 500,\n service_unavailable_error: 503,\n};\n\n/** Reads an error object, from an HTTP error body or an error chunk in a stream. */\nexport function failureFrom(body: unknown, status: number | undefined, fallback: string): WireFailure {\n const error = isObject(body) && isObject(body.error) ? body.error : undefined;\n return {\n ...(status === undefined ? {} : { status }),\n ...(typeof error?.type === \"string\" && error.type !== \"\" ? { type: error.type } : {}),\n ...(typeof error?.code === \"string\" && error.code !== \"\" ? { errorCode: error.code } : {}),\n message: typeof error?.message === \"string\" && error.message !== \"\" ? error.message : fallback,\n };\n}\n\n/** Reads a failed HTTP response's error body; a body that is not JSON keeps its text as the message. */\nexport async function failureFromResponse(response: Response): Promise<WireFailure> {\n const { body, text } = await readErrorBody(response);\n return failureFrom(body, response.status, text || `HTTP ${response.status}`);\n}\n\n/** The `error` terminal for a failure, with any partial content and usage the attempt reached. */\nexport function failureEvent(\n model: ModelRef,\n failure: WireFailure,\n partial: PartialReply = {},\n): Extract<ModelEvent, { type: \"error\" }> {\n return failureTerminal(model, failure, STATUS_OF_TYPE, partial);\n}\n"]}
1
+ {"version":3,"file":"failure.js","sourceRoot":"","sources":["../../../src/adapters/openai-chat/failure.ts"],"names":[],"mappings":"AAoBA,OAAO,EACL,eAAe,EACf,QAAQ,EAER,aAAa,EACb,YAAY,GAEb,MAAM,YAAY,CAAC;AAEpB,qHAAqH;AACrH,qGAAqG;AACrG,MAAM,cAAc,GAAqC;IACvD,qBAAqB,EAAE,GAAG;IAC1B,oBAAoB,EAAE,GAAG;IACzB,gBAAgB,EAAE,GAAG;IACrB,eAAe,EAAE,GAAG;IACpB,kBAAkB,EAAE,GAAG;IACvB,gBAAgB,EAAE,GAAG;IACrB,YAAY,EAAE,GAAG;IACjB,yBAAyB,EAAE,GAAG;CAC/B,CAAC;AA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;QACxE,GAAG,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC;KACtD,CAAC;AACJ,CAAC;AAED,kGAAkG;AAClG,MAAM,UAAU,YAAY,CAC1B,KAAe,EACf,OAAoB,EACpB,OAAO,GAAiB,EAAE;IAE1B,OAAO,eAAe,CAAC,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,OAAO,CAAC,CAAC;AAClE,CAAC","sourcesContent":["/**\n * Failed requests and streams, as `error` terminals. A failed response's body is\n * `{ \"error\": { \"message\", \"type\", \"param\", \"code\" } }`, as openai-node v7.49.0 reads it (`src/core/error.ts`). A\n * stream that already returned 200 reports a later error as a chunk whose `error` field holds the same object, or as\n * an SSE event named `error` (`src/core/streaming.ts`); both as of November 2026.\n *\n * OpenAI sends billing, spend and usage limits as 429s, and retrying them \"won't restore API access\" (Error codes,\n * https://developers.openai.com/api/docs/guides/error-codes, as of November 2026). Their `code` names the cause, such\n * as `credit_balance_exhausted`, and their `type` can be `insufficient_quota`. `classifyError()` reads the code and\n * the type, so these are `quota` errors even at 429, while a 429 `rate_limit_error` such as `slow_down` stays\n * retryable. `context_length_exceeded`, which the fixtures use for\n * an over-long prompt, is not on that page, so its wording is unverified; the classifier also matches the phrase\n * \"maximum context\".\n *\n * A 429 for a temporary rate limit and a 503 for an overloaded model may carry `Retry-After`, \"the minimum number of\n * seconds to wait before retrying\" (Rate limits, https://developers.openai.com/api/docs/guides/rate-limits, as of\n * November 2026). The adapter puts the hint on the error as `retryAfterMs`.\n */\nimport type { ModelEvent } from \"../../spec.js\";\nimport type { ModelRef } from \"../../types.js\";\nimport {\n failureTerminal,\n isObject,\n type PartialReply,\n readErrorBody,\n retryAfterMs,\n type WireFailure,\n} from \"../wire.js\";\n\n// The HTTP status each error type stands for, so a stream error, which has no status, classifies like the HTTP error\n// it would have been. A type not listed here classifies as a failure in transit, which is retryable.\nconst STATUS_OF_TYPE: Readonly<Record<string, number>> = {\n invalid_request_error: 400,\n authentication_error: 401,\n permission_error: 403,\n not_found_error: 404,\n insufficient_quota: 429,\n rate_limit_error: 429,\n server_error: 500,\n service_unavailable_error: 503,\n};\n\n/** Reads an error object, from an HTTP error body or an error chunk in a stream. */\nexport function failureFrom(body: unknown, status: number | undefined, fallback: string): WireFailure {\n const error = isObject(body) && isObject(body.error) ? body.error : undefined;\n return {\n ...(status === undefined ? {} : { status }),\n ...(typeof error?.type === \"string\" && error.type !== \"\" ? { type: error.type } : {}),\n ...(typeof error?.code === \"string\" && error.code !== \"\" ? { errorCode: error.code } : {}),\n message: typeof error?.message === \"string\" && error.message !== \"\" ? error.message : fallback,\n };\n}\n\n/**\n * Reads a failed HTTP response's error body and its retry-after hint; a body that is not JSON keeps its text as the\n * message.\n */\nexport async function failureFromResponse(response: Response): Promise<WireFailure> {\n const { body, text } = await readErrorBody(response);\n const wait = retryAfterMs(response.headers);\n return {\n ...failureFrom(body, response.status, text || `HTTP ${response.status}`),\n ...(wait === undefined ? {} : { retryAfterMs: wait }),\n };\n}\n\n/** The `error` terminal for a failure, with any partial content and usage the attempt reached. */\nexport function failureEvent(\n model: ModelRef,\n failure: WireFailure,\n partial: PartialReply = {},\n): Extract<ModelEvent, { type: \"error\" }> {\n return failureTerminal(model, failure, STATUS_OF_TYPE, partial);\n}\n"]}
@@ -15,5 +15,8 @@
15
15
  * The usage object holds token counts only, so a reply carries no billed price and the cost comes from the catalog.
16
16
  */
17
17
  import type { Usage } from "../../types.js";
18
- /** The gateway's `Usage` for a Chat Completions usage object; a reply without one reports zero tokens. */
18
+ /**
19
+ * The gateway's `Usage` for a Chat Completions usage object. A reply without one, from a server that ignores
20
+ * `stream_options.include_usage` or a stream that ended before its usage chunk, has `unreported` usage.
21
+ */
19
22
  export declare function openaiUsage(raw: unknown): Usage;
@@ -1,9 +1,12 @@
1
- import { emptyUsage } from "../../usage.js";
1
+ import { unreportedUsage } from "../../usage.js";
2
2
  import { count, isObject } from "../wire.js";
3
- /** The gateway's `Usage` for a Chat Completions usage object; a reply without one reports zero tokens. */
3
+ /**
4
+ * The gateway's `Usage` for a Chat Completions usage object. A reply without one, from a server that ignores
5
+ * `stream_options.include_usage` or a stream that ended before its usage chunk, has `unreported` usage.
6
+ */
4
7
  export function openaiUsage(raw) {
5
8
  if (!isObject(raw))
6
- return emptyUsage(raw ?? null);
9
+ return unreportedUsage(raw ?? null);
7
10
  const prompt = isObject(raw.prompt_tokens_details) ? raw.prompt_tokens_details : {};
8
11
  const completion = isObject(raw.completion_tokens_details) ? raw.completion_tokens_details : {};
9
12
  const cacheRead = count(prompt.cached_tokens);
@@ -1 +1 @@
1
- {"version":3,"file":"usage.js","sourceRoot":"","sources":["../../../src/adapters/openai-chat/usage.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE7C,0GAA0G;AAC1G,MAAM,UAAU,WAAW,CAAC,GAAY;IACtC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,OAAO,UAAU,CAAC,GAAG,IAAI,IAAI,CAAC,CAAC;IACnD,MAAM,MAAM,GAAG,QAAQ,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC,CAAC,EAAE,CAAC;IACpF,MAAM,UAAU,GAAG,QAAQ,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC,CAAC,EAAE,CAAC;IAChG,MAAM,SAAS,GAAG,KAAK,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;IAC9C,MAAM,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,kBAAkB,CAAC,CAAC;IACjD,MAAM,MAAM,GAAG,KAAK,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;IAC5C,OAAO;QACL,aAAa,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,aAAa,CAAC,GAAG,SAAS,GAAG,OAAO,CAAC;QAC1E,SAAS;QACT,UAAU,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,EAAE;QACtC,MAAM;QACN,yFAAyF;QACzF,SAAS,EAAE,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;QAC/D,GAAG;KACJ,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Maps a Chat Completions `usage` object into the gateway's four token classes (D3), from the `usage` of a chat\n * completion (https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create) and\n * the Prompt caching guide (https://developers.openai.com/api/docs/guides/prompt-caching), both as of November 2026:\n *\n * - `prompt_tokens` counts the whole prompt. `prompt_tokens_details.cached_tokens` counts billed cache reads, which\n * exclude the tokens charged as writes, and `cache_write_tokens` the prompt tokens written to cache. The guide\n * computes ordinary input as the input tokens less both, and so does the adapter.\n * - Chat Completions writes only 30-minute cache entries, so every write counts under `Usage.cacheWrite[\"5m\"]`, the\n * key for the short cache-write rate; an OpenAI catalog entry stores its 30-minute rate there.\n * - `completion_tokens` is the output, and `completion_tokens_details.reasoning_tokens` the part of it spent on\n * reasoning: `max_completion_tokens` bounds \"visible output tokens and reasoning tokens\" together, and the\n * reference says rejected prediction tokens are, \"like reasoning tokens\", counted in the completion tokens for billing.\n *\n * The usage object holds token counts only, so a reply carries no billed price and the cost comes from the catalog.\n */\nimport type { Usage } from \"../../types.js\";\nimport { emptyUsage } from \"../../usage.js\";\nimport { count, isObject } from \"../wire.js\";\n\n/** The gateway's `Usage` for a Chat Completions usage object; a reply without one reports zero tokens. */\nexport function openaiUsage(raw: unknown): Usage {\n if (!isObject(raw)) return emptyUsage(raw ?? null);\n const prompt = isObject(raw.prompt_tokens_details) ? raw.prompt_tokens_details : {};\n const completion = isObject(raw.completion_tokens_details) ? raw.completion_tokens_details : {};\n const cacheRead = count(prompt.cached_tokens);\n const written = count(prompt.cache_write_tokens);\n const output = count(raw.completion_tokens);\n return {\n uncachedInput: Math.max(0, count(raw.prompt_tokens) - cacheRead - written),\n cacheRead,\n cacheWrite: { \"5m\": written, \"1h\": 0 },\n output,\n // Reasoning is a part of output; the cap keeps that true for a server that reports more.\n reasoning: Math.min(count(completion.reasoning_tokens), output),\n raw,\n };\n}\n"]}
1
+ {"version":3,"file":"usage.js","sourceRoot":"","sources":["../../../src/adapters/openai-chat/usage.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE7C;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,GAAY;IACtC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,OAAO,eAAe,CAAC,GAAG,IAAI,IAAI,CAAC,CAAC;IACxD,MAAM,MAAM,GAAG,QAAQ,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC,CAAC,EAAE,CAAC;IACpF,MAAM,UAAU,GAAG,QAAQ,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC,CAAC,EAAE,CAAC;IAChG,MAAM,SAAS,GAAG,KAAK,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;IAC9C,MAAM,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,kBAAkB,CAAC,CAAC;IACjD,MAAM,MAAM,GAAG,KAAK,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;IAC5C,OAAO;QACL,aAAa,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,aAAa,CAAC,GAAG,SAAS,GAAG,OAAO,CAAC;QAC1E,SAAS;QACT,UAAU,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,EAAE;QACtC,MAAM;QACN,yFAAyF;QACzF,SAAS,EAAE,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;QAC/D,GAAG;KACJ,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Maps a Chat Completions `usage` object into the gateway's four token classes (D3), from the `usage` of a chat\n * completion (https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create) and\n * the Prompt caching guide (https://developers.openai.com/api/docs/guides/prompt-caching), both as of November 2026:\n *\n * - `prompt_tokens` counts the whole prompt. `prompt_tokens_details.cached_tokens` counts billed cache reads, which\n * exclude the tokens charged as writes, and `cache_write_tokens` the prompt tokens written to cache. The guide\n * computes ordinary input as the input tokens less both, and so does the adapter.\n * - Chat Completions writes only 30-minute cache entries, so every write counts under `Usage.cacheWrite[\"5m\"]`, the\n * key for the short cache-write rate; an OpenAI catalog entry stores its 30-minute rate there.\n * - `completion_tokens` is the output, and `completion_tokens_details.reasoning_tokens` the part of it spent on\n * reasoning: `max_completion_tokens` bounds \"visible output tokens and reasoning tokens\" together, and the\n * reference says rejected prediction tokens are, \"like reasoning tokens\", counted in the completion tokens for billing.\n *\n * The usage object holds token counts only, so a reply carries no billed price and the cost comes from the catalog.\n */\nimport type { Usage } from \"../../types.js\";\nimport { unreportedUsage } from \"../../usage.js\";\nimport { count, isObject } from \"../wire.js\";\n\n/**\n * The gateway's `Usage` for a Chat Completions usage object. A reply without one, from a server that ignores\n * `stream_options.include_usage` or a stream that ended before its usage chunk, has `unreported` usage.\n */\nexport function openaiUsage(raw: unknown): Usage {\n if (!isObject(raw)) return unreportedUsage(raw ?? null);\n const prompt = isObject(raw.prompt_tokens_details) ? raw.prompt_tokens_details : {};\n const completion = isObject(raw.completion_tokens_details) ? raw.completion_tokens_details : {};\n const cacheRead = count(prompt.cached_tokens);\n const written = count(prompt.cache_write_tokens);\n const output = count(raw.completion_tokens);\n return {\n uncachedInput: Math.max(0, count(raw.prompt_tokens) - cacheRead - written),\n cacheRead,\n cacheWrite: { \"5m\": written, \"1h\": 0 },\n output,\n // Reasoning is a part of output; the cap keeps that true for a server that reports more.\n reasoning: Math.min(count(completion.reasoning_tokens), output),\n raw,\n };\n}\n"]}
@@ -2,6 +2,10 @@
2
2
  * What every wire adapter shares: sending one HTTP request through the caller's transport, reading a server-sent
3
3
  * event stream to its terminal, and turning a failed request, a broken stream or an abort into an `error` terminal.
4
4
  * A failed model call never throws; only a guard's error or a `GatewayError` does.
5
+ *
6
+ * Usage: an attempt that ends without a usage report has `unreported` usage, so `createModel()` prices it as unknown.
7
+ * The one exception is an HTTP error response, which counts as zero tokens: the provider answered with an error
8
+ * instead of a reply, and its body reports no usage to read.
5
9
  */
6
10
  import { type ErrorKind } from "../classify.js";
7
11
  import type { Transport } from "../runtime-types.js";
@@ -25,6 +29,8 @@ export interface WireFailure {
25
29
  readonly message: string;
26
30
  /** Sets the kind outright, for a failure that no status describes, such as a refusal inside a 200 stream. */
27
31
  readonly kind?: ErrorKind;
32
+ /** How long the response's `retry-after-ms` or `retry-after` header asked the caller to wait, in milliseconds. */
33
+ readonly retryAfterMs?: number;
28
34
  }
29
35
  /** True for a JSON object, not an array or `null`. */
30
36
  export declare function isObject(value: unknown): value is Json;
@@ -34,7 +40,10 @@ export declare function str(value: unknown): string;
34
40
  export declare function count(value: unknown): number;
35
41
  /** A tool call's input: the parsed JSON, or the partial JSON text when the output limit cut it off. */
36
42
  export declare function parseToolInput(text: string, empty?: unknown): unknown;
37
- /** An assistant message with an unknown cost, which `createModel()` prices from the catalog. */
43
+ /**
44
+ * An assistant message with an unknown cost, which `createModel()` prices from the catalog. Without `partial.usage`,
45
+ * the provider reported no usage, so the message's usage is `unreported`.
46
+ */
38
47
  export declare function terminalMessage(model: ModelRef, partial: PartialReply, stopReason: AssistantMessage["stopReason"], error?: NonNullable<AssistantMessage["error"]>): AssistantMessage;
39
48
  /** The `error` terminal of an aborted call, which carries no `error`. */
40
49
  export declare function abortedEvent(model: ModelRef, partial?: PartialReply): Extract<ModelEvent, {
@@ -43,6 +52,7 @@ export declare function abortedEvent(model: ModelRef, partial?: PartialReply): E
43
52
  /**
44
53
  * The `error` terminal for a failure. A failure with no HTTP status, such as an error event inside a 200 stream,
45
54
  * classifies like the status its type stands for in `statusOfType`. The message starts with the error code or type.
55
+ * A failure with a status is an HTTP error response, so without `partial.usage` it reports zero tokens.
46
56
  */
47
57
  export declare function failureTerminal(model: ModelRef, failure: WireFailure, statusOfType: Readonly<Record<string, number>>, partial?: PartialReply, code?: ModelErrorCode): Extract<ModelEvent, {
48
58
  type: "error";
@@ -52,6 +62,17 @@ export declare function thrownTerminal(model: ModelRef, thrown: unknown, partial
52
62
  type: "error";
53
63
  message: AssistantMessage;
54
64
  };
65
+ /**
66
+ * How long a failed response asks the caller to wait before retrying, in milliseconds, or `undefined` when it gives
67
+ * no valid delay. `retry-after-ms` wins over `retry-after`, as in the official TypeScript SDKs (openai-node v7.49.0
68
+ * and anthropic-sdk-typescript v0.129.0, `src/client.ts`, as of November 2026). `retry-after` holds seconds, as
69
+ * Anthropic's and OpenAI's rate-limit pages say (https://platform.claude.com/docs/en/api/rate-limits and
70
+ * https://developers.openai.com/api/docs/guides/rate-limits, as of November 2026), or an HTTP date (RFC 9110,
71
+ * section 10.2.3). A date counts from the response's own `date` header, so the delay depends on no local clock, and
72
+ * a response without one gives no delay. Any other value, such as a negative number or the comma-joined values of a
73
+ * repeated header, gives no delay.
74
+ */
75
+ export declare function retryAfterMs(headers: Headers): number | undefined;
55
76
  /** A failed response's body, parsed as JSON when it is JSON, and its text. */
56
77
  export declare function readErrorBody(response: Response): Promise<{
57
78
  body: unknown;