@buildanagent/gateway 0.0.0-stage → 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.
Files changed (126) hide show
  1. package/LICENSE +52 -0
  2. package/LICENSE-APACHE +202 -0
  3. package/LICENSE-MIT +21 -0
  4. package/README.md +305 -2
  5. package/dist/adapters/anthropic/adapter.d.ts +25 -0
  6. package/dist/adapters/anthropic/adapter.js +183 -0
  7. package/dist/adapters/anthropic/adapter.js.map +1 -0
  8. package/dist/adapters/anthropic/failure.d.ts +27 -0
  9. package/dist/adapters/anthropic/failure.js +53 -0
  10. package/dist/adapters/anthropic/failure.js.map +1 -0
  11. package/dist/adapters/anthropic/index.d.ts +3 -0
  12. package/dist/adapters/anthropic/index.js +3 -0
  13. package/dist/adapters/anthropic/index.js.map +1 -0
  14. package/dist/adapters/anthropic/request.d.ts +53 -0
  15. package/dist/adapters/anthropic/request.js +250 -0
  16. package/dist/adapters/anthropic/request.js.map +1 -0
  17. package/dist/adapters/anthropic/response.d.ts +38 -0
  18. package/dist/adapters/anthropic/response.js +237 -0
  19. package/dist/adapters/anthropic/response.js.map +1 -0
  20. package/dist/adapters/anthropic/usage.d.ts +26 -0
  21. package/dist/adapters/anthropic/usage.js +39 -0
  22. package/dist/adapters/anthropic/usage.js.map +1 -0
  23. package/dist/adapters/openai-chat/adapter.d.ts +18 -0
  24. package/dist/adapters/openai-chat/adapter.js +86 -0
  25. package/dist/adapters/openai-chat/adapter.js.map +1 -0
  26. package/dist/adapters/openai-chat/compat.d.ts +58 -0
  27. package/dist/adapters/openai-chat/compat.js +19 -0
  28. package/dist/adapters/openai-chat/compat.js.map +1 -0
  29. package/dist/adapters/openai-chat/failure.d.ts +32 -0
  30. package/dist/adapters/openai-chat/failure.js +40 -0
  31. package/dist/adapters/openai-chat/failure.js.map +1 -0
  32. package/dist/adapters/openai-chat/index.d.ts +4 -0
  33. package/dist/adapters/openai-chat/index.js +3 -0
  34. package/dist/adapters/openai-chat/index.js.map +1 -0
  35. package/dist/adapters/openai-chat/request.d.ts +47 -0
  36. package/dist/adapters/openai-chat/request.js +227 -0
  37. package/dist/adapters/openai-chat/request.js.map +1 -0
  38. package/dist/adapters/openai-chat/response.d.ts +22 -0
  39. package/dist/adapters/openai-chat/response.js +203 -0
  40. package/dist/adapters/openai-chat/response.js.map +1 -0
  41. package/dist/adapters/openai-chat/usage.d.ts +22 -0
  42. package/dist/adapters/openai-chat/usage.js +25 -0
  43. package/dist/adapters/openai-chat/usage.js.map +1 -0
  44. package/dist/adapters/strict-schema.d.ts +67 -0
  45. package/dist/adapters/strict-schema.js +269 -0
  46. package/dist/adapters/strict-schema.js.map +1 -0
  47. package/dist/adapters/wire.d.ts +98 -0
  48. package/dist/adapters/wire.js +187 -0
  49. package/dist/adapters/wire.js.map +1 -0
  50. package/dist/catalog.d.ts +65 -0
  51. package/dist/catalog.js +145 -0
  52. package/dist/catalog.js.map +1 -0
  53. package/dist/catalog.json +120 -0
  54. package/dist/classify.d.ts +25 -0
  55. package/dist/classify.js +37 -0
  56. package/dist/classify.js.map +1 -0
  57. package/dist/complete.d.ts +9 -0
  58. package/dist/complete.js +13 -0
  59. package/dist/complete.js.map +1 -0
  60. package/dist/cost.d.ts +44 -0
  61. package/dist/cost.js +132 -0
  62. package/dist/cost.js.map +1 -0
  63. package/dist/create-model.d.ts +7 -0
  64. package/dist/create-model.js +81 -0
  65. package/dist/create-model.js.map +1 -0
  66. package/dist/errors.d.ts +17 -0
  67. package/dist/errors.js +24 -0
  68. package/dist/errors.js.map +1 -0
  69. package/dist/index.d.ts +19 -0
  70. package/dist/index.js +17 -0
  71. package/dist/index.js.map +1 -0
  72. package/dist/middleware.d.ts +11 -0
  73. package/dist/middleware.js +22 -0
  74. package/dist/middleware.js.map +1 -0
  75. package/dist/names.d.ts +72 -0
  76. package/dist/names.js +175 -0
  77. package/dist/names.js.map +1 -0
  78. package/dist/provider-config.d.ts +15 -0
  79. package/dist/provider-config.js +23 -0
  80. package/dist/provider-config.js.map +1 -0
  81. package/dist/request-dump.d.ts +28 -0
  82. package/dist/request-dump.js +52 -0
  83. package/dist/request-dump.js.map +1 -0
  84. package/dist/request-policy.d.ts +18 -0
  85. package/dist/request-policy.js +27 -0
  86. package/dist/request-policy.js.map +1 -0
  87. package/dist/retry.d.ts +33 -0
  88. package/dist/retry.js +219 -0
  89. package/dist/retry.js.map +1 -0
  90. package/dist/runtime-types.d.ts +112 -0
  91. package/dist/runtime-types.js +2 -0
  92. package/dist/runtime-types.js.map +1 -0
  93. package/dist/spec.d.ts +67 -0
  94. package/dist/spec.js +2 -0
  95. package/dist/spec.js.map +1 -0
  96. package/dist/sse.d.ts +15 -0
  97. package/dist/sse.js +73 -0
  98. package/dist/sse.js.map +1 -0
  99. package/dist/stream-contract.d.ts +23 -0
  100. package/dist/stream-contract.js +101 -0
  101. package/dist/stream-contract.js.map +1 -0
  102. package/dist/testing/guards.d.ts +16 -0
  103. package/dist/testing/guards.js +48 -0
  104. package/dist/testing/guards.js.map +1 -0
  105. package/dist/testing/index.d.ts +12 -0
  106. package/dist/testing/index.js +13 -0
  107. package/dist/testing/index.js.map +1 -0
  108. package/dist/testing/mock-transport.d.ts +49 -0
  109. package/dist/testing/mock-transport.js +101 -0
  110. package/dist/testing/mock-transport.js.map +1 -0
  111. package/dist/testing/random.d.ts +3 -0
  112. package/dist/testing/random.js +13 -0
  113. package/dist/testing/random.js.map +1 -0
  114. package/dist/testing/setup.d.ts +1 -0
  115. package/dist/testing/setup.js +12 -0
  116. package/dist/testing/setup.js.map +1 -0
  117. package/dist/transform-messages.d.ts +32 -0
  118. package/dist/transform-messages.js +291 -0
  119. package/dist/transform-messages.js.map +1 -0
  120. package/dist/types.d.ts +143 -0
  121. package/dist/types.js +6 -0
  122. package/dist/types.js.map +1 -0
  123. package/dist/usage.d.ts +16 -0
  124. package/dist/usage.js +31 -0
  125. package/dist/usage.js.map +1 -0
  126. package/package.json +50 -3
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Maps Anthropic's `usage` object into the gateway's four token classes (D3), from the Messages API reference's
3
+ * `Usage` and `MessageDeltaUsage` (https://platform.claude.com/docs/en/api/messages/create, as of November 2026):
4
+ *
5
+ * - `input_tokens` is the uncached input: the reference says total input is the sum of `input_tokens`,
6
+ * `cache_creation_input_tokens` and `cache_read_input_tokens`.
7
+ * - `cache_creation.ephemeral_5m_input_tokens` and `ephemeral_1h_input_tokens` split the cache writes by TTL.
8
+ * - `output_tokens` is "the inclusive, authoritative total used for billing", and
9
+ * `output_tokens_details.thinking_tokens` is the part spent on reasoning, "always ≤ `output_tokens`". When
10
+ * streaming, the breakdown arrives only on the final `message_delta` (Extended thinking,
11
+ * https://platform.claude.com/docs/en/build-with-claude/extended-thinking, as of November 2026).
12
+ *
13
+ * The response carries no billed price, so the cost always comes from the catalog.
14
+ */
15
+ import type { Usage } from "../../types.js";
16
+ import { type Json } from "../wire.js";
17
+ /**
18
+ * Overlays a later usage report on an earlier one. A `message_delta`'s counts are cumulative, and a field it sends
19
+ * as `null` or leaves out keeps the earlier value, so the `message_start` split of cache writes survives.
20
+ */
21
+ export declare function mergeUsage(earlier: Json, later: unknown): Json;
22
+ /**
23
+ * The gateway's `Usage` for an Anthropic usage object. Cache writes reported without their TTL split count as
24
+ * `fallbackTtl`, the TTL the request asked for.
25
+ */
26
+ export declare function anthropicUsage(raw: Json, fallbackTtl: "5m" | "1h"): Usage;
@@ -0,0 +1,39 @@
1
+ import { count, isObject } from "../wire.js";
2
+ /**
3
+ * Overlays a later usage report on an earlier one. A `message_delta`'s counts are cumulative, and a field it sends
4
+ * as `null` or leaves out keeps the earlier value, so the `message_start` split of cache writes survives.
5
+ */
6
+ export function mergeUsage(earlier, later) {
7
+ if (!isObject(later))
8
+ return earlier;
9
+ const merged = { ...earlier };
10
+ for (const [key, value] of Object.entries(later)) {
11
+ if (value === null || value === undefined)
12
+ continue;
13
+ merged[key] = isObject(value) && isObject(earlier[key]) ? { ...earlier[key], ...value } : value;
14
+ }
15
+ return merged;
16
+ }
17
+ /**
18
+ * The gateway's `Usage` for an Anthropic usage object. Cache writes reported without their TTL split count as
19
+ * `fallbackTtl`, the TTL the request asked for.
20
+ */
21
+ export function anthropicUsage(raw, fallbackTtl) {
22
+ const split = isObject(raw.cache_creation) ? raw.cache_creation : undefined;
23
+ const written = count(raw.cache_creation_input_tokens);
24
+ const cacheWrite = split
25
+ ? { "5m": count(split.ephemeral_5m_input_tokens), "1h": count(split.ephemeral_1h_input_tokens) }
26
+ : { "5m": fallbackTtl === "5m" ? written : 0, "1h": fallbackTtl === "1h" ? written : 0 };
27
+ const output = count(raw.output_tokens);
28
+ const details = isObject(raw.output_tokens_details) ? raw.output_tokens_details : {};
29
+ return {
30
+ uncachedInput: count(raw.input_tokens),
31
+ cacheRead: count(raw.cache_read_input_tokens),
32
+ cacheWrite,
33
+ output,
34
+ // Reasoning is a part of output; the reference guarantees it never exceeds it, and the cap keeps that true.
35
+ reasoning: Math.min(count(details.thinking_tokens), output),
36
+ raw,
37
+ };
38
+ }
39
+ //# sourceMappingURL=usage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage.js","sourceRoot":"","sources":["../../../src/adapters/anthropic/usage.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAa,MAAM,YAAY,CAAC;AAExD;;;GAGG;AACH,MAAM,UAAU,UAAU,CAAC,OAAa,EAAE,KAAc;IACtD,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,OAAO,CAAC;IACrC,MAAM,MAAM,GAAS,EAAE,GAAG,OAAO,EAAE,CAAC;IACpC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACjD,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS;YAAE,SAAS;QACpD,MAAM,CAAC,GAAG,CAAC,GAAG,QAAQ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I,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;QAC3D,GAAG;KACJ,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Maps Anthropic's `usage` object into the gateway's four token classes (D3), from the Messages API reference's\n * `Usage` and `MessageDeltaUsage` (https://platform.claude.com/docs/en/api/messages/create, as of November 2026):\n *\n * - `input_tokens` is the uncached input: the reference says total input is the sum of `input_tokens`,\n * `cache_creation_input_tokens` and `cache_read_input_tokens`.\n * - `cache_creation.ephemeral_5m_input_tokens` and `ephemeral_1h_input_tokens` split the cache writes by TTL.\n * - `output_tokens` is \"the inclusive, authoritative total used for billing\", and\n * `output_tokens_details.thinking_tokens` is the part spent on reasoning, \"always ≤ `output_tokens`\". When\n * streaming, the breakdown arrives only on the final `message_delta` (Extended thinking,\n * https://platform.claude.com/docs/en/build-with-claude/extended-thinking, as of November 2026).\n *\n * The response carries no billed price, so the cost always comes from the catalog.\n */\nimport type { Usage } from \"../../types.js\";\nimport { count, isObject, type Json } from \"../wire.js\";\n\n/**\n * Overlays a later usage report on an earlier one. A `message_delta`'s counts are cumulative, and a field it sends\n * as `null` or leaves out keeps the earlier value, so the `message_start` split of cache writes survives.\n */\nexport function mergeUsage(earlier: Json, later: unknown): Json {\n if (!isObject(later)) return earlier;\n const merged: Json = { ...earlier };\n for (const [key, value] of Object.entries(later)) {\n if (value === null || value === undefined) continue;\n merged[key] = isObject(value) && isObject(earlier[key]) ? { ...(earlier[key] as Json), ...value } : value;\n }\n return merged;\n}\n\n/**\n * The gateway's `Usage` for an Anthropic usage object. Cache writes reported without their TTL split count as\n * `fallbackTtl`, the TTL the request asked for.\n */\nexport function anthropicUsage(raw: Json, fallbackTtl: \"5m\" | \"1h\"): Usage {\n const split = isObject(raw.cache_creation) ? raw.cache_creation : undefined;\n const written = count(raw.cache_creation_input_tokens);\n const cacheWrite = split\n ? { \"5m\": count(split.ephemeral_5m_input_tokens), \"1h\": count(split.ephemeral_1h_input_tokens) }\n : { \"5m\": fallbackTtl === \"5m\" ? written : 0, \"1h\": fallbackTtl === \"1h\" ? written : 0 };\n const output = count(raw.output_tokens);\n const details = isObject(raw.output_tokens_details) ? raw.output_tokens_details : {};\n return {\n uncachedInput: count(raw.input_tokens),\n cacheRead: count(raw.cache_read_input_tokens),\n cacheWrite,\n output,\n // Reasoning is a part of output; the reference guarantees it never exceeds it, and the cap keeps that true.\n reasoning: Math.min(count(details.thinking_tokens), output),\n raw,\n };\n}\n"]}
@@ -0,0 +1,18 @@
1
+ import type { ModelAdapter } from "../../spec.js";
2
+ import { type OpenAIChatConfig } from "./compat.js";
3
+ /**
4
+ * Creates an adapter for OpenAI's Chat Completions API or a server compatible with it. Every request goes to
5
+ * `{baseURL}/chat/completions` through `config.transport`, streams its response, and sends the key from
6
+ * `config.apiKey` as a bearer token; it is the only key the adapter sends. `baseURL` defaults to
7
+ * `https://api.openai.com/v1`. Throws a `GatewayError` with code `missing_api_key` when the key is missing or empty.
8
+ *
9
+ * The adapter reports the provider `config.provider`, `"openai"` by default, which is the name `createModel()` looks
10
+ * the model up under in the price catalog. `config.compat` sets the server's quirks for every model, and
11
+ * `config.modelCompat` for single models by id. The model's caps come from `options.caps`, which `createModel()`
12
+ * sets; a direct call without them uses `defaultCaps`, which send no images.
13
+ *
14
+ * Caller headers from `config.headers` are sent with lower-case names; a caller `authorization`, `api-key` or
15
+ * `x-api-key` is dropped. `providerOptions.openaiChat.extraBody` adds fields to the request body, such as
16
+ * `reasoning_effort`.
17
+ */
18
+ export declare function openaiChat(config: OpenAIChatConfig): ModelAdapter;
@@ -0,0 +1,86 @@
1
+ /**
2
+ * `openaiChat()`: the OpenAI-compatible Chat Completions adapter over the gateway's `Transport` (D2). It streams every
3
+ * call and posts to `{baseURL}/chat/completions` with `Authorization: Bearer <apiKey>`, as openai-node v7.49.0 does
4
+ * (`src/client.ts`, `src/resources/chat/completions/completions.ts`, as of November 2026). The quirks of other
5
+ * compatible servers come in through `ChatCompat` flags, per adapter or per model.
6
+ */
7
+ import { resolveProviderConfig } from "../../provider-config.js";
8
+ import { payloadOf, readEventStream, sendRequest } from "../wire.js";
9
+ import { compatFor } from "./compat.js";
10
+ import { failureEvent, failureFromResponse } from "./failure.js";
11
+ import { buildRequest } from "./request.js";
12
+ import { ChunkAssembler } from "./response.js";
13
+ const DEFAULT_BASE_URL = "https://api.openai.com/v1";
14
+ // The adapter's `defaultCaps`, for a model with no catalog entry. An unknown model behind a compatible server may
15
+ // read text only and may reject reasoning settings, so it is sent no images and asked for no reasoning.
16
+ const DEFAULT_CAPS = { contextWindow: 128_000, maxOutputTokens: 16_384, images: false, reasoning: false };
17
+ // Header names the adapter sets itself. A caller's key header is dropped, because `config.apiKey` is the only key
18
+ // the adapter sends.
19
+ const CALLER_HEADERS_DROPPED = new Set(["authorization", "api-key", "x-api-key"]);
20
+ function callerHeaders(headers) {
21
+ const rest = {};
22
+ for (const [name, value] of Object.entries(headers)) {
23
+ const lower = name.toLowerCase();
24
+ if (!CALLER_HEADERS_DROPPED.has(lower))
25
+ rest[lower] = value;
26
+ }
27
+ return rest;
28
+ }
29
+ function requestFor(config, body, signal) {
30
+ const headers = {
31
+ ...callerHeaders(config.headers),
32
+ "content-type": "application/json",
33
+ accept: "text/event-stream",
34
+ authorization: `Bearer ${config.apiKey}`,
35
+ };
36
+ const url = `${config.baseURL.replace(/\/+$/, "")}/chat/completions`;
37
+ return new Request(url, { method: "POST", headers, body: JSON.stringify(body), ...(signal ? { signal } : {}) });
38
+ }
39
+ async function* streamCompletion(settings, resolved, model, context, options) {
40
+ yield { type: "start" };
41
+ const plan = buildRequest(model, context, options, options.caps ?? DEFAULT_CAPS, compatFor(settings, model.id));
42
+ // Each attempt warns again; the gateway's retries stream a repeated warning only once per call.
43
+ yield* plan.warnings;
44
+ const request = requestFor(resolved, payloadOf(plan.body, options), options.signal);
45
+ const response = yield* sendRequest(resolved.transport, request, model, options.signal);
46
+ if (response === undefined)
47
+ return;
48
+ if (!response.ok) {
49
+ yield failureEvent(model, await failureFromResponse(response));
50
+ return;
51
+ }
52
+ yield* readEventStream(response, model, new ChunkAssembler(model, plan), options.signal);
53
+ }
54
+ /**
55
+ * Creates an adapter for OpenAI's Chat Completions API or a server compatible with it. Every request goes to
56
+ * `{baseURL}/chat/completions` through `config.transport`, streams its response, and sends the key from
57
+ * `config.apiKey` as a bearer token; it is the only key the adapter sends. `baseURL` defaults to
58
+ * `https://api.openai.com/v1`. Throws a `GatewayError` with code `missing_api_key` when the key is missing or empty.
59
+ *
60
+ * The adapter reports the provider `config.provider`, `"openai"` by default, which is the name `createModel()` looks
61
+ * the model up under in the price catalog. `config.compat` sets the server's quirks for every model, and
62
+ * `config.modelCompat` for single models by id. The model's caps come from `options.caps`, which `createModel()`
63
+ * sets; a direct call without them uses `defaultCaps`, which send no images.
64
+ *
65
+ * Caller headers from `config.headers` are sent with lower-case names; a caller `authorization`, `api-key` or
66
+ * `x-api-key` is dropped. `providerOptions.openaiChat.extraBody` adds fields to the request body, such as
67
+ * `reasoning_effort`.
68
+ */
69
+ export function openaiChat(config) {
70
+ const resolved = resolveProviderConfig(config, { baseURL: DEFAULT_BASE_URL });
71
+ // Copied, so a caller who changes the objects later does not change the adapter's requests.
72
+ const settings = {
73
+ ...(config.compat ? { compat: { ...config.compat } } : {}),
74
+ ...(config.modelCompat
75
+ ? { modelCompat: Object.fromEntries(Object.entries(config.modelCompat).map(([id, own]) => [id, { ...own }])) }
76
+ : {}),
77
+ };
78
+ return {
79
+ specificationVersion: "v1",
80
+ api: "openai-chat",
81
+ provider: config.provider ?? "openai",
82
+ defaultCaps: DEFAULT_CAPS,
83
+ stream: (model, context, options) => streamCompletion(settings, resolved, model, context, options),
84
+ };
85
+ }
86
+ //# sourceMappingURL=adapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.js","sourceRoot":"","sources":["../../../src/adapters/openai-chat/adapter.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAA+B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O;IACT,CAAC;IACD,KAAK,CAAC,CAAC,eAAe,CAAC,QAAQ,EAAE,KAAK,EAAE,IAAI,cAAc,CAAC,KAAK,EAAE,IAAI,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;AAC3F,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,UAAU,CAAC,MAAwB;IACjD,MAAM,QAAQ,GAAG,qBAAqB,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,gBAAgB,EAAE,CAAC,CAAC;IAC9E,4FAA4F;IAC5F,MAAM,QAAQ,GAAmB;QAC/B,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,GAAG,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC1D,GAAG,CAAC,MAAM,CAAC,WAAW;YACpB,CAAC,CAAC,EAAE,WAAW,EAAE,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,GAAG,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE;YAC9G,CAAC,CAAC,EAAE,CAAC;KACR,CAAC;IACF,OAAO;QACL,oBAAoB,EAAE,IAAI;QAC1B,GAAG,EAAE,aAAa;QAClB,QAAQ,EAAE,MAAM,CAAC,QAAQ,IAAI,QAAQ;QACrC,WAAW,EAAE,YAAY;QACzB,MAAM,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC;KACnG,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `openaiChat()`: the OpenAI-compatible Chat Completions adapter over the gateway's `Transport` (D2). It streams every\n * call and posts to `{baseURL}/chat/completions` with `Authorization: Bearer <apiKey>`, as openai-node v7.49.0 does\n * (`src/client.ts`, `src/resources/chat/completions/completions.ts`, as of November 2026). The quirks of other\n * compatible servers come in through `ChatCompat` flags, per adapter or per model.\n */\nimport { type ResolvedProviderConfig, resolveProviderConfig } from \"../../provider-config.js\";\nimport type { ModelAdapter, ModelEvent, StreamOptions } from \"../../spec.js\";\nimport type { ModelCaps, ModelContext, ModelRef } from \"../../types.js\";\nimport { payloadOf, readEventStream, sendRequest } from \"../wire.js\";\nimport { type CompatSettings, compatFor, type OpenAIChatConfig } from \"./compat.js\";\nimport { failureEvent, failureFromResponse } from \"./failure.js\";\nimport { buildRequest } from \"./request.js\";\nimport { ChunkAssembler } from \"./response.js\";\n\nconst DEFAULT_BASE_URL = \"https://api.openai.com/v1\";\n\n// The adapter's `defaultCaps`, for a model with no catalog entry. An unknown model behind a compatible server may\n// read text only and may reject reasoning settings, so it is sent no images and asked for no reasoning.\nconst DEFAULT_CAPS: ModelCaps = { contextWindow: 128_000, maxOutputTokens: 16_384, images: false, reasoning: false };\n\n// Header names the adapter sets itself. A caller's key header is dropped, because `config.apiKey` is the only key\n// the adapter sends.\nconst CALLER_HEADERS_DROPPED = new Set([\"authorization\", \"api-key\", \"x-api-key\"]);\n\nfunction callerHeaders(headers: Readonly<Record<string, string>>): Record<string, string> {\n const rest: Record<string, string> = {};\n for (const [name, value] of Object.entries(headers)) {\n const lower = name.toLowerCase();\n if (!CALLER_HEADERS_DROPPED.has(lower)) rest[lower] = value;\n }\n return rest;\n}\n\nfunction requestFor(config: ResolvedProviderConfig, body: unknown, signal: AbortSignal | undefined): Request {\n const headers = {\n ...callerHeaders(config.headers),\n \"content-type\": \"application/json\",\n accept: \"text/event-stream\",\n authorization: `Bearer ${config.apiKey}`,\n };\n const url = `${config.baseURL.replace(/\\/+$/, \"\")}/chat/completions`;\n return new Request(url, { method: \"POST\", headers, body: JSON.stringify(body), ...(signal ? { signal } : {}) });\n}\n\nasync function* streamCompletion(\n settings: CompatSettings,\n resolved: ResolvedProviderConfig,\n model: ModelRef,\n context: ModelContext,\n options: StreamOptions,\n): AsyncGenerator<ModelEvent> {\n yield { type: \"start\" };\n const plan = buildRequest(model, context, options, options.caps ?? DEFAULT_CAPS, compatFor(settings, model.id));\n // Each attempt warns again; the gateway's retries stream a repeated warning only once per call.\n yield* plan.warnings;\n const request = requestFor(resolved, payloadOf(plan.body, options), options.signal);\n const response = yield* sendRequest(resolved.transport, request, model, options.signal);\n if (response === undefined) return;\n if (!response.ok) {\n yield failureEvent(model, await failureFromResponse(response));\n return;\n }\n yield* readEventStream(response, model, new ChunkAssembler(model, plan), options.signal);\n}\n\n/**\n * Creates an adapter for OpenAI's Chat Completions API or a server compatible with it. Every request goes to\n * `{baseURL}/chat/completions` through `config.transport`, streams its response, and sends the key from\n * `config.apiKey` as a bearer token; it is the only key the adapter sends. `baseURL` defaults to\n * `https://api.openai.com/v1`. Throws a `GatewayError` with code `missing_api_key` when the key is missing or empty.\n *\n * The adapter reports the provider `config.provider`, `\"openai\"` by default, which is the name `createModel()` looks\n * the model up under in the price catalog. `config.compat` sets the server's quirks for every model, and\n * `config.modelCompat` for single models by id. The model's caps come from `options.caps`, which `createModel()`\n * sets; a direct call without them uses `defaultCaps`, which send no images.\n *\n * Caller headers from `config.headers` are sent with lower-case names; a caller `authorization`, `api-key` or\n * `x-api-key` is dropped. `providerOptions.openaiChat.extraBody` adds fields to the request body, such as\n * `reasoning_effort`.\n */\nexport function openaiChat(config: OpenAIChatConfig): ModelAdapter {\n const resolved = resolveProviderConfig(config, { baseURL: DEFAULT_BASE_URL });\n // Copied, so a caller who changes the objects later does not change the adapter's requests.\n const settings: CompatSettings = {\n ...(config.compat ? { compat: { ...config.compat } } : {}),\n ...(config.modelCompat\n ? { modelCompat: Object.fromEntries(Object.entries(config.modelCompat).map(([id, own]) => [id, { ...own }])) }\n : {}),\n };\n return {\n specificationVersion: \"v1\",\n api: \"openai-chat\",\n provider: config.provider ?? \"openai\",\n defaultCaps: DEFAULT_CAPS,\n stream: (model, context, options) => streamCompletion(settings, resolved, model, context, options),\n };\n}\n"]}
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The quirks of one OpenAI-compatible server or model, as flags (D2: one wire adapter serves many vendors, and their
3
+ * differences live in per-model data, as Pi's `compat` objects do). Every default is what OpenAI's own Chat
4
+ * Completions API accepts, as its parameters read in openai-node v7.49.0
5
+ * (`src/resources/chat/completions/completions.ts`, as of November 2026).
6
+ */
7
+ import type { ProviderConfig } from "../../runtime-types.js";
8
+ /** How one OpenAI-compatible server or model differs from OpenAI's own Chat Completions API. */
9
+ export interface ChatCompat {
10
+ /**
11
+ * The body field that carries the output limit. Defaults to `"max_completion_tokens"`; OpenAI deprecates
12
+ * `max_tokens` and says reasoning models do not accept it, but many compatible servers read only `max_tokens`.
13
+ */
14
+ readonly maxTokensField?: "max_completion_tokens" | "max_tokens";
15
+ /** The role the system prompt is sent as. Defaults to `"system"`, which every compatible server reads. */
16
+ readonly systemRole?: "system" | "developer";
17
+ /**
18
+ * Whether to ask for a final usage chunk with `stream_options: { include_usage: true }`. Defaults to `true`. A
19
+ * server that rejects the field needs `false`, and its replies then report no usage.
20
+ */
21
+ readonly streamUsage?: boolean;
22
+ /** Whether tools are sent with `strict: true` when their schema allows it. Defaults to `true`. */
23
+ readonly strictTools?: boolean;
24
+ /**
25
+ * Whether the model accepts `temperature`. Defaults to `true`; with `false`, a `temperature` you set is not sent and
26
+ * the call streams a warning.
27
+ */
28
+ readonly temperature?: boolean;
29
+ /**
30
+ * Whether the model takes explicit cache breakpoints (`prompt_cache_breakpoint` on content parts and
31
+ * `prompt_cache_options`), which OpenAI supports from `gpt-5.6`. Defaults to `false`, which leaves caching to the
32
+ * server's automatic prefix cache.
33
+ */
34
+ readonly cacheBreakpoints?: boolean;
35
+ /**
36
+ * Whether `cacheRetention: "long"` sends `prompt_cache_retention: "24h"`, for models before `gpt-5.6` that offer
37
+ * extended caching. Defaults to `false`.
38
+ */
39
+ readonly promptCacheRetention?: boolean;
40
+ }
41
+ /** The configuration `openaiChat()` takes: a `ProviderConfig` plus the server's name and quirks. */
42
+ export interface OpenAIChatConfig extends ProviderConfig {
43
+ /**
44
+ * The vendor name the adapter reports, which `createModel()` looks the model up under in the price catalog.
45
+ * Defaults to `"openai"`; set it for another OpenAI-compatible server.
46
+ */
47
+ readonly provider?: string;
48
+ /** Quirks that hold for every model behind this adapter. */
49
+ readonly compat?: ChatCompat;
50
+ /** Quirks for single models, by model id, which override `compat` flag by flag. */
51
+ readonly modelCompat?: Readonly<Record<string, ChatCompat>>;
52
+ }
53
+ /** The part of the configuration `compatFor()` reads. */
54
+ export type CompatSettings = Pick<OpenAIChatConfig, "compat" | "modelCompat">;
55
+ /** A `ChatCompat` with every flag set. */
56
+ export type ResolvedCompat = Required<ChatCompat>;
57
+ /** The flags for one model: its own entry over the adapter's, over the defaults. */
58
+ export declare function compatFor(config: CompatSettings, modelId: string): ResolvedCompat;
@@ -0,0 +1,19 @@
1
+ const DEFAULT_COMPAT = {
2
+ maxTokensField: "max_completion_tokens",
3
+ systemRole: "system",
4
+ streamUsage: true,
5
+ strictTools: true,
6
+ temperature: true,
7
+ cacheBreakpoints: false,
8
+ promptCacheRetention: false,
9
+ };
10
+ /** The flags for one model: its own entry over the adapter's, over the defaults. */
11
+ export function compatFor(config, modelId) {
12
+ const own = Object.hasOwn(config.modelCompat ?? {}, modelId) ? config.modelCompat?.[modelId] : undefined;
13
+ return { ...DEFAULT_COMPAT, ...definedFlags(config.compat), ...definedFlags(own) };
14
+ }
15
+ /** The flags that are set, so an `undefined` flag keeps the value beneath it. */
16
+ function definedFlags(compat) {
17
+ return Object.fromEntries(Object.entries(compat ?? {}).filter(([, value]) => value !== undefined));
18
+ }
19
+ //# sourceMappingURL=compat.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compat.js","sourceRoot":"","sources":["../../../src/adapters/openai-chat/compat.ts"],"names":[],"mappings":"AA6DA,MAAM,cAAc,GAAmB;IACrC,cAAc,EAAE,uBAAuB;IACvC,UAAU,EAAE,QAAQ;IACpB,WAAW,EAAE,IAAI;IACjB,WAAW,EAAE,IAAI;IACjB,WAAW,EAAE,IAAI;IACjB,gBAAgB,EAAE,KAAK;IACvB,oBAAoB,EAAE,KAAK;CAC5B,CAAC;AAEF,oFAAoF;AACpF,MAAM,UAAU,SAAS,CAAC,MAAsB,EAAE,OAAe;IAC/D,MAAM,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,WAAW,IAAI,EAAE,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACzG,OAAO,EAAE,GAAG,cAAc,EAAE,GAAG,YAAY,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,YAAY,CAAC,GAAG,CAAC,EAAE,CAAC;AACrF,CAAC;AAED,iFAAiF;AACjF,SAAS,YAAY,CAAC,MAA8B;IAClD,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC;AACrG,CAAC","sourcesContent":["/**\n * The quirks of one OpenAI-compatible server or model, as flags (D2: one wire adapter serves many vendors, and their\n * differences live in per-model data, as Pi's `compat` objects do). Every default is what OpenAI's own Chat\n * Completions API accepts, as its parameters read in openai-node v7.49.0\n * (`src/resources/chat/completions/completions.ts`, as of November 2026).\n */\nimport type { ProviderConfig } from \"../../runtime-types.js\";\n\n/** How one OpenAI-compatible server or model differs from OpenAI's own Chat Completions API. */\nexport interface ChatCompat {\n /**\n * The body field that carries the output limit. Defaults to `\"max_completion_tokens\"`; OpenAI deprecates\n * `max_tokens` and says reasoning models do not accept it, but many compatible servers read only `max_tokens`.\n */\n readonly maxTokensField?: \"max_completion_tokens\" | \"max_tokens\";\n /** The role the system prompt is sent as. Defaults to `\"system\"`, which every compatible server reads. */\n readonly systemRole?: \"system\" | \"developer\";\n /**\n * Whether to ask for a final usage chunk with `stream_options: { include_usage: true }`. Defaults to `true`. A\n * server that rejects the field needs `false`, and its replies then report no usage.\n */\n readonly streamUsage?: boolean;\n /** Whether tools are sent with `strict: true` when their schema allows it. Defaults to `true`. */\n readonly strictTools?: boolean;\n /**\n * Whether the model accepts `temperature`. Defaults to `true`; with `false`, a `temperature` you set is not sent and\n * the call streams a warning.\n */\n readonly temperature?: boolean;\n /**\n * Whether the model takes explicit cache breakpoints (`prompt_cache_breakpoint` on content parts and\n * `prompt_cache_options`), which OpenAI supports from `gpt-5.6`. Defaults to `false`, which leaves caching to the\n * server's automatic prefix cache.\n */\n readonly cacheBreakpoints?: boolean;\n /**\n * Whether `cacheRetention: \"long\"` sends `prompt_cache_retention: \"24h\"`, for models before `gpt-5.6` that offer\n * extended caching. Defaults to `false`.\n */\n readonly promptCacheRetention?: boolean;\n}\n\n/** The configuration `openaiChat()` takes: a `ProviderConfig` plus the server's name and quirks. */\nexport interface OpenAIChatConfig extends ProviderConfig {\n /**\n * The vendor name the adapter reports, which `createModel()` looks the model up under in the price catalog.\n * Defaults to `\"openai\"`; set it for another OpenAI-compatible server.\n */\n readonly provider?: string;\n /** Quirks that hold for every model behind this adapter. */\n readonly compat?: ChatCompat;\n /** Quirks for single models, by model id, which override `compat` flag by flag. */\n readonly modelCompat?: Readonly<Record<string, ChatCompat>>;\n}\n\n/** The part of the configuration `compatFor()` reads. */\nexport type CompatSettings = Pick<OpenAIChatConfig, \"compat\" | \"modelCompat\">;\n\n/** A `ChatCompat` with every flag set. */\nexport type ResolvedCompat = Required<ChatCompat>;\n\nconst DEFAULT_COMPAT: ResolvedCompat = {\n maxTokensField: \"max_completion_tokens\",\n systemRole: \"system\",\n streamUsage: true,\n strictTools: true,\n temperature: true,\n cacheBreakpoints: false,\n promptCacheRetention: false,\n};\n\n/** The flags for one model: its own entry over the adapter's, over the defaults. */\nexport function compatFor(config: CompatSettings, modelId: string): ResolvedCompat {\n const own = Object.hasOwn(config.modelCompat ?? {}, modelId) ? config.modelCompat?.[modelId] : undefined;\n return { ...DEFAULT_COMPAT, ...definedFlags(config.compat), ...definedFlags(own) };\n}\n\n/** The flags that are set, so an `undefined` flag keeps the value beneath it. */\nfunction definedFlags(compat: ChatCompat | undefined): ChatCompat {\n return Object.fromEntries(Object.entries(compat ?? {}).filter(([, value]) => value !== undefined));\n}\n"]}
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Failed requests and streams, as `error` terminals. A failed response's body is
3
+ * `{ "error": { "message", "type", "param", "code" } }`, as openai-node v7.49.0 reads it (`src/core/error.ts`). A
4
+ * stream that already returned 200 reports a later error as a chunk whose `error` field holds the same object, or as
5
+ * an SSE event named `error` (`src/core/streaming.ts`); both as of November 2026.
6
+ *
7
+ * OpenAI sends billing, spend and usage limits as 429s, and retrying them "won't restore API access" (Error codes,
8
+ * https://developers.openai.com/api/docs/guides/error-codes, as of November 2026). Their `code` names the cause, such
9
+ * as `credit_balance_exhausted`, and their `type` can be `insufficient_quota`. `classifyError()` reads the code and
10
+ * the type, so these are `quota` errors even at 429, while a 429 `rate_limit_error` such as `slow_down` stays
11
+ * retryable. `context_length_exceeded`, which the fixtures use for
12
+ * an over-long prompt, is not on that page, so its wording is unverified; the classifier also matches the phrase
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`.
18
+ */
19
+ import type { ModelEvent } from "../../spec.js";
20
+ import type { ModelRef } from "../../types.js";
21
+ import { type PartialReply, type WireFailure } from "../wire.js";
22
+ /** Reads an error object, from an HTTP error body or an error chunk in a stream. */
23
+ export declare function failureFrom(body: unknown, status: number | undefined, fallback: string): WireFailure;
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
+ */
28
+ export declare function failureFromResponse(response: Response): Promise<WireFailure>;
29
+ /** The `error` terminal for a failure, with any partial content and usage the attempt reached. */
30
+ export declare function failureEvent(model: ModelRef, failure: WireFailure, partial?: PartialReply): Extract<ModelEvent, {
31
+ type: "error";
32
+ }>;
@@ -0,0 +1,40 @@
1
+ import { failureTerminal, isObject, readErrorBody, retryAfterMs, } from "../wire.js";
2
+ // The HTTP status each error type stands for, so a stream error, which has no status, classifies like the HTTP error
3
+ // it would have been. A type not listed here classifies as a failure in transit, which is retryable.
4
+ const STATUS_OF_TYPE = {
5
+ invalid_request_error: 400,
6
+ authentication_error: 401,
7
+ permission_error: 403,
8
+ not_found_error: 404,
9
+ insufficient_quota: 429,
10
+ rate_limit_error: 429,
11
+ server_error: 500,
12
+ service_unavailable_error: 503,
13
+ };
14
+ /** Reads an error object, from an HTTP error body or an error chunk in a stream. */
15
+ export function failureFrom(body, status, fallback) {
16
+ const error = isObject(body) && isObject(body.error) ? body.error : undefined;
17
+ return {
18
+ ...(status === undefined ? {} : { status }),
19
+ ...(typeof error?.type === "string" && error.type !== "" ? { type: error.type } : {}),
20
+ ...(typeof error?.code === "string" && error.code !== "" ? { errorCode: error.code } : {}),
21
+ message: typeof error?.message === "string" && error.message !== "" ? error.message : fallback,
22
+ };
23
+ }
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
+ */
28
+ export async function failureFromResponse(response) {
29
+ const { body, text } = await readErrorBody(response);
30
+ const wait = retryAfterMs(response.headers);
31
+ return {
32
+ ...failureFrom(body, response.status, text || `HTTP ${response.status}`),
33
+ ...(wait === undefined ? {} : { retryAfterMs: wait }),
34
+ };
35
+ }
36
+ /** The `error` terminal for a failure, with any partial content and usage the attempt reached. */
37
+ export function failureEvent(model, failure, partial = {}) {
38
+ return failureTerminal(model, failure, STATUS_OF_TYPE, partial);
39
+ }
40
+ //# sourceMappingURL=failure.js.map
@@ -0,0 +1 @@
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;AAEF,oFAAoF;AACpF,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,OAAO;QACL,GAAG,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC;QAC3C,GAAG,CAAC,OAAO,KAAK,EAAE,IAAI,KAAK,QAAQ,IAAI,KAAK,CAAC,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACrF,GAAG,CAAC,OAAO,KAAK,EAAE,IAAI,KAAK,QAAQ,IAAI,KAAK,CAAC,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC1F,OAAO,EAAE,OAAO,KAAK,EAAE,OAAO,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,KAAK,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ;KAC/F,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,mBAAmB,CAAC,QAAkB;IAC1D,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,MAAM,aAAa,CAAC,QAAQ,CAAC,CAAC;IACrD,MAAM,IAAI,GAAG,YAAY,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IAC5C,OAAO;QACL,GAAG,WAAW,CAAC,IAAI,EAAE,QAAQ,CAAC,MAAM,EAAE,IAAI,IAAI,QAAQ,QAAQ,CAAC,MAAM,EAAE,CAAC;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"]}
@@ -0,0 +1,4 @@
1
+ /** `@buildanagent/gateway/openai-chat`: the OpenAI-compatible Chat Completions adapter. */
2
+ export { openaiChat } from "./adapter.js";
3
+ export type { ChatCompat, OpenAIChatConfig } from "./compat.js";
4
+ export type { OpenAIChatProviderOptions } from "./request.js";
@@ -0,0 +1,3 @@
1
+ /** `@buildanagent/gateway/openai-chat`: the OpenAI-compatible Chat Completions adapter. */
2
+ export { openaiChat } from "./adapter.js";
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/adapters/openai-chat/index.ts"],"names":[],"mappings":"AAAA,2FAA2F;AAC3F,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC","sourcesContent":["/** `@buildanagent/gateway/openai-chat`: the OpenAI-compatible Chat Completions adapter. */\nexport { openaiChat } from \"./adapter.js\";\nexport type { ChatCompat, OpenAIChatConfig } from \"./compat.js\";\nexport type { OpenAIChatProviderOptions } from \"./request.js\";\n"]}
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Builds the Chat Completions request body from a `ModelContext`. Every field below follows the API reference at
3
+ * https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create and
4
+ * `ChatCompletionCreateParams` in openai-node v7.49.0 (`src/resources/chat/completions/completions.ts`), both as of
5
+ * November 2026.
6
+ *
7
+ * - Messages pass through `transformMessages()` first. A tool result becomes a `tool` message, whose content can hold
8
+ * only text, so a result's images follow in one user message after the turn's results, and a failed result's text
9
+ * starts with `Error: `. The transcript's reasoning
10
+ * is never sent, because a Chat Completions message has no field for it.
11
+ * - Tool names go through the run's `ToolNameMap`. A tool is sent with `strict: true` when its schema can be lowered,
12
+ * and the plan keeps the original schema of each, so the reply's added nulls can be stripped.
13
+ * - Caching follows the model's `ChatCompat` flags: explicit breakpoints on the system prompt and the newest user or
14
+ * tool message, with the 30-minute lifetime Chat Completions offers; `prompt_cache_retention: "24h"`; or neither,
15
+ * which leaves the server's automatic prefix cache.
16
+ */
17
+ import { type ToolNameMap } from "../../names.js";
18
+ import type { ModelEvent, StreamOptions } from "../../spec.js";
19
+ import type { ModelCaps, ModelContext, ModelRef } from "../../types.js";
20
+ import { type Json } from "../wire.js";
21
+ import type { ResolvedCompat } from "./compat.js";
22
+ type Warning = Extract<ModelEvent, {
23
+ type: "warning";
24
+ }>;
25
+ /** What the adapter reads from `providerOptions.openaiChat`. */
26
+ export interface OpenAIChatProviderOptions {
27
+ /**
28
+ * Extra fields for the request body, such as `reasoning_effort`, `prompt_cache_key` or `parallel_tool_calls`. The
29
+ * fields the adapter sets itself (`model`, `stream`, `stream_options`, `messages`, `tools`, `max_completion_tokens`
30
+ * and `max_tokens`) win over these: an `extraBody` value for one is not sent, and the call streams an
31
+ * `unsupported_option` warning.
32
+ */
33
+ readonly extraBody?: Readonly<Record<string, unknown>>;
34
+ }
35
+ /** One request's body and what reading its response needs. */
36
+ export interface RequestPlan {
37
+ readonly body: Json;
38
+ readonly warnings: readonly Warning[];
39
+ readonly names: ToolNameMap;
40
+ /** The original input schema of each tool sent strict, by tool name. */
41
+ readonly strictSchemas: ReadonlyMap<string, Json>;
42
+ }
43
+ /** Reads `providerOptions.openaiChat`, ignoring fields of the wrong type. */
44
+ export declare function openaiChatOptions(options: StreamOptions): OpenAIChatProviderOptions;
45
+ /** Builds one call's request body. */
46
+ export declare function buildRequest(model: ModelRef, context: ModelContext, options: StreamOptions, caps: ModelCaps, compat: ResolvedCompat): RequestPlan;
47
+ export {};