@warlock.js/ai-openai 5.30.0 → 5.31.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 (44) hide show
  1. package/CHANGELOG.md +24 -1
  2. package/README.md +3 -3
  3. package/cjs/index.cjs +416 -48
  4. package/cjs/index.cjs.map +1 -1
  5. package/esm/config.type.d.mts +5 -3
  6. package/esm/config.type.d.mts.map +1 -1
  7. package/esm/embedder.d.mts.map +1 -1
  8. package/esm/embedder.mjs.map +1 -1
  9. package/esm/index.d.mts +3 -1
  10. package/esm/index.mjs +2 -1
  11. package/esm/known-pricing.d.mts +35 -0
  12. package/esm/known-pricing.d.mts.map +1 -0
  13. package/esm/known-pricing.mjs +117 -0
  14. package/esm/known-pricing.mjs.map +1 -0
  15. package/esm/model.mjs +75 -23
  16. package/esm/model.mjs.map +1 -1
  17. package/esm/provider-options.d.mts +8 -0
  18. package/esm/provider-options.d.mts.map +1 -0
  19. package/esm/provider-options.mjs +49 -0
  20. package/esm/provider-options.mjs.map +1 -0
  21. package/esm/responses-model.mjs +116 -17
  22. package/esm/responses-model.mjs.map +1 -1
  23. package/esm/sdk.d.mts +3 -2
  24. package/esm/sdk.d.mts.map +1 -1
  25. package/esm/sdk.mjs +5 -3
  26. package/esm/sdk.mjs.map +1 -1
  27. package/esm/transcription.mjs.map +1 -1
  28. package/esm/utils/build-usage.mjs +14 -2
  29. package/esm/utils/build-usage.mjs.map +1 -1
  30. package/esm/utils/index.mjs +1 -1
  31. package/esm/utils/map-responses-status.mjs.map +1 -1
  32. package/esm/utils/prompt-cache-params.mjs +25 -6
  33. package/esm/utils/prompt-cache-params.mjs.map +1 -1
  34. package/esm/utils/reasoning-replay.mjs +23 -1
  35. package/esm/utils/reasoning-replay.mjs.map +1 -1
  36. package/esm/utils/structured-output.mjs.map +1 -1
  37. package/esm/utils/to-openai-messages.mjs.map +1 -1
  38. package/esm/utils/to-openai-tools.mjs.map +1 -1
  39. package/esm/utils/wrap-openai-error.mjs +6 -1
  40. package/esm/utils/wrap-openai-error.mjs.map +1 -1
  41. package/llms-full.txt +128 -37
  42. package/llms.txt +1 -1
  43. package/package.json +3 -3
  44. package/skills/setup-openai/SKILL.md +128 -37
@@ -0,0 +1,49 @@
1
+ import { InvalidRequestError } from "@warlock.js/ai";
2
+
3
+ //#region ../../packages/ai-openai/src/provider-options.ts
4
+ const RESERVED_FIELDS = new Set([
5
+ "model",
6
+ "messages",
7
+ "input",
8
+ "instructions",
9
+ "tools",
10
+ "stream",
11
+ "stream_options",
12
+ "previous_response_id",
13
+ "conversation",
14
+ "store",
15
+ "include",
16
+ "functions",
17
+ "function_call",
18
+ "prompt",
19
+ "background"
20
+ ]);
21
+ function mergeProviderBody(built, options) {
22
+ const body = (options?.providerOptions?.openai)?.body ?? {};
23
+ const reserved = Object.keys(body).filter((key) => RESERVED_FIELDS.has(key));
24
+ if (reserved.length > 0) throw new InvalidRequestError(`providerOptions.openai.body cannot set ${reserved.join(", ")}: use the call's messages, tools and model options.`, { context: { fields: reserved } });
25
+ const defaults = built;
26
+ const overrides = Object.fromEntries(Object.entries(body).map(([key, value]) => {
27
+ const previous = defaults[key];
28
+ if (!isPlainObject(previous) || !isPlainObject(value)) return [key, value];
29
+ if (typeof previous.type === "string" && typeof value.type === "string" && previous.type !== value.type) return [key, value];
30
+ return [key, {
31
+ ...previous,
32
+ ...value
33
+ }];
34
+ }));
35
+ return {
36
+ ...built,
37
+ ...overrides
38
+ };
39
+ }
40
+ /** Merge only plain objects; arrays, null and provider scalar values replace the field. */
41
+ function isPlainObject(value) {
42
+ if (value === null || typeof value !== "object") return false;
43
+ const prototype = Object.getPrototypeOf(value);
44
+ return prototype === Object.prototype || prototype === null;
45
+ }
46
+
47
+ //#endregion
48
+ export { mergeProviderBody };
49
+ //# sourceMappingURL=provider-options.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider-options.mjs","names":[],"sources":["../../../../../../../packages/ai-openai/src/provider-options.ts"],"sourcesContent":["import { InvalidRequestError, type ModelCallOptions } from \"@warlock.js/ai\";\n\n/** Adapter-only fields merged after the neutral request parameters. */\nexport type OpenAICallOptions = { body?: Record<string, unknown> };\n\nconst RESERVED_FIELDS = new Set([\n \"model\",\n \"messages\",\n \"input\",\n \"instructions\",\n \"tools\",\n \"stream\",\n \"stream_options\",\n \"previous_response_id\",\n \"conversation\",\n \"store\",\n \"include\",\n \"functions\",\n \"function_call\",\n \"prompt\",\n \"background\",\n]);\n\nexport function mergeProviderBody<T extends object>(\n built: T,\n options: ModelCallOptions | undefined,\n): T {\n const provider = options?.providerOptions?.openai as OpenAICallOptions | undefined;\n const body = provider?.body ?? {};\n const reserved = Object.keys(body).filter((key) => RESERVED_FIELDS.has(key));\n if (reserved.length > 0) {\n throw new InvalidRequestError(\n `providerOptions.openai.body cannot set ${reserved.join(\", \")}: use the call's messages, tools and model options.`,\n { context: { fields: reserved } },\n );\n }\n const defaults = built as Record<string, unknown>;\n const overrides = Object.fromEntries(\n Object.entries(body).map(([key, value]) => {\n const previous = defaults[key];\n if (!isPlainObject(previous) || !isPlainObject(value)) return [key, value];\n // A different discriminator selects a whole SDK variant. Keeping fields\n // from the previous variant can make an otherwise valid override invalid.\n if (\n typeof previous.type === \"string\" &&\n typeof value.type === \"string\" &&\n previous.type !== value.type\n )\n return [key, value];\n return [key, { ...previous, ...value }];\n }),\n );\n return { ...built, ...overrides };\n}\n\n/** Merge only plain objects; arrays, null and provider scalar values replace the field. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n"],"mappings":";;;AAKA,MAAM,kBAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAgB,kBACd,OACA,SACG;CAEH,MAAM,QADW,SAAS,iBAAiB,OACtB,EAAE,QAAQ,CAAC;CAChC,MAAM,WAAW,OAAO,KAAK,IAAI,CAAC,CAAC,QAAQ,QAAQ,gBAAgB,IAAI,GAAG,CAAC;CAC3E,IAAI,SAAS,SAAS,GACpB,MAAM,IAAI,oBACR,0CAA0C,SAAS,KAAK,IAAI,EAAE,sDAC9D,EAAE,SAAS,EAAE,QAAQ,SAAS,EAAE,CAClC;CAEF,MAAM,WAAW;CACjB,MAAM,YAAY,OAAO,YACvB,OAAO,QAAQ,IAAI,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW;EACzC,MAAM,WAAW,SAAS;EAC1B,IAAI,CAAC,cAAc,QAAQ,KAAK,CAAC,cAAc,KAAK,GAAG,OAAO,CAAC,KAAK,KAAK;EAGzE,IACE,OAAO,SAAS,SAAS,YACzB,OAAO,MAAM,SAAS,YACtB,SAAS,SAAS,MAAM,MAExB,OAAO,CAAC,KAAK,KAAK;EACpB,OAAO,CAAC,KAAK;GAAE,GAAG;GAAU,GAAG;EAAM,CAAC;CACxC,CAAC,CACH;CACA,OAAO;EAAE,GAAG;EAAO,GAAG;CAAU;AAClC;;AAGA,SAAS,cAAc,OAAkD;CACvE,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD"}
@@ -4,18 +4,32 @@ import { mapResponsesFinishReason, toResponseFailure } from "./utils/map-respons
4
4
  import { buildPromptCacheParams } from "./utils/prompt-cache-params.mjs";
5
5
  import { toOpenAIReasoningEffort } from "./utils/reasoning-effort.mjs";
6
6
  import { inferStructuredOutput, planStructuredOutput } from "./utils/structured-output.mjs";
7
- import { attachReasoningReplay } from "./utils/reasoning-replay.mjs";
7
+ import { attachReasoningReplay, pickTurnReasoning } from "./utils/reasoning-replay.mjs";
8
8
  import { toResponsesInput } from "./utils/to-responses-input.mjs";
9
9
  import { toResponsesToolChoice, toResponsesTools } from "./utils/to-responses-tools.mjs";
10
10
  import "./utils/index.mjs";
11
+ import { mergeProviderBody } from "./provider-options.mjs";
11
12
  import { inferReasoningCapability } from "./known-reasoning-models.mjs";
12
13
  import { inferVisionCapability } from "./known-vision-models.mjs";
13
- import { InvalidRequestError, ProviderError, safeJsonParse } from "@warlock.js/ai";
14
+ import { InvalidRequestError, ProviderError, resolveStreamChunks, safeJsonParse, selectProviderTools } from "@warlock.js/ai";
14
15
  import { log } from "@warlock.js/logger";
15
16
 
16
17
  //#region ../../packages/ai-openai/src/responses-model.ts
17
18
  const LOG_MODULE = "ai.openai";
18
19
  /**
20
+ * Responses output item types of built-in tools the CALLER must execute
21
+ * (installed SDK `ResponseOutputItem` union). The adapter maps only
22
+ * `function_call` to a neutral tool call, so these fail closed.
23
+ */
24
+ const CLIENT_RUN_ITEM_TYPES = new Set([
25
+ "computer_call",
26
+ "custom_tool_call",
27
+ "local_shell_call",
28
+ "shell_call",
29
+ "apply_patch_call",
30
+ "mcp_approval_request"
31
+ ]);
32
+ /**
19
33
  * OpenAI Responses API implementation of `ModelContract` (`api: "responses"`).
20
34
  *
21
35
  * **Role.** A sibling of `OpenAIModel` that speaks `POST /v1/responses`
@@ -42,7 +56,16 @@ const LOG_MODULE = "ai.openai";
42
56
  *
43
57
  * **Streaming.** `stream()` uses `responses.create({ stream: true })` and yields
44
58
  * the same chunk sequence as the Chat path: text `delta`s, then the
45
- * `tool-call`s, then one `done`.
59
+ * `tool-call`s, then one `done`. With `streamChunks` it also yields
60
+ * `reasoning` (reasoning summary / reasoning text deltas) and `tool-args`
61
+ * (`response.function_call_arguments.delta`).
62
+ *
63
+ * **Provider-defined tools.** `ai.providerTool({ provider: "openai" })`
64
+ * definitions are appended to `tools` verbatim. Hosted tools run inside the
65
+ * response; their output items (`web_search_call`, …) are not replayed
66
+ * (with `store: false` the next turn only needs the answer text), and a
67
+ * reasoning item that led into one is not replayed either (see
68
+ * `pickTurnReasoning`).
46
69
  */
