0214. OpenAI-compatible chat adapter
Context
- The only adapter in the repository is Anthropic's
(
plugins/agent/anthropic.hn), andplugins/agent/transport.hnhard-codes the Anthropic endpoint URL and headers. - M14 needs OpenAI, OpenRouter, and DeepSeek-compatible Chat Completions endpoints.
- ADR-0167 forbids extracting shared curl helpers into
http.clientuntil its scheduled refactor. - ADR-0212 fixes the shape of
ModelReply.callsandTokenUsageacross the runner.
Decision
- Ship a separate library package,
plugins/openai_chat, that depends onagent_platformand declares no capabilities (capabilities = []). - Reuse
sse,stream.ToolArguments,jsonscan,CurlProcess, andReplayTransportfromagent_platform. - Keep JSON field/string/array readers (
wire_*) and curl config quoting as local copies insideopenai_chat, with consolidation parked until ADR-0167. - Decode streaming Chat Completions (
chat_stream,chat_on_sse,chat_finish) with a fail-closed finish-reason table:stopwithout tool calls completes (Completed("stop")), orRefusedwhendelta.refusalwas non-empty;stopwith pending tool calls fails (tool calls without tool_calls finish).tool_callswith non-empty pending calls releases validatedToolCalls and completes (Completed("tool_calls"));tool_callswithout calls fails (tool_calls finish without calls).lengthmaps toTruncatedwith no calls;content_filtermaps toRefused;erroror a top-level{"error":...}chunk maps toFailed(Provider(..)); unknown finish reasons and[DONE]without a finish reason fail closed; EOF before[DONE]maps toDisconnected(orTruncatedwhen tool fragments are open with no finish reason).
- Tool-call fragment rules: release calls only at the
finish_reason == "tool_calls"chunk; require contiguous 0-basedindexvalues (0..pending.len()); require non-emptyidandfunction.nameon first sight and forbid changing them on later fragments; require each assembled argument string to be a valid JSON object ({...}). - Usage mapping: map OpenAI (
prompt_tokens,prompt_tokens_details.cached_tokens) and DeepSeek (prompt_cache_hit_tokens,prompt_cache_miss_tokens) to uncachedinput_tokensandcache_read_input_tokens; mapcompletion_tokenstooutput_tokensandcompletion_tokens_details.reasoning_tokenstoreasoning_tokens. Keepcache_creation_input_tokensalwaysnone. Returnusage.cost(validated non-negative JSON number token or numeric string) asoption<str>onChatDecodedoutsideTokenUsage. - Reasoning fields (
delta.reasoning,delta.reasoning_content,delta.reasoning_details) are validated for JSON type, their UTF-8 string byte length is counted (chat_reasoning_bytes), and their text is never emitted asDelta.Text, retained, or encoded back into follow-up requests. - Encode Chat Completions requests (
encode_chat) with deterministic key order (model,messages, optionaltools/tool_choice/parallel_tool_calls,stream,stream_options, optionalmax_tokens,seed, and OpenRouterproviderpin object{"order":[...],"allow_fallbacks":...}). ChatCurltakes a fullhttps://endpoint URL andSecretRefkey, passesAuthorization: Bearer <key>via curl--config -on stdin, and screens responses and decoded fields/arguments for the key using the same KMP and JSON-escape checks as Anthropic.
Amends 0108: OpenAI tool-call argument
fragments are buffered in ToolArguments and released
only at the finish_reason chunk. Amends
0112: plugins/openai_chat is a second
fixture-tested provider adapter, with its golden suites under
plugins/openai_chat/tests/. Amends
0212: defines the OpenAI/OpenRouter/DeepSeek usage
category mapping and carries provider cost as
option<str> outside
TokenUsage.
Alternatives considered
- Generalise
plugins/agent/transport.hnwith a URL and header list — rejected because it modifies a security-sensitive file that ADR-0167 schedules separately. - Make
anth_*JSON helperspubinagent_platform— freezes an internal scanner API that is parked for replacement. - Reuse Anthropic
Storeblobs for request encoding — wrong schema for Chat Completions messages and tool calls. - Add
costtoTokenUsageorModelReply— breaks the runner and app ABI on top of ADR-0212's density constraints. - Report
cache_creation_input_tokens = some(0)— OpenRouter routes to Anthropic upstreams where cache writes are billed separately, so reporting0could falsify accounting. - Release tool calls at
[DONE]instead of the finish chunk — equivalent on well-formed streams, butfinish_reason: "tool_calls"is the protocol's own release point. - Treat a missing
[DONE]afterfinish_reasonas completion — unsafe because trailing usage/error chunks may have been truncated on the wire.
Consequences
- OpenAI-compatible replies have
cache_creation_input_tokens == none, sotoken_budget_usagetreats input tokens as budget-unknown and falls back to ADR-0110 call counting until a provider documents a cache-write field or an endpoint policy opts intosome(0). costis visible to callers ofdecode_chat,chat_cost, andchat_curl_decoded; runner and journal cost plumbing is a later task.- Live network behavior remains UNVERIFIED until M14.5.
- Two copies of curl config quoting exist until ADR-0167 consolidates them.