import type * as plugins from './plugins.js'; const isNonEmptyString = (value: unknown): value is string => typeof value === 'string' && value.trim().length > 0; type TPrompt = plugins.LanguageModelV4CallOptions['prompt']; /** The number of system messages the prompt opens with, before its first other message. */ const countLeadingInstructions = (prompt: readonly { role?: unknown }[], serialized = false): number => { const firstOther = prompt.findIndex((message) => message.role !== 'system' && !(serialized && message.role === 'developer')); return firstOther === -1 ? prompt.length : firstOther; }; const joinSystemInstructions = (messages: TPrompt): string | undefined => { const instructions = messages .map((message) => message.content) .filter(isNonEmptyString); return instructions.length > 0 ? instructions.join('\n') : undefined; }; const hasUnsupportedChatGptCacheRetention = (options: plugins.JSONObject): boolean => { return options.promptCacheRetention !== undefined || options.prompt_cache_retention !== undefined; }; /** * ChatGPT's Codex backend requires top-level Responses API instructions. * * The system messages a prompt opens with become those instructions. A system message later in the * conversation keeps its place and is sent as a `developer` input item, the role the Codex backend reads * mid-conversation instructions in, so moving it would neither reorder the conversation nor change the * instructions prefix a prompt cache keys on. A caller's own `instructions` or `systemMessageMode` is kept. * * The backend never stores a response, so every call is sent with `store: false`. A stored call would * send earlier assistant items as references to stored items, and none of them exists. */ export function createOpenAiChatGptInstructionsMiddleware(): plugins.LanguageModelV4Middleware { return { specificationVersion: 'v4', transformParams: async ({ params }) => { const providerOptions = params.providerOptions ?? {}; const openAiProviderOptions = providerOptions.openai ?? {}; const leadingCount = countLeadingInstructions(params.prompt); const shouldHoist = leadingCount > 0 && !isNonEmptyString(openAiProviderOptions.instructions); const instructions = shouldHoist ? joinSystemInstructions(params.prompt.slice(0, leadingCount)) : undefined; const prompt = shouldHoist ? params.prompt.slice(leadingCount) : params.prompt; const keepsSystemMessages = prompt.some((message) => message.role === 'system'); const shouldSetDeveloperMode = keepsSystemMessages && openAiProviderOptions.systemMessageMode === undefined; const shouldStripCacheRetention = hasUnsupportedChatGptCacheRetention(openAiProviderOptions); const shouldDisableStore = openAiProviderOptions.store !== false; if (!shouldHoist && !shouldSetDeveloperMode && !shouldStripCacheRetention && !shouldDisableStore) { return params; } const nextOpenAiProviderOptions: plugins.JSONObject = { ...openAiProviderOptions, store: false }; delete nextOpenAiProviderOptions.promptCacheRetention; delete nextOpenAiProviderOptions.prompt_cache_retention; if (instructions) { nextOpenAiProviderOptions.instructions = instructions; } if (shouldSetDeveloperMode) { nextOpenAiProviderOptions.systemMessageMode = 'developer'; } return { ...params, prompt, providerOptions: { ...providerOptions, openai: nextOpenAiProviderOptions, }, } satisfies plugins.LanguageModelV4CallOptions; }, }; } const isRecord = (value: unknown): value is Record => value !== null && typeof value === 'object' && !Array.isArray(value); /** A serialized Responses message: an explicit `message` item or an untyped role/content item. */ const isMessageItem = (item: unknown): boolean => isRecord(item) && (item.type === undefined || item.type === 'message'); /** * Apply the ChatGPT instruction dialect to an already serialized Responses request (for HTTP gateways). * Leading system/developer messages become the dynamic instructions prefix unless one was supplied. * A prefix item that is not a message (Codex opens with an `additional_tools` item) is no instruction: it * stays at the head of the input in its order. Later instructions keep their order as developer messages. * The Codex backend takes no output limit, so `max_output_tokens` is removed, as Codex never sends one and * OpenCode's ChatGPT plugin removes it. Other request fields are preserved. * This does not authenticate, choose a model, change storage/streaming policy, or mutate the input. */ export function normalizeOpenAiChatGptResponsesRequest(body: Readonly>): Record { if (body.instructions !== undefined && body.instructions !== null && typeof body.instructions !== 'string') { throw new Error('Responses instructions must be a string or null.'); } const result = { ...body }; delete result.prompt_cache_retention; delete result.max_output_tokens; if (!Array.isArray(body.input)) return result; const input: unknown[] = body.input; const prefix = countLeadingInstructions(input.map((item) => isRecord(item) ? item : {}), true); const shouldHoist = prefix > 0 && body.instructions === undefined; if (shouldHoist) { const instructions = input.slice(0, prefix).filter(isMessageItem).map((item) => { const content = (item as Record).content; if (typeof content === 'string') return content; if (!Array.isArray(content) || !content.every((part) => isRecord(part) && part.type === 'input_text' && typeof part.text === 'string')) { throw new Error('ChatGPT instruction messages must contain text only.'); } return content.map((part) => part.text).join(''); }).filter(isNonEmptyString).join('\n'); // An empty prefix is an explicit empty instruction, not an invented prompt. result.instructions = instructions; } const kept = shouldHoist ? [...input.slice(0, prefix).filter((item) => !isMessageItem(item)), ...input.slice(prefix)] : input; result.input = kept.map((item) => isRecord(item) && item.role === 'system' ? { ...item, role: 'developer' } : item); return result; }