@warlock.js/ai-openai 5.39.1 → 5.40.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.
package/esm/index.d.mts CHANGED
@@ -1,10 +1,11 @@
1
1
  import { OpenAIEmbedderConfig, OpenAIImageConfig, OpenAISDKConfig, OpenAISpeechConfig, OpenAITranscriptionConfig } from "./config.type.mjs";
2
2
  import { OpenAISDK } from "./sdk.mjs";
3
3
  import { OPENAI_MODEL_PRICING, OPENAI_SERVER_TOOL_PRICING, openAIPricingFor } from "./known-pricing.mjs";
4
+ import { OpenAIResponsesModel } from "./responses-model.mjs";
4
5
  import { OpenAIEmbedder } from "./embedder.mjs";
5
6
  import { OpenAIImageModel } from "./image.mjs";
6
7
  import { OpenAISpeechModel } from "./speech.mjs";
7
8
  import { OpenAITranscriptionModel } from "./transcription.mjs";
8
9
  import { OpenAICallOptions, QwenCallOptions } from "./provider-options.mjs";
9
10
  import { KIMI_SERVER_TOOL_PRICING, KimiFetchOutput, KimiSearchOutput, KimiSearchResult, KimiSearchToolOptions, KimiToolOptions, kimiFetchTool, kimiSearchTool } from "./kimi-tools.mjs";
10
- export { KIMI_SERVER_TOOL_PRICING, type KimiFetchOutput, type KimiSearchOutput, type KimiSearchResult, type KimiSearchToolOptions, type KimiToolOptions, OPENAI_MODEL_PRICING, OPENAI_SERVER_TOOL_PRICING, type OpenAICallOptions, OpenAIEmbedder, type OpenAIEmbedderConfig, type OpenAIImageConfig, OpenAIImageModel, OpenAISDK, type OpenAISDKConfig, type OpenAISpeechConfig, OpenAISpeechModel, type OpenAITranscriptionConfig, OpenAITranscriptionModel, type QwenCallOptions, kimiFetchTool, kimiSearchTool, openAIPricingFor };
11
+ export { KIMI_SERVER_TOOL_PRICING, type KimiFetchOutput, type KimiSearchOutput, type KimiSearchResult, type KimiSearchToolOptions, type KimiToolOptions, OPENAI_MODEL_PRICING, OPENAI_SERVER_TOOL_PRICING, type OpenAICallOptions, OpenAIEmbedder, type OpenAIEmbedderConfig, type OpenAIImageConfig, OpenAIImageModel, OpenAIResponsesModel, OpenAISDK, type OpenAISDKConfig, type OpenAISpeechConfig, OpenAISpeechModel, type OpenAITranscriptionConfig, OpenAITranscriptionModel, type QwenCallOptions, kimiFetchTool, kimiSearchTool, openAIPricingFor };
package/esm/index.mjs CHANGED
@@ -1,9 +1,10 @@
1
1
  import { OPENAI_MODEL_PRICING, OPENAI_SERVER_TOOL_PRICING, openAIPricingFor } from "./known-pricing.mjs";
2
2
  import { OpenAIEmbedder } from "./embedder.mjs";
3
3
  import { OpenAIImageModel } from "./image.mjs";
4
+ import { OpenAIResponsesModel } from "./responses-model.mjs";
4
5
  import { OpenAISpeechModel } from "./speech.mjs";
5
6
  import { OpenAITranscriptionModel } from "./transcription.mjs";
6
7
  import { OpenAISDK } from "./sdk.mjs";
7
8
  import { KIMI_SERVER_TOOL_PRICING, kimiFetchTool, kimiSearchTool } from "./kimi-tools.mjs";
8
9
 
9
- export { KIMI_SERVER_TOOL_PRICING, OPENAI_MODEL_PRICING, OPENAI_SERVER_TOOL_PRICING, OpenAIEmbedder, OpenAIImageModel, OpenAISDK, OpenAISpeechModel, OpenAITranscriptionModel, kimiFetchTool, kimiSearchTool, openAIPricingFor };
10
+ export { KIMI_SERVER_TOOL_PRICING, OPENAI_MODEL_PRICING, OPENAI_SERVER_TOOL_PRICING, OpenAIEmbedder, OpenAIImageModel, OpenAIResponsesModel, OpenAISDK, OpenAISpeechModel, OpenAITranscriptionModel, kimiFetchTool, kimiSearchTool, openAIPricingFor };
@@ -0,0 +1,54 @@
1
+ import { inferModelKind } from "@warlock.js/ai";
2
+
3
+ //#region ../../packages/ai-openai/src/list-models.ts
4
+ /**
5
+ * Map one entry of an OpenAI-style `GET /models` listing to {@link ModelInfo}.
6
+ *
7
+ * OpenAI's own entries carry `id`, `created` and `owned_by` only. The
8
+ * compatible vendors add fields on top of that shape, and this reads the ones
9
+ * that are documented: Groq `context_window` and `active`, Mistral `name`,
10
+ * `description`, `max_context_length` and `capabilities`, and a `created_at`
11
+ * date string. Returns `undefined` for an entry that should not be offered
12
+ * (an id-less row, or one the vendor marks inactive).
13
+ */
14
+ function toModelInfo(entry, provider) {
15
+ if (typeof entry !== "object" || entry === null) return;
16
+ const row = entry;
17
+ const id = row.id;
18
+ if (typeof id !== "string" || id === "" || row.active === false) return;
19
+ const created = numberOf(row.created) ?? secondsOf(row.created_at);
20
+ const contextWindow = numberOf(row.context_window) ?? numberOf(row.max_context_length);
21
+ const maxOutputTokens = numberOf(row.max_completion_tokens);
22
+ return {
23
+ id,
24
+ label: typeof row.name === "string" && row.name !== "" ? row.name : id,
25
+ provider,
26
+ kind: kindOf(id, row.capabilities),
27
+ ...created !== void 0 ? { created } : {},
28
+ ...contextWindow !== void 0 ? { contextWindow } : {},
29
+ ...maxOutputTokens !== void 0 ? { maxOutputTokens } : {},
30
+ ...typeof row.description === "string" && row.description !== "" ? { description: row.description } : {}
31
+ };
32
+ }
33
+ /** Mistral reports `capabilities.completion_chat`; everything else is classified by id. */
34
+ function kindOf(id, capabilities) {
35
+ const inferred = inferModelKind(id);
36
+ if (typeof capabilities === "object" && capabilities !== null) {
37
+ const flags = capabilities;
38
+ if (flags.completion_chat === true) return "chat";
39
+ if (flags.completion_chat === false && inferred === "chat") return "other";
40
+ }
41
+ return inferred;
42
+ }
43
+ function numberOf(value) {
44
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
45
+ }
46
+ function secondsOf(value) {
47
+ if (typeof value !== "string") return;
48
+ const milliseconds = Date.parse(value);
49
+ return Number.isNaN(milliseconds) ? void 0 : Math.floor(milliseconds / 1e3);
50
+ }
51
+
52
+ //#endregion
53
+ export { toModelInfo };
54
+ //# sourceMappingURL=list-models.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"list-models.mjs","names":[],"sources":["../../../../../../../packages/ai-openai/src/list-models.ts"],"sourcesContent":["import { inferModelKind, type ModelInfo, type ModelKind } from \"@warlock.js/ai\";\n\n/**\n * Map one entry of an OpenAI-style `GET /models` listing to {@link ModelInfo}.\n *\n * OpenAI's own entries carry `id`, `created` and `owned_by` only. The\n * compatible vendors add fields on top of that shape, and this reads the ones\n * that are documented: Groq `context_window` and `active`, Mistral `name`,\n * `description`, `max_context_length` and `capabilities`, and a `created_at`\n * date string. Returns `undefined` for an entry that should not be offered\n * (an id-less row, or one the vendor marks inactive).\n */\nexport function toModelInfo(entry: unknown, provider: string): ModelInfo | undefined {\n if (typeof entry !== \"object\" || entry === null) {\n return undefined;\n }\n\n const row = entry as Record<string, unknown>;\n const id = row.id;\n\n if (typeof id !== \"string\" || id === \"\" || row.active === false) {\n return undefined;\n }\n\n const created = numberOf(row.created) ?? secondsOf(row.created_at);\n const contextWindow = numberOf(row.context_window) ?? numberOf(row.max_context_length);\n const maxOutputTokens = numberOf(row.max_completion_tokens);\n const label = typeof row.name === \"string\" && row.name !== \"\" ? row.name : id;\n\n return {\n id,\n label,\n provider,\n kind: kindOf(id, row.capabilities),\n ...(created !== undefined ? { created } : {}),\n ...(contextWindow !== undefined ? { contextWindow } : {}),\n ...(maxOutputTokens !== undefined ? { maxOutputTokens } : {}),\n ...(typeof row.description === \"string\" && row.description !== \"\"\n ? { description: row.description }\n : {}),\n };\n}\n\n/** Mistral reports `capabilities.completion_chat`; everything else is classified by id. */\nfunction kindOf(id: string, capabilities: unknown): ModelKind {\n const inferred = inferModelKind(id);\n\n if (typeof capabilities === \"object\" && capabilities !== null) {\n const flags = capabilities as Record<string, unknown>;\n\n if (flags.completion_chat === true) {\n return \"chat\";\n }\n\n if (flags.completion_chat === false && inferred === \"chat\") {\n return \"other\";\n }\n }\n\n return inferred;\n}\n\nfunction numberOf(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nfunction secondsOf(value: unknown): number | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n const milliseconds = Date.parse(value);\n\n return Number.isNaN(milliseconds) ? undefined : Math.floor(milli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AI,SAAY,KAAK,MAAM,eAAe,GAAI;AAChF"}
package/esm/model.mjs CHANGED
@@ -7,9 +7,11 @@ import { inferStructuredOutput, planStructuredOutput } from "./utils/structured-
7
7
  import { toOpenAIMessages } from "./utils/to-openai-messages.mjs";
8
8
  import { toOpenAITools } from "./utils/to-openai-tools.mjs";
9
9
  import "./utils/index.mjs";
10
+ import { assertHostedSearchSupported, requestsHostedSearch } from "./native-search.mjs";
10
11
  import { compatibleSearchParams, mergeProviderBody } from "./provider-options.mjs";
11
12
  import { inferReasoningCapability } from "./known-reasoning-models.mjs";
12
13
  import { inferVisionCapability } from "./known-vision-models.mjs";
14
+ import { OpenAIResponsesModel } from "./responses-model.mjs";
13
15
  import { InvalidRequestError, ProviderError, resolveStreamChunks, safeJsonParse, selectProviderTools } from "@warlock.js/ai";
14
16
  import { log } from "@warlock.js/logger";
15
17
 
