@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.
@@ -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 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 { hostedOutput } from \"./utils/hosted-output\";\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 retained in\n * `providerMetadata.openai.output` for inspection and 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 const providerMetadata = hostedOutput(usage, output, this.pricing);\n\n this.logger.debug(LOG_MODULE, \"response\", \"call to responses.create succeeded\", {\n finishReason,\n usage,\n });\n\n return {\n content,\n finishReason,\n usage,\n ...(providerMetadata ? { providerMetadata } : {}),\n ...(toolCalls ? { toolCalls } : {}),\n };\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 // Terminal output is authoritative; fall back to item.done events when absent.\n // Never add both snapshots, which would double-count hosted calls.\n const output = terminal.output?.length ? terminal.output : outputItems;\n const providerMetadata = hostedOutput(usage, output, this.pricing);\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, ...(providerMetadata ? { providerMetadata } : {}) };\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: [\n \"reasoning.encrypted_content\",\n ...(tools?.some(\n (tool) =>\n tool.type === \"web_search\" ||\n tool.type === \"web_search_2025_08_26\" ||\n tool.type === \"web_search_preview\" ||\n tool.type === \"web_search_preview_2025_03_11\",\n )\n ? [\"web_search_call.action.sources\" as const]\n : []),\n ],\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":";;;;;;;;;;;;;;;;;;AAuCA,MAAM,aAAa;;;;;;AAOnB,MAAM,wCAA6C,IAAI,IAAI;CACzD;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCD,IAAa,uBAAb,MAA2D;CAUzD,AAAO,YAAY,QAAgB,QAA2B,WAAmB,UAAU;gBAFz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ACF"}
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 { hostedOutput } from \"./utils/hosted-output\";\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 retained in\n * `providerMetadata.openai.output` for inspection and 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 /** `true` for an OpenAI-compatible vendor (xAI) that serves `/v1/responses` itself. */\n private readonly compatible: boolean;\n\n /**\n * `options.compatible` lets a vendor package that implements `/v1/responses`\n * (xAI) reuse this adapter under its own provider label. It is accepted\n * only from those packages' own code: it drops the OpenAI-only request\n * fields (`include` of encrypted reasoning and search sources), so no\n * reasoning replay happens and no field unknown to the vendor is sent.\n */\n public constructor(\n client: OpenAI,\n config: OpenAIModelConfig,\n provider: string = \"openai\",\n options: { compatible?: boolean } = {},\n ) {\n this.compatible = options.compatible === true;\n\n if (provider !== \"openai\" && !this.compatible) {\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 const providerMetadata = hostedOutput(\n usage,\n output,\n this.pricing,\n this.compatible ? this.provider : \"openai\",\n );\n\n this.logger.debug(LOG_MODULE, \"response\", \"call to responses.create succeeded\", {\n finishReason,\n usage,\n });\n\n return {\n content,\n finishReason,\n usage,\n ...(providerMetadata ? { providerMetadata } : {}),\n ...(toolCalls ? { toolCalls } : {}),\n };\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 // Terminal output is authoritative; fall back to item.done events when absent.\n // Never add both snapshots, which would double-count hosted calls.\n const output = terminal.output?.length ? terminal.output : outputItems;\n const providerMetadata = hostedOutput(\n usage,\n output,\n this.pricing,\n this.compatible ? this.provider : \"openai\",\n );\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, ...(providerMetadata ? { providerMetadata } : {}) };\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 // Stateless replay: ask for the encrypted reasoning blobs so they can be\n // sent back on the next tool turn (decision 3). OpenAI-only fields.\n const include: Array<\"reasoning.encrypted_content\" | \"web_search_call.action.sources\"> = this\n .compatible\n ? []\n : [\n \"reasoning.encrypted_content\",\n ...(tools?.some(\n (tool) =>\n tool.type === \"web_search\" ||\n tool.type === \"web_search_2025_08_26\" ||\n tool.type === \"web_search_preview\" ||\n tool.type === \"web_search_preview_2025_03_11\",\n )\n ? [\"web_search_call.action.sources\" as const]\n : []),\n ];\n\n return mergeProviderBody<OpenAI.Responses.ResponseCreateParamsNonStreaming>(\n {\n model: this.name,\n ...(instructions !== undefined ? { instructions } : {}),\n input,\n store: false,\n ...(include.length > 0 ? { include } : {}),\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":";;;;;;;;;;;;;;;;;;AAuCA,MAAM,aAAa;;;;;;AAOnB,MAAM,wCAA6C,IAAI,IAAI;CACzD;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCD,IAAa,uBAAb,MAA2D;;;;;;;;CAoBzD,AAAO,YACL,QACA,QACA,WAAmB,UACnB,UAAoC,CAAC,GACrC;gBAjBgC;EAkBhC,KAAK,aAAa,QAAQ,eAAe;EAEzC,IAAI,aAAa,YAAY,CAAC,KAAK,YACjC,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;EACtB,KAAK,eAAe;GAClB,kBAAkB,OAAO,oBAAoB,sBAAsB,OAAO,cAAc;GACxF,QAAQ,OAAO,UAAU,sBAAsB,OAAO,IAAI;GAC1D,WAAW,OAAO,aAAa,yBAAyB,OAAO,IAAI;GAKnE,eAAe;GAIf,KAAK;GACL,OAAO;EACT;CACF;;;;;;;CAQA,MAAa,SAAS,UAAqB,SAAoD;EAC7F,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,UAAU,OACrC,KAAK,aAAa,UAAU,OAAO,GACnC,SAAS,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,MACjD;EACF,SAAS,QAAQ;GACf,MAAM,KAAK,WAAW,MAAM;EAC9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AAO;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
@@ -1,5 +1,5 @@
1
1
  import { OpenAIEmbedderConfig, OpenAIImageConfig, OpenAIModelConfig, OpenAISDKConfig, OpenAISpeechConfig, OpenAITranscriptionConfig } from "./config.type.mjs";
