diff --git a/containers/api-proxy/Dockerfile b/containers/api-proxy/Dockerfile index d1d55dd62..7b11fef06 100644 --- a/containers/api-proxy/Dockerfile +++ b/containers/api-proxy/Dockerfile @@ -86,6 +86,7 @@ COPY guards/ ./guards/ COPY providers/ ./providers/ COPY transforms/ ./transforms/ COPY catalogue-contract/ ./catalogue-contract/ +COPY protocol-compatibility/ ./protocol-compatibility/ # Create non-root user RUN addgroup -S apiproxy && adduser -S apiproxy -G apiproxy diff --git a/containers/api-proxy/fixtures/protocol-compatibility/contract-types.ts b/containers/api-proxy/fixtures/protocol-compatibility/contract-types.ts new file mode 100644 index 000000000..8f758c242 --- /dev/null +++ b/containers/api-proxy/fixtures/protocol-compatibility/contract-types.ts @@ -0,0 +1,22 @@ +import { + assessFeature, CONTRACTS, DirectedContract, FeatureAssessment, +} from '../../protocol-compatibility'; + +const contract: DirectedContract = CONTRACTS[0]; +const assessment: FeatureAssessment = assessFeature({ + source: 'anthropic_messages', target: 'chat_completions', + direction: 'request', feature: 'future_feature', +}); +const status: 'supported' | 'conditional' | 'rejected' | 'unknown' = assessment.status; +void status; + +// @ts-expect-error Evidence is immutable. +contract.features.push(contract.features[0]); +// @ts-expect-error Conditions are immutable. +contract.features[0].conditions.push('anything'); +// @ts-expect-error Implementation revision is immutable. +contract.implementation.sha256 = 'anything'; +// @ts-expect-error Assessment is not a whole-request success verdict. +void (assessment.compatible); +// @ts-expect-error Request versus return response is explicit. +assessFeature({ source: 'responses', target: 'chat_completions', direction: 'reverse', feature: 'message_text' }); diff --git a/containers/api-proxy/fixtures/protocol-compatibility/gaps.js b/containers/api-proxy/fixtures/protocol-compatibility/gaps.js new file mode 100644 index 000000000..72039a794 --- /dev/null +++ b/containers/api-proxy/fixtures/protocol-compatibility/gaps.js @@ -0,0 +1,109 @@ +'use strict'; + +/** + * Existing semantic discrepancies, not declarations of supported translation. + * Reviewed enforcement/translator changes are deferred to Phase 6 (#10296). + */ +module.exports = [ + { + name: 'Messages drops image detail, text cache_control and unknown nested message fields', + contract: 'chat-to-messages-request', feature: 'cache_controls', + input: { + model: 'fixture-model', messages: [{ role: 'user', future_field: 'fixture', content: [ + { type: 'text', text: 'hello', cache_control: { type: 'ephemeral' } }, + { type: 'image_url', image_url: { url: 'https://example.test/a.png', detail: 'high' } }, + ] }], + }, + output: { + model: 'fixture-model', max_tokens: 8192, + messages: [{ role: 'user', content: [ + { type: 'text', text: 'hello' }, + { type: 'image', source: { type: 'url', url: 'https://example.test/a.png' } }, + ] }], + }, + }, + { + name: 'Messages clamps temperature, filters non-string stops and appends refusal as text', + contract: 'chat-to-messages-request', feature: 'sampling_out_of_range', + input: { + model: 'fixture-model', messages: [{ role: 'assistant', content: 'hello', refusal: 'no' }], + temperature: 1.7, stop: ['END', 42], + }, + output: { + model: 'fixture-model', max_tokens: 8192, temperature: 1, stop_sequences: ['END'], + messages: [{ role: 'assistant', content: [{ type: 'text', text: 'hello' }, { type: 'text', text: 'no' }] }], + }, + }, + { + name: 'Chat wire drops unknown outer tool fields while mapping known function fields', + contract: 'chat-to-responses-request', feature: 'nested_tool_metadata', + input: { + model: 'fixture-model', messages: [{ role: 'user', content: 'hello' }], + tools: [{ type: 'function', future_field: 'fixture', function: { name: 'lookup' } }], + }, + output: { model: 'fixture-model', input: [{ role: 'user', content: 'hello' }], tools: [{ type: 'function', name: 'lookup' }] }, + }, + { + name: 'Responses request drops output_text annotations and format description', + contract: 'responses-to-chat-request', feature: 'output_annotations', + input: { + model: 'fixture-model', input: [{ role: 'assistant', content: [{ type: 'output_text', text: 'hello', annotations: [{ type: 'fixture' }] }] }], + text: { format: { type: 'json_schema', name: 'answer', schema: { type: 'object' }, description: 'fixture' } }, + }, + output: { + model: 'fixture-model', messages: [{ role: 'assistant', content: [{ type: 'text', text: 'hello' }] }], + response_format: { type: 'json_schema', json_schema: { name: 'answer', schema: { type: 'object' } } }, + }, + }, + { + name: 'Chat JSON return uses first choice and ignores reasoning content', + contract: 'chat-to-responses-return', feature: 'reasoning_content', + input: { + id: 'fixture_chat', created: 1700000000, model: 'fixture-model', + choices: [{ message: { content: 'hello', reasoning_content: 'fixture reasoning' }, finish_reason: 'stop' }, { message: { content: 'lost second choice' } }], + }, + output: { + id: 'fixture_chat', object: 'response', created_at: 1700000000, model: 'fixture-model', status: 'completed', + output: [{ type: 'message', id: 'msg_0', role: 'assistant', status: 'completed', content: [{ type: 'output_text', text: 'hello', annotations: [] }] }], + }, + }, + { + name: 'Responses JSON return ignores reasoning, unknown items and output annotations', + contract: 'responses-to-chat-return', feature: 'reasoning_content', + input: { + id: 'fixture_response', created_at: 1700000000, model: 'fixture-model', status: 'completed', + output: [{ type: 'reasoning', summary: [{ type: 'summary_text', text: 'fixture reasoning' }] }, { type: 'future_item' }, + { type: 'message', content: [{ type: 'output_text', text: 'hello', annotations: [{ type: 'fixture' }] }] }], + }, + output: { + id: 'fixture_response', object: 'chat.completion', created: 1700000000, model: 'fixture-model', + choices: [{ index: 0, message: { role: 'assistant', content: 'hello' }, finish_reason: 'stop' }], + }, + }, + { + name: 'Responses JSON return keeps only the last of multiple refusal parts', + contract: 'responses-to-chat-return', feature: 'multiple_refusal_parts', + input: { + id: 'fixture_response', created_at: 1700000000, model: 'fixture-model', status: 'completed', + output: [{ type: 'message', content: [ + { type: 'refusal', refusal: 'lost first refusal' }, { type: 'refusal', refusal: 'last refusal' }, + ] }], + }, + output: { + id: 'fixture_response', object: 'chat.completion', created: 1700000000, model: 'fixture-model', + choices: [{ index: 0, message: { role: 'assistant', content: null, refusal: 'last refusal' }, finish_reason: 'stop' }], + }, + }, + { + name: 'Messages JSON return ignores thinking, signatures and future output blocks', + contract: 'messages-to-chat-return', feature: 'reasoning_content', + input: { + id: 'fixture_message', model: 'fixture-model', stop_reason: 'future_stop', + content: [{ type: 'thinking', thinking: 'fixture reasoning', signature: 'fixture' }, { type: 'future_block' }, { type: 'text', text: 'hello' }], + }, + output: { + id: 'fixture_message', object: 'chat.completion', created: 1700000000, model: 'fixture-model', + choices: [{ index: 0, message: { role: 'assistant', content: 'hello' }, finish_reason: 'stop' }], + }, + }, +]; diff --git a/containers/api-proxy/fixtures/protocol-compatibility/requests.js b/containers/api-proxy/fixtures/protocol-compatibility/requests.js new file mode 100644 index 000000000..65ed59e83 --- /dev/null +++ b/containers/api-proxy/fixtures/protocol-compatibility/requests.js @@ -0,0 +1,205 @@ +'use strict'; + +const schema = { type: 'object', properties: { q: { type: 'string' } }, required: ['q'], additionalProperties: false }; +const fn = { name: 'lookup', description: 'Lookup', parameters: schema, strict: true }; +const chat = { model: 'fixture-model', messages: [{ role: 'user', content: 'hello' }] }; +const responses = { model: 'fixture-model', input: 'hello' }; +const chatId = 'chat-to-responses-request'; +const responsesId = 'responses-to-chat-request'; +const anthropicId = 'chat-to-messages-request'; +const commonFeatures = [ + 'message_text', 'message_roles', 'function_tools', 'tool_choice', + 'parallel_tool_calls', 'structured_output', 'image_input', 'streaming', + 'reasoning_fields', 'token_limits', 'transport_fields', +]; + +const cases = [ + { + name: 'Chat roles, strict schemas, images, calls/results, limits and transport', + contract: chatId, features: commonFeatures, + input: { + ...chat, + messages: [ + { role: 'system', content: 'rules' }, + { role: 'developer', content: 'guidance' }, + { role: 'user', content: [{ type: 'text', text: 'hello' }, { type: 'image_url', image_url: { url: 'https://example.test/a.png', detail: 'low' } }] }, + { role: 'assistant', content: 'checking', tool_calls: [{ id: 'call_1', type: 'function', function: { name: 'lookup', arguments: '{"q":"x"}' } }] }, + { role: 'tool', tool_call_id: 'call_1', content: { result: 'ok' } }, + ], + tools: [{ type: 'function', function: fn }], + tool_choice: { type: 'function', function: { name: 'lookup' } }, + parallel_tool_calls: false, reasoning_effort: 'opaque-fixture-effort', + max_tokens: 30, max_completion_tokens: 20, stream: true, stream_options: { include_usage: true }, n: 1, + response_format: { type: 'json_schema', json_schema: { name: 'answer', schema, strict: true } }, + }, + output: { + model: 'fixture-model', + input: [ + { role: 'user', content: [{ type: 'input_text', text: 'hello' }, { type: 'input_image', image_url: 'https://example.test/a.png', detail: 'low' }] }, + { role: 'assistant', content: 'checking' }, + { type: 'function_call', call_id: 'call_1', name: 'lookup', arguments: '{"q":"x"}' }, + { type: 'function_call_output', call_id: 'call_1', output: '{"result":"ok"}' }, + ], + instructions: 'rules\n\nguidance', tools: [{ type: 'function', ...fn }], + tool_choice: { type: 'function', name: 'lookup' }, parallel_tool_calls: false, + reasoning: { effort: 'opaque-fixture-effort' }, max_output_tokens: 20, stream: true, + text: { format: { type: 'json_schema', name: 'answer', schema, strict: true } }, + }, + }, + { + name: 'Responses roles, IDs, strict schemas, images, calls/results and no-op fields', + contract: responsesId, features: commonFeatures, + input: { + ...responses, instructions: 'rules', + input: [ + { type: 'message', id: 'transport-id', status: 'completed', role: 'developer', content: 'guidance' }, + { content: [{ type: 'input_text', text: 'hello' }, { type: 'input_image', image_url: 'https://example.test/a.png', detail: 'low' }] }, + { role: 'assistant', content: [{ type: 'output_text', text: 'checking' }] }, + { type: 'function_call', id: 'item_1', status: 'completed', call_id: 'call_1', name: 'lookup', arguments: '{"q":"x"}' }, + { type: 'function_call', call_id: 'call_2', name: 'lookup', arguments: '' }, + { type: 'function_call_output', call_id: 'call_1', output: { result: 'ok' } }, + ], + tools: [{ type: 'function', ...fn }], tool_choice: { type: 'function', name: 'lookup' }, + parallel_tool_calls: true, reasoning: { effort: 'opaque-fixture-effort' }, + max_output_tokens: 20, stream: true, store: false, metadata: null, include: false, + truncation: null, previous_response_id: false, prompt_cache_key: null, + text: { format: { type: 'json_schema', name: 'answer', schema, strict: true } }, + }, + output: { + model: 'fixture-model', + messages: [ + { role: 'system', content: 'rules' }, { role: 'developer', content: 'guidance' }, + { role: 'user', content: [{ type: 'text', text: 'hello' }, { type: 'image_url', image_url: { url: 'https://example.test/a.png', detail: 'low' } }] }, + { role: 'assistant', content: [{ type: 'text', text: 'checking' }] }, + { role: 'assistant', content: null, tool_calls: [ + { id: 'call_1', type: 'function', function: { name: 'lookup', arguments: '{"q":"x"}' } }, + { id: 'call_2', type: 'function', function: { name: 'lookup', arguments: '{}' } }, + ] }, + { role: 'tool', tool_call_id: 'call_1', content: '{"result":"ok"}' }, + ], + tools: [{ type: 'function', function: fn }], tool_choice: { type: 'function', function: { name: 'lookup' } }, + parallel_tool_calls: true, reasoning_effort: 'opaque-fixture-effort', max_tokens: 20, + stream: true, stream_options: { include_usage: true }, + response_format: { type: 'json_schema', json_schema: { name: 'answer', schema, strict: true } }, + }, + }, + { + name: 'Messages role merging, function calls/results, images and transport no-ops', + contract: anthropicId, + features: ['message_text', 'message_roles', 'function_tools', 'tool_choice', 'parallel_tool_calls', 'image_input', 'streaming', 'token_limits', 'transport_fields'], + input: { + ...chat, messages: [ + { role: 'system', content: 'rules' }, { role: 'developer', content: [{ type: 'text', text: 'guidance' }] }, + { role: 'user', content: '' }, + { role: 'user', content: 'hello' }, { role: 'user', content: [ + { type: 'image_url', image_url: 'https://example.test/a.png' }, + { type: 'image_url', image_url: { url: 'data:image/png;base64,YQ==' } }, + ] }, + { role: 'assistant', content: 'checking', tool_calls: [{ id: 'call_1', type: 'function', function: { name: 'lookup', arguments: '{"q":"x"}' } }] }, + { role: 'tool', tool_call_id: 'call_1', content: [{ type: 'text', text: 'ok' }, { type: 'text', text: '!' }] }, + ], + tools: [{ type: 'function', function: fn }], tool_choice: 'required', + parallel_tool_calls: false, max_tokens: 30, max_completion_tokens: 20, + temperature: 0.5, top_p: 0.9, stop: ['END'], stream: true, user: 'fixture-user', + stream_options: { include_usage: true }, n: 1, logprobs: false, response_format: { type: 'text' }, future_field: null, + }, + output: { + model: 'fixture-model', system: 'rules\n\nguidance', + messages: [ + { role: 'user', content: [ + { type: 'text', text: 'hello' }, + { type: 'image', source: { type: 'url', url: 'https://example.test/a.png' } }, + { type: 'image', source: { type: 'base64', media_type: 'image/png', data: 'YQ==' } }, + ] }, + { role: 'assistant', content: [{ type: 'text', text: 'checking' }, { type: 'tool_use', id: 'call_1', name: 'lookup', input: { q: 'x' } }] }, + { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'call_1', content: 'ok!' }] }, + ], + max_tokens: 20, temperature: 0.5, top_p: 0.9, stop_sequences: ['END'], stream: true, + metadata: { user_id: 'fixture-user' }, + tools: [{ name: 'lookup', description: 'Lookup', strict: true, input_schema: schema }], + tool_choice: { type: 'any', disable_parallel_tool_use: true }, + }, + }, +]; + +for (const [contract, base, field] of [[chatId, chat, 'response_format'], [responsesId, responses, 'text']]) { + cases.push({ + name: `${contract}: json_object`, contract, features: ['structured_output'], + input: { ...base, [field]: contract === chatId ? { type: 'json_object' } : { format: { type: 'json_object' } } }, + output: contract === chatId + ? { model: base.model, input: [{ role: 'user', content: 'hello' }], text: { format: { type: 'json_object' } } } + : { model: base.model, messages: [{ role: 'user', content: 'hello' }], response_format: { type: 'json_object' } }, + }); +} + +for (const max_tokens of [undefined, 0, -1, 1.5]) { + cases.push({ + name: `Messages limit default: ${max_tokens}`, contract: anthropicId, features: ['token_limits'], + input: { ...chat, max_tokens }, + output: { model: chat.model, messages: [{ role: 'user', content: [{ type: 'text', text: 'hello' }] }], max_tokens: 8192 }, + }); +} + +for (const choice of ['auto', 'none', 'required', { type: 'function', function: { name: 'lookup' } }]) { + const mapped = typeof choice === 'object' ? { type: 'tool', name: 'lookup' } : { type: choice === 'required' ? 'any' : choice }; + cases.push({ + name: `Messages tool choice: ${mapped.type}`, contract: anthropicId, features: ['tool_choice', 'parallel_tool_calls', 'function_tools'], + input: { ...chat, tools: [{ type: 'function', function: { name: 'lookup' } }], tool_choice: choice, parallel_tool_calls: false }, + output: { + model: chat.model, messages: [{ role: 'user', content: [{ type: 'text', text: 'hello' }] }], max_tokens: 8192, + tools: [{ name: 'lookup', input_schema: { type: 'object', properties: {} } }], + tool_choice: { ...mapped, ...(mapped.type === 'none' ? {} : { disable_parallel_tool_use: true }) }, + }, + }); +} + +const rejections = []; +function reject(contract, input, feature, evidence) { + rejections.push({ + name: `${contract}: rejects ${feature}`, contract, features: [evidence], input, + error: { code: contract === anthropicId ? 'unsupported_protocol_feature' : 'unsupported_wire_api_feature', feature }, + }); +} + +for (const [contract, base] of [[chatId, chat], [responsesId, responses], [anthropicId, chat]]) { + reject(contract, { ...base, tools: [{ type: 'web_search' }] }, 'tools[web_search]', 'hosted_tools'); + reject(contract, { ...base, tools: [{ type: 'custom', name: 'run' }] }, 'tools[custom]', 'hosted_tools'); + reject(contract, { ...base, audio: { voice: 'fixture' } }, 'audio', 'audio'); + reject(contract, { ...base, future_feature: true }, 'future_feature', 'unknown_fields'); + reject(contract, { ...base, previous_response_id: 'resp_previous' }, 'previous_response_id', 'stateful_fields'); + for (const [type, evidence] of [['input_audio', 'audio'], ['video', 'other_modalities'], ['reasoning', 'reasoning_content'], ['future_content', 'other_modalities']]) { + const input = contract === responsesId + ? { ...base, input: [{ role: 'user', content: [{ type }] }] } + : { ...base, messages: [{ role: 'user', content: [{ type }] }] }; + const feature = contract === responsesId ? `input.content[${type}]` + : contract === chatId ? `messages.content[${type}]` : `messages[user].content[${type}]`; + reject(contract, input, feature, evidence); + } +} + +for (const field of ['store', 'metadata', 'truncation', 'include', 'prompt_cache_key']) { + reject(responsesId, { ...responses, [field]: field === 'store' ? true : 'active' }, field, 'stateful_fields'); +} +reject(chatId, { ...chat, store: true }, 'store', 'stateful_fields'); +reject(chatId, { ...chat, n: 2 }, 'n', 'transport_fields'); +reject(chatId, { ...chat, stream_options: { include_usage: 'yes' } }, 'stream_options.include_usage', 'transport_fields'); +reject(chatId, { ...chat, stream_options: { future_option: true } }, 'future_option', 'transport_fields'); +reject(chatId, { ...chat, response_format: { type: 'text' } }, 'response_format', 'structured_output'); +reject(chatId, { ...chat, messages: [{ role: 'system', content: [{ type: 'text', text: 'rules' }] }] }, 'messages[system].content', 'message_roles'); +reject(responsesId, { ...responses, input: [{ type: 'reasoning', encrypted_content: 'fixture' }] }, 'input[0].type=reasoning', 'reasoning_content'); +reject(responsesId, { ...responses, reasoning: { summary: 'auto' } }, 'reasoning.summary', 'reasoning_fields'); +reject(responsesId, { ...responses, reasoning: { encrypted_content: 'fixture' } }, 'reasoning.encrypted_content', 'reasoning_fields'); +reject(responsesId, { ...responses, reasoning: { future_reasoning: true } }, 'future_reasoning', 'reasoning_fields'); +reject(responsesId, { ...responses, input: [{ type: 'function_call', name: 'lookup', arguments: '{}' }] }, 'input[0].call_id', 'function_tools'); +for (const contract of [chatId, anthropicId]) { + reject(contract, { ...chat, messages: [{ role: 'tool', content: 'ok' }] }, 'messages[tool].tool_call_id', 'function_tools'); + reject(contract, { ...chat, messages: [{ role: 'future_role', content: 'hello' }] }, 'messages[future_role]', 'message_roles'); +} +reject(anthropicId, { ...chat, reasoning_effort: 'opaque-fixture-effort' }, 'reasoning_effort', 'reasoning_fields'); +reject(anthropicId, { ...chat, response_format: { type: 'json_schema', json_schema: { schema, strict: true } } }, 'response_format', 'structured_output'); +reject(anthropicId, { ...chat, response_format: { type: 'json_object' } }, 'response_format', 'structured_output'); +reject(anthropicId, { ...chat, tool_choice: 'required' }, 'tool_choice', 'tool_choice'); +reject(anthropicId, { ...chat, messages: [{ role: 'user', content: [{ type: 'image_url', image_url: 'http://example.test/a.png' }] }] }, 'messages.content[image_url]', 'image_input'); +reject(anthropicId, { ...chat, messages: [{ role: 'assistant', tool_calls: [{ id: 'call_1', type: 'function', function: { name: 'lookup', arguments: '[1]' } }] }] }, 'messages.tool_calls.function.arguments', 'function_tools'); + +module.exports = { cases: [...cases, ...rejections], chat, responses }; diff --git a/containers/api-proxy/fixtures/protocol-compatibility/responses.js b/containers/api-proxy/fixtures/protocol-compatibility/responses.js new file mode 100644 index 000000000..cf9254085 --- /dev/null +++ b/containers/api-proxy/fixtures/protocol-compatibility/responses.js @@ -0,0 +1,104 @@ +'use strict'; + +const created = 1700000000; +const chatUsage = { + prompt_tokens: 10, completion_tokens: 4, total_tokens: 14, + prompt_tokens_details: { cached_tokens: 3 }, + completion_tokens_details: { reasoning_tokens: 2 }, +}; +const responsesUsage = { + input_tokens: 10, output_tokens: 4, total_tokens: 14, + input_tokens_details: { cached_tokens: 3 }, + output_tokens_details: { reasoning_tokens: 2 }, +}; +const chatMessage = { + role: 'assistant', content: 'hello 🌍', refusal: 'cannot do that', + tool_calls: [{ id: 'call_1', type: 'function', function: { name: 'lookup', arguments: '{"q":"x"}' } }], +}; +const responseOutput = [ + { type: 'message', id: 'msg_0', role: 'assistant', status: 'completed', content: [{ type: 'output_text', text: 'hello 🌍', annotations: [] }] }, + { type: 'message', id: 'msg_refusal_0', role: 'assistant', status: 'completed', content: [{ type: 'refusal', refusal: 'cannot do that' }] }, + { type: 'function_call', id: 'call_1', call_id: 'call_1', name: 'lookup', arguments: '{"q":"x"}', status: 'completed' }, +]; +const cases = [ + { + name: 'Chat JSON to Responses: text, refusal, function IDs and detailed usage', + contract: 'chat-to-responses-return', + features: ['message_text', 'function_tools', 'usage', 'finish_reasons', 'refusal'], + input: { id: 'fixture_chat', created, model: 'fixture-model', choices: [{ index: 0, message: chatMessage, finish_reason: 'tool_calls' }], usage: chatUsage }, + output: { id: 'fixture_chat', object: 'response', created_at: created, status: 'completed', model: 'fixture-model', output: responseOutput, usage: responsesUsage }, + }, + { + name: 'Responses JSON to Chat: text, refusal, call_id precedence and detailed usage', + contract: 'responses-to-chat-return', + features: ['message_text', 'function_tools', 'usage', 'finish_reasons', 'refusal'], + input: { + id: 'fixture_response', created_at: created, model: 'fixture-model', status: 'incomplete', + incomplete_details: { reason: 'max_output_tokens' }, + output: responseOutput.map(item => item.type === 'function_call' ? { ...item, id: 'transport_item' } : item), + usage: responsesUsage, + }, + output: { + id: 'fixture_response', object: 'chat.completion', created, model: 'fixture-model', + choices: [{ index: 0, message: chatMessage, finish_reason: 'tool_calls' }], usage: chatUsage, + }, + }, + { + name: 'Messages JSON to Chat: text concatenation, function IDs and cache usage', + contract: 'messages-to-chat-return', + features: ['message_text', 'function_tools', 'usage', 'finish_reasons'], + input: { + id: 'fixture_message', model: 'fixture-model', stop_reason: 'tool_use', + content: [{ type: 'text', text: 'hello ' }, { type: 'text', text: '🌍' }, { type: 'tool_use', id: 'call_1', name: 'lookup', input: { q: 'x' } }], + usage: { input_tokens: 5, cache_read_input_tokens: 3, cache_creation_input_tokens: 2, output_tokens: 4 }, + }, + output: { + id: 'fixture_message', object: 'chat.completion', created, model: 'fixture-model', + choices: [{ index: 0, message: { role: 'assistant', content: 'hello 🌍', tool_calls: chatMessage.tool_calls }, finish_reason: 'tool_calls' }], + usage: { prompt_tokens: 10, completion_tokens: 4, total_tokens: 14, prompt_tokens_details: { cached_tokens: 3 } }, + }, + }, +]; + +for (const finish of ['stop', 'length', 'content_filter']) { + cases.push({ + name: `Chat JSON finish: ${finish}`, contract: 'chat-to-responses-return', features: ['finish_reasons'], + input: { id: 'fixture_chat', created, model: 'fixture-model', choices: [{ message: { content: 'text' }, finish_reason: finish }], usage: {} }, + output: { + id: 'fixture_chat', object: 'response', created_at: created, model: 'fixture-model', + status: finish === 'stop' ? 'completed' : 'incomplete', + ...(finish === 'stop' ? {} : { incomplete_details: { reason: finish === 'length' ? 'max_output_tokens' : 'content_filter' } }), + output: [{ type: 'message', id: 'msg_0', role: 'assistant', status: 'completed', content: [{ type: 'output_text', text: 'text', annotations: [] }] }], + usage: { input_tokens: 0, output_tokens: 0, total_tokens: 0 }, + }, + }); +} + +for (const [status, reason, finish] of [['completed', undefined, 'stop'], ['incomplete', 'max_output_tokens', 'length'], ['incomplete', 'content_filter', 'content_filter']]) { + cases.push({ + name: `Responses JSON finish: ${finish}`, contract: 'responses-to-chat-return', features: ['finish_reasons', 'usage'], + input: { id: 'fixture_response', created_at: created, model: 'fixture-model', status, ...(reason ? { incomplete_details: { reason } } : {}), output: [], usage: {} }, + output: { + id: 'fixture_response', object: 'chat.completion', created, model: 'fixture-model', + choices: [{ index: 0, message: { role: 'assistant', content: null }, finish_reason: finish }], + usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 }, + }, + }); +} + +for (const [stop_reason, finish] of [ + ['end_turn', 'stop'], ['stop_sequence', 'stop'], ['max_tokens', 'length'], + ['model_context_window_exceeded', 'length'], ['refusal', 'content_filter'], +]) { + cases.push({ + name: `Messages JSON finish: ${stop_reason}`, contract: 'messages-to-chat-return', features: ['finish_reasons', 'usage'], + input: { id: 'fixture_message', model: 'fixture-model', stop_reason, content: [], usage: {} }, + output: { + id: 'fixture_message', object: 'chat.completion', created, model: 'fixture-model', + choices: [{ index: 0, message: { role: 'assistant', content: null }, finish_reason: finish }], + usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 }, + }, + }); +} + +module.exports = { cases, chatUsage, responsesUsage, created }; diff --git a/containers/api-proxy/fixtures/protocol-compatibility/streams.js b/containers/api-proxy/fixtures/protocol-compatibility/streams.js new file mode 100644 index 000000000..cfa0bda0b --- /dev/null +++ b/containers/api-proxy/fixtures/protocol-compatibility/streams.js @@ -0,0 +1,108 @@ +'use strict'; + +const { chatUsage, responsesUsage, created } = require('./responses'); + +function frame(value) { + return `data: ${JSON.stringify(value)}\n\n`; +} + +const chatFrames = [ + { id: 'fixture_chat', model: 'fixture-model', choices: [{ delta: { role: 'assistant', content: 'hello ' } }] }, + { choices: [{ delta: { content: '🌍', refusal: 'cannot ' } }] }, + { choices: [{ delta: { refusal: 'do that', tool_calls: [ + { index: 0, id: 'call_1', type: 'function', function: { name: 'look', arguments: '{"q":' } }, + { index: 1, id: 'call_2', type: 'function', function: { name: 'second', arguments: '{' } }, + ] } }] }, + { choices: [{ delta: { tool_calls: [ + { index: 1, function: { arguments: '}' } }, + { index: 0, function: { name: 'up', arguments: '"x"}' } }, + ] }, finish_reason: 'tool_calls' }] }, + { choices: [], usage: chatUsage }, +]; +const responsesFrames = [ + { type: 'response.created', response: { id: 'fixture_response', model: 'fixture-model', created_at: created } }, + { type: 'response.output_text.delta', delta: 'hello ' }, + { type: 'response.output_text.delta', delta: '🌍' }, + { type: 'response.refusal.delta', delta: 'cannot do that' }, + { type: 'response.output_item.added', item: { type: 'function_call', id: 'item_1', call_id: 'call_1', name: 'lookup' } }, + { type: 'response.output_item.added', item: { type: 'function_call', id: 'item_2', call_id: 'call_2', name: 'second' } }, + { type: 'response.function_call_arguments.delta', item_id: 'item_1', delta: '{"q":' }, + { type: 'response.function_call_arguments.delta', item_id: 'item_2', delta: '{}' }, + { type: 'response.function_call_arguments.delta', item_id: 'item_1', delta: '"x"}' }, + { type: 'response.completed', response: { status: 'completed', output: [{ type: 'function_call' }], usage: responsesUsage } }, +]; +const anthropicFrames = [ + { type: 'message_start', message: { id: 'fixture_message', model: 'fixture-model', usage: { input_tokens: 5, cache_read_input_tokens: 3, cache_creation_input_tokens: 2 } } }, + { type: 'content_block_start', index: 0, content_block: { type: 'text', text: 'hello ' } }, + { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: '🌍' } }, + { type: 'content_block_start', index: 7, content_block: { type: 'tool_use', id: 'call_1', name: 'lookup', input: {} } }, + { type: 'content_block_start', index: 9, content_block: { type: 'tool_use', id: 'call_2', name: 'second', input: {} } }, + { type: 'content_block_delta', index: 7, delta: { type: 'input_json_delta', partial_json: '{"q":' } }, + { type: 'content_block_delta', index: 9, delta: { type: 'input_json_delta', partial_json: '{}' } }, + { type: 'content_block_delta', index: 7, delta: { type: 'input_json_delta', partial_json: '"x"}' } }, + { type: 'content_block_stop', index: 7 }, + { type: 'message_delta', delta: { stop_reason: 'tool_use' }, usage: { output_tokens: 4 } }, + { type: 'message_stop' }, +]; +const calls = [ + { id: 'call_1', name: 'lookup', arguments: '{"q":"x"}' }, + { id: 'call_2', name: 'second', arguments: '{}' }, +]; + +const cases = [ + { + name: 'Chat SSE assembles partial text, refusal, parallel tool calls, usage and completion', + contract: 'chat-to-responses-return', features: ['streaming', 'message_text', 'function_tools', 'usage', 'finish_reasons', 'refusal'], + input: chatFrames.map(frame).join('') + 'data: [DONE]\n\n', + summary: { text: 'hello 🌍', refusal: 'cannot do that', calls, finish: 'tool_calls', usage: responsesUsage, done: true, errors: [] }, + }, + { + name: 'Responses SSE emits text, refusal, indexed tool deltas, usage and DONE', + contract: 'responses-to-chat-return', features: ['streaming', 'message_text', 'function_tools', 'usage', 'finish_reasons', 'refusal'], + input: responsesFrames.map(frame).join(''), includeUsage: true, + summary: { text: 'hello 🌍', refusal: 'cannot do that', calls, finish: 'tool_calls', usage: chatUsage, done: true, errors: [] }, + }, + { + name: 'Messages SSE emits text, indexed parallel tool deltas, cache usage and DONE', + contract: 'messages-to-chat-return', features: ['streaming', 'message_text', 'function_tools', 'usage', 'finish_reasons'], + input: anthropicFrames.map(frame).join(''), includeUsage: true, + summary: { + text: 'hello 🌍', refusal: '', calls, finish: 'tool_calls', + usage: { prompt_tokens: 10, completion_tokens: 4, total_tokens: 14, prompt_tokens_details: { cached_tokens: 3 } }, done: true, errors: [], + }, + }, +]; + +for (const [contract, event, expectedError] of [ + ['chat-to-responses-return', { error: { code: 'fixture_error', message: 'upstream failed' } }, { code: 'fixture_error', message: 'upstream failed' }], + ['responses-to-chat-return', { type: 'response.failed', response: { error: { code: 'fixture_error', message: 'upstream failed' } } }, + { type: 'response.failed', response: { error: { code: 'fixture_error', message: 'upstream failed' } } }], + ['messages-to-chat-return', { type: 'error', error: { type: 'fixture_error', message: 'upstream failed' } }, + { type: 'fixture_error', message: 'upstream failed' }], +]) { + cases.push({ + name: `${contract}: upstream error without synthetic completion`, + contract, features: ['streaming'], input: frame(event), + summary: { text: '', refusal: '', calls: [], finish: null, usage: undefined, done: false, errors: [expectedError] }, + }); +} + +const gaps = [ + { + name: 'Responses SSE drops initial function-call arguments and ignores the final item', + contract: 'responses-to-chat-return', + input: [ + { type: 'response.created', response: { id: 'fixture_response', model: 'fixture-model', created_at: created } }, + { type: 'response.output_item.added', item: { + type: 'function_call', id: 'item_1', call_id: 'call_1', name: 'lookup', arguments: '{"q":"initial"}', + } }, + { type: 'response.function_call_arguments.delta', item_id: 'item_1', delta: '{"q":"delta"}' }, + { type: 'response.completed', response: { status: 'completed', output: [ + { type: 'function_call', id: 'item_1', call_id: 'call_1', name: 'lookup', arguments: '{"q":"final"}' }, + ] } }, + ].map(frame).join(''), + calls: [{ id: 'call_1', name: 'lookup', arguments: '{"q":"delta"}' }], + }, +]; + +module.exports = { cases, gaps, frame, chatFrames, responsesFrames, anthropicFrames }; diff --git a/containers/api-proxy/protocol-compatibility.packaging.test.js b/containers/api-proxy/protocol-compatibility.packaging.test.js new file mode 100644 index 000000000..b62c3f7a8 --- /dev/null +++ b/containers/api-proxy/protocol-compatibility.packaging.test.js @@ -0,0 +1,62 @@ +'use strict'; + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { spawnSync } = require('child_process'); + +test('the declared API and readonly invariants type-check with existing root TypeScript tooling', () => { + const ts = require('typescript'); + const fixture = path.join(__dirname, 'fixtures/protocol-compatibility/contract-types.ts'); + const program = ts.createProgram([fixture], { + noEmit: true, strict: true, skipLibCheck: true, types: [], + target: ts.ScriptTarget.ES2020, + module: ts.ModuleKind.Node16, moduleResolution: ts.ModuleResolutionKind.Node16, + }); + expect(ts.getPreEmitDiagnostics(program).map(diagnostic => + ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'))).toEqual([]); +}); + +test('contracts and declarations load with translators from the actual Docker COPY layout', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'awf-protocol-layout-')); + try { + const dockerfile = fs.readFileSync(path.join(__dirname, 'Dockerfile'), 'utf8').replace(/\\\n/g, ' '); + const copies = dockerfile.split('\n').map(line => /^COPY (.+) (\.\/\S*)$/.exec(line)).filter(Boolean); + expect(copies.some(copy => copy[1] === 'protocol-compatibility/')).toBe(true); + for (const [, sources, destination] of copies) { + for (const source of sources.trim().split(/\s+/)) { + const names = source === 'package*.json' + ? fs.readdirSync(__dirname).filter(name => /^package.*\.json$/.test(name)) + : [source]; + for (const name of names) { + const absolute = path.join(__dirname, name); + const target = destination === './' ? path.join(root, path.basename(name)) : path.join(root, destination); + fs.cpSync(absolute, target, { recursive: true }); + } + } + } + expect(fs.existsSync(path.join(root, 'protocol-compatibility', 'index.d.ts'))).toBe(true); + expect(fs.existsSync(path.join(root, 'fixtures'))).toBe(false); + const result = spawnSync(process.execPath, ['-e', ` + const assert = require('assert/strict'); + const { CONTRACTS, assessFeature } = require('./protocol-compatibility'); + const wire = require('./wire-api-compat'); + const messages = require('./anthropic-chat-compat'); + assert.equal(CONTRACTS.length, 6); + assert.equal(assessFeature({source:'anthropic_messages', target:'chat_completions', + direction:'request', feature:'message_text'}).status, 'unknown'); + assert.deepEqual(wire.translateChatRequest({model:'fixture-model', messages:[{role:'user',content:'hello'}]}), + {model:'fixture-model',input:[{role:'user',content:'hello'}]}); + assert.equal(messages.chatRequestToAnthropic({model:'fixture-model',messages:[]}).max_tokens,8192); + assert.equal(JSON.parse(messages.anthropicResponseToChat(Buffer.from('{"content":[]}'))).object,'chat.completion'); + const transform = wire.createWireApiSseTransform({direction:'responses_to_chat'}); + let output = ''; + transform.on('data', chunk => { output += chunk; }); + transform.on('end', () => assert.ok(output.includes('response.completed'))); + transform.end('data: [DONE]\\n\\n'); + `], { cwd: root, encoding: 'utf8', timeout: 10000 }); + expect({ status: result.status, stderr: result.stderr }).toEqual({ status: 0, stderr: '' }); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/containers/api-proxy/protocol-compatibility.test.js b/containers/api-proxy/protocol-compatibility.test.js new file mode 100644 index 000000000..b5edf7579 --- /dev/null +++ b/containers/api-proxy/protocol-compatibility.test.js @@ -0,0 +1,450 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const { createHash } = require('crypto'); +const { CONTRACTS, FEATURES, REVISION, assessFeature } = require('./protocol-compatibility'); +const wire = require('./wire-api-compat'); +const anthropic = require('./anthropic-chat-compat'); +const requests = require('./fixtures/protocol-compatibility/requests'); +const responses = require('./fixtures/protocol-compatibility/responses'); +const streams = require('./fixtures/protocol-compatibility/streams'); +const gaps = require('./fixtures/protocol-compatibility/gaps'); + +function deepFreeze(value) { + if (value && typeof value === 'object') { + Object.values(value).forEach(deepFreeze); + Object.freeze(value); + } + return value; +} + +function requestTranslator(id) { + switch (id) { + case 'chat-to-responses-request': return wire.translateChatRequest; + case 'responses-to-chat-request': return wire.translateResponsesRequest; + case 'chat-to-messages-request': return anthropic.chatRequestToAnthropic; + default: throw new Error('Fixture has no implemented request direction'); + } +} + +function wireReturnContext(id, includeUsage) { + switch (id) { + // The existing wire context names the REQUEST direction, not this return direction. + case 'chat-to-responses-return': return { direction: 'responses_to_chat' }; + case 'responses-to-chat-return': return { direction: 'chat_to_responses', includeUsage }; + default: throw new Error('Fixture has no implemented wire return direction'); + } +} + +function responseTranslator(id, body) { + return id === 'messages-to-chat-return' + ? anthropic.anthropicResponseToChat(body) + : wire.transformWireApiResponseBody(body, wireReturnContext(id)); +} + +function streamTranslator(id, includeUsage = false) { + return id === 'messages-to-chat-return' + ? anthropic.createAnthropicToChatSseTransform({ includeUsage }) + : wire.createWireApiSseTransform(wireReturnContext(id, includeUsage)); +} + +async function collectStream(id, input, chunkSize, includeUsage = false) { + const transform = streamTranslator(id, includeUsage); + const chunks = []; + const done = new Promise((resolve, reject) => { + transform.on('data', chunk => chunks.push(chunk)); + transform.on('end', resolve); + transform.on('error', reject); + }); + const bytes = Buffer.from(input); + for (let offset = 0; offset < bytes.length; offset += chunkSize) { + transform.write(bytes.subarray(offset, offset + chunkSize)); + } + transform.end(); + await done; + return Buffer.concat(chunks).toString('utf8'); +} + +function parseFrames(output) { + return output.split(/\r?\n\r?\n/).filter(Boolean).map(block => { + const data = block.split(/\r?\n/).filter(line => line.startsWith('data:')).map(line => line.slice(5).trimStart()).join('\n'); + return data === '[DONE]' ? data : JSON.parse(data); + }); +} + +function summarize(frames) { + const result = { text: '', refusal: '', calls: [], finish: null, usage: undefined, done: false, errors: [] }; + const calls = new Map(); + for (const event of frames) { + if (event === '[DONE]') { result.done = true; continue; } + if (event.error) { result.errors.push(event.error); continue; } + if (event.type === 'response.completed') { + result.done = true; + result.usage = event.response.usage; + for (const item of event.response.output) { + if (item.type === 'message') { + expect(item.role).toBe('assistant'); + for (const part of item.content) { + if (part.type === 'output_text') result.text += part.text; + if (part.type === 'refusal') result.refusal += part.refusal; + } + } else if (item.type === 'function_call') { + result.calls.push({ id: item.call_id, name: item.name, arguments: item.arguments }); + expect(item.id).toBe(item.call_id); + } + } + result.finish = result.calls.length ? 'tool_calls' : event.response.status === 'incomplete' + ? event.response.incomplete_details.reason === 'content_filter' ? 'content_filter' : 'length' + : 'stop'; + } + if (event.choices) { + if (event.usage) result.usage = event.usage; + for (const choice of event.choices) { + if (choice.finish_reason) result.finish = choice.finish_reason; + const delta = choice.delta || {}; + if (delta.role) expect(delta.role).toBe('assistant'); + result.text += delta.content || ''; + result.refusal += delta.refusal || ''; + for (const call of delta.tool_calls || []) { + const previous = calls.get(call.index) || { id: undefined, name: '', arguments: '' }; + if (call.id) previous.id = call.id; + previous.name += call.function?.name || ''; + previous.arguments += call.function?.arguments || ''; + calls.set(call.index, previous); + } + } + } + } + if (calls.size) result.calls = [...calls.values()]; + return result; +} + +describe('directed protocol compatibility contracts', () => { + test('enumerates only implemented request and return directions', () => { + expect(CONTRACTS.map(({ source, target, direction }) => [source, target, direction])).toEqual([ + ['chat_completions', 'responses', 'request'], + ['responses', 'chat_completions', 'request'], + ['chat_completions', 'anthropic_messages', 'request'], + ['chat_completions', 'responses', 'return_response'], + ['responses', 'chat_completions', 'return_response'], + ['anthropic_messages', 'chat_completions', 'return_response'], + ]); + expect(new Set(CONTRACTS.map(contract => contract.id)).size).toBe(CONTRACTS.length); + for (const contract of CONTRACTS) { + expect(contract.features.map(row => row.feature)).toEqual(FEATURES); + expect(contract.revision).toBe(REVISION); + for (const row of contract.features) { + expect(row.reason.length).toBeGreaterThan(0); + if (row.status === 'conditional') expect(row.conditions.length).toBeGreaterThan(0); + } + } + }); + + test('pins evidence to the actual implementation bytes and exported boundaries', () => { + for (const contract of CONTRACTS) { + const implementationPath = path.join(__dirname, contract.implementation.file); + const hash = createHash('sha256').update(fs.readFileSync(implementationPath)).digest('hex'); + expect(hash).toBe(contract.implementation.sha256); + const implementation = require(implementationPath); + for (const name of contract.entryPoints) expect(typeof implementation[name]).toBe('function'); + } + }); + + test('documentation matrix agrees with every executable feature row', () => { + const documentation = fs.readFileSync(path.resolve(__dirname, '../../docs/api-proxy-sidecar.md'), 'utf8'); + const statuses = { supported: 'S', conditional: 'C', rejected: 'R', unknown: 'U' }; + for (const feature of FEATURES) { + const line = documentation.split('\n').find(candidate => candidate.startsWith(`| \`${feature}\` |`)); + expect(line).toBeDefined(); + const cells = line.split('|').slice(2, -1).map(cell => cell.trim()); + expect(cells).toEqual([0, 1, 2, 3, 5].map(index => + statuses[CONTRACTS[index].features.find(row => row.feature === feature).status])); + expect(CONTRACTS[3].features.find(row => row.feature === feature).status) + .toBe(CONTRACTS[4].features.find(row => row.feature === feature).status); + } + }); + + test('assessment is immutable, deterministic and does not consult model discovery', () => { + const discovery = jest.spyOn(require('./runtime-model-catalog'), 'findRuntimeModel'); + const query = deepFreeze({ + source: 'chat_completions', target: 'responses', direction: 'request', feature: 'function_tools', + }); + const first = assessFeature(query); + expect(assessFeature(query)).toEqual(first); + expect(first.status).toBe('conditional'); + expect(discovery).not.toHaveBeenCalled(); + expect(() => { first.status = 'supported'; }).toThrow(TypeError); + expect(() => { first.evidence.conditions.push('anything'); }).toThrow(TypeError); + expect(() => { first.contract.implementation.sha256 = 'anything'; }).toThrow(TypeError); + expect(() => { CONTRACTS.push(first.contract); }).toThrow(TypeError); + discovery.mockRestore(); + }); + + test.each([ + ['anthropic_messages', 'chat_completions', 'request', 'message_text'], + ['responses', 'anthropic_messages', 'request', 'message_text'], + ['chat_completions', 'anthropic_messages', 'return_response', 'message_text'], + ['chat_completions', 'chat_completions', 'request', 'message_text'], + ['chat_completions', 'responses', 'request', 'future_feature_with_private_value'], + ['chat_completions', 'responses', 'return_response', 'reasoning_content'], + ['anthropic_messages', 'chat_completions', 'return_response', 'image_input'], + ])('does not infer compatibility for %s → %s %s %s', (source, target, direction, feature) => { + const result = assessFeature({ source, target, direction, feature }); + expect(result.status).toBe('unknown'); + expect(result).not.toHaveProperty('compatible'); + expect(result.reason).not.toContain('private_value'); + }); + + test('missing assessment input does not imply compatibility', () => { + expect(assessFeature().status).toBe('unknown'); + expect(assessFeature(null).status).toBe('unknown'); + expect(assessFeature(42).status).toBe('unknown'); + }); +}); + +describe('pre-existing semantic gaps are evidence, not support claims (Phase 6 #10296)', () => { + beforeEach(() => jest.spyOn(Date, 'now').mockReturnValue(responses.created * 1000)); + afterEach(() => jest.restoreAllMocks()); + + test.each(gaps)('$name', fixture => { + const contract = CONTRACTS.find(candidate => candidate.id === fixture.contract); + const input = deepFreeze(structuredClone(fixture.input)); + const output = contract.direction === 'request' + ? requestTranslator(contract.id)(input) + : JSON.parse(responseTranslator(contract.id, Buffer.from(JSON.stringify(input)))); + expect(output).toEqual(fixture.output); + expect(assessFeature({ ...contract, feature: fixture.feature }).status).toBe('unknown'); + }); + + test('Messages SSE loses nonempty initial tool input and ignores thinking/signature deltas', async () => { + const input = [ + { type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: 'call_1', name: 'lookup', input: { q: 'lost' } } }, + { type: 'content_block_delta', index: 2, delta: { type: 'thinking_delta', thinking: 'lost' } }, + { type: 'content_block_delta', index: 2, delta: { type: 'signature_delta', signature: 'lost' } }, + { type: 'message_delta', delta: { stop_reason: 'tool_use' } }, + { type: 'message_stop' }, + ].map(streams.frame).join(''); + const result = summarize(parseFrames(await collectStream('messages-to-chat-return', input, 1))); + expect(result).toEqual({ + text: '', refusal: '', calls: [{ id: 'call_1', name: 'lookup', arguments: '' }], + finish: 'tool_calls', usage: undefined, done: true, errors: [], + }); + expect(assessFeature({ + source: 'anthropic_messages', target: 'chat_completions', direction: 'return_response', feature: 'reasoning_content', + }).status).toBe('unknown'); + expect(assessFeature({ + source: 'anthropic_messages', target: 'chat_completions', direction: 'return_response', feature: 'initial_tool_input', + }).status).toBe('unknown'); + }); + + test.each(streams.gaps)('$name', async fixture => { + const frames = parseFrames(await collectStream(fixture.contract, fixture.input, 1)); + expect(summarize(frames).calls).toEqual(fixture.calls); + }); + + test('Chat return treats comment-only frames as completion; comments are not declared supported', async () => { + const frames = parseFrames(await collectStream('chat-to-responses-return', ': ping\n\n', 1)); + expect(frames.find(event => event.type === 'response.completed').response.status).toBe('completed'); + expect(assessFeature({ + source: 'chat_completions', target: 'responses', direction: 'return_response', feature: 'sse_comments', + }).status).toBe('unknown'); + }); + + test('Responses response.incomplete is currently ignored, not a supported completion event', async () => { + const input = streams.frame({ + type: 'response.incomplete', + response: { status: 'incomplete', incomplete_details: { reason: 'max_output_tokens' } }, + }); + expect(await collectStream('responses-to-chat-return', input, 1)).toBe(''); + expect(assessFeature({ + source: 'responses', target: 'chat_completions', direction: 'return_response', feature: 'response.incomplete', + }).status).toBe('unknown'); + }); +}); + +describe('executable request fixtures', () => { + test.each(requests.cases)('$name', fixture => { + const translate = requestTranslator(fixture.contract); + const input = deepFreeze(structuredClone(fixture.input)); + const before = JSON.stringify(input); + if (fixture.error) { + let error; + try { translate(input); } catch (caught) { error = caught; } + expect(error).toMatchObject(fixture.error); + expect(error.name).toBe(fixture.error.code === 'unsupported_wire_api_feature' + ? 'WireApiCompatibilityError' : 'ProtocolTranslationError'); + } else { + expect(translate(input)).toEqual(fixture.output); + } + expect(JSON.stringify(input)).toBe(before); + const contract = CONTRACTS.find(candidate => candidate.id === fixture.contract); + for (const feature of fixture.features) { + const assessment = assessFeature({ ...contract, feature }); + expect(assessment.evidence).not.toBeNull(); + expect(assessment.status).not.toBe('unknown'); + if (assessment.status === 'rejected') { + expect(fixture.error?.code).toBe(assessment.evidence.rejectionCode); + } + } + }); + + describe('executable JSON return and usage fixtures', () => { + beforeEach(() => jest.spyOn(Date, 'now').mockReturnValue(responses.created * 1000)); + afterEach(() => jest.restoreAllMocks()); + + test.each(responses.cases)('$name', fixture => { + const body = Buffer.from(JSON.stringify(fixture.input)); + const before = Buffer.from(body); + expect(JSON.parse(responseTranslator(fixture.contract, body))).toEqual(fixture.output); + expect(body).toEqual(before); + }); + + test.each(['not-json', 'null', '[]', '{}', '{"error":{"code":"fixture_error"}}'])( + 'malformed/error JSON is not a success-shaped adaptation: %s', input => { + for (const contract of CONTRACTS.filter(candidate => candidate.direction === 'return_response')) { + expect(responseTranslator(contract.id, Buffer.from(input))).toBeNull(); + } + }); + + test('direct Messages usage retains cache read/write counting and missing-counter defaults', () => { + expect(anthropic.anthropicUsageToChat({ + input_tokens: 5, output_tokens: 4, cache_read_input_tokens: 3, cache_creation_input_tokens: 2, + })).toEqual({ prompt_tokens: 10, completion_tokens: 4, total_tokens: 14, prompt_tokens_details: { cached_tokens: 3 } }); + expect(anthropic.anthropicUsageToChat({})).toEqual({ prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 }); + expect(anthropic.anthropicUsageToChat(null)).toBeUndefined(); + }); + + test('every declared return feature has executing JSON/SSE evidence', () => { + for (const contract of CONTRACTS.filter(candidate => candidate.direction === 'return_response')) { + for (const row of contract.features.filter(candidate => candidate.status !== 'unknown')) { + const evidence = [...responses.cases, ...streams.cases].filter(fixture => + fixture.contract === contract.id && fixture.features.includes(row.feature)); + expect({ id: contract.id, feature: row.feature, covered: evidence.length > 0 }) + .toEqual({ id: contract.id, feature: row.feature, covered: true }); + } + } + }); + }); + + describe('executable SSE return fixtures', () => { + beforeEach(() => jest.spyOn(Date, 'now').mockReturnValue(responses.created * 1000)); + afterEach(() => jest.restoreAllMocks()); + + test.each(streams.cases)('$name (UTF-8, CRLF and final-frame boundaries)', async fixture => { + for (const chunkSize of [1, 7, 65536]) { + // Final complete frames need not end in a blank line; flush must still process them. + const input = fixture.input.replace(/\n/g, '\r\n').replace(/\r\n\r\n$/, ''); + const output = await collectStream(fixture.contract, input, chunkSize, fixture.includeUsage); + const frames = parseFrames(output); + expect(summarize(frames)).toEqual(fixture.summary); + if (fixture.contract === 'chat-to-responses-return' && fixture.summary.done) { + expect(frames.filter(event => event.type === 'response.completed')).toHaveLength(1); + expect(frames.filter(event => event.type === 'response.function_call_arguments.done').map(event => event.arguments)) + .toEqual(['{"q":"x"}', '{}']); + } else if (fixture.summary.done) { + expect(frames.filter(event => event === '[DONE]')).toHaveLength(1); + } + } + }); + + test.each(['responses-to-chat-return', 'messages-to-chat-return'])( + '%s only emits usage when explicitly requested', async id => { + const fixture = streams.cases.find(candidate => candidate.contract === id && candidate.summary.done); + const frames = parseFrames(await collectStream(id, fixture.input, 5, false)); + expect(frames.some(event => event.usage)).toBe(false); + expect(summarize(frames)).toEqual({ ...fixture.summary, usage: undefined }); + }); + + test.each(['chat-to-responses-return', 'responses-to-chat-return', 'messages-to-chat-return'])( + '%s does not synthesize completion at EOF', async id => { + const event = id === 'chat-to-responses-return' ? streams.chatFrames[0] + : id === 'responses-to-chat-return' ? streams.responsesFrames[0] : streams.anthropicFrames[0]; + const frames = parseFrames(await collectStream(id, streams.frame(event), 1)); + expect(summarize(frames).done).toBe(false); + expect(summarize(frames).finish).toBeNull(); + }); + + test.each(['responses-to-chat-return', 'messages-to-chat-return'])( + '%s ignores unknown/malformed frames, without implying feature support', async id => { + const malformed = 'data: {partial-json\n\n'; + const unknown = streams.frame({ type: 'future_event', private_field: 'fixture' }); + expect(await collectStream(id, malformed + unknown, 1)).toBe(''); + const contract = CONTRACTS.find(candidate => candidate.id === id); + expect(assessFeature({ ...contract, feature: 'future_event' }).status).toBe('unknown'); + }); + + test('Chat return preserves malformed SSE bytes rather than declaring them translated', async () => { + const malformed = 'data: {partial-json\n\n'; + expect(await collectStream('chat-to-responses-return', malformed, 1)).toBe(malformed); + }); + + test.each([ + ['chat-to-responses-return', 'length', 'length'], + ['chat-to-responses-return', 'content_filter', 'content_filter'], + ['responses-to-chat-return', 'max_output_tokens', 'length'], + ['responses-to-chat-return', 'content_filter', 'content_filter'], + ['messages-to-chat-return', 'max_tokens', 'length'], + ['messages-to-chat-return', 'model_context_window_exceeded', 'length'], + ['messages-to-chat-return', 'refusal', 'content_filter'], + ])('%s SSE preserves characterized terminal outcome %s', async (id, reason, finish) => { + const input = id === 'chat-to-responses-return' + ? streams.frame({ choices: [{ delta: { content: 'hello' }, finish_reason: reason }] }) + 'data: [DONE]\n\n' + : id === 'responses-to-chat-return' + ? streams.frame({ type: 'response.completed', response: { status: 'incomplete', incomplete_details: { reason }, output: [] } }) + : streams.frame({ type: 'message_delta', delta: { stop_reason: reason } }) + streams.frame({ type: 'message_stop' }); + const result = summarize(parseFrames(await collectStream(id, input, 1))); + expect(result.finish).toBe(finish); + expect(result.done).toBe(true); + }); + }); + + test('each declared request feature has executable evidence, including actual rejection codes', () => { + for (const contract of CONTRACTS.filter(candidate => candidate.direction === 'request')) { + for (const row of contract.features.filter(candidate => candidate.status !== 'unknown')) { + const evidence = requests.cases.filter(fixture => fixture.contract === contract.id && fixture.features.includes(row.feature)); + expect({ id: contract.id, feature: row.feature, covered: evidence.length > 0 }) + .toEqual({ id: contract.id, feature: row.feature, covered: true }); + if (row.status === 'supported' || row.status === 'conditional') { + expect(evidence.some(fixture => !fixture.error)).toBe(true); + } else { + expect(evidence.some(fixture => fixture.error?.code === row.rejectionCode)).toBe(true); + } + } + } + }); + + test('outer wire adapter retains requested usage separately without using discovery facts', () => { + const input = { ...requests.chat, stream: true, stream_options: { include_usage: true } }; + const result = wire.translateCopilotWireApi(Buffer.from(JSON.stringify(input)), '/v1/chat/completions', { upstreamEndpoint: '/responses' }); + expect(JSON.parse(result.body)).toEqual(wire.translateChatRequest(input)); + expect(result.compatibility).toEqual({ + requestedEndpoint: '/chat/completions', upstreamEndpoint: '/responses', + direction: 'chat_to_responses', includeUsage: true, + }); + }); + + test.each(['not-json', 'null', '[]', '{}', '{"model":42}', '{"model":"fixture-model","input":"hello"}'])( + 'malformed/inapplicable wire input stays a null adaptation, not a support verdict: %s', body => { + expect(wire.translateCopilotWireApi(Buffer.from(body), '/chat/completions')).toBeNull(); + }); + + test('same-protocol return passthrough never creates a translator or support evidence', () => { + const body = Buffer.from('{"future_feature":true}'); + expect(wire.transformWireApiResponseBody(body, { passthrough: true })).toBeNull(); + expect(wire.createWireApiSseTransform({ passthrough: true })).toBeNull(); + expect(wire.transformWireApiResponseBody(body, null)).toBeNull(); + expect(wire.createWireApiSseTransform(null)).toBeNull(); + expect(wire.translateCopilotWireApi(body, '/unimplemented')).toBeNull(); + }); + + test.each([ + ['chat-to-responses-request', { messages: null }, 'messages'], + ['responses-to-chat-request', { input: null }, 'input'], + ['chat-to-messages-request', null, 'body'], + ['chat-to-messages-request', { messages: [null] }, 'messages'], + ])('malformed direct input: %s', (id, input, feature) => { + expect(() => requestTranslator(id)(input)).toThrow(); + try { requestTranslator(id)(input); } catch (error) { expect(error.feature).toBe(feature); } + }); +}); diff --git a/containers/api-proxy/protocol-compatibility/index.d.ts b/containers/api-proxy/protocol-compatibility/index.d.ts new file mode 100644 index 000000000..6c005c145 --- /dev/null +++ b/containers/api-proxy/protocol-compatibility/index.d.ts @@ -0,0 +1,48 @@ +export type Protocol = 'chat_completions' | 'responses' | 'anthropic_messages'; +export type TranslationDirection = 'request' | 'return_response'; +export type CompatibilityStatus = 'supported' | 'conditional' | 'rejected' | 'unknown'; +export type Feature = + | 'message_text' | 'message_roles' | 'function_tools' | 'hosted_tools' | 'tool_choice' + | 'parallel_tool_calls' | 'structured_output' | 'image_input' | 'audio' + | 'other_modalities' | 'streaming' | 'usage' | 'stateful_fields' | 'reasoning_fields' + | 'reasoning_content' | 'cache_controls' | 'token_limits' | 'transport_fields' + | 'finish_reasons' | 'refusal' | 'unknown_fields'; + +export interface FeatureEvidence { + readonly feature: Feature; + readonly status: CompatibilityStatus; + readonly conditions: readonly string[]; + readonly normalizations: readonly string[]; + readonly reason: string; + readonly rejectionCode?: 'unsupported_wire_api_feature' | 'unsupported_protocol_feature'; +} + +export interface DirectedContract { + readonly id: string; + readonly source: Protocol; + readonly target: Protocol; + readonly direction: TranslationDirection; + readonly revision: string; + readonly implementation: Readonly<{ file: string; sha256: string }>; + readonly entryPoints: readonly string[]; + readonly features: readonly FeatureEvidence[]; +} + +export interface FeatureAssessment { + readonly revision: string; + readonly status: CompatibilityStatus; + readonly reason: string; + readonly contract: DirectedContract | null; + readonly evidence: FeatureEvidence | null; +} + +export const REVISION: string; +export const FEATURES: readonly Feature[]; +export const CONTRACTS: readonly DirectedContract[]; +/** Bounded feature evidence only. No request validation, routing or model discovery. */ +export function assessFeature(query?: Readonly<{ + source: Protocol; + target: Protocol; + direction: TranslationDirection; + feature: string; +}>): FeatureAssessment; diff --git a/containers/api-proxy/protocol-compatibility/index.js b/containers/api-proxy/protocol-compatibility/index.js new file mode 100644 index 000000000..cd13b2e7c --- /dev/null +++ b/containers/api-proxy/protocol-compatibility/index.js @@ -0,0 +1,248 @@ +'use strict'; + +/** + * Feature-level evidence, not a whole-request validator or model capability list. + * Conditions must be checked by a future consumer before using conditional rows. + * Never infer a reverse request direction from a return-response contract. + */ +const REVISION = 'awf-directed-protocol-v1'; +const FEATURES = Object.freeze([ + 'message_text', 'message_roles', 'function_tools', 'hosted_tools', 'tool_choice', + 'parallel_tool_calls', 'structured_output', 'image_input', 'audio', + 'other_modalities', 'streaming', 'usage', 'stateful_fields', 'reasoning_fields', + 'reasoning_content', 'cache_controls', 'token_limits', 'transport_fields', + 'finish_reasons', 'refusal', 'unknown_fields', +]); + +const IMPLEMENTATIONS = Object.freeze({ + wire: Object.freeze({ + file: 'wire-api-compat.js', + sha256: '99195a2687352cbb4c65aaa1c31b7f630f71ed1d0a3647638092e3a1e5676125', + }), + anthropic: Object.freeze({ + file: 'anthropic-chat-compat.js', + sha256: '47e879c966fca727e6a483649366a60f77e354adbeeede11b3c0c8b6853c0f2b', + }), +}); + +function conditional(conditions, normalizations, reason) { + return { status: 'conditional', conditions, normalizations, reason }; +} + +function supported(reason) { + return { status: 'supported', conditions: [], normalizations: [], reason }; +} + +function rejected(reason, rejectionCode) { + return { status: 'rejected', conditions: [], normalizations: [], reason, rejectionCode }; +} + +const wireReject = reason => rejected(reason, 'unsupported_wire_api_feature'); +const anthropicReject = reason => rejected(reason, 'unsupported_protocol_feature'); +const wireRequests = { + message_text: supported('String text is retained; this does not cover arbitrary content objects.'), + function_tools: conditional( + ['Function definitions and calls use known fields, nonempty names and call identifiers.'], + ['Function tool nesting changes; call IDs are retained; non-string results are JSON encoded.'], + 'Function schemas and strict flags are forwarded, not validated against a backend.'), + hosted_tools: wireReject('Non-function tool types cannot be translated.'), + tool_choice: conditional( + ['Choice is auto, none, required, or a named function choice without extra fields.'], + ['Named function choice nesting changes.'], + 'Known function choices are representable; arbitrary choice objects are not characterized.'), + parallel_tool_calls: supported('The parallel_tool_calls boolean is forwarded without changing it.'), + structured_output: conditional( + ['Format is json_object or json_schema with name, schema and optional strict only.'], + ['JSON schema format nesting changes.'], + 'Schema and strict are forwarded; schema validity and model enforcement are not established.'), + image_input: conditional( + ['Image parts have a URL and optional detail, with no additional semantic fields.'], + ['image_url and input_image representations change; URL and detail are retained.'], + 'Only URL image input is characterized, not image output or backend image support.'), + audio: wireReject('Audio request fields and audio content parts have no mapping.'), + other_modalities: wireReject('Non-text/non-image request content types have no mapping.'), + streaming: supported('The stream boolean is forwarded; return-stream behavior has a separate contract.'), + stateful_fields: wireReject('Stateful requests, storage and nonempty response metadata/include/truncation cannot be represented.'), + reasoning_fields: conditional( + ['Only the opaque effort field is present; Responses reasoning has no summary or encrypted content.'], + ['reasoning.effort and reasoning_effort change nesting without changing the value.'], + 'No model-specific effort support, default or reasoning decision is inferred.'), + reasoning_content: wireReject('Reasoning content items cannot be represented in translated requests.'), + token_limits: conditional( + ['Limits are positive integer values supplied by the caller.'], + ['Chat max_completion_tokens takes precedence over max_tokens; wire limit names change.'], + 'Wire translation does not validate limit ranges or insert a limit.'), + unknown_fields: wireReject('Unknown top-level request fields are rejected, including null or false values.'), +}; + +const wireReturns = { + message_text: supported('Known text output is retained in an assistant message.'), + function_tools: conditional( + ['JSON function calls have names, identifiers and nonempty string arguments; Messages JSON inputs are objects.', + 'Responses-to-Chat SSE function calls have no nonempty initial arguments; all argument text arrives in delta frames.', + 'Chat-to-Responses SSE function-call arguments arrive in Chat deltas.'], + ['Function call nesting changes; IDs and argument strings are retained.'], + 'Empty JSON arguments default to {}; Responses SSE drops nonempty initial arguments and ignores final items. Other output item kinds and arbitrary nested fields are not covered.'), + streaming: conditional( + ['Recognized SSE frames are well formed and include an explicit completion trigger.', + 'Chat uses choice deltas plus terminal usage-only/DONE; Responses uses created/in_progress, text/refusal/function deltas and completed/failed/error, not response.incomplete.'], + ['Frames are buffered across UTF-8 chunks; tool arguments are assembled or emitted as deltas.'], + 'EOF alone does not complete a response; errors are forwarded without synthetic success.'), + usage: conditional( + ['Known token counters are nonnegative and total_tokens, when provided, is coherent.', + 'Responses-to-Chat SSE requires includeUsage=true; Chat-to-Responses SSE requires a terminal usage-only chunk before DONE.'], + ['Input/output names change; cached and reasoning token details are retained.'], + 'Missing counters default to zero; this is usage adaptation, not pricing or accounting-family compatibility.'), + finish_reasons: conditional( + ['One choice/output sequence uses the characterized stop, tool_calls, length or content_filter outcomes.'], + ['Length/content_filter become incomplete status; return Chat tool calls take precedence over incomplete status.'], + 'Unknown finish reasons and additional choices are not claimed faithful.'), + refusal: conditional( + ['JSON contains at most one refusal string/part; SSE uses recognized refusal deltas.'], + ['Refusal changes between a Chat field and a Responses content part.'], + 'Known refusal text is retained; arbitrary refusal metadata is not covered.'), +}; + +const anthropicRequests = { + message_text: conditional( + ['Content consists of strings or known text parts; null/empty content is allowed.'], + ['Text becomes blocks; empty messages are omitted.'], + 'Text values are retained, but turn boundaries can change.'), + message_roles: conditional( + ['Only system, developer, user, assistant and tool roles with known fields are used.'], + ['System/developer text is joined with two newlines; consecutive same-role turns merge; tool results become user blocks.'], + 'Role priority and turn boundaries are not preserved losslessly.'), + function_tools: conditional( + ['Known function fields, IDs and object-valued JSON arguments are used; no extra semantic fields.'], + ['Arguments are parsed as JSON objects; missing arguments become {}; missing schema becomes an empty object schema.'], + 'Strict function flags are forwarded, not a claim of native structured-output enforcement.'), + hosted_tools: anthropicReject('Non-function tool definitions have no mapping.'), + tool_choice: conditional( + ['Choices are auto, none, required or a named function; required/named choices require nonempty tools.'], + ['required becomes any; named function becomes tool; auto/none without tools are omitted.'], + 'Other choices are rejected.'), + parallel_tool_calls: conditional( + ['Value is boolean; false with tools and a choice other than none disables parallel tool use.'], + ['false adds disable_parallel_tool_use; true leaves the upstream default in place.'], + 'Explicit parallel enablement is not guaranteed; none does not gain a disable flag.'), + structured_output: anthropicReject('json_schema/json_object response_format has no request mapping; text format is a no-op.'), + image_input: conditional( + ['Image URL is HTTPS or a base64 data URL; no detail, cache control or additional semantic fields.'], + ['URL images become source.url; base64 images split media type and data.'], + 'Image detail is otherwise discarded by the existing translator, not preserved.'), + audio: anthropicReject('Audio fields and audio content parts have no mapping.'), + other_modalities: anthropicReject('Non-text/non-image content parts have no mapping.'), + streaming: conditional( + ['stream is boolean.'], + ['Only true is emitted; false is omitted.'], + 'Streaming intent is mapped; return SSE has its own contract.'), + stateful_fields: anthropicReject('Non-null previous_response_id/store requests have no mapping.'), + reasoning_fields: anthropicReject('Non-null reasoning_effort/reasoning request fields have no mapping.'), + reasoning_content: anthropicReject('Reasoning content parts cannot be translated.'), + token_limits: conditional( + ['Caller accepts the required Messages limit and supplies a positive integer if overriding it.'], + ['max_completion_tokens takes precedence; missing, nonpositive or noninteger limits become 8192.'], + 'Default insertion changes an unspecified/invalid Chat limit; it is not transport-only.'), + transport_fields: conditional( + ['Only stream_options.include_usage, n=1, logprobs=false and response_format.type=text are used.'], + ['stream_options is dropped; n=1, logprobs=false and text format are no-ops.'], + 'Return usage must be requested separately on the SSE adapter; unknown stream options are not characterized.'), + unknown_fields: { + ...anthropicReject('Non-null unknown top-level fields are rejected; nested-field acceptance does not establish compatibility.'), + conditions: ['The unmapped top-level field has a non-null value.'], + normalizations: ['Unmapped null/undefined values are skipped, not declared supported.'], + }, +}; + +const anthropicReturns = { + message_text: supported('Known text blocks concatenate into assistant text.'), + function_tools: conditional( + ['Output contains known tool_use blocks with IDs, names and object inputs.', + 'SSE initial tool_use.input is empty; arguments are supplied through subsequent input_json_delta frames.'], + ['Tool input objects become JSON argument strings; SSE arguments arrive as partial_json deltas.'], + 'Initial SSE tool_use.input is not emitted; nonempty initial input is an uncharacterized gap.'), + streaming: conditional( + ['Recognized frames include message_stop; tool starts precede argument deltas.'], + ['UTF-8 frames are buffered; message_stop emits finish and DONE; errors do not emit success.'], + 'EOF does not synthesize completion; unknown or malformed JSON frames are ignored.'), + usage: conditional( + ['Known counters are nonnegative; SSE includeUsage is explicitly enabled when needed.'], + ['Cache reads and writes join input_tokens in prompt_tokens; cached_tokens reports reads only.'], + 'Missing counters default to zero; cache-write detail is not separately representable in Chat usage.'), + finish_reasons: conditional( + ['Stop reason is end_turn, stop_sequence, tool_use, max_tokens, model_context_window_exceeded or refusal.'], + ['tool_use becomes tool_calls; token/context limits become length; refusal becomes content_filter; other known stops become stop.'], + 'Unknown stop reasons default to stop and are not claimed faithful.'), +}; + +function contract(id, source, target, direction, implementation, entryPoints, specifications) { + const features = FEATURES.map(feature => { + const spec = specifications[feature] || { + status: 'unknown', conditions: [], normalizations: [], + reason: 'This feature has not been characterized for this direction.', + }; + return Object.freeze({ + feature, ...spec, + conditions: Object.freeze(spec.conditions), + normalizations: Object.freeze(spec.normalizations), + }); + }); + return Object.freeze({ + id, source, target, direction, revision: REVISION, implementation, + entryPoints: Object.freeze(entryPoints), features: Object.freeze(features), + }); +} + +const CONTRACTS = Object.freeze([ + contract('chat-to-responses-request', 'chat_completions', 'responses', 'request', + IMPLEMENTATIONS.wire, ['translateChatRequest'], { + ...wireRequests, + message_roles: conditional( + ['Known Chat roles; system/developer content is string-only.'], + ['System/developer messages become joined instructions; priority and placement are collapsed.'], + 'Role collapse is a semantic alteration, not lossless transport normalization.'), + transport_fields: conditional( + ['n is omitted or 1; stream_options contains only boolean include_usage.'], + ['n=1 and stream_options are omitted from the translated request.'], + 'The outer wire adapter retains include_usage for the return path.'), + }), + contract('responses-to-chat-request', 'responses', 'chat_completions', 'request', + IMPLEMENTATIONS.wire, ['translateResponsesRequest'], { + ...wireRequests, + message_roles: conditional( + ['Known Responses message roles; instructions is a string.'], + ['Instructions prepend a system message; missing role defaults to user; item id/status are omitted.'], + 'Item IDs/status are transport metadata; function call_id remains semantic and is retained.'), + transport_fields: conditional( + ['store is false/absent; stateful metadata/include/truncation/cache key are absent, null or false.'], + ['No-op fields are omitted; stream=true inserts stream_options.include_usage=true.'], + 'Nonempty stateful fields and store=true are rejected.'), + }), + contract('chat-to-messages-request', 'chat_completions', 'anthropic_messages', 'request', + IMPLEMENTATIONS.anthropic, ['chatRequestToAnthropic'], anthropicRequests), + contract('chat-to-responses-return', 'chat_completions', 'responses', 'return_response', + IMPLEMENTATIONS.wire, ['transformWireApiResponseBody', 'createWireApiSseTransform'], wireReturns), + contract('responses-to-chat-return', 'responses', 'chat_completions', 'return_response', + IMPLEMENTATIONS.wire, ['transformWireApiResponseBody', 'createWireApiSseTransform'], wireReturns), + contract('messages-to-chat-return', 'anthropic_messages', 'chat_completions', 'return_response', + IMPLEMENTATIONS.anthropic, + ['anthropicResponseToChat', 'anthropicUsageToChat', 'createAnthropicToChatSseTransform'], anthropicReturns), +]); + +function assessFeature(query = {}) { + const { source, target, direction, feature } = query || {}; + const match = CONTRACTS.find(candidate => + candidate.source === source && candidate.target === target && candidate.direction === direction); + const evidence = match?.features.find(candidate => candidate.feature === feature); + return Object.freeze({ + revision: REVISION, + status: evidence?.status || 'unknown', + reason: evidence?.reason || (match + ? 'This feature has not been characterized.' + : 'No directed translation contract is implemented for this pair.'), + contract: evidence ? match : null, + evidence: evidence || null, + }); +} + +module.exports = { REVISION, FEATURES, CONTRACTS, assessFeature }; diff --git a/containers/api-proxy/wire-api-compat.js b/containers/api-proxy/wire-api-compat.js index 913139975..45d2189ba 100644 --- a/containers/api-proxy/wire-api-compat.js +++ b/containers/api-proxy/wire-api-compat.js @@ -775,6 +775,7 @@ module.exports = { WireApiCompatibilityError, endpointForPath, translateCopilotWireApi, + translateChatRequest, translateResponsesRequest, replaceUpstreamEndpoint, transformWireApiResponseBody, diff --git a/docs/api-proxy-sidecar.md b/docs/api-proxy-sidecar.md index 6bc9d7f93..92a374cf3 100644 --- a/docs/api-proxy-sidecar.md +++ b/docs/api-proxy-sidecar.md @@ -40,6 +40,169 @@ conclusion, or safe outputs; gh-aw must implement that per-job exchange. The `--enable-api-proxy` CLI flag is deprecated and ignored — it is kept only so existing command lines and workflows continue to work. `--no-enable-api-proxy` is rejected as a runtime error; the API proxy cannot be disabled. Do not add the deprecated flag to new commands. ::: +## Directed translator compatibility contracts + +The dependency-free [protocol contract module](../containers/api-proxy/protocol-compatibility/index.js) +and its [TypeScript declarations](../containers/api-proxy/protocol-compatibility/index.d.ts) +describe **translator features, not native model capabilities or candidate availability**. +They are shipped in the API proxy's `/app/protocol-compatibility/` directory. +Endpoint advertisement, accounting families, model names and opposite-direction success +are not evidence of compatibility. + +### Directions and revision + +`CONTRACTS` enumerates these directions only: + +| Source | Target | Direction | Actual boundary | +|---|---|---|---| +| Chat Completions | Responses | request | `translateChatRequest` | +| Responses | Chat Completions | request | `translateResponsesRequest` | +| Chat Completions | Anthropic Messages | request | `chatRequestToAnthropic` | +| Chat Completions | Responses | return_response | Wire JSON/SSE adapters | +| Responses | Chat Completions | return_response | Wire JSON/SSE adapters | +| Anthropic Messages | Chat Completions | return_response | Messages JSON/usage/SSE adapters | + +**Messages request → Chat request is not implemented.** A return adapter cannot +establish that reverse request direction. Composed paths are not additional contracts. +Same-protocol passthrough is also not a translation-support verdict: the existing +wire boundaries return `null` when no adaptation applies, leaving the original +body/stream to the caller. + +Contract revision: `awf-directed-protocol-v1`. Each contract pins its implementation +bytes using SHA-256: + +- `wire-api-compat.js`: `99195a2687352cbb4c65aaa1c31b7f630f71ed1d0a3647638092e3a1e5676125` +- `anthropic-chat-compat.js`: `47e879c966fca727e6a483649366a60f77e354adbeeede11b3c0c8b6853c0f2b` + +The revision test fails when either translator changes. Re-characterize affected +fixtures and conditions, update the implementation pin, and revise the contract +revision when its meaning changes; do not merely update hashes to silence drift. + +### Bounded feature matrix + +S = supported representation; C = conditional, including stated semantic +normalizations/defaults; R = existing rejection for active feature shapes; +U = unknown/uncharacterized, **not success**. These are not whole-protocol or +lossless-path ratings. The executable module supplies each row's conditions, +normalizations, sanitized reason and rejection code where applicable. + +| Feature identifier | Chat→Responses request | Responses→Chat request | Chat→Messages request | Wire return paths | Messages→Chat return | +|---|---|---|---|---|---| +| `message_text` | S | S | C | S | S | +| `message_roles` | C | C | C | U | U | +| `function_tools` | C | C | C | C | C | +| `hosted_tools` | R | R | R | U | U | +| `tool_choice` | C | C | C | U | U | +| `parallel_tool_calls` | S | S | C | U | U | +| `structured_output` | C | C | R | U | U | +| `image_input` | C | C | C | U | U | +| `audio` | R | R | R | U | U | +| `other_modalities` | R | R | R | U | U | +| `streaming` | S | S | C | C | C | +| `usage` | U | U | U | C | C | +| `stateful_fields` | R | R | R | U | U | +| `reasoning_fields` | C | C | R | U | U | +| `reasoning_content` | R | R | R | U | U | +| `cache_controls` | U | U | U | U | U | +| `token_limits` | C | C | C | U | U | +| `transport_fields` | C | C | C | U | U | +| `finish_reasons` | U | U | U | C | C | +| `refusal` | U | U | U | C | U | +| `unknown_fields` | R | R | R | U | U | + +Important conditions and defaults: + +- Function calls/results retain semantic call identifiers. Known schemas and + strict flags are forwarded; this does not prove native strict-schema enforcement. + Messages parses object-valued argument JSON and defaults missing arguments/schema. +- Chat system/developer messages collapse into joined wire instructions or a + Messages system string. Messages also merges consecutive roles and omits empty + turns. These change priority/turn structure; they are **not lossless**. +- Wire limits change field names without range validation or default insertion. + `max_completion_tokens` takes precedence over `max_tokens`. Messages inserts + `8192` for absent, nonpositive or noninteger limits; this is semantic defaulting. +- Wire `stream_options.include_usage` is transport intent retained separately by + the outer adapter. Responses streaming inserts upstream `include_usage=true`. + Messages drops `stream_options`; its return SSE adapter must separately receive + `includeUsage`. Unknown nested stream options are not declared supported. + Responses→Chat SSE usage also requires `includeUsage=true`; Chat→Responses SSE + needs a terminal usage-only chunk before `DONE`. +- `n=1`, explicit text output for Messages, and disabled logprobs for Messages + are no-ops. Responses `store=false` and null/false stateful sentinels are omitted; + `store=true` and active stateful fields are rejected. Empty arrays/objects are + not the same as null/false for wire rejection. + Messages rejects non-null unknown top-level fields but skips null/undefined + values; this skip is not evidence of unknown-feature support. +- Messages maps required tool choice to `any`; required/named choices need tools. + Parallel `false` adds `disable_parallel_tool_use` except with `none`; + `true` leaves the upstream default, not guaranteed enablement. +- Only URL/detail wire images and detail-free HTTPS/base64 Messages images are + characterized. Audio/video and other content types are rejected on requests. +- Wire effort values move opaquely between fields. No effort validity, defaults + or model-specific reasoning support is inferred. Messages rejects active reasoning + fields. Reasoning token usage adaptation does not establish reasoning-content support. +- Known finish reasons map to completion/incomplete outcomes. Return Chat function + calls take precedence over incomplete status. Messages cache reads/writes join + prompt tokens, but cached-token detail reports reads only. + +### Known gaps and consumer handoff + +[Executable discrepancy fixtures](../containers/api-proxy/fixtures/protocol-compatibility/gaps.js) +preserve pre-existing behavior without calling it lossless: + +- Messages silently clamps out-of-range temperature, filters non-string stop + entries, appends assistant refusal as ordinary text, and discards image detail, + cache controls and unknown nested fields. +- Wire nested validation is uneven: unknown outer Chat tool fields can disappear; + Responses output-text annotations and schema-format descriptions disappear. + Invalid content objects/limit values can also pass without a schema validation. +- JSON return paths ignore unknown output/reasoning fields; Chat uses only the + first choice. Messages ignores thinking/signatures and defaults unknown stop + reasons to `stop`. Responses→Chat JSON keeps only the last of multiple refusal + parts; only a single JSON refusal part is characterized as retained. + Annotation and richer refusal semantics are not established. +- Wire JSON return adapters replace empty function arguments with `{}`. + Responses→Chat SSE drops nonempty arguments on `response.output_item.added` + and ignores final function-call items; only argument deltas are forwarded. +- Messages SSE emits argument deltas but loses nonempty initial `tool_use.input`. + Reasoning/signature and unknown events are ignored. +- EOF alone does not synthesize completion. Messages/Responses malformed SSE JSON + is ignored; Chat malformed SSE is returned verbatim. A comment-only Chat frame + currently triggers completion. SSE comments and unknown future frames are not + declared compatible. Responses `response.incomplete` is currently ignored; + only `response.completed` with an incomplete status has a characterized + incomplete-completion mapping. + +These discrepancies require separately reviewed enforcement/translation follow-up +under [Phase 6 #10296](https://github.com/github/gh-aw-firewall/issues/10296). +This slice does not fix or expand translation behavior. + +`assessFeature({ source, target, direction, feature })` returns frozen feature +evidence, not `compatible: true` or a request-level eligibility decision. It accepts +no request/model catalogue and never dispatches inference, discovers providers, +selects models or consumes budget. Unknown feature identifiers and unimplemented +directions return `unknown` with fixed reasons that do not echo caller data. +Future consumers must extract **all** semantic requirements (including nested +fields), independently verify conditions and reject/withhold unknown support. +Successful translation alone cannot replace those checks. + +Fallback filtering remains unwired; `/reflect` integration remains tracked by +[#11322](https://github.com/github/gh-aw-firewall/issues/11322) / +[#11323](https://github.com/github/gh-aw-firewall/pull/11323). +This module does not replace [shared reasoning #11319](https://github.com/github/gh-aw-firewall/issues/11319) / +[#11320](https://github.com/github/gh-aw-firewall/pull/11320). +Compiler/standalone package distribution and additional runtime consumers are +deferred to a coordinated additive handoff; no CLI or reflection endpoint is added. +The provider-free packaging test stages the actual sidecar Docker `COPY` layout, +not a container/VM or live provider call. + +With root dev tooling installed (also needed by the existing npm-package smoke), +run the characterization and existing translator suites from `containers/api-proxy`: +`npm test -- --runInBand protocol-compatibility wire-api-compat anthropic-chat-compat`. +The compile-only fixture `fixtures/protocol-compatibility/contract-types.ts` +is checked by the packaging suite and can also be checked with the repository's TypeScript compiler using +`--noEmit --strict --skipLibCheck --target ES2020 --module Node16 --moduleResolution Node16`. + ## Architecture ```