47
70
  var OpenAIResponsesModel = class {
48
71
  constructor(client, config, provider = "openai") {
@@ -105,6 +128,26 @@ var OpenAIResponsesModel = class {
105
128
  ...toolCalls ? { toolCalls } : {}
106
129
  };
107
130
  }
131
+ /** Count native Responses input tokens using the same converted input and tools. */
132
+ async countTokens(messages, options) {
133
+ const request = this.buildRequest(messages, options);
134
+ const body = {
135
+ model: request.model,
136
+ input: request.input,
137
+ instructions: request.instructions,
138
+ tools: request.tools,
139
+ tool_choice: request.tool_choice,
140
+ reasoning: request.reasoning,
141
+ text: request.text,
142
+ parallel_tool_calls: request.parallel_tool_calls,
143
+ truncation: request.truncation ?? void 0
144
+ };
145
+ try {
146
+ return (await this.client.responses.inputTokens.count(body, options?.signal ? { signal: options.signal } : void 0)).input_tokens;
147
+ } catch (thrown) {
148
+ throw this.logAndWrap(thrown);
149
+ }
150
+ }
108
151
  /**
109
152
  * Incremental streaming completion via `responses.create({ stream: true })`
110
153
  * (the SDK's `Stream<ResponseStreamEvent>`, `responses.d.ts:55`). Yields the
@@ -139,7 +182,9 @@ var OpenAIResponsesModel = class {
139
182
  throw this.logAndWrap(thrown);
140
183
  }
141
184
  const toolCalls = [];
142
- const reasoningItems = [];
185
+ const outputItems = [];
186
+ const want = resolveStreamChunks(options);
187
+ const streamingCalls = /* @__PURE__ */ new Map();
143
188
  let terminal;
144
189
  try {
145
190
  for await (const event of events) {
@@ -150,10 +195,36 @@ var OpenAIResponsesModel = class {
150
195
  };
151
196
  continue;
152
197
  }
198
+ if (event.type === "response.reasoning_summary_text.delta" || event.type === "response.reasoning_text.delta") {
199
+ if (want.reasoning && event.delta) yield {
200
+ type: "reasoning",
201
+ delta: event.delta
202
+ };
203
+ continue;
204
+ }
205
+ if (event.type === "response.output_item.added") {
206
+ const { item } = event;
207
+ if (item.type === "function_call" && item.id) streamingCalls.set(item.id, {
208
+ callId: item.call_id,
209
+ name: item.name
210
+ });
211
+ continue;
212
+ }
213
+ if (event.type === "response.function_call_arguments.delta") {
214
+ const call = streamingCalls.get(event.item_id);
215
+ if (want.toolArgs && call && event.delta) yield {
216
+ type: "tool-args",
217
+ callId: call.callId,
218
+ name: call.name,
219
+ delta: event.delta
220
+ };
221
+ continue;
222
+ }
153
223
  if (event.type === "response.output_item.done") {
154
224
  const { item } = event;
155
- if (item.type === "reasoning") reasoningItems.push(item);
156
- else if (item.type === "function_call" && item.status !== "incomplete") toolCalls.push(this.toToolCall(item));
225
+ this.assertServerRunItem(item);
226
+ outputItems.push(item);
227
+ if (item.type === "function_call" && item.status !== "incomplete") toolCalls.push(this.toToolCall(item));
157
228
  continue;
158
229
  }
159
230
  if (event.type === "response.completed" || event.type === "response.incomplete") {
@@ -174,7 +245,7 @@ var OpenAIResponsesModel = class {
174
245
  } catch (thrown) {
175
246
  throw this.logAndWrap(thrown);
176
247
  }
177
- for (const call of attachReasoningReplay(toolCalls, this.name, reasoningItems)) yield {
248
+ for (const call of attachReasoningReplay(toolCalls, this.name, pickTurnReasoning(outputItems))) yield {
178
249
  type: "tool-call",
179
250
  id: call.id,
180
251
  name: call.name,
@@ -212,11 +283,11 @@ var OpenAIResponsesModel = class {
212
283
  */
213
284
  buildRequest(messages, options) {
214
285
  const { instructions, input } = toResponsesInput(messages, this.name);
215
- const tools = toResponsesTools(options?.tools);
286
+ const tools = this.buildTools(options);
216
287
  const toolChoice = tools ? toResponsesToolChoice(options?.toolChoice) : void 0;
217
288
  const maxTokens = options?.maxTokens ?? this.config.maxTokens;
218
289
  const temperature = options?.temperature ?? this.config.temperature;
219
- return {
290
+ return mergeProviderBody({
220
291
  model: this.name,
221
292
  ...instructions !== void 0 ? { instructions } : {},
222
293
  input,
@@ -229,7 +300,24 @@ var OpenAIResponsesModel = class {
229
300
  ...this.buildTextFormat(options?.responseSchema),
230
301
  ...this.buildReasoningParams(options?.reasoning),
231
302
  ...buildPromptCacheParams(this.provider, this.config)
232
- };
303
+ }, options);
304
+ }
305
+ /**
306
+ * The request `tools`: function tools (flat, `strict: false`), then the
307
+ * `ai.providerTool({ provider: "openai" })` definitions verbatim — the
308
+ * Responses built-in tools (`web_search`, `file_search`,
309
+ * `code_interpreter`, `image_generation`, `mcp`, …). Other providers'
310
+ * definitions are skipped with a warning. `undefined` when there are none.
311
+ */
312
+ buildTools(options) {
313
+ const { tools, definitions } = selectProviderTools(options, {
314
+ accepts: [this.provider],
315
+ module: LOG_MODULE,
316
+ model: this.name,
317
+ logger: this.logger
318
+ });
319
+ const mapped = [...toResponsesTools(tools) ?? [], ...definitions];
320
+ return mapped.length > 0 ? mapped : void 0;
233
321
  }
234
322
  /**
235
323
  * Structured output on Responses lives in `text.format`, and `name` /
@@ -266,12 +354,8 @@ var OpenAIResponsesModel = class {
266
354
  readOutput(output) {
267
355
  let content = "";
268
356
  const toolCalls = [];
269
- const reasoningItems = [];
270
357
  for (const item of output) {
271
- if (item.type === "reasoning") {
272
- reasoningItems.push(item);
273
- continue;
274
- }
358
+ this.assertServerRunItem(item);
275
359
  if (item.type === "message") {
276
360
  for (const part of item.content) content += part.type === "refusal" ? part.refusal : part.text;
277
361
  continue;
@@ -280,9 +364,24 @@ var OpenAIResponsesModel = class {
280
364
  }
281
365
  return {
282
366
  content,
283
- toolCalls: toolCalls.length > 0 ? attachReasoningReplay(toolCalls, this.name, reasoningItems) : void 0
367
+ toolCalls: toolCalls.length > 0 ? attachReasoningReplay(toolCalls, this.name, pickTurnReasoning(output)) : void 0
284
368
  };
285
369
  }
370
+ /**
371
+ * Fail closed on a built-in tool call that YOUR code would have to run
372
+ * (`shell_call`, `apply_patch_call`, `computer_call`, …, from a
373
+ * provider-defined client tool). These items have their own output item
374
+ * types that this adapter does not map, so the turn would otherwise end
375
+ * silently with the call dropped. Hosted (server-run) tool items pass.
376
+ */
377
+ assertServerRunItem(item) {
378
+ if (!CLIENT_RUN_ITEM_TYPES.has(item.type)) return;
379
+ throw new InvalidRequestError(`OpenAI returned a "${item.type}" item: that built-in tool is executed by the caller, which the Responses adapter does not support. Use OpenAI's server-run built-in tools (web_search, file_search, code_interpreter, image_generation, mcp without approval) with ai.providerTool(), or a function tool from ai.tool().`, { context: {
380
+ provider: this.provider,
381
+ model: this.name,
382
+ itemType: item.type
383
+ } });
384
+ }
286
385
  /** One completed `function_call` item as a neutral tool call (`call_id` -> `id`). */
287
386
  toToolCall(item) {
288
387
  return {
@@ -311,7 +410,7 @@ var OpenAIResponsesModel = class {
311
410
  cachedTokens: raw.input_tokens_details?.cached_tokens,
312
411
  cacheWriteTokens: raw.input_tokens_details?.cache_write_tokens,
313
412
  reasoningTokens: raw.output_tokens_details?.reasoning_tokens
314
- });
413
+ }, this.pricing);
315
414
  }
316
415
  /** Wrap (idempotently), log and return a failure for the caller to throw. */
317
416
  logAndWrap(thrown) {
@@ -1 +1 @@
1
- {"version":3,"file":"responses-model.mjs","names":[],"sources":["../../../../../../../packages/ai-openai/src/responses-model.ts"],"sourcesContent":["import {\n InvalidRequestError,\n ProviderError,\n safeJsonParse,\n type Message,\n type ModelCallOptions,\n type ModelCapabilities,\n type ModelContract,\n type ModelPricing,\n type ModelResponse,\n type ModelStreamChunk,\n type ModelToolCallRequest,\n type Usage,\n} from \"@warlock.js/ai\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport type OpenAI from \"openai\";\nimport type { OpenAIModelConfig } from \"./config.type\";\nimport { inferReasoningCapability } from \"./known-reasoning-models\";\nimport { inferVisionCapability } from \"./known-vision-models\";\nimport {\n attachReasoningReplay,\n buildPromptCacheParams,\n buildUsage,\n inferStructuredOutput,\n mapResponsesFinishReason,\n planStructuredOutput,\n toOpenAIReasoningEffort,\n toResponseFailure,\n toResponsesInput,\n toResponsesToolChoice,\n toResponsesTools,\n wrapOpenAIError,\n} from \"./utils\";\n\nconst LOG_MODULE = \"ai.openai\";\n\n/**\n * OpenAI Responses API implementation of `ModelContract` (`api: \"responses\"`).\n *\n * **Role.** A sibling of `OpenAIModel` that speaks `POST /v1/responses`\n * instead of Chat Completions. Its point is letting a tool-using agent run a\n * reasoning model with reasoning ON: the Chat path has to force\n * `reasoning_effort: \"none\"` whenever tools are attached, Responses does not.\n *\n * **Why a separate class.** Only `OpenAISDK.model()` constructs it, and only\n * for the direct `\"openai\"` provider. The wrapper packages (deepseek, groq,\n * xai, mistral) build `OpenAIModel` and cannot reach this class, so an\n * endpoint that does not implement `/v1/responses` is never sent there. The\n * constructor re-checks the provider label as a second lock.\n *\n * **Stateless.** Every request sends `store: false`; nothing is kept on the\n * server and no `previous_response_id` is used. Full history is re-sent each\n * call, exactly like the Chat path.\n *\n * **Reasoning replay.** Every request asks for\n * `include: [\"reasoning.encrypted_content\"]`. The `reasoning` items of a\n * tool-calling turn are stored on the FIRST tool call as\n * `providerMetadata.openaiResponses = { model, reasoningItems }` and sent back\n * before that turn's `function_call` items on the next request (only when the\n * stored model equals the current one). Text-only turns are not replayed.\n *\n * **Streaming.** `stream()` uses `responses.create({ stream: true })` and yields\n * the same chunk sequence as the Chat path: text `delta`s, then the\n * `tool-call`s, then one `done`.\n */\nexport class OpenAIResponsesModel implements ModelContract {\n public readonly name: string;\n public readonly provider: string;\n public readonly capabilities: ModelCapabilities;\n public readonly pricing?: ModelPricing;\n\n private readonly client: OpenAI;\n private readonly config: OpenAIModelConfig;\n private readonly logger: Logger = log;\n\n public constructor(client: OpenAI, config: OpenAIModelConfig, provider: string = \"openai\") {\n if (provider !== \"openai\") {\n throw new InvalidRequestError(\n `api: \"responses\" is supported only on the direct \"openai\" provider; got provider \"${provider}\".`,\n { context: { provider, model: config.name, api: \"responses\" } },\n );\n }\n\n this.client = client;\n this.config = config;\n this.name = config.name;\n this.provider = provider;\n this.pricing = config.pricing;\n this.capabilities = {\n structuredOutput: config.structuredOutput ?? inferStructuredOutput(config.responseFormat),\n vision: config.vision ?? inferVisionCapability(config.name),\n reasoning: config.reasoning ?? inferReasoningCapability(config.name),\n // Read-side cache accounting (`cachedTokens`, `cacheWriteTokens`) works\n // and `prompt_cache_key` is forwarded. Explicit write breakpoints are not\n // mapped onto Responses yet, so a `cacheControl.breakpoints` hint is\n // ignored rather than rejected.\n promptCaching: true,\n // PDF and audio input are off under Responses in this adapter: the\n // `input_file` / `input_audio` field-level mapping is unverified. The\n // `pdf` / `audio` config flags are deliberately NOT honoured here.\n pdf: false,\n audio: false,\n };\n }\n\n /**\n * Single-shot completion against `client.responses.create`. Sends the full\n * history as Responses `input` items, walks `response.output`, and reshapes\n * it into a vendor-neutral `ModelResponse`. Per-call `options` override the\n * instance defaults for this call only.\n */\n public async complete(messages: Message[], options?: ModelCallOptions): Promise<ModelResponse> {\n this.logger.debug(LOG_MODULE, \"request\", \"Starting call to responses.create\", {\n model: this.name,\n messageCount: messages.length,\n streaming: false,\n toolCount: options?.tools?.length ?? 0,\n });\n\n let response: OpenAI.Responses.Response;\n\n try {\n response = await this.client.responses.create(\n this.buildRequest(messages, options),\n options?.signal ? { signal: options.signal } : undefined,\n );\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n if (response.status === \"failed\") {\n throw this.logAndWrap(toResponseFailure(response, this.name));\n }\n\n const output = Array.isArray(response.output) ? response.output : [];\n const { content, toolCalls } = this.readOutput(output);\n const finishReason = mapResponsesFinishReason({\n status: response.status,\n incomplete_details: response.incomplete_details,\n hasToolCalls: toolCalls !== undefined,\n });\n const usage = this.extractUsage(response.usage);\n\n this.logger.debug(LOG_MODULE, \"response\", \"call to responses.create succeeded\", {\n finishReason,\n usage,\n });\n\n return { content, finishReason, usage, ...(toolCalls ? { toolCalls } : {}) };\n }\n\n /**\n * Incremental streaming completion via `responses.create({ stream: true })`\n * (the SDK's `Stream<ResponseStreamEvent>`, `responses.d.ts:55`). Yields the\n * same neutral `ModelStreamChunk` sequence as the Chat path:\n *\n * - `response.output_text.delta` / `response.refusal.delta` -> `delta`.\n * - `response.output_item.done` with a completed `function_call` item ->\n * buffered; `reasoning` items are captured for replay. The `done` copy is\n * used because the `added` copy may be incomplete (`responses.d.ts:5711`).\n * - After the loop: the buffered `tool-call`s (the first carries the\n * replay metadata), then a single `done` with the finish reason and usage\n * from `response.completed` / `response.incomplete`.\n * - `response.failed` and `error` events throw a typed `AIError`; a stream\n * that ends with no terminal event throws `ProviderError`.\n * - Abort goes through the request `signal`; the SDK rejects the read and\n * the error is wrapped like any other.\n */\n public async *stream(\n messages: Message[],\n options?: ModelCallOptions,\n ): AsyncIterable<ModelStreamChunk> {\n this.logger.debug(LOG_MODULE, \"request\", \"Starting streaming call to responses.create\", {\n model: this.name,\n messageCount: messages.length,\n streaming: true,\n toolCount: options?.tools?.length ?? 0,\n });\n\n let events: AsyncIterable<OpenAI.Responses.ResponseStreamEvent>;\n\n try {\n events = await this.client.responses.create(\n { ...this.buildRequest(messages, options), stream: true },\n options?.signal ? { signal: options.signal } : undefined,\n );\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n const toolCalls: ModelToolCallRequest[] = [];\n const reasoningItems: OpenAI.Responses.ResponseReasoningItem[] = [];\n let terminal: OpenAI.Responses.Response | undefined;\n\n try {\n for await (const event of events) {\n if (event.type === \"response.output_text.delta\" || event.type === \"response.refusal.delta\") {\n if (event.delta) {\n yield { type: \"delta\", content: event.delta };\n }\n\n continue;\n }\n\n if (event.type === \"response.output_item.done\") {\n const { item } = event;\n\n if (item.type === \"reasoning\") {\n reasoningItems.push(item);\n } else if (item.type === \"function_call\" && item.status !== \"incomplete\") {\n toolCalls.push(this.toToolCall(item));\n }\n\n continue;\n }\n\n if (event.type === \"response.completed\" || event.type === \"response.incomplete\") {\n terminal = event.response;\n continue;\n }\n\n if (event.type === \"response.failed\") {\n throw toResponseFailure(event.response, this.name);\n }\n\n if (event.type === \"error\") {\n throw wrapOpenAIError({ code: event.code, message: event.message, param: event.param });\n }\n }\n\n if (terminal === undefined) {\n throw new ProviderError(\"OpenAI Responses stream ended before response.completed.\", {\n context: { provider: this.provider, model: this.name },\n });\n }\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n for (const call of attachReasoningReplay(toolCalls, this.name, reasoningItems)) {\n yield {\n type: \"tool-call\",\n id: call.id,\n name: call.name,\n input: call.input,\n ...(call.providerMetadata ? { providerMetadata: call.providerMetadata } : {}),\n };\n }\n\n const finishReason = mapResponsesFinishReason({\n status: terminal.status,\n incomplete_details: terminal.incomplete_details,\n hasToolCalls: toolCalls.length > 0,\n });\n const usage = this.extractUsage(terminal.usage);\n\n this.logger.debug(LOG_MODULE, \"response\", \"Streaming call to responses.create succeeded\", {\n finishReason,\n usage,\n });\n\n yield { type: \"done\", finishReason, usage };\n }\n\n /**\n * Assemble the `responses.create` body.\n *\n * - System prompt -> `instructions`; history -> `input` items.\n * - `store: false` always (the API default is `true` when omitted), plus\n * `include: [\"reasoning.encrypted_content\"]` for stateless reasoning replay.\n * - `max_output_tokens` caps reasoning and visible output together.\n * - `temperature` only for non-reasoning models (same rule as Chat).\n * - `tools` flat with `strict: false`; `tool_choice` only with tools.\n * - `reasoning.effort` only when the caller gave one, through the same\n * clamp table as Chat. With no explicit effort the provider default\n * applies EVEN with tools attached - that is the point of this API.\n */\n private buildRequest(\n messages: Message[],\n options: ModelCallOptions | undefined,\n ): OpenAI.Responses.ResponseCreateParamsNonStreaming {\n const { instructions, input } = toResponsesInput(messages, this.name);\n const tools = toResponsesTools(options?.tools);\n const toolChoice = tools ? toResponsesToolChoice(options?.toolChoice) : undefined;\n const maxTokens = options?.maxTokens ?? this.config.maxTokens;\n const temperature = options?.temperature ?? this.config.temperature;\n\n return {\n model: this.name,\n ...(instructions !== undefined ? { instructions } : {}),\n input,\n store: false,\n // Stateless replay: ask for the encrypted reasoning blobs so they can be\n // sent back on the next tool turn (decision 3).\n include: [\"reasoning.encrypted_content\"],\n ...(maxTokens !== undefined ? { max_output_tokens: maxTokens } : {}),\n ...(!this.capabilities.reasoning && temperature !== undefined ? { temperature } : {}),\n ...(tools ? { tools } : {}),\n ...(toolChoice !== undefined ? { tool_choice: toolChoice } : {}),\n ...this.buildTextFormat(options?.responseSchema),\n ...this.buildReasoningParams(options?.reasoning),\n ...buildPromptCacheParams(this.provider, this.config),\n };\n }\n\n /**\n * Structured output on Responses lives in `text.format`, and `name` /\n * `schema` / `strict` sit directly on the format object (Chat nests them\n * under `json_schema`). The strict-or-downgrade decision is the shared\n * `planStructuredOutput`.\n */\n private buildTextFormat(responseSchema: Record<string, unknown> | undefined): {\n text?: OpenAI.Responses.ResponseTextConfig;\n } {\n const plan = planStructuredOutput(responseSchema, this.config.responseFormat);\n\n if (plan.mode === \"json_schema\") {\n return {\n text: { format: { type: \"json_schema\", name: \"response\", schema: plan.schema, strict: true } },\n };\n }\n\n if (plan.mode === \"json_object\") {\n return { text: { format: { type: \"json_object\" } } };\n }\n\n return {};\n }\n\n /** `reasoning.effort` for reasoning-capable models, only when the caller set one. */\n private buildReasoningParams(reasoning: ModelCallOptions[\"reasoning\"]): {\n reasoning?: { effort: ReturnType<typeof toOpenAIReasoningEffort> };\n } {\n if (!this.capabilities.reasoning || !reasoning?.effort) {\n return {};\n }\n\n return { reasoning: { effort: toOpenAIReasoningEffort(reasoning.effort) } };\n }\n\n /**\n * Walk `response.output`: `message` items contribute their `output_text`\n * text and any `refusal` text (surfaced as ordinary content, decision 5);\n * each completed `function_call` item becomes one tool call with\n * `id = call_id`. `reasoning` items carry no visible content and are\n * not content. A `function_call` the API marked `incomplete` (truncated\n * arguments) is skipped rather than dispatched with empty input.\n * `reasoning` items are captured and attached to the first tool call for\n * replay (see `attachReasoningReplay`).\n */\n private readOutput(output: OpenAI.Responses.ResponseOutputItem[]): {\n content: string;\n toolCalls: ModelToolCallRequest[] | undefined;\n } {\n let content = \"\";\n const toolCalls: ModelToolCallRequest[] = [];\n const reasoningItems: OpenAI.Responses.ResponseReasoningItem[] = [];\n\n for (const item of output) {\n if (item.type === \"reasoning\") {\n reasoningItems.push(item);\n continue;\n }\n\n if (item.type === \"message\") {\n for (const part of item.content) {\n content += part.type === \"refusal\" ? part.refusal : part.text;\n }\n\n continue;\n }\n\n if (item.type === \"function_call\" && item.status !== \"incomplete\") {\n toolCalls.push(this.toToolCall(item));\n }\n }\n\n return {\n content,\n toolCalls:\n toolCalls.length > 0\n ? attachReasoningReplay(toolCalls, this.name, reasoningItems)\n : undefined,\n };\n }\n\n /** One completed `function_call` item as a neutral tool call (`call_id` -> `id`). */\n private toToolCall(item: OpenAI.Responses.ResponseFunctionToolCall): ModelToolCallRequest {\n return {\n id: item.call_id,\n name: item.name,\n input: safeJsonParse<Record<string, unknown>>(item.arguments, {}),\n };\n }\n\n /**\n * Normalize `usage` (absent on some partials) into the neutral `Usage`.\n * `input_tokens_details.cached_tokens` -> `cachedTokens`,\n * `cache_write_tokens` -> `cacheWriteTokens`,\n * `output_tokens_details.reasoning_tokens` -> `reasoningTokens`. The\n * detail blocks are typed non-optional but read defensively.\n */\n private extractUsage(raw: OpenAI.Responses.ResponseUsage | undefined): Usage {\n if (!raw) {\n return { input: 0, output: 0, total: 0 };\n }\n\n return buildUsage({\n input: raw.input_tokens,\n output: raw.output_tokens,\n total: raw.total_tokens,\n cachedTokens: raw.input_tokens_details?.cached_tokens,\n cacheWriteTokens: raw.input_tokens_details?.cache_write_tokens,\n reasoningTokens: raw.output_tokens_details?.reasoning_tokens,\n });\n }\n\n /** Wrap (idempotently), log and return a failure for the caller to throw. */\n private logAndWrap(thrown: unknown): ReturnType<typeof wrapOpenAIError> {\n const wrapped = wrapOpenAIError(thrown);\n\n this.logger.error(LOG_MODULE, \"error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n\n return wrapped;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkCA,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BnB,IAAa,uBAAb,MAA2D;CAUzD,AAAO,YAAY,QAAgB,QAA2B,WAAmB,UAAU;gBAFzD;EAGhC,IAAI,aAAa,UACf,MAAM,IAAI,oBACR,qFAAqF,SAAS,KAC9F,EAAE,SAAS;GAAE;GAAU,OAAO,OAAO;GAAM,KAAK;EAAY,EAAE,CAChE;EAGF,KAAK,SAAS;EACd,KAAK,SAAS;EACd,KAAK,OAAO,OAAO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AAO,WAAW;GAChB,OAAO,IAAI;GACX,QAAQ,IAAI;GACZ,OAAO,IAAI;GACX,cAAc,IAAI,sBAAsB;GACxC,kBAAkB,IAAI,sBAAsB;GAC5C,iBAAiB,IAAI,uBAAuB;EAC9C,CAAC;CACH;;CAGA,AAAQ,WAAW,QAAqD;EACtE,MAAM,UAAU,gBAAgB,MAAM;EAEtC,KAAK,OAAO,MAAM,YAAY,SAAS,QAAQ,SAAS;GACtD,MAAM,QAAQ;GACd,SAAS,QAAQ;EACnB,CAAC;EAED,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"responses-model.mjs","names":[],"sources":["../../../../../../../packages/ai-openai/src/responses-model.ts"],"sourcesContent":["import {\n InvalidRequestError,\n ProviderError,\n resolveStreamChunks,\n safeJsonParse,\n selectProviderTools,\n type Message,\n type ModelCallOptions,\n type ModelCapabilities,\n type ModelContract,\n type ModelPricing,\n type ModelResponse,\n type ModelStreamChunk,\n type ModelToolCallRequest,\n type Usage,\n} from \"@warlock.js/ai\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport type OpenAI from \"openai\";\nimport { mergeProviderBody } from \"./provider-options\";\nimport type { OpenAIModelConfig } from \"./config.type\";\nimport { inferReasoningCapability } from \"./known-reasoning-models\";\nimport { inferVisionCapability } from \"./known-vision-models\";\nimport {\n attachReasoningReplay,\n buildPromptCacheParams,\n buildUsage,\n inferStructuredOutput,\n mapResponsesFinishReason,\n pickTurnReasoning,\n planStructuredOutput,\n toOpenAIReasoningEffort,\n toResponseFailure,\n toResponsesInput,\n toResponsesToolChoice,\n toResponsesTools,\n wrapOpenAIError,\n} from \"./utils\";\n\nconst LOG_MODULE = \"ai.openai\";\n\n/**\n * Responses output item types of built-in tools the CALLER must execute\n * (installed SDK `ResponseOutputItem` union). The adapter maps only\n * `function_call` to a neutral tool call, so these fail closed.\n */\nconst CLIENT_RUN_ITEM_TYPES: ReadonlySet<string> = new Set([\n \"computer_call\",\n \"custom_tool_call\",\n \"local_shell_call\",\n \"shell_call\",\n \"apply_patch_call\",\n \"mcp_approval_request\",\n]);\n\n/**\n * OpenAI Responses API implementation of `ModelContract` (`api: \"responses\"`).\n *\n * **Role.** A sibling of `OpenAIModel` that speaks `POST /v1/responses`\n * instead of Chat Completions. Its point is letting a tool-using agent run a\n * reasoning model with reasoning ON: the Chat path has to force\n * `reasoning_effort: \"none\"` whenever tools are attached, Responses does not.\n *\n * **Why a separate class.** Only `OpenAISDK.model()` constructs it, and only\n * for the direct `\"openai\"` provider. The wrapper packages (deepseek, groq,\n * xai, mistral) build `OpenAIModel` and cannot reach this class, so an\n * endpoint that does not implement `/v1/responses` is never sent there. The\n * constructor re-checks the provider label as a second lock.\n *\n * **Stateless.** Every request sends `store: false`; nothing is kept on the\n * server and no `previous_response_id` is used. Full history is re-sent each\n * call, exactly like the Chat path.\n *\n * **Reasoning replay.** Every request asks for\n * `include: [\"reasoning.encrypted_content\"]`. The `reasoning` items of a\n * tool-calling turn are stored on the FIRST tool call as\n * `providerMetadata.openaiResponses = { model, reasoningItems }` and sent back\n * before that turn's `function_call` items on the next request (only when the\n * stored model equals the current one). Text-only turns are not replayed.\n *\n * **Streaming.** `stream()` uses `responses.create({ stream: true })` and yields\n * the same chunk sequence as the Chat path: text `delta`s, then the\n * `tool-call`s, then one `done`. With `streamChunks` it also yields\n * `reasoning` (reasoning summary / reasoning text deltas) and `tool-args`\n * (`response.function_call_arguments.delta`).\n *\n * **Provider-defined tools.** `ai.providerTool({ provider: \"openai\" })`\n * definitions are appended to `tools` verbatim. Hosted tools run inside the\n * response; their output items (`web_search_call`, …) are not replayed\n * (with `store: false` the next turn only needs the answer text), and a\n * reasoning item that led into one is not replayed either (see\n * `pickTurnReasoning`).\n */\nexport class OpenAIResponsesModel implements ModelContract {\n public readonly name: string;\n public readonly provider: string;\n public readonly capabilities: ModelCapabilities;\n public readonly pricing?: ModelPricing;\n\n private readonly client: OpenAI;\n private readonly config: OpenAIModelConfig;\n private readonly logger: Logger = log;\n\n public constructor(client: OpenAI, config: OpenAIModelConfig, provider: string = \"openai\") {\n if (provider !== \"openai\") {\n throw new InvalidRequestError(\n `api: \"responses\" is supported only on the direct \"openai\" provider; got provider \"${provider}\".`,\n { context: { provider, model: config.name, api: \"responses\" } },\n );\n }\n\n this.client = client;\n this.config = config;\n this.name = config.name;\n this.provider = provider;\n this.pricing = config.pricing;\n this.capabilities = {\n structuredOutput: config.structuredOutput ?? inferStructuredOutput(config.responseFormat),\n vision: config.vision ?? inferVisionCapability(config.name),\n reasoning: config.reasoning ?? inferReasoningCapability(config.name),\n // Read-side cache accounting (`cachedTokens`, `cacheWriteTokens`) works\n // and `prompt_cache_key` is forwarded. Explicit write breakpoints are not\n // mapped onto Responses yet, so a `cacheControl.breakpoints` hint is\n // ignored rather than rejected.\n promptCaching: true,\n // PDF and audio input are off under Responses in this adapter: the\n // `input_file` / `input_audio` field-level mapping is unverified. The\n // `pdf` / `audio` config flags are deliberately NOT honoured here.\n pdf: false,\n audio: false,\n };\n }\n\n /**\n * Single-shot completion against `client.responses.create`. Sends the full\n * history as Responses `input` items, walks `response.output`, and reshapes\n * it into a vendor-neutral `ModelResponse`. Per-call `options` override the\n * instance defaults for this call only.\n */\n public async complete(messages: Message[], options?: ModelCallOptions): Promise<ModelResponse> {\n this.logger.debug(LOG_MODULE, \"request\", \"Starting call to responses.create\", {\n model: this.name,\n messageCount: messages.length,\n streaming: false,\n toolCount: options?.tools?.length ?? 0,\n });\n\n let response: OpenAI.Responses.Response;\n\n try {\n response = await this.client.responses.create(\n this.buildRequest(messages, options),\n options?.signal ? { signal: options.signal } : undefined,\n );\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n if (response.status === \"failed\") {\n throw this.logAndWrap(toResponseFailure(response, this.name));\n }\n\n const output = Array.isArray(response.output) ? response.output : [];\n const { content, toolCalls } = this.readOutput(output);\n const finishReason = mapResponsesFinishReason({\n status: response.status,\n incomplete_details: response.incomplete_details,\n hasToolCalls: toolCalls !== undefined,\n });\n const usage = this.extractUsage(response.usage);\n\n this.logger.debug(LOG_MODULE, \"response\", \"call to responses.create succeeded\", {\n finishReason,\n usage,\n });\n\n return { content, finishReason, usage, ...(toolCalls ? { toolCalls } : {}) };\n }\n\n /** Count native Responses input tokens using the same converted input and tools. */\n public async countTokens(messages: Message[], options?: ModelCallOptions): Promise<number> {\n const request = this.buildRequest(messages, options);\n const body: OpenAI.Responses.InputTokenCountParams = {\n model: request.model,\n input: request.input,\n instructions: request.instructions,\n tools: request.tools,\n tool_choice: request.tool_choice,\n reasoning: request.reasoning,\n text: request.text,\n parallel_tool_calls: request.parallel_tool_calls,\n truncation: request.truncation ?? undefined,\n };\n try {\n const response = await this.client.responses.inputTokens.count(\n body,\n options?.signal ? { signal: options.signal } : undefined,\n );\n return response.input_tokens;\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n }\n\n /**\n * Incremental streaming completion via `responses.create({ stream: true })`\n * (the SDK's `Stream<ResponseStreamEvent>`, `responses.d.ts:55`). Yields the\n * same neutral `ModelStreamChunk` sequence as the Chat path:\n *\n * - `response.output_text.delta` / `response.refusal.delta` -> `delta`.\n * - `response.output_item.done` with a completed `function_call` item ->\n * buffered; `reasoning` items are captured for replay. The `done` copy is\n * used because the `added` copy may be incomplete (`responses.d.ts:5711`).\n * - After the loop: the buffered `tool-call`s (the first carries the\n * replay metadata), then a single `done` with the finish reason and usage\n * from `response.completed` / `response.incomplete`.\n * - `response.failed` and `error` events throw a typed `AIError`; a stream\n * that ends with no terminal event throws `ProviderError`.\n * - Abort goes through the request `signal`; the SDK rejects the read and\n * the error is wrapped like any other.\n */\n public async *stream(\n messages: Message[],\n options?: ModelCallOptions,\n ): AsyncIterable<ModelStreamChunk> {\n this.logger.debug(LOG_MODULE, \"request\", \"Starting streaming call to responses.create\", {\n model: this.name,\n messageCount: messages.length,\n streaming: true,\n toolCount: options?.tools?.length ?? 0,\n });\n\n let events: AsyncIterable<OpenAI.Responses.ResponseStreamEvent>;\n\n try {\n events = await this.client.responses.create(\n { ...this.buildRequest(messages, options), stream: true },\n options?.signal ? { signal: options.signal } : undefined,\n );\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n const toolCalls: ModelToolCallRequest[] = [];\n const outputItems: OpenAI.Responses.ResponseOutputItem[] = [];\n const want = resolveStreamChunks(options);\n // `function_call_arguments.delta` names its item by `item_id` only; the\n // `call_id` and `name` come from that item's `output_item.added`.\n const streamingCalls = new Map<string, { callId: string; name: string }>();\n let terminal: OpenAI.Responses.Response | undefined;\n\n try {\n for await (const event of events) {\n if (\n event.type === \"response.output_text.delta\" ||\n event.type === \"response.refusal.delta\"\n ) {\n if (event.delta) {\n yield { type: \"delta\", content: event.delta };\n }\n\n continue;\n }\n\n if (\n event.type === \"response.reasoning_summary_text.delta\" ||\n event.type === \"response.reasoning_text.delta\"\n ) {\n if (want.reasoning && event.delta) {\n yield { type: \"reasoning\", delta: event.delta };\n }\n\n continue;\n }\n\n if (event.type === \"response.output_item.added\") {\n const { item } = event;\n\n if (item.type === \"function_call\" && item.id) {\n streamingCalls.set(item.id, { callId: item.call_id, name: item.name });\n }\n\n continue;\n }\n\n if (event.type === \"response.function_call_arguments.delta\") {\n const call = streamingCalls.get(event.item_id);\n\n if (want.toolArgs && call && event.delta) {\n yield { type: \"tool-args\", callId: call.callId, name: call.name, delta: event.delta };\n }\n\n continue;\n }\n\n if (event.type === \"response.output_item.done\") {\n const { item } = event;\n\n this.assertServerRunItem(item);\n outputItems.push(item);\n\n if (item.type === \"function_call\" && item.status !== \"incomplete\") {\n toolCalls.push(this.toToolCall(item));\n }\n\n continue;\n }\n\n if (event.type === \"response.completed\" || event.type === \"response.incomplete\") {\n terminal = event.response;\n continue;\n }\n\n if (event.type === \"response.failed\") {\n throw toResponseFailure(event.response, this.name);\n }\n\n if (event.type === \"error\") {\n throw wrapOpenAIError({ code: event.code, message: event.message, param: event.param });\n }\n }\n\n if (terminal === undefined) {\n throw new ProviderError(\"OpenAI Responses stream ended before response.completed.\", {\n context: { provider: this.provider, model: this.name },\n });\n }\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n for (const call of attachReasoningReplay(\n toolCalls,\n this.name,\n pickTurnReasoning(outputItems),\n )) {\n yield {\n type: \"tool-call\",\n id: call.id,\n name: call.name,\n input: call.input,\n ...(call.providerMetadata ? { providerMetadata: call.providerMetadata } : {}),\n };\n }\n\n const finishReason = mapResponsesFinishReason({\n status: terminal.status,\n incomplete_details: terminal.incomplete_details,\n hasToolCalls: toolCalls.length > 0,\n });\n const usage = this.extractUsage(terminal.usage);\n\n this.logger.debug(LOG_MODULE, \"response\", \"Streaming call to responses.create succeeded\", {\n finishReason,\n usage,\n });\n\n yield { type: \"done\", finishReason, usage };\n }\n\n /**\n * Assemble the `responses.create` body.\n *\n * - System prompt -> `instructions`; history -> `input` items.\n * - `store: false` always (the API default is `true` when omitted), plus\n * `include: [\"reasoning.encrypted_content\"]` for stateless reasoning replay.\n * - `max_output_tokens` caps reasoning and visible output together.\n * - `temperature` only for non-reasoning models (same rule as Chat).\n * - `tools` flat with `strict: false`; `tool_choice` only with tools.\n * - `reasoning.effort` only when the caller gave one, through the same\n * clamp table as Chat. With no explicit effort the provider default\n * applies EVEN with tools attached - that is the point of this API.\n */\n private buildRequest(\n messages: Message[],\n options: ModelCallOptions | undefined,\n ): OpenAI.Responses.ResponseCreateParamsNonStreaming {\n const { instructions, input } = toResponsesInput(messages, this.name);\n const tools = this.buildTools(options);\n const toolChoice = tools ? toResponsesToolChoice(options?.toolChoice) : undefined;\n const maxTokens = options?.maxTokens ?? this.config.maxTokens;\n const temperature = options?.temperature ?? this.config.temperature;\n\n return mergeProviderBody<OpenAI.Responses.ResponseCreateParamsNonStreaming>(\n {\n model: this.name,\n ...(instructions !== undefined ? { instructions } : {}),\n input,\n store: false,\n // Stateless replay: ask for the encrypted reasoning blobs so they can be\n // sent back on the next tool turn (decision 3).\n include: [\"reasoning.encrypted_content\"],\n ...(maxTokens !== undefined ? { max_output_tokens: maxTokens } : {}),\n ...(!this.capabilities.reasoning && temperature !== undefined ? { temperature } : {}),\n ...(tools ? { tools } : {}),\n ...(toolChoice !== undefined ? { tool_choice: toolChoice } : {}),\n ...this.buildTextFormat(options?.responseSchema),\n ...this.buildReasoningParams(options?.reasoning),\n ...buildPromptCacheParams(this.provider, this.config),\n },\n options,\n );\n }\n\n /**\n * The request `tools`: function tools (flat, `strict: false`), then the\n * `ai.providerTool({ provider: \"openai\" })` definitions verbatim — the\n * Responses built-in tools (`web_search`, `file_search`,\n * `code_interpreter`, `image_generation`, `mcp`, …). Other providers'\n * definitions are skipped with a warning. `undefined` when there are none.\n */\n private buildTools(options: ModelCallOptions | undefined): OpenAI.Responses.Tool[] | undefined {\n const { tools, definitions } = selectProviderTools(options, {\n accepts: [this.provider],\n module: LOG_MODULE,\n model: this.name,\n logger: this.logger,\n });\n const mapped: OpenAI.Responses.Tool[] = [\n ...(toResponsesTools(tools) ?? []),\n ...(definitions as unknown as OpenAI.Responses.Tool[]),\n ];\n\n return mapped.length > 0 ? mapped : undefined;\n }\n\n /**\n * Structured output on Responses lives in `text.format`, and `name` /\n * `schema` / `strict` sit directly on the format object (Chat nests them\n * under `json_schema`). The strict-or-downgrade decision is the shared\n * `planStructuredOutput`.\n */\n private buildTextFormat(responseSchema: Record<string, unknown> | undefined): {\n text?: OpenAI.Responses.ResponseTextConfig;\n } {\n const plan = planStructuredOutput(responseSchema, this.config.responseFormat);\n\n if (plan.mode === \"json_schema\") {\n return {\n text: {\n format: { type: \"json_schema\", name: \"response\", schema: plan.schema, strict: true },\n },\n };\n }\n\n if (plan.mode === \"json_object\") {\n return { text: { format: { type: \"json_object\" } } };\n }\n\n return {};\n }\n\n /** `reasoning.effort` for reasoning-capable models, only when the caller set one. */\n private buildReasoningParams(reasoning: ModelCallOptions[\"reasoning\"]): {\n reasoning?: { effort: ReturnType<typeof toOpenAIReasoningEffort> };\n } {\n if (!this.capabilities.reasoning || !reasoning?.effort) {\n return {};\n }\n\n return { reasoning: { effort: toOpenAIReasoningEffort(reasoning.effort) } };\n }\n\n /**\n * Walk `response.output`: `message` items contribute their `output_text`\n * text and any `refusal` text (surfaced as ordinary content, decision 5);\n * each completed `function_call` item becomes one tool call with\n * `id = call_id`. `reasoning` items carry no visible content and are\n * not content. A `function_call` the API marked `incomplete` (truncated\n * arguments) is skipped rather than dispatched with empty input.\n * `reasoning` items are captured and attached to the first tool call for\n * replay (see `attachReasoningReplay`).\n */\n private readOutput(output: OpenAI.Responses.ResponseOutputItem[]): {\n content: string;\n toolCalls: ModelToolCallRequest[] | undefined;\n } {\n let content = \"\";\n const toolCalls: ModelToolCallRequest[] = [];\n\n for (const item of output) {\n this.assertServerRunItem(item);\n\n if (item.type === \"message\") {\n for (const part of item.content) {\n content += part.type === \"refusal\" ? part.refusal : part.text;\n }\n\n continue;\n }\n\n if (item.type === \"function_call\" && item.status !== \"incomplete\") {\n toolCalls.push(this.toToolCall(item));\n }\n }\n\n return {\n content,\n toolCalls:\n toolCalls.length > 0\n ? attachReasoningReplay(toolCalls, this.name, pickTurnReasoning(output))\n : undefined,\n };\n }\n\n /**\n * Fail closed on a built-in tool call that YOUR code would have to run\n * (`shell_call`, `apply_patch_call`, `computer_call`, …, from a\n * provider-defined client tool). These items have their own output item\n * types that this adapter does not map, so the turn would otherwise end\n * silently with the call dropped. Hosted (server-run) tool items pass.\n */\n private assertServerRunItem(item: { type: string }): void {\n if (!CLIENT_RUN_ITEM_TYPES.has(item.type)) {\n return;\n }\n\n throw new InvalidRequestError(\n `OpenAI returned a \"${item.type}\" item: that built-in tool is executed by the caller, ` +\n \"which the Responses adapter does not support. Use OpenAI's server-run built-in tools \" +\n \"(web_search, file_search, code_interpreter, image_generation, mcp without approval) \" +\n \"with ai.providerTool(), or a function tool from ai.tool().\",\n { context: { provider: this.provider, model: this.name, itemType: item.type } },\n );\n }\n\n /** One completed `function_call` item as a neutral tool call (`call_id` -> `id`). */\n private toToolCall(item: OpenAI.Responses.ResponseFunctionToolCall): ModelToolCallRequest {\n return {\n id: item.call_id,\n name: item.name,\n input: safeJsonParse<Record<string, unknown>>(item.arguments, {}),\n };\n }\n\n /**\n * Normalize `usage` (absent on some partials) into the neutral `Usage`.\n * `input_tokens_details.cached_tokens` -> `cachedTokens`,\n * `cache_write_tokens` -> `cacheWriteTokens`,\n * `output_tokens_details.reasoning_tokens` -> `reasoningTokens`. The\n * detail blocks are typed non-optional but read defensively.\n */\n private extractUsage(raw: OpenAI.Responses.ResponseUsage | undefined): Usage {\n if (!raw) {\n return { input: 0, output: 0, total: 0 };\n }\n\n return buildUsage(\n {\n input: raw.input_tokens,\n output: raw.output_tokens,\n total: raw.total_tokens,\n cachedTokens: raw.input_tokens_details?.cached_tokens,\n cacheWriteTokens: raw.input_tokens_details?.cache_write_tokens,\n reasoningTokens: raw.output_tokens_details?.reasoning_tokens,\n },\n this.pricing,\n );\n }\n\n /** Wrap (idempotently), log and return a failure for the caller to throw. */\n private logAndWrap(thrown: unknown): ReturnType<typeof wrapOpenAIError> {\n const wrapped = wrapOpenAIError(thrown);\n\n this.logger.error(LOG_MODULE, \"error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n\n return wrapped;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAsCA,MAAM,aAAa;;;;;;AAOnB,MAAM,wBAA6C,IAAI,IAAI;CACzD;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCD,IAAa,uBAAb,MAA2D;CAUzD,AAAO,YAAY,QAAgB,QAA2B,WAAmB,UAAU;gBAFzD;EAGhC,IAAI,aAAa,UACf,MAAM,IAAI,oBACR,qFAAqF,SAAS,KAC9F,EAAE,SAAS;GAAE;GAAU,OAAO,OAAO;GAAM,KAAK;EAAY,EAAE,CAChE;EAGF,KAAK,SAAS;EACd,KAAK,SAAS;EACd,KAAK,OAAO,OAAO;EACnB,KAAK,WAAW;EAChB,KAAK,UAAU,OAAO;EAC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AU,KAAK;EAAK,EAAE,CAChF;CACF;;CAGA,AAAQ,WAAW,MAAuE;EACxF,OAAO;GACL,IAAI,KAAK;GACT,MAAM,KAAK;GACX,OAAO,cAAuC,KAAK,WAAW,CAAC,CAAC;EAClE;CACF;;;;;;;;CASA,AAAQ,aAAa,KAAwD;EAC3E,IAAI,CAAC,KACH,OAAO;GAAE,OAAO;GAAG,QAAQ;GAAG,OAAO;EAAE;EAGzC,OAAO,WACL;GACE,OAAO,IAAI;GACX,QAAQ,IAAI;GACZ,OAAO,IAAI;GACX,cAAc,IAAI,sBAAsB;GACxC,kBAAkB,IAAI,sBAAsB;GAC5C,iBAAiB,IAAI,uBAAuB;EAC9C,GACA,KAAK,OACP;CACF;;CAGA,AAAQ,WAAW,QAAqD;EACtE,MAAM,UAAU,gBAAgB,MAAM;EAEtC,KAAK,OAAO,MAAM,YAAY,SAAS,QAAQ,SAAS;GACtD,MAAM,QAAQ;GACd,SAAS,QAAQ;EACnB,CAAC;EAED,OAAO;CACT;AACF"}
package/esm/sdk.d.mts CHANGED
@@ -50,8 +50,9 @@ declare class OpenAISDK implements SDKAdapterContract {
50
50
  * coming from the same upstream.
51
51
  *
52
52
  * Pricing resolution: per-model `config.pricing` wins; otherwise the
53
- * SDK-level registry entry keyed by `config.name`; otherwise
54
- * `undefined` (no cost computed).
53
+ * SDK-level registry entry keyed by `config.name`; otherwise, when the
54
+ * provider label is `"openai"`, the built-in list price
55
+ * (`OPENAI_MODEL_PRICING`); otherwise `undefined` (no cost computed).
55
56
  *
56
57
  * `config.api` selects the wire API. Omitted or `"chat"` builds the Chat
57
58
  * Completions `OpenAIModel`. `"responses"` builds `OpenAIResponsesModel`
package/esm/sdk.d.mts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.d.mts","names":[],"sources":["../../../../../../../packages/ai-openai/src/sdk.ts"],"mappings":";;;;;;AA4DA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAAa,SAAA,YAAqB,kBAAA;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 import { openAIPricingFor } from "./known-pricing.mjs";
1
2
  import { OpenAIEmbedder } from "./embedder.mjs";
2
3
  import { OpenAIImageModel } from "./image.mjs";
3
4
  import { OpenAIModel } from "./model.mjs";
@@ -58,8 +59,9 @@ var OpenAISDK = class {
58
59
  * coming from the same upstream.
59
60
  *
60
61
  * Pricing resolution: per-model `config.pricing` wins; otherwise the
61
- * SDK-level registry entry keyed by `config.name`; otherwise
62
- * `undefined` (no cost computed).
62
+ * SDK-level registry entry keyed by `config.name`; otherwise, when the
63
+ * provider label is `"openai"`, the built-in list price
64
+ * (`OPENAI_MODEL_PRICING`); otherwise `undefined` (no cost computed).
63
65
  *
64
66
  * `config.api` selects the wire API. Omitted or `"chat"` builds the Chat
65
67
  * Completions `OpenAIModel`. `"responses"` builds `OpenAIResponsesModel`
@@ -80,7 +82,7 @@ var OpenAISDK = class {
80
82
  model: config.name,
81
83
  api
82
84
  } });
83
- const resolvedPricing = config.pricing ?? this.pricing?.[config.name];
85
+ const resolvedPricing = config.pricing ?? this.pricing?.[config.name] ?? (this.provider === "openai" ? openAIPricingFor(config.name) : void 0);
84
86
  const resolvedConfig = resolvedPricing === config.pricing ? config : {
85
87
  ...config,
86
88
  pricing: resolvedPricing
package/esm/sdk.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.mjs","names":[],"sources":["../../../../../../../packages/ai-openai/src/sdk.ts"],"sourcesContent":["import OpenAI from \"openai\";\nimport type {\n EmbedderContract,\n ImageModelContract,\n ModelContract,\n ModelPricing,\n SDKAdapterContract,\n SpeechModelContract,\n TranscriptionModelContract,\n} from \"@warlock.js/ai\";\nimport { InvalidRequestError, approximateTokenCount } from \"@warlock.js/ai\";\nimport type {\n OpenAIEmbedderConfig,\n OpenAIImageConfig,\n OpenAIModelConfig,\n OpenAISDKConfig,\n OpenAISpeechConfig,\n OpenAITranscriptionConfig,\n} from \"./config.type\";\nimport { OpenAIEmbedder } from \"./embedder\";\nimport { OpenAIImageModel } from \"./image\";\nimport { OpenAIModel } from \"./model\";\nimport { OpenAIResponsesModel } from \"./responses-model\";\nimport { OpenAISpeechModel } from \"./speech\";\nimport { OpenAITranscriptionModel } from \"./transcription\";\n\n/**\n * OpenAI-backed implementation of `SDKAdapterContract`.\n *\n * **Role.** The package entry point for any OpenAI-compatible provider\n * (OpenAI, Azure OpenAI, OpenRouter, local gateways speaking the Chat\n * Completions protocol). A single `OpenAISDK` instance holds one live\n * `OpenAI` client, shared by every `ModelContract` it produces via\n * `model()`. Users construct one SDK per provider/account and reuse it\n * across all agents, workflows, and supervisors that target that\n * provider.\n *\n * **Responsibility.**\n * - Owns: a long-lived `OpenAI` client (authentication, base URL) and\n * its lifetime scope. Factory for `OpenAIModel` instances — each\n * model call gets a reference to the same client.\n * - Does NOT own: anything per-call (tool execution, message history,\n * streaming loop) — those live in `OpenAIModel` and the agent runtime.\n *\n * Modeled as a class (see §4.2 of code-style.md — \"long-lived state\n * across many calls\"): the `OpenAI` client is heavy to construct and\n * designed to be reused; keeping it on `this` makes that reuse\n * explicit and aligns with the PascalCase naming convention readers\n * expect from a constructor.\n *\n * @example\n * const openai = new OpenAISDK({ apiKey: process.env.OPENAI_API_KEY! });\n * const model = openai.model({ name: \"gpt-4o\", temperature: 0.7 });\n * const tokens = await openai.count(\"Hello world\");\n *\n * @example\n * // Compose into an `ai.openai` namespace for ergonomic agent wiring\n * const ai = { agent, tool, systemPrompt, persona, instruction, openai: new OpenAISDK({ apiKey }) };\n * const myAgent = ai.agent({ model: ai.openai.model({ name: \"gpt-4o-mini\" }) });\n */\nexport class OpenAISDK implements SDKAdapterContract {\n private readonly client: OpenAI;\n private readonly provider: string;\n private readonly pricing?: Record<string, ModelPricing>;\n\n public constructor(config: OpenAISDKConfig) {\n // Peel off the framework-only keys and forward every other upstream\n // `ClientOptions` (timeout, maxRetries, defaultHeaders, fetch,\n // organization, project, …) verbatim — they type-check, so dropping them\n // is a silent footgun. Mirrors the Bedrock/Google/Ollama adapters.\n const { provider, pricing, ...clientOptions } = config;\n\n this.client = new OpenAI(clientOptions);\n this.provider = provider ?? \"openai\";\n this.pricing = pricing;\n }\n\n /**\n * Build an `OpenAIModel` bound to this SDK's client. Each call returns\n * a fresh model instance, but all instances share the underlying\n * `OpenAI` client — connection pools, rate limits, and authentication\n * state stay unified across every model produced here. The SDK's\n * `provider` label is forwarded so every model self-identifies as\n * coming from the same upstream.\n *\n * Pricing resolution: per-model `config.pricing` wins; otherwise the\n * SDK-level registry entry keyed by `config.name`; otherwise\n * `undefined` (no cost computed).\n *\n * `config.api` selects the wire API. Omitted or `\"chat\"` builds the Chat\n * Completions `OpenAIModel`. `\"responses\"` builds `OpenAIResponsesModel`\n * and is accepted ONLY when this SDK's provider label is `\"openai\"`: any\n * other label (the wrapper packages deepseek / groq / xai / mistral, or a\n * custom gateway label) throws, so an endpoint not known to implement\n * `/v1/responses` is never sent there.\n */\n public model(config: OpenAIModelConfig): ModelContract {\n const api: unknown = config.api;\n\n if (api !== undefined && api !== \"chat\" && api !== \"responses\") {\n throw new InvalidRequestError(\n `Unknown OpenAI api \"${String(api)}\"; expected \"chat\" or \"responses\".`,\n { context: { provider: this.provider, model: config.name, api } },\n );\n }\n\n if (api === \"responses\" && this.provider !== \"openai\") {\n throw new InvalidRequestError(\n `api: \"responses\" is supported only on the direct \"openai\" provider; this SDK is labeled \"${this.provider}\". Use the default api: \"chat\".`,\n { context: { provider: this.provider, model: config.name, api } },\n );\n }\n\n const resolvedPricing = config.pricing ?? this.pricing?.[config.name];\n const resolvedConfig: OpenAIModelConfig =\n resolvedPricing === config.pricing ? config : { ...config, pricing: resolvedPricing };\n\n if (api === \"responses\") {\n return new OpenAIResponsesModel(this.client, resolvedConfig, this.provider);\n }\n\n return new OpenAIModel(this.client, resolvedConfig, this.provider);\n }\n\n /**\n * Rough token-count estimate for a given text. Uses a\n * character-heuristic (`approximateTokenCount`) from the core package\n * — good enough for budgeting and quota guards, not for billing.\n * Accepts an optional model id for future per-model tokenizer\n * dispatch; currently ignored.\n */\n public async count(text: string, _model?: string): Promise<number> {\n return approximateTokenCount(text);\n }\n\n /**\n * Build an `OpenAIEmbedder` bound to this SDK's client. Each call\n * returns a fresh embedder instance sharing the same underlying\n * `OpenAI` client — connection pools and authentication stay unified\n * across every embedder produced here.\n *\n * @example\n * const embedder = openai.embedder({ name: \"text-embedding-3-small\" });\n * const { vector } = await embedder.embed(\"Hello world\");\n */\n public embedder(config: OpenAIEmbedderConfig): EmbedderContract {\n return new OpenAIEmbedder(this.client, config);\n }\n\n /**\n * Build an `OpenAIImageModel` bound to this SDK's client for use with\n * `ai.image({ model, prompt })`. `config.name` is passed through to\n * `client.images.generate` as given — no id is rejected locally, so\n * an unsupported model fails at OpenAI, not here. Metering follows\n * the family: `gpt-image-*` is token-metered, `dall-e-*` per-image.\n *\n * Pricing resolution mirrors `model()`: per-model `config.pricing`\n * wins, otherwise the SDK-level registry entry keyed by `config.name`,\n * otherwise `undefined` (no cost computed). A token-priced\n * `gpt-image-1` entry can live in the same SDK registry as the chat\n * models.\n *\n * @example\n * const model = openai.image({ name: \"gpt-image-1\" });\n * const { data } = await ai.image({ model, prompt: \"a red bicycle\" });\n */\n public image(config: OpenAIImageConfig): ImageModelContract {\n const resolvedPricing = config.pricing ?? this.pricing?.[config.name];\n const resolvedConfig: OpenAIImageConfig =\n resolvedPricing === config.pricing ? config : { ...config, pricing: resolvedPricing };\n\n return new OpenAIImageModel(this.client, resolvedConfig, this.provider);\n }\n\n /**\n * Build an `OpenAISpeechModel` (text-to-speech) bound to this SDK's\n * client, for use with `ai.speech({ model, text })`. `config.name` is\n * passed through to `audio.speech.create` as given — no id is\n * rejected locally, so an unsupported model fails at OpenAI, not\n * here.\n *\n * @example\n * const tts = openai.speech({ name: \"tts-1\", voice: \"alloy\" });\n * const { data } = await ai.speech({ model: tts, text: \"Hello\" });\n */\n public speech(config: OpenAISpeechConfig): SpeechModelContract {\n return new OpenAISpeechModel(this.client, config, this.provider);\n }\n\n /**\n * Build an `OpenAITranscriptionModel` (speech-to-text) bound to this\n * SDK's client, for use with `ai.transcribe({ model, audio })`.\n * `config.name` is passed through to `audio.transcriptions.create`\n * as given — no id is rejected locally, so an unsupported model\n * fails at OpenAI, not here.\n *\n * @example\n * const stt = openai.transcribe({ name: \"whisper-1\" });\n * const { data } = await ai.transcribe({ model: stt, audio });\n */\n public transcribe(config: OpenAITranscriptionConfig): TranscriptionModelContract {\n return new OpenAITranscriptionModel(this.client, config, this.provider);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DA,IAAa,YAAb,MAAqD;CAKnD,AAAO,YAAY,QAAyB;EAK1C,MAAM,EAAE,UAAU,SAAS,GAAG,kBAAkB;EAEhD,KAAK,SAAS,IAAI,OAAO,aAAa;EACtC,KAAK,WAAW,YAAY;EAC5B,KAAK,UAAU;CACjB;;;;;;;;;;;;;;;;;;;;CAqBA,AAAO,MAAM,QAA0C;EACrD,MAAM,MAAe,OAAO;EAE5B,IAAI,QAAQ,UAAa,QAAQ,UAAU,QAAQ,aACjD,MAAM,IAAI,oBACR,uBAAuB,OAAO,GAAG,EAAE,qCACnC,EAAE,SAAS;GAAE,UAAU,KAAK;GAAU,OAAO,OAAO;GAAM;EAAI,EAAE,CAClE;EAGF,IAAI,QAAQ,eAAe,KAAK,aAAa,UAC3C,MAAM,IAAI,oBACR,4FAA4F,KAAK,SAAS,kCAC1G,EAAE,SAAS;GAAE,UAAU,KAAK;GAAU,OAAO,OAAO;GAAM;EAAI,EAAE,CAClE;EAGF,MAAM,kBAAkB,OAAO,WAAW,KAAK,UAAU,OAAO;EAChE,MAAM,iBACJ,oBAAoB,OAAO,UAAU,SAAS;GAAE,GAAG;GAAQ,SAAS;EAAgB;EAEtF,IAAI,QAAQ,aACV,OAAO,IAAI,qBAAqB,KAAK,QAAQ,gBAAgB,KAAK,QAAQ;EAG5E,OAAO,IAAI,YAAY,KAAK,QAAQ,gBAAgB,KAAK,QAAQ;CACnE;;;;;;;;CASA,MAAa,MAAM,MAAc,QAAkC;EACjE,OAAO,sBAAsB,IAAI;CACnC;;;;;;;;;;;CAYA,AAAO,SAAS,QAAgD;EAC9D,OAAO,IAAI,eAAe,KAAK,QAAQ,MAAM;CAC/C;;;;;;;;;;;;;;;;;;CAmBA,AAAO,MAAM,QAA+C;EAC1D,MAAM,kBAAkB,OAAO,WAAW,KAAK,UAAU,OAAO;EAChE,MAAM,iBACJ,oBAAoB,OAAO,UAAU,SAAS;GAAE,GAAG;GAAQ,SAAS;EAAgB;EAEtF,OAAO,IAAI,iBAAiB,KAAK,QAAQ,gBAAgB,KAAK,QAAQ;CACxE;;;;;;;;;;;;CAaA,AAAO,OAAO,QAAiD;EAC7D,OAAO,IAAI,kBAAkB,KAAK,QAAQ,QAAQ,KAAK,QAAQ;CACjE;;;;;;;;;;;;CAaA,AAAO,WAAW,QAA+D;EAC/E,OAAO,IAAI,yBAAyB,KAAK,QAAQ,QAAQ,KAAK,QAAQ;CACxE;AACF"}
1
+ {"version":3,"file":"sdk.mjs","names":[],"sources":["../../../../../../../packages/ai-openai/src/sdk.ts"],"sourcesContent":["import OpenAI from \"openai\";\nimport type {\n EmbedderContract,\n ImageModelContract,\n ModelContract,\n ModelPricing,\n SDKAdapterContract,\n SpeechModelContract,\n TranscriptionModelContract,\n} from \"@warlock.js/ai\";\nimport { InvalidRequestError, approximateTokenCount } from \"@warlock.js/ai\";\nimport { openAIPricingFor } from \"./known-pricing\";\nimport type {\n OpenAIEmbedderConfig,\n OpenAIImageConfig,\n OpenAIModelConfig,\n OpenAISDKConfig,\n OpenAISpeechConfig,\n OpenAITranscriptionConfig,\n} from \"./config.type\";\nimport { OpenAIEmbedder } from \"./embedder\";\nimport { OpenAIImageModel } from \"./image\";\nimport { OpenAIModel } from \"./model\";\nimport { OpenAIResponsesModel } from \"./responses-model\";\nimport { OpenAISpeechModel } from \"./speech\";\nimport { OpenAITranscriptionModel } from \"./transcription\";\n\n/**\n * OpenAI-backed implementation of `SDKAdapterContract`.\n *\n * **Role.** The package entry point for any OpenAI-compatible provider\n * (OpenAI, Azure OpenAI, OpenRouter, local gateways speaking the Chat\n * Completions protocol). A single `OpenAISDK` instance holds one live\n * `OpenAI` client, shared by every `ModelContract` it produces via\n * `model()`. Users construct one SDK per provider/account and reuse it\n * across all agents, workflows, and supervisors that target that\n * provider.\n *\n * **Responsibility.**\n * - Owns: a long-lived `OpenAI` client (authentication, base URL) and\n * its lifetime scope. Factory for `OpenAIModel` instances — each\n * model call gets a reference to the same client.\n * - Does NOT own: anything per-call (tool execution, message history,\n * streaming loop) — those live in `OpenAIModel` and the agent runtime.\n *\n * Modeled as a class (see §4.2 of code-style.md — \"long-lived state\n * across many calls\"): the `OpenAI` client is heavy to construct and\n * designed to be reused; keeping it on `this` makes that reuse\n * explicit and aligns with the PascalCase naming convention readers\n * expect from a constructor.\n *\n * @example\n * const openai = new OpenAISDK({ apiKey: process.env.OPENAI_API_KEY! });\n * const model = openai.model({ name: \"gpt-4o\", temperature: 0.7 });\n * const tokens = await openai.count(\"Hello world\");\n *\n * @example\n * // Compose into an `ai.openai` namespace for ergonomic agent wiring\n * const ai = { agent, tool, systemPrompt, persona, instruction, openai: new OpenAISDK({ apiKey }) };\n * const myAgent = ai.agent({ model: ai.openai.model({ name: \"gpt-4o-mini\" }) });\n */\nexport class OpenAISDK implements SDKAdapterContract {\n private readonly client: OpenAI;\n private readonly provider: string;\n private readonly pricing?: Record<string, ModelPricing>;\n\n public constructor(config: OpenAISDKConfig) {\n // Peel off the framework-only keys and forward every other upstream\n // `ClientOptions` (timeout, maxRetries, defaultHeaders, fetch,\n // organization, project, …) verbatim — they type-check, so dropping them\n // is a silent footgun. Mirrors the Bedrock/Google/Ollama adapters.\n const { provider, pricing, ...clientOptions } = config;\n\n this.client = new OpenAI(clientOptions);\n this.provider = provider ?? \"openai\";\n this.pricing = pricing;\n }\n\n /**\n * Build an `OpenAIModel` bound to this SDK's client. Each call returns\n * a fresh model instance, but all instances share the underlying\n * `OpenAI` client — connection pools, rate limits, and authentication\n * state stay unified across every model produced here. The SDK's\n * `provider` label is forwarded so every model self-identifies as\n * coming from the same upstream.\n *\n * Pricing resolution: per-model `config.pricing` wins; otherwise the\n * SDK-level registry entry keyed by `config.name`; otherwise, when the\n * provider label is `\"openai\"`, the built-in list price\n * (`OPENAI_MODEL_PRICING`); otherwise `undefined` (no cost computed).\n *\n * `config.api` selects the wire API. Omitted or `\"chat\"` builds the Chat\n * Completions `OpenAIModel`. `\"responses\"` builds `OpenAIResponsesModel`\n * and is accepted ONLY when this SDK's provider label is `\"openai\"`: any\n * other label (the wrapper packages deepseek / groq / xai / mistral, or a\n * custom gateway label) throws, so an endpoint not known to implement\n * `/v1/responses` is never sent there.\n */\n public model(config: OpenAIModelConfig): ModelContract {\n const api: unknown = config.api;\n\n if (api !== undefined && api !== \"chat\" && api !== \"responses\") {\n throw new InvalidRequestError(\n `Unknown OpenAI api \"${String(api)}\"; expected \"chat\" or \"responses\".`,\n { context: { provider: this.provider, model: config.name, api } },\n );\n }\n\n if (api === \"responses\" && this.provider !== \"openai\") {\n throw new InvalidRequestError(\n `api: \"responses\" is supported only on the direct \"openai\" provider; this SDK is labeled \"${this.provider}\". Use the default api: \"chat\".`,\n { context: { provider: this.provider, model: config.name, api } },\n );\n }\n\n const resolvedPricing =\n config.pricing ??\n this.pricing?.[config.name] ??\n (this.provider === \"openai\" ? openAIPricingFor(config.name) : undefined);\n const resolvedConfig: OpenAIModelConfig =\n resolvedPricing === config.pricing ? config : { ...config, pricing: resolvedPricing };\n\n if (api === \"responses\") {\n return new OpenAIResponsesModel(this.client, resolvedConfig, this.provider);\n }\n\n return new OpenAIModel(this.client, resolvedConfig, this.provider);\n }\n\n /**\n * Rough token-count estimate for a given text. Uses a\n * character-heuristic (`approximateTokenCount`) from the core package\n * — good enough for budgeting and quota guards, not for billing.\n * Accepts an optional model id for future per-model tokenizer\n * dispatch; currently ignored.\n */\n public async count(text: string, _model?: string): Promise<number> {\n return approximateTokenCount(text);\n }\n\n /**\n * Build an `OpenAIEmbedder` bound to this SDK's client. Each call\n * returns a fresh embedder instance sharing the same underlying\n * `OpenAI` client — connection pools and authentication stay unified\n * across every embedder produced here.\n *\n * @example\n * const embedder = openai.embedder({ name: \"text-embedding-3-small\" });\n * const { vector } = await embedder.embed(\"Hello world\");\n */\n public embedder(config: OpenAIEmbedderConfig): EmbedderContract {\n return new OpenAIEmbedder(this.client, config);\n }\n\n /**\n * Build an `OpenAIImageModel` bound to this SDK's client for use with\n * `ai.image({ model, prompt })`. `config.name` is passed through to\n * `client.images.generate` as given — no id is rejected locally, so\n * an unsupported model fails at OpenAI, not here. Metering follows\n * the family: `gpt-image-*` is token-metered, `dall-e-*` per-image.\n *\n * Pricing resolution mirrors `model()`: per-model `config.pricing`\n * wins, otherwise the SDK-level registry entry keyed by `config.name`,\n * otherwise `undefined` (no cost computed). A token-priced\n * `gpt-image-1` entry can live in the same SDK registry as the chat\n * models.\n *\n * @example\n * const model = openai.image({ name: \"gpt-image-1\" });\n * const { data } = await ai.image({ model, prompt: \"a red bicycle\" });\n */\n public image(config: OpenAIImageConfig): ImageModelContract {\n const resolvedPricing = config.pricing ?? this.pricing?.[config.name];\n const resolvedConfig: OpenAIImageConfig =\n resolvedPricing === config.pricing ? config : { ...config, pricing: resolvedPricing };\n\n return new OpenAIImageModel(this.client, resolvedConfig, this.provider);\n }\n\n /**\n * Build an `OpenAISpeechModel` (text-to-speech) bound to this SDK's\n * client, for use with `ai.speech({ model, text })`. `config.name` is\n * passed through to `audio.speech.create` as given — no id is\n * rejected locally, so an unsupported model fails at OpenAI, not\n * here.\n *\n * @example\n * const tts = openai.speech({ name: \"tts-1\", voice: \"alloy\" });\n * const { data } = await ai.speech({ model: tts, text: \"Hello\" });\n */\n public speech(config: OpenAISpeechConfig): SpeechModelContract {\n return new OpenAISpeechModel(this.client, config, this.provider);\n }\n\n /**\n * Build an `OpenAITranscriptionModel` (speech-to-text) bound to this\n * SDK's client, for use with `ai.transcribe({ model, audio })`.\n * `config.name` is passed through to `audio.transcriptions.create`\n * as given — no id is rejected locally, so an unsupported model\n * fails at OpenAI, not here.\n *\n * @example\n * const stt = openai.transcribe({ name: \"whisper-1\" });\n * const { data } = await ai.transcribe({ model: stt, audio });\n */\n public transcribe(config: OpenAITranscriptionConfig): TranscriptionModelContract {\n return new OpenAITranscriptionModel(this.client, config, this.provider);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,IAAa,YAAb,MAAqD;CAKnD,AAAO,YAAY,QAAyB;EAK1C,MAAM,EAAE,UAAU,SAAS,GAAG,kBAAkB;EAEhD,KAAK,SAAS,IAAI,OAAO,aAAa;EACtC,KAAK,WAAW,YAAY;EAC5B,KAAK,UAAU;CACjB;;;;;;;;;;;;;;;;;;;;;CAsBA,AAAO,MAAM,QAA0C;EACrD,MAAM,MAAe,OAAO;EAE5B,IAAI,QAAQ,UAAa,QAAQ,UAAU,QAAQ,aACjD,MAAM,IAAI,oBACR,uBAAuB,OAAO,GAAG,EAAE,qCACnC,EAAE,SAAS;GAAE,UAAU,KAAK;GAAU,OAAO,OAAO;GAAM;EAAI,EAAE,CAClE;EAGF,IAAI,QAAQ,eAAe,KAAK,aAAa,UAC3C,MAAM,IAAI,oBACR,4FAA4F,KAAK,SAAS,kCAC1G,EAAE,SAAS;GAAE,UAAU,KAAK;GAAU,OAAO,OAAO;GAAM;EAAI,EAAE,CAClE;EAGF,MAAM,kBACJ,OAAO,WACP,KAAK,UAAU,OAAO,UACrB,KAAK,aAAa,WAAW,iBAAiB,OAAO,IAAI,IAAI;EAChE,MAAM,iBACJ,oBAAoB,OAAO,UAAU,SAAS;GAAE,GAAG;GAAQ,SAAS;EAAgB;EAEtF,IAAI,QAAQ,aACV,OAAO,IAAI,qBAAqB,KAAK,QAAQ,gBAAgB,KAAK,QAAQ;EAG5E,OAAO,IAAI,YAAY,KAAK,QAAQ,gBAAgB,KAAK,QAAQ;CACnE;;;;;;;;CASA,MAAa,MAAM,MAAc,QAAkC;EACjE,OAAO,sBAAsB,IAAI;CACnC;;;;;;;;;;;CAYA,AAAO,SAAS,QAAgD;EAC9D,OAAO,IAAI,eAAe,KAAK,QAAQ,MAAM;CAC/C;;;;;;;;;;;;;;;;;;CAmBA,AAAO,MAAM,QAA+C;EAC1D,MAAM,kBAAkB,OAAO,WAAW,KAAK,UAAU,OAAO;EAChE,MAAM,iBACJ,oBAAoB,OAAO,UAAU,SAAS;GAAE,GAAG;GAAQ,SAAS;EAAgB;EAEtF,OAAO,IAAI,iBAAiB,KAAK,QAAQ,gBAAgB,KAAK,QAAQ;CACxE;;;;;;;;;;;;CAaA,AAAO,OAAO,QAAiD;EAC7D,OAAO,IAAI,kBAAkB,KAAK,QAAQ,QAAQ,KAAK,QAAQ;CACjE;;;;;;;;;;;;CAaA,AAAO,WAAW,QAA+D;EAC/E,OAAO,IAAI,yBAAyB,KAAK,QAAQ,QAAQ,KAAK,QAAQ;CACxE;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"transcription.mjs","names":[],"sources":["../../../../../../../packages/ai-openai/src/transcription.ts"],"sourcesContent":["import {\n type AudioInput,\n type TranscribeOptions,\n type TranscriptionModelContract,\n type TranscriptionModelPricing,\n type TranscriptionResponse,\n type TranscriptionSegment,\n} from \"@warlock.js/ai\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport OpenAI, { toFile } from \"openai\";\nimport type { OpenAITranscriptionConfig } from \"./config.type\";\nimport { wrapOpenAIError } from \"./utils\";\n\nconst LOG_MODULE = \"ai.openai\";\n\n/** Defensive view over the response, whose shape varies by `response_format`. */\ntype RawTranscription = {\n text: string;\n duration?: number;\n language?: string;\n segments?: Array<{ text: string; start?: number; end?: number }>;\n usage?: {\n type?: string;\n seconds?: number;\n input_tokens?: number;\n output_tokens?: number;\n total_tokens?: number;\n };\n};\n\n/**\n * OpenAI-backed implementation of `TranscriptionModelContract`\n * (speech-to-text) via `audio.transcriptions.create`. Consumed by the\n * `ai.transcribe()` verb.\n *\n * **No model-id validation.** `config.name` is forwarded to\n * `audio.transcriptions.create` exactly as given — the constructor\n * never inspects it. An unrecognized id fails at OpenAI (wrapped into\n * the typed `AIError` hierarchy by `transcribe()`), not here.\n *\n * **Response format.** Defaults to `verbose_json` for `whisper-1` (so\n * the run gets a `duration` + timestamped `segments`) and `json` for\n * the token-metered `gpt-4o-transcribe` family. Base64 audio is wrapped\n * in an uploadable via the SDK's `toFile`.\n *\n * @example\n * const stt = new OpenAITranscriptionModel(client, { name: \"whisper-1\" }, \"openai\");\n * const { text } = await stt.transcribe({ base64, mediaType: \"audio/mpeg\" });\n */\nexport class OpenAITranscriptionModel implements TranscriptionModelContract {\n public readonly name: string;\n public readonly provider: string;\n public readonly pricing?: TranscriptionModelPricing;\n\n private readonly client: OpenAI;\n private readonly logger: Logger = log;\n\n public constructor(\n client: OpenAI,\n config: OpenAITranscriptionConfig,\n provider: string = \"openai\",\n ) {\n this.client = client;\n this.name = config.name;\n this.provider = provider;\n this.pricing = config.pricing;\n }\n\n public async transcribe(\n audio: AudioInput,\n options?: TranscribeOptions,\n ): Promise<TranscriptionResponse> {\n const isWhisper = this.name.startsWith(\"whisper\");\n const format = options?.format ?? (isWhisper ? \"verbose_json\" : \"json\");\n\n const file = await toFile(Buffer.from(audio.base64, \"base64\"), audio.filename ?? \"audio\", {\n type: audio.mediaType,\n });\n\n this.logger.debug(LOG_MODULE, \"transcription.request\", \"audio.transcriptions.create\", {\n model: this.name,\n format,\n });\n\n let raw: unknown;\n\n try {\n raw = await this.client.audio.transcriptions.create(\n {\n model: this.name,\n file,\n response_format: format as OpenAI.Audio.TranscriptionCreateParams[\"response_format\"],\n ...(options?.language ? { language: options.language } : {}),\n ...(options?.prompt ? { prompt: options.prompt } : {}),\n } as OpenAI.Audio.TranscriptionCreateParamsNonStreaming,\n options?.signal ? { signal: options.signal } : undefined,\n );\n } catch (thrown) {\n const wrapped = wrapOpenAIError(thrown);\n this.logger.error(LOG_MODULE, \"transcription.error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n throw wrapped;\n }\n\n const response = raw as RawTranscription;\n\n const segments: TranscriptionSegment[] | undefined = response.segments?.map((segment) => ({\n text: segment.text,\n ...(segment.start !== undefined ? { start: segment.start } : {}),\n ...(segment.end !== undefined ? { end: segment.end } : {}),\n }));\n\n const durationSeconds =\n response.duration ?? (response.usage?.type === \"duration\" ? response.usage.seconds : undefined);\n\n const usage =\n response.usage?.type === \"tokens\"\n ? {\n input: response.usage.input_tokens ?? 0,\n output: response.usage.output_tokens ?? 0,\n total: response.usage.total_tokens ?? 0,\n }\n : { input: 0, output: 0, total: 0 };\n\n return {\n text: response.text,\n ...(segments && segments.length > 0 ? { segments } : {}),\n ...(durationSeconds !== undefined ? { durationSeconds } : {}),\n usage,\n };\n }\n}\n"],"mappings":";;;;;;AAaA,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;AAoCnB,IAAa,2BAAb,MAA4E;CAQ1E,AAAO,YACL,QACA,QACA,WAAmB,UACnB;gBANgC;EAOhC,KAAK,SAAS;EACd,KAAK,OAAO,OAAO;EACnB,KAAK,WAAW;EAChB,KAAK,UAAU,OAAO;CACxB;CAEA,MAAa,WACX,OACA,SACgC;EAChC,MAAM,YAAY,KAAK,KAAK,WAAW,SAAS;EAChD,MAAM,SAAS,SAAS,WAAW,YAAY,iBAAiB;EAEhE,MAAM,OAAO,MAAM,OAAO,OAAO,KAAK,MAAM,QAAQ,QAAQ,GAAG,MAAM,YAAY,SAAS,EACxF,MAAM,MAAM,UACd,CAAC;EAED,KAAK,OAAO,MAAM,YAAY,yBAAyB,+BAA+B;GACpF,OAAO,KAAK;GACZ;EACF,CAAC;EAED,IAAI;EAEJ,IAAI;GACF,MAAM,MAAM,KAAK,OAAO,MAAM,eAAe,OAC3C;IACE,OAAO,KAAK;IACZ;IACA,iBAAiB;IACjB,GAAI,SAAS,WAAW,EAAE,UAAU,QAAQ,SAAS,IAAI,CAAC;IAC1D,GAAI,SAAS,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;GACtD,GACA,SAAS,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,MACjD;EACF,SAAS,QAAQ;GACf,MAAM,UAAU,gBAAgB,MAAM;GACtC,KAAK,OAAO,MAAM,YAAY,uBAAuB,QAAQ,SAAS;IACpE,MAAM,QAAQ;IACd,SAAS,QAAQ;GACnB,CAAC;GACD,MAAM;EACR;EAEA,MAAM,WAAW;EAEjB,MAAM,WAA+C,SAAS,UAAU,KAAK,aAAa;GACxF,MAAM,QAAQ;GACd,GAAI,QAAQ,UAAU,SAAY,EAAE,OAAO,QAAQ,MAAM,IAAI,CAAC;GAC9D,GAAI,QAAQ,QAAQ,SAAY,EAAE,KAAK,QAAQ,IAAI,IAAI,CAAC;EAC1D,EAAE;EAEF,MAAM,kBACJ,SAAS,aAAa,SAAS,OAAO,SAAS,aAAa,SAAS,MAAM,UAAU;EAEvF,MAAM,QACJ,SAAS,OAAO,SAAS,WACrB;GACE,OAAO,SAAS,MAAM,gBAAgB;GACtC,QAAQ,SAAS,MAAM,iBAAiB;GACxC,OAAO,SAAS,MAAM,gBAAgB;EACxC,IACA;GAAE,OAAO;GAAG,QAAQ;GAAG,OAAO;EAAE;EAEtC,OAAO;GACL,MAAM,SAAS;GACf,GAAI,YAAY,SAAS,SAAS,IAAI,EAAE,SAAS,IAAI,CAAC;GACtD,GAAI,oBAAoB,SAAY,EAAE,gBAAgB,IAAI,CAAC;GAC3D;EACF;CACF;AACF"}
1
+ {"version":3,"file":"transcription.mjs","names":[],"sources":["../../../../../../../packages/ai-openai/src/transcription.ts"],"sourcesContent":["import {\n type AudioInput,\n type TranscribeOptions,\n type TranscriptionModelContract,\n type TranscriptionModelPricing,\n type TranscriptionResponse,\n type TranscriptionSegment,\n} from \"@warlock.js/ai\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport OpenAI, { toFile } from \"openai\";\nimport type { OpenAITranscriptionConfig } from \"./config.type\";\nimport { wrapOpenAIError } from \"./utils\";\n\nconst LOG_MODULE = \"ai.openai\";\n\n/** Defensive view over the response, whose shape varies by `response_format`. */\ntype RawTranscription = {\n text: string;\n duration?: number;\n language?: string;\n segments?: Array<{ text: string; start?: number; end?: number }>;\n usage?: {\n type?: string;\n seconds?: number;\n input_tokens?: number;\n output_tokens?: number;\n total_tokens?: number;\n };\n};\n\n/**\n * OpenAI-backed implementation of `TranscriptionModelContract`\n * (speech-to-text) via `audio.transcriptions.create`. Consumed by the\n * `ai.transcribe()` verb.\n *\n * **No model-id validation.** `config.name` is forwarded to\n * `audio.transcriptions.create` exactly as given — the constructor\n * never inspects it. An unrecognized id fails at OpenAI (wrapped into\n * the typed `AIError` hierarchy by `transcribe()`), not here.\n *\n * **Response format.** Defaults to `verbose_json` for `whisper-1` (so\n * the run gets a `duration` + timestamped `segments`) and `json` for\n * the token-metered `gpt-4o-transcribe` family. Base64 audio is wrapped\n * in an uploadable via the SDK's `toFile`.\n *\n * @example\n * const stt = new OpenAITranscriptionModel(client, { name: \"whisper-1\" }, \"openai\");\n * const { text } = await stt.transcribe({ base64, mediaType: \"audio/mpeg\" });\n */\nexport class OpenAITranscriptionModel implements TranscriptionModelContract {\n public readonly name: string;\n public readonly provider: string;\n public readonly pricing?: TranscriptionModelPricing;\n\n private readonly client: OpenAI;\n private readonly logger: Logger = log;\n\n public constructor(\n client: OpenAI,\n config: OpenAITranscriptionConfig,\n provider: string = \"openai\",\n ) {\n this.client = client;\n this.name = config.name;\n this.provider = provider;\n this.pricing = config.pricing;\n }\n\n public async transcribe(\n audio: AudioInput,\n options?: TranscribeOptions,\n ): Promise<TranscriptionResponse> {\n const isWhisper = this.name.startsWith(\"whisper\");\n const format = options?.format ?? (isWhisper ? \"verbose_json\" : \"json\");\n\n const file = await toFile(Buffer.from(audio.base64, \"base64\"), audio.filename ?? \"audio\", {\n type: audio.mediaType,\n });\n\n this.logger.debug(LOG_MODULE, \"transcription.request\", \"audio.transcriptions.create\", {\n model: this.name,\n format,\n });\n\n let raw: unknown;\n\n try {\n raw = await this.client.audio.transcriptions.create(\n {\n model: this.name,\n file,\n response_format: format as OpenAI.Audio.TranscriptionCreateParams[\"response_format\"],\n ...(options?.language ? { language: options.language } : {}),\n ...(options?.prompt ? { prompt: options.prompt } : {}),\n } as OpenAI.Audio.TranscriptionCreateParamsNonStreaming,\n options?.signal ? { signal: options.signal } : undefined,\n );\n } catch (thrown) {\n const wrapped = wrapOpenAIError(thrown);\n this.logger.error(LOG_MODULE, \"transcription.error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n throw wrapped;\n }\n\n const response = raw as RawTranscription;\n\n const segments: TranscriptionSegment[] | undefined = response.segments?.map((segment) => ({\n text: segment.text,\n ...(segment.start !== undefined ? { start: segment.start } : {}),\n ...(segment.end !== undefined ? { end: segment.end } : {}),\n }));\n\n const durationSeconds =\n response.duration ??\n (response.usage?.type === \"duration\" ? response.usage.seconds : undefined);\n\n const usage =\n response.usage?.type === \"tokens\"\n ? {\n input: response.usage.input_tokens ?? 0,\n output: response.usage.output_tokens ?? 0,\n total: response.usage.total_tokens ?? 0,\n }\n : { input: 0, output: 0, total: 0 };\n\n return {\n text: response.text,\n ...(segments && segments.length > 0 ? { segments } : {}),\n ...(durationSeconds !== undefined ? { durationSeconds } : {}),\n usage,\n };\n }\n}\n"],"mappings":";;;;;;AAaA,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;AAoCnB,IAAa,2BAAb,MAA4E;CAQ1E,AAAO,YACL,QACA,QACA,WAAmB,UACnB;gBANgC;EAOhC,KAAK,SAAS;EACd,KAAK,OAAO,OAAO;EACnB,KAAK,WAAW;EAChB,KAAK,UAAU,OAAO;CACxB;CAEA,MAAa,WACX,OACA,SACgC;EAChC,MAAM,YAAY,KAAK,KAAK,WAAW,SAAS;EAChD,MAAM,SAAS,SAAS,WAAW,YAAY,iBAAiB;EAEhE,MAAM,OAAO,MAAM,OA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BAAoB,SAAY,EAAE,gBAAgB,IAAI,CAAC;GAC3D;EACF;CACF;AACF"}
@@ -1,3 +1,5 @@
1
+ import { computeCost } from "@warlock.js/ai";
2
+
1
3
  //#region ../../packages/ai-openai/src/utils/build-usage.ts
2
4
  /**
3
5
  * Build the neutral `Usage` from extracted counts. The optional detail
@@ -5,17 +7,27 @@
5
7
  * non-reasoning / uncached calls keep the lean `{ input, output, total }`
6
8
  * shape. Shared by the Chat Completions and Responses adapters so both
7
9
  * apply the same rule.
10
+ *
11
+ * OpenAI-style usage counts cache reads and writes inside the prompt
12
+ * total (`input_tokens` includes `cached_tokens` and `cache_write_tokens`,
13
+ * and the compatible vendors — DeepSeek, xAI, Groq, Mistral — document
14
+ * the same), so the result is marked `inputIncludesCache: true`. When the
15
+ * model is priced, `cost` is attached.
8
16
  */
9
- function buildUsage(counts) {
17
+ function buildUsage(counts, pricing) {
10
18
  const { input, output, total, cachedTokens, reasoningTokens, cacheWriteTokens } = counts;
11
- return {
19
+ const usage = {
12
20
  input,
13
21
  output,
14
22
  total,
23
+ inputIncludesCache: true,
15
24
  ...cachedTokens !== void 0 && cachedTokens > 0 ? { cachedTokens } : {},
16
25
  ...reasoningTokens !== void 0 && reasoningTokens > 0 ? { reasoningTokens } : {},
17
26
  ...cacheWriteTokens !== void 0 && cacheWriteTokens > 0 ? { cacheWriteTokens } : {}
18
27
  };
28
+ const cost = computeCost(usage, pricing);
29
+ if (cost) usage.cost = cost;
30
+ return usage;
19
31
  }
20
32
 
21
33
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"build-usage.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/build-usage.ts"],"sourcesContent":["import type { Usage } from \"@warlock.js/ai\";\n\n/** The already-extracted token counts of one provider usage block. */\nexport type UsageCounts = {\n input: number;\n output: number;\n total: number;\n /** Subset of `input` served from the prompt cache. */\n cachedTokens?: number;\n /** Hidden reasoning channel, already counted within `output`. */\n reasoningTokens?: number;\n /** Subset of `input` written to the prompt cache. */\n cacheWriteTokens?: number;\n};\n\n/**\n * Build the neutral `Usage` from extracted counts. The optional detail\n * counters are emitted only when the provider reports a positive value, so\n * non-reasoning / uncached calls keep the lean `{ input, output, total }`\n * shape. Shared by the Chat Completions and Responses adapters so both\n * apply the same rule.\n */\nexport function buildUsage(counts: UsageCounts): Usage {\n const { input, output, total, cachedTokens, reasoningTokens, cacheWriteTokens } = counts;\n\n return {\n input,\n output,\n total,\n ...(cachedTokens !== undefined && cachedTokens > 0 ? { cachedTokens } : {}),\n ...(reasoningTokens !== undefined && reasoningTokens > 0 ? { reasoningTokens } : {}),\n ...(cacheWriteTokens !== undefined && cacheWriteTokens > 0 ? { cacheWriteTokens } : {}),\n };\n}\n"],"mappings":";;;;;;;;AAsBA,SAAgB,WAAW,QAA4B;CACrD,MAAM,EAAE,OAAO,QAAQ,OAAO,cAAc,iBAAiB,qBAAqB;CAElF,OAAO;EACL;EACA;EACA;EACA,GAAI,iBAAiB,UAAa,eAAe,IAAI,EAAE,aAAa,IAAI,CAAC;EACzE,GAAI,oBAAoB,UAAa,kBAAkB,IAAI,EAAE,gBAAgB,IAAI,CAAC;EAClF,GAAI,qBAAqB,UAAa,mBAAmB,IAAI,EAAE,iBAAiB,IAAI,CAAC;CACvF;AACF"}
1
+ {"version":3,"file":"build-usage.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/build-usage.ts"],"sourcesContent":["import { computeCost, type ModelPricing, type Usage } from \"@warlock.js/ai\";\n\n/** The already-extracted token counts of one provider usage block. */\nexport type UsageCounts = {\n input: number;\n output: number;\n total: number;\n /** Subset of `input` served from the prompt cache. */\n cachedTokens?: number;\n /** Hidden reasoning channel, already counted within `output`. */\n reasoningTokens?: number;\n /** Subset of `input` written to the prompt cache. */\n cacheWriteTokens?: number;\n};\n\n/**\n * Build the neutral `Usage` from extracted counts. The optional detail\n * counters are emitted only when the provider reports a positive value, so\n * non-reasoning / uncached calls keep the lean `{ input, output, total }`\n * shape. Shared by the Chat Completions and Responses adapters so both\n * apply the same rule.\n *\n * OpenAI-style usage counts cache reads and writes inside the prompt\n * total (`input_tokens` includes `cached_tokens` and `cache_write_tokens`,\n * and the compatible vendors — DeepSeek, xAI, Groq, Mistral — document\n * the same), so the result is marked `inputIncludesCache: true`. When the\n * model is priced, `cost` is attached.\n */\nexport function buildUsage(counts: UsageCounts, pricing?: ModelPricing): Usage {\n const { input, output, total, cachedTokens, reasoningTokens, cacheWriteTokens } = counts;\n\n const usage: Usage = {\n input,\n output,\n total,\n inputIncludesCache: true,\n ...(cachedTokens !== undefined && cachedTokens > 0 ? { cachedTokens } : {}),\n ...(reasoningTokens !== undefined && reasoningTokens > 0 ? { reasoningTokens } : {}),\n ...(cacheWriteTokens !== undefined && cacheWriteTokens > 0 ? { cacheWriteTokens } : {}),\n };\n\n const cost = computeCost(usage, pricing);\n\n if (cost) {\n usage.cost = cost;\n }\n\n return usage;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA4BA,SAAgB,WAAW,QAAqB,SAA+B;CAC7E,MAAM,EAAE,OAAO,QAAQ,OAAO,cAAc,iBAAiB,qBAAqB;CAElF,MAAM,QAAe;EACnB;EACA;EACA;EACA,oBAAoB;EACpB,GAAI,iBAAiB,UAAa,eAAe,IAAI,EAAE,aAAa,IAAI,CAAC;EACzE,GAAI,oBAAoB,UAAa,kBAAkB,IAAI,EAAE,gBAAgB,IAAI,CAAC;EAClF,GAAI,qBAAqB,UAAa,mBAAmB,IAAI,EAAE,iBAAiB,IAAI,CAAC;CACvF;CAEA,MAAM,OAAO,YAAY,OAAO,OAAO;CAEvC,IAAI,MACF,MAAM,OAAO;CAGf,OAAO;AACT"}
@@ -5,7 +5,7 @@ import { mapFinishReason } from "./map-finish-reason.mjs";
5
5
  import { buildPromptCacheParams } from "./prompt-cache-params.mjs";
6
6
  import { toOpenAIReasoningEffort } from "./reasoning-effort.mjs";
7
7
  import { inferStructuredOutput, planStructuredOutput } from "./structured-output.mjs";
8
- import { RESPONSES_METADATA_KEY, attachReasoningReplay, pickReplayableReasoning, readReasoningReplay, toReplayReasoningItem } from "./reasoning-replay.mjs";
8
+ import { RESPONSES_METADATA_KEY, attachReasoningReplay, pickReplayableReasoning, pickTurnReasoning, readReasoningReplay, toReplayReasoningItem } from "./reasoning-replay.mjs";
9
9
  import { toOpenAIMessages } from "./to-openai-messages.mjs";
10
10
  import { toOpenAITools } from "./to-openai-tools.mjs";
11
11
  import { toResponsesInput } from "./to-responses-input.mjs";
@@ -1 +1 @@
1
- {"version":3,"file":"map-responses-status.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/map-responses-status.ts"],"sourcesContent":["import type { AIError, FinishReason } from \"@warlock.js/ai\";\nimport type OpenAI from \"openai\";\nimport { wrapOpenAIError } from \"./wrap-openai-error\";\n\n/** The slice of a Responses `Response` the status mapper reads. */\nexport type ResponsesTerminalState = Pick<\n OpenAI.Responses.Response,\n \"status\" | \"incomplete_details\"\n> & {\n /** True when `output` holds at least one `function_call` item the model completed. */\n hasToolCalls: boolean;\n};\n\n/**\n * Derive our `FinishReason` from a Responses terminal state. Responses has\n * no `finish_reason`, so it comes from `status`, `incomplete_details` and the\n * output items (design section 2, decision 5):\n *\n * - `completed` with a function call -> `tool_calls`; without -> `stop`\n * (a refusal is ordinary text and also `stop`).\n * - `incomplete` / `max_output_tokens` and `max_messages` -> `length`.\n * - `incomplete` / `content_filter` and `steered` (or an unknown / missing\n * reason) -> `error`. There is no neutral `content_filter` value.\n * - `cancelled`, `queued`, `in_progress` at a terminal read -> `error`.\n * - `failed` is not mapped here: callers throw it via {@link toResponseFailure}.\n *\n * A missing `status` is treated as `completed` (the SDK types it optional).\n */\nexport function mapResponsesFinishReason(state: ResponsesTerminalState): FinishReason {\n const status = state.status ?? \"completed\";\n\n if (status === \"completed\") {\n return state.hasToolCalls ? \"tool_calls\" : \"stop\";\n }\n\n if (status === \"incomplete\") {\n const reason = state.incomplete_details?.reason;\n\n return reason === \"max_output_tokens\" || reason === \"max_messages\" ? \"length\" : \"error\";\n }\n\n return \"error\";\n}\n\n/**\n * Turn a `failed` Responses payload into the same typed `AIError` the Chat\n * path throws for a provider failure, by running it through\n * `wrapOpenAIError` (so `rate_limit_exceeded` becomes a\n * `ProviderRateLimitError`, everything else a `ProviderError`, with `code`\n * and request id kept on `context`). The response id and model are added so\n * the failure is traceable.\n */\nexport function toResponseFailure(\n response: OpenAI.Responses.Response,\n model: string,\n): AIError {\n const error = response.error;\n const requestId = (response as { _request_id?: string | null })._request_id;\n\n const wrapped = wrapOpenAIError({\n code: error?.code,\n message: error?.message ?? \"OpenAI response failed without an error object.\",\n ...(requestId ? { request_id: requestId } : {}),\n });\n\n if (wrapped.context) {\n Object.assign(wrapped.context, { provider: \"openai\", model, responseId: response.id });\n }\n\n return wrapped;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA4BA,SAAgB,yBAAyB,OAA6C;CACpF,MAAM,SAAS,MAAM,UAAU;CAE/B,IAAI,WAAW,aACb,OAAO,MAAM,eAAe,eAAe;CAG7C,IAAI,WAAW,cAAc;EAC3B,MAAM,SAAS,MAAM,oBAAoB;EAEzC,OAAO,WAAW,uBAAuB,WAAW,iBAAiB,WAAW;CAClF;CAEA,OAAO;AACT;;;;;;;;;AAUA,SAAgB,kBACd,UACA,OACS;CACT,MAAM,QAAQ,SAAS;CACvB,MAAM,YAAa,SAA6C;CAEhE,MAAM,UAAU,gBAAgB;EAC9B,MAAM,OAAO;EACb,SAAS,OAAO,WAAW;EAC3B,GAAI,YAAY,EAAE,YAAY,UAAU,IAAI,CAAC;CAC/C,CAAC;CAED,IAAI,QAAQ,SACV,OAAO,OAAO,QAAQ,SAAS;EAAE,UAAU;EAAU;EAAO,YAAY,SAAS;CAAG,CAAC;CAGvF,OAAO;AACT"}
1
+ {"version":3,"file":"map-responses-status.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/map-responses-status.ts"],"sourcesContent":["import type { AIError, FinishReason } from \"@warlock.js/ai\";\nimport type OpenAI from \"openai\";\nimport { wrapOpenAIError } from \"./wrap-openai-error\";\n\n/** The slice of a Responses `Response` the status mapper reads. */\nexport type ResponsesTerminalState = Pick<\n OpenAI.Responses.Response,\n \"status\" | \"incomplete_details\"\n> & {\n /** True when `output` holds at least one `function_call` item the model completed. */\n hasToolCalls: boolean;\n};\n\n/**\n * Derive our `FinishReason` from a Responses terminal state. Responses has\n * no `finish_reason`, so it comes from `status`, `incomplete_details` and the\n * output items (design section 2, decision 5):\n *\n * - `completed` with a function call -> `tool_calls`; without -> `stop`\n * (a refusal is ordinary text and also `stop`).\n * - `incomplete` / `max_output_tokens` and `max_messages` -> `length`.\n * - `incomplete` / `content_filter` and `steered` (or an unknown / missing\n * reason) -> `error`. There is no neutral `content_filter` value.\n * - `cancelled`, `queued`, `in_progress` at a terminal read -> `error`.\n * - `failed` is not mapped here: callers throw it via {@link toResponseFailure}.\n *\n * A missing `status` is treated as `completed` (the SDK types it optional).\n */\nexport function mapResponsesFinishReason(state: ResponsesTerminalState): FinishReason {\n const status = state.status ?? \"completed\";\n\n if (status === \"completed\") {\n return state.hasToolCalls ? \"tool_calls\" : \"stop\";\n }\n\n if (status === \"incomplete\") {\n const reason = state.incomplete_details?.reason;\n\n return reason === \"max_output_tokens\" || reason === \"max_messages\" ? \"length\" : \"error\";\n }\n\n return \"error\";\n}\n\n/**\n * Turn a `failed` Responses payload into the same typed `AIError` the Chat\n * path throws for a provider failure, by running it through\n * `wrapOpenAIError` (so `rate_limit_exceeded` becomes a\n * `ProviderRateLimitError`, everything else a `ProviderError`, with `code`\n * and request id kept on `context`). The response id and model are added so\n * the failure is traceable.\n */\nexport function toResponseFailure(response: OpenAI.Responses.Response, model: string): AIError {\n const error = response.error;\n const requestId = (response as { _request_id?: string | null })._request_id;\n\n const wrapped = wrapOpenAIError({\n code: error?.code,\n message: error?.message ?? \"OpenAI response failed without an error object.\",\n ...(requestId ? { request_id: requestId } : {}),\n });\n\n if (wrapped.context) {\n Object.assign(wrapped.context, { provider: \"openai\", model, responseId: response.id });\n }\n\n return wrapped;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA4BA,SAAgB,yBAAyB,OAA6C;CACpF,MAAM,SAAS,MAAM,UAAU;CAE/B,IAAI,WAAW,aACb,OAAO,MAAM,eAAe,eAAe;CAG7C,IAAI,WAAW,cAAc;EAC3B,MAAM,SAAS,MAAM,oBAAoB;EAEzC,OAAO,WAAW,uBAAuB,WAAW,iBAAiB,WAAW;CAClF;CAEA,OAAO;AACT;;;;;;;;;AAUA,SAAgB,kBAAkB,UAAqC,OAAwB;CAC7F,MAAM,QAAQ,SAAS;CACvB,MAAM,YAAa,SAA6C;CAEhE,MAAM,UAAU,gBAAgB;EAC9B,MAAM,OAAO;EACb,SAAS,OAAO,WAAW;EAC3B,GAAI,YAAY,EAAE,YAAY,UAAU,IAAI,CAAC;CAC/C,CAAC;CAED,IAAI,QAAQ,SACV,OAAO,OAAO,QAAQ,SAAS;EAAE,UAAU;EAAU;EAAO,YAAY,SAAS;CAAG,CAAC;CAGvF,OAAO;AACT"}