2
- import { EmbedderContract, ImageModelContract, ModelContract, SDKAdapterContract, SpeechModelContract, TranscriptionModelContract } from "@warlock.js/ai";
2
+ import { EmbedderContract, ImageModelContract, ListModelsOptions, ModelContract, ModelInfo, SDKAdapterContract, SpeechModelContract, TranscriptionModelContract } from "@warlock.js/ai";
3
3
  //#region ../../packages/ai-openai/src/sdk.d.ts
4
4
  /**
5
5
  * OpenAI-backed implementation of `SDKAdapterContract`.
@@ -61,6 +61,16 @@ export declare class OpenAISDK implements SDKAdapterContract {
61
61
  * `/v1/responses` is never sent there.
62
62
  */
63
63
  model(config: OpenAIModelConfig): ModelContract;
64
+ /**
65
+ * Build the Responses-API model for an OpenAI-compatible vendor that serves
66
+ * `POST /v1/responses` itself (xAI). For vendor wrapper packages: the direct
67
+ * OpenAI provider reaches the same adapter through `model({ api:
68
+ * "responses" })`, and every other label is refused there on purpose. The
69
+ * returned model keeps this SDK's provider label, sends `store: false`, and
70
+ * leaves out the OpenAI-only `include` fields (encrypted reasoning, search
71
+ * sources), so nothing the vendor does not know is sent.
72
+ */
73
+ compatibleResponses(config: OpenAIModelConfig): ModelContract;
64
74
  /**
65
75
  * Rough token-count estimate for a given text. Uses a
66
76
  * character-heuristic (`approximateTokenCount`) from the core package
@@ -69,6 +79,23 @@ export declare class OpenAISDK implements SDKAdapterContract {
69
79
  * dispatch; currently ignored.
70
80
  */
71
81
  count(text: string, _model?: string): Promise<number>;
