@buildanagent/gateway 0.0.0-stage → 0.1.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/LICENSE +52 -0
  2. package/LICENSE-APACHE +202 -0
  3. package/LICENSE-MIT +21 -0
  4. package/README.md +299 -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 +20 -0
  9. package/dist/adapters/anthropic/failure.js +46 -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 +31 -0
  18. package/dist/adapters/anthropic/response.js +212 -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 +25 -0
  30. package/dist/adapters/openai-chat/failure.js +33 -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 +19 -0
  42. package/dist/adapters/openai-chat/usage.js +22 -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 +77 -0
  48. package/dist/adapters/wire.js +137 -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 +42 -0
  61. package/dist/cost.js +122 -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 +30 -0
  88. package/dist/retry.js +191 -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 +130 -0
  121. package/dist/types.js +6 -0
  122. package/dist/types.js.map +1 -0
  123. package/dist/usage.d.ts +8 -0
  124. package/dist/usage.js +20 -0
  125. package/dist/usage.js.map +1 -0
  126. package/package.json +50 -3
@@ -0,0 +1,203 @@
1
+ import { stripAddedNulls } from "../strict-schema.js";
2
+ import { isObject, parseToolInput, str, terminalMessage } from "../wire.js";
3
+ import { failureEvent, failureFrom } from "./failure.js";
4
+ import { openaiUsage } from "./usage.js";
5
+ // Each wire finish reason as the gateway's. `content_filter` is handled apart, as a failure.
6
+ const STOP_REASONS = {
7
+ stop: "stop",
8
+ length: "length",
9
+ tool_calls: "tool_calls",
10
+ function_call: "tool_calls",
11
+ };
12
+ /**
13
+ * An error chunk as the `{ error: { message, ... } }` body `failureFrom()` reads. A compatible server may send the
14
+ * error object bare, or only its message as a string.
15
+ */
16
+ function errorBody(chunk) {
17
+ if (isObject(chunk) && isObject(chunk.error))
18
+ return chunk;
19
+ if (isObject(chunk) && typeof chunk.error === "string")
20
+ return { error: { message: chunk.error } };
21
+ if (typeof chunk === "string")
22
+ return { error: { message: chunk } };
23
+ return isObject(chunk) ? { error: chunk } : {};
24
+ }
25
+ /** An error event's data: JSON when it parses, else its text, which some compatible servers send bare. */
26
+ function parseErrorData(data) {
27
+ try {
28
+ return JSON.parse(data);
29
+ }
30
+ catch {
31
+ return data;
32
+ }
33
+ }
34
+ /** One stream's state: the blocks so far, the usage and the finish reason. */
35
+ export class ChunkAssembler {
36
+ #model;
37
+ #names;
38
+ #strictSchemas;
39
+ #open = new Map();
40
+ #closed = new Map();
41
+ // The block index of each wire tool-call index, and of the open text and reasoning blocks.
42
+ #tools = new Map();
43
+ #text;
44
+ #reasoning;
45
+ #nextIndex = 0;
46
+ #usage = null;
47
+ #finish = "";
48
+ #refusal = "";
49
+ constructor(model, plan) {
50
+ this.#model = model;
51
+ this.#names = plan.names;
52
+ this.#strictSchemas = plan.strictSchemas;
53
+ }
54
+ /** The events one server-sent event produces. The last one is the terminal when the stream has ended. */
55
+ handle(sse) {
56
+ if (sse.data.trim() === "[DONE]")
57
+ return this.#terminal();
58
+ const chunk = sse.event === "error" ? parseErrorData(sse.data) : JSON.parse(sse.data);
59
+ if (sse.event === "error" || (isObject(chunk) && (isObject(chunk.error) || typeof chunk.error === "string"))) {
60
+ return [failureEvent(this.#model, failureFrom(errorBody(chunk), undefined, "stream error"), this.partial())];
61
+ }
62
+ if (!isObject(chunk))
63
+ return [];
64
+ if (isObject(chunk.usage))
65
+ this.#usage = chunk.usage;
66
+ const choices = Array.isArray(chunk.choices) ? chunk.choices.filter(isObject) : [];
67
+ // The adapter never asks for more than one choice, so it reads the first.
68
+ const choice = choices.find((entry) => entry.index === 0) ?? choices[0];
69
+ if (choice === undefined)
70
+ return [];
71
+ if (typeof choice.finish_reason === "string")
72
+ this.#finish = choice.finish_reason;
73
+ return isObject(choice.delta) ? this.#delta(choice.delta) : [];
74
+ }
75
+ /**
76
+ * A stream that closed without `[DONE]`. One that already sent its finish reason ends as it would have, because
77
+ * some compatible servers never send `[DONE]`; any other is a retryable failure.
78
+ */
79
+ ended() {
80
+ if (this.#finish !== "")
81
+ return this.#terminal();
82
+ return [failureEvent(this.#model, { message: "the stream ended before [DONE]" }, this.partial())];
83
+ }
84
+ /** The content and usage so far, open blocks included, for an `error` terminal. */
85
+ partial() {
86
+ const open = [...this.#open].map(([index, block]) => [index, this.#finishBlock(block)]);
87
+ const content = [...this.#closed, ...open].sort(([a], [b]) => a - b).map(([, block]) => block);
88
+ return { content, usage: openaiUsage(this.#usage) };
89
+ }
90
+ #delta(delta) {
91
+ const events = [];
92
+ const reasoning = str(delta.reasoning_content) || str(delta.reasoning);
93
+ if (reasoning !== "")
94
+ events.push(...this.#appendProse("reasoning", reasoning));
95
+ const content = str(delta.content);
96
+ if (content !== "")
97
+ events.push(...this.#appendProse("text", content));
98
+ this.#refusal += str(delta.refusal);
99
+ const calls = Array.isArray(delta.tool_calls) ? delta.tool_calls.filter(isObject) : [];
100
+ for (const call of calls)
101
+ events.push(...this.#appendToolCall(call));
102
+ return events;
103
+ }
104
+ /** Adds text or reasoning to its open block, opening one first and closing the other kind. */
105
+ #appendProse(kind, text) {
106
+ const events = this.#closeIndex(kind === "text" ? this.#reasoning : this.#text);
107
+ let index = kind === "text" ? this.#text : this.#reasoning;
108
+ if (index === undefined) {
109
+ index = this.#openBlock({ kind, text: "" });
110
+ if (kind === "text")
111
+ this.#text = index;
112
+ else
113
+ this.#reasoning = index;
114
+ events.push({ type: `${kind}_start`, index });
115
+ }
116
+ const open = this.#open.get(index);
117
+ if (open)
118
+ open.text += text;
119
+ events.push({ type: `${kind}_delta`, index, delta: text });
120
+ return events;
121
+ }
122
+ #appendToolCall(call) {
123
+ const wireIndex = typeof call.index === "number" ? call.index : 0;
124
+ const fn = isObject(call.function) ? call.function : {};
125
+ const id = str(call.id);
126
+ const events = [];
127
+ let index = this.#tools.get(wireIndex);
128
+ // A server that leaves out `index` sends each call whole under its own id, so a new id starts a new call.
129
+ const current = index === undefined ? undefined : this.#open.get(index);
130
+ if (id !== "" && current?.callId && current.callId !== id)
131
+ index = undefined;
132
+ if (index === undefined) {
133
+ events.push(...this.#closeIndex(this.#text), ...this.#closeIndex(this.#reasoning));
134
+ index = this.#openBlock({ kind: "tool_input", text: "", callId: id, name: str(fn.name) });
135
+ this.#tools.set(wireIndex, index);
136
+ events.push({ type: "tool_input_start", index });
137
+ }
138
+ const open = this.#open.get(index);
139
+ if (open === undefined)
140
+ return events;
141
+ // The first entry carries the id and name; a server that repeats them in later entries adds nothing.
142
+ if (!open.callId)
143
+ open.callId = id;
144
+ if (!open.name)
145
+ open.name = str(fn.name);
146
+ const args = str(fn.arguments);
147
+ if (args === "")
148
+ return events;
149
+ open.text += args;
150
+ events.push({ type: "tool_input_delta", index, delta: args });
151
+ return events;
152
+ }
153
+ #openBlock(block) {
154
+ const index = this.#nextIndex;
155
+ this.#nextIndex += 1;
156
+ this.#open.set(index, block);
157
+ return index;
158
+ }
159
+ #closeIndex(index) {
160
+ if (index === undefined)
161
+ return [];
162
+ const open = this.#open.get(index);
163
+ if (index === this.#text)
164
+ this.#text = undefined;
165
+ if (index === this.#reasoning)
166
+ this.#reasoning = undefined;
167
+ if (open === undefined)
168
+ return [];
169
+ this.#open.delete(index);
170
+ const block = this.#finishBlock(open);
171
+ this.#closed.set(index, block);
172
+ return [{ type: `${open.kind}_end`, index, block }];
173
+ }
174
+ #finishBlock(open) {
175
+ if (open.kind === "text")
176
+ return { type: "text", text: open.text };
177
+ if (open.kind === "reasoning")
178
+ return { type: "reasoning", text: open.text };
179
+ const wire = open.name ?? "";
180
+ const name = this.#names.restore(wire) ?? wire;
181
+ const input = parseToolInput(open.text);
182
+ const schema = this.#strictSchemas.get(name);
183
+ // A call cut off by the output limit keeps its partial JSON text as it arrived.
184
+ const stripped = schema === undefined || typeof input === "string" ? input : stripAddedNulls(input, schema);
185
+ return { type: "tool_call", callId: open.callId ?? "", name, input: stripped };
186
+ }
187
+ #terminal() {
188
+ const closing = [...this.#open.keys()].sort((a, b) => a - b).flatMap((index) => this.#closeIndex(index));
189
+ const { content, usage } = this.partial();
190
+ if (this.#finish === "content_filter" || this.#refusal !== "") {
191
+ const message = this.#refusal !== ""
192
+ ? `refusal: ${this.#refusal}`
193
+ : "content_filter: the provider's content filter omitted all or part of the reply";
194
+ return [...closing, failureEvent(this.#model, { message, kind: "fatal" }, { content, usage })];
195
+ }
196
+ const hasCalls = content.some((block) => block.type === "tool_call");
197
+ const mapped = STOP_REASONS[this.#finish] ?? "stop";
198
+ // Some compatible servers end a reply that calls tools with "stop"; the calls still need their results.
199
+ const stopReason = mapped === "stop" && hasCalls ? "tool_calls" : mapped;
200
+ return [...closing, { type: "done", message: terminalMessage(this.#model, { content, usage }, stopReason) }];
201
+ }
202
+ }
203
+ //# sourceMappingURL=response.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"response.js","sourceRoot":"","sources":["../../../src/adapters/openai-chat/response.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,QAAQ,EAAa,cAAc,EAAqB,GAAG,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC1G,OAAO,E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AK,CAAC,CAAC,CAAC;QACzG,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;QAC1C,IAAI,IAAI,CAAC,OAAO,KAAK,gBAAgB,IAAI,IAAI,CAAC,QAAQ,KAAK,EAAE,EAAE,CAAC;YAC9D,MAAM,OAAO,GACX,IAAI,CAAC,QAAQ,KAAK,EAAE;gBAClB,CAAC,CAAC,YAAY,IAAI,CAAC,QAAQ,EAAE;gBAC7B,CAAC,CAAC,gFAAgF,CAAC;YACvF,OAAO,CAAC,GAAG,OAAO,EAAE,YAAY,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;QACjG,CAAC;QACD,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC;QACrE,MAAM,MAAM,GAAG,YAAY,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,MAAM,CAAC;QACpD,wGAAwG;QACxG,MAAM,UAAU,GAAG,MAAM,KAAK,MAAM,IAAI,QAAQ,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,MAAM,CAAC;QACzE,OAAO,CAAC,GAAG,OAAO,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;IAC/G,CAAC;CACF","sourcesContent":["/**\n * Turns a Chat Completions stream into `ModelEvent`s, from `ChatCompletionChunk` and the stream reader in\n * openai-node v7.49.0 (`src/resources/chat/completions/completions.ts`, `src/core/streaming.ts`, as of November 2026).\n * Each server-sent event's data is one chunk; `data: [DONE]` ends the stream. A chunk's `choices[0].delta` carries\n * text in `content`, a refusal in `refusal`, and tool calls in `tool_calls`, each entry keyed by its `index`, with\n * the `id` and `function.name` in its first entry and `function.arguments` streamed in pieces. `finish_reason` arrives\n * on the last chunk with a choice. With `stream_options.include_usage`, one more chunk, with empty `choices`, carries\n * the `usage` of the whole request before `[DONE]`.\n *\n * OpenAI's models stream no reasoning text, only a count of reasoning tokens. Several compatible servers stream it as\n * `delta.reasoning_content` or `delta.reasoning`, which becomes an unsigned reasoning block.\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 { stripAddedNulls } from \"../strict-schema.js\";\nimport { isObject, type Json, parseToolInput, type StreamReader, str, terminalMessage } from \"../wire.js\";\nimport { failureEvent, failureFrom } from \"./failure.js\";\nimport type { RequestPlan } from \"./request.js\";\nimport { openaiUsage } from \"./usage.js\";\n\ntype BlockKind = \"text\" | \"reasoning\" | \"tool_input\";\n\ninterface OpenBlock {\n readonly kind: BlockKind;\n text: string;\n callId?: string;\n name?: string;\n}\n\n// Each wire finish reason as the gateway's. `content_filter` is handled apart, as a failure.\nconst STOP_REASONS: Readonly<Record<string, AssistantMessage[\"stopReason\"]>> = {\n stop: \"stop\",\n length: \"length\",\n tool_calls: \"tool_calls\",\n function_call: \"tool_calls\",\n};\n\n/**\n * An error chunk as the `{ error: { message, ... } }` body `failureFrom()` reads. A compatible server may send the\n * error object bare, or only its message as a string.\n */\nfunction errorBody(chunk: unknown): Json {\n if (isObject(chunk) && isObject(chunk.error)) return chunk;\n if (isObject(chunk) && typeof chunk.error === \"string\") return { error: { message: chunk.error } };\n if (typeof chunk === \"string\") return { error: { message: chunk } };\n return isObject(chunk) ? { error: chunk } : {};\n}\n\n/** An error event's data: JSON when it parses, else its text, which some compatible servers send bare. */\nfunction parseErrorData(data: string): unknown {\n try {\n return JSON.parse(data);\n } catch {\n return data;\n }\n}\n\n/** One stream's state: the blocks so far, the usage and the finish reason. */\nexport class ChunkAssembler implements StreamReader {\n readonly #model: ModelRef;\n readonly #names: ToolNameMap;\n readonly #strictSchemas: ReadonlyMap<string, Json>;\n readonly #open = new Map<number, OpenBlock>();\n readonly #closed = new Map<number, ContentBlock>();\n // The block index of each wire tool-call index, and of the open text and reasoning blocks.\n readonly #tools = new Map<number, number>();\n #text: number | undefined;\n #reasoning: number | undefined;\n #nextIndex = 0;\n #usage: unknown = null;\n #finish = \"\";\n #refusal = \"\";\n\n constructor(model: ModelRef, plan: Pick<RequestPlan, \"names\" | \"strictSchemas\">) {\n this.#model = model;\n this.#names = plan.names;\n this.#strictSchemas = plan.strictSchemas;\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 if (sse.data.trim() === \"[DONE]\") return this.#terminal();\n const chunk: unknown = sse.event === \"error\" ? parseErrorData(sse.data) : JSON.parse(sse.data);\n if (sse.event === \"error\" || (isObject(chunk) && (isObject(chunk.error) || typeof chunk.error === \"string\"))) {\n return [failureEvent(this.#model, failureFrom(errorBody(chunk), undefined, \"stream error\"), this.partial())];\n }\n if (!isObject(chunk)) return [];\n if (isObject(chunk.usage)) this.#usage = chunk.usage;\n const choices = Array.isArray(chunk.choices) ? chunk.choices.filter(isObject) : [];\n // The adapter never asks for more than one choice, so it reads the first.\n const choice = choices.find((entry) => entry.index === 0) ?? choices[0];\n if (choice === undefined) return [];\n if (typeof choice.finish_reason === \"string\") this.#finish = choice.finish_reason;\n return isObject(choice.delta) ? this.#delta(choice.delta) : [];\n }\n\n /**\n * A stream that closed without `[DONE]`. One that already sent its finish reason ends as it would have, because\n * some compatible servers never send `[DONE]`; any other is a retryable failure.\n */\n ended(): ModelEvent[] {\n if (this.#finish !== \"\") return this.#terminal();\n return [failureEvent(this.#model, { message: \"the stream ended before [DONE]\" }, this.partial())];\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.#finishBlock(block)] as const);\n const content = [...this.#closed, ...open].sort(([a], [b]) => a - b).map(([, block]) => block);\n return { content, usage: openaiUsage(this.#usage) };\n }\n\n #delta(delta: Json): ModelEvent[] {\n const events: ModelEvent[] = [];\n const reasoning = str(delta.reasoning_content) || str(delta.reasoning);\n if (reasoning !== \"\") events.push(...this.#appendProse(\"reasoning\", reasoning));\n const content = str(delta.content);\n if (content !== \"\") events.push(...this.#appendProse(\"text\", content));\n this.#refusal += str(delta.refusal);\n const calls = Array.isArray(delta.tool_calls) ? delta.tool_calls.filter(isObject) : [];\n for (const call of calls) events.push(...this.#appendToolCall(call));\n return events;\n }\n\n /** Adds text or reasoning to its open block, opening one first and closing the other kind. */\n #appendProse(kind: \"text\" | \"reasoning\", text: string): ModelEvent[] {\n const events = this.#closeIndex(kind === \"text\" ? this.#reasoning : this.#text);\n let index = kind === \"text\" ? this.#text : this.#reasoning;\n if (index === undefined) {\n index = this.#openBlock({ kind, text: \"\" });\n if (kind === \"text\") this.#text = index;\n else this.#reasoning = index;\n events.push({ type: `${kind}_start`, index });\n }\n const open = this.#open.get(index);\n if (open) open.text += text;\n events.push({ type: `${kind}_delta`, index, delta: text });\n return events;\n }\n\n #appendToolCall(call: Json): ModelEvent[] {\n const wireIndex = typeof call.index === \"number\" ? call.index : 0;\n const fn = isObject(call.function) ? call.function : {};\n const id = str(call.id);\n const events: ModelEvent[] = [];\n let index = this.#tools.get(wireIndex);\n // A server that leaves out `index` sends each call whole under its own id, so a new id starts a new call.\n const current = index === undefined ? undefined : this.#open.get(index);\n if (id !== \"\" && current?.callId && current.callId !== id) index = undefined;\n if (index === undefined) {\n events.push(...this.#closeIndex(this.#text), ...this.#closeIndex(this.#reasoning));\n index = this.#openBlock({ kind: \"tool_input\", text: \"\", callId: id, name: str(fn.name) });\n this.#tools.set(wireIndex, index);\n events.push({ type: \"tool_input_start\", index });\n }\n const open = this.#open.get(index);\n if (open === undefined) return events;\n // The first entry carries the id and name; a server that repeats them in later entries adds nothing.\n if (!open.callId) open.callId = id;\n if (!open.name) open.name = str(fn.name);\n const args = str(fn.arguments);\n if (args === \"\") return events;\n open.text += args;\n events.push({ type: \"tool_input_delta\", index, delta: args });\n return events;\n }\n\n #openBlock(block: OpenBlock): number {\n const index = this.#nextIndex;\n this.#nextIndex += 1;\n this.#open.set(index, block);\n return index;\n }\n\n #closeIndex(index: number | undefined): ModelEvent[] {\n if (index === undefined) return [];\n const open = this.#open.get(index);\n if (index === this.#text) this.#text = undefined;\n if (index === this.#reasoning) this.#reasoning = undefined;\n if (open === undefined) return [];\n this.#open.delete(index);\n const block = this.#finishBlock(open);\n this.#closed.set(index, block);\n return [{ type: `${open.kind}_end`, index, block }];\n }\n\n #finishBlock(open: OpenBlock): ContentBlock {\n if (open.kind === \"text\") return { type: \"text\", text: open.text };\n if (open.kind === \"reasoning\") return { type: \"reasoning\", text: open.text };\n const wire = open.name ?? \"\";\n const name = this.#names.restore(wire) ?? wire;\n const input = parseToolInput(open.text);\n const schema = this.#strictSchemas.get(name);\n // A call cut off by the output limit keeps its partial JSON text as it arrived.\n const stripped = schema === undefined || typeof input === \"string\" ? input : stripAddedNulls(input, schema);\n return { type: \"tool_call\", callId: open.callId ?? \"\", name, input: stripped };\n }\n\n #terminal(): ModelEvent[] {\n const closing = [...this.#open.keys()].sort((a, b) => a - b).flatMap((index) => this.#closeIndex(index));\n const { content, usage } = this.partial();\n if (this.#finish === \"content_filter\" || this.#refusal !== \"\") {\n const message =\n this.#refusal !== \"\"\n ? `refusal: ${this.#refusal}`\n : \"content_filter: the provider's content filter omitted all or part of the reply\";\n return [...closing, failureEvent(this.#model, { message, kind: \"fatal\" }, { content, usage })];\n }\n const hasCalls = content.some((block) => block.type === \"tool_call\");\n const mapped = STOP_REASONS[this.#finish] ?? \"stop\";\n // Some compatible servers end a reply that calls tools with \"stop\"; the calls still need their results.\n const stopReason = mapped === \"stop\" && hasCalls ? \"tool_calls\" : mapped;\n return [...closing, { type: \"done\", message: terminalMessage(this.#model, { content, usage }, stopReason) }];\n }\n}\n"]}
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Maps a Chat Completions `usage` object into the gateway's four token classes (D3), from the `usage` of a chat
3
+ * completion (https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create) and
4
+ * the Prompt caching guide (https://developers.openai.com/api/docs/guides/prompt-caching), both as of November 2026:
5
+ *
6
+ * - `prompt_tokens` counts the whole prompt. `prompt_tokens_details.cached_tokens` counts billed cache reads, which
7
+ * exclude the tokens charged as writes, and `cache_write_tokens` the prompt tokens written to cache. The guide
8
+ * computes ordinary input as the input tokens less both, and so does the adapter.
9
+ * - Chat Completions writes only 30-minute cache entries, so every write counts under `Usage.cacheWrite["5m"]`, the
10
+ * key for the short cache-write rate; an OpenAI catalog entry stores its 30-minute rate there.
11
+ * - `completion_tokens` is the output, and `completion_tokens_details.reasoning_tokens` the part of it spent on
12
+ * reasoning: `max_completion_tokens` bounds "visible output tokens and reasoning tokens" together, and the
13
+ * reference says rejected prediction tokens are, "like reasoning tokens", counted in the completion tokens for billing.
14
+ *
15
+ * The usage object holds token counts only, so a reply carries no billed price and the cost comes from the catalog.
16
+ */
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. */
19
+ export declare function openaiUsage(raw: unknown): Usage;
@@ -0,0 +1,22 @@
1
+ import { emptyUsage } from "../../usage.js";
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. */
4
+ export function openaiUsage(raw) {
5
+ if (!isObject(raw))
6
+ return emptyUsage(raw ?? null);
7
+ const prompt = isObject(raw.prompt_tokens_details) ? raw.prompt_tokens_details : {};
8
+ const completion = isObject(raw.completion_tokens_details) ? raw.completion_tokens_details : {};
9
+ const cacheRead = count(prompt.cached_tokens);
10
+ const written = count(prompt.cache_write_tokens);
11
+ const output = count(raw.completion_tokens);
12
+ return {
13
+ uncachedInput: Math.max(0, count(raw.prompt_tokens) - cacheRead - written),
14
+ cacheRead,
15
+ cacheWrite: { "5m": written, "1h": 0 },
16
+ output,
17
+ // Reasoning is a part of output; the cap keeps that true for a server that reports more.
18
+ reasoning: Math.min(count(completion.reasoning_tokens), output),
19
+ raw,
20
+ };
21
+ }
22
+ //# sourceMappingURL=usage.js.map
@@ -0,0 +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"]}
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Lowers a tool's JSON Schema to the subset a provider's strict tool mode accepts, and undoes the one change the
3
+ * model can see: the `null` that a nullable dialect adds to an optional property. Each adapter passes its own
4
+ * `StrictDialect`; the rules both first providers share are these:
5
+ *
6
+ * - every object needs `additionalProperties: false`, and an object with any other `additionalProperties` cannot be
7
+ * strict. An object that declares neither `properties` nor `additionalProperties` accepts any keys, and adding
8
+ * `additionalProperties: false` would let the model send only `{}`, so it cannot be strict either;
9
+ * - `not` is unsupported, and `oneOf` must be written as `anyOf`;
10
+ * - numeric constraints, string length constraints and array constraints beyond `minItems` of 0 or 1 are dropped,
11
+ * unless the dialect keeps them. Anthropic rejects them (Structured outputs, "JSON Schema limitations",
12
+ * https://platform.claude.com/docs/en/build-with-claude/structured-outputs, as of November 2026).
13
+ *
14
+ * OpenAI's strict mode requires every property (Structured model outputs, "Supported schemas",
15
+ * https://developers.openai.com/api/docs/guides/structured-outputs#supported-schemas, as of November 2026). It
16
+ * accepts the numeric constraints and `minItems`/`maxItems`, rejects `allOf`, `if`/`then`/`else` and the
17
+ * `dependent*` keywords, and limits a schema's size, for example to 5,000 properties and 10 levels of nesting. Its
18
+ * dialect therefore writes an optional property as a required one that also accepts `null`. The removed constraints
19
+ * are not lost: the SDK validates every call against the original schema, after `stripAddedNulls()`.
20
+ */
21
+ type Json = Record<string, unknown>;
22
+ /** How one provider's strict mode differs from the shared rules above. */
23
+ export interface StrictDialect {
24
+ /** `"keep"` leaves optional properties optional; `"nullable"` requires them and lets them be `null`. */
25
+ readonly optional: "keep" | "nullable";
26
+ /** The string formats the provider accepts; any other `format` is dropped. */
27
+ readonly formats: ReadonlySet<string>;
28
+ /** True when the provider accepts only an object schema, with `type: "object"`, at the root. */
29
+ readonly objectRoot: boolean;
30
+ /** Keywords the provider enforces, which lowering keeps although the shared rules drop them. */
31
+ readonly keeps?: ReadonlySet<string>;
32
+ /** Keywords the provider rejects; a schema that uses one is sent without strict. */
33
+ readonly rejects?: ReadonlySet<string>;
34
+ /** Limits on one schema; a schema over any of them is sent without strict. */
35
+ readonly limits?: StrictLimits;
36
+ }
37
+ /** The size limits of one strict schema. */
38
+ export interface StrictLimits {
39
+ readonly properties: number;
40
+ /** Levels of object nesting. */
41
+ readonly depth: number;
42
+ readonly enumValues: number;
43
+ /** Characters in all property names, definition names, and string enum and `const` values. */
44
+ readonly stringLength: number;
45
+ /** The most characters one string enum may hold once it has more than `values` values. */
46
+ readonly largeEnum: {
47
+ readonly values: number;
48
+ readonly length: number;
49
+ };
50
+ }
51
+ /** A schema lowered to strict form, with the counts the request-wide complexity limits are checked against. */
52
+ export interface StrictSchema {
53
+ readonly schema: Json;
54
+ /** Properties left out of `required`, across the whole schema. Always 0 for a nullable dialect. */
55
+ readonly optional: number;
56
+ /** Subschemas that use `anyOf` or a type array, the null unions a nullable dialect adds included. */
57
+ readonly unions: number;
58
+ }
59
+ /** The schema in strict form with its counts, or `undefined` when strict mode cannot express it. */
60
+ export declare function lowerToStrict(schema: Json, dialect: StrictDialect): StrictSchema | undefined;
61
+ /**
62
+ * Removes from a tool call's input each `null` that nullable lowering added: a `null` in a property that the original
63
+ * schema leaves optional and does not let be `null`. It follows `properties`, `items`, local `$ref`s and, for an
64
+ * object or array inside an `anyOf` or `oneOf`, the first branch whose properties or items fit the value.
65
+ */
66
+ export declare function stripAddedNulls(input: unknown, original: Json): unknown;
67
+ export {};
@@ -0,0 +1,269 @@
1
+ /**
2
+ * Lowers a tool's JSON Schema to the subset a provider's strict tool mode accepts, and undoes the one change the
3
+ * model can see: the `null` that a nullable dialect adds to an optional property. Each adapter passes its own
4
+ * `StrictDialect`; the rules both first providers share are these:
5
+ *
6
+ * - every object needs `additionalProperties: false`, and an object with any other `additionalProperties` cannot be
7
+ * strict. An object that declares neither `properties` nor `additionalProperties` accepts any keys, and adding
8
+ * `additionalProperties: false` would let the model send only `{}`, so it cannot be strict either;
9
+ * - `not` is unsupported, and `oneOf` must be written as `anyOf`;
10
+ * - numeric constraints, string length constraints and array constraints beyond `minItems` of 0 or 1 are dropped,
11
+ * unless the dialect keeps them. Anthropic rejects them (Structured outputs, "JSON Schema limitations",
12
+ * https://platform.claude.com/docs/en/build-with-claude/structured-outputs, as of November 2026).
13
+ *
14
+ * OpenAI's strict mode requires every property (Structured model outputs, "Supported schemas",
15
+ * https://developers.openai.com/api/docs/guides/structured-outputs#supported-schemas, as of November 2026). It
16
+ * accepts the numeric constraints and `minItems`/`maxItems`, rejects `allOf`, `if`/`then`/`else` and the
17
+ * `dependent*` keywords, and limits a schema's size, for example to 5,000 properties and 10 levels of nesting. Its
18
+ * dialect therefore writes an optional property as a required one that also accepts `null`. The removed constraints
19
+ * are not lost: the SDK validates every call against the original schema, after `stripAddedNulls()`.
20
+ */
21
+ const UNSUPPORTED_KEYWORDS = new Set([
22
+ "minimum",
23
+ "maximum",
24
+ "exclusiveMinimum",
25
+ "exclusiveMaximum",
26
+ "multipleOf",
27
+ "minLength",
28
+ "maxLength",
29
+ "maxItems",
30
+ "uniqueItems",
31
+ "minProperties",
32
+ "maxProperties",
33
+ "patternProperties",
34
+ "propertyNames",
35
+ ]);
36
+ // Lookaround, named groups and backreferences fall outside the documented regex subset.
37
+ const UNSUPPORTED_PATTERN = /\(\?|\\[1-9k]/;
38
+ const SCHEMA_LISTS = ["anyOf", "allOf", "oneOf", "prefixItems"];
39
+ const SCHEMA_MAPS = ["properties", "$defs", "definitions"];
40
+ function isObject(value) {
41
+ return typeof value === "object" && value !== null && !Array.isArray(value);
42
+ }
43
+ /** True for a key strict mode rejects, so lowering removes it. */
44
+ function dropsKey(key, value, dialect) {
45
+ if (dialect.keeps?.has(key))
46
+ return false;
47
+ if (UNSUPPORTED_KEYWORDS.has(key))
48
+ return true;
49
+ if (key === "minItems")
50
+ return typeof value !== "number" || value > 1;
51
+ if (key === "format")
52
+ return typeof value !== "string" || !dialect.formats.has(value);
53
+ return key === "pattern" && (typeof value !== "string" || UNSUPPORTED_PATTERN.test(value));
54
+ }
55
+ function lowerChildren(key, value, walk) {
56
+ if (SCHEMA_LISTS.includes(key) && Array.isArray(value))
57
+ return value.map((item) => lowerNode(item, walk));
58
+ if (SCHEMA_MAPS.includes(key) && isObject(value)) {
59
+ return Object.fromEntries(Object.entries(value).map(([name, item]) => [name, lowerNode(item, walk)]));
60
+ }
61
+ if (key === "items" && isObject(value))
62
+ return lowerNode(value, walk);
63
+ return value;
64
+ }
65
+ /**
66
+ * True when the schema already accepts `null`. A schema that constrains nothing, such as `{}`, accepts it; a `$ref`,
67
+ * an `allOf`, or an object or array schema written without `type` counts as not accepting it, so a nullable dialect
68
+ * gives it an explicit `null` branch.
69
+ */
70
+ function allowsNull(schema) {
71
+ if (!isObject(schema))
72
+ return true;
73
+ if (schema.type === "null" || (Array.isArray(schema.type) && schema.type.includes("null")))
74
+ return true;
75
+ if (Array.isArray(schema.enum))
76
+ return schema.enum.includes(null);
77
+ if ("const" in schema)
78
+ return schema.const === null;
79
+ const branches = Array.isArray(schema.anyOf) ? schema.anyOf : Array.isArray(schema.oneOf) ? schema.oneOf : undefined;
80
+ if (branches)
81
+ return branches.some(allowsNull);
82
+ return schema.type === undefined && !["$ref", "allOf", "properties", "items"].some((key) => key in schema);
83
+ }
84
+ /** The schema made to accept `null` as well, in the simplest form strict mode reads. */
85
+ function withNull(schema, walk) {
86
+ if (allowsNull(schema))
87
+ return schema;
88
+ walk.unions += 1;
89
+ if (typeof schema.type === "string" && !Array.isArray(schema.enum) && !("const" in schema)) {
90
+ return { ...schema, type: [schema.type, "null"] };
91
+ }
92
+ if (Array.isArray(schema.anyOf))
93
+ return { ...schema, anyOf: [...schema.anyOf, { type: "null" }] };
94
+ return { anyOf: [schema, { type: "null" }] };
95
+ }
96
+ /** Marks every property required, and lets each one that was optional be `null`. */
97
+ function requireAll(lowered, original, walk) {
98
+ if (!isObject(lowered.properties))
99
+ return;
100
+ const required = new Set(Array.isArray(original.required) ? original.required : []);
101
+ const properties = lowered.properties;
102
+ for (const [name, property] of Object.entries(properties)) {
103
+ if (!required.has(name) && isObject(property))
104
+ properties[name] = withNull(property, walk);
105
+ }
106
+ lowered.required = Object.keys(properties);
107
+ }
108
+ function countOptional(node, walk) {
109
+ const properties = isObject(node.properties) ? Object.keys(node.properties) : [];
110
+ const required = new Set(Array.isArray(node.required) ? node.required : []);
111
+ walk.optional += properties.filter((name) => !required.has(name)).length;
112
+ }
113
+ /** Why strict mode cannot express this node itself, or `undefined` when it can. */
114
+ function strictFailure(node, isObjectSchema, dialect) {
115
+ if ("not" in node)
116
+ return "uses not";
117
+ const rejected = Object.keys(node).find((key) => dialect.rejects?.has(key));
118
+ if (rejected !== undefined)
119
+ return `uses ${rejected}`;
120
+ if (!isObjectSchema)
121
+ return undefined;
122
+ if ("additionalProperties" in node) {
123
+ return node.additionalProperties === false ? undefined : "allows additional properties";
124
+ }
125
+ return isObject(node.properties) ? undefined : "declares no properties";
126
+ }
127
+ // A nullable object, `type: ["object", "null"]`, is an object too and needs the same treatment.
128
+ function isObjectNode(node) {
129
+ return (node.type === "object" || (Array.isArray(node.type) && node.type.includes("object")) || isObject(node.properties));
130
+ }
131
+ /** Counts the node toward `StrictDialect.limits`; an object nests one level deeper until its children are lowered. */
132
+ function measure(node, isObjectSchema, walk) {
133
+ if (isObjectSchema)
134
+ walk.depth += 1;
135
+ walk.maxDepth = Math.max(walk.maxDepth, walk.depth);
136
+ const names = SCHEMA_MAPS.flatMap((key) => (isObject(node[key]) ? Object.keys(node[key]) : []));
137
+ if (isObject(node.properties))
138
+ walk.properties += Object.keys(node.properties).length;
139
+ const strings = [...(Array.isArray(node.enum) ? node.enum : []), node.const].filter((v) => typeof v === "string");
140
+ walk.stringLength += [...names, ...strings].reduce((sum, text) => sum + text.length, 0);
141
+ if (!Array.isArray(node.enum))
142
+ return;
143
+ walk.enumValues += node.enum.length;
144
+ const enumStrings = node.enum.filter((value) => typeof value === "string");
145
+ const large = walk.dialect.limits?.largeEnum.values ?? Number.POSITIVE_INFINITY;
146
+ if (enumStrings.length > large) {
147
+ const length = enumStrings.reduce((sum, text) => sum + text.length, 0);
148
+ walk.largeEnumLength = Math.max(walk.largeEnumLength, length);
149
+ }
150
+ }
151
+ function overLimits(walk, limits) {
152
+ if (limits === undefined)
153
+ return false;
154
+ return (walk.properties > limits.properties ||
155
+ walk.maxDepth > limits.depth ||
156
+ walk.enumValues > limits.enumValues ||
157
+ walk.stringLength > limits.stringLength ||
158
+ walk.largeEnumLength > limits.largeEnum.length);
159
+ }
160
+ function lowerNode(node, walk) {
161
+ if (!isObject(node) || walk.failure !== undefined)
162
+ return node;
163
+ const isObjectSchema = isObjectNode(node);
164
+ const failure = strictFailure(node, isObjectSchema, walk.dialect);
165
+ if (failure !== undefined) {
166
+ walk.failure = failure;
167
+ return node;
168
+ }
169
+ measure(node, isObjectSchema, walk);
170
+ const lowered = {};
171
+ for (const [key, value] of Object.entries(node)) {
172
+ if (dropsKey(key, value, walk.dialect))
173
+ continue;
174
+ lowered[key === "oneOf" ? "anyOf" : key] = lowerChildren(key, value, walk);
175
+ }
176
+ if (isObjectSchema)
177
+ walk.depth -= 1;
178
+ if (isObjectSchema) {
179
+ lowered.additionalProperties = false;
180
+ if (walk.dialect.optional === "nullable")
181
+ requireAll(lowered, node, walk);
182
+ else
183
+ countOptional(node, walk);
184
+ }
185
+ if (Array.isArray(node.type) || Array.isArray(lowered.anyOf))
186
+ walk.unions += 1;
187
+ return lowered;
188
+ }
189
+ /** The schema in strict form with its counts, or `undefined` when strict mode cannot express it. */
190
+ export function lowerToStrict(schema, dialect) {
191
+ if (dialect.objectRoot && schema.type !== "object")
192
+ return undefined;
193
+ const walk = {
194
+ dialect,
195
+ optional: 0,
196
+ unions: 0,
197
+ properties: 0,
198
+ depth: 0,
199
+ maxDepth: 0,
200
+ enumValues: 0,
201
+ stringLength: 0,
202
+ largeEnumLength: 0,
203
+ };
204
+ const lowered = lowerNode(schema, walk);
205
+ if (walk.failure !== undefined || overLimits(walk, dialect.limits))
206
+ return undefined;
207
+ return { schema: lowered, optional: walk.optional, unions: walk.unions };
208
+ }
209
+ // Stripping the added nulls ------------------------------------------------------------------------------------------
210
+ /** Follows a local `#/$defs/…` or `#/definitions/…` reference; any other schema comes back as it is. */
211
+ function resolve(schema, root) {
212
+ if (!isObject(schema) || typeof schema.$ref !== "string")
213
+ return schema;
214
+ const match = /^#\/(\$defs|definitions)\/([^/]+)$/.exec(schema.$ref);
215
+ if (match === null)
216
+ return schema;
217
+ const defs = root[match[1] ?? ""];
218
+ return isObject(defs) ? defs[decodeURIComponent(match[2] ?? "")] : schema;
219
+ }
220
+ /**
221
+ * The first `anyOf`/`oneOf` branch that can describe the value: for an array, one with `items`; for an object, one
222
+ * whose `properties` name every key the value has. The branch the model chose is the one its value fits.
223
+ */
224
+ function matchingBranch(value, schema, root) {
225
+ const branches = Array.isArray(schema.anyOf) ? schema.anyOf : Array.isArray(schema.oneOf) ? schema.oneOf : [];
226
+ return branches.find((branch) => {
227
+ const resolved = resolve(branch, root);
228
+ if (!isObject(resolved))
229
+ return false;
230
+ if (Array.isArray(value))
231
+ return isObject(resolved.items);
232
+ const properties = resolved.properties;
233
+ return isObject(value) && isObject(properties) && Object.keys(value).every((key) => key in properties);
234
+ });
235
+ }
236
+ function strip(value, node, root) {
237
+ const schema = resolve(node, root);
238
+ if (!isObject(schema))
239
+ return value;
240
+ if (!isObject(schema.properties) && !isObject(schema.items) && value !== null && typeof value === "object") {
241
+ const branch = matchingBranch(value, schema, root);
242
+ return branch === undefined ? value : strip(value, branch, root);
243
+ }
244
+ if (Array.isArray(value))
245
+ return isObject(schema.items) ? value.map((item) => strip(item, schema.items, root)) : value;
246
+ return isObject(value) && isObject(schema.properties) ? stripObject(value, schema.properties, schema, root) : value;
247
+ }
248
+ function stripObject(value, properties, schema, root) {
249
+ const required = new Set(Array.isArray(schema.required) ? schema.required : []);
250
+ const out = {};
251
+ for (const [name, item] of Object.entries(value)) {
252
+ const property = properties[name];
253
+ // A null the original schema does not allow here is one lowering added, and leaving the field out is what the
254
+ // model meant by it.
255
+ if (item === null && property !== undefined && !required.has(name) && !allowsNull(resolve(property, root)))
256
+ continue;
257
+ out[name] = property === undefined ? item : strip(item, property, root);
258
+ }
259
+ return out;
260
+ }
261
+ /**
262
+ * Removes from a tool call's input each `null` that nullable lowering added: a `null` in a property that the original
263
+ * schema leaves optional and does not let be `null`. It follows `properties`, `items`, local `$ref`s and, for an
264
+ * object or array inside an `anyOf` or `oneOf`, the first branch whose properties or items fit the value.
265
+ */
266
+ export function stripAddedNulls(input, original) {
267
+ return strip(input, original, original);
268
+ }
269
+ //# sourceMappingURL=strict-schema.js.map