@@ -81,6 +83,8 @@ var OpenAIModel = class {
81
83
  * instance's `ModelConfig` defaults for this call only.
82
84
  */
83
85
  async complete(messages, options) {
86
+ const searchRoute = this.hostedSearchRoute(options);
87
+ if (searchRoute) return searchRoute.complete(messages, options);
84
88
  this.logger.debug(LOG_MODULE, "request", "Starting call to chat.completions", {
85
89
  model: this.name,
86
90
  messageCount: messages.length,
@@ -138,6 +142,11 @@ var OpenAIModel = class {
138
142
  * only on the final chunk here, so no `usage` chunk is emitted.
139
143
  */
140
144
  async *stream(messages, options) {
145
+ const searchRoute = this.hostedSearchRoute(options);
146
+ if (searchRoute) {
147
+ yield* searchRoute.stream(messages, options);
148
+ return;
149
+ }
141
150
  this.logger.debug(LOG_MODULE, "request", "Starting streaming call to chat.completions", {
142
151
  model: this.name,
143
152
  messageCount: messages.length,
@@ -243,6 +252,27 @@ var OpenAIModel = class {
243
252
  };
244
253
  }
245
254
  /**
255
+ * OpenAI's hosted `web_search` tool exists only on the Responses API, and
256
+ * Chat Completions answers it with a 400. When a call on the direct
257
+ * `"openai"` provider carries it, the call is served by the Responses
258
+ * adapter instead (same client, same pricing, same model name), unless the
259
+ * model was pinned to `api: "chat"` or cannot search at all: both throw a
260
+ * clear error before any request, never a silent fallback to something
261
+ * else. Every other call stays on Chat Completions.
262
+ */
263
+ hostedSearchRoute(options) {
264
+ if (this.provider !== "openai" || !requestsHostedSearch(options, this.provider)) return;
265
+ if (this.config.api === "chat") throw new InvalidRequestError(`OpenAI's hosted web_search tool needs the Responses API, but "${this.name}" is pinned to api: "chat". Remove api: "chat" (the call is then routed to the Responses API) or use api: "responses".`, { context: {
266
+ provider: this.provider,
267
+ model: this.name,
268
+ api: "chat",
269
+ tool: "web_search"
270
+ } });
271
+ assertHostedSearchSupported(this.name, options);
272
+ this.searchModel ??= new OpenAIResponsesModel(this.client, this.config, this.provider);
273
+ return this.searchModel;
274
+ }
275
+ /**
246
276
  * Spread-friendly `tools` fragment: the function tools, then the
247
277
  * provider-defined entries whose `provider` equals this model's
248
278
  * provider label (`"openai"`, or the vendor label an OpenAI-compatible
@@ -262,7 +292,7 @@ var OpenAIModel = class {
262
292
  const fn = definition.function;
263
293
  return definition.type === "builtin_function" && typeof fn === "object" && fn !== null && "name" in fn && fn.name === "$web_search";
264
294
  })) throw new InvalidRequestError("Kimi's builtin $web_search retires on 20 October 2026. Use kimiSearchTool() / kimiFetchTool() from @warlock.js/ai-openai.");
265
- if (this.provider === "xai" && definitions.some((definition) => definition.type === "web_search" || definition.type === "x_search")) throw new InvalidRequestError("xAI native web_search / x_search requires POST /v1/responses. XaiSDK currently supports Chat Completions only; use xAI's Responses API with the vendor SDK for native search.");
295
+ if (this.provider === "xai" && definitions.some((definition) => definition.type === "web_search" || definition.type === "x_search")) throw new InvalidRequestError("xAI native web_search / x_search requires POST /v1/responses. Build the model with XaiSDK from @warlock.js/ai-xai, which routes those calls to the Responses API.");
266
296
  const mapped = [...toOpenAITools(tools) ?? [], ...definitions];
267
297
  return mapped.length > 0 ? { tools: mapped } : {};
268
298
  }
package/esm/model.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"model.mjs","names":[],"sources":["../../../../../../../packages/ai-openai/src/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 { compatibleSearchParams, mergeProviderBody } from \"./provider-options\";\nimport type { OpenAIModelConfig } from \"./config.type\";\nimport { inferReasoningCapability } from \"./known-reasoning-models\";\nimport { inferVisionCapability } from \"./known-vision-models\";\nimport {\n buildPromptCacheParams,\n buildUsage,\n inferStructuredOutput,\n mapFinishReason,\n planStructuredOutput,\n toOpenAIMessages,\n toOpenAIReasoningEffort,\n toOpenAITools,\n wrapOpenAIError,\n} from \"./utils\";\n\nconst LOG_MODULE = \"ai.openai\";\n\n/**\n * OpenAI-backed implementation of `ModelContract`.\n *\n * **Role.** The provider-facing bridge between the vendor-neutral\n * `@warlock.js/ai` agent runtime and the official `openai` SDK. Agents,\n * workflows, and supervisors never talk to OpenAI directly — they hold a\n * `ModelContract`, and this class is what makes that contract concrete for\n * any OpenAI-compatible endpoint (OpenAI, Azure OpenAI, OpenRouter, local\n * gateways that speak the Chat Completions protocol).\n *\n * **Responsibility.**\n * - Owns: a long-lived `OpenAI` client + frozen `ModelConfig` (name,\n * temperature, maxTokens) used as defaults for every call.\n * - Owns: translating vendor-neutral `Message[]` and\n * `ToolContract[]` into OpenAI wire shapes on the way out, and\n * translating OpenAI's response (content, finish reason, tool calls,\n * usage) back into the neutral shapes on the way in.\n * - Does NOT own: dispatching tools, deciding whether to loop, tracking\n * conversation history, or retrying on failure — those are agent\n * concerns. The model is a stateless (per-call) protocol adapter.\n *\n * Because it holds a live client and shared defaults, it is modeled as a\n * class (see §4.2 of code-style.md — \"long-lived state across calls\").\n *\n * @example\n * import OpenAI from \"openai\";\n * const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });\n * const model = new OpenAIModel(client, { name: \"gpt-4o\", temperature: 0.3 });\n *\n * const myAgent = agent({\n * model,\n * systemPrompt: \"You are a helpful assistant.\",\n * tools: [searchTool],\n * });\n *\n * const result = await myAgent.execute(\"Summarize today's news.\");\n */\nexport class OpenAIModel 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 // `api: \"responses\"` belongs to `OpenAIResponsesModel`, which only the\n // `OpenAISDK.model()` factory constructs. This class speaks Chat\n // Completions only; accepting the flag here would silently ignore it.\n if (config.api === \"responses\") {\n throw new InvalidRequestError(\n 'OpenAIModel speaks Chat Completions only and cannot serve api: \"responses\". Use OpenAISDK.model({ api: \"responses\" }) on the direct OpenAI provider.',\n { context: { provider, model: config.name, api: config.api } },\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 // o-series + gpt-5 / gpt-6 models surface a reasoning channel and accept\n // the `reasoning_effort` param. Explicit config wins over the\n // name-prefix inference.\n reasoning: config.reasoning ?? inferReasoningCapability(config.name),\n // Direct OpenAI requests support automatic cache hits and explicit\n // content-part breakpoints. Wrapper endpoints have distinct provider\n // labels and may reject these OpenAI-only request fields.\n promptCaching: this.provider === \"openai\",\n // PDF + audio INPUT are off by default — OpenAI accepts `file`\n // (PDF) and `input_audio` parts only on specific models, so the\n // flags are conservative/honest and opt-in via config rather than\n // name-inferred. When set, the agent admits the attachments and\n // `toOpenAIMessages` maps them to the real wire parts.\n pdf: config.pdf ?? false,\n audio: config.audio ?? false,\n };\n }\n\n /**\n * Single-shot completion. Sends the full message list to the Chat\n * Completions endpoint, waits for the terminal response, and reshapes it\n * into a vendor-neutral `ModelResponse`. Per-call `options` override the\n * instance's `ModelConfig` defaults for this call only.\n */\n public async complete(messages: Message[], options?: ModelCallOptions): Promise<ModelResponse> {\n // Per-call request/response logs are hot-path in production agents\n // — keep them at `debug` so `info` stays reserved for lifecycle\n // events (agent starting/completed, etc.). Operators who need to\n // audit every LLM call can raise log-level at runtime.\n this.logger.debug(LOG_MODULE, \"request\", \"Starting call to chat.completions\", {\n model: this.name,\n messageCount: messages.length,\n streaming: false,\n toolCount: options?.tools?.length ?? 0,\n });\n\n let response: OpenAI.Chat.Completions.ChatCompletion;\n\n try {\n response = await this.client.chat.completions.create(\n mergeProviderBody<OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming>(\n {\n model: this.name,\n ...compatibleSearchParams(this.provider, options),\n messages: toOpenAIMessages(messages, this.promptCacheBreakpoints(options)),\n ...this.buildSamplingParams(options),\n ...buildPromptCacheParams(this.provider, this.config),\n ...this.buildTools(options),\n ...this.buildResponseFormat(options?.responseSchema),\n ...this.buildReasoningParams(options?.reasoning, Boolean(options?.tools?.length)),\n },\n options,\n ),\n options?.signal ? { signal: options.signal } : undefined,\n );\n } catch (thrown) {\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 throw wrapped;\n }\n\n const [choice] = response.choices;\n\n if (choice === undefined) {\n // A 200 carrying an empty `choices` array. Every line below reads off\n // `choice`, so without this the caller got a bare `TypeError: Cannot\n // read properties of undefined` — no provider, no model, no hint that\n // the response itself was the problem rather than our handling of it.\n //\n // `ProviderError` because that is what this is: the provider answered\n // successfully and returned nothing usable. Callers already branch on\n // `instanceof ProviderError` for any provider-side failure.\n throw new ProviderError(\"OpenAI returned a response with no choices.\", {\n context: { provider: \"openai\", model: this.name, choices: response.choices.length },\n });\n }\n\n const finishReason = mapFinishReason(choice.finish_reason);\n const usage = this.extractUsage(response.usage);\n\n this.logger.debug(LOG_MODULE, \"response\", \"call to chat.completions succeeded\", {\n finishReason,\n usage,\n });\n\n return {\n content: choice.message.content ?? \"\",\n finishReason,\n usage,\n toolCalls: this.extractToolCalls(choice.message.tool_calls),\n };\n }\n\n /**\n * Incremental streaming completion. Yields neutral `ModelStreamChunk`s —\n * `delta` for text tokens, `tool-call` when the model requests a tool,\n * and a terminal `done` carrying the final finish reason + usage totals.\n * Callers consume it with `for await`.\n *\n * With `options.streamChunks` it also yields `tool-args` for each\n * `tool_calls[].function.arguments` fragment and `reasoning` for a\n * vendor's `reasoning_content` / `reasoning` delta field. Usage arrives\n * only on the final chunk here, so no `usage` chunk is emitted.\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 chat.completions\", {\n model: this.name,\n messageCount: messages.length,\n streaming: true,\n toolCount: options?.tools?.length ?? 0,\n });\n\n let stream: Awaited<ReturnType<typeof this.client.chat.completions.create>>;\n\n try {\n stream = await this.client.chat.completions.create(\n mergeProviderBody<OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming>(\n {\n model: this.name,\n ...compatibleSearchParams(this.provider, options),\n messages: toOpenAIMessages(messages, this.promptCacheBreakpoints(options)),\n ...this.buildSamplingParams(options),\n ...buildPromptCacheParams(this.provider, this.config),\n ...this.buildTools(options),\n stream: true,\n stream_options: { include_usage: true },\n ...this.buildResponseFormat(options?.responseSchema),\n ...this.buildReasoningParams(options?.reasoning, Boolean(options?.tools?.length)),\n },\n options,\n ),\n options?.signal ? { signal: options.signal } : undefined,\n );\n } catch (thrown) {\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 throw wrapped;\n }\n\n let rawFinishReason: string = \"stop\";\n let usage: Usage = { input: 0, output: 0, total: 0 };\n const want = resolveStreamChunks(options);\n const toolCallAccum = new Map<\n number,\n { id: string; name: string; arguments: string; streamed: number }\n >();\n\n try {\n for await (const chunk of stream as AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>) {\n const delta = chunk.choices[0]?.delta;\n const finish = chunk.choices[0]?.finish_reason;\n\n if (want.reasoning && delta) {\n const reasoning = readReasoningDelta(delta);\n\n if (reasoning) {\n yield { type: \"reasoning\", delta: reasoning };\n }\n }\n\n if (delta?.content) {\n yield { type: \"delta\", content: delta.content };\n }\n\n if (delta?.tool_calls) {\n for (const toolCall of delta.tool_calls) {\n const idx = toolCall.index ?? 0;\n if (!toolCallAccum.has(idx)) {\n toolCallAccum.set(idx, { id: \"\", name: \"\", arguments: \"\", streamed: 0 });\n }\n const acc = toolCallAccum.get(idx)!;\n if (toolCall.id) acc.id = toolCall.id;\n if (toolCall.function?.name) acc.name = toolCall.function.name;\n if (toolCall.function?.arguments) acc.arguments += toolCall.function.arguments;\n\n // The first fragment of a call carries its id and name; later\n // ones only `index` + argument text. Anything that arrived\n // before the name is flushed once the call is identified.\n if (want.toolArgs && acc.name && acc.arguments.length > acc.streamed) {\n yield {\n type: \"tool-args\",\n callId: acc.id,\n name: acc.name,\n delta: acc.arguments.slice(acc.streamed),\n };\n acc.streamed = acc.arguments.length;\n }\n }\n }\n\n if (finish) {\n rawFinishReason = finish;\n }\n\n if (chunk.usage) {\n usage = this.extractUsage(chunk.usage);\n }\n }\n\n for (const acc of toolCallAccum.values()) {\n // Skip accumulators that never received a function name — those\n // are partial fragments the model started but never identified\n // (e.g. arguments-only deltas with no originating `id`/`name`).\n // Yielding them produces nameless tool-calls the agent runtime\n // can't dispatch and would mis-attribute as a registered tool.\n if (!acc.name) continue;\n\n yield {\n type: \"tool-call\",\n id: acc.id,\n name: acc.name,\n input: safeJsonParse<Record<string, unknown>>(acc.arguments, {}),\n };\n }\n } catch (thrown) {\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 throw wrapped;\n }\n\n const finishReason = mapFinishReason(rawFinishReason);\n\n this.logger.debug(LOG_MODULE, \"response\", \"Streaming call to chat.completions succeeded\", {\n finishReason,\n usage,\n });\n\n yield {\n type: \"done\",\n finishReason,\n usage,\n };\n }\n\n /**\n * Spread-friendly `tools` fragment: the function tools, then the\n * provider-defined entries whose `provider` equals this model's\n * provider label (`\"openai\"`, or the vendor label an OpenAI-compatible\n * wrapper sets, e.g. `\"groq\"`), sent verbatim. Chat Completions only\n * accepts `function` and `custom` tool types from OpenAI itself; its\n * hosted tools (`web_search`, `file_search`, …) need `api: \"responses\"`\n * and OpenAI rejects them here with a 400.\n */\n private buildTools(options: ModelCallOptions | undefined): {\n tools?: OpenAI.Chat.Completions.ChatCompletionTool[];\n } {\n const { tools, definitions } = selectProviderTools(options, {\n accepts: [this.provider],\n module: LOG_MODULE,\n model: this.name,\n logger: this.logger,\n });\n // https://platform.kimi.ai/docs/guide/use-web-search — retires 2026-10-20.\n if (\n (this.provider === \"moonshot\" || this.provider === \"kimi\") &&\n definitions.some((definition) => {\n const fn = definition.function;\n return (\n definition.type === \"builtin_function\" &&\n typeof fn === \"object\" &&\n fn !== null &&\n \"name\" in fn &&\n fn.name === \"$web_search\"\n );\n })\n ) {\n throw new InvalidRequestError(\n \"Kimi's builtin $web_search retires on 20 October 2026. Use kimiSearchTool() / kimiFetchTool() from @warlock.js/ai-openai.\",\n );\n }\n // Native search is a Responses-only xAI feature. Fail before transport.\n // https://docs.x.ai/developers/tools/web-search\n if (\n this.provider === \"xai\" &&\n definitions.some(\n (definition) => definition.type === \"web_search\" || definition.type === \"x_search\",\n )\n ) {\n throw new InvalidRequestError(\n \"xAI native web_search / x_search requires POST /v1/responses. XaiSDK currently supports Chat Completions only; use xAI's Responses API with the vendor SDK for native search.\",\n );\n }\n const mapped = [\n ...(toOpenAITools(tools) ?? []),\n ...(definitions as unknown as OpenAI.Chat.Completions.ChatCompletionTool[]),\n ];\n\n return mapped.length > 0 ? { tools: mapped } : {};\n }\n\n /** Map the neutral cache hint only for the direct OpenAI provider. */\n private promptCacheBreakpoints(options: ModelCallOptions | undefined): number {\n return this.provider === \"openai\" ? (options?.cacheControl?.breakpoints ?? 0) : 0;\n }\n\n /**\n * Translate the neutral `responseSchema` option into OpenAI's\n * `response_format` parameter. The mode decision (override handling,\n * strict-compatibility downgrade to `json_object`) lives in\n * `planStructuredOutput`, shared with the Responses adapter.\n *\n * Returns an empty spread when no schema was supplied, so the caller\n * can unconditionally `...buildResponseFormat(...)` into the request.\n */\n private buildResponseFormat(responseSchema: Record<string, unknown> | undefined): {\n response_format?: OpenAI.Chat.Completions.ChatCompletionCreateParams[\"response_format\"];\n } {\n const plan = planStructuredOutput(responseSchema, this.config.responseFormat);\n\n if (plan.mode === \"json_schema\") {\n return {\n response_format: {\n type: \"json_schema\",\n json_schema: { name: \"response\", schema: plan.schema, strict: true },\n },\n };\n }\n\n if (plan.mode === \"json_object\") {\n return { response_format: { type: \"json_object\" } };\n }\n\n return {};\n }\n\n /**\n * Normalize OpenAI's `usage` block (which may be absent on some responses\n * or partials) into the neutral `Usage` shape. Missing usage collapses to\n * zeros rather than propagating `undefined`, so downstream aggregation\n * math stays safe.\n *\n * `cachedTokens` mirrors `prompt_tokens_details.cached_tokens` (the\n * subset of the prompt served from OpenAI's automatic prompt cache);\n * `reasoningTokens` mirrors `completion_tokens_details.reasoning_tokens`\n * (the hidden reasoning channel on o-series / gpt-5 models, already\n * counted within `output`). Both are emitted only when the provider\n * reports a positive value, so non-reasoning / uncached calls keep the\n * lean `{ input, output, total }` shape. `cacheWriteTokens` mirrors\n * `prompt_tokens_details.cache_write_tokens` (billed writes on the\n * models that charge for them). `cost` is attached when priced.\n */\n private extractUsage(raw: OpenAI.Completions.CompletionUsage | undefined): Usage {\n if (!raw) {\n return { input: 0, output: 0, total: 0 };\n }\n\n return buildUsage(\n {\n input: raw.prompt_tokens ?? 0,\n output: raw.completion_tokens ?? 0,\n total: raw.total_tokens ?? 0,\n cachedTokens: raw.prompt_tokens_details?.cached_tokens,\n cacheWriteTokens: raw.prompt_tokens_details?.cache_write_tokens,\n reasoningTokens: raw.completion_tokens_details?.reasoning_tokens,\n },\n this.pricing,\n );\n }\n\n /**\n * Translate the neutral `ModelCallOptions.reasoning` hint into OpenAI's\n * `reasoning_effort` request param. Only `effort` maps — OpenAI's Chat\n * Completions API exposes a discrete effort knob, not a token budget,\n * so `reasoning.maxTokens` (the Anthropic extended-thinking cap) has no\n * wire equivalent here and is silently ignored.\n *\n * The neutral `ReasoningEffort` (`\"low\" | \"medium\" | \"high\" | \"none\"`)\n * is a subset of OpenAI's accepted values, so it forwards verbatim —\n * `\"none\"` included. `\"none\"` is load-bearing: gpt-5 / o-series models\n * **reject function tools** on Chat Completions while reasoning is\n * active, and the endpoint accepts tools only when `reasoning_effort`\n * is `\"none\"` (the alternative is the Responses API). This is why the\n * param is EMITTED for `\"none\"` rather than omitted — omitting it\n * leaves the model reasoning server-side by default, so tools would\n * still be rejected.\n *\n * No-ops when the model is not reasoning-capable\n * (`capabilities.reasoning` is false — e.g. `gpt-4o`, which 400s on any\n * `reasoning_effort`).\n *\n * When the caller gave no explicit `effort`: defaults to `\"none\"` IF\n * `hasTools` is true, else omits the param (provider default — the\n * pre-existing behavior for a tool-less call). The default exists\n * because, on a reasoning-capable model, there is no working alternative\n * to `\"none\"` when tools are attached — omitting `reasoning_effort`\n * leaves reasoning on server-side, which Chat Completions rejects tools\n * for (empty replies on some model generations, a hard 400 — \"Function\n * tools with reasoning_effort are not supported ... in\n * /v1/chat/completions\" — on newer ones). An explicit `effort` from the\n * caller always wins over this default, in either direction.\n *\n * Returns an empty spread when nothing applies, so the caller can\n * unconditionally `...buildReasoningParams(...)` into the request.\n */\n /**\n * Output-length and sampling params, in current Chat Completions shapes only.\n *\n * - `max_completion_tokens`, never the legacy `max_tokens`: current\n * models (the gpt-5 family and later) answer `400 unsupported_parameter`\n * to `max_tokens`, and `max_completion_tokens` is accepted everywhere.\n * - No `temperature` for a reasoning-capable model: those accept only the\n * default value and reject any other with a 400.\n */\n private buildSamplingParams(options: ModelCallOptions | undefined): {\n max_completion_tokens?: number;\n temperature?: number;\n } {\n const maxTokens = options?.maxTokens ?? this.config.maxTokens;\n const temperature = options?.temperature ?? this.config.temperature;\n\n return {\n max_completion_tokens: maxTokens,\n ...(!this.capabilities.reasoning && { temperature }),\n };\n }\n\n private buildReasoningParams(\n reasoning: ModelCallOptions[\"reasoning\"],\n hasTools: boolean,\n ): {\n reasoning_effort?: OpenAI.Chat.Completions.ChatCompletionCreateParams[\"reasoning_effort\"];\n } {\n if (!this.capabilities.reasoning) {\n return {};\n }\n\n if (!reasoning?.effort) {\n return hasTools ? { reasoning_effort: \"none\" } : {};\n }\n\n return { reasoning_effort: toOpenAIReasoningEffort(reasoning.effort) };\n }\n\n /**\n * Reshape OpenAI's `tool_calls` array into the neutral\n * `ModelToolCallRequest[]`. The raw `arguments` field is a JSON string\n * per OpenAI's protocol — we parse it defensively via `safeJsonParse` so\n * malformed or empty arguments yield an empty object instead of crashing\n * the trip. Returns `undefined` when no tools were requested so callers\n * can branch on presence.\n */\n private extractToolCalls(\n rawToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] | undefined,\n ): ModelToolCallRequest[] | undefined {\n if (!rawToolCalls || rawToolCalls.length === 0) {\n return undefined;\n }\n\n return rawToolCalls.map((toolCall) => ({\n id: toolCall.id,\n name: (toolCall as any).function.name,\n input: safeJsonParse<Record<string, unknown>>((toolCall as any).function.arguments, {}),\n }));\n }\n}\n\n/**\n * Reasoning text an OpenAI-compatible vendor puts on a Chat Completions\n * stream delta. OpenAI itself streams none on this API. DeepSeek documents\n * `delta.reasoning_content` (API reference, chat completion chunk); Groq\n * documents the parsed reasoning under a `reasoning` field. Neither is in\n * the OpenAI SDK's delta type, so the delta is read as a plain record.\n */\nfunction readReasoningDelta(delta: object): string | undefined {\n const record = delta as Record<string, unknown>;\n\n for (const key of [\"reasoning_content\", \"reasoning\"]) {\n const value = record[key];\n\n if (typeof value === \"string\" && value !== \"\") {\n return value;\n }\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkCA,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCnB,IAAa,cAAb,MAAkD;CAUhD,AAAO,YAAY,QAAgB,QAA2B,WAAmB,UAAU;gBAFzD;EAMhC,IAAI,OAAO,QAAQ,aACjB,MAAM,IAAI,oBACR,4JACA,EAAE,SAAS;GAAE;GAAU,OAAO,OAAO;GAAM,KAAK,OAAO;EAAI,EAAE,CAC/D;EAGF,KAAK,SAAS;EACd,KAAK,SAAS;EACd,KAAK,OAAO,OAAO;EACnB,KAAK,WAAW;EAChB,KAAK,UAAU,OAAO;EACtB,KAAK,eAAe;GAClB,kBAAkB,OAAO,oBAAoB,sBAAsB,OAAO,cAAc;GACxF,QAAQ,OAAO,UAAU,sBAAsB,OAAO,IAAI;GAI1D,WAAW,OAAO,aAAa,yBAAyB,OAAO,IAAI;GAInE,eAAe,KAAK,aAAa;GAMjC,KAAK,OAAO,OAAO;GACnB,OAAO,OAAO,SAAS;EACzB;CACF;;;;;;;CAQA,MAAa,SAAS,UAAqB,SAAoD;EAK7F,KAAK,OAAO,MAAM,YAAY,WAAW,qCAAqC;GAC5E,OAAO,KAAK;GACZ,cAAc,SAAS;GACvB,WAAW;GACX,WAAW,SAAS,OAAO,UAAU;EACvC,CAAC;EAED,IAAI;EAEJ,IAAI;GACF,WAAW,MAAM,KAAK,OAAO,KAAK,YAAY,OAC5C,kBACE;IACE,OAAO,KAAK;IACZ,GAAG,uBAAuB,KAAK,UAAU,OAAO;IAChD,UAAU,iBAAiB,UAAU,KAAK,uBAAuB,OAAO,CAAC;IACzE,GAAG,KAAK,oBAAoB,OAAO;IACnC,GAAG,uBAAuB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;GACvB,GAAI,CAAC,KAAK,aAAa,aAAa,EAAE,YAAY;EACpD;CACF;CAEA,AAAQ,qBACN,WACA,UAGA;EACA,IAAI,CAAC,KAAK,aAAa,WACrB,OAAO,CAAC;EAGV,IAAI,CAAC,WAAW,QACd,OAAO,WAAW,EAAE,kBAAkB,OAAO,IAAI,CAAC;EAGpD,OAAO,EAAE,kBAAkB,wBAAwB,UAAU,MAAM,EAAE;CACvE;;;;;;;;;CAUA,AAAQ,iBACN,cACoC;EACpC,IAAI,CAAC,gBAAgB,aAAa,WAAW,GAC3C;EAGF,OAAO,aAAa,KAAK,cAAc;GACrC,IAAI,SAAS;GACb,MAAO,SAAiB,SAAS;GACjC,OAAO,cAAwC,SAAiB,SAAS,WAAW,CAAC,CAAC;EACxF,EAAE;CACJ;AACF;;;;;;;;AASA,SAAS,mBAAmB,OAAmC;CAC7D,MAAM,SAAS;CAEf,KAAK,MAAM,OAAO,CAAC,qBAAqB,WAAW,GAAG;EACpD,MAAM,QAAQ,OAAO;EAErB,IAAI,OAAO,UAAU,YAAY,UAAU,IACzC,OAAO;CAEX;AAGF"}
1
+ {"version":3,"file":"model.mjs","names":[],"sources":["../../../../../../../packages/ai-openai/src/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 { assertHostedSearchSupported, requestsHostedSearch } from \"./native-search\";\nimport { OpenAIResponsesModel } from \"./responses-model\";\nimport type OpenAI from \"openai\";\nimport { compatibleSearchParams, mergeProviderBody } from \"./provider-options\";\nimport type { OpenAIModelConfig } from \"./config.type\";\nimport { inferReasoningCapability } from \"./known-reasoning-models\";\nimport { inferVisionCapability } from \"./known-vision-models\";\nimport {\n buildPromptCacheParams,\n buildUsage,\n inferStructuredOutput,\n mapFinishReason,\n planStructuredOutput,\n toOpenAIMessages,\n toOpenAIReasoningEffort,\n toOpenAITools,\n wrapOpenAIError,\n} from \"./utils\";\n\nconst LOG_MODULE = \"ai.openai\";\n\n/**\n * OpenAI-backed implementation of `ModelContract`.\n *\n * **Role.** The provider-facing bridge between the vendor-neutral\n * `@warlock.js/ai` agent runtime and the official `openai` SDK. Agents,\n * workflows, and supervisors never talk to OpenAI directly — they hold a\n * `ModelContract`, and this class is what makes that contract concrete for\n * any OpenAI-compatible endpoint (OpenAI, Azure OpenAI, OpenRouter, local\n * gateways that speak the Chat Completions protocol).\n *\n * **Responsibility.**\n * - Owns: a long-lived `OpenAI` client + frozen `ModelConfig` (name,\n * temperature, maxTokens) used as defaults for every call.\n * - Owns: translating vendor-neutral `Message[]` and\n * `ToolContract[]` into OpenAI wire shapes on the way out, and\n * translating OpenAI's response (content, finish reason, tool calls,\n * usage) back into the neutral shapes on the way in.\n * - Does NOT own: dispatching tools, deciding whether to loop, tracking\n * conversation history, or retrying on failure — those are agent\n * concerns. The model is a stateless (per-call) protocol adapter.\n *\n * Because it holds a live client and shared defaults, it is modeled as a\n * class (see §4.2 of code-style.md — \"long-lived state across calls\").\n *\n * @example\n * import OpenAI from \"openai\";\n * const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });\n * const model = new OpenAIModel(client, { name: \"gpt-4o\", temperature: 0.3 });\n *\n * const myAgent = agent({\n * model,\n * systemPrompt: \"You are a helpful assistant.\",\n * tools: [searchTool],\n * });\n *\n * const result = await myAgent.execute(\"Summarize today's news.\");\n */\nexport class OpenAIModel 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 private searchModel?: OpenAIResponsesModel;\n\n public constructor(client: OpenAI, config: OpenAIModelConfig, provider: string = \"openai\") {\n // `api: \"responses\"` belongs to `OpenAIResponsesModel`, which only the\n // `OpenAISDK.model()` factory constructs. This class speaks Chat\n // Completions only; accepting the flag here would silently ignore it.\n if (config.api === \"responses\") {\n throw new InvalidRequestError(\n 'OpenAIModel speaks Chat Completions only and cannot serve api: \"responses\". Use OpenAISDK.model({ api: \"responses\" }) on the direct OpenAI provider.',\n { context: { provider, model: config.name, api: config.api } },\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 // o-series + gpt-5 / gpt-6 models surface a reasoning channel and accept\n // the `reasoning_effort` param. Explicit config wins over the\n // name-prefix inference.\n reasoning: config.reasoning ?? inferReasoningCapability(config.name),\n // Direct OpenAI requests support automatic cache hits and explicit\n // content-part breakpoints. Wrapper endpoints have distinct provider\n // labels and may reject these OpenAI-only request fields.\n promptCaching: this.provider === \"openai\",\n // PDF + audio INPUT are off by default — OpenAI accepts `file`\n // (PDF) and `input_audio` parts only on specific models, so the\n // flags are conservative/honest and opt-in via config rather than\n // name-inferred. When set, the agent admits the attachments and\n // `toOpenAIMessages` maps them to the real wire parts.\n pdf: config.pdf ?? false,\n audio: config.audio ?? false,\n };\n }\n\n /**\n * Single-shot completion. Sends the full message list to the Chat\n * Completions endpoint, waits for the terminal response, and reshapes it\n * into a vendor-neutral `ModelResponse`. Per-call `options` override the\n * instance's `ModelConfig` defaults for this call only.\n */\n public async complete(messages: Message[], options?: ModelCallOptions): Promise<ModelResponse> {\n const searchRoute = this.hostedSearchRoute(options);\n\n if (searchRoute) {\n return searchRoute.complete(messages, options);\n }\n\n // Per-call request/response logs are hot-path in production agents\n // — keep them at `debug` so `info` stays reserved for lifecycle\n // events (agent starting/completed, etc.). Operators who need to\n // audit every LLM call can raise log-level at runtime.\n this.logger.debug(LOG_MODULE, \"request\", \"Starting call to chat.completions\", {\n model: this.name,\n messageCount: messages.length,\n streaming: false,\n toolCount: options?.tools?.length ?? 0,\n });\n\n let response: OpenAI.Chat.Completions.ChatCompletion;\n\n try {\n response = await this.client.chat.completions.create(\n mergeProviderBody<OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming>(\n {\n model: this.name,\n ...compatibleSearchParams(this.provider, options),\n messages: toOpenAIMessages(messages, this.promptCacheBreakpoints(options)),\n ...this.buildSamplingParams(options),\n ...buildPromptCacheParams(this.provider, this.config),\n ...this.buildTools(options),\n ...this.buildResponseFormat(options?.responseSchema),\n ...this.buildReasoningParams(options?.reasoning, Boolean(options?.tools?.length)),\n },\n options,\n ),\n options?.signal ? { signal: options.signal } : undefined,\n );\n } catch (thrown) {\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 throw wrapped;\n }\n\n const [choice] = response.choices;\n\n if (choice === undefined) {\n // A 200 carrying an empty `choices` array. Every line below reads off\n // `choice`, so without this the caller got a bare `TypeError: Cannot\n // read properties of undefined` — no provider, no model, no hint that\n // the response itself was the problem rather than our handling of it.\n //\n // `ProviderError` because that is what this is: the provider answered\n // successfully and returned nothing usable. Callers already branch on\n // `instanceof ProviderError` for any provider-side failure.\n throw new ProviderError(\"OpenAI returned a response with no choices.\", {\n context: { provider: \"openai\", model: this.name, choices: response.choices.length },\n });\n }\n\n const finishReason = mapFinishReason(choice.finish_reason);\n const usage = this.extractUsage(response.usage);\n\n this.logger.debug(LOG_MODULE, \"response\", \"call to chat.completions succeeded\", {\n finishReason,\n usage,\n });\n\n return {\n content: choice.message.content ?? \"\",\n finishReason,\n usage,\n toolCalls: this.extractToolCalls(choice.message.tool_calls),\n };\n }\n\n /**\n * Incremental streaming completion. Yields neutral `ModelStreamChunk`s —\n * `delta` for text tokens, `tool-call` when the model requests a tool,\n * and a terminal `done` carrying the final finish reason + usage totals.\n * Callers consume it with `for await`.\n *\n * With `options.streamChunks` it also yields `tool-args` for each\n * `tool_calls[].function.arguments` fragment and `reasoning` for a\n * vendor's `reasoning_content` / `reasoning` delta field. Usage arrives\n * only on the final chunk here, so no `usage` chunk is emitted.\n */\n public async *stream(\n messages: Message[],\n options?: ModelCallOptions,\n ): AsyncIterable<ModelStreamChunk> {\n const searchRoute = this.hostedSearchRoute(options);\n\n if (searchRoute) {\n yield* searchRoute.stream(messages, options);\n return;\n }\n\n this.logger.debug(LOG_MODULE, \"request\", \"Starting streaming call to chat.completions\", {\n model: this.name,\n messageCount: messages.length,\n streaming: true,\n toolCount: options?.tools?.length ?? 0,\n });\n\n let stream: Awaited<ReturnType<typeof this.client.chat.completions.create>>;\n\n try {\n stream = await this.client.chat.completions.create(\n mergeProviderBody<OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming>(\n {\n model: this.name,\n ...compatibleSearchParams(this.provider, options),\n messages: toOpenAIMessages(messages, this.promptCacheBreakpoints(options)),\n ...this.buildSamplingParams(options),\n ...buildPromptCacheParams(this.provider, this.config),\n ...this.buildTools(options),\n stream: true,\n stream_options: { include_usage: true },\n ...this.buildResponseFormat(options?.responseSchema),\n ...this.buildReasoningParams(options?.reasoning, Boolean(options?.tools?.length)),\n },\n options,\n ),\n options?.signal ? { signal: options.signal } : undefined,\n );\n } catch (thrown) {\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 throw wrapped;\n }\n\n let rawFinishReason: string = \"stop\";\n let usage: Usage = { input: 0, output: 0, total: 0 };\n const want = resolveStreamChunks(options);\n const toolCallAccum = new Map<\n number,\n { id: string; name: string; arguments: string; streamed: number }\n >();\n\n try {\n for await (const chunk of stream as AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>) {\n const delta = chunk.choices[0]?.delta;\n const finish = chunk.choices[0]?.finish_reason;\n\n if (want.reasoning && delta) {\n const reasoning = readReasoningDelta(delta);\n\n if (reasoning) {\n yield { type: \"reasoning\", delta: reasoning };\n }\n }\n\n if (delta?.content) {\n yield { type: \"delta\", content: delta.content };\n }\n\n if (delta?.tool_calls) {\n for (const toolCall of delta.tool_calls) {\n const idx = toolCall.index ?? 0;\n if (!toolCallAccum.has(idx)) {\n toolCallAccum.set(idx, { id: \"\", name: \"\", arguments: \"\", streamed: 0 });\n }\n const acc = toolCallAccum.get(idx)!;\n if (toolCall.id) acc.id = toolCall.id;\n if (toolCall.function?.name) acc.name = toolCall.function.name;\n if (toolCall.function?.arguments) acc.arguments += toolCall.function.arguments;\n\n // The first fragment of a call carries its id and name; later\n // ones only `index` + argument text. Anything that arrived\n // before the name is flushed once the call is identified.\n if (want.toolArgs && acc.name && acc.arguments.length > acc.streamed) {\n yield {\n type: \"tool-args\",\n callId: acc.id,\n name: acc.name,\n delta: acc.arguments.slice(acc.streamed),\n };\n acc.streamed = acc.arguments.length;\n }\n }\n }\n\n if (finish) {\n rawFinishReason = finish;\n }\n\n if (chunk.usage) {\n usage = this.extractUsage(chunk.usage);\n }\n }\n\n for (const acc of toolCallAccum.values()) {\n // Skip accumulators that never received a function name — those\n // are partial fragments the model started but never identified\n // (e.g. arguments-only deltas with no originating `id`/`name`).\n // Yielding them produces nameless tool-calls the agent runtime\n // can't dispatch and would mis-attribute as a registered tool.\n if (!acc.name) continue;\n\n yield {\n type: \"tool-call\",\n id: acc.id,\n name: acc.name,\n input: safeJsonParse<Record<string, unknown>>(acc.arguments, {}),\n };\n }\n } catch (thrown) {\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 throw wrapped;\n }\n\n const finishReason = mapFinishReason(rawFinishReason);\n\n this.logger.debug(LOG_MODULE, \"response\", \"Streaming call to chat.completions succeeded\", {\n finishReason,\n usage,\n });\n\n yield {\n type: \"done\",\n finishReason,\n usage,\n };\n }\n\n /**\n * OpenAI's hosted `web_search` tool exists only on the Responses API, and\n * Chat Completions answers it with a 400. When a call on the direct\n * `\"openai\"` provider carries it, the call is served by the Responses\n * adapter instead (same client, same pricing, same model name), unless the\n * model was pinned to `api: \"chat\"` or cannot search at all: both throw a\n * clear error before any request, never a silent fallback to something\n * else. Every other call stays on Chat Completions.\n */\n private hostedSearchRoute(\n options: ModelCallOptions | undefined,\n ): OpenAIResponsesModel | undefined {\n if (this.provider !== \"openai\" || !requestsHostedSearch(options, this.provider)) {\n return undefined;\n }\n\n if (this.config.api === \"chat\") {\n throw new InvalidRequestError(\n `OpenAI's hosted web_search tool needs the Responses API, but \"${this.name}\" is pinned to api: \"chat\". Remove api: \"chat\" (the call is then routed to the Responses API) or use api: \"responses\".`,\n { context: { provider: this.provider, model: this.name, api: \"chat\", tool: \"web_search\" } },\n );\n }\n\n assertHostedSearchSupported(this.name, options);\n this.searchModel ??= new OpenAIResponsesModel(this.client, this.config, this.provider);\n\n return this.searchModel;\n }\n\n /**\n * Spread-friendly `tools` fragment: the function tools, then the\n * provider-defined entries whose `provider` equals this model's\n * provider label (`\"openai\"`, or the vendor label an OpenAI-compatible\n * wrapper sets, e.g. `\"groq\"`), sent verbatim. Chat Completions only\n * accepts `function` and `custom` tool types from OpenAI itself; its\n * hosted tools (`web_search`, `file_search`, …) need `api: \"responses\"`\n * and OpenAI rejects them here with a 400.\n */\n private buildTools(options: ModelCallOptions | undefined): {\n tools?: OpenAI.Chat.Completions.ChatCompletionTool[];\n } {\n const { tools, definitions } = selectProviderTools(options, {\n accepts: [this.provider],\n module: LOG_MODULE,\n model: this.name,\n logger: this.logger,\n });\n // https://platform.kimi.ai/docs/guide/use-web-search — retires 2026-10-20.\n if (\n (this.provider === \"moonshot\" || this.provider === \"kimi\") &&\n definitions.some((definition) => {\n const fn = definition.function;\n return (\n definition.type === \"builtin_function\" &&\n typeof fn === \"object\" &&\n fn !== null &&\n \"name\" in fn &&\n fn.name === \"$web_search\"\n );\n })\n ) {\n throw new InvalidRequestError(\n \"Kimi's builtin $web_search retires on 20 October 2026. Use kimiSearchTool() / kimiFetchTool() from @warlock.js/ai-openai.\",\n );\n }\n // Native search is a Responses-only xAI feature. Fail before transport.\n // https://docs.x.ai/developers/tools/web-search\n if (\n this.provider === \"xai\" &&\n definitions.some(\n (definition) => definition.type === \"web_search\" || definition.type === \"x_search\",\n )\n ) {\n throw new InvalidRequestError(\n \"xAI native web_search / x_search requires POST /v1/responses. Build the model with XaiSDK from @warlock.js/ai-xai, which routes those calls to the Responses API.\",\n );\n }\n const mapped = [\n ...(toOpenAITools(tools) ?? []),\n ...(definitions as unknown as OpenAI.Chat.Completions.ChatCompletionTool[]),\n ];\n\n return mapped.length > 0 ? { tools: mapped } : {};\n }\n\n /** Map the neutral cache hint only for the direct OpenAI provider. */\n private promptCacheBreakpoints(options: ModelCallOptions | undefined): number {\n return this.provider === \"openai\" ? (options?.cacheControl?.breakpoints ?? 0) : 0;\n }\n\n /**\n * Translate the neutral `responseSchema` option into OpenAI's\n * `response_format` parameter. The mode decision (override handling,\n * strict-compatibility downgrade to `json_object`) lives in\n * `planStructuredOutput`, shared with the Responses adapter.\n *\n * Returns an empty spread when no schema was supplied, so the caller\n * can unconditionally `...buildResponseFormat(...)` into the request.\n */\n private buildResponseFormat(responseSchema: Record<string, unknown> | undefined): {\n response_format?: OpenAI.Chat.Completions.ChatCompletionCreateParams[\"response_format\"];\n } {\n const plan = planStructuredOutput(responseSchema, this.config.responseFormat);\n\n if (plan.mode === \"json_schema\") {\n return {\n response_format: {\n type: \"json_schema\",\n json_schema: { name: \"response\", schema: plan.schema, strict: true },\n },\n };\n }\n\n if (plan.mode === \"json_object\") {\n return { response_format: { type: \"json_object\" } };\n }\n\n return {};\n }\n\n /**\n * Normalize OpenAI's `usage` block (which may be absent on some responses\n * or partials) into the neutral `Usage` shape. Missing usage collapses to\n * zeros rather than propagating `undefined`, so downstream aggregation\n * math stays safe.\n *\n * `cachedTokens` mirrors `prompt_tokens_details.cached_tokens` (the\n * subset of the prompt served from OpenAI's automatic prompt cache);\n * `reasoningTokens` mirrors `completion_tokens_details.reasoning_tokens`\n * (the hidden reasoning channel on o-series / gpt-5 models, already\n * counted within `output`). Both are emitted only when the provider\n * reports a positive value, so non-reasoning / uncached calls keep the\n * lean `{ input, output, total }` shape. `cacheWriteTokens` mirrors\n * `prompt_tokens_details.cache_write_tokens` (billed writes on the\n * models that charge for them). `cost` is attached when priced.\n */\n private extractUsage(raw: OpenAI.Completions.CompletionUsage | undefined): Usage {\n if (!raw) {\n return { input: 0, output: 0, total: 0 };\n }\n\n return buildUsage(\n {\n input: raw.prompt_tokens ?? 0,\n output: raw.completion_tokens ?? 0,\n total: raw.total_tokens ?? 0,\n cachedTokens: raw.prompt_tokens_details?.cached_tokens,\n cacheWriteTokens: raw.prompt_tokens_details?.cache_write_tokens,\n reasoningTokens: raw.completion_tokens_details?.reasoning_tokens,\n },\n this.pricing,\n );\n }\n\n /**\n * Translate the neutral `ModelCallOptions.reasoning` hint into OpenAI's\n * `reasoning_effort` request param. Only `effort` maps — OpenAI's Chat\n * Completions API exposes a discrete effort knob, not a token budget,\n * so `reasoning.maxTokens` (the Anthropic extended-thinking cap) has no\n * wire equivalent here and is silently ignored.\n *\n * The neutral `ReasoningEffort` (`\"low\" | \"medium\" | \"high\" | \"none\"`)\n * is a subset of OpenAI's accepted values, so it forwards verbatim —\n * `\"none\"` included. `\"none\"` is load-bearing: gpt-5 / o-series models\n * **reject function tools** on Chat Completions while reasoning is\n * active, and the endpoint accepts tools only when `reasoning_effort`\n * is `\"none\"` (the alternative is the Responses API). This is why the\n * param is EMITTED for `\"none\"` rather than omitted — omitting it\n * leaves the model reasoning server-side by default, so tools would\n * still be rejected.\n *\n * No-ops when the model is not reasoning-capable\n * (`capabilities.reasoning` is false — e.g. `gpt-4o`, which 400s on any\n * `reasoning_effort`).\n *\n * When the caller gave no explicit `effort`: defaults to `\"none\"` IF\n * `hasTools` is true, else omits the param (provider default — the\n * pre-existing behavior for a tool-less call). The default exists\n * because, on a reasoning-capable model, there is no working alternative\n * to `\"none\"` when tools are attached — omitting `reasoning_effort`\n * leaves reasoning on server-side, which Chat Completions rejects tools\n * for (empty replies on some model generations, a hard 400 — \"Function\n * tools with reasoning_effort are not supported ... in\n * /v1/chat/completions\" — on newer ones). An explicit `effort` from the\n * caller always wins over this default, in either direction.\n *\n * Returns an empty spread when nothing applies, so the caller can\n * unconditionally `...buildReasoningParams(...)` into the request.\n */\n /**\n * Output-length and sampling params, in current Chat Completions shapes only.\n *\n * - `max_completion_tokens`, never the legacy `max_tokens`: current\n * models (the gpt-5 family and later) answer `400 unsupported_parameter`\n * to `max_tokens`, and `max_completion_tokens` is accepted everywhere.\n * - No `temperature` for a reasoning-capable model: those accept only the\n * default value and reject any other with a 400.\n */\n private buildSamplingParams(options: ModelCallOptions | undefined): {\n max_completion_tokens?: number;\n temperature?: number;\n } {\n const maxTokens = options?.maxTokens ?? this.config.maxTokens;\n const temperature = options?.temperature ?? this.config.temperature;\n\n return {\n max_completion_tokens: maxTokens,\n ...(!this.capabilities.reasoning && { temperature }),\n };\n }\n\n private buildReasoningParams(\n reasoning: ModelCallOptions[\"reasoning\"],\n hasTools: boolean,\n ): {\n reasoning_effort?: OpenAI.Chat.Completions.ChatCompletionCreateParams[\"reasoning_effort\"];\n } {\n if (!this.capabilities.reasoning) {\n return {};\n }\n\n if (!reasoning?.effort) {\n return hasTools ? { reasoning_effort: \"none\" } : {};\n }\n\n return { reasoning_effort: toOpenAIReasoningEffort(reasoning.effort) };\n }\n\n /**\n * Reshape OpenAI's `tool_calls` array into the neutral\n * `ModelToolCallRequest[]`. The raw `arguments` field is a JSON string\n * per OpenAI's protocol — we parse it defensively via `safeJsonParse` so\n * malformed or empty arguments yield an empty object instead of crashing\n * the trip. Returns `undefined` when no tools were requested so callers\n * can branch on presence.\n */\n private extractToolCalls(\n rawToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] | undefined,\n ): ModelToolCallRequest[] | undefined {\n if (!rawToolCalls || rawToolCalls.length === 0) {\n return undefined;\n }\n\n return rawToolCalls.map((toolCall) => ({\n id: toolCall.id,\n name: (toolCall as any).function.name,\n input: safeJsonParse<Record<string, unknown>>((toolCall as any).function.arguments, {}),\n }));\n }\n}\n\n/**\n * Reasoning text an OpenAI-compatible vendor puts on a Chat Completions\n * stream delta. OpenAI itself streams none on this API. DeepSeek documents\n * `delta.reasoning_content` (API reference, chat completion chunk); Groq\n * documents the parsed reasoning under a `reasoning` field. Neither is in\n * the OpenAI SDK's delta type, so the delta is read as a plain record.\n */\nfunction readReasoningDelta(delta: object): string | undefined {\n const record = delta as Record<string, unknown>;\n\n for (const key of [\"reasoning_content\", \"reasoning\"]) {\n const value = record[key];\n\n if (typeof value === \"string\" && value !== \"\") {\n return value;\n }\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoCA,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCnB,IAAa,cAAb,MAAkD;CAWhD,AAAO,YAAY,QAAgB,QAA2B,WAAmB,UAAU;gBAHzD;EAOhC,IAAI,OAAO,QAAQ,aACjB,MAAM,IAAI,oBACR,4JACA,EAAE,SAAS;GAAE;GAAU,OAAO,OAAO;GAAM,KAAK,OAAO;EAAI,EAAE,CAC/D;EAGF,KAAK,SAAS;EACd,KAAK,SAAS;EACd,KAAK,OAAO,OAAO;EACnB,KAAK,WAAW;EAChB,KAAK,UAAU,OAAO;EACtB,KAAK,eAAe;GAClB,kBAAkB,OAAO,oBAAoB,sBAAsB,OAAO,cAAc;GACxF,QAAQ,OAAO,UAAU,sBAAsB,OAAO,IAAI;GAI1D,WAAW,OAAO,aAAa,yBAAyB,OAAO,IAAI;GAInE,eAAe,KAAK,aAAa;GAMjC,KAAK,OAAO,OAAO;GACnB,OAAO,OAAO,SAAS;EACzB;CACF;;;;;;;CAQA,MAAa,SAAS,UAAqB,SAAoD;EAC7F,MAAM,cAAc,KAAK,kBAAkB,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AAAQ,iBACN,cACoC;EACpC,IAAI,CAAC,gBAAgB,aAAa,WAAW,GAC3C;EAGF,OAAO,aAAa,KAAK,cAAc;GACrC,IAAI,SAAS;GACb,MAAO,SAAiB,SAAS;GACjC,OAAO,cAAwC,SAAiB,SAAS,WAAW,CAAC,CAAC;EACxF,EAAE;CACJ;AACF;;;;;;;;AASA,SAAS,mBAAmB,OAAmC;CAC7D,MAAM,SAAS;CAEf,KAAK,MAAM,OAAO,CAAC,qBAAqB,WAAW,GAAG;EACpD,MAAM,QAAQ,OAAO;EAErB,IAAI,OAAO,UAAU,YAAY,UAAU,IACzC,OAAO;CAEX;AAGF"}
@@ -0,0 +1,47 @@
1
+ import { InvalidRequestError, isProviderTool } from "@warlock.js/ai";
2
+
3
+ //#region ../../packages/ai-openai/src/native-search.ts
4
+ /** Hosted web-search tool types the Responses API accepts. */
5
+ const HOSTED_SEARCH_TYPES = /* @__PURE__ */ new Set([
6
+ "web_search",
7
+ "web_search_2025_08_26",
8
+ "web_search_preview",
9
+ "web_search_preview_2025_03_11"
10
+ ]);
11
+ /**
12
+ * Models the OpenAI web-search tool is documented as unavailable on, plus
13
+ * ids that are not conversational at all. Everything else is attempted:
14
+ * an id the list does not know still reaches OpenAI, which is the authority.
15
+ * https://developers.openai.com/api/docs/guides/tools-web-search
16
+ */
17
+ const UNSUPPORTED_SEARCH_MODELS = /^(?:gpt-3\.5|gpt-4(?:-\d|-turbo|-32k|$)|gpt-4\.1-nano|o1-mini|o1-preview|o3-mini|text-embedding|whisper|tts|dall-e|gpt-image|omni-moderation)/u;
18
+ /** The provider-defined entries on a call that belong to `provider`. */
19
+ function providerToolsOf(options, provider) {
20
+ return [...options?.providerTools ?? [], ...(options?.tools ?? []).filter(isProviderTool)].filter((entry) => entry.provider === provider).map((entry) => entry);
21
+ }
22
+ /** `true` when the call carries OpenAI's hosted web-search tool. */
23
+ function requestsHostedSearch(options, provider) {
24
+ return providerToolsOf(options, provider).some((entry) => typeof entry.definition.type === "string" && HOSTED_SEARCH_TYPES.has(entry.definition.type));
25
+ }
26
+ /**
27
+ * Throw a capability error, before any request, when a model cannot run
28
+ * OpenAI's hosted web search. Nothing falls back silently: the caller picks
29
+ * another model or drops the tool.
30
+ */
31
+ function assertHostedSearchSupported(model, options) {
32
+ if (UNSUPPORTED_SEARCH_MODELS.test(model)) throw new InvalidRequestError(`OpenAI's hosted web_search tool is not available on "${model}". Use a model that supports it (for example gpt-4.1, gpt-4.1-mini, gpt-4o, gpt-5), or remove the web_search tool.`, { context: {
33
+ provider: "openai",
34
+ model,
35
+ tool: "web_search"
36
+ } });
37
+ if (/^gpt-5/u.test(model) && options?.reasoning?.effort === "minimal") throw new InvalidRequestError(`OpenAI's hosted web_search tool is not available on "${model}" with minimal reasoning. Use a higher reasoning effort or remove the web_search tool.`, { context: {
38
+ provider: "openai",
39
+ model,
40
+ tool: "web_search",
41
+ effort: "minimal"
42
+ } });
43
+ }
44
+
45
+ //#endregion
46
+ export { assertHostedSearchSupported, providerToolsOf, requestsHostedSearch };
47
+ //# sourceMappingURL=native-search.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"native-search.mjs","names":[],"sources":["../../../../../../../packages/ai-openai/src/native-search.ts"],"sourcesContent":["import {\n InvalidRequestError,\n isProviderTool,\n type ModelCallOptions,\n type ProviderToolDefinition,\n} from \"@warlock.js/ai\";\n\n/** Hosted web-search tool types the Responses API accepts. */\nconst HOSTED_SEARCH_TYPES: ReadonlySet<string> = new Set([\n \"web_search\",\n \"web_search_2025_08_26\",\n \"web_search_preview\",\n \"web_search_preview_2025_03_11\",\n]);\n\n/**\n * Models the OpenAI web-search tool is documented as unavailable on, plus\n * ids that are not conversational at all. Everything else is attempted:\n * an id the list does not know still reaches OpenAI, which is the authority.\n * https://developers.openai.com/api/docs/guides/tools-web-search\n */\nconst UNSUPPORTED_SEARCH_MODELS =\n /^(?:gpt-3\\.5|gpt-4(?:-\\d|-turbo|-32k|$)|gpt-4\\.1-nano|o1-mini|o1-preview|o3-mini|text-embedding|whisper|tts|dall-e|gpt-image|omni-moderation)/u;\n\n/** The provider-defined entries on a call that belong to `provider`. */\nexport function providerToolsOf(\n options: ModelCallOptions | undefined,\n provider: string,\n): ProviderToolDefinition[] {\n return [...(options?.providerTools ?? []), ...(options?.tools ?? []).filter(isProviderTool)]\n .filter((entry) => entry.provider === provider)\n .map((entry) => entry as ProviderToolDefinition);\n}\n\n/** `true` when the call carries OpenAI's hosted web-search tool. */\nexport function requestsHostedSearch(\n options: ModelCallOptions | undefined,\n provider: string,\n): boolean {\n return providerToolsOf(options, provider).some(\n (entry) =>\n typeof entry.definition.type === \"string\" && HOSTED_SEARCH_TYPES.has(entry.definition.type),\n );\n}\n\n/**\n * Throw a capability error, before any request, when a model cannot run\n * OpenAI's hosted web search. Nothing falls back silently: the caller picks\n * another model or drops the tool.\n */\nexport function assertHostedSearchSupported(\n model: string,\n options: ModelCallOptions | undefined,\n): void {\n if (UNSUPPORTED_SEARCH_MODELS.test(model)) {\n throw new InvalidRequestError(\n `OpenAI's hosted web_search tool is not available on \"${model}\". Use a model that supports it (for example gpt-4.1, gpt-4.1-mini, gpt-4o, gpt-5), or remove the web_search tool.`,\n { context: { provider: \"openai\", model, tool: \"web_search\" } },\n );\n }\n\n if (/^gpt-5/u.test(model) && options?.reasoning?.effort === \"minimal\") {\n throw new InvalidRequestError(\n `OpenAI's hosted web_search tool is not available on \"${model}\" with minimal reasoning. Use a higher reasoning effort or remove the web_search tool.`,\n { context: { provider: \"openai\", model, tool: \"web_search\", effort: \"minimal\" } },\n );\n }\n}\n"],"mappings":";;;;AAQA,MAAM,sCAA2C,IAAI,IAAI;CACvD;CACA;CACA;CACA;AACF,CAAC;;;;;;;AAQD,MAAM,4BACJ;;AAGF,SAAgB,gBACd,SACA,UAC0B;CAC1B,OAAO,CAAC,GAAI,SAAS,iBAAiB,CAAC,GAAI,IAAI,SAAS,SAAS,CAAC,EAAC,CAAE,OAAO,cAAc,CAAC,CAAC,CACzF,QAAQ,UAAU,MAAM,aAAa,QAAQ,CAAC,CAC9C,KAAK,UAAU,KAA+B;AACnD;;AAGA,SAAgB,qBACd,SACA,UACS;CACT,OAAO,gBAAgB,SAAS,QAAQ,CAAC,CAAC,MACvC,UACC,OAAO,MAAM,WAAW,SAAS,YAAY,oBAAoB,IAAI,MAAM,WAAW,IAAI,CAC9F;AACF;;;;;;AAOA,SAAgB,4BACd,OACA,SACM;CACN,IAAI,0BAA0B,KAAK,KAAK,GACtC,MAAM,IAAI,oBACR,wDAAwD,MAAM,qHAC9D,EAAE,SAAS;EAAE,UAAU;EAAU;EAAO,MAAM;CAAa,EAAE,CAC/D;CAGF,IAAI,UAAU,KAAK,KAAK,KAAK,SAAS,WAAW,WAAW,WAC1D,MAAM,IAAI,oBACR,wDAAwD,MAAM,yFAC9D,EAAE,SAAS;EAAE,UAAU;EAAU;EAAO,MAAM;EAAc,QAAQ;CAAU,EAAE,CAClF;AAEJ"}
@@ -1,4 +1,4 @@
1
- import "@warlock.js/ai";
1
+ import { ModelCallOptions } from "@warlock.js/ai";
2
2
  //#region ../../packages/ai-openai/src/provider-options.d.ts
3
3
  /** Adapter-only fields merged after the neutral request parameters. */
4
4
  export type OpenAICallOptions = {
@@ -0,0 +1,155 @@
1
+ import { OpenAIModelConfig } from "./config.type.mjs";
2
+ import OpenAI from "openai";
3
+ import { Message, ModelCallOptions, ModelCapabilities, ModelContract, ModelPricing, ModelResponse, ModelStreamChunk } from "@warlock.js/ai";
4
+ //#region ../../packages/ai-openai/src/responses-model.d.ts
5
+ /**
6
+ * OpenAI Responses API implementation of `ModelContract` (`api: "responses"`).
7
+ *
8
+ * **Role.** A sibling of `OpenAIModel` that speaks `POST /v1/responses`
9
+ * instead of Chat Completions. Its point is letting a tool-using agent run a
10
+ * reasoning model with reasoning ON: the Chat path has to force
11
+ * `reasoning_effort: "none"` whenever tools are attached, Responses does not.
12
+ *
13
+ * **Why a separate class.** Only `OpenAISDK.model()` constructs it, and only
14
+ * for the direct `"openai"` provider. The wrapper packages (deepseek, groq,
15
+ * xai, mistral) build `OpenAIModel` and cannot reach this class, so an
16
+ * endpoint that does not implement `/v1/responses` is never sent there. The
17
+ * constructor re-checks the provider label as a second lock.
18
+ *
19
+ * **Stateless.** Every request sends `store: false`; nothing is kept on the
20
+ * server and no `previous_response_id` is used. Full history is re-sent each
21
+ * call, exactly like the Chat path.
22
+ *
23
+ * **Reasoning replay.** Every request asks for
24
+ * `include: ["reasoning.encrypted_content"]`. The `reasoning` items of a
25
+ * tool-calling turn are stored on the FIRST tool call as
26
+ * `providerMetadata.openaiResponses = { model, reasoningItems }` and sent back
27
+ * before that turn's `function_call` items on the next request (only when the
28
+ * stored model equals the current one). Text-only turns are not replayed.
29
+ *
30
+ * **Streaming.** `stream()` uses `responses.create({ stream: true })` and yields
31
+ * the same chunk sequence as the Chat path: text `delta`s, then the
32
+ * `tool-call`s, then one `done`. With `streamChunks` it also yields
33
+ * `reasoning` (reasoning summary / reasoning text deltas) and `tool-args`
34
+ * (`response.function_call_arguments.delta`).
35
+ *
36
+ * **Provider-defined tools.** `ai.providerTool({ provider: "openai" })`
37
+ * definitions are appended to `tools` verbatim. Hosted tools run inside the
38
+ * response; their output items (`web_search_call`, …) are retained in
39
+ * `providerMetadata.openai.output` for inspection and are not replayed
40
+ * (with `store: false` the next turn only needs the answer text), and a
41
+ * reasoning item that led into one is not replayed either (see
42
+ * `pickTurnReasoning`).
43
+ */
44
+ export declare class OpenAIResponsesModel implements ModelContract {
45
+ readonly name: string;
46
+ readonly provider: string;
47
+ readonly capabilities: ModelCapabilities;
48
+ readonly pricing?: ModelPricing;
49
+ private readonly client;
50
+ private readonly config;
51
+ private readonly logger;
52
+ /** `true` for an OpenAI-compatible vendor (xAI) that serves `/v1/responses` itself. */
53
+ private readonly compatible;
54
+ /**
55
+ * `options.compatible` lets a vendor package that implements `/v1/responses`
56
+ * (xAI) reuse this adapter under its own provider label. It is accepted
57
+ * only from those packages' own code: it drops the OpenAI-only request
58
+ * fields (`include` of encrypted reasoning and search sources), so no
59
+ * reasoning replay happens and no field unknown to the vendor is sent.
60
+ */
61
+ constructor(client: OpenAI, config: OpenAIModelConfig, provider?: string, options?: {
62
+ compatible?: boolean;
63
+ });
64
+ /**
65
+ * Single-shot completion against `client.responses.create`. Sends the full
66
+ * history as Responses `input` items, walks `response.output`, and reshapes
67
+ * it into a vendor-neutral `ModelResponse`. Per-call `options` override the
68
+ * instance defaults for this call only.
69
+ */
70
+ complete(messages: Message[], options?: ModelCallOptions): Promise<ModelResponse>;
71
+ /** Count native Responses input tokens using the same converted input and tools. */
72
+ countTokens(messages: Message[], options?: ModelCallOptions): Promise<number>;
73
+ /**
74
+ * Incremental streaming completion via `responses.create({ stream: true })`
75
+ * (the SDK's `Stream<ResponseStreamEvent>`, `responses.d.ts:55`). Yields the
76
+ * same neutral `ModelStreamChunk` sequence as the Chat path:
77
+ *
78
+ * - `response.output_text.delta` / `response.refusal.delta` -> `delta`.
79
+ * - `response.output_item.done` with a completed `function_call` item ->
80
+ * buffered; `reasoning` items are captured for replay. The `done` copy is
81
+ * used because the `added` copy may be incomplete (`responses.d.ts:5711`).
82
+ * - After the loop: the buffered `tool-call`s (the first carries the
83
+ * replay metadata), then a single `done` with the finish reason and usage
84
+ * from `response.completed` / `response.incomplete`.
85
+ * - `response.failed` and `error` events throw a typed `AIError`; a stream
86
+ * that ends with no terminal event throws `ProviderError`.
87
+ * - Abort goes through the request `signal`; the SDK rejects the read and
88
+ * the error is wrapped like any other.
89
+ */
90
+ stream(messages: Message[], options?: ModelCallOptions): AsyncIterable<ModelStreamChunk>;
91
+ /**
92
+ * Assemble the `responses.create` body.
93
+ *
94
+ * - System prompt -> `instructions`; history -> `input` items.
95
+ * - `store: false` always (the API default is `true` when omitted), plus
96
+ * `include: ["reasoning.encrypted_content"]` for stateless reasoning replay.
97
+ * - `max_output_tokens` caps reasoning and visible output together.
98
+ * - `temperature` only for non-reasoning models (same rule as Chat).
99
+ * - `tools` flat with `strict: false`; `tool_choice` only with tools.
100
+ * - `reasoning.effort` only when the caller gave one, through the same
101
+ * clamp table as Chat. With no explicit effort the provider default
102
+ * applies EVEN with tools attached - that is the point of this API.
103
+ */
104
+ private buildRequest;
105
+ /**
106
+ * The request `tools`: function tools (flat, `strict: false`), then the
107
+ * `ai.providerTool({ provider: "openai" })` definitions verbatim — the
108
+ * Responses built-in tools (`web_search`, `file_search`,
109
+ * `code_interpreter`, `image_generation`, `mcp`, …). Other providers'
110
+ * definitions are skipped with a warning. `undefined` when there are none.
111
+ */
112
+ private buildTools;
113
+ /**
114
+ * Structured output on Responses lives in `text.format`, and `name` /
115
+ * `schema` / `strict` sit directly on the format object (Chat nests them
116
+ * under `json_schema`). The strict-or-downgrade decision is the shared
117
+ * `planStructuredOutput`.
118
+ */
119
+ private buildTextFormat;
120
+ /** `reasoning.effort` for reasoning-capable models, only when the caller set one. */
121
+ private buildReasoningParams;
122
+ /**
123
+ * Walk `response.output`: `message` items contribute their `output_text`
124
+ * text and any `refusal` text (surfaced as ordinary content, decision 5);
125
+ * each completed `function_call` item becomes one tool call with
126
+ * `id = call_id`. `reasoning` items carry no visible content and are
127
+ * not content. A `function_call` the API marked `incomplete` (truncated
128
+ * arguments) is skipped rather than dispatched with empty input.
129
+ * `reasoning` items are captured and attached to the first tool call for
130
+ * replay (see `attachReasoningReplay`).
131
+ */
132
+ private readOutput;
133
+ /**
134
+ * Fail closed on a built-in tool call that YOUR code would have to run
135
+ * (`shell_call`, `apply_patch_call`, `computer_call`, …, from a
136
+ * provider-defined client tool). These items have their own output item
137
+ * types that this adapter does not map, so the turn would otherwise end
138
+ * silently with the call dropped. Hosted (server-run) tool items pass.
139
+ */
140
+ private assertServerRunItem;
141
+ /** One completed `function_call` item as a neutral tool call (`call_id` -> `id`). */
142
+ private toToolCall;
143
+ /**
144
+ * Normalize `usage` (absent on some partials) into the neutral `Usage`.
145
+ * `input_tokens_details.cached_tokens` -> `cachedTokens`,
146
+ * `cache_write_tokens` -> `cacheWriteTokens`,
147
+ * `output_tokens_details.reasoning_tokens` -> `reasoningTokens`. The
148
+ * detail blocks are typed non-optional but read defensively.
149
+ */
150
+ private extractUsage;
151
+ /** Wrap (idempotently), log and return a failure for the caller to throw. */
152
+ private logAndWrap;
153
+ }
154
+ //#endregion
155
+ //# sourceMappingURL=responses-model.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"responses-model.d.mts","names":[],"sources":["../../../../../../../packages/ai-openai/src/responses-model.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBA8Fa,gCAAgC;WAC3B;WACA;WACA,cAAc;WACd,UAAU;mBAET;mBACA;mBACA;;mBAGA;;;;;;;;EASjB,YACE,QAAQ,QACR,QAAQ,mBACR,mBACA;IAAW;;;;;;;;EAuCA,SAAS,UAAU,WAAW,UAAU,mBAAmB,QAAQ;;EAqDnE,YAAY,UAAU,WAAW,UAAU,mBAAmB;;;;;;;;;;;;;;;;;;EAyC7D,OACZ,UAAU,WACV,UAAU,mBACT,cAAc;;;;;;;;;;;;;;UA8JT;;;;;;;;UAsDA;;;;;;;UAqBA;;UAqBA;;;;;;;;;;;UAoBA;;;;;;;;UAuCA;;UAeA;;;;;;;;UAeA;;UAmBA"}
@@ -8,10 +8,10 @@ import { attachReasoningReplay, pickTurnReasoning } from "./utils/reasoning-repl
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 { hostedOutput } from "./utils/hosted-output.mjs";
11
12
  import { mergeProviderBody } from "./provider-options.mjs";
12
13
  import { inferReasoningCapability } from "./known-reasoning-models.mjs";
13
14
  import { inferVisionCapability } from "./known-vision-models.mjs";
14
- import { hostedOutput } from "./utils/hosted-output.mjs";
15
15
  import { InvalidRequestError, ProviderError, resolveStreamChunks, safeJsonParse, selectProviderTools } from "@warlock.js/ai";
16
16
  import { log } from "@warlock.js/logger";
17
17
 
@@ -70,9 +70,17 @@ const CLIENT_RUN_ITEM_TYPES = /* @__PURE__ */ new Set([
70
70
  * `pickTurnReasoning`).
71
71
  */
72
72
  var OpenAIResponsesModel = class {
73
- constructor(client, config, provider = "openai") {
73
+ /**
74
+ * `options.compatible` lets a vendor package that implements `/v1/responses`
75
+ * (xAI) reuse this adapter under its own provider label. It is accepted
76
+ * only from those packages' own code: it drops the OpenAI-only request
77
+ * fields (`include` of encrypted reasoning and search sources), so no
78
+ * reasoning replay happens and no field unknown to the vendor is sent.
79
+ */
80
+ constructor(client, config, provider = "openai", options = {}) {
74
81
  this.logger = log;
75
- if (provider !== "openai") throw new InvalidRequestError(`api: "responses" is supported only on the direct "openai" provider; got provider "${provider}".`, { context: {
82
+ this.compatible = options.compatible === true;
83
+ if (provider !== "openai" && !this.compatible) throw new InvalidRequestError(`api: "responses" is supported only on the direct "openai" provider; got provider "${provider}".`, { context: {
76
84
  provider,
77
85
  model: config.name,
78
86
  api: "responses"
@@ -119,7 +127,7 @@ var OpenAIResponsesModel = class {
119
127
  hasToolCalls: toolCalls !== void 0
120
128
  });
121
129
  const usage = this.extractUsage(response.usage);
122
- const providerMetadata = hostedOutput(usage, output, this.pricing);
130
+ const providerMetadata = hostedOutput(usage, output, this.pricing, this.compatible ? this.provider : "openai");
123
131
  this.logger.debug(LOG_MODULE, "response", "call to responses.create succeeded", {
124
132
  finishReason,
125
133
  usage
@@ -263,7 +271,7 @@ var OpenAIResponsesModel = class {
263
271
  });
264
272
  const usage = this.extractUsage(terminal.usage);
265
273
  const output = terminal.output?.length ? terminal.output : outputItems;
266
- const providerMetadata = hostedOutput(usage, output, this.pricing);
274
+ const providerMetadata = hostedOutput(usage, output, this.pricing, this.compatible ? this.provider : "openai");
267
275
  this.logger.debug(LOG_MODULE, "response", "Streaming call to responses.create succeeded", {
268
276
  finishReason,
269
277
  usage
@@ -294,12 +302,13 @@ var OpenAIResponsesModel = class {
294
302
  const toolChoice = tools ? toResponsesToolChoice(options?.toolChoice) : void 0;
295
303
  const maxTokens = options?.maxTokens ?? this.config.maxTokens;
296
304
  const temperature = options?.temperature ?? this.config.temperature;
305
+ const include = this.compatible ? [] : ["reasoning.encrypted_content", ...tools?.some((tool) => tool.type === "web_search" || tool.type === "web_search_2025_08_26" || tool.type === "web_search_preview" || tool.type === "web_search_preview_2025_03_11") ? ["web_search_call.action.sources"] : []];
297
306
  return mergeProviderBody({
298
307
  model: this.name,
299
308
  ...instructions !== void 0 ? { instructions } : {},
300
309
  input,
301
310
  store: false,
302
- include: ["reasoning.encrypted_content", ...tools?.some((tool) => tool.type === "web_search" || tool.type === "web_search_2025_08_26" || tool.type === "web_search_preview" || tool.type === "web_search_preview_2025_03_11") ? ["web_search_call.action.sources"] : []],
311
+ ...include.length > 0 ? { include } : {},
303
312
  ...maxTokens !== void 0 ? { max_output_tokens: maxTokens } : {},
304
313
  ...!this.capabilities.reasoning && temperature !== void 0 ? { temperature } : {},
305
314
  ...tools ? { tools } : {},