82
+ /**
83
+ * List the models this account can use, live from `GET /models`, mapped to
84
+ * {@link ModelInfo}. Works for OpenAI and for every OpenAI-compatible vendor
85
+ * that implements the listing (the wrapper packages for xAI, Groq,
86
+ * DeepSeek and Mistral call this). Follows pagination to the end; a
87
+ * vendor-marked inactive model is left out. Failures are thrown as the
88
+ * adapter's usual provider errors, never an empty list.
89
+ *
90
+ * `kind` comes from the vendor's own flags when it has them (Mistral
91
+ * `capabilities`) and from the model id otherwise, so treat it as a filter
92
+ * hint for ids OpenAI does not describe.
93
+ *
94
+ * @example
95
+ * const models = await openai.models();
96
+ * const chat = models.filter((model) => model.kind === "chat");
97
+ */
98
+ models(options?: ListModelsOptions): Promise<ModelInfo[]>;
72
99
  /**
73
100
  * Build an `OpenAIEmbedder` bound to this SDK's client. Each call
74
101
  * returns a fresh embedder instance sharing the same underlying
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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBA6Da,qBAAqB;mBACf;mBACA;mBACA;EAEjB,YAAmB,QAAQ;;;;;;;;;;;;;;;;;;;;;EAgCpB,MAAM,QAAQ,oBAAoB;;;;;;;;EAsC5B,MAAM,cAAc,kBAAkB;;;;;;;;;;;EAc5C,SAAS,QAAQ,uBAAuB;;;;;;;;;;;;;;;;;;EAqBxC,MAAM,QAAQ,oBAAoB;;;;;;;;;;;;EAmBlC,OAAO,QAAQ,qBAAqB;;;;;;;;;;;;EAepC,WAAW,QAAQ,4BAA4B"}
1
+ {"version":3,"file":"sdk.d.mts","names":[],"sources":["../../../../../../../packages/ai-openai/src/sdk.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAiEa,qBAAqB;mBACf;mBACA;mBACA;EAEjB,YAAmB,QAAQ;;;;;;;;;;;;;;;;;;;;;EAgCpB,MAAM,QAAQ,oBAAoB;;;;;;;;;;EAwClC,oBAAoB,QAAQ,oBAAoB;;;;;;;;EAiB1C,MAAM,cAAc,kBAAkB;;;;;;;;;;;;;;;;;EAoBtC,OAAO,UAAU,oBAAoB,QAAQ;;;;;;;;;;;EA8BnD,SAAS,QAAQ,uBAAuB;;;;;;;;;;;;;;;;;;EAqBxC,MAAM,QAAQ,oBAAoB;;;;;;;;;;;;EAmBlC,OAAO,QAAQ,qBAAqB;;;;;;;;;;;;EAepC,WAAW,QAAQ,4BAA4B"}
package/esm/sdk.mjs CHANGED
@@ -1,8 +1,11 @@
1
1
  import { openAIPricingFor } from "./known-pricing.mjs";
2
+ import { toModelInfo } from "./list-models.mjs";
3
+ import { wrapOpenAIError } from "./utils/wrap-openai-error.mjs";
4
+ import "./utils/index.mjs";
2
5
  import { OpenAIEmbedder } from "./embedder.mjs";
3
6
  import { OpenAIImageModel } from "./image.mjs";
4
- import { OpenAIModel } from "./model.mjs";
5
7
  import { OpenAIResponsesModel } from "./responses-model.mjs";
8
+ import { OpenAIModel } from "./model.mjs";
6
9
  import { OpenAISpeechModel } from "./speech.mjs";
7
10
  import { OpenAITranscriptionModel } from "./transcription.mjs";
8
11
  import OpenAI from "openai";
@@ -91,6 +94,23 @@ var OpenAISDK = class {
91
94
  return new OpenAIModel(this.client, resolvedConfig, this.provider);
92
95
  }
93
96
  /**
97
+ * Build the Responses-API model for an OpenAI-compatible vendor that serves
98
+ * `POST /v1/responses` itself (xAI). For vendor wrapper packages: the direct
99
+ * OpenAI provider reaches the same adapter through `model({ api:
100
+ * "responses" })`, and every other label is refused there on purpose. The
101
+ * returned model keeps this SDK's provider label, sends `store: false`, and
102
+ * leaves out the OpenAI-only `include` fields (encrypted reasoning, search
103
+ * sources), so nothing the vendor does not know is sent.
104
+ */
105
+ compatibleResponses(config) {
106
+ const resolvedPricing = config.pricing ?? this.pricing?.[config.name];
107
+ const resolvedConfig = resolvedPricing === config.pricing ? config : {
108
+ ...config,
109
+ pricing: resolvedPricing
110
+ };
111
+ return new OpenAIResponsesModel(this.client, resolvedConfig, this.provider, { compatible: true });
112
+ }
113
+ /**
94
114
  * Rough token-count estimate for a given text. Uses a
95
115
  * character-heuristic (`approximateTokenCount`) from the core package
96
116
  * — good enough for budgeting and quota guards, not for billing.
@@ -101,6 +121,34 @@ var OpenAISDK = class {
101
121
  return approximateTokenCount(text);
102
122
  }
103
123
  /**
124
+ * List the models this account can use, live from `GET /models`, mapped to
125
+ * {@link ModelInfo}. Works for OpenAI and for every OpenAI-compatible vendor
126
+ * that implements the listing (the wrapper packages for xAI, Groq,
127
+ * DeepSeek and Mistral call this). Follows pagination to the end; a
128
+ * vendor-marked inactive model is left out. Failures are thrown as the
129
+ * adapter's usual provider errors, never an empty list.
130
+ *
131
+ * `kind` comes from the vendor's own flags when it has them (Mistral
132
+ * `capabilities`) and from the model id otherwise, so treat it as a filter
133
+ * hint for ids OpenAI does not describe.
134
+ *
135
+ * @example
136
+ * const models = await openai.models();
137
+ * const chat = models.filter((model) => model.kind === "chat");
138
+ */
139
+ async models(options) {
140
+ const found = /* @__PURE__ */ new Map();
141
+ try {
142
+ for await (const entry of this.client.models.list(options?.signal ? { signal: options.signal } : void 0)) {
143
+ const info = toModelInfo(entry, this.provider);
144
+ if (info) found.set(info.id, info);
145
+ }
146
+ } catch (thrown) {
147
+ throw wrapOpenAIError(thrown);
148
+ }
149
+ return [...found.values()];
150
+ }
151
+ /**
104
152
  * Build an `OpenAIEmbedder` bound to this SDK's client. Each call
105
153
  * returns a fresh embedder instance sharing the same underlying
106
154
  * `OpenAI` client — connection pools and authentication stay unified
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 { 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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D,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 ListModelsOptions,\n ModelInfo,\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 { toModelInfo } from \"./list-models\";\nimport { wrapOpenAIError } from \"./utils\";\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 * Build the Responses-API model for an OpenAI-compatible vendor that serves\n * `POST /v1/responses` itself (xAI). For vendor wrapper packages: the direct\n * OpenAI provider reaches the same adapter through `model({ api:\n * \"responses\" })`, and every other label is refused there on purpose. The\n * returned model keeps this SDK's provider label, sends `store: false`, and\n * leaves out the OpenAI-only `include` fields (encrypted reasoning, search\n * sources), so nothing the vendor does not know is sent.\n */\n public compatibleResponses(config: OpenAIModelConfig): ModelContract {\n const resolvedPricing = config.pricing ?? this.pricing?.[config.name];\n const resolvedConfig: OpenAIModelConfig =\n resolvedPricing === config.pricing ? config : { ...config, pricing: resolvedPricing };\n\n return new OpenAIResponsesModel(this.client, resolvedConfig, this.provider, {\n compatible: true,\n });\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 * List the models this account can use, live from `GET /models`, mapped to\n * {@link ModelInfo}. Works for OpenAI and for every OpenAI-compatible vendor\n * that implements the listing (the wrapper packages for xAI, Groq,\n * DeepSeek and Mistral call this). Follows pagination to the end; a\n * vendor-marked inactive model is left out. Failures are thrown as the\n * adapter's usual provider errors, never an empty list.\n *\n * `kind` comes from the vendor's own flags when it has them (Mistral\n * `capabilities`) and from the model id otherwise, so treat it as a filter\n * hint for ids OpenAI does not describe.\n *\n * @example\n * const models = await openai.models();\n * const chat = models.filter((model) => model.kind === \"chat\");\n */\n public async models(options?: ListModelsOptions): Promise<ModelInfo[]> {\n const found = new Map<string, ModelInfo>();\n\n try {\n for await (const entry of this.client.models.list(\n options?.signal ? { signal: options.signal } : undefined,\n )) {\n const info = toModelInfo(entry, this.provider);\n\n if (info) {\n found.set(info.id, info);\n }\n }\n } catch (thrown) {\n throw wrapOpenAIError(thrown);\n }\n\n return [...found.values()];\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA,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,MA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O,KAAK,QAAQ;IAE7C,IAAI,MACF,MAAM,IAAI,KAAK,IAAI,IAAI;GAE3B;EACF,SAAS,QAAQ;GACf,MAAM,gBAAgB,MAAM;EAC9B;EAEA,OAAO,CAAC,GAAG,MAAM,OAAO,CAAC;CAC3B;;;;;;;;;;;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"}
@@ -6,7 +6,7 @@ import { attachCost } from "@warlock.js/ai";
6
6
  * Count output items, never URLs, sources, answer text, or function calls.
7
7
  * Fees and search content tokens are separate; preview pricing varies:
8
8
  * https://developers.openai.com/api/docs/pricing#built-in-tools */
9
- function hostedOutput(usage, output, pricing) {
9
+ function hostedOutput(usage, output, pricing, key = "openai") {
10
10
  const hosted = output.filter((item) => item.type !== "message" && item.type !== "reasoning" && item.type !== "function_call");
11
11
  const searches = hosted.filter((item) => item.type === "web_search_call");
12
12
  if (searches.length) usage.serverToolUse = {
@@ -14,7 +14,7 @@ function hostedOutput(usage, output, pricing) {
14
14
  webSearchRequests: searches.length
15
15
  };
16
16
  attachCost(usage, pricing);
17
- return hosted.length ? { openai: { output: hosted } } : void 0;
17
+ return hosted.length ? { [key]: { output: hosted } } : void 0;
18
18
  }
19
19
 
20
20
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"hosted-output.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/hosted-output.ts"],"sourcesContent":["import { attachCost, type ModelPricing, type Usage } from \"@warlock.js/ai\";\nimport type OpenAI from \"openai\";\n\n/** Installed openai 7.23.0 ResponseFunctionWebSearch (action includes search/open_page/find).\n * https://developers.openai.com/api/docs/guides/tools-web-search\n * Count output items, never URLs, sources, answer text, or function calls.\n * Fees and search content tokens are separate; preview pricing varies:\n * https://developers.openai.com/api/docs/pricing#built-in-tools */\nexport function hostedOutput(\n usage: Usage,\n output: OpenAI.Responses.ResponseOutputItem[],\n pricing: ModelPricing | undefined,\n): Record<string, unknown> | undefined {\n const hosted = output.filter(\n (item) => item.type !== \"message\" && item.type !== \"reasoning\" && item.type !== \"function_call\",\n );\n const searches = hosted.filter((item) => item.type === \"web_search_call\");\n if (searches.length)\n usage.serverToolUse = { ...usage.serverToolUse, webSearchRequests: searches.length };\n attachCost(usage, pricing);\n return hosted.length ? { openai: { output: hosted } } : undefined;\n}\n"],"mappings":";;;;;;;;AAQA,SAAgB,aACd,OACA,QACA,SACqC;CACrC,MAAM,SAAS,OAAO,QACnB,SAAS,KAAK,SAAS,aAAa,KAAK,SAAS,eAAe,KAAK,SAAS,eAClF;CACA,MAAM,WAAW,OAAO,QAAQ,SAAS,KAAK,SAAS,iBAAiB;CACxE,IAAI,SAAS,QACX,MAAM,gBAAgB;EAAE,GAAG,MAAM;EAAe,mBAAmB,SAAS;CAAO;CACrF,WAAW,OAAO,OAAO;CACzB,OAAO,OAAO,SAAS,EAAE,QAAQ,EAAE,QAAQ,OAAO,EAAE,IAAI;AAC1D"}
1
+ {"version":3,"file":"hosted-output.mjs","names":[],"sources":["../../../../../../../../packages/ai-openai/src/utils/hosted-output.ts"],"sourcesContent":["import { attachCost, type ModelPricing, type Usage } from \"@warlock.js/ai\";\nimport type OpenAI from \"openai\";\n\n/** Installed openai 7.23.0 ResponseFunctionWebSearch (action includes search/open_page/find).\n * https://developers.openai.com/api/docs/guides/tools-web-search\n * Count output items, never URLs, sources, answer text, or function calls.\n * Fees and search content tokens are separate; preview pricing varies:\n * https://developers.openai.com/api/docs/pricing#built-in-tools */\nexport function hostedOutput(\n usage: Usage,\n output: OpenAI.Responses.ResponseOutputItem[],\n pricing: ModelPricing | undefined,\n key: string = \"openai\",\n): Record<string, unknown> | undefined {\n const hosted = output.filter(\n (item) => item.type !== \"message\" && item.type !== \"reasoning\" && item.type !== \"function_call\",\n );\n const searches = hosted.filter((item) => item.type === \"web_search_call\");\n if (searches.length)\n usage.serverToolUse = { ...usage.serverToolUse, webSearchRequests: searches.length };\n attachCost(usage, pricing);\n return hosted.length ? { [key]: { output: hosted } } : undefined;\n}\n"],"mappings":";;;;;;;;AAQA,SAAgB,aACd,OACA,QACA,SACA,MAAc,UACuB;CACrC,MAAM,SAAS,OAAO,QACnB,SAAS,KAAK,SAAS,aAAa,KAAK,SAAS,eAAe,KAAK,SAAS,eAClF;CACA,MAAM,WAAW,OAAO,QAAQ,SAAS,KAAK,SAAS,iBAAiB;CACxE,IAAI,SAAS,QACX,MAAM,gBAAgB;EAAE,GAAG,MAAM;EAAe,mBAAmB,SAAS;CAAO;CACrF,WAAW,OAAO,OAAO;CACzB,OAAO,OAAO,SAAS,GAAG,MAAM,EAAE,QAAQ,OAAO,EAAE,IAAI;AACzD"}
package/llms-full.txt CHANGED
@@ -453,4 +453,12 @@ Abort signals cancel transport; retries are disabled. `invoke().error` is a
453
453
  `AgentCancelledError` for caller cancellation). `execute()` returns data only
454
454
  and throws mapped errors. Never infer fees from function calls or prose.
455
455
 
456
+ ## Native web search picks the API
457
+
458
+ On the direct `"openai"` provider a call carrying the hosted `web_search` tool is served by the Responses API automatically (same model, client and pricing); other calls stay on Chat Completions. It throws `InvalidRequestError` before any request on models OpenAI documents as unable to search (`gpt-3.5*`, `gpt-4`, `gpt-4-turbo`, `gpt-4.1-nano`, `o1-mini`, `o1-preview`, `o3-mini`, non-chat ids), on `gpt-5*` with `reasoning.effort: "minimal"`, and on a model pinned to `api: "chat"`. Never a silent fallback.
459
+
460
+ ## List models
461
+
462
+ `await openai.models()` returns `ModelInfo[]` from `GET /models` (also on compatible gateways, with the SDK's provider label); `kind` is classified from the id.
463
+
456
464
 
package/package.json CHANGED
@@ -15,12 +15,12 @@
15
15
  },
16
16
  "dependencies": {
17
17
  "openai": "^7.23.0",
18
- "@warlock.js/logger": "5.39.1"
18
+ "@warlock.js/logger": "5.40.0"
19
19
  },
20
20
  "peerDependencies": {
21
- "@warlock.js/ai": "5.39.1"
21
+ "@warlock.js/ai": "5.40.0"
22
22
  },
23
- "version": "5.39.1",
23
+ "version": "5.40.0",
24
24
  "main": "./cjs/index.cjs",
25
25
  "module": "./esm/index.mjs",
26
26
  "types": "./esm/index.d.mts",
package/skills/SKILL.md CHANGED
@@ -444,3 +444,11 @@ Abort signals cancel transport; retries are disabled. `invoke().error` is a
444
444
  `ToolExecutionError` whose `cause` is the mapped provider error (or
445
445
  `AgentCancelledError` for caller cancellation). `execute()` returns data only
446
446
  and throws mapped errors. Never infer fees from function calls or prose.
447
+
448
+ ## Native web search picks the API
449
+
450
+ On the direct `"openai"` provider a call carrying the hosted `web_search` tool is served by the Responses API automatically (same model, client and pricing); other calls stay on Chat Completions. It throws `InvalidRequestError` before any request on models OpenAI documents as unable to search (`gpt-3.5*`, `gpt-4`, `gpt-4-turbo`, `gpt-4.1-nano`, `o1-mini`, `o1-preview`, `o3-mini`, non-chat ids), on `gpt-5*` with `reasoning.effort: "minimal"`, and on a model pinned to `api: "chat"`. Never a silent fallback.
451
+
452
+ ## List models
453
+
454
+ `await openai.models()` returns `ModelInfo[]` from `GET /models` (also on compatible gateways, with the SDK's provider label); `kind` is classified from the id.