Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat(gateway): serve the Anthropic Messages API on /v1/messages (#753)
Krisztian Gajdar1f9e0ff648b0
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex c03f6cc1b..7c9ca57e0 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -87,6 +87,13 @@ jobs:mise exec -- uv run --frozen ruff format --check .mise exec -- uv run --frozen ruff check .mise exec -- uv run --frozen pytest -q+ - name: Claude Code example gate+ working-directory: examples/coding-agent-claude-code+ run: |+ mise exec -- uv lock --check+ mise exec -- uv run --frozen ruff format --check .+ mise exec -- uv run --frozen ruff check .+ mise exec -- uv run --frozen pytest -q- name: Pinned collector privacyrun: |mise run helm -- dependenciesdiff --git a/conformance/anthropic_messages/claude_code_requests.json b/conformance/anthropic_messages/claude_code_requests.jsonnew file mode 100644index 000000000..275a1c4f5--- /dev/null+++ b/conformance/anthropic_messages/claude_code_requests.json@@ -0,0 +1,7066 @@+{+ "client": "Claude Code 2.1.300",+ "recorded": "headless runs (claude -p) against a local stub that answered canned Messages replies; no model was called",+ "scrubbed": "client-written text, tool descriptions and schema annotations are placeholders; ids, paths and credentials are replaced",+ "setups": {+ "recipe": "the recipe environment, Bearer credential through ANTHROPIC_AUTH_TOKEN",+ "bare": "claude --bare with an apiKeyHelper, which sends the same credential as Authorization: Bearer and x-api-key",+ "without_recipe": "ANTHROPIC_AUTH_TOKEN only, without CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS"+ },+ "cases": [+ {+ "name": "first_turn",+ "setup": "recipe",+ "path": "/v1/messages?beta=true",+ "headers": {+ "anthropic-version": "2023-06-01",+ "anthropic-beta": "claude-code-20250219,interleaved-thinking-2025-05-14,effort-2025-11-24",+ "anthropic-dangerous-direct-browser-access": "true",+ "authorization": "Bearer (token)",+ "x-app": "cli",+ "x-claude-code-session-id": "(session id)",+ "content-type": "application/json",+ "accept": "application/json",+ "user-agent": "claude-cli/2.1.300 (external, sdk-cli)",+ "x-stainless-lang": "js",+ "x-stainless-package-version": "0.128.0",+ "x-stainless-retry-count": "0",+ "x-stainless-timeout": "600"+ },+ "body": {+ "model": "zai-org/GLM-5.3-Flash:relay",+ "messages": [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 1)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "(user prompt)",+ "cache_control": {+ "type": "ephemeral"+ }+ }+ ]+ },+ {+ "role": "system",+ "content": "(client environment and session context)"+ }+ ],+ "system": [+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 1)"+ },+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 2)"+ }+ ],+ "tools": [+ {+ "name": "Agent",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "description": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "subagent_type": {+ "type": "string"+ },+ "model": {+ "type": "string",+ "enum": [+ "sonnet",+ "opus",+ "haiku",+ "fable"+ ]+ },+ "effort": {+ "type": "string",+ "enum": [+ "low",+ "medium",+ "high",+ "xhigh",+ "max"+ ]+ },+ "run_in_background": {+ "type": "boolean"+ },+ "isolation": {+ "type": "string",+ "enum": [+ "worktree",+ "remote"+ ]+ }+ },+ "required": [+ "description",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Bash",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "command": {+ "type": "string"+ },+ "timeout": {+ "type": "number"+ },+ "description": {+ "type": "string"+ },+ "run_in_background": {+ "type": "boolean"+ },+ "dangerouslyDisableSandbox": {+ "type": "boolean"+ }+ },+ "required": [+ "command"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronCreate",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "cron": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "recurring": {+ "type": "boolean"+ },+ "durable": {+ "type": "boolean"+ }+ },+ "required": [+ "cron",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronDelete",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronList",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {},+ "additionalProperties": false+ }+ },+ {+ "name": "Edit",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "old_string": {+ "type": "string"+ },+ "new_string": {+ "type": "string"+ },+ "replace_all": {+ "default": false,+ "type": "boolean"+ }+ },+ "required": [+ "file_path",+ "old_string",+ "new_string"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "EnterWorktree",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "path": {+ "type": "string"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "ExitWorktree",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "enum": [+ "keep",+ "remove"+ ]+ },+ "discard_changes": {+ "type": "boolean"+ }+ },+ "required": [+ "action"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ListAgents",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "channel": {+ "type": "string",+ "maxLength": 256+ },+ "q": {+ "type": "string",+ "maxLength": 256+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "NotebookEdit",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "notebook_path": {+ "type": "string"+ },+ "cell_id": {+ "type": "string"+ },+ "new_source": {+ "type": "string"+ },+ "cell_type": {+ "type": "string",+ "enum": [+ "code",+ "markdown"+ ]+ },+ "edit_mode": {+ "type": "string",+ "enum": [+ "replace",+ "insert",+ "delete"+ ]+ }+ },+ "required": [+ "notebook_path",+ "new_source"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Read",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "limit": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 9007199254740991+ },+ "pages": {+ "type": "string"+ },+ "allow_large": {+ "type": "boolean"+ }+ },+ "required": [+ "file_path"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ReportFindings",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "level": {+ "type": "string",+ "enum": [+ "low",+ "medium",+ "high",+ "xhigh",+ "max"+ ]+ },+ "findings": {+ "maxItems": 32,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "file": {+ "type": "string"+ },+ "line": {+ "type": "integer",+ "minimum": -9007199254740991,+ "maximum": 9007199254740991+ },+ "summary": {+ "type": "string"+ },+ "short_summary": {+ "type": "string",+ "maxLength": 60+ },+ "failure_scenario": {+ "type": "string"+ },+ "category": {+ "type": "string",+ "maxLength": 40+ },+ "verdict": {+ "type": "string",+ "enum": [+ "CONFIRMED",+ "PLAUSIBLE"+ ]+ },+ "outcome": {+ "type": "string",+ "enum": [+ "fixed",+ "skipped",+ "no_change_needed"+ ]+ }+ },+ "required": [+ "file",+ "summary",+ "failure_scenario"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "findings"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ScheduleWakeup",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "delaySeconds": {+ "type": "number"+ },+ "reason": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "stop": {+ "type": "boolean"+ },+ "noop": {+ "type": "boolean"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "SendMessage",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "to": {+ "type": "string",+ "allOf": [+ {+ "pattern": "^[^\\n\\r]*$"+ },+ {+ "pattern": "^[\\s\\S]{0,300}$"+ }+ ]+ },+ "summary": {+ "type": "string",+ "maxLength": 200+ },+ "message": {+ "default": "",+ "type": "string"+ },+ "notify_when_idle": {+ "type": "boolean"+ }+ },+ "required": [+ "to",+ "message"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Skill",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "skill": {+ "type": "string"+ },+ "args": {+ "type": "string"+ }+ },+ "required": [+ "skill"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "TaskStop",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "task_id": {+ "type": "string"+ },+ "shell_id": {+ "type": "string"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "WebFetch",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "url": {+ "type": "string",+ "format": "uri"+ },+ "prompt": {+ "type": "string"+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ }+ },+ "required": [+ "url",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "WebSearch",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "minLength": 2+ },+ "allowed_domains": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "blocked_domains": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "query"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Workflow",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "script": {+ "type": "string",+ "maxLength": 524288+ },+ "name": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "title": {+ "type": "string"+ },+ "args": {},+ "scriptPath": {+ "type": "string"+ },+ "resumeFromRunId": {+ "type": "string",+ "pattern": "^wf_[a-z0-9-]{6,}$"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "Write",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "content": {+ "type": "string"+ }+ },+ "required": [+ "file_path",+ "content"+ ],+ "additionalProperties": false+ }+ }+ ],+ "metadata": {+ "user_id": "{\"device_id\":\"(device id)\",\"account_uuid\":\"\",\"session_id\":\"(session id)\"}"+ },+ "max_tokens": 32768,+ "thinking": {+ "type": "adaptive"+ },+ "output_config": {+ "effort": "high"+ },+ "stream": true+ },+ "expect": {+ "error": "output_config.effort: Extra inputs are not permitted"+ }+ },+ {+ "name": "first_turn_retry_without_effort",+ "setup": "recipe",+ "path": "/v1/messages?beta=true",+ "headers": {+ "anthropic-version": "2023-06-01",+ "anthropic-beta": "claude-code-20250219,interleaved-thinking-2025-05-14",+ "anthropic-dangerous-direct-browser-access": "true",+ "authorization": "Bearer (token)",+ "x-app": "cli",+ "x-claude-code-session-id": "(session id)",+ "content-type": "application/json",+ "accept": "application/json",+ "user-agent": "claude-cli/2.1.300 (external, sdk-cli)",+ "x-stainless-lang": "js",+ "x-stainless-package-version": "0.128.0",+ "x-stainless-retry-count": "0",+ "x-stainless-timeout": "600"+ },+ "body": {+ "model": "zai-org/GLM-5.3-Flash:relay",+ "messages": [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 1)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "(user prompt)",+ "cache_control": {+ "type": "ephemeral"+ }+ }+ ]+ },+ {+ "role": "system",+ "content": "(client environment and session context)"+ }+ ],+ "system": [+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 1)"+ },+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 2)"+ }+ ],+ "tools": [+ {+ "name": "Agent",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "description": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "subagent_type": {+ "type": "string"+ },+ "model": {+ "type": "string",+ "enum": [+ "sonnet",+ "opus",+ "haiku",+ "fable"+ ]+ },+ "effort": {+ "type": "string",+ "enum": [+ "low",+ "medium",+ "high",+ "xhigh",+ "max"+ ]+ },+ "run_in_background": {+ "type": "boolean"+ },+ "isolation": {+ "type": "string",+ "enum": [+ "worktree",+ "remote"+ ]+ }+ },+ "required": [+ "description",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Bash",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "command": {+ "type": "string"+ },+ "timeout": {+ "type": "number"+ },+ "description": {+ "type": "string"+ },+ "run_in_background": {+ "type": "boolean"+ },+ "dangerouslyDisableSandbox": {+ "type": "boolean"+ }+ },+ "required": [+ "command"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronCreate",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "cron": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "recurring": {+ "type": "boolean"+ },+ "durable": {+ "type": "boolean"+ }+ },+ "required": [+ "cron",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronDelete",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronList",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {},+ "additionalProperties": false+ }+ },+ {+ "name": "Edit",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "old_string": {+ "type": "string"+ },+ "new_string": {+ "type": "string"+ },+ "replace_all": {+ "default": false,+ "type": "boolean"+ }+ },+ "required": [+ "file_path",+ "old_string",+ "new_string"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "EnterWorktree",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "path": {+ "type": "string"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "ExitWorktree",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "enum": [+ "keep",+ "remove"+ ]+ },+ "discard_changes": {+ "type": "boolean"+ }+ },+ "required": [+ "action"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ListAgents",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "channel": {+ "type": "string",+ "maxLength": 256+ },+ "q": {+ "type": "string",+ "maxLength": 256+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "NotebookEdit",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "notebook_path": {+ "type": "string"+ },+ "cell_id": {+ "type": "string"+ },+ "new_source": {+ "type": "string"+ },+ "cell_type": {+ "type": "string",+ "enum": [+ "code",+ "markdown"+ ]+ },+ "edit_mode": {+ "type": "string",+ "enum": [+ "replace",+ "insert",+ "delete"+ ]+ }+ },+ "required": [+ "notebook_path",+ "new_source"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Read",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "limit": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 9007199254740991+ },+ "pages": {+ "type": "string"+ },+ "allow_large": {+ "type": "boolean"+ }+ },+ "required": [+ "file_path"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ReportFindings",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "level": {+ "type": "string",+ "enum": [+ "low",+ "medium",+ "high",+ "xhigh",+ "max"+ ]+ },+ "findings": {+ "maxItems": 32,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "file": {+ "type": "string"+ },+ "line": {+ "type": "integer",+ "minimum": -9007199254740991,+ "maximum": 9007199254740991+ },+ "summary": {+ "type": "string"+ },+ "short_summary": {+ "type": "string",+ "maxLength": 60+ },+ "failure_scenario": {+ "type": "string"+ },+ "category": {+ "type": "string",+ "maxLength": 40+ },+ "verdict": {+ "type": "string",+ "enum": [+ "CONFIRMED",+ "PLAUSIBLE"+ ]+ },+ "outcome": {+ "type": "string",+ "enum": [+ "fixed",+ "skipped",+ "no_change_needed"+ ]+ }+ },+ "required": [+ "file",+ "summary",+ "failure_scenario"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "findings"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ScheduleWakeup",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "delaySeconds": {+ "type": "number"+ },+ "reason": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "stop": {+ "type": "boolean"+ },+ "noop": {+ "type": "boolean"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "SendMessage",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "to": {+ "type": "string",+ "allOf": [+ {+ "pattern": "^[^\\n\\r]*$"+ },+ {+ "pattern": "^[\\s\\S]{0,300}$"+ }+ ]+ },+ "summary": {+ "type": "string",+ "maxLength": 200+ },+ "message": {+ "default": "",+ "type": "string"+ },+ "notify_when_idle": {+ "type": "boolean"+ }+ },+ "required": [+ "to",+ "message"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Skill",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "skill": {+ "type": "string"+ },+ "args": {+ "type": "string"+ }+ },+ "required": [+ "skill"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "TaskStop",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "task_id": {+ "type": "string"+ },+ "shell_id": {+ "type": "string"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "WebFetch",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "url": {+ "type": "string",+ "format": "uri"+ },+ "prompt": {+ "type": "string"+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ }+ },+ "required": [+ "url",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "WebSearch",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "minLength": 2+ },+ "allowed_domains": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "blocked_domains": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "query"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Workflow",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "script": {+ "type": "string",+ "maxLength": 524288+ },+ "name": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "title": {+ "type": "string"+ },+ "args": {},+ "scriptPath": {+ "type": "string"+ },+ "resumeFromRunId": {+ "type": "string",+ "pattern": "^wf_[a-z0-9-]{6,}$"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "Write",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "content": {+ "type": "string"+ }+ },+ "required": [+ "file_path",+ "content"+ ],+ "additionalProperties": false+ }+ }+ ],+ "metadata": {+ "user_id": "{\"device_id\":\"(device id)\",\"account_uuid\":\"\",\"session_id\":\"(session id)\"}"+ },+ "max_tokens": 32768,+ "thinking": {+ "type": "adaptive"+ },+ "stream": true+ },+ "expect": {+ "error": "messages.1.role: role \"system\" is not supported in messages; use the top-level system parameter"+ }+ },+ {+ "name": "first_turn_retry_without_system_turns",+ "setup": "recipe",+ "path": "/v1/messages?beta=true",+ "headers": {+ "anthropic-version": "2023-06-01",+ "anthropic-beta": "claude-code-20250219,interleaved-thinking-2025-05-14",+ "anthropic-dangerous-direct-browser-access": "true",+ "authorization": "Bearer (token)",+ "x-app": "cli",+ "x-claude-code-session-id": "(session id)",+ "content-type": "application/json",+ "accept": "application/json",+ "user-agent": "claude-cli/2.1.300 (external, sdk-cli)",+ "x-stainless-lang": "js",+ "x-stainless-package-version": "0.128.0",+ "x-stainless-retry-count": "0",+ "x-stainless-timeout": "600"+ },+ "body": {+ "model": "zai-org/GLM-5.3-Flash:relay",+ "messages": [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 1)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 2)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 3)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 4)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 5)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 6)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 7)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "(user prompt)",+ "cache_control": {+ "type": "ephemeral"+ }+ }+ ]+ }+ ],+ "system": [+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 1)"+ },+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 2)"+ }+ ],+ "tools": [+ {+ "name": "Agent",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "description": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "subagent_type": {+ "type": "string"+ },+ "model": {+ "type": "string",+ "enum": [+ "sonnet",+ "opus",+ "haiku",+ "fable"+ ]+ },+ "effort": {+ "type": "string",+ "enum": [+ "low",+ "medium",+ "high",+ "xhigh",+ "max"+ ]+ },+ "run_in_background": {+ "type": "boolean"+ },+ "isolation": {+ "type": "string",+ "enum": [+ "worktree",+ "remote"+ ]+ }+ },+ "required": [+ "description",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Bash",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "command": {+ "type": "string"+ },+ "timeout": {+ "type": "number"+ },+ "description": {+ "type": "string"+ },+ "run_in_background": {+ "type": "boolean"+ },+ "dangerouslyDisableSandbox": {+ "type": "boolean"+ }+ },+ "required": [+ "command"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronCreate",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "cron": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "recurring": {+ "type": "boolean"+ },+ "durable": {+ "type": "boolean"+ }+ },+ "required": [+ "cron",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronDelete",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronList",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {},+ "additionalProperties": false+ }+ },+ {+ "name": "Edit",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "old_string": {+ "type": "string"+ },+ "new_string": {+ "type": "string"+ },+ "replace_all": {+ "default": false,+ "type": "boolean"+ }+ },+ "required": [+ "file_path",+ "old_string",+ "new_string"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "EnterWorktree",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "path": {+ "type": "string"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "ExitWorktree",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "enum": [+ "keep",+ "remove"+ ]+ },+ "discard_changes": {+ "type": "boolean"+ }+ },+ "required": [+ "action"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ListAgents",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "channel": {+ "type": "string",+ "maxLength": 256+ },+ "q": {+ "type": "string",+ "maxLength": 256+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "NotebookEdit",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "notebook_path": {+ "type": "string"+ },+ "cell_id": {+ "type": "string"+ },+ "new_source": {+ "type": "string"+ },+ "cell_type": {+ "type": "string",+ "enum": [+ "code",+ "markdown"+ ]+ },+ "edit_mode": {+ "type": "string",+ "enum": [+ "replace",+ "insert",+ "delete"+ ]+ }+ },+ "required": [+ "notebook_path",+ "new_source"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Read",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "limit": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 9007199254740991+ },+ "pages": {+ "type": "string"+ },+ "allow_large": {+ "type": "boolean"+ }+ },+ "required": [+ "file_path"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ReportFindings",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "level": {+ "type": "string",+ "enum": [+ "low",+ "medium",+ "high",+ "xhigh",+ "max"+ ]+ },+ "findings": {+ "maxItems": 32,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "file": {+ "type": "string"+ },+ "line": {+ "type": "integer",+ "minimum": -9007199254740991,+ "maximum": 9007199254740991+ },+ "summary": {+ "type": "string"+ },+ "short_summary": {+ "type": "string",+ "maxLength": 60+ },+ "failure_scenario": {+ "type": "string"+ },+ "category": {+ "type": "string",+ "maxLength": 40+ },+ "verdict": {+ "type": "string",+ "enum": [+ "CONFIRMED",+ "PLAUSIBLE"+ ]+ },+ "outcome": {+ "type": "string",+ "enum": [+ "fixed",+ "skipped",+ "no_change_needed"+ ]+ }+ },+ "required": [+ "file",+ "summary",+ "failure_scenario"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "findings"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ScheduleWakeup",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "delaySeconds": {+ "type": "number"+ },+ "reason": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "stop": {+ "type": "boolean"+ },+ "noop": {+ "type": "boolean"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "SendMessage",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "to": {+ "type": "string",+ "allOf": [+ {+ "pattern": "^[^\\n\\r]*$"+ },+ {+ "pattern": "^[\\s\\S]{0,300}$"+ }+ ]+ },+ "summary": {+ "type": "string",+ "maxLength": 200+ },+ "message": {+ "default": "",+ "type": "string"+ },+ "notify_when_idle": {+ "type": "boolean"+ }+ },+ "required": [+ "to",+ "message"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Skill",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "skill": {+ "type": "string"+ },+ "args": {+ "type": "string"+ }+ },+ "required": [+ "skill"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "TaskStop",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "task_id": {+ "type": "string"+ },+ "shell_id": {+ "type": "string"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "WebFetch",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "url": {+ "type": "string",+ "format": "uri"+ },+ "prompt": {+ "type": "string"+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ }+ },+ "required": [+ "url",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "WebSearch",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "minLength": 2+ },+ "allowed_domains": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "blocked_domains": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "query"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Workflow",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "script": {+ "type": "string",+ "maxLength": 524288+ },+ "name": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "title": {+ "type": "string"+ },+ "args": {},+ "scriptPath": {+ "type": "string"+ },+ "resumeFromRunId": {+ "type": "string",+ "pattern": "^wf_[a-z0-9-]{6,}$"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "Write",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "content": {+ "type": "string"+ }+ },+ "required": [+ "file_path",+ "content"+ ],+ "additionalProperties": false+ }+ }+ ],+ "metadata": {+ "user_id": "{\"device_id\":\"(device id)\",\"account_uuid\":\"\",\"session_id\":\"(session id)\"}"+ },+ "max_tokens": 32768,+ "thinking": {+ "type": "adaptive"+ },+ "stream": true+ },+ "expect": {+ "chat": {+ "roles": [+ "system",+ "user"+ ],+ "stream": true,+ "max_tokens": 32768,+ "tool_count": 20,+ "include_reasoning": true+ }+ }+ },+ {+ "name": "tool_loop",+ "setup": "recipe",+ "path": "/v1/messages?beta=true",+ "headers": {+ "anthropic-version": "2023-06-01",+ "anthropic-beta": "claude-code-20250219,interleaved-thinking-2025-05-14",+ "anthropic-dangerous-direct-browser-access": "true",+ "authorization": "Bearer (token)",+ "x-app": "cli",+ "x-claude-code-session-id": "(session id)",+ "content-type": "application/json",+ "accept": "application/json",+ "user-agent": "claude-cli/2.1.300 (external, sdk-cli)",+ "x-stainless-lang": "js",+ "x-stainless-package-version": "0.128.0",+ "x-stainless-retry-count": "0",+ "x-stainless-timeout": "600"+ },+ "body": {+ "model": "zai-org/GLM-5.3-Flash:relay",+ "messages": [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 1)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 2)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 3)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 4)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 5)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 6)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 7)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "(user prompt)"+ }+ ]+ },+ {+ "role": "assistant",+ "content": [+ {+ "type": "tool_use",+ "id": "toolu_01",+ "name": "Bash",+ "input": {+ "command": "echo capture-ok",+ "description": "(description)"+ }+ }+ ]+ },+ {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "toolu_01",+ "content": "(tool output)",+ "is_error": false,+ "cache_control": {+ "type": "ephemeral"+ }+ }+ ]+ }+ ],+ "system": [+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 1)"+ },+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 2)"+ }+ ],+ "tools": [+ {+ "name": "Agent",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "description": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "subagent_type": {+ "type": "string"+ },+ "model": {+ "type": "string",+ "enum": [+ "sonnet",+ "opus",+ "haiku",+ "fable"+ ]+ },+ "effort": {+ "type": "string",+ "enum": [+ "low",+ "medium",+ "high",+ "xhigh",+ "max"+ ]+ },+ "run_in_background": {+ "type": "boolean"+ },+ "isolation": {+ "type": "string",+ "enum": [+ "worktree",+ "remote"+ ]+ }+ },+ "required": [+ "description",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Bash",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "command": {+ "type": "string"+ },+ "timeout": {+ "type": "number"+ },+ "description": {+ "type": "string"+ },+ "run_in_background": {+ "type": "boolean"+ },+ "dangerouslyDisableSandbox": {+ "type": "boolean"+ }+ },+ "required": [+ "command"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronCreate",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "cron": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "recurring": {+ "type": "boolean"+ },+ "durable": {+ "type": "boolean"+ }+ },+ "required": [+ "cron",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronDelete",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronList",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {},+ "additionalProperties": false+ }+ },+ {+ "name": "Edit",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "old_string": {+ "type": "string"+ },+ "new_string": {+ "type": "string"+ },+ "replace_all": {+ "default": false,+ "type": "boolean"+ }+ },+ "required": [+ "file_path",+ "old_string",+ "new_string"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "EnterWorktree",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "path": {+ "type": "string"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "ExitWorktree",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "enum": [+ "keep",+ "remove"+ ]+ },+ "discard_changes": {+ "type": "boolean"+ }+ },+ "required": [+ "action"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ListAgents",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "channel": {+ "type": "string",+ "maxLength": 256+ },+ "q": {+ "type": "string",+ "maxLength": 256+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "NotebookEdit",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "notebook_path": {+ "type": "string"+ },+ "cell_id": {+ "type": "string"+ },+ "new_source": {+ "type": "string"+ },+ "cell_type": {+ "type": "string",+ "enum": [+ "code",+ "markdown"+ ]+ },+ "edit_mode": {+ "type": "string",+ "enum": [+ "replace",+ "insert",+ "delete"+ ]+ }+ },+ "required": [+ "notebook_path",+ "new_source"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Read",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "limit": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 9007199254740991+ },+ "pages": {+ "type": "string"+ },+ "allow_large": {+ "type": "boolean"+ }+ },+ "required": [+ "file_path"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ReportFindings",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "level": {+ "type": "string",+ "enum": [+ "low",+ "medium",+ "high",+ "xhigh",+ "max"+ ]+ },+ "findings": {+ "maxItems": 32,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "file": {+ "type": "string"+ },+ "line": {+ "type": "integer",+ "minimum": -9007199254740991,+ "maximum": 9007199254740991+ },+ "summary": {+ "type": "string"+ },+ "short_summary": {+ "type": "string",+ "maxLength": 60+ },+ "failure_scenario": {+ "type": "string"+ },+ "category": {+ "type": "string",+ "maxLength": 40+ },+ "verdict": {+ "type": "string",+ "enum": [+ "CONFIRMED",+ "PLAUSIBLE"+ ]+ },+ "outcome": {+ "type": "string",+ "enum": [+ "fixed",+ "skipped",+ "no_change_needed"+ ]+ }+ },+ "required": [+ "file",+ "summary",+ "failure_scenario"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "findings"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ScheduleWakeup",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "delaySeconds": {+ "type": "number"+ },+ "reason": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "stop": {+ "type": "boolean"+ },+ "noop": {+ "type": "boolean"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "SendMessage",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "to": {+ "type": "string",+ "allOf": [+ {+ "pattern": "^[^\\n\\r]*$"+ },+ {+ "pattern": "^[\\s\\S]{0,300}$"+ }+ ]+ },+ "summary": {+ "type": "string",+ "maxLength": 200+ },+ "message": {+ "default": "",+ "type": "string"+ },+ "notify_when_idle": {+ "type": "boolean"+ }+ },+ "required": [+ "to",+ "message"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Skill",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "skill": {+ "type": "string"+ },+ "args": {+ "type": "string"+ }+ },+ "required": [+ "skill"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "TaskStop",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "task_id": {+ "type": "string"+ },+ "shell_id": {+ "type": "string"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "WebFetch",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "url": {+ "type": "string",+ "format": "uri"+ },+ "prompt": {+ "type": "string"+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ }+ },+ "required": [+ "url",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "WebSearch",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "minLength": 2+ },+ "allowed_domains": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "blocked_domains": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "query"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Workflow",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "script": {+ "type": "string",+ "maxLength": 524288+ },+ "name": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "title": {+ "type": "string"+ },+ "args": {},+ "scriptPath": {+ "type": "string"+ },+ "resumeFromRunId": {+ "type": "string",+ "pattern": "^wf_[a-z0-9-]{6,}$"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "Write",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "content": {+ "type": "string"+ }+ },+ "required": [+ "file_path",+ "content"+ ],+ "additionalProperties": false+ }+ }+ ],+ "metadata": {+ "user_id": "{\"device_id\":\"(device id)\",\"account_uuid\":\"\",\"session_id\":\"(session id)\"}"+ },+ "max_tokens": 32768,+ "thinking": {+ "type": "adaptive"+ },+ "stream": true+ },+ "expect": {+ "chat": {+ "roles": [+ "system",+ "user",+ "assistant",+ "tool"+ ],+ "stream": true,+ "max_tokens": 32768,+ "tool_count": 20,+ "include_reasoning": true+ }+ }+ },+ {+ "name": "image_tool_result",+ "setup": "recipe",+ "path": "/v1/messages?beta=true",+ "headers": {+ "anthropic-version": "2023-06-01",+ "anthropic-beta": "claude-code-20250219,interleaved-thinking-2025-05-14",+ "anthropic-dangerous-direct-browser-access": "true",+ "authorization": "Bearer (token)",+ "x-app": "cli",+ "x-claude-code-session-id": "(session id)",+ "content-type": "application/json",+ "accept": "application/json",+ "user-agent": "claude-cli/2.1.300 (external, sdk-cli)",+ "x-stainless-lang": "js",+ "x-stainless-package-version": "0.128.0",+ "x-stainless-retry-count": "0",+ "x-stainless-timeout": "600"+ },+ "body": {+ "model": "zai-org/GLM-5.3-Flash:relay",+ "messages": [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 1)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 2)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 3)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 4)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 5)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 6)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 7)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "(user prompt)"+ }+ ]+ },+ {+ "role": "assistant",+ "content": [+ {+ "type": "tool_use",+ "id": "toolu_01",+ "name": "Read",+ "input": {+ "file_path": "/workspace/pixel.png"+ }+ }+ ]+ },+ {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "toolu_01",+ "content": [+ {+ "type": "image",+ "source": {+ "type": "base64",+ "data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",+ "media_type": "image/png"+ }+ },+ {+ "type": "text",+ "text": "(tool output)"+ }+ ],+ "cache_control": {+ "type": "ephemeral"+ }+ }+ ]+ }+ ],+ "system": [+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 1)"+ },+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 2)"+ }+ ],+ "tools": [+ {+ "name": "Agent",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "description": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "subagent_type": {+ "type": "string"+ },+ "model": {+ "type": "string",+ "enum": [+ "sonnet",+ "opus",+ "haiku",+ "fable"+ ]+ },+ "effort": {+ "type": "string",+ "enum": [+ "low",+ "medium",+ "high",+ "xhigh",+ "max"+ ]+ },+ "run_in_background": {+ "type": "boolean"+ },+ "isolation": {+ "type": "string",+ "enum": [+ "worktree",+ "remote"+ ]+ }+ },+ "required": [+ "description",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Bash",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "command": {+ "type": "string"+ },+ "timeout": {+ "type": "number"+ },+ "description": {+ "type": "string"+ },+ "run_in_background": {+ "type": "boolean"+ },+ "dangerouslyDisableSandbox": {+ "type": "boolean"+ }+ },+ "required": [+ "command"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronCreate",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "cron": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "recurring": {+ "type": "boolean"+ },+ "durable": {+ "type": "boolean"+ }+ },+ "required": [+ "cron",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronDelete",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronList",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {},+ "additionalProperties": false+ }+ },+ {+ "name": "Edit",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "old_string": {+ "type": "string"+ },+ "new_string": {+ "type": "string"+ },+ "replace_all": {+ "default": false,+ "type": "boolean"+ }+ },+ "required": [+ "file_path",+ "old_string",+ "new_string"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "EnterWorktree",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "path": {+ "type": "string"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "ExitWorktree",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "enum": [+ "keep",+ "remove"+ ]+ },+ "discard_changes": {+ "type": "boolean"+ }+ },+ "required": [+ "action"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ListAgents",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "channel": {+ "type": "string",+ "maxLength": 256+ },+ "q": {+ "type": "string",+ "maxLength": 256+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "NotebookEdit",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "notebook_path": {+ "type": "string"+ },+ "cell_id": {+ "type": "string"+ },+ "new_source": {+ "type": "string"+ },+ "cell_type": {+ "type": "string",+ "enum": [+ "code",+ "markdown"+ ]+ },+ "edit_mode": {+ "type": "string",+ "enum": [+ "replace",+ "insert",+ "delete"+ ]+ }+ },+ "required": [+ "notebook_path",+ "new_source"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Read",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "limit": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 9007199254740991+ },+ "pages": {+ "type": "string"+ },+ "allow_large": {+ "type": "boolean"+ }+ },+ "required": [+ "file_path"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ReportFindings",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "level": {+ "type": "string",+ "enum": [+ "low",+ "medium",+ "high",+ "xhigh",+ "max"+ ]+ },+ "findings": {+ "maxItems": 32,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "file": {+ "type": "string"+ },+ "line": {+ "type": "integer",+ "minimum": -9007199254740991,+ "maximum": 9007199254740991+ },+ "summary": {+ "type": "string"+ },+ "short_summary": {+ "type": "string",+ "maxLength": 60+ },+ "failure_scenario": {+ "type": "string"+ },+ "category": {+ "type": "string",+ "maxLength": 40+ },+ "verdict": {+ "type": "string",+ "enum": [+ "CONFIRMED",+ "PLAUSIBLE"+ ]+ },+ "outcome": {+ "type": "string",+ "enum": [+ "fixed",+ "skipped",+ "no_change_needed"+ ]+ }+ },+ "required": [+ "file",+ "summary",+ "failure_scenario"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "findings"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ScheduleWakeup",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "delaySeconds": {+ "type": "number"+ },+ "reason": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "stop": {+ "type": "boolean"+ },+ "noop": {+ "type": "boolean"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "SendMessage",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "to": {+ "type": "string",+ "allOf": [+ {+ "pattern": "^[^\\n\\r]*$"+ },+ {+ "pattern": "^[\\s\\S]{0,300}$"+ }+ ]+ },+ "summary": {+ "type": "string",+ "maxLength": 200+ },+ "message": {+ "default": "",+ "type": "string"+ },+ "notify_when_idle": {+ "type": "boolean"+ }+ },+ "required": [+ "to",+ "message"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Skill",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "skill": {+ "type": "string"+ },+ "args": {+ "type": "string"+ }+ },+ "required": [+ "skill"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "TaskStop",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "task_id": {+ "type": "string"+ },+ "shell_id": {+ "type": "string"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "WebFetch",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "url": {+ "type": "string",+ "format": "uri"+ },+ "prompt": {+ "type": "string"+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ }+ },+ "required": [+ "url",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "WebSearch",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "minLength": 2+ },+ "allowed_domains": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "blocked_domains": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "query"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Workflow",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "script": {+ "type": "string",+ "maxLength": 524288+ },+ "name": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "title": {+ "type": "string"+ },+ "args": {},+ "scriptPath": {+ "type": "string"+ },+ "resumeFromRunId": {+ "type": "string",+ "pattern": "^wf_[a-z0-9-]{6,}$"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "Write",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "content": {+ "type": "string"+ }+ },+ "required": [+ "file_path",+ "content"+ ],+ "additionalProperties": false+ }+ }+ ],+ "metadata": {+ "user_id": "{\"device_id\":\"(device id)\",\"account_uuid\":\"\",\"session_id\":\"(session id)\"}"+ },+ "max_tokens": 32768,+ "thinking": {+ "type": "adaptive"+ },+ "stream": true+ },+ "expect": {+ "chat": {+ "roles": [+ "system",+ "user",+ "assistant",+ "tool",+ "user"+ ],+ "stream": true,+ "max_tokens": 32768,+ "tool_count": 20,+ "include_reasoning": true+ }+ }+ },+ {+ "name": "image_removed_retry",+ "setup": "recipe",+ "path": "/v1/messages?beta=true",+ "headers": {+ "anthropic-version": "2023-06-01",+ "anthropic-beta": "claude-code-20250219,interleaved-thinking-2025-05-14",+ "anthropic-dangerous-direct-browser-access": "true",+ "authorization": "Bearer (token)",+ "x-app": "cli",+ "x-claude-code-session-id": "(session id)",+ "content-type": "application/json",+ "accept": "application/json",+ "user-agent": "claude-cli/2.1.300 (external, sdk-cli)",+ "x-stainless-lang": "js",+ "x-stainless-package-version": "0.128.0",+ "x-stainless-retry-count": "0",+ "x-stainless-timeout": "600"+ },+ "body": {+ "model": "zai-org/GLM-5.3-Flash:relay",+ "messages": [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 1)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 2)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 3)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 4)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 5)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 6)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 7)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "(user prompt)"+ }+ ]+ },+ {+ "role": "assistant",+ "content": [+ {+ "type": "tool_use",+ "id": "toolu_01",+ "name": "Read",+ "input": {+ "file_path": "/workspace/pixel.png"+ }+ }+ ]+ },+ {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "toolu_01",+ "content": [+ {+ "type": "text",+ "text": "(tool output)"+ },+ {+ "type": "text",+ "text": "(tool output)"+ }+ ],+ "cache_control": {+ "type": "ephemeral"+ }+ }+ ]+ }+ ],+ "system": [+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 1)"+ },+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 2)"+ }+ ],+ "tools": [+ {+ "name": "Agent",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "description": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "subagent_type": {+ "type": "string"+ },+ "model": {+ "type": "string",+ "enum": [+ "sonnet",+ "opus",+ "haiku",+ "fable"+ ]+ },+ "effort": {+ "type": "string",+ "enum": [+ "low",+ "medium",+ "high",+ "xhigh",+ "max"+ ]+ },+ "run_in_background": {+ "type": "boolean"+ },+ "isolation": {+ "type": "string",+ "enum": [+ "worktree",+ "remote"+ ]+ }+ },+ "required": [+ "description",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Bash",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "command": {+ "type": "string"+ },+ "timeout": {+ "type": "number"+ },+ "description": {+ "type": "string"+ },+ "run_in_background": {+ "type": "boolean"+ },+ "dangerouslyDisableSandbox": {+ "type": "boolean"+ }+ },+ "required": [+ "command"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronCreate",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "cron": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "recurring": {+ "type": "boolean"+ },+ "durable": {+ "type": "boolean"+ }+ },+ "required": [+ "cron",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronDelete",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronList",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {},+ "additionalProperties": false+ }+ },+ {+ "name": "Edit",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "old_string": {+ "type": "string"+ },+ "new_string": {+ "type": "string"+ },+ "replace_all": {+ "default": false,+ "type": "boolean"+ }+ },+ "required": [+ "file_path",+ "old_string",+ "new_string"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "EnterWorktree",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "path": {+ "type": "string"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "ExitWorktree",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "enum": [+ "keep",+ "remove"+ ]+ },+ "discard_changes": {+ "type": "boolean"+ }+ },+ "required": [+ "action"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ListAgents",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "channel": {+ "type": "string",+ "maxLength": 256+ },+ "q": {+ "type": "string",+ "maxLength": 256+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "NotebookEdit",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "notebook_path": {+ "type": "string"+ },+ "cell_id": {+ "type": "string"+ },+ "new_source": {+ "type": "string"+ },+ "cell_type": {+ "type": "string",+ "enum": [+ "code",+ "markdown"+ ]+ },+ "edit_mode": {+ "type": "string",+ "enum": [+ "replace",+ "insert",+ "delete"+ ]+ }+ },+ "required": [+ "notebook_path",+ "new_source"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Read",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "limit": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 9007199254740991+ },+ "pages": {+ "type": "string"+ },+ "allow_large": {+ "type": "boolean"+ }+ },+ "required": [+ "file_path"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ReportFindings",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "level": {+ "type": "string",+ "enum": [+ "low",+ "medium",+ "high",+ "xhigh",+ "max"+ ]+ },+ "findings": {+ "maxItems": 32,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "file": {+ "type": "string"+ },+ "line": {+ "type": "integer",+ "minimum": -9007199254740991,+ "maximum": 9007199254740991+ },+ "summary": {+ "type": "string"+ },+ "short_summary": {+ "type": "string",+ "maxLength": 60+ },+ "failure_scenario": {+ "type": "string"+ },+ "category": {+ "type": "string",+ "maxLength": 40+ },+ "verdict": {+ "type": "string",+ "enum": [+ "CONFIRMED",+ "PLAUSIBLE"+ ]+ },+ "outcome": {+ "type": "string",+ "enum": [+ "fixed",+ "skipped",+ "no_change_needed"+ ]+ }+ },+ "required": [+ "file",+ "summary",+ "failure_scenario"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "findings"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ScheduleWakeup",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "delaySeconds": {+ "type": "number"+ },+ "reason": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "stop": {+ "type": "boolean"+ },+ "noop": {+ "type": "boolean"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "SendMessage",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "to": {+ "type": "string",+ "allOf": [+ {+ "pattern": "^[^\\n\\r]*$"+ },+ {+ "pattern": "^[\\s\\S]{0,300}$"+ }+ ]+ },+ "summary": {+ "type": "string",+ "maxLength": 200+ },+ "message": {+ "default": "",+ "type": "string"+ },+ "notify_when_idle": {+ "type": "boolean"+ }+ },+ "required": [+ "to",+ "message"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Skill",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "skill": {+ "type": "string"+ },+ "args": {+ "type": "string"+ }+ },+ "required": [+ "skill"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "TaskStop",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "task_id": {+ "type": "string"+ },+ "shell_id": {+ "type": "string"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "WebFetch",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "url": {+ "type": "string",+ "format": "uri"+ },+ "prompt": {+ "type": "string"+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ }+ },+ "required": [+ "url",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "WebSearch",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "minLength": 2+ },+ "allowed_domains": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "blocked_domains": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "query"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Workflow",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "script": {+ "type": "string",+ "maxLength": 524288+ },+ "name": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "title": {+ "type": "string"+ },+ "args": {},+ "scriptPath": {+ "type": "string"+ },+ "resumeFromRunId": {+ "type": "string",+ "pattern": "^wf_[a-z0-9-]{6,}$"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "Write",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "content": {+ "type": "string"+ }+ },+ "required": [+ "file_path",+ "content"+ ],+ "additionalProperties": false+ }+ }+ ],+ "metadata": {+ "user_id": "{\"device_id\":\"(device id)\",\"account_uuid\":\"\",\"session_id\":\"(session id)\"}"+ },+ "max_tokens": 32768,+ "thinking": {+ "type": "adaptive"+ },+ "stream": true+ },+ "expect": {+ "chat": {+ "roles": [+ "system",+ "user",+ "assistant",+ "tool"+ ],+ "stream": true,+ "max_tokens": 32768,+ "tool_count": 20,+ "include_reasoning": true+ }+ }+ },+ {+ "name": "parallel_tool_use",+ "setup": "recipe",+ "path": "/v1/messages?beta=true",+ "headers": {+ "anthropic-version": "2023-06-01",+ "anthropic-beta": "claude-code-20250219,interleaved-thinking-2025-05-14",+ "anthropic-dangerous-direct-browser-access": "true",+ "authorization": "Bearer (token)",+ "x-app": "cli",+ "x-claude-code-session-id": "(session id)",+ "content-type": "application/json",+ "accept": "application/json",+ "user-agent": "claude-cli/2.1.300 (external, sdk-cli)",+ "x-stainless-lang": "js",+ "x-stainless-package-version": "0.128.0",+ "x-stainless-retry-count": "0",+ "x-stainless-timeout": "600"+ },+ "body": {+ "model": "zai-org/GLM-5.3-Flash:relay",+ "messages": [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 1)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 2)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 3)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 4)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 5)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 6)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 7)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "(user prompt)"+ }+ ]+ },+ {+ "role": "assistant",+ "content": [+ {+ "type": "tool_use",+ "id": "toolu_01",+ "name": "Bash",+ "input": {+ "command": "echo one",+ "description": "(description)"+ }+ },+ {+ "type": "tool_use",+ "id": "toolu_02",+ "name": "Bash",+ "input": {+ "command": "echo two",+ "description": "(description)"+ }+ }+ ]+ },+ {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "toolu_01",+ "content": "(tool output)",+ "is_error": false+ },+ {+ "type": "tool_result",+ "tool_use_id": "toolu_02",+ "content": "(tool output)",+ "is_error": false,+ "cache_control": {+ "type": "ephemeral"+ }+ }+ ]+ }+ ],+ "system": [+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 1)"+ },+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 2)"+ }+ ],+ "tools": [+ {+ "name": "Agent",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "description": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "subagent_type": {+ "type": "string"+ },+ "model": {+ "type": "string",+ "enum": [+ "sonnet",+ "opus",+ "haiku",+ "fable"+ ]+ },+ "effort": {+ "type": "string",+ "enum": [+ "low",+ "medium",+ "high",+ "xhigh",+ "max"+ ]+ },+ "run_in_background": {+ "type": "boolean"+ },+ "isolation": {+ "type": "string",+ "enum": [+ "worktree",+ "remote"+ ]+ }+ },+ "required": [+ "description",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Bash",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "command": {+ "type": "string"+ },+ "timeout": {+ "type": "number"+ },+ "description": {+ "type": "string"+ },+ "run_in_background": {+ "type": "boolean"+ },+ "dangerouslyDisableSandbox": {+ "type": "boolean"+ }+ },+ "required": [+ "command"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronCreate",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "cron": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "recurring": {+ "type": "boolean"+ },+ "durable": {+ "type": "boolean"+ }+ },+ "required": [+ "cron",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronDelete",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronList",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {},+ "additionalProperties": false+ }+ },+ {+ "name": "Edit",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "old_string": {+ "type": "string"+ },+ "new_string": {+ "type": "string"+ },+ "replace_all": {+ "default": false,+ "type": "boolean"+ }+ },+ "required": [+ "file_path",+ "old_string",+ "new_string"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "EnterWorktree",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "path": {+ "type": "string"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "ExitWorktree",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "enum": [+ "keep",+ "remove"+ ]+ },+ "discard_changes": {+ "type": "boolean"+ }+ },+ "required": [+ "action"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ListAgents",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "channel": {+ "type": "string",+ "maxLength": 256+ },+ "q": {+ "type": "string",+ "maxLength": 256+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "NotebookEdit",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "notebook_path": {+ "type": "string"+ },+ "cell_id": {+ "type": "string"+ },+ "new_source": {+ "type": "string"+ },+ "cell_type": {+ "type": "string",+ "enum": [+ "code",+ "markdown"+ ]+ },+ "edit_mode": {+ "type": "string",+ "enum": [+ "replace",+ "insert",+ "delete"+ ]+ }+ },+ "required": [+ "notebook_path",+ "new_source"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Read",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "limit": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 9007199254740991+ },+ "pages": {+ "type": "string"+ },+ "allow_large": {+ "type": "boolean"+ }+ },+ "required": [+ "file_path"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ReportFindings",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "level": {+ "type": "string",+ "enum": [+ "low",+ "medium",+ "high",+ "xhigh",+ "max"+ ]+ },+ "findings": {+ "maxItems": 32,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "file": {+ "type": "string"+ },+ "line": {+ "type": "integer",+ "minimum": -9007199254740991,+ "maximum": 9007199254740991+ },+ "summary": {+ "type": "string"+ },+ "short_summary": {+ "type": "string",+ "maxLength": 60+ },+ "failure_scenario": {+ "type": "string"+ },+ "category": {+ "type": "string",+ "maxLength": 40+ },+ "verdict": {+ "type": "string",+ "enum": [+ "CONFIRMED",+ "PLAUSIBLE"+ ]+ },+ "outcome": {+ "type": "string",+ "enum": [+ "fixed",+ "skipped",+ "no_change_needed"+ ]+ }+ },+ "required": [+ "file",+ "summary",+ "failure_scenario"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "findings"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ScheduleWakeup",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "delaySeconds": {+ "type": "number"+ },+ "reason": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "stop": {+ "type": "boolean"+ },+ "noop": {+ "type": "boolean"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "SendMessage",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "to": {+ "type": "string",+ "allOf": [+ {+ "pattern": "^[^\\n\\r]*$"+ },+ {+ "pattern": "^[\\s\\S]{0,300}$"+ }+ ]+ },+ "summary": {+ "type": "string",+ "maxLength": 200+ },+ "message": {+ "default": "",+ "type": "string"+ },+ "notify_when_idle": {+ "type": "boolean"+ }+ },+ "required": [+ "to",+ "message"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Skill",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "skill": {+ "type": "string"+ },+ "args": {+ "type": "string"+ }+ },+ "required": [+ "skill"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "TaskStop",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "task_id": {+ "type": "string"+ },+ "shell_id": {+ "type": "string"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "WebFetch",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "url": {+ "type": "string",+ "format": "uri"+ },+ "prompt": {+ "type": "string"+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ }+ },+ "required": [+ "url",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "WebSearch",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "minLength": 2+ },+ "allowed_domains": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "blocked_domains": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "query"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Workflow",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "script": {+ "type": "string",+ "maxLength": 524288+ },+ "name": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "title": {+ "type": "string"+ },+ "args": {},+ "scriptPath": {+ "type": "string"+ },+ "resumeFromRunId": {+ "type": "string",+ "pattern": "^wf_[a-z0-9-]{6,}$"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "Write",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "content": {+ "type": "string"+ }+ },+ "required": [+ "file_path",+ "content"+ ],+ "additionalProperties": false+ }+ }+ ],+ "metadata": {+ "user_id": "{\"device_id\":\"(device id)\",\"account_uuid\":\"\",\"session_id\":\"(session id)\"}"+ },+ "max_tokens": 32768,+ "thinking": {+ "type": "adaptive"+ },+ "stream": true+ },+ "expect": {+ "chat": {+ "roles": [+ "system",+ "user",+ "assistant",+ "tool",+ "tool"+ ],+ "stream": true,+ "max_tokens": 32768,+ "tool_count": 20,+ "include_reasoning": true+ }+ }+ },+ {+ "name": "side_query_classifier_stage_one",+ "setup": "recipe",+ "path": "/v1/messages?beta=true",+ "headers": {+ "anthropic-version": "2023-06-01",+ "anthropic-beta": "claude-code-20250219,interleaved-thinking-2025-05-14",+ "anthropic-dangerous-direct-browser-access": "true",+ "authorization": "Bearer (token)",+ "x-app": "cli",+ "x-claude-code-session-id": "(session id)",+ "content-type": "application/json",+ "accept": "application/json",+ "user-agent": "claude-cli/2.1.300 (external, sdk-cli)",+ "x-stainless-lang": "js",+ "x-stainless-package-version": "0.128.0",+ "x-stainless-retry-count": "0",+ "x-stainless-timeout": "60"+ },+ "body": {+ "model": "zai-org/GLM-5.3-Flash:relay",+ "max_tokens": 2112,+ "system": [+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 1)"+ }+ ],+ "messages": [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "(user prompt)"+ },+ {+ "type": "text",+ "text": "(user prompt)",+ "cache_control": {+ "type": "ephemeral"+ }+ },+ {+ "type": "text",+ "text": "(user prompt)",+ "cache_control": {+ "type": "ephemeral"+ }+ },+ {+ "type": "text",+ "text": "(user prompt)"+ },+ {+ "type": "text",+ "text": "(user prompt)"+ }+ ]+ }+ ],+ "stop_sequences": [+ "</block>"+ ],+ "metadata": {+ "user_id": "{\"device_id\":\"(device id)\",\"account_uuid\":\"\",\"session_id\":\"(session id)\"}"+ }+ },+ "expect": {+ "chat": {+ "roles": [+ "system",+ "user"+ ],+ "stop": [+ "</block>"+ ],+ "stream": false,+ "max_tokens": 2112,+ "tool_count": 0,+ "include_reasoning": false+ }+ }+ },+ {+ "name": "side_query_classifier_stage_two",+ "setup": "recipe",+ "path": "/v1/messages?beta=true",+ "headers": {+ "anthropic-version": "2023-06-01",+ "anthropic-beta": "claude-code-20250219,interleaved-thinking-2025-05-14",+ "anthropic-dangerous-direct-browser-access": "true",+ "authorization": "Bearer (token)",+ "x-app": "cli",+ "x-claude-code-session-id": "(session id)",+ "content-type": "application/json",+ "accept": "application/json",+ "user-agent": "claude-cli/2.1.300 (external, sdk-cli)",+ "x-stainless-lang": "js",+ "x-stainless-package-version": "0.128.0",+ "x-stainless-retry-count": "0",+ "x-stainless-timeout": "60"+ },+ "body": {+ "model": "zai-org/GLM-5.3-Flash:relay",+ "max_tokens": 10240,+ "system": [+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 1)"+ }+ ],+ "messages": [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "(user prompt)"+ },+ {+ "type": "text",+ "text": "(user prompt)",+ "cache_control": {+ "type": "ephemeral"+ }+ },+ {+ "type": "text",+ "text": "(user prompt)",+ "cache_control": {+ "type": "ephemeral"+ }+ },+ {+ "type": "text",+ "text": "(user prompt)"+ },+ {+ "type": "text",+ "text": "(user prompt)"+ }+ ]+ }+ ],+ "metadata": {+ "user_id": "{\"device_id\":\"(device id)\",\"account_uuid\":\"\",\"session_id\":\"(session id)\"}"+ }+ },+ "expect": {+ "chat": {+ "roles": [+ "system",+ "user"+ ],+ "stream": false,+ "max_tokens": 10240,+ "tool_count": 0,+ "include_reasoning": false+ }+ }+ },+ {+ "name": "subagent_first_turn",+ "setup": "recipe",+ "path": "/v1/messages?beta=true",+ "headers": {+ "anthropic-version": "2023-06-01",+ "anthropic-beta": "claude-code-20250219,interleaved-thinking-2025-05-14,effort-2025-11-24",+ "anthropic-dangerous-direct-browser-access": "true",+ "authorization": "Bearer (token)",+ "x-app": "cli",+ "x-claude-code-session-id": "(session id)",+ "content-type": "application/json",+ "accept": "application/json",+ "user-agent": "claude-cli/2.1.300 (external, sdk-cli)",+ "x-stainless-lang": "js",+ "x-stainless-package-version": "0.128.0",+ "x-stainless-retry-count": "0",+ "x-stainless-timeout": "600"+ },+ "body": {+ "model": "zai-org/GLM-5.3-Flash:relay",+ "messages": [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 1)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "(user prompt)",+ "cache_control": {+ "type": "ephemeral"+ }+ }+ ]+ },+ {+ "role": "system",+ "content": "(client environment and session context)"+ }+ ],+ "system": [+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 1)"+ },+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 2)"+ }+ ],+ "tools": [+ {+ "name": "Agent",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "description": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "subagent_type": {+ "type": "string"+ },+ "model": {+ "type": "string",+ "enum": [+ "sonnet",+ "opus",+ "haiku",+ "fable"+ ]+ },+ "effort": {+ "type": "string",+ "enum": [+ "low",+ "medium",+ "high",+ "xhigh",+ "max"+ ]+ },+ "run_in_background": {+ "type": "boolean"+ },+ "isolation": {+ "type": "string",+ "enum": [+ "worktree",+ "remote"+ ]+ }+ },+ "required": [+ "description",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Bash",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "command": {+ "type": "string"+ },+ "timeout": {+ "type": "number"+ },+ "description": {+ "type": "string"+ },+ "run_in_background": {+ "type": "boolean"+ },+ "dangerouslyDisableSandbox": {+ "type": "boolean"+ }+ },+ "required": [+ "command"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Edit",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "old_string": {+ "type": "string"+ },+ "new_string": {+ "type": "string"+ },+ "replace_all": {+ "default": false,+ "type": "boolean"+ }+ },+ "required": [+ "file_path",+ "old_string",+ "new_string"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "EnterWorktree",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "path": {+ "type": "string"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "ExitWorktree",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "enum": [+ "keep",+ "remove"+ ]+ },+ "discard_changes": {+ "type": "boolean"+ }+ },+ "required": [+ "action"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "NotebookEdit",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "notebook_path": {+ "type": "string"+ },+ "cell_id": {+ "type": "string"+ },+ "new_source": {+ "type": "string"+ },+ "cell_type": {+ "type": "string",+ "enum": [+ "code",+ "markdown"+ ]+ },+ "edit_mode": {+ "type": "string",+ "enum": [+ "replace",+ "insert",+ "delete"+ ]+ }+ },+ "required": [+ "notebook_path",+ "new_source"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Read",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "limit": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 9007199254740991+ },+ "pages": {+ "type": "string"+ },+ "allow_large": {+ "type": "boolean"+ }+ },+ "required": [+ "file_path"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "SendMessage",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "to": {+ "type": "string",+ "allOf": [+ {+ "pattern": "^[^\\n\\r]*$"+ },+ {+ "pattern": "^[\\s\\S]{0,300}$"+ }+ ]+ },+ "summary": {+ "type": "string",+ "maxLength": 200+ },+ "message": {+ "default": "",+ "type": "string"+ },+ "notify_when_idle": {+ "type": "boolean"+ }+ },+ "required": [+ "to",+ "message"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Skill",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "skill": {+ "type": "string"+ },+ "args": {+ "type": "string"+ }+ },+ "required": [+ "skill"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "TaskStop",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "task_id": {+ "type": "string"+ },+ "shell_id": {+ "type": "string"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "WebFetch",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "url": {+ "type": "string",+ "format": "uri"+ },+ "prompt": {+ "type": "string"+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ }+ },+ "required": [+ "url",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "WebSearch",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "minLength": 2+ },+ "allowed_domains": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "blocked_domains": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "query"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Write",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "content": {+ "type": "string"+ }+ },+ "required": [+ "file_path",+ "content"+ ],+ "additionalProperties": false+ }+ }+ ],+ "metadata": {+ "user_id": "{\"device_id\":\"(device id)\",\"account_uuid\":\"\",\"session_id\":\"(session id)\"}"+ },+ "max_tokens": 32768,+ "thinking": {+ "type": "adaptive"+ },+ "output_config": {+ "effort": "high"+ },+ "stream": true+ },+ "expect": {+ "error": "output_config.effort: Extra inputs are not permitted"+ }+ },+ {+ "name": "bare_first_turn",+ "setup": "bare",+ "path": "/v1/messages?beta=true",+ "headers": {+ "anthropic-version": "2023-06-01",+ "anthropic-beta": "claude-code-20250219,interleaved-thinking-2025-05-14,effort-2025-11-24",+ "anthropic-dangerous-direct-browser-access": "true",+ "authorization": "Bearer (token)",+ "x-api-key": "(token)",+ "x-app": "cli",+ "x-claude-code-session-id": "(session id)",+ "content-type": "application/json",+ "accept": "application/json",+ "user-agent": "claude-cli/2.1.300 (external, sdk-cli)",+ "x-stainless-lang": "js",+ "x-stainless-package-version": "0.128.0",+ "x-stainless-retry-count": "0",+ "x-stainless-timeout": "600"+ },+ "body": {+ "model": "zai-org/GLM-5.3-Flash:relay",+ "messages": [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "(user prompt)",+ "cache_control": {+ "type": "ephemeral"+ }+ }+ ]+ }+ ],+ "system": [+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 1)"+ },+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 2)"+ }+ ],+ "tools": [+ {+ "name": "Bash",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "command": {+ "type": "string"+ },+ "timeout": {+ "type": "number"+ },+ "description": {+ "type": "string"+ },+ "dangerouslyDisableSandbox": {+ "type": "boolean"+ }+ },+ "required": [+ "command"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Edit",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "old_string": {+ "type": "string"+ },+ "new_string": {+ "type": "string"+ },+ "replace_all": {+ "default": false,+ "type": "boolean"+ }+ },+ "required": [+ "file_path",+ "old_string",+ "new_string"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Read",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "limit": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 9007199254740991+ },+ "pages": {+ "type": "string"+ },+ "allow_large": {+ "type": "boolean"+ }+ },+ "required": [+ "file_path"+ ],+ "additionalProperties": false+ }+ }+ ],+ "metadata": {+ "user_id": "{\"device_id\":\"(device id)\",\"account_uuid\":\"\",\"session_id\":\"(session id)\"}"+ },+ "max_tokens": 32768,+ "thinking": {+ "type": "adaptive"+ },+ "output_config": {+ "effort": "high"+ },+ "stream": true+ },+ "expect": {+ "error": "output_config.effort: Extra inputs are not permitted"+ }+ },+ {+ "name": "without_recipe_first_turn",+ "setup": "without_recipe",+ "path": "/v1/messages?beta=true",+ "headers": {+ "anthropic-version": "2023-06-01",+ "anthropic-beta": "claude-code-20250219,interleaved-thinking-2025-05-14,thinking-token-count-2026-05-13,context-management-2025-06-27,prompt-caching-scope-2026-01-05,mid-conversation-tool-changes-2026-07-01,effort-2025-11-24",+ "anthropic-dangerous-direct-browser-access": "true",+ "authorization": "Bearer (token)",+ "x-app": "cli",+ "x-claude-code-session-id": "(session id)",+ "content-type": "application/json",+ "accept": "application/json",+ "user-agent": "claude-cli/2.1.300 (external, sdk-cli)",+ "x-stainless-lang": "js",+ "x-stainless-package-version": "0.128.0",+ "x-stainless-retry-count": "0",+ "x-stainless-timeout": "600"+ },+ "body": {+ "model": "zai-org/GLM-5.3-Flash:relay",+ "messages": [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 1)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "(user prompt)"+ }+ ]+ },+ {+ "role": "system",+ "content": [+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client environment and session context)"+ }+ ]+ }+ ],+ "system": [+ {+ "type": "text",+ "text": "(client system prompt block 1)"+ },+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 2)"+ },+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 3)"+ }+ ],+ "tools": [+ {+ "name": "Agent",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "description": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "subagent_type": {+ "type": "string"+ },+ "model": {+ "type": "string",+ "enum": [+ "sonnet",+ "opus",+ "haiku",+ "fable"+ ]+ },+ "effort": {+ "type": "string",+ "enum": [+ "low",+ "medium",+ "high",+ "xhigh",+ "max"+ ]+ },+ "run_in_background": {+ "type": "boolean"+ },+ "isolation": {+ "type": "string",+ "enum": [+ "worktree",+ "remote"+ ]+ }+ },+ "required": [+ "description",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Bash",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "command": {+ "type": "string"+ },+ "timeout": {+ "type": "number"+ },+ "description": {+ "type": "string"+ },+ "run_in_background": {+ "type": "boolean"+ },+ "dangerouslyDisableSandbox": {+ "type": "boolean"+ }+ },+ "required": [+ "command"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronCreate",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "cron": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "recurring": {+ "type": "boolean"+ },+ "durable": {+ "type": "boolean"+ }+ },+ "required": [+ "cron",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronDelete",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronList",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {},+ "additionalProperties": false+ }+ },+ {+ "name": "Edit",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "old_string": {+ "type": "string"+ },+ "new_string": {+ "type": "string"+ },+ "replace_all": {+ "default": false,+ "type": "boolean"+ }+ },+ "required": [+ "file_path",+ "old_string",+ "new_string"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "EnterWorktree",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "path": {+ "type": "string"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "ExitWorktree",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "enum": [+ "keep",+ "remove"+ ]+ },+ "discard_changes": {+ "type": "boolean"+ }+ },+ "required": [+ "action"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ListAgents",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "channel": {+ "type": "string",+ "maxLength": 256+ },+ "q": {+ "type": "string",+ "maxLength": 256+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "NotebookEdit",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "notebook_path": {+ "type": "string"+ },+ "cell_id": {+ "type": "string"+ },+ "new_source": {+ "type": "string"+ },+ "cell_type": {+ "type": "string",+ "enum": [+ "code",+ "markdown"+ ]+ },+ "edit_mode": {+ "type": "string",+ "enum": [+ "replace",+ "insert",+ "delete"+ ]+ }+ },+ "required": [+ "notebook_path",+ "new_source"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Read",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "limit": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 9007199254740991+ },+ "pages": {+ "type": "string"+ },+ "allow_large": {+ "type": "boolean"+ }+ },+ "required": [+ "file_path"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ReportFindings",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "level": {+ "type": "string",+ "enum": [+ "low",+ "medium",+ "high",+ "xhigh",+ "max"+ ]+ },+ "findings": {+ "maxItems": 32,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "file": {+ "type": "string"+ },+ "line": {+ "type": "integer",+ "minimum": -9007199254740991,+ "maximum": 9007199254740991+ },+ "summary": {+ "type": "string"+ },+ "short_summary": {+ "type": "string",+ "maxLength": 60+ },+ "failure_scenario": {+ "type": "string"+ },+ "category": {+ "type": "string",+ "maxLength": 40+ },+ "verdict": {+ "type": "string",+ "enum": [+ "CONFIRMED",+ "PLAUSIBLE"+ ]+ },+ "outcome": {+ "type": "string",+ "enum": [+ "fixed",+ "skipped",+ "no_change_needed"+ ]+ }+ },+ "required": [+ "file",+ "summary",+ "failure_scenario"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "findings"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ScheduleWakeup",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "delaySeconds": {+ "type": "number"+ },+ "reason": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "stop": {+ "type": "boolean"+ },+ "noop": {+ "type": "boolean"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "SendMessage",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "to": {+ "type": "string",+ "allOf": [+ {+ "pattern": "^[^\\n\\r]*$"+ },+ {+ "pattern": "^[\\s\\S]{0,300}$"+ }+ ]+ },+ "summary": {+ "type": "string",+ "maxLength": 200+ },+ "message": {+ "default": "",+ "type": "string"+ },+ "notify_when_idle": {+ "type": "boolean"+ }+ },+ "required": [+ "to",+ "message"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Skill",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "skill": {+ "type": "string"+ },+ "args": {+ "type": "string"+ }+ },+ "required": [+ "skill"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "TaskStop",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "task_id": {+ "type": "string"+ },+ "shell_id": {+ "type": "string"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "WebFetch",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "url": {+ "type": "string",+ "format": "uri"+ },+ "prompt": {+ "type": "string"+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ }+ },+ "required": [+ "url",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "WebSearch",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "minLength": 2+ },+ "allowed_domains": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "blocked_domains": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "query"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Workflow",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "script": {+ "type": "string",+ "maxLength": 524288+ },+ "name": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "title": {+ "type": "string"+ },+ "args": {},+ "scriptPath": {+ "type": "string"+ },+ "resumeFromRunId": {+ "type": "string",+ "pattern": "^wf_[a-z0-9-]{6,}$"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "Write",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "content": {+ "type": "string"+ }+ },+ "required": [+ "file_path",+ "content"+ ],+ "additionalProperties": false+ }+ }+ ],+ "metadata": {+ "user_id": "{\"device_id\":\"(device id)\",\"account_uuid\":\"\",\"session_id\":\"(session id)\"}"+ },+ "max_tokens": 32000,+ "thinking": {+ "type": "adaptive",+ "display": "omitted"+ },+ "context_management": {+ "edits": [+ {+ "type": "clear_thinking_20251015",+ "keep": "all"+ }+ ]+ },+ "output_config": {+ "effort": "high"+ },+ "stream": true+ },+ "expect": {+ "error": "context_management: Extra inputs are not permitted (Claude Code: set CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1)"+ }+ },+ {+ "name": "without_recipe_tool_loop",+ "setup": "without_recipe",+ "path": "/v1/messages?beta=true",+ "headers": {+ "anthropic-version": "2023-06-01",+ "anthropic-beta": "claude-code-20250219,interleaved-thinking-2025-05-14,thinking-token-count-2026-05-13,context-management-2025-06-27,prompt-caching-scope-2026-01-05,mid-conversation-tool-changes-2026-07-01,effort-2025-11-24",+ "anthropic-dangerous-direct-browser-access": "true",+ "authorization": "Bearer (token)",+ "x-app": "cli",+ "x-claude-code-session-id": "(session id)",+ "content-type": "application/json",+ "accept": "application/json",+ "user-agent": "claude-cli/2.1.300 (external, sdk-cli)",+ "x-stainless-lang": "js",+ "x-stainless-package-version": "0.128.0",+ "x-stainless-retry-count": "0",+ "x-stainless-timeout": "600"+ },+ "body": {+ "model": "zai-org/GLM-5.3-Flash:relay",+ "messages": [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "<system-reminder>\n(client reminder 1)\n</system-reminder>\n"+ },+ {+ "type": "text",+ "text": "(user prompt)"+ }+ ]+ },+ {+ "role": "system",+ "content": "(client environment and session context)"+ },+ {+ "role": "assistant",+ "content": [+ {+ "type": "tool_use",+ "id": "toolu_03",+ "name": "Bash",+ "input": {+ "command": "echo capture-ok",+ "description": "(description)"+ }+ }+ ]+ },+ {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "toolu_03",+ "content": "(tool output)",+ "is_error": false+ }+ ]+ },+ {+ "role": "system",+ "content": [+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client environment and session context)"+ }+ ]+ }+ ],+ "system": [+ {+ "type": "text",+ "text": "(client system prompt block 1)"+ },+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 2)"+ },+ {+ "type": "text",+ "cache_control": {+ "type": "ephemeral"+ },+ "text": "(client system prompt block 3)"+ }+ ],+ "tools": [+ {+ "name": "Agent",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "description": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "subagent_type": {+ "type": "string"+ },+ "model": {+ "type": "string",+ "enum": [+ "sonnet",+ "opus",+ "haiku",+ "fable"+ ]+ },+ "effort": {+ "type": "string",+ "enum": [+ "low",+ "medium",+ "high",+ "xhigh",+ "max"+ ]+ },+ "run_in_background": {+ "type": "boolean"+ },+ "isolation": {+ "type": "string",+ "enum": [+ "worktree",+ "remote"+ ]+ }+ },+ "required": [+ "description",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Bash",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "command": {+ "type": "string"+ },+ "timeout": {+ "type": "number"+ },+ "description": {+ "type": "string"+ },+ "run_in_background": {+ "type": "boolean"+ },+ "dangerouslyDisableSandbox": {+ "type": "boolean"+ }+ },+ "required": [+ "command"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronCreate",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "cron": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "recurring": {+ "type": "boolean"+ },+ "durable": {+ "type": "boolean"+ }+ },+ "required": [+ "cron",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronDelete",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "CronList",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {},+ "additionalProperties": false+ }+ },+ {+ "name": "Edit",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "old_string": {+ "type": "string"+ },+ "new_string": {+ "type": "string"+ },+ "replace_all": {+ "default": false,+ "type": "boolean"+ }+ },+ "required": [+ "file_path",+ "old_string",+ "new_string"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "EnterWorktree",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "path": {+ "type": "string"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "ExitWorktree",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "enum": [+ "keep",+ "remove"+ ]+ },+ "discard_changes": {+ "type": "boolean"+ }+ },+ "required": [+ "action"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ListAgents",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "channel": {+ "type": "string",+ "maxLength": 256+ },+ "q": {+ "type": "string",+ "maxLength": 256+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "NotebookEdit",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "notebook_path": {+ "type": "string"+ },+ "cell_id": {+ "type": "string"+ },+ "new_source": {+ "type": "string"+ },+ "cell_type": {+ "type": "string",+ "enum": [+ "code",+ "markdown"+ ]+ },+ "edit_mode": {+ "type": "string",+ "enum": [+ "replace",+ "insert",+ "delete"+ ]+ }+ },+ "required": [+ "notebook_path",+ "new_source"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Read",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "limit": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "maximum": 9007199254740991+ },+ "pages": {+ "type": "string"+ },+ "allow_large": {+ "type": "boolean"+ }+ },+ "required": [+ "file_path"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ReportFindings",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "level": {+ "type": "string",+ "enum": [+ "low",+ "medium",+ "high",+ "xhigh",+ "max"+ ]+ },+ "findings": {+ "maxItems": 32,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "file": {+ "type": "string"+ },+ "line": {+ "type": "integer",+ "minimum": -9007199254740991,+ "maximum": 9007199254740991+ },+ "summary": {+ "type": "string"+ },+ "short_summary": {+ "type": "string",+ "maxLength": 60+ },+ "failure_scenario": {+ "type": "string"+ },+ "category": {+ "type": "string",+ "maxLength": 40+ },+ "verdict": {+ "type": "string",+ "enum": [+ "CONFIRMED",+ "PLAUSIBLE"+ ]+ },+ "outcome": {+ "type": "string",+ "enum": [+ "fixed",+ "skipped",+ "no_change_needed"+ ]+ }+ },+ "required": [+ "file",+ "summary",+ "failure_scenario"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "findings"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "ScheduleWakeup",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "delaySeconds": {+ "type": "number"+ },+ "reason": {+ "type": "string"+ },+ "prompt": {+ "type": "string"+ },+ "stop": {+ "type": "boolean"+ },+ "noop": {+ "type": "boolean"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "SendMessage",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "to": {+ "type": "string",+ "allOf": [+ {+ "pattern": "^[^\\n\\r]*$"+ },+ {+ "pattern": "^[\\s\\S]{0,300}$"+ }+ ]+ },+ "summary": {+ "type": "string",+ "maxLength": 200+ },+ "message": {+ "default": "",+ "type": "string"+ },+ "notify_when_idle": {+ "type": "boolean"+ }+ },+ "required": [+ "to",+ "message"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Skill",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "skill": {+ "type": "string"+ },+ "args": {+ "type": "string"+ }+ },+ "required": [+ "skill"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "TaskStop",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "task_id": {+ "type": "string"+ },+ "shell_id": {+ "type": "string"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "WebFetch",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "url": {+ "type": "string",+ "format": "uri"+ },+ "prompt": {+ "type": "string"+ },+ "offset": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ }+ },+ "required": [+ "url",+ "prompt"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "WebSearch",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "minLength": 2+ },+ "allowed_domains": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "blocked_domains": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "query"+ ],+ "additionalProperties": false+ }+ },+ {+ "name": "Workflow",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "script": {+ "type": "string",+ "maxLength": 524288+ },+ "name": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "title": {+ "type": "string"+ },+ "args": {},+ "scriptPath": {+ "type": "string"+ },+ "resumeFromRunId": {+ "type": "string",+ "pattern": "^wf_[a-z0-9-]{6,}$"+ }+ },+ "additionalProperties": false+ }+ },+ {+ "name": "Write",+ "description": "(tool description)",+ "input_schema": {+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "file_path": {+ "type": "string"+ },+ "content": {+ "type": "string"+ }+ },+ "required": [+ "file_path",+ "content"+ ],+ "additionalProperties": false+ }+ }+ ],+ "metadata": {+ "user_id": "{\"device_id\":\"(device id)\",\"account_uuid\":\"\",\"session_id\":\"(session id)\"}"+ },+ "max_tokens": 32000,+ "thinking": {+ "type": "adaptive",+ "display": "omitted"+ },+ "context_management": {+ "edits": [+ {+ "type": "clear_thinking_20251015",+ "keep": "all"+ }+ ]+ },+ "output_config": {+ "effort": "high"+ },+ "stream": true+ },+ "expect": {+ "error": "context_management: Extra inputs are not permitted (Claude Code: set CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1)"+ }+ }+ ]+}diff --git a/conformance/anthropic_messages/error_vectors.json b/conformance/anthropic_messages/error_vectors.jsonnew file mode 100644index 000000000..7374dda20--- /dev/null+++ b/conformance/anthropic_messages/error_vectors.json@@ -0,0 +1,138 @@+{+ "description": "An inner error answer (status, headers, JSON body or null for an empty body) and the Anthropic error answer it becomes. Headers not listed under expect.headers are not asserted, except that expect.absent_headers must be missing.",+ "errors": [+ {+ "name": "model without tool calling",+ "status": 400,+ "body": {"error": {"message": "Model 'm' does not support tool calling", "type": "invalid_request_error", "param": "tools", "code": "unsupported_field"}},+ "expect": {"status": 400, "type": "invalid_request_error", "message": "tools: Model 'm' does not support tool calling", "headers": {"x-sie-error-code": "unsupported_field"}}+ },+ {+ "name": "output cap named by the chat route",+ "status": 400,+ "body": {"error": {"message": "max_completion_tokens (40000) exceeds model max_output_tokens (32768)", "type": "invalid_request_error", "param": "max_completion_tokens", "code": "invalid_request"}},+ "expect": {"status": 400, "type": "invalid_request_error", "message": "max_tokens: 40000 > 32768, which is the maximum allowed number of output tokens for this model"}+ },+ {+ "name": "output cap named by the worker",+ "status": 400,+ "body": {"error": {"message": "max_new_tokens (40000) exceeds model cap (4096)", "type": "context_length_exceeded", "param": null, "code": "context_exceeded"}},+ "expect": {"status": 400, "type": "invalid_request_error", "message": "max_tokens: 40000 > 4096, which is the maximum allowed number of output tokens for this model"}+ },+ {+ "name": "prompt over the context window",+ "status": 400,+ "headers": {"x-sie-request-id": "req-7"},+ "body": {"error": {"message": "prompt_tokens (130000) + max_new_tokens (32768) = 162768 exceeds context_length (131072) for model 'm'", "type": "context_length_exceeded", "param": null, "code": "context_exceeded"}},+ "expect": {"status": 400, "type": "invalid_request_error", "message": "prompt is too long: 162768 tokens > 131072 maximum", "request_id": "req-7", "headers": {"request-id": "req-7", "x-sie-request-id": "req-7"}}+ },+ {+ "name": "prompt over the context window, independent accounting",+ "status": 400,+ "body": {"error": {"message": "prompt_tokens (140000) exceeds context_length (131072) for model 'm'", "type": "context_length_exceeded", "param": null, "code": "context_exceeded"}},+ "expect": {"status": 400, "type": "invalid_request_error", "message": "prompt is too long: 140000 tokens > 131072 maximum"}+ },+ {+ "name": "prompt over the byte limit",+ "status": 400,+ "body": {"error": {"message": "prompt exceeds the configured UTF-8 size limit", "type": "context_length_exceeded", "param": null, "code": "INPUT_TOO_LONG"}},+ "expect": {"status": 400, "type": "invalid_request_error", "message": "prompt is too long"}+ },+ {+ "name": "image on a text-only model names the block",+ "status": 400,+ "first_image": "messages.2.content.0.tool_result.content.0.image",+ "body": {"error": {"message": "Model 'm' does not support image input", "type": "invalid_request_error", "param": "messages", "code": "unsupported_field"}},+ "expect": {"status": 400, "type": "invalid_request_error", "message": "messages.2.content.0.tool_result.content.0.image: Model 'm' does not support image input"}+ },+ {+ "name": "unknown model",+ "status": 404,+ "body": {"error": {"message": "Model 'nope' not found", "type": "invalid_request_error", "param": "model", "code": "model_not_found"}},+ "expect": {"status": 404, "type": "not_found_error", "message": "Model 'nope' not found"}+ },+ {+ "name": "missing credential, SIE envelope",+ "status": 401,+ "body": {"detail": {"code": "UNAUTHORIZED", "message": "Missing or invalid bearer token"}},+ "expect": {"status": 401, "type": "authentication_error", "message": "Missing or invalid bearer token", "headers": {"x-sie-error-code": "UNAUTHORIZED"}}+ },+ {+ "name": "payment required",+ "status": 402,+ "body": {"error": {"message": "insufficient credits", "type": "invalid_request_error", "param": null, "code": "INSUFFICIENT_CREDITS"}},+ "expect": {"status": 402, "type": "billing_error", "message": "insufficient credits"}+ },+ {+ "name": "forbidden",+ "status": 403,+ "body": {"detail": {"code": "INSUFFICIENT_SCOPE", "message": "the key does not grant inference"}},+ "expect": {"status": 403, "type": "permission_error", "message": "the key does not grant inference"}+ },+ {+ "name": "too large",+ "status": 413,+ "body": {"error": {"message": "Request body too large (max 16777216 bytes)", "type": "invalid_request_error", "param": null, "code": "payload_too_large"}},+ "expect": {"status": 413, "type": "request_too_large", "message": "Request body too large (max 16777216 bytes)"}+ },+ {+ "name": "rate limited",+ "status": 429,+ "headers": {"retry-after": "1"},+ "body": {"error": {"message": "rate limit exceeded", "type": "rate_limit_error", "param": null, "code": "rate_limit_exceeded"}},+ "expect": {"status": 429, "type": "rate_limit_error", "message": "rate limit exceeded", "headers": {"retry-after": "1", "x-should-retry": "true"}}+ },+ {+ "name": "provisioning keeps 503 and caps Retry-After at 60",+ "status": 503,+ "headers": {"retry-after": "120", "x-sie-error-code": "PROVISIONING"},+ "body": {"error": {"message": "Model 'm' is provisioning; retry later", "type": "server_error", "param": null, "code": "provisioning"}},+ "expect": {"status": 503, "type": "overloaded_error", "message": "Model 'm' is provisioning; retry later", "headers": {"retry-after": "60", "x-should-retry": "true", "x-sie-error-code": "PROVISIONING"}}+ },+ {+ "name": "unparseable Retry-After is dropped",+ "status": 503,+ "headers": {"retry-after": "Wed, 21 Oct 2026 07:28:00 GMT"},+ "body": {"error": {"message": "busy", "type": "server_error", "param": null, "code": "RESOURCE_EXHAUSTED"}},+ "expect": {"status": 503, "type": "overloaded_error", "message": "busy", "absent_headers": ["retry-after", "x-should-retry"]}+ },+ {+ "name": "gateway timeout",+ "status": 504,+ "body": {"error": {"message": "Generation aborted: first_chunk timeout", "type": "server_error", "param": null, "code": "first_chunk_timeout"}},+ "expect": {"status": 504, "type": "timeout_error", "message": "Generation aborted: first_chunk timeout"}+ },+ {+ "name": "worker output fault",+ "status": 500,+ "body": {"error": {"message": "internal error during generation", "type": "server_error", "param": null, "code": "inference_error", "attempt_id": "a1"}},+ "expect": {"status": 500, "type": "api_error", "message": "internal error during generation"}+ },+ {+ "name": "model load failure",+ "status": 502,+ "headers": {"x-sie-error-code": "MODEL_LOAD_FAILED", "x-sie-error-version": "0.10.1"},+ "body": {"error": {"code": "MODEL_LOAD_FAILED", "message": "The requested model failed to load."}},+ "expect": {"status": 502, "type": "api_error", "message": "The requested model failed to load.", "headers": {"x-sie-error-code": "MODEL_LOAD_FAILED", "x-sie-error-version": "0.10.1"}}+ },+ {+ "name": "empty not found",+ "status": 404,+ "body": null,+ "expect": {"status": 404, "type": "not_found_error", "message": "not found"}+ },+ {+ "name": "method not allowed",+ "status": 405,+ "body": null,+ "expect": {"status": 405, "type": "invalid_request_error", "message": "method not allowed"}+ },+ {+ "name": "an Anthropic envelope passes through",+ "status": 529,+ "headers": {"retry-after": "5"},+ "body": {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}, "request_id": null},+ "expect": {"status": 529, "type": "overloaded_error", "message": "Overloaded", "headers": {"retry-after": "5", "x-should-retry": "true"}}+ }+ ]+}diff --git a/conformance/anthropic_messages/request_vectors.json b/conformance/anthropic_messages/request_vectors.jsonnew file mode 100644index 000000000..9ef8d3c99--- /dev/null+++ b/conformance/anthropic_messages/request_vectors.json@@ -0,0 +1,405 @@+{+ "accepted": [+ {+ "name": "string content",+ "body": {"model": "m", "max_tokens": 64, "messages": [{"role": "user", "content": "Hi"}]},+ "chat": {+ "model": "m",+ "messages": [{"role": "user", "content": "Hi"}],+ "max_tokens": 64,+ "stream": false,+ "include_reasoning": false+ }+ },+ {+ "name": "system blocks and text blocks are concatenated as sent, inert fields dropped",+ "anthropic_version": "2023-06-01",+ "body": {+ "model": "org/model:profile",+ "max_tokens": 32,+ "cache_control": {"type": "ephemeral"},+ "metadata": {"user_id": "opaque-user"},+ "system": [+ {"type": "text", "text": "You are terse.", "cache_control": {"type": "ephemeral"}},+ {"type": "text", "text": "\nAnswer in English."}+ ],+ "messages": [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "<context>notes</context>\n"},+ {"type": "text", "text": "", "cache_control": {"type": "ephemeral"}},+ {"type": "text", "text": "Summarize.", "cache_control": {"type": "ephemeral", "ttl": "5m"}}+ ]+ }+ ]+ },+ "chat": {+ "model": "org/model:profile",+ "messages": [+ {"role": "system", "content": "You are terse.\nAnswer in English."},+ {"role": "user", "content": "<context>notes</context>\nSummarize."}+ ],+ "max_tokens": 32,+ "stream": false,+ "include_reasoning": false+ }+ },+ {+ "name": "sampling and stop sequences",+ "body": {+ "model": "m",+ "max_tokens": 16,+ "temperature": 0.5,+ "top_p": 0.9,+ "top_k": 40,+ "stop_sequences": ["</block>", "END"],+ "messages": [{"role": "user", "content": "x"}]+ },+ "chat": {+ "model": "m",+ "messages": [{"role": "user", "content": "x"}],+ "max_tokens": 16,+ "stop": ["</block>", "END"],+ "temperature": 0.5,+ "top_p": 0.9,+ "top_k": 40,+ "stream": false,+ "include_reasoning": false+ }+ },+ {+ "name": "streaming asks for usage",+ "body": {"model": "m", "max_tokens": 16, "stream": true, "stop_sequences": [], "messages": [{"role": "user", "content": "x"}]},+ "chat": {+ "model": "m",+ "messages": [{"role": "user", "content": "x"}],+ "max_tokens": 16,+ "stream": true,+ "stream_options": {"include_usage": true},+ "include_reasoning": false+ }+ },+ {+ "name": "custom tools and tool_choice any without parallel calls",+ "body": {+ "model": "m",+ "max_tokens": 16,+ "tools": [+ {+ "name": "get_weather",+ "description": "Weather for a city",+ "input_schema": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},+ "cache_control": {"type": "ephemeral"},+ "eager_input_streaming": true+ },+ {"type": "custom", "name": "noop", "input_schema": {"type": "object"}}+ ],+ "tool_choice": {"type": "any", "disable_parallel_tool_use": true},+ "messages": [{"role": "user", "content": "Weather in Paris?"}]+ },+ "chat": {+ "model": "m",+ "messages": [{"role": "user", "content": "Weather in Paris?"}],+ "max_tokens": 16,+ "stream": false,+ "tools": [+ {+ "type": "function",+ "function": {+ "name": "get_weather",+ "description": "Weather for a city",+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}+ }+ },+ {"type": "function", "function": {"name": "noop", "parameters": {"type": "object"}}}+ ],+ "tool_choice": "required",+ "parallel_tool_calls": false,+ "include_reasoning": false+ }+ },+ {+ "name": "named tool choice",+ "body": {+ "model": "m",+ "max_tokens": 16,+ "tools": [{"name": "lookup", "input_schema": {"type": "object"}}],+ "tool_choice": {"type": "tool", "name": "lookup"},+ "messages": [{"role": "user", "content": "go"}]+ },+ "chat": {+ "model": "m",+ "messages": [{"role": "user", "content": "go"}],+ "max_tokens": 16,+ "stream": false,+ "tools": [{"type": "function", "function": {"name": "lookup", "parameters": {"type": "object"}}}],+ "tool_choice": {"type": "function", "function": {"name": "lookup"}},+ "include_reasoning": false+ }+ },+ {+ "name": "tool_choice none and auto",+ "body": {+ "model": "m",+ "max_tokens": 16,+ "tools": [{"name": "lookup", "input_schema": {"type": "object"}}],+ "tool_choice": {"type": "none"},+ "messages": [{"role": "user", "content": "go"}]+ },+ "chat": {+ "model": "m",+ "messages": [{"role": "user", "content": "go"}],+ "max_tokens": 16,+ "stream": false,+ "tools": [{"type": "function", "function": {"name": "lookup", "parameters": {"type": "object"}}}],+ "tool_choice": "none",+ "include_reasoning": false+ }+ },+ {+ "name": "tool_choice auto without tools is dropped",+ "body": {"model": "m", "max_tokens": 16, "tools": [], "tool_choice": {"type": "auto"}, "messages": [{"role": "user", "content": "go"}]},+ "chat": {+ "model": "m",+ "messages": [{"role": "user", "content": "go"}],+ "max_tokens": 16,+ "stream": false,+ "include_reasoning": false+ }+ },+ {+ "name": "tool loop: tool results first, following text becomes a user turn",+ "body": {+ "model": "m",+ "max_tokens": 16,+ "tools": [{"name": "add", "input_schema": {"type": "object"}}],+ "messages": [+ {"role": "user", "content": "Add 40 and 2."},+ {+ "role": "assistant",+ "content": [+ {"type": "thinking", "thinking": "I should call add.", "signature": "sie-unsigned"},+ {"type": "text", "text": "Calling add."},+ {"type": "tool_use", "id": "call_1", "name": "add", "input": {"a": 40, "b": 2}}+ ]+ },+ {+ "role": "user",+ "content": [+ {"type": "tool_result", "tool_use_id": "call_1", "content": "42", "is_error": false, "cache_control": {"type": "ephemeral"}},+ {"type": "text", "text": "Now explain."}+ ]+ }+ ]+ },+ "chat": {+ "model": "m",+ "messages": [+ {"role": "user", "content": "Add 40 and 2."},+ {+ "role": "assistant",+ "content": "Calling add.",+ "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "add", "arguments": "{\"a\":40,\"b\":2}"}}]+ },+ {"role": "tool", "tool_call_id": "call_1", "content": "42"},+ {"role": "user", "content": "Now explain."}+ ],+ "max_tokens": 16,+ "stream": false,+ "tools": [{"type": "function", "function": {"name": "add", "parameters": {"type": "object"}}}],+ "include_reasoning": false+ }+ },+ {+ "name": "parallel tool results and a tool_use-only assistant turn",+ "body": {+ "model": "m",+ "max_tokens": 16,+ "messages": [+ {"role": "user", "content": "Run both."},+ {+ "role": "assistant",+ "content": [+ {"type": "redacted_thinking", "data": "opaque"},+ {"type": "tool_use", "id": "t1", "name": "run", "input": {"cmd": "one"}},+ {"type": "tool_use", "id": "t2", "name": "run", "input": {"cmd": "two"}}+ ]+ },+ {+ "role": "user",+ "content": [+ {"type": "tool_result", "tool_use_id": "t1", "content": [{"type": "text", "text": "out "}, {"type": "text", "text": "one"}]},+ {"type": "tool_result", "tool_use_id": "t2", "is_error": true, "content": "failed"}+ ]+ }+ ]+ },+ "chat": {+ "model": "m",+ "messages": [+ {"role": "user", "content": "Run both."},+ {+ "role": "assistant",+ "content": null,+ "tool_calls": [+ {"id": "t1", "type": "function", "function": {"name": "run", "arguments": "{\"cmd\":\"one\"}"}},+ {"id": "t2", "type": "function", "function": {"name": "run", "arguments": "{\"cmd\":\"two\"}"}}+ ]+ },+ {"role": "tool", "tool_call_id": "t1", "content": "out one"},+ {"role": "tool", "tool_call_id": "t2", "content": "failed"}+ ],+ "max_tokens": 16,+ "stream": false,+ "include_reasoning": false+ }+ },+ {+ "name": "images in a tool result follow the tool message in a user turn",+ "body": {+ "model": "m",+ "max_tokens": 16,+ "messages": [+ {"role": "user", "content": "Read the image."},+ {"role": "assistant", "content": [{"type": "tool_use", "id": "r1", "name": "read", "input": {}}]},+ {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "r1",+ "content": [+ {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="}},+ {"type": "text", "text": "pixel.png"}+ ]+ }+ ]+ }+ ]+ },+ "first_image": "messages.2.content.0.tool_result.content.0.image",+ "chat": {+ "model": "m",+ "messages": [+ {"role": "user", "content": "Read the image."},+ {+ "role": "assistant",+ "content": null,+ "tool_calls": [{"id": "r1", "type": "function", "function": {"name": "read", "arguments": "{}"}}]+ },+ {"role": "tool", "tool_call_id": "r1", "content": "pixel.png"},+ {+ "role": "user",+ "content": [+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="}}+ ]+ }+ ],+ "max_tokens": 16,+ "stream": false,+ "include_reasoning": false+ }+ },+ {+ "name": "user image between text keeps its position",+ "body": {+ "model": "m",+ "max_tokens": 16,+ "messages": [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "Before "},+ {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "/9j/AA=="}, "cache_control": {"type": "ephemeral"}},+ {"type": "text", "text": "after"}+ ]+ }+ ]+ },+ "first_image": "messages.0.content.1.image",+ "chat": {+ "model": "m",+ "messages": [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "Before "},+ {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,/9j/AA=="}},+ {"type": "text", "text": "after"}+ ]+ }+ ],+ "max_tokens": 16,+ "stream": false,+ "include_reasoning": false+ }+ },+ {+ "name": "adaptive thinking opts into reasoning",+ "body": {"model": "m", "max_tokens": 16, "thinking": {"type": "adaptive"}, "messages": [{"role": "user", "content": "x"}]},+ "chat": {"model": "m", "messages": [{"role": "user", "content": "x"}], "max_tokens": 16, "stream": false, "include_reasoning": true}+ },+ {+ "name": "enabled thinking with a budget opts into reasoning",+ "body": {"model": "m", "max_tokens": 4096, "thinking": {"type": "enabled", "budget_tokens": 1024, "display": "summarized"}, "messages": [{"role": "user", "content": "x"}]},+ "chat": {"model": "m", "messages": [{"role": "user", "content": "x"}], "max_tokens": 4096, "stream": false, "include_reasoning": true}+ },+ {+ "name": "omitted display keeps reasoning private",+ "body": {"model": "m", "max_tokens": 16, "thinking": {"type": "adaptive", "display": "omitted"}, "messages": [{"role": "user", "content": "x"}]},+ "chat": {"model": "m", "messages": [{"role": "user", "content": "x"}], "max_tokens": 16, "stream": false, "include_reasoning": false}+ },+ {+ "name": "disabled thinking",+ "body": {"model": "m", "max_tokens": 16, "thinking": {"type": "disabled"}, "messages": [{"role": "user", "content": "x"}]},+ "chat": {"model": "m", "messages": [{"role": "user", "content": "x"}], "max_tokens": 16, "stream": false, "include_reasoning": false}+ },+ {+ "name": "empty output_config is accepted",+ "body": {"model": "m", "max_tokens": 16, "output_config": {}, "messages": [{"role": "user", "content": "x"}]},+ "chat": {"model": "m", "messages": [{"role": "user", "content": "x"}], "max_tokens": 16, "stream": false, "include_reasoning": false}+ }+ ],+ "rejected": [+ {"name": "missing model", "body": {"max_tokens": 1, "messages": [{"role": "user", "content": "x"}]}, "message": "model: Field required"},+ {"name": "missing max_tokens", "body": {"model": "m", "messages": [{"role": "user", "content": "x"}]}, "message": "max_tokens: Field required"},+ {"name": "zero max_tokens", "body": {"model": "m", "max_tokens": 0, "messages": [{"role": "user", "content": "x"}]}, "message": "max_tokens: Input should be greater than or equal to 1"},+ {"name": "fractional max_tokens", "body": {"model": "m", "max_tokens": 1.5, "messages": [{"role": "user", "content": "x"}]}, "message": "max_tokens: Input should be a valid integer"},+ {"name": "missing messages", "body": {"model": "m", "max_tokens": 1}, "message": "messages: Field required"},+ {"name": "empty messages", "body": {"model": "m", "max_tokens": 1, "messages": []}, "message": "messages: List should have at least 1 item"},+ {"name": "unknown top-level field", "body": {"model": "m", "max_tokens": 1, "service_tier": "auto", "messages": [{"role": "user", "content": "x"}]}, "message": "service_tier: Extra inputs are not permitted"},+ {"name": "effort", "body": {"model": "m", "max_tokens": 1, "output_config": {"effort": "high"}, "messages": [{"role": "user", "content": "x"}]}, "message": "output_config.effort: Extra inputs are not permitted"},+ {"name": "structured output format", "body": {"model": "m", "max_tokens": 1, "output_config": {"format": {"type": "json_schema"}}, "messages": [{"role": "user", "content": "x"}]}, "message": "output_config.format: Extra inputs are not permitted"},+ {"name": "context management", "body": {"model": "m", "max_tokens": 1, "context_management": {"edits": []}, "messages": [{"role": "user", "content": "x"}]}, "message": "context_management: Extra inputs are not permitted (Claude Code: set CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1)"},+ {"name": "unsupported anthropic-version", "anthropic_version": "2024-01-01", "body": {"model": "m", "max_tokens": 1, "messages": [{"role": "user", "content": "x"}]}, "message": "anthropic-version: only 2023-06-01 is supported"},+ {"name": "mid-conversation system turn", "body": {"model": "m", "max_tokens": 1, "messages": [{"role": "user", "content": "x"}, {"role": "system", "content": "context"}]}, "message": "messages.1.role: role \"system\" is not supported in messages; use the top-level system parameter"},+ {"name": "unknown role", "body": {"model": "m", "max_tokens": 1, "messages": [{"role": "tool", "content": "x"}]}, "message": "messages.0.role: Input should be 'user' or 'assistant'"},+ {"name": "assistant prefill", "body": {"model": "m", "max_tokens": 1, "messages": [{"role": "user", "content": "x"}, {"role": "assistant", "content": "{"}]}, "message": "messages: assistant message prefill is not supported; the conversation must end with a user message"},+ {"name": "extra message field", "body": {"model": "m", "max_tokens": 1, "messages": [{"role": "user", "content": "x", "name": "n"}]}, "message": "messages.0.name: Extra inputs are not permitted"},+ {"name": "url image source", "body": {"model": "m", "max_tokens": 1, "messages": [{"role": "user", "content": [{"type": "image", "source": {"type": "url", "url": "https://example.com/a.png"}}]}]}, "message": "messages.0.content.0.image.source: only base64 image sources are supported"},+ {"name": "image media type", "body": {"model": "m", "max_tokens": 1, "messages": [{"role": "user", "content": [{"type": "image", "source": {"type": "base64", "media_type": "image/bmp", "data": "Qk0="}}]}]}, "message": "messages.0.content.0.image.source.base64.media_type: Input should be 'image/jpeg', 'image/png', 'image/gif' or 'image/webp'"},+ {"name": "document block", "body": {"model": "m", "max_tokens": 1, "messages": [{"role": "user", "content": [{"type": "document", "source": {"type": "text", "media_type": "text/plain", "data": "x"}}]}]}, "message": "messages.0.content.0.document: content blocks of type 'document' are not supported here"},+ {"name": "unknown block type", "body": {"model": "m", "max_tokens": 1, "messages": [{"role": "user", "content": [{"type": "audio"}]}]}, "message": "messages.0.content.0.type: Input tag 'audio' found using 'type' does not match any of the expected tags"},+ {"name": "tool_use input must be an object", "body": {"model": "m", "max_tokens": 1, "messages": [{"role": "user", "content": "x"}, {"role": "assistant", "content": [{"type": "tool_use", "id": "t", "name": "n", "input": "[]"}]}, {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t"}]}]}, "message": "messages.1.content.0.tool_use.input: Input should be a valid dictionary"},+ {"name": "server tool use in history", "body": {"model": "m", "max_tokens": 1, "messages": [{"role": "user", "content": "x"}, {"role": "assistant", "content": [{"type": "server_tool_use", "id": "s", "name": "web_search", "input": {}}]}, {"role": "user", "content": "y"}]}, "message": "messages.1.content.0.server_tool_use: content blocks of type 'server_tool_use' are not supported here"},+ {"name": "system citations", "body": {"model": "m", "max_tokens": 1, "system": [{"type": "text", "text": "s", "citations": [{"type": "char_location"}]}], "messages": [{"role": "user", "content": "x"}]}, "message": "system.0.citations: citations are not supported"},+ {"name": "anthropic-defined tool", "body": {"model": "m", "max_tokens": 1, "tools": [{"type": "bash_20250124", "name": "bash"}], "messages": [{"role": "user", "content": "x"}]}, "message": "tools.0.type: tool type 'bash_20250124' is not supported; only custom tools with an input_schema are"},+ {"name": "strict tool", "body": {"model": "m", "max_tokens": 1, "tools": [{"name": "t", "input_schema": {"type": "object"}, "strict": true}], "messages": [{"role": "user", "content": "x"}]}, "message": "tools.0.strict: Extra inputs are not permitted"},+ {"name": "deferred tool", "body": {"model": "m", "max_tokens": 1, "tools": [{"name": "t", "input_schema": {"type": "object"}, "defer_loading": true}], "messages": [{"role": "user", "content": "x"}]}, "message": "tools.0.defer_loading: Extra inputs are not permitted"},+ {"name": "tool name over 64 characters", "body": {"model": "m", "max_tokens": 1, "tools": [{"name": "mcp__a_very_long_server_name__and_an_equally_long_tool_name_beyond", "input_schema": {"type": "object"}}], "messages": [{"role": "user", "content": "x"}]}, "message": "tools.0.name: tool names longer than 64 characters are not supported"},+ {"name": "tool name pattern", "body": {"model": "m", "max_tokens": 1, "tools": [{"name": "math.add", "input_schema": {"type": "object"}}], "messages": [{"role": "user", "content": "x"}]}, "message": "tools.0.name: String should match pattern '^[a-zA-Z0-9_-]{1,64}$'"},+ {"name": "tool without input_schema", "body": {"model": "m", "max_tokens": 1, "tools": [{"name": "t"}], "messages": [{"role": "user", "content": "x"}]}, "message": "tools.0.input_schema: Field required"},+ {"name": "unsupported schema keyword", "body": {"model": "m", "max_tokens": 1, "tools": [{"name": "t", "input_schema": {"type": "object", "if": {"properties": {"a": {"const": 1}}}, "then": {"required": ["b"]}}}], "messages": [{"role": "user", "content": "x"}]}, "message": "tools.0.input_schema: the schema uses an unsupported JSON Schema keyword (if, then, else, $dynamicRef, unevaluatedProperties, dependentSchemas) or exceeds the size or depth limits"},+ {"name": "undeclared named tool", "body": {"model": "m", "max_tokens": 1, "tools": [{"name": "a", "input_schema": {"type": "object"}}], "tool_choice": {"type": "tool", "name": "b"}, "messages": [{"role": "user", "content": "x"}]}, "message": "tool_choice.tool.name: tool 'b' is not declared in tools"},+ {"name": "tool_choice any without tools", "body": {"model": "m", "max_tokens": 1, "tool_choice": {"type": "any"}, "messages": [{"role": "user", "content": "x"}]}, "message": "tool_choice.any: tool_choice requires tools"},+ {"name": "thinking budget below minimum", "body": {"model": "m", "max_tokens": 4096, "thinking": {"type": "enabled", "budget_tokens": 512}, "messages": [{"role": "user", "content": "x"}]}, "message": "thinking.enabled.budget_tokens: Input should be greater than or equal to 1024"},+ {"name": "thinking budget not below max_tokens", "body": {"model": "m", "max_tokens": 2048, "thinking": {"type": "enabled", "budget_tokens": 2048}, "messages": [{"role": "user", "content": "x"}]}, "message": "thinking.enabled.budget_tokens: must be less than max_tokens"},+ {"name": "unknown thinking display", "body": {"model": "m", "max_tokens": 16, "thinking": {"type": "adaptive", "display": "updates"}, "messages": [{"role": "user", "content": "x"}]}, "message": "thinking.adaptive.display: Input should be 'summarized' or 'omitted'"},+ {"name": "unknown thinking field", "body": {"model": "m", "max_tokens": 16, "thinking": {"type": "adaptive", "block_binding": {}}, "messages": [{"role": "user", "content": "x"}]}, "message": "thinking.adaptive.block_binding: Extra inputs are not permitted"},+ {"name": "thinking between tools", "body": {"model": "m", "max_tokens": 16, "thinking": {"type": "between_tools"}, "messages": [{"role": "user", "content": "x"}]}, "message": "\"thinking.type.between_tools\" is not supported for this model."},+ {"name": "temperature above 1", "body": {"model": "m", "max_tokens": 1, "temperature": 1.5, "messages": [{"role": "user", "content": "x"}]}, "message": "temperature: Input should be less than or equal to 1"},+ {"name": "zero top_p", "body": {"model": "m", "max_tokens": 1, "top_p": 0, "messages": [{"role": "user", "content": "x"}]}, "message": "top_p: Input should be greater than 0"},+ {"name": "metadata field", "body": {"model": "m", "max_tokens": 1, "metadata": {"user_id": "u", "tenant": "t"}, "messages": [{"role": "user", "content": "x"}]}, "message": "metadata.tenant: Extra inputs are not permitted"}+ ]+}diff --git a/conformance/anthropic_messages/response_vectors.json b/conformance/anthropic_messages/response_vectors.jsonnew file mode 100644index 000000000..bcd1550bb--- /dev/null+++ b/conformance/anthropic_messages/response_vectors.json@@ -0,0 +1,189 @@+{+ "translated": [+ {+ "name": "text",+ "model": "m",+ "request_id": "r1",+ "chat": {+ "id": "chatcmpl-r1",+ "object": "chat.completion",+ "model": "m",+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "Hello."}, "finish_reason": "stop", "logprobs": null}],+ "usage": {"prompt_tokens": 10, "completion_tokens": 3, "total_tokens": 13}+ },+ "message": {+ "id": "msg_r1",+ "type": "message",+ "role": "assistant",+ "model": "m",+ "content": [{"type": "text", "text": "Hello."}],+ "stop_reason": "end_turn",+ "stop_sequence": null,+ "usage": {"input_tokens": 10, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "output_tokens": 3}+ }+ },+ {+ "name": "cached prompt tokens are reported as cache reads",+ "model": "org/model:profile",+ "request_id": "r2",+ "chat": {+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],+ "usage": {"prompt_tokens": 100, "completion_tokens": 2, "total_tokens": 102, "prompt_tokens_details": {"cached_tokens": 60}}+ },+ "message": {+ "id": "msg_r2",+ "type": "message",+ "role": "assistant",+ "model": "org/model:profile",+ "content": [{"type": "text", "text": "ok"}],+ "stop_reason": "end_turn",+ "stop_sequence": null,+ "usage": {"input_tokens": 40, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 60, "output_tokens": 2}+ }+ },+ {+ "name": "tool calls",+ "model": "m",+ "request_id": "r3",+ "chat": {+ "choices": [+ {+ "index": 0,+ "message": {+ "role": "assistant",+ "content": null,+ "tool_calls": [+ {"id": "call_1", "type": "function", "function": {"name": "get_weather", "arguments": "{\"city\": \"Paris\"}"}},+ {"id": "call_2", "type": "function", "function": {"name": "noop", "arguments": ""}}+ ]+ },+ "finish_reason": "tool_calls"+ }+ ],+ "usage": {"prompt_tokens": 20, "completion_tokens": 12, "total_tokens": 32}+ },+ "message": {+ "id": "msg_r3",+ "type": "message",+ "role": "assistant",+ "model": "m",+ "content": [+ {"type": "tool_use", "id": "call_1", "name": "get_weather", "input": {"city": "Paris"}},+ {"type": "tool_use", "id": "call_2", "name": "noop", "input": {}}+ ],+ "stop_reason": "tool_use",+ "stop_sequence": null,+ "usage": {"input_tokens": 20, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "output_tokens": 12}+ }+ },+ {+ "name": "reasoning becomes a thinking block before the text",+ "model": "m",+ "request_id": "r4",+ "chat": {+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "9.9", "reasoning_content": "Compare the tenths."}, "finish_reason": "stop"}],+ "usage": {"prompt_tokens": 8, "completion_tokens": 30, "total_tokens": 38}+ },+ "message": {+ "id": "msg_r4",+ "type": "message",+ "role": "assistant",+ "model": "m",+ "content": [+ {"type": "thinking", "thinking": "Compare the tenths.", "signature": "sie-unsigned"},+ {"type": "text", "text": "9.9"}+ ],+ "stop_reason": "end_turn",+ "stop_sequence": null,+ "usage": {"input_tokens": 8, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "output_tokens": 30}+ }+ },+ {+ "name": "whitespace-only text is dropped, a stop with tool calls is a tool_use stop",+ "model": "m",+ "request_id": "r5",+ "chat": {+ "choices": [+ {+ "index": 0,+ "message": {"role": "assistant", "content": "\n\n", "tool_calls": [{"id": "c", "type": "function", "function": {"name": "run", "arguments": "{}"}}]},+ "finish_reason": "stop"+ }+ ],+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}+ },+ "message": {+ "id": "msg_r5",+ "type": "message",+ "role": "assistant",+ "model": "m",+ "content": [{"type": "tool_use", "id": "c", "name": "run", "input": {}}],+ "stop_reason": "tool_use",+ "stop_sequence": null,+ "usage": {"input_tokens": 1, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "output_tokens": 1}+ }+ },+ {+ "name": "length",+ "model": "m",+ "request_id": "r6",+ "chat": {+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "partial"}, "finish_reason": "length"}],+ "usage": {"prompt_tokens": 5, "completion_tokens": 16, "total_tokens": 21}+ },+ "message": {+ "id": "msg_r6",+ "type": "message",+ "role": "assistant",+ "model": "m",+ "content": [{"type": "text", "text": "partial"}],+ "stop_reason": "max_tokens",+ "stop_sequence": null,+ "usage": {"input_tokens": 5, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "output_tokens": 16}+ }+ },+ {+ "name": "content filter is a refusal, empty content is an empty list",+ "model": "m",+ "request_id": "r7",+ "chat": {+ "choices": [{"index": 0, "message": {"role": "assistant", "content": ""}, "finish_reason": "content_filter"}],+ "usage": {"prompt_tokens": 5, "completion_tokens": 0, "total_tokens": 5}+ },+ "message": {+ "id": "msg_r7",+ "type": "message",+ "role": "assistant",+ "model": "m",+ "content": [],+ "stop_reason": "refusal",+ "stop_sequence": null,+ "usage": {"input_tokens": 5, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "output_tokens": 0}+ }+ }+ ],+ "faults": [+ {+ "name": "tool arguments are not an object",+ "chat": {+ "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "tool_calls": [{"id": "c", "type": "function", "function": {"name": "run", "arguments": "[1]"}}]}, "finish_reason": "tool_calls"}],+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}+ }+ },+ {+ "name": "tool arguments are not JSON",+ "chat": {+ "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "tool_calls": [{"id": "c", "type": "function", "function": {"name": "run", "arguments": "{\"a\":"}}]}, "finish_reason": "tool_calls"}],+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}+ }+ },+ {+ "name": "no usage",+ "chat": {"choices": [{"index": 0, "message": {"role": "assistant", "content": "x"}, "finish_reason": "stop"}]}+ },+ {+ "name": "no choices",+ "chat": {"choices": [], "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}}+ }+ ]+}diff --git a/conformance/anthropic_messages/stream_vectors.json b/conformance/anthropic_messages/stream_vectors.jsonnew file mode 100644index 000000000..ebb26d732--- /dev/null+++ b/conformance/anthropic_messages/stream_vectors.json@@ -0,0 +1,1758 @@+{+ "description": "Chat completion SSE data payloads in, Anthropic Messages events out. The stream ends after the last frame. Pings are timer-driven and not part of these vectors.",+ "streams": [+ {+ "name": "text",+ "message_id": "msg_r",+ "model": "m",+ "frames": [+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "role": "assistant"+ },+ "finish_reason": null+ }+ ]+ },+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "content": "Hel"+ },+ "finish_reason": null+ }+ ]+ },+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "content": "lo"+ },+ "finish_reason": null+ }+ ]+ },+ {+ "choices": [+ {+ "index": 0,+ "delta": {},+ "finish_reason": "stop"+ }+ ]+ },+ {+ "choices": [],+ "usage": {+ "prompt_tokens": 10,+ "completion_tokens": 2,+ "total_tokens": 12+ }+ },+ "[DONE]"+ ],+ "events": [+ {+ "event": "message_start",+ "data": {+ "type": "message_start",+ "message": {+ "id": "msg_r",+ "type": "message",+ "role": "assistant",+ "model": "m",+ "content": [],+ "stop_reason": null,+ "stop_sequence": null,+ "usage": {+ "input_tokens": 0,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 0+ }+ }+ }+ },+ {+ "event": "content_block_start",+ "data": {+ "type": "content_block_start",+ "index": 0,+ "content_block": {+ "type": "text",+ "text": ""+ }+ }+ },+ {+ "event": "content_block_delta",+ "data": {+ "type": "content_block_delta",+ "index": 0,+ "delta": {+ "type": "text_delta",+ "text": "Hel"+ }+ }+ },+ {+ "event": "content_block_delta",+ "data": {+ "type": "content_block_delta",+ "index": 0,+ "delta": {+ "type": "text_delta",+ "text": "lo"+ }+ }+ },+ {+ "event": "content_block_stop",+ "data": {+ "type": "content_block_stop",+ "index": 0+ }+ },+ {+ "event": "message_delta",+ "data": {+ "type": "message_delta",+ "delta": {+ "stop_reason": "end_turn",+ "stop_sequence": null+ },+ "usage": {+ "input_tokens": 10,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 2+ }+ }+ },+ {+ "event": "message_stop",+ "data": {+ "type": "message_stop"+ }+ }+ ]+ },+ {+ "name": "cached prompt tokens",+ "message_id": "msg_r",+ "model": "m",+ "frames": [+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "content": "ok"+ },+ "finish_reason": "stop"+ }+ ]+ },+ {+ "choices": [],+ "usage": {+ "prompt_tokens": 100,+ "completion_tokens": 1,+ "total_tokens": 101,+ "prompt_tokens_details": {+ "cached_tokens": 60+ }+ }+ },+ "[DONE]"+ ],+ "events": [+ {+ "event": "message_start",+ "data": {+ "type": "message_start",+ "message": {+ "id": "msg_r",+ "type": "message",+ "role": "assistant",+ "model": "m",+ "content": [],+ "stop_reason": null,+ "stop_sequence": null,+ "usage": {+ "input_tokens": 0,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 0+ }+ }+ }+ },+ {+ "event": "content_block_start",+ "data": {+ "type": "content_block_start",+ "index": 0,+ "content_block": {+ "type": "text",+ "text": ""+ }+ }+ },+ {+ "event": "content_block_delta",+ "data": {+ "type": "content_block_delta",+ "index": 0,+ "delta": {+ "type": "text_delta",+ "text": "ok"+ }+ }+ },+ {+ "event": "content_block_stop",+ "data": {+ "type": "content_block_stop",+ "index": 0+ }+ },+ {+ "event": "message_delta",+ "data": {+ "type": "message_delta",+ "delta": {+ "stop_reason": "end_turn",+ "stop_sequence": null+ },+ "usage": {+ "input_tokens": 40,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 60,+ "output_tokens": 1+ }+ }+ },+ {+ "event": "message_stop",+ "data": {+ "type": "message_stop"+ }+ }+ ]+ },+ {+ "name": "leading whitespace before a tool call is dropped",+ "message_id": "msg_r",+ "model": "m",+ "frames": [+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "role": "assistant",+ "content": "\n\n"+ },+ "finish_reason": null+ }+ ]+ },+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "tool_calls": [+ {+ "index": 0,+ "id": "call_1",+ "type": "function",+ "function": {+ "name": "Read",+ "arguments": ""+ }+ }+ ]+ },+ "finish_reason": null+ }+ ]+ },+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "tool_calls": [+ {+ "index": 0,+ "function": {+ "arguments": "{\"file_path\": \"/a\"}"+ }+ }+ ]+ },+ "finish_reason": null+ }+ ]+ },+ {+ "choices": [+ {+ "index": 0,+ "delta": {},+ "finish_reason": "tool_calls"+ }+ ]+ },+ {+ "choices": [],+ "usage": {+ "prompt_tokens": 50,+ "completion_tokens": 9,+ "total_tokens": 59+ }+ },+ "[DONE]"+ ],+ "events": [+ {+ "event": "message_start",+ "data": {+ "type": "message_start",+ "message": {+ "id": "msg_r",+ "type": "message",+ "role": "assistant",+ "model": "m",+ "content": [],+ "stop_reason": null,+ "stop_sequence": null,+ "usage": {+ "input_tokens": 0,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 0+ }+ }+ }+ },+ {+ "event": "content_block_start",+ "data": {+ "type": "content_block_start",+ "index": 0,+ "content_block": {+ "type": "tool_use",+ "id": "call_1",+ "name": "Read",+ "input": {}+ }+ }+ },+ {+ "event": "content_block_delta",+ "data": {+ "type": "content_block_delta",+ "index": 0,+ "delta": {+ "type": "input_json_delta",+ "partial_json": "{\"file_path\": \"/a\"}"+ }+ }+ },+ {+ "event": "content_block_stop",+ "data": {+ "type": "content_block_stop",+ "index": 0+ }+ },+ {+ "event": "message_delta",+ "data": {+ "type": "message_delta",+ "delta": {+ "stop_reason": "tool_use",+ "stop_sequence": null+ },+ "usage": {+ "input_tokens": 50,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 9+ }+ }+ },+ {+ "event": "message_stop",+ "data": {+ "type": "message_stop"+ }+ }+ ]+ },+ {+ "name": "leading whitespace before text is kept",+ "message_id": "msg_r",+ "model": "m",+ "frames": [+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "content": " "+ },+ "finish_reason": null+ }+ ]+ },+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "content": "\n"+ },+ "finish_reason": null+ }+ ]+ },+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "content": "Hi"+ },+ "finish_reason": null+ }+ ]+ },+ {+ "choices": [+ {+ "index": 0,+ "delta": {},+ "finish_reason": "stop"+ }+ ]+ },+ {+ "choices": [],+ "usage": {+ "prompt_tokens": 1,+ "completion_tokens": 3,+ "total_tokens": 4+ }+ },+ "[DONE]"+ ],+ "events": [+ {+ "event": "message_start",+ "data": {+ "type": "message_start",+ "message": {+ "id": "msg_r",+ "type": "message",+ "role": "assistant",+ "model": "m",+ "content": [],+ "stop_reason": null,+ "stop_sequence": null,+ "usage": {+ "input_tokens": 0,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 0+ }+ }+ }+ },+ {+ "event": "content_block_start",+ "data": {+ "type": "content_block_start",+ "index": 0,+ "content_block": {+ "type": "text",+ "text": ""+ }+ }+ },+ {+ "event": "content_block_delta",+ "data": {+ "type": "content_block_delta",+ "index": 0,+ "delta": {+ "type": "text_delta",+ "text": " \nHi"+ }+ }+ },+ {+ "event": "content_block_stop",+ "data": {+ "type": "content_block_stop",+ "index": 0+ }+ },+ {+ "event": "message_delta",+ "data": {+ "type": "message_delta",+ "delta": {+ "stop_reason": "end_turn",+ "stop_sequence": null+ },+ "usage": {+ "input_tokens": 1,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 3+ }+ }+ },+ {+ "event": "message_stop",+ "data": {+ "type": "message_stop"+ }+ }+ ]+ },+ {+ "name": "reasoning then text",+ "message_id": "msg_r",+ "model": "m",+ "frames": [+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "reasoning_content": "Compare"+ },+ "finish_reason": null+ }+ ]+ },+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "reasoning_content": " tenths."+ },+ "finish_reason": null+ }+ ]+ },+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "content": "9.9"+ },+ "finish_reason": null+ }+ ]+ },+ {+ "choices": [+ {+ "index": 0,+ "delta": {},+ "finish_reason": "stop"+ }+ ]+ },+ {+ "choices": [],+ "usage": {+ "prompt_tokens": 8,+ "completion_tokens": 30,+ "total_tokens": 38+ }+ },+ "[DONE]"+ ],+ "events": [+ {+ "event": "message_start",+ "data": {+ "type": "message_start",+ "message": {+ "id": "msg_r",+ "type": "message",+ "role": "assistant",+ "model": "m",+ "content": [],+ "stop_reason": null,+ "stop_sequence": null,+ "usage": {+ "input_tokens": 0,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 0+ }+ }+ }+ },+ {+ "event": "content_block_start",+ "data": {+ "type": "content_block_start",+ "index": 0,+ "content_block": {+ "type": "thinking",+ "thinking": "",+ "signature": ""+ }+ }+ },+ {+ "event": "content_block_delta",+ "data": {+ "type": "content_block_delta",+ "index": 0,+ "delta": {+ "type": "thinking_delta",+ "thinking": "Compare"+ }+ }+ },+ {+ "event": "content_block_delta",+ "data": {+ "type": "content_block_delta",+ "index": 0,+ "delta": {+ "type": "thinking_delta",+ "thinking": " tenths."+ }+ }+ },+ {+ "event": "content_block_delta",+ "data": {+ "type": "content_block_delta",+ "index": 0,+ "delta": {+ "type": "signature_delta",+ "signature": "sie-unsigned"+ }+ }+ },+ {+ "event": "content_block_stop",+ "data": {+ "type": "content_block_stop",+ "index": 0+ }+ },+ {+ "event": "content_block_start",+ "data": {+ "type": "content_block_start",+ "index": 1,+ "content_block": {+ "type": "text",+ "text": ""+ }+ }+ },+ {+ "event": "content_block_delta",+ "data": {+ "type": "content_block_delta",+ "index": 1,+ "delta": {+ "type": "text_delta",+ "text": "9.9"+ }+ }+ },+ {+ "event": "content_block_stop",+ "data": {+ "type": "content_block_stop",+ "index": 1+ }+ },+ {+ "event": "message_delta",+ "data": {+ "type": "message_delta",+ "delta": {+ "stop_reason": "end_turn",+ "stop_sequence": null+ },+ "usage": {+ "input_tokens": 8,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 30+ }+ }+ },+ {+ "event": "message_stop",+ "data": {+ "type": "message_stop"+ }+ }+ ]+ },+ {+ "name": "text then parallel tool calls",+ "message_id": "msg_r",+ "model": "m",+ "frames": [+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "content": "Running both."+ },+ "finish_reason": null+ }+ ]+ },+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "tool_calls": [+ {+ "index": 0,+ "id": "t1",+ "type": "function",+ "function": {+ "name": "Bash",+ "arguments": "{\"command\":\"echo one\"}"+ }+ }+ ]+ },+ "finish_reason": null+ }+ ]+ },+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "tool_calls": [+ {+ "index": 1,+ "id": "t2",+ "type": "function",+ "function": {+ "name": "Bash",+ "arguments": "{\"command\""+ }+ }+ ]+ },+ "finish_reason": null+ }+ ]+ },+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "tool_calls": [+ {+ "index": 1,+ "function": {+ "arguments": ":\"echo two\"}"+ }+ }+ ]+ },+ "finish_reason": null+ }+ ]+ },+ {+ "choices": [+ {+ "index": 0,+ "delta": {},+ "finish_reason": "tool_calls"+ }+ ]+ },+ {+ "choices": [],+ "usage": {+ "prompt_tokens": 30,+ "completion_tokens": 20,+ "total_tokens": 50+ }+ },+ "[DONE]"+ ],+ "events": [+ {+ "event": "message_start",+ "data": {+ "type": "message_start",+ "message": {+ "id": "msg_r",+ "type": "message",+ "role": "assistant",+ "model": "m",+ "content": [],+ "stop_reason": null,+ "stop_sequence": null,+ "usage": {+ "input_tokens": 0,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 0+ }+ }+ }+ },+ {+ "event": "content_block_start",+ "data": {+ "type": "content_block_start",+ "index": 0,+ "content_block": {+ "type": "text",+ "text": ""+ }+ }+ },+ {+ "event": "content_block_delta",+ "data": {+ "type": "content_block_delta",+ "index": 0,+ "delta": {+ "type": "text_delta",+ "text": "Running both."+ }+ }+ },+ {+ "event": "content_block_stop",+ "data": {+ "type": "content_block_stop",+ "index": 0+ }+ },+ {+ "event": "content_block_start",+ "data": {+ "type": "content_block_start",+ "index": 1,+ "content_block": {+ "type": "tool_use",+ "id": "t1",+ "name": "Bash",+ "input": {}+ }+ }+ },+ {+ "event": "content_block_delta",+ "data": {+ "type": "content_block_delta",+ "index": 1,+ "delta": {+ "type": "input_json_delta",+ "partial_json": "{\"command\":\"echo one\"}"+ }+ }+ },+ {+ "event": "content_block_stop",+ "data": {+ "type": "content_block_stop",+ "index": 1+ }+ },+ {+ "event": "content_block_start",+ "data": {+ "type": "content_block_start",+ "index": 2,+ "content_block": {+ "type": "tool_use",+ "id": "t2",+ "name": "Bash",+ "input": {}+ }+ }+ },+ {+ "event": "content_block_delta",+ "data": {+ "type": "content_block_delta",+ "index": 2,+ "delta": {+ "type": "input_json_delta",+ "partial_json": "{\"command\""+ }+ }+ },+ {+ "event": "content_block_delta",+ "data": {+ "type": "content_block_delta",+ "index": 2,+ "delta": {+ "type": "input_json_delta",+ "partial_json": ":\"echo two\"}"+ }+ }+ },+ {+ "event": "content_block_stop",+ "data": {+ "type": "content_block_stop",+ "index": 2+ }+ },+ {+ "event": "message_delta",+ "data": {+ "type": "message_delta",+ "delta": {+ "stop_reason": "tool_use",+ "stop_sequence": null+ },+ "usage": {+ "input_tokens": 30,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 20+ }+ }+ },+ {+ "event": "message_stop",+ "data": {+ "type": "message_stop"+ }+ }+ ]+ },+ {+ "name": "length",+ "message_id": "msg_r",+ "model": "m",+ "frames": [+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "content": "partial"+ },+ "finish_reason": null+ }+ ]+ },+ {+ "choices": [+ {+ "index": 0,+ "delta": {},+ "finish_reason": "length"+ }+ ]+ },+ {+ "choices": [],+ "usage": {+ "prompt_tokens": 5,+ "completion_tokens": 16,+ "total_tokens": 21+ }+ },+ "[DONE]"+ ],+ "events": [+ {+ "event": "message_start",+ "data": {+ "type": "message_start",+ "message": {+ "id": "msg_r",+ "type": "message",+ "role": "assistant",+ "model": "m",+ "content": [],+ "stop_reason": null,+ "stop_sequence": null,+ "usage": {+ "input_tokens": 0,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 0+ }+ }+ }+ },+ {+ "event": "content_block_start",+ "data": {+ "type": "content_block_start",+ "index": 0,+ "content_block": {+ "type": "text",+ "text": ""+ }+ }+ },+ {+ "event": "content_block_delta",+ "data": {+ "type": "content_block_delta",+ "index": 0,+ "delta": {+ "type": "text_delta",+ "text": "partial"+ }+ }+ },+ {+ "event": "content_block_stop",+ "data": {+ "type": "content_block_stop",+ "index": 0+ }+ },+ {+ "event": "message_delta",+ "data": {+ "type": "message_delta",+ "delta": {+ "stop_reason": "max_tokens",+ "stop_sequence": null+ },+ "usage": {+ "input_tokens": 5,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 16+ }+ }+ },+ {+ "event": "message_stop",+ "data": {+ "type": "message_stop"+ }+ }+ ]+ },+ {+ "name": "whitespace-only answer has no content block",+ "message_id": "msg_r",+ "model": "m",+ "frames": [+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "content": "\n"+ },+ "finish_reason": null+ }+ ]+ },+ {+ "choices": [+ {+ "index": 0,+ "delta": {},+ "finish_reason": "stop"+ }+ ]+ },+ {+ "choices": [],+ "usage": {+ "prompt_tokens": 5,+ "completion_tokens": 1,+ "total_tokens": 6+ }+ },+ "[DONE]"+ ],+ "events": [+ {+ "event": "message_start",+ "data": {+ "type": "message_start",+ "message": {+ "id": "msg_r",+ "type": "message",+ "role": "assistant",+ "model": "m",+ "content": [],+ "stop_reason": null,+ "stop_sequence": null,+ "usage": {+ "input_tokens": 0,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 0+ }+ }+ }+ },+ {+ "event": "message_delta",+ "data": {+ "type": "message_delta",+ "delta": {+ "stop_reason": "end_turn",+ "stop_sequence": null+ },+ "usage": {+ "input_tokens": 5,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 1+ }+ }+ },+ {+ "event": "message_stop",+ "data": {+ "type": "message_stop"+ }+ }+ ]+ },+ {+ "name": "finish without usage completes with zero usage at the end",+ "message_id": "msg_r",+ "model": "m",+ "frames": [+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "content": "ok"+ },+ "finish_reason": null+ }+ ]+ },+ {+ "choices": [+ {+ "index": 0,+ "delta": {},+ "finish_reason": "stop"+ }+ ]+ },+ "[DONE]"+ ],+ "events": [+ {+ "event": "message_start",+ "data": {+ "type": "message_start",+ "message": {+ "id": "msg_r",+ "type": "message",+ "role": "assistant",+ "model": "m",+ "content": [],+ "stop_reason": null,+ "stop_sequence": null,+ "usage": {+ "input_tokens": 0,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 0+ }+ }+ }+ },+ {+ "event": "content_block_start",+ "data": {+ "type": "content_block_start",+ "index": 0,+ "content_block": {+ "type": "text",+ "text": ""+ }+ }+ },+ {+ "event": "content_block_delta",+ "data": {+ "type": "content_block_delta",+ "index": 0,+ "delta": {+ "type": "text_delta",+ "text": "ok"+ }+ }+ },+ {+ "event": "content_block_stop",+ "data": {+ "type": "content_block_stop",+ "index": 0+ }+ },+ {+ "event": "message_delta",+ "data": {+ "type": "message_delta",+ "delta": {+ "stop_reason": "end_turn",+ "stop_sequence": null+ },+ "usage": {+ "input_tokens": 0,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 0+ }+ }+ },+ {+ "event": "message_stop",+ "data": {+ "type": "message_stop"+ }+ }+ ]+ },+ {+ "name": "error after output",+ "message_id": "msg_r",+ "model": "m",+ "frames": [+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "content": "par"+ },+ "finish_reason": null+ }+ ]+ },+ {+ "choices": [+ {+ "index": 0,+ "delta": {},+ "finish_reason": null+ }+ ],+ "error": {+ "message": "Generation aborted: inter_chunk timeout",+ "type": "server_error",+ "param": null,+ "code": "inter_chunk_timeout"+ },+ "request_id": "r"+ },+ "[DONE]"+ ],+ "events": [+ {+ "event": "message_start",+ "data": {+ "type": "message_start",+ "message": {+ "id": "msg_r",+ "type": "message",+ "role": "assistant",+ "model": "m",+ "content": [],+ "stop_reason": null,+ "stop_sequence": null,+ "usage": {+ "input_tokens": 0,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 0+ }+ }+ }+ },+ {+ "event": "content_block_start",+ "data": {+ "type": "content_block_start",+ "index": 0,+ "content_block": {+ "type": "text",+ "text": ""+ }+ }+ },+ {+ "event": "content_block_delta",+ "data": {+ "type": "content_block_delta",+ "index": 0,+ "delta": {+ "type": "text_delta",+ "text": "par"+ }+ }+ },+ {+ "event": "error",+ "data": {+ "type": "error",+ "error": {+ "type": "timeout_error",+ "message": "Generation aborted: inter_chunk timeout"+ }+ }+ }+ ]+ },+ {+ "name": "capacity error before output",+ "message_id": "msg_r",+ "model": "m",+ "frames": [+ {+ "choices": [+ {+ "index": 0,+ "delta": {},+ "finish_reason": null+ }+ ],+ "error": {+ "message": "The upstream serving the model is busy, please retry",+ "type": "server_error",+ "param": null,+ "code": "RESOURCE_EXHAUSTED",+ "retry_after_s": 5+ }+ },+ "[DONE]"+ ],+ "events": [+ {+ "event": "message_start",+ "data": {+ "type": "message_start",+ "message": {+ "id": "msg_r",+ "type": "message",+ "role": "assistant",+ "model": "m",+ "content": [],+ "stop_reason": null,+ "stop_sequence": null,+ "usage": {+ "input_tokens": 0,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 0+ }+ }+ }+ },+ {+ "event": "error",+ "data": {+ "type": "error",+ "error": {+ "type": "overloaded_error",+ "message": "The upstream serving the model is busy, please retry"+ }+ }+ }+ ]+ },+ {+ "name": "prompt too long mid-stream",+ "message_id": "msg_r",+ "model": "m",+ "frames": [+ {+ "choices": [+ {+ "index": 0,+ "delta": {},+ "finish_reason": null+ }+ ],+ "error": {+ "message": "prompt_tokens (140000) + max_new_tokens (4096) = 144096 exceeds context_length (131072) for model 'm'",+ "type": "context_length_exceeded",+ "param": null,+ "code": "context_exceeded"+ }+ },+ "[DONE]"+ ],+ "events": [+ {+ "event": "message_start",+ "data": {+ "type": "message_start",+ "message": {+ "id": "msg_r",+ "type": "message",+ "role": "assistant",+ "model": "m",+ "content": [],+ "stop_reason": null,+ "stop_sequence": null,+ "usage": {+ "input_tokens": 0,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 0+ }+ }+ }+ },+ {+ "event": "error",+ "data": {+ "type": "error",+ "error": {+ "type": "invalid_request_error",+ "message": "prompt is too long: 144096 tokens > 131072 maximum"+ }+ }+ }+ ]+ },+ {+ "name": "end without a finish reason",+ "message_id": "msg_r",+ "model": "m",+ "frames": [+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "content": "x"+ },+ "finish_reason": null+ }+ ]+ },+ "[DONE]"+ ],+ "events": [+ {+ "event": "message_start",+ "data": {+ "type": "message_start",+ "message": {+ "id": "msg_r",+ "type": "message",+ "role": "assistant",+ "model": "m",+ "content": [],+ "stop_reason": null,+ "stop_sequence": null,+ "usage": {+ "input_tokens": 0,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 0+ }+ }+ }+ },+ {+ "event": "content_block_start",+ "data": {+ "type": "content_block_start",+ "index": 0,+ "content_block": {+ "type": "text",+ "text": ""+ }+ }+ },+ {+ "event": "content_block_delta",+ "data": {+ "type": "content_block_delta",+ "index": 0,+ "delta": {+ "type": "text_delta",+ "text": "x"+ }+ }+ },+ {+ "event": "error",+ "data": {+ "type": "error",+ "error": {+ "type": "api_error",+ "message": "the generation stream ended without a finish reason"+ }+ }+ }+ ]+ },+ {+ "name": "stream closed without DONE after a finish",+ "message_id": "msg_r",+ "model": "m",+ "frames": [+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "content": "x"+ },+ "finish_reason": "stop"+ }+ ]+ }+ ],+ "events": [+ {+ "event": "message_start",+ "data": {+ "type": "message_start",+ "message": {+ "id": "msg_r",+ "type": "message",+ "role": "assistant",+ "model": "m",+ "content": [],+ "stop_reason": null,+ "stop_sequence": null,+ "usage": {+ "input_tokens": 0,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 0+ }+ }+ }+ },+ {+ "event": "content_block_start",+ "data": {+ "type": "content_block_start",+ "index": 0,+ "content_block": {+ "type": "text",+ "text": ""+ }+ }+ },+ {+ "event": "content_block_delta",+ "data": {+ "type": "content_block_delta",+ "index": 0,+ "delta": {+ "type": "text_delta",+ "text": "x"+ }+ }+ },+ {+ "event": "content_block_stop",+ "data": {+ "type": "content_block_stop",+ "index": 0+ }+ },+ {+ "event": "message_delta",+ "data": {+ "type": "message_delta",+ "delta": {+ "stop_reason": "end_turn",+ "stop_sequence": null+ },+ "usage": {+ "input_tokens": 0,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 0+ }+ }+ },+ {+ "event": "message_stop",+ "data": {+ "type": "message_stop"+ }+ }+ ]+ },+ {+ "name": "tool arguments for a closed call",+ "message_id": "msg_r",+ "model": "m",+ "frames": [+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "tool_calls": [+ {+ "index": 0,+ "id": "a",+ "type": "function",+ "function": {+ "name": "x",+ "arguments": ""+ }+ }+ ]+ },+ "finish_reason": null+ }+ ]+ },+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "tool_calls": [+ {+ "index": 1,+ "id": "b",+ "type": "function",+ "function": {+ "name": "y",+ "arguments": ""+ }+ }+ ]+ },+ "finish_reason": null+ }+ ]+ },+ {+ "choices": [+ {+ "index": 0,+ "delta": {+ "tool_calls": [+ {+ "index": 0,+ "function": {+ "arguments": "{}"+ }+ }+ ]+ },+ "finish_reason": null+ }+ ]+ }+ ],+ "events": [+ {+ "event": "message_start",+ "data": {+ "type": "message_start",+ "message": {+ "id": "msg_r",+ "type": "message",+ "role": "assistant",+ "model": "m",+ "content": [],+ "stop_reason": null,+ "stop_sequence": null,+ "usage": {+ "input_tokens": 0,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 0+ }+ }+ }+ },+ {+ "event": "content_block_start",+ "data": {+ "type": "content_block_start",+ "index": 0,+ "content_block": {+ "type": "tool_use",+ "id": "a",+ "name": "x",+ "input": {}+ }+ }+ },+ {+ "event": "content_block_stop",+ "data": {+ "type": "content_block_stop",+ "index": 0+ }+ },+ {+ "event": "content_block_start",+ "data": {+ "type": "content_block_start",+ "index": 1,+ "content_block": {+ "type": "tool_use",+ "id": "b",+ "name": "y",+ "input": {}+ }+ }+ },+ {+ "event": "error",+ "data": {+ "type": "error",+ "error": {+ "type": "api_error",+ "message": "tool call arguments arrived after another content block started"+ }+ }+ }+ ]+ }+ ]+}diff --git a/examples/coding-agent-claude-code/.gitignore b/examples/coding-agent-claude-code/.gitignorenew file mode 100644index 000000000..92bd2e73f--- /dev/null+++ b/examples/coding-agent-claude-code/.gitignore@@ -0,0 +1,5 @@+.venv/+run-output/+__pycache__/+.ruff_cache/+.pytest_cache/diff --git a/examples/coding-agent-claude-code/README.md b/examples/coding-agent-claude-code/README.mdnew file mode 100644index 000000000..0f1a328b5--- /dev/null+++ b/examples/coding-agent-claude-code/README.md@@ -0,0 +1,246 @@+# Run Claude Code on SIE through the Anthropic Messages API++## What this shows++Claude Code talks to models through the Anthropic Messages API. The SIE+gateway serves `POST /v1/messages`: it translates the request into a+`/v1/chat/completions` request, serves it on the chat route with all of that+route's limits, and translates the answer back, streamed or buffered. So Claude+Code reaches a model served by SIE by changing its base URL.++Anthropic does not support Claude Code with models other than Claude behind a+gateway. Nothing here is supported or endorsed by Anthropic. This example+records how Claude Code behaves against SIE's endpoint and checks that the+agent loop closes.++The pieces:++1. `recipes/cloud.sh` and `recipes/cluster.sh`, the environment Claude Code+ needs for SIE Cloud and for a self-hosted cluster's gateway.+2. The conformance check of the OpenCode example, run with `--api messages`.+ It drives `/v1/messages` the way Claude Code does and reports each case as+ pass, fail or recorded.+3. `run_gate.sh`, a seeded gate on the OpenCode example's fixture: a tiny+ package with two failing tests and the task "make the tests pass". Claude+ Code works a copy headless, then pytest judges the result.++`sie-server`, the single-node server, does not serve `/v1/messages`. This+example needs an SIE gateway: a cluster's or SIE Cloud's.++## Run it++```sh+export SIE_BASE_URL=https://... # the gateway, without /v1+export SIE_API_KEY=...+source recipes/cloud.sh # or recipes/cluster.sh, see below+claude+```++The cluster recipe also reads the model and its window, which must match what+the gateway's `GET /v1/models` declares for the model:++```sh+export SIE_MODEL=zai-org/GLM-5.3-Flash:relay+export SIE_CONTEXT_TOKENS=131072+export SIE_OUTPUT_TOKENS=32768+source recipes/cluster.sh+```++Claude Code's system prompt and tool schemas take tens of thousands of tokens,+so a profile with a window under about 64K tokens runs out early in a session.++The conformance check, from this directory:++```sh+uv run --project ../coding-agent-opencode python ../coding-agent-opencode/conformance.py \+ --api messages --base-url "$SIE_BASE_URL/v1" --model zai-org/GLM-5.3-Flash:relay+```++The seeded gate, which needs `claude` and `uv` on `PATH`:++```sh+./run_gate.sh # SIE Cloud+./run_gate.sh cluster # your gateway, with SIE_MODEL, SIE_CONTEXT_TOKENS and SIE_OUTPUT_TOKENS set+```++Neither recipe has been run against a live endpoint yet. The checks below were+run against the gateway's own tests and against a recording stub.++## The recipe++`recipes/cloud.sh` in full:++```sh+export ANTHROPIC_BASE_URL="$SIE_BASE_URL"+export ANTHROPIC_AUTH_TOKEN="$SIE_API_KEY"+export ANTHROPIC_MODEL="zai-org/GLM-5.3-Flash:relay"+export ANTHROPIC_DEFAULT_OPUS_MODEL="$ANTHROPIC_MODEL"+export ANTHROPIC_DEFAULT_SONNET_MODEL="$ANTHROPIC_MODEL"+export ANTHROPIC_DEFAULT_HAIKU_MODEL="$ANTHROPIC_MODEL"+export CLAUDE_CODE_SUBAGENT_MODEL="$ANTHROPIC_MODEL"+export CLAUDE_CODE_MAX_CONTEXT_TOKENS=131072+export CLAUDE_CODE_MAX_OUTPUT_TOKENS=32768+export CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1+export CLAUDE_CODE_ATTRIBUTION_HEADER=0+export CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1+export API_TIMEOUT_MS=1800000+```++- `ANTHROPIC_BASE_URL` is the gateway without `/v1`. Claude Code appends+ `/v1/messages`.+- `ANTHROPIC_AUTH_TOKEN` arrives as `Authorization: Bearer ...`, which is+ where SIE reads the key. Claude Code sends `ANTHROPIC_API_KEY` as+ `x-api-key` instead, which SIE does not read.+- The model id is sent byte for byte, slash and colon included. The four+ model variables keep every request, background tasks and subagents+ included, on the SIE model. A request that names a model the gateway does+ not serve, such as a Claude model id, is answered with+ `404 not_found_error`.+- Claude Code assumes a 200K window for a model it does not know.+ `CLAUDE_CODE_MAX_CONTEXT_TOKENS` sets the profile's window, so Claude Code+ compacts the conversation before the server refuses it. The output cap must+ be at most the profile's `max_output_tokens`. A larger `max_tokens` is+ refused with `max_tokens: N > M, which is the maximum allowed number of+ output tokens for this model`.+- `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1` stops `context_management` and+ the experimental tool fields. SIE refuses `context_management` with a 400+ that names this variable, and Claude Code does not retry that refusal.+- `CLAUDE_CODE_ATTRIBUTION_HEADER=0` removes a block Claude Code otherwise adds+ to the system prompt. SIE passes system text through unchanged.+- `API_TIMEOUT_MS` is 30 minutes, so a long silent stretch, such as a model+ writing a large file in one tool call, does not end the request. SIE sends a+ `ping` event every 10 seconds while nothing else is due.++## What Claude Code puts on the wire++Recorded on 2026-10-15 with Claude Code 2.1.300, run headless (`claude -p`)+against a local stub that answered canned Messages replies. No model was+called. The scrubbed requests are in+[`conformance/anthropic_messages/claude_code_requests.json`](../../conformance/anthropic_messages/claude_code_requests.json),+and the gateway's tests translate every one of them.++- Every request goes to `POST /v1/messages?beta=true` with+ `anthropic-version: 2023-06-01` and an `anthropic-beta` list, which SIE+ accepts and ignores.+- The body carries `thinking: {"type": "adaptive"}`, which asks SIE for the+ model's reasoning as `thinking` blocks, `cache_control` on system and+ message blocks, and `metadata.user_id`. SIE accepts both and does nothing+ with them: prefix caching is automatic, and `metadata` is never logged or+ forwarded.+- The first request of a session carries `output_config.effort`. SIE refuses+ it with `output_config.effort: Extra inputs are not permitted`, and Claude+ Code sends the request again without effort and leaves it off for that+ model.+- Without `--bare`, Claude Code puts its environment notes into+ `role: "system"` turns in the middle of the conversation. SIE refuses those+ with `messages.N.role: role "system" is not supported in messages; use the+ top-level system parameter`, and Claude Code sends the request again with+ the same text as user-turn reminders, until `/clear` or `/compact`. So a+ session costs up to two refused requests at its start.+- An image on a model without image input is refused with a path such as+ `messages.2.content.0.tool_result.content.0.image: Model '...' does not+ support image input`. Claude Code replaces the image with a note and+ continues.+- A prompt over the window is refused with `prompt is too long: N tokens > M+ maximum`, the wording that starts Claude Code's compaction.+- SIE sends zero usage on `message_start` and the counts on `message_delta`.+ Claude Code reports the `message_delta` counts.+- With `--bare`, Claude Code declares three tools (`Bash`, `Edit`, `Read`) and+ a short system prompt, sends no system turns, and reads its key only from+ `ANTHROPIC_API_KEY` or an `apiKeyHelper`. The helper's value goes out as+ both `Authorization: Bearer` and `x-api-key`.+- Its `auto` permission mode asks the model to approve some tool calls in+ separate, non-streamed requests with `stop_sequences`. A model that answers+ them in another format gets the action blocked. The gate uses+ `--permission-mode acceptEdits`.++## What the Messages conformance check checks++| Case | Passes when |+|---|---|+| `streaming_tool_use` | a `tool_use` block opens with an id and the name `get_weather`, its `input_json_delta` pieces join into a JSON object with `city`, and `stop_reason` is `tool_use` |+| `parallel_tool_use` | one turn asked for Paris and Tokyo returns two or more `tool_use` blocks with distinct ids and both cities |+| `tool_result_round_trip` | after the assistant `tool_use` and a `tool_result` of 18 degrees, the answer carries 18, no further call, `stop_reason: end_turn` |+| `prompt_above_64k_tokens` | a 68,000-word prompt is accepted with over 65,536 input tokens and answered. When the declared window is smaller, the refusal and whether it uses Claude Code's compaction wording are recorded |+| `stop_reason_end_turn` | a one-word answer ends with `end_turn` |+| `stop_reason_tool_use` | the tool turn above ended with `tool_use` |+| `stop_reason_max_tokens` | `max_tokens: 8` on a long request ends with `max_tokens` |+| `usage_on_message_delta` | `message_start` carries a usage object and `message_delta` carries non-zero `input_tokens` and `output_tokens` |+| `thinking_blocks` | with `thinking` adaptive, reasoning comes back as `thinking` blocks streamed and buffered, never without asking, and no `<think>` tag leaks into text. A model that returns no reasoning is recorded |+| `tool_choice_any` | recorded: a forced call, or the refusal |+| `buffered_message` | a non-streamed request, which Claude Code falls back to after a broken stream, returns `end_turn` and usage |+| `inert_fields_accepted` | `metadata`, `cache_control` on system, message and tool blocks, and `anthropic-beta` are accepted |+| `effort_refusal` | `output_config.effort` is refused with exactly the wording Claude Code retries on |+| `system_turn_refusal` | a `role: "system"` turn is refused with wording Claude Code resends on |+| `unknown_model` | an unknown model answers `404 not_found_error` |+| `event_grammar` | every stream starts with `message_start`, opens one block at a time with indices from 0, and ends with `message_delta` then `message_stop`, or with one `error` event |+| `ping_events` | recorded: the `ping` events seen |+| `count_tokens` | recorded: the answer to `POST /v1/messages/count_tokens`, which SIE does not serve, so Claude Code estimates locally |++Busy refusals are retried as in the chat check: a `429` or `503`, or an+`overloaded_error` or `rate_limit_error` event before any output, with the+`Retry-After` wait, at most 4 times and 3 minutes.++## What result to expect++### The gate against a recording stub, recorded++`run_gate.sh` with Claude Code 2.1.300 and a stub on `SIE_BASE_URL` that+refuses `output_config.effort` as SIE does and otherwise plays a model that+reads the module, edits it and runs the tests, 2026-10-15:++```+== before: the seeded tests+FAILED tests/test_amounts.py::test_credit_in_parentheses_is_negative - decima...+FAILED tests/test_amounts.py::test_total_nets_credits - decimal.InvalidOperat...+2 failed, 1 passed in 0.02s+== claude run, recipe cloud, up to 50 turns and 1800 s+== the run+{+ "turns": 4,+ "usage": {"input_tokens": 4000, "cache_read_input_tokens": 800, "output_tokens": 20},+ "tool_uses": ["Read", "Edit", "Bash"],+ "api_retries": 0,+ "problems": []+}+== after: the seeded tests must be untouched+== after: pytest in a fresh environment, pinned to the seeded config and tests+... [100%]+3 passed in 0.01s+GATE PASS (.../run-output/gate-20261015T160142Z-L4yhJy)+```++This checks the plumbing only: the recipe, `--bare` with the key helper, the+effort refusal and retry, the tool permissions and the verdict. It says+nothing about a model.++### Checked in this repository++- The gateway's tests replay the shared vectors in+ `conformance/anthropic_messages/` (request translation, buffered answer,+ event sequence, error mapping), translate every captured Claude Code+ request, serve `/v1/messages` through the real chat handler with a scripted+ transport, and check that any chat chunk sequence yields a well-formed event+ sequence.+- `tests/test_run_gate.py` runs `run_gate.sh` with a scripted stand-in for+ `claude`: a real fix, no change, a failed run, a run that ended in an error,+ read no input tokens or took too few turns, edited tests, a run past its+ deadline, both recipes, and the arguments and environment Claude Code is+ started with.+- The OpenCode example's `tests/test_messages_conformance.py` checks the+ `--api messages` checker against a scripted Messages stub.++```sh+uv run pytest+```++## What this does NOT establish++- **Not supported by Anthropic.** Anthropic does not support Claude Code with+ non-Claude models behind a gateway. A Claude Code release can change what it+ sends. The capture above is how to re-check a new version.+- **Not a live result yet.** Neither recipe has been run against a live+ endpoint, and no model has worked the fixture through `/v1/messages` here.+- **Not a coding benchmark.** The fixture is two failing tests in a+ twenty-line module.+- **Not the single-node server.** `sie-server` does not serve `/v1/messages`.diff --git a/examples/coding-agent-claude-code/gate_verdict.py b/examples/coding-agent-claude-code/gate_verdict.pynew file mode 100755index 000000000..7250df54b--- /dev/null+++ b/examples/coding-agent-claude-code/gate_verdict.py@@ -0,0 +1,97 @@+#!/usr/bin/env python3+"""Judge a headless Claude Code run from its ``--output-format stream-json`` events.++ python gate_verdict.py run-output/gate-.../claude-events.jsonl++The run passes when Claude Code finished without an error, took at least+``MIN_TURNS`` turns, read a non-zero input token count from the endpoint's+usage, and retried no request that the endpoint refused as invalid. Prints a+JSON summary of the run either way.+"""++from __future__ import annotations++import json+import sys+from pathlib import Path+from typing import Any++MIN_TURNS = 3+++def _events(lines: list[str]) -> tuple[list[dict[str, Any]], int]:+ events: list[dict[str, Any]] = []+ unreadable = 0+ for line in lines:+ line = line.strip()+ if not line:+ continue+ try:+ event = json.loads(line)+ except json.JSONDecodeError:+ unreadable += 1+ continue+ if isinstance(event, dict):+ events.append(event)+ return events, unreadable+++def _tool_uses(events: list[dict[str, Any]]) -> list[str]:+ names = []+ for event in events:+ if event.get("type") != "assistant":+ continue+ for block in (event.get("message") or {}).get("content") or []:+ if isinstance(block, dict) and block.get("type") == "tool_use":+ names.append(str(block.get("name")))+ return names+++def judge(lines: list[str]) -> tuple[bool, dict[str, Any]]:+ events, unreadable = _events(lines)+ results = [event for event in events if event.get("type") == "result"]+ retries = [event for event in events if event.get("type") == "system" and event.get("subtype") == "api_retry"]+ invalid_retries = [+ event+ for event in retries+ if event.get("error_status") == 400 or event.get("error") in ("invalid_request", "invalid_request_error")+ ]+ result = results[-1] if results else {}+ usage = result.get("usage") or {}+ problems = []+ if not results:+ problems.append("no result event")+ else:+ if result.get("is_error"):+ problems.append(f"the run ended in an error: {str(result.get('result'))[:200]}")+ if result.get("subtype") != "success":+ problems.append(f"result subtype is {result.get('subtype')!r}")+ if (result.get("num_turns") or 0) < MIN_TURNS:+ problems.append(f"{result.get('num_turns')} turns, fewer than {MIN_TURNS}")+ if not usage.get("input_tokens"):+ problems.append("Claude Code read no input tokens from the endpoint's usage")+ if invalid_retries:+ problems.append(f"{len(invalid_retries)} request(s) refused as invalid were retried")+ summary = {+ "turns": result.get("num_turns"),+ "duration_ms": result.get("duration_ms"),+ "usage": {key: usage.get(key) for key in ("input_tokens", "cache_read_input_tokens", "output_tokens")},+ "tool_uses": _tool_uses(events),+ "api_retries": len(retries),+ "unreadable_lines": unreadable,+ "problems": problems,+ }+ return not problems, summary+++def main() -> int:+ if len(sys.argv) != 2:+ print(__doc__, file=sys.stderr)+ return 2+ passed, summary = judge(Path(sys.argv[1]).read_text(encoding="utf-8").splitlines())+ print(json.dumps(summary, indent=2))+ return 0 if passed else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/examples/coding-agent-claude-code/pyproject.toml b/examples/coding-agent-claude-code/pyproject.tomlnew file mode 100644index 000000000..9ebb98023--- /dev/null+++ b/examples/coding-agent-claude-code/pyproject.toml@@ -0,0 +1,23 @@+[project]+name = "superlinked-sie-coding-agent-claude-code-example"+version = "0.1.0"+description = "Claude Code recipes and a seeded gate for SIE's Anthropic Messages endpoint"+requires-python = ">=3.12,<3.13"+dependencies = []++[tool.uv]+package = false++[dependency-groups]+dev = [+ "pytest>=8",+ "ruff>=0.14",+]++[tool.pytest.ini_options]+testpaths = ["tests"]+pythonpath = ["."]++[tool.ruff]+line-length = 120+target-version = "py312"diff --git a/examples/coding-agent-claude-code/recipes/cloud.sh b/examples/coding-agent-claude-code/recipes/cloud.shnew file mode 100644index 000000000..778a455b6--- /dev/null+++ b/examples/coding-agent-claude-code/recipes/cloud.sh@@ -0,0 +1,20 @@+# Claude Code on SIE Cloud, through /v1/messages, with GLM-5.3-Flash via SIE Relay.+#+# export SIE_BASE_URL=https://... # your SIE Cloud endpoint, without /v1+# export SIE_API_KEY=sk-sie-...+# source recipes/cloud.sh && claude+#+# The window matches what the :relay profile declares in /v1/models.+export ANTHROPIC_BASE_URL="$SIE_BASE_URL"+export ANTHROPIC_AUTH_TOKEN="$SIE_API_KEY"+export ANTHROPIC_MODEL="zai-org/GLM-5.3-Flash:relay"+export ANTHROPIC_DEFAULT_OPUS_MODEL="$ANTHROPIC_MODEL"+export ANTHROPIC_DEFAULT_SONNET_MODEL="$ANTHROPIC_MODEL"+export ANTHROPIC_DEFAULT_HAIKU_MODEL="$ANTHROPIC_MODEL"+export CLAUDE_CODE_SUBAGENT_MODEL="$ANTHROPIC_MODEL"+export CLAUDE_CODE_MAX_CONTEXT_TOKENS=131072+export CLAUDE_CODE_MAX_OUTPUT_TOKENS=32768+export CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1+export CLAUDE_CODE_ATTRIBUTION_HEADER=0+export CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1+export API_TIMEOUT_MS=1800000diff --git a/examples/coding-agent-claude-code/recipes/cluster.sh b/examples/coding-agent-claude-code/recipes/cluster.shnew file mode 100644index 000000000..03705a3e1--- /dev/null+++ b/examples/coding-agent-claude-code/recipes/cluster.sh@@ -0,0 +1,21 @@+# Claude Code on a self-hosted SIE cluster, through its gateway's /v1/messages.+#+# export SIE_BASE_URL=https://your-gateway # without /v1+# export SIE_API_KEY=...+# export SIE_MODEL=zai-org/GLM-5.3-Flash # a tools-capable generation model, or model:profile+# export SIE_CONTEXT_TOKENS=... # the window /v1/models declares for it+# export SIE_OUTPUT_TOKENS=... # at most the profile's max_output_tokens+# source recipes/cluster.sh && claude+export ANTHROPIC_BASE_URL="$SIE_BASE_URL"+export ANTHROPIC_AUTH_TOKEN="$SIE_API_KEY"+export ANTHROPIC_MODEL="$SIE_MODEL"+export ANTHROPIC_DEFAULT_OPUS_MODEL="$ANTHROPIC_MODEL"+export ANTHROPIC_DEFAULT_SONNET_MODEL="$ANTHROPIC_MODEL"+export ANTHROPIC_DEFAULT_HAIKU_MODEL="$ANTHROPIC_MODEL"+export CLAUDE_CODE_SUBAGENT_MODEL="$ANTHROPIC_MODEL"+export CLAUDE_CODE_MAX_CONTEXT_TOKENS="$SIE_CONTEXT_TOKENS"+export CLAUDE_CODE_MAX_OUTPUT_TOKENS="$SIE_OUTPUT_TOKENS"+export CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1+export CLAUDE_CODE_ATTRIBUTION_HEADER=0+export CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1+export API_TIMEOUT_MS=1800000diff --git a/examples/coding-agent-claude-code/run_gate.sh b/examples/coding-agent-claude-code/run_gate.shnew file mode 100755index 000000000..9654b2d6b--- /dev/null+++ b/examples/coding-agent-claude-code/run_gate.sh@@ -0,0 +1,138 @@+#!/usr/bin/env bash+# Seeded gate: Claude Code works the shared fixture headless through SIE's /v1/messages,+# then pytest judges it.+#+# SIE_BASE_URL=https://... SIE_API_KEY=sk-sie-... ./run_gate.sh # SIE Cloud (recipes/cloud.sh)+# SIE_BASE_URL=https://... SIE_API_KEY=... SIE_MODEL=... \+# SIE_CONTEXT_TOKENS=... SIE_OUTPUT_TOKENS=... ./run_gate.sh cluster # your gateway (recipes/cluster.sh)+#+# Needs claude and uv on PATH. The fixture is the OpenCode example's, unchanged. Writes+# run-output/gate-<timestamp>-<suffix>/ with the worked copy of the fixture, Claude Code's+# stream-json events, a summary of the run and the pytest verdict.+#+# Claude Code runs with --bare and an empty config directory, so no user settings, hooks,+# MCP servers or CLAUDE.md files take part. Its key comes from an apiKeyHelper that prints+# SIE_API_KEY. The run is bounded: GATE_TURNS turns (default 50), and a run still going+# after GATE_DEADLINE_SECONDS (default 1800) is stopped and fails.+set -euo pipefail++HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+FIXTURE="$HERE/../coding-agent-opencode/fixture"+RECIPE="${1:-cloud}"+ENV_FILE="$HERE/recipes/$RECIPE.sh"+if [[ ! -f "$ENV_FILE" ]]; then+ echo "unknown recipe '$RECIPE'; pick cloud or cluster" >&2+ exit 2+fi+for tool in claude uv; do+ if ! command -v "$tool" >/dev/null; then+ echo "$tool is not on PATH" >&2+ exit 2+ fi+done+GATE_TURNS="${GATE_TURNS:-50}"+GATE_DEADLINE_SECONDS="${GATE_DEADLINE_SECONDS:-1800}"+for var in GATE_TURNS GATE_DEADLINE_SECONDS; do+ if [[ ! "${!var}" =~ ^[1-9][0-9]*$ ]]; then+ echo "$var must be a positive whole number" >&2+ exit 2+ fi+done+REQUIRED=(SIE_BASE_URL SIE_API_KEY)+if [[ "$RECIPE" == "cluster" ]]; then+ REQUIRED+=(SIE_MODEL SIE_CONTEXT_TOKENS SIE_OUTPUT_TOKENS)+fi+for var in "${REQUIRED[@]}"; do+ if [[ -z "${!var:-}" ]]; then+ echo "$var is not set" >&2+ exit 2+ fi+done++mkdir -p "$HERE/run-output"+OUT="$(mktemp -d "$HERE/run-output/gate-$(date -u +%Y%m%dT%H%M%SZ)-XXXXXX")"+WORK="$OUT/fixture"+cp -R "$FIXTURE" "$WORK"+rm -rf "$WORK/.venv" "$WORK/uv.lock"+git -C "$WORK" init -q+TASK="$(cat "$WORK/README.md")"+mkdir -p "$OUT/claude-config"++seeded_tests() {+ (cd "$WORK" && unset PYTEST_ADDOPTS PYTEST_PLUGINS && uv tool run --quiet --isolated --no-config --python 3.12 --from 'pytest>=8' pytest -q -c pyproject.toml tests)+}++echo "== before: the seeded tests"+seeded_tests 2>&1 | tail -n 3 || true++echo "== claude run, recipe $RECIPE, up to $GATE_TURNS turns and $GATE_DEADLINE_SECONDS s"+set -m+{+ (+ cd "$WORK"+ # shellcheck source=/dev/null+ source "$ENV_FILE"+ unset ANTHROPIC_API_KEY ANTHROPIC_CUSTOM_HEADERS ANTHROPIC_BEDROCK_BASE_URL ANTHROPIC_VERTEX_BASE_URL \+ ANTHROPIC_FOUNDRY_BASE_URL CLAUDE_CODE_USE_BEDROCK CLAUDE_CODE_USE_VERTEX CLAUDE_CODE_USE_FOUNDRY+ export CLAUDE_CONFIG_DIR="$OUT/claude-config"+ claude --bare -p "$TASK" \+ --settings '{"apiKeyHelper": "printenv SIE_API_KEY"}' \+ --permission-mode acceptEdits \+ --allowedTools "Read,Edit,Bash(uv run pytest *)" \+ --output-format stream-json --verbose \+ --max-turns "$GATE_TURNS" </dev/null+ ) | tee "$OUT/claude-events.jsonl"+} &+RUN=$!+{+ sleep "$GATE_DEADLINE_SECONDS"+ touch "$OUT/deadline-passed"+ kill -TERM -- "-$RUN"+ for _ in 1 2 3 4 5 6 7 8 9 10; do+ sleep 1+ kill -0 -- "-$RUN" || exit 0+ done+ kill -KILL -- "-$RUN"+} >/dev/null 2>&1 &+WATCHDOG=$!+set +m+trap 'kill -- "-$RUN" "-$WATCHDOG" 2>/dev/null || true' EXIT+trap 'exit 130' INT+trap 'exit 143' TERM+CLAUDE_STATUS=0+wait "$RUN" || CLAUDE_STATUS=$?+[[ -e "$OUT/deadline-passed" ]] || kill -- "-$WATCHDOG" 2>/dev/null || true+wait "$WATCHDOG" 2>/dev/null || true+trap - EXIT INT TERM+if [[ -e "$OUT/deadline-passed" ]]; then+ echo "GATE FAIL: claude run passed its ${GATE_DEADLINE_SECONDS}s deadline and was stopped ($OUT)"+ exit 1+fi+if [[ "$CLAUDE_STATUS" -ne 0 ]]; then+ echo "GATE FAIL: claude run exited $CLAUDE_STATUS ($OUT)"+ exit 1+fi++echo "== the run"+if ! uv run --quiet --no-project --python 3.12 python "$HERE/gate_verdict.py" "$OUT/claude-events.jsonl" | tee "$OUT/run-summary.json"; then+ echo "GATE FAIL: the Claude Code run did not finish cleanly ($OUT)"+ exit 1+fi++echo "== after: the seeded tests must be untouched"+if ! diff -r -x __pycache__ "$FIXTURE/tests" "$WORK/tests" || ! diff "$FIXTURE/pyproject.toml" "$WORK/pyproject.toml"; then+ echo "GATE FAIL: the tests or pyproject.toml were changed ($OUT)"+ exit 1+fi+if find "$WORK" -name conftest.py -not -path '*/.venv/*' | grep -q .; then+ echo "GATE FAIL: a conftest.py was added ($OUT)"+ exit 1+fi++echo "== after: pytest in a fresh environment, pinned to the seeded config and tests"+if seeded_tests 2>&1 | tee "$OUT/pytest.txt"; then+ echo "GATE PASS ($OUT)"+else+ echo "GATE FAIL ($OUT)"+ exit 1+fidiff --git a/examples/coding-agent-claude-code/tests/test_run_gate.py b/examples/coding-agent-claude-code/tests/test_run_gate.pynew file mode 100644index 000000000..9bb815371--- /dev/null+++ b/examples/coding-agent-claude-code/tests/test_run_gate.py@@ -0,0 +1,224 @@+"""run_gate.sh end to end, with a scripted stand-in for ``claude`` on PATH.++Everything but the agent is real: the script copies the shared fixture, sources+the recipe, runs the seeded tests before and after, judges the stream-json+events, checks the tests were left alone and prints the verdict. Each stand-in+plays one kind of Claude Code run.+"""++from __future__ import annotations++import json+import os+import shutil+import subprocess+from pathlib import Path++import pytest++import gate_verdict++EXAMPLE = Path(__file__).resolve().parents[1]+FIXTURE = EXAMPLE.parent / "coding-agent-opencode" / "fixture"++FIXED_AMOUNTS = """+from decimal import Decimal+++def parse_amount(text: str) -> Decimal:+ cleaned = text.strip()+ negative = cleaned.startswith("(") and cleaned.endswith(")")+ value = Decimal(cleaned.strip("()").replace("$", "").replace(",", ""))+ return -value if negative else value+++def total(cells: list[str]) -> Decimal:+ return sum((parse_amount(cell) for cell in cells), Decimal(0))+"""++FIX = f"cat > invoice_totals/amounts.py <<'PY'\n{FIXED_AMOUNTS}\nPY"+++def _events(turns: int = 4, input_tokens: int = 4000, is_error: bool = False) -> str:+ lines = [+ {"type": "system", "subtype": "init", "tools": ["Bash", "Edit", "Read"]},+ {"type": "assistant", "message": {"content": [{"type": "tool_use", "name": "Read", "input": {}}]}},+ {"type": "assistant", "message": {"content": [{"type": "tool_use", "name": "Edit", "input": {}}]}},+ {+ "type": "result",+ "subtype": "success",+ "is_error": is_error,+ "num_turns": turns,+ "duration_ms": 1200,+ "result": "done",+ "usage": {"input_tokens": input_tokens, "cache_read_input_tokens": 0, "output_tokens": 20},+ },+ ]+ return "\n".join(json.dumps(line) for line in lines)+++def _stand_in(body: str) -> str:+ return f"""#!/usr/bin/env bash+set -eu+printf '%s\\n' "$@" > "$GATE_TEST_RECORD/args"+env | grep -E '^(ANTHROPIC|CLAUDE_CODE|CLAUDE_CONFIG_DIR|API_TIMEOUT_MS)' | sort > "$GATE_TEST_RECORD/env" || true+{body}+"""+++def _gate(+ tmp_path: Path, agent: str, recipe: str = "cloud", extra_env: dict[str, str] | None = None+) -> tuple[int, str, Path]:+ root = tmp_path / "examples"+ example = root / "coding-agent-claude-code"+ if not example.exists():+ example.mkdir(parents=True)+ for name in ("run_gate.sh", "gate_verdict.py"):+ shutil.copy(EXAMPLE / name, example)+ shutil.copytree(EXAMPLE / "recipes", example / "recipes")+ ignored = shutil.ignore_patterns(".venv", "uv.lock", "__pycache__", ".pytest_cache")+ shutil.copytree(FIXTURE, root / "coding-agent-opencode" / "fixture", ignore=ignored)+ bin_dir = tmp_path / "bin"+ bin_dir.mkdir(exist_ok=True)+ claude = bin_dir / "claude"+ claude.write_text(_stand_in(agent))+ claude.chmod(0o755)+ record = tmp_path / "record"+ record.mkdir(exist_ok=True)+ env = {+ key: value+ for key, value in os.environ.items()+ if not key.startswith(("ANTHROPIC_", "CLAUDE_CODE_", "SIE_", "GATE_", "PYTEST_"))+ }+ env.update(+ {+ "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}",+ "SIE_BASE_URL": "https://sie.example",+ "SIE_API_KEY": "sk-test",+ "ANTHROPIC_API_KEY": "must-not-reach-claude",+ "ANTHROPIC_CUSTOM_HEADERS": "x-forward: elsewhere",+ "CLAUDE_CODE_USE_BEDROCK": "1",+ "GATE_TEST_RECORD": str(record),+ **(extra_env or {}),+ }+ )+ completed = subprocess.run(+ ["bash", str(example / "run_gate.sh"), recipe],+ capture_output=True,+ text=True,+ env=env,+ timeout=300,+ check=False,+ )+ return completed.returncode, completed.stdout + completed.stderr, record+++def test_a_fixing_run_passes_with_the_recipe_and_bare_flags(tmp_path: Path) -> None:+ status, output, record = _gate(tmp_path, f"{FIX}\ncat <<'EOF'\n{_events()}\nEOF")+ assert status == 0, output+ assert "GATE PASS" in output+ args = (record / "args").read_text().splitlines()+ assert args[:2] == ["--bare", "-p"]+ assert "Make the tests pass." in "\n".join(args[2 : args.index("--settings")])+ assert args[args.index("--settings") + 1] == '{"apiKeyHelper": "printenv SIE_API_KEY"}'+ assert args[args.index("--permission-mode") + 1] == "acceptEdits"+ assert args[args.index("--allowedTools") + 1] == "Read,Edit,Bash(uv run pytest *)"+ assert args[args.index("--output-format") + 1] == "stream-json"+ assert args[args.index("--max-turns") + 1] == "50"+ env = dict(line.split("=", 1) for line in (record / "env").read_text().splitlines())+ assert env["ANTHROPIC_BASE_URL"] == "https://sie.example"+ assert env["ANTHROPIC_AUTH_TOKEN"] == "sk-test"+ assert env["ANTHROPIC_MODEL"] == "zai-org/GLM-5.3-Flash:relay"+ assert env["ANTHROPIC_DEFAULT_HAIKU_MODEL"] == "zai-org/GLM-5.3-Flash:relay"+ assert env["CLAUDE_CODE_MAX_CONTEXT_TOKENS"] == "131072"+ assert env["CLAUDE_CODE_MAX_OUTPUT_TOKENS"] == "32768"+ assert env["CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS"] == "1"+ assert env["CLAUDE_CODE_ATTRIBUTION_HEADER"] == "0"+ assert "ANTHROPIC_API_KEY" not in env+ assert "ANTHROPIC_CUSTOM_HEADERS" not in env+ assert "CLAUDE_CODE_USE_BEDROCK" not in env+ assert "/run-output/gate-" in env["CLAUDE_CONFIG_DIR"]+++def test_the_cluster_recipe_takes_the_model_and_window_from_the_environment(tmp_path: Path) -> None:+ extra = {"SIE_MODEL": "org/model:long", "SIE_CONTEXT_TOKENS": "65536", "SIE_OUTPUT_TOKENS": "8192"}+ status, output, record = _gate(tmp_path, f"{FIX}\ncat <<'EOF'\n{_events()}\nEOF", "cluster", extra)+ assert status == 0, output+ env = dict(line.split("=", 1) for line in (record / "env").read_text().splitlines())+ assert env["ANTHROPIC_MODEL"] == "org/model:long"+ assert env["CLAUDE_CODE_SUBAGENT_MODEL"] == "org/model:long"+ assert env["CLAUDE_CODE_MAX_CONTEXT_TOKENS"] == "65536"+ assert env["CLAUDE_CODE_MAX_OUTPUT_TOKENS"] == "8192"++[email protected]("missing", ["SIE_MODEL", "SIE_CONTEXT_TOKENS", "SIE_OUTPUT_TOKENS"])+def test_the_cluster_recipe_needs_the_model_and_window(tmp_path: Path, missing: str) -> None:+ extra = {"SIE_MODEL": "m", "SIE_CONTEXT_TOKENS": "65536", "SIE_OUTPUT_TOKENS": "8192", missing: ""}+ status, output, _ = _gate(tmp_path, "exit 0", "cluster", extra)+ assert status == 2+ assert f"{missing} is not set" in output+++def test_an_unknown_recipe_is_refused(tmp_path: Path) -> None:+ status, output, _ = _gate(tmp_path, "exit 0", "laptop")+ assert status == 2+ assert "unknown recipe 'laptop'" in output+++def test_no_change_fails_on_the_seeded_tests(tmp_path: Path) -> None:+ status, output, _ = _gate(tmp_path, f"cat <<'EOF'\n{_events()}\nEOF")+ assert status == 1+ assert output.rstrip().splitlines()[-1].startswith("GATE FAIL (")+++def test_a_failed_run_fails(tmp_path: Path) -> None:+ status, output, _ = _gate(tmp_path, "exit 3")+ assert status == 1+ assert "GATE FAIL: claude run exited 3" in output+++ ("events", "problem"),+ [+ (_events(is_error=True), "the run ended in an error"),+ (_events(input_tokens=0), "read no input tokens"),+ (_events(turns=1), "fewer than 3"),+ ("", "no result event"),+ ],+)+def test_an_unclean_run_fails_before_pytest(tmp_path: Path, events: str, problem: str) -> None:+ status, output, _ = _gate(tmp_path, f"{FIX}\ncat <<'EOF'\n{events}\nEOF")+ assert status == 1+ assert "GATE FAIL: the Claude Code run did not finish cleanly" in output+ assert problem in output+++def test_edited_tests_fail(tmp_path: Path) -> None:+ edit = "echo 'def test_nothing(): pass' > tests/test_amounts.py"+ status, output, _ = _gate(tmp_path, f"{FIX}\n{edit}\ncat <<'EOF'\n{_events()}\nEOF")+ assert status == 1+ assert "GATE FAIL: the tests or pyproject.toml were changed" in output+++def test_a_run_past_its_deadline_is_stopped(tmp_path: Path) -> None:+ status, output, _ = _gate(tmp_path, "sleep 60", extra_env={"GATE_DEADLINE_SECONDS": "2"})+ assert status == 1+ assert "passed its 2s deadline" in output+++def test_the_verdict_counts_invalid_request_retries() -> None:+ lines = _events().splitlines()+ retry = {"type": "system", "subtype": "api_retry", "error_status": 400, "error": "invalid_request_error"}+ passed, summary = gate_verdict.judge([json.dumps(retry), *lines, "not json"])+ assert not passed+ assert summary["api_retries"] == 1+ assert summary["unreadable_lines"] == 1+ assert summary["tool_uses"] == ["Read", "Edit"]+ assert "1 request(s) refused as invalid were retried" in summary["problems"]+++def test_the_verdict_accepts_a_busy_retry() -> None:+ retry = {"type": "system", "subtype": "api_retry", "error_status": 503, "error": "overloaded_error"}+ passed, summary = gate_verdict.judge([json.dumps(retry), *_events().splitlines()])+ assert passed, summary+ assert summary["usage"]["input_tokens"] == 4000diff --git a/examples/coding-agent-claude-code/uv.lock b/examples/coding-agent-claude-code/uv.locknew file mode 100644index 000000000..0a60176de--- /dev/null+++ b/examples/coding-agent-claude-code/uv.lock@@ -0,0 +1,107 @@+version = 1+requires-python = "==3.12.*"++[[package]]+name = "colorama"+version = "0.4.6"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335 },+]++[[package]]+name = "iniconfig"+version = "2.3.1"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/01/e1/2069291243c926a2ff1cd706c7f3eeb9b62144bf60f77c9fb9ff2fb26bd3/iniconfig-2.3.1.tar.gz", hash = "sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960", size = 21209 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552 },+]++[[package]]+name = "packaging"+version = "26.3"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956 },+]++[[package]]+name = "pluggy"+version = "1.7.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/bf/db/7fc19e6f2dc92a966727031389fc2e08b558f0f25eb7403c1119ad4713cd/pluggy-1.7.0.tar.gz", hash = "sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8", size = 123304 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/40/9e/2b38731e0fc536806f16490e1a12d7f0dc2a1235aa8cc07bcc75416a7daa/pluggy-1.7.0-py3-none-any.whl", hash = "sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec", size = 27082 },+]++[[package]]+name = "pygments"+version = "2.21.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147 },+]++[[package]]+name = "pytest"+version = "9.1.1"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "colorama", marker = "sys_platform == 'win32'" },+ { name = "iniconfig" },+ { name = "packaging" },+ { name = "pluggy" },+ { name = "pygments" },+]+sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536 },+]++[[package]]+name = "ruff"+version = "0.17.1"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/f9/e7/e6d5749983b020e6cb1055abec0a6f361a8e94f0184cdcf56d4760995f02/ruff-0.17.1.tar.gz", hash = "sha256:5bb796c5112e9fb9527f2ef2faa0a130d6312d19de92bcfaddd70dbb2d41020f", size = 5323349 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/2e/78/90c46ca6250709f7c37e397b60d06061adee8d0f7d13959ed6a8e49b14fd/ruff-0.17.1-py3-none-linux_armv6l.whl", hash = "sha256:1796c41eafec66f4635125dd1e074a7aa27b8d20c187d484360acf11d247fc4a", size = 10147528 },+ { url = "https://files.pythonhosted.org/packages/aa/d2/a2e28bc35b083ae51fa07dfba5280a667c8b01ecaee7802fc8849dcd5c46/ruff-0.17.1-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:8eadb09a788010be29c895418bdfa513e4e1c65e64b94e5b19e4cd381f6cc7fb", size = 10225974 },+ { url = "https://files.pythonhosted.org/packages/8e/71/7a9029a81c8206ee01a98f6cfeeb56e6c095af86857581a37045c46d7e94/ruff-0.17.1-py3-none-macosx_11_0_arm64.whl", hash = "sha256:29b454f18ca3eeaf37fbf140841dcf27d36109e29dee9aae8acecb68c26c6f74", size = 9270361 },+ { url = "https://files.pythonhosted.org/packages/c0/8c/e075e9c917cb0575297880c96768304e881240171c870cbd8d9b7b54bec2/ruff-0.17.1-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:872e03dd231744d6c5ec5c8af6be52b71323fc6ee096e4c8b34d9f844ee3b978", size = 9938300 },+ { url = "https://files.pythonhosted.org/packages/87/27/0b4bb926a49de2383f161272b4d863571a4c7ecdbf595a6bc58813a13367/ruff-0.17.1-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4c0d6cb5f8fbac77eec9af49f4fc0eaf856b05545e372b0694d24b4e76b1c640", size = 9948464 },+ { url = "https://files.pythonhosted.org/packages/14/27/518d57e0e02aecb8ea4acac6b57b51a53173d25fa734952bfdd7d531e88e/ruff-0.17.1-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:78beced4a3c94dfedbee4b999b95b6a27b35820fdc0afbacc6d37a8da26c1cd1", size = 10638639 },+ { url = "https://files.pythonhosted.org/packages/01/82/d89a4e498ade59e6cee52d67f8da569019372212b87468c1fdeae884601c/ruff-0.17.1-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7feefc63921202894f0e158b0e32f45a5950d70a7fb693ccb9264816c25b1c05", size = 11337238 },+ { url = "https://files.pythonhosted.org/packages/a2/7c/3b0fdef9352656317c977086fe1d802902406e4f2a0d8578da90c0e6d1c5/ruff-0.17.1-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:684154861a819bf1f433669d2a0ce9c3e54677c65b8ebb866cc2a7ec86345785", size = 10896327 },+ { url = "https://files.pythonhosted.org/packages/62/86/5566290219708ce2928f3a29c4f843a1185b341ec6111c4631a33c5ceced/ruff-0.17.1-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a6ef98e51de8ef38082f90653ceeb84944bd7673783eea13e1647c5b9b064189", size = 10350811 },+ { url = "https://files.pythonhosted.org/packages/ad/d2/ca8462dabb3c413990d49703ba306c30c862195a75448d080fa8fcce9775/ruff-0.17.1-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:8f9aa5b5bd5fa1937803ea609c8f153b8de39bf3e0e149897ae34b0c5b52f467", size = 10569994 },+ { url = "https://files.pythonhosted.org/packages/e3/ad/dd1864c1f1db17c8cfb297ce70b352388e6977620f66f7182c52855407df/ruff-0.17.1-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:80e53b0e5faa3c5667f035daaa032893ae42b7cfe708c886d39ed131e54688ab", size = 10059672 },+ { url = "https://files.pythonhosted.org/packages/65/45/3f56cf1d2168c2165cdd5ac6f9668aee66a4cfdd4caf2b2cc5ccb2b1d568/ruff-0.17.1-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:056c5d5fa0ac790051ae165d7035c7bf956d02de2db557f2e9b31d877a505fca", size = 9947803 },+ { url = "https://files.pythonhosted.org/packages/aa/4b/5457cb2be4c1d1ea5e919558131a0f197a4a454a0530d9e30820e8206e4c/ruff-0.17.1-py3-none-musllinux_1_2_i686.whl", hash = "sha256:bd8f5a55b10f371642eacd0e8665a42a8b97da15c9a7187c79e697b77b5e0ce4", size = 10351807 },+ { url = "https://files.pythonhosted.org/packages/49/fb/db15b4f8fa24a1e36b99e1401f42ef6df16ee299a48670d5d262b771e7d7/ruff-0.17.1-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:ce05e6f3973611d9550a600e04bb531061e368baba31610eb57c1509a8f21a0a", size = 10765716 },+ { url = "https://files.pythonhosted.org/packages/0a/e8/1e186578076aff7a80735f625005fde678412ab609cd323ed182eb7d6b87/ruff-0.17.1-py3-none-win32.whl", hash = "sha256:1de0030a8aa78c65c5fecb84b2e5c390ac684c0452875a02afc7c083d49a496a", size = 9895093 },+ { url = "https://files.pythonhosted.org/packages/6a/2e/da3d9589bae8e8b58f3a48bd5bc0b980232fb14a83bf02c3be7660f87c1b/ruff-0.17.1-py3-none-win_amd64.whl", hash = "sha256:5df76f16580fab58d0f6c98a3ac254a4abceb7b2489b8b678335869cff77b3d7", size = 10097955 },+ { url = "https://files.pythonhosted.org/packages/df/c9/0f2a4dea06a5e12c1191ee3d96b1e1233797d0d5e18f97a2b909a95a9836/ruff-0.17.1-py3-none-win_arm64.whl", hash = "sha256:42400b9a6ff8515ff27796f07f92e0195be011c86e81e381606f58ea5502fef4", size = 9853542 },+]++[[package]]+name = "superlinked-sie-coding-agent-claude-code-example"+version = "0.1.0"+source = { virtual = "." }++[package.dev-dependencies]+dev = [+ { name = "pytest" },+ { name = "ruff" },+]++[package.metadata]++[package.metadata.requires-dev]+dev = [+ { name = "pytest", specifier = ">=8" },+ { name = "ruff", specifier = ">=0.14" },+]diff --git a/examples/coding-agent-opencode/README.md b/examples/coding-agent-opencode/README.mdindex a53d4d11d..5ff5aab5d 100644--- a/examples/coding-agent-opencode/README.md+++ b/examples/coding-agent-opencode/README.md@@ -40,6 +40,11 @@ SDK. The thing under test is the OpenAI-compatible wire surface thatOpenCode's provider speaks, so the reference client for that surface is theright instrument.+`conformance.py --api messages` checks the Anthropic Messages endpoint,+`/v1/messages`, the way Claude Code speaks it, reading the raw event stream.+[The Claude Code example](../coding-agent-claude-code/README.md) lists its+cases and runs Claude Code on this directory's fixture.+## Run it### Against SIE Cloud@@ -459,6 +464,12 @@ What runs anywhere, and in this repository's CI, is the test suite:a `/v1/models` answered as a bare list, a model that thinks for thousandsof tokens, and a model that answers `MODEL_LOADING` for its first requests.Each verdict is checked for what it accepts and what it refuses.+- `tests/test_messages_conformance.py` runs `conformance.py --api messages`+ against a scripted Anthropic Messages stub that plays a conforming event+ stream, then breaks one thing per test: usage missing from+ `message_delta`, a delta before its block, an accepted `output_config.effort`,+ a system-turn refusal without the wording Claude Code resends on, busy+ refusals and a loading model.- `tests/test_run_gate.py` runs `run_gate.sh` with a scripted stand-in for`opencode`: a real fix, no change, a failed `opencode run`, edited tests, anenvironment planted in the worked copy, a caller's `PYTEST_ADDOPTS` ordiff --git a/examples/coding-agent-opencode/conformance.py b/examples/coding-agent-opencode/conformance.pyindex e996ff770..e6edf03cc 100755--- a/examples/coding-agent-opencode/conformance.py+++ b/examples/coding-agent-opencode/conformance.py@@ -17,6 +17,12 @@ only that it was wrong.The check goes through the ``openai`` package on purpose. The thing under testis the OpenAI-compatible wire surface that OpenCode's provider speaks, so thereference client for that surface is the right instrument here.++``--api messages`` checks ``/v1/messages`` instead, the Anthropic Messages wire+that Claude Code speaks: the same agent-loop cases over ``tool_use`` and+``tool_result`` blocks, plus the event grammar, the inert fields Claude Code+sends and the refusal wording it recovers from. It reads the raw event stream+with ``httpx``, because the event sequence is what the client depends on."""from __future__ import annotations@@ -25,6 +31,7 @@ import argparseimport jsonimport mathimport os+import reimport sysimport timefrom collections.abc import Callable@@ -32,7 +39,7 @@ from dataclasses import dataclass, fieldfrom datetime import UTC, datetimefrom email.utils import parsedate_to_datetimefrom pathlib import Path-from typing import Any+from typing import Any, castimport httpximport openai@@ -55,6 +62,16 @@ LONG_PROMPT_WORDS = 68_000NEEDLE = "The access code is 7741-ZEBRA."RECORDED_HEADERS = ("x-sie-served-by", "x-sie-model-revision")REASONING_QUESTION = "Which is larger, 9.11 or 9.9? Answer with just the larger number."+MESSAGES_HEADERS = {+ "anthropic-version": "2023-06-01",+ "anthropic-beta": "claude-code-20250219,interleaved-thinking-2025-05-14",+}+MESSAGES_BUSY_TYPES = frozenset({"overloaded_error", "rate_limit_error"})+MESSAGES_WARM_UP_CODES = frozenset({"MODEL_LOADING", "PROVISIONING"})+MISSING_MODEL = "sie-conformance/no-such-model"+EFFORT_REFUSAL = "output_config.effort: Extra inputs are not permitted"+SYSTEM_TURN_REFUSAL = re.compile(r"role .{0,2}system", re.IGNORECASE)+PROMPT_TOO_LONG = re.compile(r"^prompt is too long(: \d+ tokens > \d+ maximum)?$")WEATHER_TOOL = {"type": "function",@@ -231,7 +248,9 @@ def _error_payload(exc: Exception) -> dict[str, Any]:def _is_busy(error: dict[str, Any] | None) -> bool:- return error is not None and error["status"] in (None, 429, 503) and error["code"] in BUSY_CODES+ if error is None or error["status"] not in (None, 429, 503, 529):+ return False+ return error["code"] in BUSY_CODES or error.get("type") in MESSAGES_BUSY_TYPESdef _delivered(result: StreamResult) -> bool:@@ -836,6 +855,677 @@ def print_table(report: dict[str, Any]) -> None:print(f"{summary['pass']} pass, {summary['fail']} fail, {summary['recorded']} recorded{capacity}")+# --- Anthropic Messages (`--api messages`) ---------------------------------++MESSAGES_TOOL = {+ "name": "get_weather",+ "description": WEATHER_TOOL["function"]["description"],+ "input_schema": WEATHER_TOOL["function"]["parameters"],+}+++@dataclass+class MessagesResult(StreamResult):+ """A ``/v1/messages`` answer. ``finish_reason`` holds ``stop_reason``, and+ ``usage_on_last_chunk`` says that usage arrived on ``message_delta``."""++ events: list[dict[str, Any]] = field(default_factory=list)+ pings: int = 0+ start_usage: dict[str, Any] | None = None+ status: int | None = None++ def observed(self) -> dict[str, Any]:+ observed = super().observed()+ observed["stop_reason"] = observed.pop("finish_reason")+ observed["usage_on_message_delta"] = observed.pop("usage_on_last_chunk")+ observed["status"] = self.status+ observed["message_start_usage"] = self.start_usage+ observed["events"] = len(self.events)+ observed["pings"] = self.pings+ return observed+++def _messages_error(status: int | None, body: Any, headers: httpx.Headers | None) -> dict[str, Any]:+ error = body.get("error") if isinstance(body, dict) and isinstance(body.get("error"), dict) else {}+ sie_code = headers.get("x-sie-error-code") if headers is not None else None+ retry_after = _retry_after(headers.get("retry-after")) if headers is not None else None+ return {+ "status": status,+ "code": sie_code or error.get("type"),+ "type": error.get("type"),+ "param": None,+ "message": error.get("message") or (json.dumps(body)[:200] if body else None),+ "retry_after_s": retry_after,+ }+++def _messages_event(result: MessagesResult, name: str, data: dict[str, Any]) -> None:+ summary: dict[str, Any] = {"event": name}+ if "index" in data:+ summary["index"] = data["index"]+ if name == "ping":+ result.pings += 1+ elif name == "message_start":+ result.start_usage = (data.get("message") or {}).get("usage")+ elif name == "content_block_start":+ block = data.get("content_block") or {}+ summary["block"] = block.get("type")+ if block.get("type") == "tool_use":+ index = data.get("index", len(result.tool_calls))+ result.tool_calls[index] = ToolCall(+ index=index,+ id=block.get("id"),+ name=block.get("name"),+ first_delta_complete=bool(block.get("id")) and bool(block.get("name")),+ )+ elif name == "content_block_delta":+ delta = data.get("delta") or {}+ summary["delta"] = delta.get("type")+ if delta.get("type") == "text_delta":+ result.content += delta.get("text", "")+ elif delta.get("type") == "thinking_delta":+ result.reasoning += delta.get("thinking", "")+ result.reasoning_deltas += 1+ elif delta.get("type") == "input_json_delta":+ call = result.tool_calls.setdefault(data.get("index", 0), ToolCall(index=data.get("index", 0)))+ call.arguments += delta.get("partial_json", "")+ call.deltas += 1+ elif name == "message_delta":+ result.finish_reason = (data.get("delta") or {}).get("stop_reason")+ result.usage = data.get("usage")+ result.usage_on_last_chunk = True+ elif name == "error":+ error = data.get("error") or {}+ result.error = {+ "status": None,+ "code": error.get("type"),+ "type": error.get("type"),+ "param": None,+ "message": error.get("message"),+ "retry_after_s": None,+ }+ if name not in ("message_delta", "message_stop", "ping"):+ result.usage_on_last_chunk = False+ result.events.append(summary)+++def _messages_once(client: httpx.Client, body: dict[str, Any], headers: dict[str, str] | None = None) -> MessagesResult:+ result = MessagesResult()+ try:+ with client.stream("POST", "/messages", json=body, headers=headers or MESSAGES_HEADERS) as response:+ result.status = response.status_code+ result.headers = {name: response.headers[name] for name in RECORDED_HEADERS if name in response.headers}+ if response.status_code != 200:+ response.read()+ try:+ payload = response.json()+ except ValueError:+ payload = None+ result.error = _messages_error(response.status_code, payload, response.headers)+ return result+ if not body.get("stream"):+ response.read()+ message = response.json()+ for block in message.get("content") or []:+ if block.get("type") == "text":+ result.content += block.get("text", "")+ elif block.get("type") == "thinking":+ result.reasoning += block.get("thinking", "")+ elif block.get("type") == "tool_use":+ index = len(result.tool_calls)+ result.tool_calls[index] = ToolCall(+ index=index,+ id=block.get("id"),+ name=block.get("name"),+ arguments=json.dumps(block.get("input")),+ first_delta_complete=True,+ )+ result.finish_reason = message.get("stop_reason")+ result.usage = message.get("usage")+ return result+ name = ""+ for line in response.iter_lines():+ if not line:+ name = ""+ elif line.startswith("event:"):+ name = line[len("event:") :].strip()+ elif line.startswith("data:"):+ result.chunks += 1+ _messages_event(result, name, json.loads(line[len("data:") :]))+ except (httpx.HTTPError, ValueError) as exc:+ result.error = {+ "status": None,+ "code": type(exc).__name__,+ "type": None,+ "param": None,+ "message": str(exc),+ "retry_after_s": None,+ }+ return result+++@dataclass+class MessagesSession:+ """The client for one run, and every answer it got, for the grammar check."""++ client: httpx.Client+ results: list[MessagesResult] = field(default_factory=list)++ def send(self, body: dict[str, Any], headers: dict[str, str] | None = None) -> MessagesResult:+ result = cast(MessagesResult, _retrying(lambda: _messages_once(self.client, body, headers)))+ self.results.append(result)+ return result+++def _messages_body(model: str, text: str, **params: Any) -> dict[str, Any]:+ params.setdefault("max_tokens", GENERATION_BUDGET)+ params.setdefault("stream", True)+ return {"model": model, "messages": [{"role": "user", "content": text}], **params}+++def grammar_problems(events: list[dict[str, Any]]) -> list[str]:+ """What breaks the Messages event grammar Anthropic clients parse."""+ names = [event["event"] for event in events if event["event"] != "ping"]+ if not names:+ return ["no events"]+ problems = []+ if names[0] != "message_start":+ problems.append(f"first event is {names[0]}, not message_start")+ open_index: int | None = None+ next_index = 0+ for event in events:+ name = event["event"]+ if name == "content_block_start":+ if open_index is not None:+ problems.append(f"block {event.get('index')} opened while {open_index} is open")+ if event.get("index") != next_index:+ problems.append(f"block index {event.get('index')}, expected {next_index}")+ open_index = event.get("index")+ next_index += 1+ elif name == "content_block_delta" and event.get("index") != open_index:+ problems.append(f"delta for block {event.get('index')} while {open_index} is open")+ elif name == "content_block_stop":+ if event.get("index") != open_index:+ problems.append(f"stop for block {event.get('index')} while {open_index} is open")+ open_index = None+ if names[-1] == "error":+ return problems+ if names[-2:] != ["message_delta", "message_stop"]:+ problems.append(f"ends with {names[-2:]}, not message_delta then message_stop")+ if open_index is not None:+ problems.append(f"block {open_index} never stopped")+ return problems+++def messages_case_streaming_tool_use(session: MessagesSession, model: str) -> tuple[Case, MessagesResult]:+ name = "streaming_tool_use"+ body = _messages_body(+ model,+ "What is the weather in Paris right now? Use the get_weather tool.",+ tools=[MESSAGES_TOOL],+ tool_choice={"type": "auto"},+ thinking={"type": "adaptive"},+ temperature=0,+ )+ result = session.send(body)+ failed = _fail_on_error(name, result)+ if failed:+ return failed, result+ calls = result.calls()+ problems = []+ if not calls:+ problems.append("no tool_use block came back")+ for call in calls:+ if not call.first_delta_complete:+ problems.append(f"block {call.index}: content_block_start lacks id or name")+ if call.name != "get_weather":+ problems.append(f"block {call.index} named {call.name!r}")+ parsed = call.parsed_arguments()+ if parsed is None:+ problems.append(f"block {call.index} input is not a JSON object: {call.arguments[:80]!r}")+ elif "city" not in parsed:+ problems.append(f"block {call.index} input lacks 'city': {parsed}")+ if result.finish_reason != "tool_use":+ problems.append(f"stop_reason is {result.finish_reason!r}, expected 'tool_use'")+ if problems:+ return Case(name, "fail", "; ".join(problems), result.observed()), result+ deltas = sum(call.deltas for call in calls)+ detail = f"{len(calls)} tool_use: {_describe_calls(result)}; {deltas} input_json_delta; stop_reason=tool_use"+ return Case(name, "pass", detail, result.observed()), result+++def messages_case_parallel_tool_use(session: MessagesSession, model: str) -> Case:+ name = "parallel_tool_use"+ body = _messages_body(+ model,+ "Get the current weather in Paris and in Tokyo. Call get_weather once per city, both in this turn.",+ tools=[MESSAGES_TOOL],+ temperature=0,+ )+ result = session.send(body)+ failed = _fail_on_error(name, result)+ if failed:+ return failed+ calls = result.calls()+ ids = [call.id for call in calls]+ cities = sorted(str((call.parsed_arguments() or {}).get("city", "")).lower() for call in calls)+ observed = result.observed()+ if len(calls) < 2:+ return Case(name, "fail", f"{len(calls)} tool_use in the turn: {_describe_calls(result)}", observed)+ if len(set(ids)) != len(ids) or None in ids:+ return Case(name, "fail", f"tool_use ids are not distinct: {ids}", observed)+ missing = [city for city in ("paris", "tokyo") if not any(city in c for c in cities)]+ if missing:+ return Case(name, "fail", f"{len(calls)} calls but cities {cities} miss {missing}", observed)+ return Case(name, "pass", f"{len(calls)} tool_use in one turn: {_describe_calls(result)}", observed)+++def messages_case_tool_result_round_trip(session: MessagesSession, model: str, first: MessagesResult) -> Case:+ name = "tool_result_round_trip"+ calls = first.calls()+ if _is_busy(first.error):+ return Case(name, "capacity", "not run, streaming_tool_use stayed busy", first.observed())+ if first.error or not calls:+ return Case(name, "fail", "no tool_use from streaming_tool_use to answer", first.observed())+ assistant: list[dict[str, Any]] = []+ if first.reasoning:+ assistant.append({"type": "thinking", "thinking": first.reasoning, "signature": "sie-unsigned"})+ if first.content:+ assistant.append({"type": "text", "text": first.content})+ assistant += [+ {"type": "tool_use", "id": call.id, "name": call.name, "input": call.parsed_arguments() or {}} for call in calls+ ]+ results = [+ {+ "type": "tool_result",+ "tool_use_id": call.id,+ "content": json.dumps({"city": "Paris", "temperature_c": 18, "conditions": "overcast"}),+ }+ for call in calls+ ]+ body = {+ "model": model,+ "max_tokens": GENERATION_BUDGET,+ "stream": True,+ "temperature": 0,+ "tools": [MESSAGES_TOOL],+ "messages": [+ {"role": "user", "content": "What is the weather in Paris right now? Use the get_weather tool."},+ {"role": "assistant", "content": assistant},+ {"role": "user", "content": results},+ ],+ }+ result = session.send(body)+ failed = _fail_on_error(name, result)+ if failed:+ return failed+ observed = result.observed()+ problems = []+ if result.calls():+ problems.append(f"answered with another tool_use: {_describe_calls(result)}")+ if result.finish_reason != "end_turn":+ problems.append(f"stop_reason is {result.finish_reason!r}, expected 'end_turn'")+ if not result.content.strip():+ problems.append("empty final answer")+ elif "18" not in result.content:+ problems.append(f"final answer does not carry the tool's 18: {result.content[:120]!r}")+ if problems:+ return Case(name, "fail", "; ".join(problems), observed)+ return Case(name, "pass", f"final answer used the tool result: {result.content.strip()[:100]!r}", observed)+++def messages_case_prompt_above_64k_tokens(session: MessagesSession, model: str, entry: dict[str, Any] | None) -> Case:+ name = "prompt_above_64k_tokens"+ text = f"Read this warehouse log, then answer.\n\n{long_prompt()}\n\nWhat is the access code? Reply with just the code."+ result = session.send(_messages_body(model, text, temperature=0))+ observed = result.observed()+ observed["needle_found"] = "7741-ZEBRA" in result.content+ window = declared_window(entry)+ observed["declared_window"] = window+ error = result.error+ if window is not None and window < LONG_PROMPT_MIN_TOKENS and error is not None and _is_refusal(error):+ wording = (+ "Claude Code's compaction wording" if PROMPT_TOO_LONG.match(error["message"] or "") else "other wording"+ )+ detail = (+ f"declared window {window} is under {LONG_PROMPT_MIN_TOKENS}; refused with {wording}: {error['message']}"+ )+ return Case(name, "recorded", detail, observed)+ failed = _fail_on_error(name, result)+ if failed:+ failed.observed = observed+ return failed+ usage = result.usage or {}+ prompt_tokens = (usage.get("input_tokens") or 0) + (usage.get("cache_read_input_tokens") or 0)+ if prompt_tokens < LONG_PROMPT_MIN_TOKENS:+ return Case(name, "fail", f"prompt counted as {prompt_tokens} tokens, under {LONG_PROMPT_MIN_TOKENS}", observed)+ if not result.content.strip() or result.finish_reason != "end_turn":+ return Case(name, "fail", f"accepted {prompt_tokens} tokens but stop_reason={result.finish_reason!r}", observed)+ needle = "needle found" if observed["needle_found"] else "needle not found"+ return Case(name, "pass", f"{prompt_tokens} prompt tokens accepted and answered; {needle}", observed)+++def messages_case_end_turn(session: MessagesSession, model: str) -> tuple[Case, MessagesResult]:+ name = "stop_reason_end_turn"+ result = session.send(_messages_body(model, "Reply with the single word: ready.", temperature=0))+ failed = _fail_on_error(name, result)+ if failed:+ return failed, result+ if result.finish_reason != "end_turn":+ return Case(name, "fail", f"stop_reason is {result.finish_reason!r}", result.observed()), result+ detail = f"stop_reason=end_turn after {result.content.strip()[:40]!r}"+ return Case(name, "pass", detail, result.observed()), result+++def messages_case_stop_tool_use(first: Case) -> Case:+ name = "stop_reason_tool_use"+ stop = first.observed.get("stop_reason")+ if first.status == "capacity":+ return Case(name, "capacity", "not judged, the tool turn stayed busy", {"stop_reason": stop})+ if stop == "tool_use":+ return Case(name, "pass", "stop_reason=tool_use on the tool turn", {"stop_reason": stop})+ return Case(name, "fail", f"tool turn ended with stop_reason={stop!r}", {"stop_reason": stop})+++def messages_case_max_tokens(session: MessagesSession, model: str) -> Case:+ name = "stop_reason_max_tokens"+ result = session.send(_messages_body(model, "Write three paragraphs about the sea.", max_tokens=8))+ failed = _fail_on_error(name, result)+ if failed:+ return failed+ if result.finish_reason != "max_tokens":+ return Case(name, "fail", f"stop_reason is {result.finish_reason!r} with max_tokens=8", result.observed())+ output = (result.usage or {}).get("output_tokens")+ return Case(name, "pass", f"stop_reason=max_tokens at max_tokens=8 (output_tokens={output})", result.observed())+++def messages_case_usage_on_message_delta(stop: MessagesResult) -> Case:+ name = "usage_on_message_delta"+ observed = {+ "usage": stop.usage,+ "message_start_usage": stop.start_usage,+ "on_message_delta": stop.usage_on_last_chunk,+ }+ if _is_busy(stop.error):+ return Case(name, "capacity", "not judged, the end_turn stream stayed busy", observed)+ if stop.error:+ return Case(name, "fail", "the end_turn stream failed, see stop_reason_end_turn", observed)+ usage = stop.usage or {}+ if not stop.usage_on_last_chunk or not usage:+ return Case(name, "fail", "no usage on message_delta", observed)+ if not isinstance(stop.start_usage, dict):+ return Case(name, "fail", "message_start carries no usage object", observed)+ missing = [key for key in ("input_tokens", "output_tokens") if not usage.get(key)]+ if missing:+ return Case(name, "fail", f"message_delta usage lacks {missing}: {usage}", observed)+ return Case(name, "pass", f"message_delta carries usage {usage}", observed)+++def messages_case_thinking(session: MessagesSession, model: str) -> Case:+ name = "thinking_blocks"+ with_thinking = session.send(+ _messages_body(model, REASONING_QUESTION, temperature=0, thinking={"type": "adaptive"})+ )+ without = session.send(_messages_body(model, REASONING_QUESTION, temperature=0))+ whole = session.send(+ _messages_body(model, REASONING_QUESTION, temperature=0, stream=False, thinking={"type": "adaptive"})+ )+ results = (with_thinking, without, whole)+ observed = {+ "with_thinking": with_thinking.observed(),+ "without_thinking": without.observed(),+ "non_streamed_with_thinking": whole.observed(),+ }+ for label, result in (("thinking", with_thinking), ("plain request", without), ("non-streamed thinking", whole)):+ if result.error and not _is_busy(result.error):+ error = result.error+ return Case(+ name, "fail", f"{label} failed: {error['status']} {error['type']}: {error['message']}", observed+ )+ busy = next((result for result in results if _is_busy(result.error)), None)+ if busy is not None:+ return Case(name, "capacity", _still_busy(busy), observed)+ if any("<think>" in result.content or "</think>" in result.content for result in results):+ return Case(name, "fail", "raw <think> tags leaked into text", observed)+ if without.reasoning_deltas:+ return Case(name, "fail", f"thinking arrived without asking ({without.reasoning_deltas} deltas)", observed)+ if not (with_thinking.reasoning or whole.reasoning):+ return Case(+ name,+ "recorded",+ "no thinking block came back; the model did not reason here or reasons privately",+ observed,+ )+ if not with_thinking.reasoning or not whole.reasoning:+ missing = "streamed" if not with_thinking.reasoning else "buffered"+ return Case(name, "fail", f"thinking came back on one path but not the {missing} one", observed)+ detail = f"{with_thinking.reasoning_deltas} thinking_delta, {len(with_thinking.reasoning)} chars; buffered thinking block {len(whole.reasoning)} chars; none without asking"+ return Case(name, "pass", detail, observed)+++def messages_case_tool_choice_any(session: MessagesSession, model: str) -> Case:+ name = "tool_choice_any"+ body = _messages_body(model, "Say hello.", tools=[MESSAGES_TOOL], tool_choice={"type": "any"}, temperature=0)+ result = session.send(body)+ observed = result.observed()+ if result.error:+ error = result.error+ if _is_busy(error):+ return Case(name, "capacity", _still_busy(result), observed)+ if _is_refusal(error):+ return Case(name, "recorded", f"refused: {error['status']} {error['type']}: {error['message']}", observed)+ return Case(name, "fail", f"request failed: {error['status']} {error['type']}: {error['message']}", observed)+ if result.calls():+ return Case(name, "recorded", f"supported: forced {_describe_calls(result)}", observed)+ return Case(+ name, "fail", f"accepted tool_choice any but answered without a call: {result.content[:80]!r}", observed+ )+++def messages_case_inert_fields(session: MessagesSession, model: str) -> Case:+ name = "inert_fields_accepted"+ body = {+ "model": model,+ "max_tokens": GENERATION_BUDGET,+ "stream": True,+ "metadata": {"user_id": "conformance-check"},+ "cache_control": {"type": "ephemeral"},+ "system": [{"type": "text", "text": "Answer briefly.", "cache_control": {"type": "ephemeral"}}],+ "tools": [{**MESSAGES_TOOL, "cache_control": {"type": "ephemeral"}}],+ "messages": [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "Reply with the single word: ready.",+ "cache_control": {"type": "ephemeral"},+ }+ ],+ }+ ],+ }+ result = session.send(body)+ failed = _fail_on_error(name, result)+ if failed:+ return failed+ return Case(name, "pass", "metadata, cache_control and anthropic-beta accepted", result.observed())+++def _refusal_case(name: str, result: MessagesResult, wanted: Callable[[str], bool], what: str) -> Case:+ observed = result.observed()+ error = result.error+ if error is None:+ return Case(name, "fail", f"accepted, expected a 400 with {what}", observed)+ if _is_busy(error):+ return Case(name, "capacity", _still_busy(result), observed)+ if error["status"] != 400 or error["type"] != "invalid_request_error":+ return Case(+ name, "fail", f"answered {error['status']} {error['type']}, expected 400 invalid_request_error", observed+ )+ if not wanted(error["message"] or ""):+ return Case(name, "fail", f"400 without {what}: {error['message']!r}", observed)+ return Case(name, "pass", f"400 invalid_request_error: {error['message']}", observed)+++def messages_case_effort_refusal(session: MessagesSession, model: str) -> Case:+ body = _messages_body(model, "Reply with the single word: ready.", output_config={"effort": "high"})+ result = session.send(body)+ return _refusal_case(+ "effort_refusal",+ result,+ lambda message: message == EFFORT_REFUSAL,+ "the wording Claude Code retries without effort on",+ )+++def messages_case_system_turn_refusal(session: MessagesSession, model: str) -> Case:+ body = {+ "model": model,+ "max_tokens": GENERATION_BUDGET,+ "stream": True,+ "messages": [+ {"role": "user", "content": "Reply with the single word: ready."},+ {"role": "system", "content": "The user prefers short answers."},+ ],+ }+ result = session.send(body)++ def wanted(message: str) -> bool:+ return "not supported" in message and SYSTEM_TURN_REFUSAL.search(message) is not None++ return _refusal_case(+ "system_turn_refusal", result, wanted, "the wording Claude Code resends without system turns on"+ )+++def messages_case_unknown_model(session: MessagesSession) -> Case:+ name = "unknown_model"+ result = session.send(_messages_body(MISSING_MODEL, "hi"))+ observed = result.observed()+ error = result.error+ if error is None:+ return Case(name, "fail", f"{MISSING_MODEL} was served", observed)+ if error["status"] == 404 and error["type"] == "not_found_error":+ return Case(name, "pass", f"404 not_found_error: {error['message']}", observed)+ return Case(name, "fail", f"answered {error['status']} {error['type']}, expected 404 not_found_error", observed)+++def messages_case_buffered(session: MessagesSession, model: str) -> Case:+ name = "buffered_message"+ result = session.send(_messages_body(model, "Reply with the single word: ready.", stream=False, temperature=0))+ failed = _fail_on_error(name, result)+ if failed:+ return failed+ usage = result.usage or {}+ if result.finish_reason != "end_turn" or not usage.get("input_tokens") or not usage.get("output_tokens"):+ return Case(name, "fail", f"stop_reason={result.finish_reason!r}, usage={usage}", result.observed())+ return Case(name, "pass", f"stop_reason=end_turn, usage {usage}", result.observed())+++def messages_case_event_grammar(results: list[MessagesResult]) -> Case:+ name = "event_grammar"+ streams = [result for result in results if result.events]+ problems = {f"stream {position}": grammar_problems(result.events) for position, result in enumerate(streams)}+ problems = {key: value for key, value in problems.items() if value}+ observed = {"streams": len(streams), "problems": problems}+ if not streams:+ return Case(name, "fail", "no stream to check", observed)+ if problems:+ first = next(iter(problems.values()))+ return Case(name, "fail", f"{len(problems)} of {len(streams)} streams break the grammar: {first[0]}", observed)+ return Case(+ name,+ "pass",+ f"{len(streams)} streams: message_start, one block at a time, message_delta then message_stop",+ observed,+ )+++def messages_case_pings(results: list[MessagesResult]) -> Case:+ pings = sum(result.pings for result in results)+ observed = {"pings": pings, "streams": sum(1 for result in results if result.events)}+ return Case("ping_events", "recorded", f"{pings} ping events across the streams", observed)+++def messages_case_count_tokens(session: MessagesSession, model: str) -> Case:+ name = "count_tokens"+ body = {"model": model, "messages": [{"role": "user", "content": "hi"}]}+ try:+ response = session.client.post("/messages/count_tokens", json=body, headers=MESSAGES_HEADERS)+ status = response.status_code+ try:+ payload = response.json()+ except ValueError:+ payload = None+ except httpx.HTTPError as exc:+ return Case(name, "recorded", f"request failed: {type(exc).__name__}", {})+ observed = {"status": status, "body": payload}+ if status == 200:+ return Case(name, "recorded", f"served: {payload}", observed)+ return Case(name, "recorded", f"not served: {status}; Claude Code then estimates locally", observed)+++def wait_until_messages_served(client: httpx.Client, model: str) -> dict[str, Any]:+ started = time.monotonic()+ attempts = 0+ while True:+ attempts += 1+ result = _messages_once(client, _messages_body(model, "Reply with the single word: ready.", max_tokens=4))+ elapsed = time.monotonic() - started+ code = str((result.error or {}).get("code") or "").upper()+ if code not in MESSAGES_WARM_UP_CODES or elapsed > WARM_UP_TIMEOUT_S:+ return {"attempts": attempts, "seconds": round(elapsed, 1), "error": result.error}+ time.sleep(WARM_UP_POLL_S)+++def run_messages(base_url: str, api_key: str, model: str) -> dict[str, Any]:+ headers = {"authorization": f"Bearer {api_key}"} if api_key else {}+ client = httpx.Client(base_url=base_url.rstrip("/"), headers=headers, timeout=REQUEST_TIMEOUT_S)+ started = datetime.now(UTC)+ entry = model_entry(base_url, api_key, model)+ warm_up = wait_until_messages_served(client, model)+ session = MessagesSession(client)+ cases: list[Case] = []++ tool_case, tool_result = messages_case_streaming_tool_use(session, model)+ cases.append(tool_case)+ cases.append(messages_case_parallel_tool_use(session, model))+ cases.append(messages_case_tool_result_round_trip(session, model, tool_result))+ cases.append(messages_case_prompt_above_64k_tokens(session, model, entry))+ stop_case, stop_result = messages_case_end_turn(session, model)+ cases.append(stop_case)+ cases.append(messages_case_stop_tool_use(tool_case))+ cases.append(messages_case_max_tokens(session, model))+ cases.append(messages_case_usage_on_message_delta(stop_result))+ cases.append(messages_case_thinking(session, model))+ cases.append(messages_case_tool_choice_any(session, model))+ cases.append(messages_case_buffered(session, model))+ cases.append(messages_case_inert_fields(session, model))+ cases.append(messages_case_effort_refusal(session, model))+ cases.append(messages_case_system_turn_refusal(session, model))+ cases.append(messages_case_unknown_model(session))+ cases.append(messages_case_event_grammar(session.results))+ cases.append(messages_case_pings(session.results))+ cases.append(messages_case_count_tokens(session, model))+ client.close()++ statuses = ("pass", "fail", "recorded", "capacity")+ counts = {status: sum(1 for case in cases if case.status == status) for status in statuses}+ return {+ "api": "messages",+ "base_url": base_url,+ "model": model,+ "model_entry": entry,+ "started_at": started.isoformat(),+ "finished_at": datetime.now(UTC).isoformat(),+ "served_by": tool_result.headers.get("x-sie-served-by"),+ "warm_up": warm_up,+ "cases": [{**case.__dict__, "retries": _retries_in(case.observed)} for case in cases],+ "summary": counts,+ }++def main() -> int:parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)parser.add_argument(@@ -846,9 +1536,16 @@ def main() -> int:parser.add_argument("--report", type=Path, default=DEFAULT_REPORT, help=f"JSON report path (default {DEFAULT_REPORT})")+ parser.add_argument(+ "--api",+ choices=("chat", "messages"),+ default="chat",+ help="wire to check: chat completions, as OpenCode speaks it (default), or Anthropic Messages",+ )args = parser.parse_args()- report = run(args.base_url, args.api_key, args.model)+ check = run_messages if args.api == "messages" else run+ report = check(args.base_url, args.api_key, args.model)args.report.parent.mkdir(parents=True, exist_ok=True)args.report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")print_table(report)diff --git a/examples/coding-agent-opencode/tests/test_messages_conformance.py b/examples/coding-agent-opencode/tests/test_messages_conformance.pynew file mode 100644index 000000000..40891fdc8--- /dev/null+++ b/examples/coding-agent-opencode/tests/test_messages_conformance.py@@ -0,0 +1,288 @@+"""``conformance.py --api messages`` against a scripted Anthropic Messages stub.++The stub plays the wire a conforming ``/v1/messages`` sends, events and+refusals included, and each knob breaks one thing, so every verdict is checked+both for what it accepts and for what it refuses. This checks the checker;+an endpoint is checked by running ``conformance.py --api messages`` against it.+"""++from __future__ import annotations++import json+import threading+from collections.abc import Iterator+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from typing import Any++import pytest++import conformance++KNOBS: dict[str, Any] = {}++EFFORT = "output_config.effort: Extra inputs are not permitted"+SYSTEM_TURN = 'messages.1.role: role "system" is not supported in messages; use the top-level system parameter'+++def _words(text: str) -> int:+ return len(text.split())+++def _texts(body: dict[str, Any]) -> str:+ out = []+ for message in body["messages"]:+ content = message["content"]+ if isinstance(content, str):+ out.append(content)+ continue+ for block in content:+ if block.get("type") == "text":+ out.append(block["text"])+ return " ".join(out)+++def _refusal(body: dict[str, Any]) -> tuple[int, str, str] | None:+ if body["model"] == conformance.MISSING_MODEL:+ return 404, "not_found_error", f"Model '{body['model']}' not found"+ if "output_config" in body and not KNOBS.get("effort_ok"):+ return 400, "invalid_request_error", EFFORT+ if any(message["role"] == "system" for message in body["messages"]):+ return 400, "invalid_request_error", KNOBS.get("system_wording", SYSTEM_TURN)+ return None+++def _reply(body: dict[str, Any]) -> dict[str, Any]:+ last = body["messages"][-1]["content"]+ text = _texts(body)+ thinking = (body.get("thinking") or {}).get("type") in ("adaptive", "enabled")+ if isinstance(last, list) and any(block.get("type") == "tool_result" for block in last):+ return {"text": "It is 18 degrees and overcast in Paris.", "stop": "end_turn"}+ if body.get("tools") and (body.get("tool_choice") or {}).get("type") == "any":+ return {"calls": [("toolu_any", {"city": "Paris"})], "stop": "tool_use"}+ if body.get("tools") and "Tokyo" in text:+ return {"calls": [("toolu_1", {"city": "Paris"}), ("toolu_2", {"city": "Tokyo"})], "stop": "tool_use"}+ if body.get("tools") and "weather" in text:+ reply: dict[str, Any] = {"calls": [("toolu_1", {"city": "Paris"})], "stop": "tool_use"}+ if thinking:+ reply["thinking"] = "a call"+ return reply+ if body["max_tokens"] == 8:+ return {"text": "The sea is", "stop": "max_tokens"}+ if _words(text) > 10_000:+ return {"text": "7741-ZEBRA", "stop": "end_turn"}+ if "9.11" in text:+ reply = {"text": "9.9", "stop": "end_turn"}+ if thinking:+ reply["thinking"] = "Compare the tenths."+ return reply+ return {"text": "ready", "stop": "end_turn"}+++class Handler(BaseHTTPRequestHandler):+ def log_message(self, *args: Any) -> None:+ pass++ def _json(self, status: int, payload: Any, headers: dict[str, str] | None = None) -> None:+ raw = json.dumps(payload).encode()+ self.send_response(status)+ self.send_header("content-type", "application/json")+ self.send_header("content-length", str(len(raw)))+ for name, value in (headers or {}).items():+ self.send_header(name, value)+ self.end_headers()+ self.wfile.write(raw)++ def _error(self, status: int, kind: str, message: str, headers: dict[str, str] | None = None) -> None:+ self._json(status, {"type": "error", "error": {"type": kind, "message": message}, "request_id": None}, headers)++ def do_GET(self) -> None:+ if self.path.endswith("/models"):+ self._json(200, {"models": [{"name": "stub-model", "max_sequence_length": 131072}]})+ return+ self._error(404, "not_found_error", "not found")++ def _event(self, name: str, data: dict[str, Any]) -> None:+ self.wfile.write(f"event: {name}\ndata: {json.dumps({'type': name, **data})}\n\n".encode())++ def do_POST(self) -> None:+ body = json.loads(self.rfile.read(int(self.headers["content-length"])))+ if self.path.endswith("/count_tokens"):+ self._error(404, "not_found_error", "not found")+ return+ KNOBS["_posts"] = KNOBS.get("_posts", 0) + 1+ if KNOBS["_posts"] <= KNOBS.get("loading", 0):+ self._error(503, "overloaded_error", "loading", {"x-sie-error-code": "MODEL_LOADING", "retry-after": "1"})+ return+ if KNOBS.get("busy", 0) > len(KNOBS.setdefault("_busy", [])) and body.get("tools"):+ KNOBS["_busy"].append(body)+ self._error(503, "overloaded_error", "busy", {"x-sie-error-code": "RESOURCE_EXHAUSTED", "retry-after": "0"})+ return+ refusal = _refusal(body)+ if refusal:+ self._error(*refusal)+ return+ reply = _reply(body)+ usage = {+ "input_tokens": max(1, _words(_texts(body))),+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": max(1, _words(reply.get("text", "")) + 3 * len(reply.get("calls", []))),+ }+ content: list[dict[str, Any]] = []+ if reply.get("thinking"):+ content.append({"type": "thinking", "thinking": reply["thinking"], "signature": "sie-unsigned"})+ if reply.get("text"):+ content.append({"type": "text", "text": reply["text"]})+ for call_id, arguments in reply.get("calls", []):+ content.append({"type": "tool_use", "id": call_id, "name": "get_weather", "input": arguments})+ if not body.get("stream"):+ self._json(+ 200,+ {+ "id": "msg_stub",+ "type": "message",+ "role": "assistant",+ "model": body["model"],+ "content": content,+ "stop_reason": reply["stop"],+ "stop_sequence": None,+ "usage": usage,+ },+ )+ return+ self.send_response(200)+ self.send_header("content-type", "text/event-stream")+ self.send_header("x-sie-served-by", "stub")+ self.end_headers()+ zero = {key: 0 for key in usage}+ message = {"id": "msg_stub", "type": "message", "role": "assistant", "model": body["model"], "content": []}+ self._event("message_start", {"message": {**message, "stop_reason": None, "usage": zero}})+ self._event("ping", {})+ for index, block in enumerate(content):+ if KNOBS.get("delta_before_start") and index == 0:+ self._event("content_block_delta", {"index": 0, "delta": {"type": "text_delta", "text": "x"}})+ if block["type"] == "thinking":+ self._event("content_block_start", {"index": index, "content_block": {**block, "thinking": ""}})+ delta = {"type": "thinking_delta", "thinking": block["thinking"]}+ self._event("content_block_delta", {"index": index, "delta": delta})+ elif block["type"] == "text":+ self._event("content_block_start", {"index": index, "content_block": {"type": "text", "text": ""}})+ self._event(+ "content_block_delta", {"index": index, "delta": {"type": "text_delta", "text": block["text"]}}+ )+ else:+ start = {**block, "input": {}}+ self._event("content_block_start", {"index": index, "content_block": start})+ delta = {"type": "input_json_delta", "partial_json": json.dumps(block["input"])}+ self._event("content_block_delta", {"index": index, "delta": delta})+ self._event("content_block_stop", {"index": index})+ delta_usage = {} if KNOBS.get("no_delta_usage") else {"usage": usage}+ self._event("message_delta", {"delta": {"stop_reason": reply["stop"], "stop_sequence": None}, **delta_usage})+ self._event("message_stop", {})++[email protected](scope="module")+def base_url() -> Iterator[str]:+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield f"http://127.0.0.1:{server.server_address[1]}/v1"+ finally:+ server.shutdown()++[email protected](autouse=True)+def reset_knobs(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:+ monkeypatch.setattr(conformance.time, "sleep", lambda _seconds: None)+ KNOBS.clear()+ yield+ KNOBS.clear()+++def _cases(base_url: str, **knobs: Any) -> dict[str, dict[str, Any]]:+ KNOBS.update(knobs)+ report = conformance.run_messages(base_url, "", "stub-model")+ return {case["name"]: case for case in report["cases"]}+++def test_a_conforming_endpoint_passes(base_url: str) -> None:+ cases = _cases(base_url)+ statuses = {name: case["status"] for name, case in cases.items()}+ recorded = {"tool_choice_any", "ping_events", "count_tokens"}+ assert {name for name, status in statuses.items() if status != "pass"} == recorded, statuses+ assert cases["streaming_tool_use"]["observed"]["tool_calls"][0]["first_delta_has_id_and_name"]+ assert cases["usage_on_message_delta"]["observed"]["on_message_delta"]+ assert cases["count_tokens"]["observed"]["status"] == 404+ assert cases["ping_events"]["observed"]["pings"] > 0+ assert cases["thinking_blocks"]["observed"]["without_thinking"]["reasoning_deltas"] == 0+++def test_missing_usage_on_message_delta_fails(base_url: str) -> None:+ case = _cases(base_url, no_delta_usage=True)["usage_on_message_delta"]+ assert case["status"] == "fail"+ assert "no usage on message_delta" in case["detail"]+++def test_a_delta_before_its_block_breaks_the_grammar(base_url: str) -> None:+ case = _cases(base_url, delta_before_start=True)["event_grammar"]+ assert case["status"] == "fail"+ assert "delta for block 0 while None is open" in case["detail"]+++def test_an_accepted_effort_fails_the_refusal_case(base_url: str) -> None:+ assert _cases(base_url, effort_ok=True)["effort_refusal"]["status"] == "fail"+++def test_a_system_turn_refusal_without_the_recovery_wording_fails(base_url: str) -> None:+ case = _cases(base_url, system_wording="messages.1: unexpected role")["system_turn_refusal"]+ assert case["status"] == "fail"+ assert "without the wording" in case["detail"]+++def test_busy_refusals_are_retried(base_url: str) -> None:+ case = _cases(base_url, busy=2)["streaming_tool_use"]+ assert case["status"] == "pass"+ assert case["retries"] == 2+++def test_the_warm_up_waits_out_a_loading_model(base_url: str) -> None:+ KNOBS.update(loading=2)+ report = conformance.run_messages(base_url, "", "stub-model")+ assert report["warm_up"]["attempts"] == 3+ assert report["summary"]["fail"] == 0+++ ("events", "problem"),+ [+ ([{"event": "content_block_start", "index": 0}], "first event is content_block_start"),+ (+ [+ {"event": "message_start"},+ {"event": "content_block_start", "index": 1},+ {"event": "content_block_stop", "index": 1},+ {"event": "message_delta"},+ {"event": "message_stop"},+ ],+ "block index 1, expected 0",+ ),+ (+ [{"event": "message_start"}, {"event": "content_block_start", "index": 0}, {"event": "message_stop"}],+ "not message_delta then message_stop",+ ),+ ],+)+def test_grammar_problems(events: list[dict[str, Any]], problem: str) -> None:+ assert any(problem in found for found in conformance.grammar_problems(events))+++def test_a_stream_ending_in_an_error_event_is_well_formed() -> None:+ events = [+ {"event": "message_start"},+ {"event": "ping"},+ {"event": "content_block_start", "index": 0},+ {"event": "content_block_delta", "index": 0},+ {"event": "error"},+ ]+ assert conformance.grammar_problems(events) == []diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex 3f50b6589..9f90b414a 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -46,6 +46,7 @@ Key terms used throughout this document:- `POST /v1/score/{*model}`- `POST /v1/extract/{*model}`- `POST /v1/embeddings` — OpenAI-compatible JSON surface; the gateway accepts **string** or **list of strings** for `input`, supports `encoding_format=float` (default) or `base64`, translates to an internal **`POST /v1/encode/{model}`** with `items[].text` and `params.output_types=["dense"]`, then maps encode `items[].dense` vectors into OpenAI `data[].embedding` plus a rough `usage` estimate. Token-id / nested-array inputs are rejected with **`400`**. `dimensions` is accepted only when it equals the model's native dense width and otherwise rejected with **`400 unsupported_field`**, the same rule as the single-node server. The wrapper must buffer the whole encode reply before reshaping it, and that reply is an *amplification* of the request (N short texts in, N × `dim` floats out), so the buffer is bounded by its own **response**-specific cap, `MAX_COMPAT_RESPONSE_BODY` (16 MiB) — deliberately a separate constant from the request cap it used to be derived from, since the two quantities are unrelated and a change to ingress must not silently move this bound. The value holds today's effective bound rather than raising it: at the queue's item ceiling a float reply reaches ~90 MB at 1024 dims and ~224 MB at 2560 dims (`Qwen/Qwen3-Embedding-4B`, served here), the handler holds ~4 copies at once, and the deployed gateway is a 1 GiB container running 4 requests concurrently — so no bound both admits the largest real reply and fits. **Consequence, stated plainly: a batch above roughly 760 inputs at 1024 dims cannot be served on this surface.** The cure is an ingress item cap (terminal `400` before any GPU work), streaming assembly, or a larger container — each its own change. Over the cap the surface answers a **terminal `413`** naming the one remedy that works (fewer inputs — `encoding_format=base64` is inert here, because the field is never forwarded to `/v1/encode` and base64 is applied afterwards to the outer response), never a retryable `503`. Both that `413` and the unreadable-body `500` carry `GatewayOwnedFault`: the worker has already run and reported its units, so a metered composition must release the hold rather than bill for a response carrying zero embeddings.+ - `POST /v1/messages` — Anthropic Messages compatibility surface (`handlers::messages`). The handler validates the body in Anthropic terms, translates it into a `/v1/chat/completions` body, awaits `proxy_chat` in process on the same task, and translates the answer back: a chat completion into a Message, chat SSE chunks into Messages events, and every error into the Anthropic envelope `{"type":"error","error":{"type","message"},"request_id"}` with the status the chat route chose. Every chat gate, profile limit, timeout, serving disclosure and metering point therefore applies unchanged. Unknown fields fail with `400 <field>: Extra inputs are not permitted`; `metadata`, every `cache_control`, `thinking.display: "summarized"`, tool `eager_input_streaming` and the `anthropic-beta` header are accepted and have no effect, and `metadata` is never logged or forwarded. `thinking` `enabled` or `adaptive` sets the chat request's `include_reasoning`, and reasoning comes back as `thinking` blocks with an opaque signature. Usage reports `prompt_tokens - cached_tokens` as `input_tokens` and the cached part as `cache_read_input_tokens`, so the two add up to the chat route's prompt tokens. A stream sends `message_start` with zero usage when the chat stream opens, the authoritative usage on `message_delta`, a `ping` whenever nothing was sent for 10 seconds, and a mid-stream failure as an `error` event without `message_stop`. Dropping the response body drops the chat body, so a client disconnect cancels the generation as on chat. The Anthropic error envelope is also an outer middleware, `anthropic_error_envelope`, applied to `/v1/messages` and every path below it, so auth refusals, unknown sub-paths such as `/v1/messages/count_tokens` (not served) and the method check take the same shape; a composition that adds admission layers applies it outermost. `messages_dispatch_inputs` composes the translation with `chat_completions_dispatch_inputs` for estimates and admission checks. Shared vectors under `conformance/anthropic_messages/` pin the request translation, the buffered answer, the event sequence and the error mapping.2. Gateway resolves the request to a model, a bundle, a machine profile, a logical API pool, and the backing queue pool using its in-memory registry.3. Gateway ordinarily publishes work to JetStream on the backing queue subject `sie.work.{pool}.{machine_profile}.{bundle}.{model}` and carries the logical pool as `admission_pool` in the work item. A capped logical batch pool instead targets one assigned worker on `sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}`.4. A matching worker consumes the work item, verifies its logical pool assignment when `admission_pool` differs from its physical queue pool, and executes inference.@@ -59,12 +60,12 @@ Rules enforced on the inference path:- If the queue transport is unavailable (no usable NATS client at init), the gateway returns `503`. It does not fall back to direct mode.- Unknown model ids fast-fail with `404` whenever the in-memory `ModelRegistry` has been populated (either by the filesystem seed or by a successful bootstrap / delta from `sie-config`). In the pre-bootstrap edge case where the registry is still empty — no seed, no export applied yet — the proxy falls back to the caller-supplied bundle (or `"default"`) so an unseeded gateway can still publish work to a cold pool that a caller pinned via `X-SIE-Pool`. Once any model is registered, this fallback is disabled and the 404 contract applies.- Automatic pool selection only considers healthy workers whose reported `bundle_config_hash` matches the gateway's expected hash. For the requested model, a lane (`pool`, `machine_profile`, `bundle`) is eligible only when no such worker in it lists the model in `unsupported_models`: every worker of a lane consumes the lane subject, so a worker that cannot serve the model would otherwise receive its items and NAK them, spending JetStream delivery attempts. Worker-direct rings (generation and capped logical pools) exclude workers that list the model. When every lane is excluded the gateway returns the `503 PROVISIONING` contract below and counts the exclusion in `sie.gateway.routing.unsupported_model_exclusions`. Explicit `X-SIE-Pool` selects a logical pool; the gateway publishes to that pool's backing queue pool (`PoolSpec.queue_pool`, default `default`) and stamps the logical pool into the work item as `admission_pool`. Deliveries whose hash is not the worker-sidecar's current hash, whose model the worker lists in `unsupported_models`, or whose logical pool does not assign that worker, are NAKed before backend IPC. Successful non-streaming results echo the execution hash; the gateway emits `X-SIE-Model-Revision` only when every successful result matches the hash and immutable revision captured atomically at routing time. The header value is the lowercase 64-hex executed bundle/config SHA-256, not the catalog weights revision (for example, a 40-hex Hugging Face commit). Buffered generation also follows this rule even though it internally collects worker chunks. True SSE responses (`stream: true`) always omit the header because headers precede the terminal result. Successful terminal SSE events may instead carry the worker-origin `execution_identity_sha256` / `execution_binding_sha256` pair, both lowercase 64-hex digests; absence remains valid for older or self-hosted deployments and does not attest execution. These digests are distinct from both the weights revision and the bundle/config hash.-- On scale-from-zero — i.e. no healthy worker registered for the `(bundle, machine_profile)` tuple and the caller did not pin an explicit pool — the gateway records pending demand for KEDA and returns a retryable `503` provisioning response with `Retry-After`, `X-SIE-Error-Code: PROVISIONING`, and gateway version headers. `Retry-After` is 60 seconds unless the dispatch transport estimates when the lane can accept work (see [Lanes a transport reports cold](#lanes-a-transport-reports-cold)). The message names the model as the caller sent it, before alias, case or `__` resolution, and not its machine profile or bundle, for example `Capacity for model 'BAAI/bge-m3' is starting. Retry after the number of seconds in Retry-After.` SIE-native surfaces use the SDK retry envelope (`{"error":{"code","message"}}`); OpenAI-compatible surfaces (`/v1/generate`, `/v1/embeddings`, `/v1/chat/completions`, `/v1/completions`, `/v1/responses`) use the OpenAI error envelope, because standard OpenAI clients parse 2xx as successful model output. This applies whether or not the caller set `X-SIE-MACHINE-PROFILE`; default-routing clients get the same contract as profile-pinned clients.+- On scale-from-zero — i.e. no healthy worker registered for the `(bundle, machine_profile)` tuple and the caller did not pin an explicit pool — the gateway records pending demand for KEDA and returns a retryable `503` provisioning response with `Retry-After`, `X-SIE-Error-Code: PROVISIONING`, and gateway version headers. `Retry-After` is 60 seconds unless the dispatch transport estimates when the lane can accept work (see [Lanes a transport reports cold](#lanes-a-transport-reports-cold)). The message names the model as the caller sent it, before alias, case or `__` resolution, and not its machine profile or bundle, for example `Capacity for model 'BAAI/bge-m3' is starting. Retry after the number of seconds in Retry-After.` SIE-native surfaces use the SDK retry envelope (`{"error":{"code","message"}}`); OpenAI-compatible surfaces (`/v1/generate`, `/v1/embeddings`, `/v1/chat/completions`, `/v1/completions`, `/v1/responses`) use the OpenAI error envelope, because standard OpenAI clients parse 2xx as successful model output. The Anthropic-compatible `/v1/messages` uses the Anthropic error envelope with type `overloaded_error`, keeping the `503`, `Retry-After` (capped at 60 seconds) and `X-SIE-Error-Code`. This applies whether or not the caller set `X-SIE-MACHINE-PROFILE`; default-routing clients get the same contract as profile-pinned clients.- On no-consumer conditions for the JetStream publish, the gateway treats the miss as the same pre-execution provisioning state and returns the same retryable `503 PROVISIONING` contract (the same `Retry-After` and message, `X-SIE-Error-Code: PROVISIONING`, and surface-specific error envelope). On backpressure conditions the gateway returns `503` with `Retry-After: 5`. Backpressure is evaluated twice: pool-wide against the `WORK_POOL_{pool}` stream's pending count (`SIE_GATEWAY_MAX_STREAM_PENDING`), and per lane (`pool`/`machine_profile`/`bundle`) against a gateway-local in-flight work-item count (`SIE_GATEWAY_MAX_LANE_IN_FLIGHT_ITEMS`). The per-lane decision is always computed and recorded on `sie.gateway.queue.lane_admission.decisions`, but it only sheds when `SIE_GATEWAY_LANE_BACKPRESSURE_ENFORCE` is set; with the flag off (the default) the pool-wide check is the sole gate. Both sheds produce the same `503` contract and both record pending demand for the exact physical lane so KEDA scales it.- On queue result timeouts the gateway returns `504` with `X-SIE-Error-Code: GATEWAY_TIMEOUT` and `Retry-After: 5`. This means the gateway accepted and published the work item, but no worker result reached the gateway before `SIE_GATEWAY_REQUEST_TIMEOUT`; it must not be collapsed into worker-emitted `MODEL_LOADING`, which remains a separate retryable `503 MODEL_LOADING` signal.- When workers report failure on every item of a batch with the **same retryable error code** in `WorkResult.error_code`, the gateway translates that into a `503` with the SDK-expected envelope (`error.code`, `Retry-After`, `X-SIE-Error-Code`) so the SDK auto-retries. Currently recognised codes: `RESOURCE_EXHAUSTED`, `MODEL_LOADING`, `LORA_LOADING`, and `QUEUE_FULL` (a worker that cannot serve the item now, such as a remote profile whose upstream is busy, unreachable, rate capped or behind an open circuit breaker; a remote profile whose upstream model is not ready answers `MODEL_LOADING`). A remote worker answers these upstream refusals at once with the upstream's wait rather than redelivering the item. Generation workers attach the operator's validated `oom_recovery.retry_after_s` value to a `RESOURCE_EXHAUSTED` terminal chunk, and a worker may set `WorkResult.retry_after_s` on a failed item; for `RESOURCE_EXHAUSTED`, `QUEUE_FULL` and `MODEL_LOADING` failures, the gateway uses the longest worker hint that qualifies as an integer in `1..=60` seconds, ignoring other hints. If no hint qualifies, or the code is `LORA_LOADING` even when a worker provides a hint, it uses the current five-second default compiled into the gateway. **Mixed batches** (different codes per item) keep going through the compatibility `500 all_items_failed` path with per-item `code` fields exposed in `details[]`, so callers can see exactly which items hit which failure mode. Workers reporting `RESOURCE_EXHAUSTED` are **not** marked unhealthy — losing an allocation race is not a worker-health signal.- When **every** failed item carries **`MODEL_LOAD_FAILED`**, the gateway returns **`502 Bad Gateway`** with the SDK-style **`error`** object (`code`, `message`, `error_class`, `attempts`, `permanent`) — matching the terminal model-load contract consumed by SDK retry logic (no `Retry-After`; the SDK must not burn the `MODEL_LOADING` retry budget). The gateway synthesises conservative `attempts` / `permanent` fields on this queue path when the worker payload does not carry registry-shaped failure metadata.-- Every successful response and every `5xx` of an inference route carries `X-SIE-Served-By` (`local` or `remote`) once routing has resolved the dispatched model, and `X-SIE-Upstream` with the upstream's name when that model's default profile uses a remote adapter (`handlers::serving_disclosure`). The value is read from the dispatched route's configuration, as `sie_server.api.helpers.serving_disclosure_headers` reads it on the single server, so a `model:remote` variant or a remote-backed model reports `remote` and the model's local profile reports `local`. Client errors carry neither header. The compatibility routes (`/v1/embeddings`, `/v1/rerank`, `/v2/rerank`, `/v1/audio/transcriptions`) forward both through `is_openai_compat_forwarded_header`.+- Every successful response and every `5xx` of an inference route carries `X-SIE-Served-By` (`local` or `remote`) once routing has resolved the dispatched model, and `X-SIE-Upstream` with the upstream's name when that model's default profile uses a remote adapter (`handlers::serving_disclosure`). The value is read from the dispatched route's configuration, as `sie_server.api.helpers.serving_disclosure_headers` reads it on the single server, so a `model:remote` variant or a remote-backed model reports `remote` and the model's local profile reports `local`. Client errors carry neither header. The compatibility routes (`/v1/embeddings`, `/v1/rerank`, `/v2/rerank`, `/v1/audio/transcriptions`, `/v1/messages`) forward both through `is_openai_compat_forwarded_header`.Encode / extract tuning fields (`output_types`, `instruction`, `options`, `labels`, `output_schema`, `is_query`) are read **only** from the nested JSON **`params`** object (and the msgpack analogue: a top-level **`params`** map). The score path continues to read `query` / `instruction` / `options` at the top level of the request body, matching `sie_server`.@@ -553,6 +554,7 @@ Inference (queue-only):- `POST /v1/score/{*model}`- `POST /v1/extract/{*model}`- `POST /v1/embeddings` — OpenAI JSON compatibility layer over encode (string or list of strings); see §2.+- `POST /v1/messages` — Anthropic Messages compatibility layer over chat completions; see §2. `POST /v1/messages/count_tokens` is not served (`404 not_found_error`).Config (read-side only):@@ -1109,7 +1111,7 @@ lane. It is `false` by default and is a non-publishing hint.budget, so the SDKs still retry after it.- On the OpenAI-compatible routes (`/v1/chat/completions`,`/v1/completions`, `/v1/responses`, `/v1/embeddings`,- `/v1/audio/transcriptions`) and the rerank routes (`/v1/rerank`,+ `/v1/audio/transcriptions`, `/v1/messages`) and the rerank routes (`/v1/rerank`,`/v2/rerank`) the ceiling is 60 seconds. The OpenAI Python clienthonors `Retry-After` only when it is greater than 0 and at most 60seconds. Above that it ignores the header and retries on its owndiff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex 0b4ae3246..3c97fc552 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -19,6 +19,45 @@],"type": "object"},+ "AnthropicErrorBody": {+ "properties": {+ "message": {+ "type": "string"+ },+ "type": {+ "description": "Follows the status: ``invalid_request_error`` (400),\n``authentication_error`` (401), ``billing_error`` (402),\n``permission_error`` (403), ``not_found_error`` (404),\n``request_too_large`` (413), ``rate_limit_error`` (429),\n``api_error`` (500, 502), ``overloaded_error`` (503),\n``timeout_error`` (504).",+ "type": "string"+ }+ },+ "required": [+ "type",+ "message"+ ],+ "type": "object"+ },+ "AnthropicErrorEnvelope": {+ "description": "Anthropic error envelope used on ``/v1/messages``. The SIE error code is\nin the ``X-SIE-Error-Code`` header. ``Retry-After`` is at most 60.",+ "properties": {+ "error": {+ "$ref": "#/components/schemas/AnthropicErrorBody"+ },+ "request_id": {+ "type": [+ "string",+ "null"+ ]+ },+ "type": {+ "description": "Always ``error``.",+ "type": "string"+ }+ },+ "required": [+ "type",+ "error"+ ],+ "type": "object"+ },"AssignedWorker": {"properties": {"bundle": {@@ -1152,6 +1191,11 @@],"type": "object"},+ "EmptyOutputConfig": {+ "additionalProperties": false,+ "description": "An ``output_config`` with no fields, the only one accepted.",+ "type": "object"+ },"EncodeParams": {"properties": {"instruction": {@@ -2193,6 +2237,181 @@],"type": "object"},+ "MessagesRequest": {+ "additionalProperties": false,+ "description": "Anthropic Messages request, as accepted by ``POST /v1/messages``.\n\nThe request is translated into a ``/v1/chat/completions`` request and\nserved by the chat route, so every chat limit applies. Fields outside this\nset fail with ``400 invalid_request_error`` and the message\n``<field>: Extra inputs are not permitted``. ``metadata`` and every\n``cache_control`` are accepted and have no effect: prefix caching is\nautomatic and ``metadata`` is neither logged nor forwarded.",+ "properties": {+ "cache_control": {+ "description": "Accepted and ignored."+ },+ "max_tokens": {+ "description": "Output token limit, at least 1 and at most the serving profile's\n``max_output_tokens``.",+ "format": "int32",+ "minimum": 1,+ "type": "integer"+ },+ "messages": {+ "description": "``user`` and ``assistant`` turns. User content blocks: ``text``,\nbase64 ``image`` and ``tool_result``. Assistant content blocks:\n``text``, ``tool_use``, and ``thinking`` / ``redacted_thinking``,\nwhich are accepted and do not reach the model. ``role: \"system\"``\nturns are refused; system text belongs in ``system``. The last turn\nmust be a user turn."+ },+ "metadata": {+ "description": "Accepted and ignored (``user_id`` only)."+ },+ "model": {+ "description": "The model id, used as on ``/v1/chat/completions`` (``model`` or\n``model:profile``, or an operator alias).",+ "type": "string"+ },+ "output_config": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/EmptyOutputConfig",+ "description": "Accepted only empty: every field in it is refused, ``effort`` with\n``output_config.effort: Extra inputs are not permitted``."+ }+ ]+ },+ "stop_sequences": {+ "items": {+ "type": "string"+ },+ "type": [+ "array",+ "null"+ ]+ },+ "stream": {+ "description": "Server-sent events: ``message_start``, content block events,\n``message_delta`` with the final usage, ``message_stop``, and ``ping``\nwhenever no other event was sent for 10 seconds. A failure after the\nstream opened is an ``error`` event, and the stream then ends without\n``message_stop``.",+ "type": [+ "boolean",+ "null"+ ]+ },+ "system": {+ "description": "A string or a list of ``text`` blocks, concatenated in order."+ },+ "temperature": {+ "description": "In ``[0, 1]``.",+ "format": "double",+ "type": [+ "number",+ "null"+ ]+ },+ "thinking": {+ "description": "``enabled`` and ``adaptive`` return the model's reasoning as\n``thinking`` blocks; ``disabled``, ``display: \"omitted\"`` or an absent\nfield do not. Whether the model reasons is a property of its serving\nprofile, and ``budget_tokens`` is validated but does not bound\nreasoning."+ },+ "tool_choice": {+ "description": "``auto``, ``any``, ``tool`` (with ``name``) or ``none``, with\n``disable_parallel_tool_use``."+ },+ "tools": {+ "description": "Custom tools (``name``, ``description``, ``input_schema``), at most\n64, names matching ``^[a-zA-Z0-9_-]{1,64}$``. Anthropic-defined tool\ntypes are refused."+ },+ "top_k": {+ "description": "At least 1.",+ "format": "int32",+ "minimum": 1,+ "type": [+ "integer",+ "null"+ ]+ },+ "top_p": {+ "description": "In ``(0, 1]``.",+ "format": "double",+ "type": [+ "number",+ "null"+ ]+ }+ },+ "required": [+ "model",+ "max_tokens",+ "messages"+ ],+ "type": "object"+ },+ "MessagesResponse": {+ "description": "Anthropic Message answered by ``POST /v1/messages`` without ``stream``.",+ "properties": {+ "content": {+ "description": "``thinking`` (when requested and produced), then ``text``, then one\n``tool_use`` per tool call. ``thinking.signature`` is an opaque\nconstant that SIE does not verify."+ },+ "id": {+ "description": "``msg_`` followed by the gateway request id.",+ "type": "string"+ },+ "model": {+ "type": "string"+ },+ "role": {+ "description": "Always ``assistant``.",+ "type": "string"+ },+ "stop_reason": {+ "description": "``end_turn``, ``tool_use``, ``max_tokens`` or ``refusal``.",+ "type": "string"+ },+ "stop_sequence": {+ "description": "Always ``null``.",+ "type": [+ "string",+ "null"+ ]+ },+ "type": {+ "description": "Always ``message``.",+ "type": "string"+ },+ "usage": {+ "$ref": "#/components/schemas/MessagesUsage"+ }+ },+ "required": [+ "id",+ "type",+ "role",+ "model",+ "content",+ "stop_reason",+ "usage"+ ],+ "type": "object"+ },+ "MessagesUsage": {+ "description": "Token usage of a Message. ``input_tokens`` plus\n``cache_read_input_tokens`` equals the prompt tokens the chat route\nreports; ``cache_creation_input_tokens`` is always 0.",+ "properties": {+ "cache_creation_input_tokens": {+ "format": "int64",+ "minimum": 0,+ "type": "integer"+ },+ "cache_read_input_tokens": {+ "format": "int64",+ "minimum": 0,+ "type": "integer"+ },+ "input_tokens": {+ "format": "int64",+ "minimum": 0,+ "type": "integer"+ },+ "output_tokens": {+ "description": "Includes reasoning tokens.",+ "format": "int64",+ "minimum": 0,+ "type": "integer"+ }+ },+ "required": [+ "input_tokens",+ "cache_creation_input_tokens",+ "cache_read_input_tokens",+ "output_tokens"+ ],+ "type": "object"+ },"ModelAckBundleStatus": {"properties": {"acked": {@@ -6974,6 +7193,337 @@"x-sie-axum-catch-all": "/v1/generate/{*model}"}},+ "/v1/messages": {+ "post": {+ "description": "Anthropic Messages API. The request is translated into a /v1/chat/completions request, served by the chat route with all of its limits, and the answer is translated back. Buffered and streaming answers are supported. POST /v1/messages/count_tokens is not served.",+ "operationId": "proxy_messages",+ "parameters": [+ {+ "description": "Absent or 2023-06-01",+ "in": "header",+ "name": "anthropic-version",+ "required": false,+ "schema": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ {+ "description": "Accepted and ignored",+ "in": "header",+ "name": "anthropic-beta",+ "required": false,+ "schema": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ {+ "description": "Preferred GPU or machine profile",+ "in": "header",+ "name": "X-SIE-MACHINE-PROFILE",+ "required": false,+ "schema": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ {+ "description": "Explicit pool routing override",+ "in": "header",+ "name": "X-SIE-Pool",+ "required": false,+ "schema": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ {+ "description": "Require local serving through a current worker execution fence. A selected remote profile returns 400; no verified local worker returns retryable 503. Duplicate or other values return 400.",+ "in": "header",+ "name": "X-SIE-Remote",+ "required": false,+ "schema": {+ "enum": [+ "forbid"+ ],+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/MessagesRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/MessagesResponse"+ }+ }+ },+ "description": "Message, or a text/event-stream of Messages events when stream is true",+ "headers": {+ "X-Inference-Time": {+ "description": "Worker-reported inference time in milliseconds",+ "schema": {+ "type": "string"+ }+ },+ "X-Payload-Fetch-Time": {+ "description": "Worker-reported offloaded payload fetch time in milliseconds, when available",+ "schema": {+ "type": "string"+ }+ },+ "X-Postprocessing-Time": {+ "description": "Worker-reported postprocessing time in milliseconds, when available",+ "schema": {+ "type": "string"+ }+ },+ "X-Queue-Publish-Time": {+ "description": "Milliseconds spent publishing work to the queue",+ "schema": {+ "type": "string"+ }+ },+ "X-Queue-Time": {+ "description": "Worker-reported queue time in milliseconds",+ "schema": {+ "type": "string"+ }+ },+ "X-Queue-Wait-Time": {+ "description": "Milliseconds spent waiting for worker results",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Execution-Binding-SHA256": {+ "description": "Worker-origin runtime-independent SHA-256 binding of the release and deployment route, when available on buffered responses. SSE carries optional execution evidence in the successful terminal event instead of headers.",+ "schema": {+ "pattern": "^[0-9a-f]{64}$",+ "type": "string"+ }+ },+ "X-SIE-Execution-Identity-SHA256": {+ "description": "Worker-origin SHA-256 identity of the immutable release and realized serving resources, when available on buffered responses. SSE carries optional execution evidence in the successful terminal event instead of headers.",+ "schema": {+ "pattern": "^[0-9a-f]{64}$",+ "type": "string"+ }+ },+ "X-SIE-Model-Revision": {+ "description": "Executed bundle/config SHA-256, distinct from the catalog weights revision (for example, a 40-hex Hugging Face commit). Buffered responses only: present when the routing snapshot has a model revision and all successful worker results report its expected config hash. Omitted when evidence is unavailable or mismatched, and always omitted on SSE because headers precede terminal execution evidence.",+ "schema": {+ "pattern": "^[0-9a-f]{64}$",+ "type": "string"+ }+ },+ "X-SIE-Request-Id": {+ "description": "Gateway request id for queue-backed inference",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Worker": {+ "description": "Logical queue worker tag that produced the response",+ "schema": {+ "type": "string"+ }+ },+ "X-Tokenization-Time": {+ "description": "Worker-reported tokenization time in milliseconds, when available",+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "400": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AnthropicErrorEnvelope"+ }+ }+ },+ "description": "Invalid or unsupported request"+ },+ "401": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AnthropicErrorEnvelope"+ }+ }+ },+ "description": "Missing or invalid bearer token"+ },+ "404": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AnthropicErrorEnvelope"+ }+ }+ },+ "description": "Model not found"+ },+ "413": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AnthropicErrorEnvelope"+ }+ }+ },+ "description": "Request body is too large"+ },+ "429": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AnthropicErrorEnvelope"+ }+ }+ },+ "description": "Rate limited; retry after Retry-After"+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "oneOf": [+ {+ "$ref": "#/components/schemas/AnthropicErrorEnvelope"+ },+ {+ "$ref": "#/components/schemas/StandardApiError"+ }+ ]+ }+ }+ },+ "description": "Worker emitted a malformed response; gateway auth enabled but no tokens configured"+ },+ "502": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AnthropicErrorEnvelope"+ }+ }+ },+ "description": "The model failed to load",+ "headers": {+ "X-SIE-Error-Code": {+ "description": "SDK-stable gateway or worker error code",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Error-Version": {+ "description": "Gateway package version associated with the error envelope",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "503": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AnthropicErrorEnvelope"+ }+ }+ },+ "description": "Capacity is not ready; retry after Retry-After",+ "headers": {+ "Retry-After": {+ "description": "Suggested retry delay in seconds, when retryable",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Error-Code": {+ "description": "SDK-stable gateway or worker error code",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Server-Version": {+ "description": "Gateway-compatible server version advertised by this gateway",+ "schema": {+ "type": "string"+ }+ },+ "X-SIE-Version": {+ "description": "Gateway package version that handled the request",+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "504": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AnthropicErrorEnvelope"+ }+ }+ },+ "description": "Generation timed out"+ }+ },+ "tags": [+ "inference"+ ]+ }+ },"/v1/models": {"get": {"operationId": "get_models",diff --git a/packages/sie_gateway/src/handlers/messages.rs b/packages/sie_gateway/src/handlers/messages.rsnew file mode 100644index 000000000..0dc004634--- /dev/null+++ b/packages/sie_gateway/src/handlers/messages.rs@@ -0,0 +1,219 @@+//! `POST /v1/messages`: the Anthropic Messages API as a translation onto+//! `/v1/chat/completions`.+//!+//! The request is validated and translated into a chat completions body+//! ([`request`]), the gateway's own chat handler serves it in process on the+//! same task, and its answer is translated back: a chat completion into a+//! Message ([`response`]), chat SSE chunks into Messages events ([`stream`]),+//! and every error into the Anthropic envelope ([`error`]). Every chat gate,+//! limit, timeout and metering point therefore applies unchanged.++mod error;+mod request;+mod response;+pub mod schema;+mod stream;+#[cfg(test)]+mod tests;++use std::sync::Arc;++use axum::body::{to_bytes, Body};+use axum::extract::{Request, State};+use axum::http::{header, HeaderName, HeaderValue, Method, StatusCode};+use axum::response::{IntoResponse, Response};+use serde_json::Value;++pub use error::anthropic_error_envelope;++use crate::handlers::proxy::{+ buffer_compat_response_body, chat_completions_dispatch_inputs, is_length_limit_error,+ is_openai_compat_inner_request_header, proxy_chat, CompatResponseBody, MAX_JSON_BODY_BYTES,+};+use crate::http_error::GatewayOwnedFault;+use crate::queue::publisher;+use crate::server::AppState;++use self::error::{anthropic_error_response, ErrorContext, MessagesError};++/// The request body bound, the same as `/v1/chat/completions`.+const MAX_MESSAGES_BODY: usize = MAX_JSON_BODY_BYTES;++fn request_id(response: &Response) -> String {+ response+ .headers()+ .get("x-sie-request-id")+ .and_then(|value| value.to_str().ok())+ .unwrap_or_default()+ .to_string()+}++fn stamp_request_id(response: &mut Response, request_id: &str) {+ if let Ok(value) = HeaderValue::from_str(request_id) {+ if !request_id.is_empty() {+ response+ .headers_mut()+ .insert(HeaderName::from_static("request-id"), value);+ }+ }+}++#[utoipa::path(+ post,+ path = "/v1/messages",+ tag = "inference",+ description = "Anthropic Messages API. The request is translated into a \+ /v1/chat/completions request, served by the chat route with all of its \+ limits, and the answer is translated back. Buffered and streaming answers \+ are supported. POST /v1/messages/count_tokens is not served.",+ request_body = crate::handlers::messages::schema::MessagesRequest,+ params(+ ("anthropic-version" = Option<String>, Header, description = "Absent or 2023-06-01"),+ ("anthropic-beta" = Option<String>, Header, description = "Accepted and ignored"),+ ("X-SIE-MACHINE-PROFILE" = Option<String>, Header, description = "Preferred GPU or machine profile"),+ ("X-SIE-Pool" = Option<String>, Header, description = "Explicit pool routing override")+ ),+ responses(+ (status = 200, description = "Message, or a text/event-stream of Messages events when stream is true", body = crate::handlers::messages::schema::MessagesResponse),+ (status = 400, description = "Invalid or unsupported request", body = crate::handlers::messages::schema::AnthropicErrorEnvelope),+ (status = 401, description = "Missing or invalid bearer token", body = crate::handlers::messages::schema::AnthropicErrorEnvelope),+ (status = 404, description = "Model not found", body = crate::handlers::messages::schema::AnthropicErrorEnvelope),+ (status = 413, description = "Request body is too large", body = crate::handlers::messages::schema::AnthropicErrorEnvelope),+ (status = 500, description = "Worker emitted a malformed response", body = crate::handlers::messages::schema::AnthropicErrorEnvelope),+ (status = 429, description = "Rate limited; retry after Retry-After", body = crate::handlers::messages::schema::AnthropicErrorEnvelope),+ (status = 502, description = "The model failed to load", body = crate::handlers::messages::schema::AnthropicErrorEnvelope),+ (status = 503, description = "Capacity is not ready; retry after Retry-After", body = crate::handlers::messages::schema::AnthropicErrorEnvelope),+ (status = 504, description = "Generation timed out", body = crate::handlers::messages::schema::AnthropicErrorEnvelope),+ )+)]+pub async fn proxy_messages(State(state): State<Arc<AppState>>, request: Request) -> Response {+ let headers = request.headers().clone();+ let (parts, body) = request.into_parts();+ let bytes = match to_bytes(body, MAX_MESSAGES_BODY).await {+ Ok(bytes) => bytes,+ Err(error) if is_length_limit_error(&error) => {+ return MessagesError::new(+ StatusCode::PAYLOAD_TOO_LARGE,+ format!("request body is larger than {MAX_MESSAGES_BODY} bytes"),+ )+ .into_response();+ }+ Err(_) => return MessagesError::invalid("failed to read the request body").into_response(),+ };+ let body: Value = match serde_json::from_slice(&bytes) {+ Ok(body) => body,+ Err(error) => {+ return MessagesError::invalid(format!("body: invalid JSON: {error}")).into_response()+ }+ };+ let version = match headers.get("anthropic-version") {+ None => None,+ Some(value) => Some(value.to_str().unwrap_or("")),+ };+ let translation = match request::messages_to_chat(&body, version) {+ Ok(translation) => translation,+ Err(error) => return error.into_response(),+ };+ let context = ErrorContext {+ first_image: translation.first_image.clone(),+ };+ let chat_bytes = match serde_json::to_vec(&translation.chat) {+ Ok(bytes) => bytes,+ Err(_) => {+ return MessagesError::new(+ StatusCode::INTERNAL_SERVER_ERROR,+ "failed to build the chat request",+ )+ .into_response()+ }+ };+ let mut builder = Request::builder()+ .method(Method::POST)+ .uri("/v1/chat/completions")+ .version(parts.version);+ for (name, value) in headers.iter() {+ if is_openai_compat_inner_request_header(name.as_str()) {+ builder = builder.header(name, value);+ }+ }+ builder = builder.header(header::CONTENT_TYPE, "application/json");+ let mut inner = match builder.body(Body::from(chat_bytes)) {+ Ok(inner) => inner,+ Err(_) => {+ return MessagesError::new(+ StatusCode::INTERNAL_SERVER_ERROR,+ "failed to build the chat request",+ )+ .into_response()+ }+ };+ *inner.extensions_mut() = parts.extensions;++ let answer = proxy_chat(State(state), inner).await;+ if !answer.status().is_success() {+ return anthropic_error_response(answer, &context).await;+ }+ let request_id = request_id(&answer);+ let message_id = format!("msg_{request_id}");+ if translation.stream {+ let (mut parts, body) = answer.into_parts();+ parts.headers.remove(header::CONTENT_LENGTH);+ let machine = stream::StreamMachine::new(message_id, translation.model);+ let mut response = Response::from_parts(+ parts,+ stream::stream_body(body, machine, stream::PING_INTERVAL),+ );+ stamp_request_id(&mut response, &request_id);+ return response;+ }+ buffered_message(answer, &translation.model, &request_id).await+}++fn translation_fault(stage: &'static str, message: &str) -> Response {+ GatewayOwnedFault::new(stage)+ .mark(MessagesError::new(StatusCode::INTERNAL_SERVER_ERROR, message).into_response())+}++async fn buffered_message(answer: Response, model: &str, request_id: &str) -> Response {+ let (parts, body) = answer.into_parts();+ let bytes = match buffer_compat_response_body(body).await {+ CompatResponseBody::Buffered(bytes) => bytes,+ CompatResponseBody::TooLarge { .. } | CompatResponseBody::Unreadable => {+ return translation_fault("read_chat_response", "failed to read the chat completion")+ }+ };+ let message = serde_json::from_slice::<Value>(&bytes)+ .map_err(|_| "the chat completion is not valid JSON".to_string())+ .and_then(|chat| response::chat_completion_to_message(&chat, model, request_id));+ let message = match message {+ Ok(message) => message,+ Err(reason) => return translation_fault("translate_chat_response", &reason),+ };+ let mut response = (StatusCode::OK, axum::Json(message)).into_response();+ for (name, value) in parts.headers.iter() {+ if crate::handlers::proxy::is_openai_compat_forwarded_header(name.as_str()) {+ response.headers_mut().insert(name.clone(), value.clone());+ }+ }+ *response.extensions_mut() = parts.extensions;+ stamp_request_id(&mut response, request_id);+ response+}++/// The `(model, WorkParams)` a `/v1/messages` body dispatches with: the+/// translation composed with the chat seam, so an estimate or an admission+/// check prices and admits exactly what the chat route would run.+///+/// A translation refusal is answered in the Anthropic envelope; a chat+/// refusal keeps the chat envelope, which [`anthropic_error_envelope`]+/// re-renders on the way out.+///+/// `dead_code`-allowed because the `sie-gateway` binary compiles this module+/// tree independently of the library, and only a downstream composition+/// calls this seam.+#[allow(clippy::result_large_err, dead_code)]+pub fn messages_dispatch_inputs(body: &Value) -> Result<(String, publisher::WorkParams), Response> {+ let translation =+ request::messages_to_chat(body, None).map_err(MessagesError::into_response)?;+ chat_completions_dispatch_inputs(&translation.chat)+}diff --git a/packages/sie_gateway/src/handlers/messages/error.rs b/packages/sie_gateway/src/handlers/messages/error.rsnew file mode 100644index 000000000..bba04e4c5--- /dev/null+++ b/packages/sie_gateway/src/handlers/messages/error.rs@@ -0,0 +1,364 @@+//! The Anthropic error envelope for `/v1/messages`.+//!+//! Every non-2xx answer on the Messages paths leaves the gateway as+//! `{"type":"error","error":{"type","message"},"request_id"}` with the status+//! the inner route chose. The error type follows the status. `Retry-After`+//! is kept and capped at [`MAX_RETRY_AFTER_S`], the longest wait Anthropic+//! clients keep retrying through.++use axum::body::{to_bytes, Body};+use axum::extract::Request;+use axum::http::{header, HeaderMap, HeaderName, HeaderValue, StatusCode};+use axum::middleware::Next;+use axum::response::{IntoResponse, Response};+use serde_json::{json, Value};++use crate::handlers::proxy::is_openai_compat_forwarded_header;++pub(crate) const MAX_RETRY_AFTER_S: u64 = 60;++const MAX_ERROR_BODY: usize = 1024 * 1024;++/// An error decided in Anthropic terms: the status and the client-facing+/// message.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct MessagesError {+ pub status: StatusCode,+ pub message: String,+}++impl MessagesError {+ pub(crate) fn invalid(message: impl Into<String>) -> Self {+ Self {+ status: StatusCode::BAD_REQUEST,+ message: message.into(),+ }+ }++ pub(crate) fn new(status: StatusCode, message: impl Into<String>) -> Self {+ Self {+ status,+ message: message.into(),+ }+ }++ pub(crate) fn into_response(self) -> Response {+ let mut response = (+ self.status,+ axum::Json(envelope(+ error_type_for_status(self.status),+ &self.message,+ None,+ )),+ )+ .into_response();+ response.headers_mut().insert(+ HeaderName::from_static("x-sie-error-code"),+ HeaderValue::from_static(sie_code_for_status(self.status)),+ );+ response+ }+}++/// What the Messages handler knows about the request that the chat route's+/// error cannot say in Anthropic terms.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub(crate) struct ErrorContext {+ /// The Anthropic path of the first image block, named when the model+ /// refuses image input.+ pub first_image: Option<String>,+}++/// The Anthropic `error.type` for an HTTP status.+pub(crate) fn error_type_for_status(status: StatusCode) -> &'static str {+ match status.as_u16() {+ 401 => "authentication_error",+ 402 => "billing_error",+ 403 => "permission_error",+ 404 => "not_found_error",+ 408 | 504 => "timeout_error",+ 413 => "request_too_large",+ 429 => "rate_limit_error",+ 503 | 529 => "overloaded_error",+ 400..=499 => "invalid_request_error",+ _ => "api_error",+ }+}++fn sie_code_for_status(status: StatusCode) -> &'static str {+ match status.as_u16() {+ 401 => "UNAUTHORIZED",+ 403 => "FORBIDDEN",+ 404 => "NOT_FOUND",+ 413 => "PAYLOAD_TOO_LARGE",+ 400..=499 => "INVALID_REQUEST",+ _ => "INTERNAL_SERVER_ERROR",+ }+}++fn default_message(status: StatusCode) -> &'static str {+ match status.as_u16() {+ 400 => "invalid request",+ 401 => "invalid or missing credential",+ 402 => "payment required",+ 403 => "permission denied",+ 404 => "not found",+ 405 => "method not allowed",+ 408 | 504 => "request timed out",+ 413 => "request too large",+ 429 => "rate limited",+ 503 | 529 => "overloaded",+ _ => "internal server error",+ }+}++pub(crate) fn envelope(error_type: &str, message: &str, request_id: Option<&str>) -> Value {+ json!({+ "type": "error",+ "error": {"type": error_type, "message": message},+ "request_id": request_id,+ })+}++/// The `(type, message, SIE code)` an inner error answer becomes.+///+/// `body` is the inner answer as JSON: the OpenAI `{error}` envelope, the+/// SIE `{detail}` envelope, or anything else. Messages are rewritten only+/// where Anthropic clients match the wording: the output cap, a prompt that+/// does not fit, and media the model cannot read.+pub(crate) fn translate_error_body(+ status: StatusCode,+ body: &Value,+ context: &ErrorContext,+) -> (&'static str, String, Option<String>) {+ let error_type = error_type_for_status(status);+ let inner = body+ .get("error")+ .filter(|value| value.is_object())+ .or_else(|| body.get("detail").filter(|value| value.is_object()));+ let code = inner+ .and_then(|value| value.get("code"))+ .and_then(Value::as_str)+ .map(str::to_string);+ let inner_type = inner+ .and_then(|value| value.get("type"))+ .and_then(Value::as_str);+ let param = inner+ .and_then(|value| value.get("param"))+ .and_then(Value::as_str);+ let message = inner+ .and_then(|value| value.get("message"))+ .and_then(Value::as_str)+ .or_else(|| body.get("detail").and_then(Value::as_str))+ .or_else(|| body.get("message").and_then(Value::as_str))+ .filter(|message| !message.is_empty())+ .unwrap_or_else(|| default_message(status))+ .to_string();+ if status != StatusCode::BAD_REQUEST {+ return (error_type, message, code);+ }+ if let Some((requested, cap)) = output_cap(&message) {+ return (+ error_type,+ format!(+ "max_tokens: {requested} > {cap}, which is the maximum allowed number of output tokens for this model"+ ),+ code,+ );+ }+ let too_long = matches!(code.as_deref(), Some("context_exceeded" | "INPUT_TOO_LONG"))+ || inner_type == Some("context_length_exceeded");+ if too_long {+ let message = match prompt_size(&message) {+ Some((tokens, limit)) => {+ format!("prompt is too long: {tokens} tokens > {limit} maximum")+ }+ None => "prompt is too long".to_string(),+ };+ return (error_type, message, code);+ }+ if message.contains("does not support image input") {+ if let Some(path) = context.first_image.as_deref() {+ return (error_type, format!("{path}: {message}"), code);+ }+ }+ if message.contains("does not support tool calling") {+ return (error_type, format!("tools: {message}"), code);+ }+ let message = message.replace("max_completion_tokens", "max_tokens");+ match param.map(anthropic_param) {+ Some(path) if !message.starts_with(&format!("{path}:")) => {+ (error_type, format!("{path}: {message}"), code)+ }+ _ => (error_type, message, code),+ }+}++fn anthropic_param(param: &str) -> String {+ if param == "max_completion_tokens" {+ return "max_tokens".to_string();+ }+ if param == "stop" {+ return "stop_sequences".to_string();+ }+ if let Some(rest) = param.strip_prefix("tools[") {+ if let Some((index, field)) = rest.split_once("].function.") {+ let field = if field == "parameters" {+ "input_schema"+ } else {+ field+ };+ return format!("tools.{index}.{field}");+ }+ }+ param.to_string()+}++fn leading_number(text: &str) -> Option<(u64, &str)> {+ let end = text+ .find(|c: char| !c.is_ascii_digit())+ .unwrap_or(text.len());+ if end == 0 {+ return None;+ }+ Some((text[..end].parse().ok()?, &text[end..]))+}++/// `(requested, cap)` from the chat route's or the worker's output-cap refusal.+fn output_cap(message: &str) -> Option<(u64, u64)> {+ for prefix in [+ "max_completion_tokens (",+ "max_tokens (",+ "max_new_tokens (",+ ] {+ let Some(rest) = message.strip_prefix(prefix) else {+ continue;+ };+ let (requested, rest) = leading_number(rest)?;+ let rest = rest+ .strip_prefix(") exceeds model max_output_tokens (")+ .or_else(|| rest.strip_prefix(") exceeds model cap ("))?;+ let (cap, rest) = leading_number(rest)?;+ return (rest == ")").then_some((requested, cap));+ }+ None+}++/// `(tokens, limit)` from a worker's `... = T exceeds context_length (C) ...`+/// or `prompt_tokens (T) exceeds context_length (C) ...`.+fn prompt_size(message: &str) -> Option<(u64, u64)> {+ let (before, after) = message.split_once(" exceeds context_length (")?;+ let (limit, _) = leading_number(after)?;+ let tokens = match before.rsplit_once("= ") {+ Some((_, total)) => leading_number(total)?.0,+ None => {+ let open = before.strip_prefix("prompt_tokens (")?;+ leading_number(open)?.0+ }+ };+ Some((tokens, limit))+}++fn clamp_retry_after(headers: &mut HeaderMap) {+ let Some(value) = headers.get(header::RETRY_AFTER) else {+ return;+ };+ let clamped = value+ .to_str()+ .ok()+ .and_then(|value| value.trim().parse::<u64>().ok())+ .map(|seconds| seconds.clamp(1, MAX_RETRY_AFTER_S));+ match clamped {+ Some(seconds) => {+ headers.insert(header::RETRY_AFTER, HeaderValue::from(seconds));+ headers.insert(+ HeaderName::from_static("x-should-retry"),+ HeaderValue::from_static("true"),+ );+ }+ None => {+ headers.remove(header::RETRY_AFTER);+ }+ }+}++fn is_anthropic_envelope(body: &Value) -> bool {+ body.get("type").and_then(Value::as_str) == Some("error")+ && body+ .get("error")+ .and_then(|error| error.get("type"))+ .and_then(Value::as_str)+ .is_some()+}++/// Re-render a non-2xx answer in the Anthropic envelope, keeping the status,+/// the response extensions, `Retry-After` and the SIE headers.+pub(crate) async fn anthropic_error_response(+ response: Response,+ context: &ErrorContext,+) -> Response {+ let (mut parts, body) = response.into_parts();+ let bytes = to_bytes(body, MAX_ERROR_BODY).await.unwrap_or_default();+ let parsed: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);+ let request_id = parts+ .headers+ .get("x-sie-request-id")+ .and_then(|value| value.to_str().ok())+ .filter(|value| !value.is_empty())+ .map(str::to_string);+ let mut headers = HeaderMap::new();+ for (name, value) in parts.headers.iter() {+ let name_str = name.as_str();+ if is_openai_compat_forwarded_header(name_str)+ || name_str.eq_ignore_ascii_case("x-sie-error-code")+ || name_str.eq_ignore_ascii_case("x-sie-error-version")+ || name_str.eq_ignore_ascii_case("retry-after")+ || name_str.eq_ignore_ascii_case("www-authenticate")+ {+ headers.append(name.clone(), value.clone());+ }+ }+ let body = if is_anthropic_envelope(&parsed) {+ bytes.to_vec()+ } else {+ let (error_type, message, code) = translate_error_body(parts.status, &parsed, context);+ if !headers.contains_key("x-sie-error-code") {+ if let Some(value) = code.and_then(|code| HeaderValue::from_str(&code).ok()) {+ headers.insert(HeaderName::from_static("x-sie-error-code"), value);+ }+ }+ serde_json::to_vec(&envelope(error_type, &message, request_id.as_deref()))+ .unwrap_or_default()+ };+ clamp_retry_after(&mut headers);+ headers.insert(+ header::CONTENT_TYPE,+ HeaderValue::from_static("application/json"),+ );+ if let Some(value) = request_id.and_then(|id| HeaderValue::from_str(&id).ok()) {+ headers.insert(HeaderName::from_static("request-id"), value);+ }+ parts.headers = headers;+ Response::from_parts(parts, Body::from(body))+}++pub(crate) fn is_messages_path(path: &str) -> bool {+ path == "/v1/messages" || path.starts_with("/v1/messages/")+}++/// Middleware that gives every error answer on `/v1/messages` and the paths+/// below it the Anthropic envelope.+///+/// Compositions that add admission layers around the gateway's routes apply+/// it outermost (`axum::middleware::from_fn(anthropic_error_envelope)`), so+/// their refusals take the same shape. Already-Anthropic bodies pass through+/// with `Retry-After` capped.+pub async fn anthropic_error_envelope(request: Request, next: Next) -> Response {+ let applies = is_messages_path(request.uri().path());+ let response = next.run(request).await;+ let status = response.status();+ if !applies || !(status.is_client_error() || status.is_server_error()) {+ return response;+ }+ anthropic_error_response(response, &ErrorContext::default()).await+}diff --git a/packages/sie_gateway/src/handlers/messages/request.rs b/packages/sie_gateway/src/handlers/messages/request.rsnew file mode 100644index 000000000..07d179ab7--- /dev/null+++ b/packages/sie_gateway/src/handlers/messages/request.rs@@ -0,0 +1,929 @@+//! Request translation: an Anthropic Messages body into a chat completions+//! body.+//!+//! Validation happens here, in Anthropic terms, so a refusal names the field+//! the caller sent. Unknown fields fail with `<path>: Extra inputs are not+//! permitted`. The accepted-but-inert set is `metadata`, `cache_control` in+//! every position, `thinking.display: "summarized"` and the tool flag+//! `eager_input_streaming`.++use serde_json::{json, Map, Value};++use super::error::MessagesError;+use crate::handlers::grammar::{parse_grammar, GrammarParseResult};++pub(crate) const SUPPORTED_ANTHROPIC_VERSION: &str = "2023-06-01";+pub(crate) const MAX_TOOLS: usize = 64;+const MAX_TOOL_NAME_LEN: usize = 64;+const MAX_USER_ID_CHARS: usize = 512;+const MIN_THINKING_BUDGET: u64 = 1024;+const IMAGE_MEDIA_TYPES: [&str; 4] = ["image/jpeg", "image/png", "image/gif", "image/webp"];++pub(crate) const SYSTEM_TURN_REFUSAL: &str =+ "role \"system\" is not supported in messages; use the top-level system parameter";+pub(crate) const CONTEXT_MANAGEMENT_REFUSAL: &str = "context_management: Extra inputs are not permitted (Claude Code: set CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1)";++/// A translated request.+#[derive(Debug, Clone, PartialEq)]+pub(crate) struct ChatTranslation {+ pub chat: Value,+ pub model: String,+ pub stream: bool,+ /// Anthropic path of the first image block, named if the model refuses+ /// image input.+ pub first_image: Option<String>,+}++fn invalid(message: impl Into<String>) -> MessagesError {+ MessagesError::invalid(message)+}++fn extra(path: &str) -> MessagesError {+ invalid(format!("{path}: Extra inputs are not permitted"))+}++fn required(path: &str) -> MessagesError {+ invalid(format!("{path}: Field required"))+}++fn object<'a>(value: &'a Value, path: &str) -> Result<&'a Map<String, Value>, MessagesError> {+ value+ .as_object()+ .ok_or_else(|| invalid(format!("{path}: Input should be a valid dictionary")))+}++fn only_keys(map: &Map<String, Value>, allowed: &[&str], path: &str) -> Result<(), MessagesError> {+ match map.keys().find(|key| !allowed.contains(&key.as_str())) {+ Some(key) => Err(extra(&format!("{path}.{key}"))),+ None => Ok(()),+ }+}++fn present<'a>(map: &'a Map<String, Value>, key: &str) -> Option<&'a Value> {+ map.get(key).filter(|value| !value.is_null())+}++fn string<'a>(+ map: &'a Map<String, Value>,+ key: &str,+ path: &str,+) -> Result<&'a str, MessagesError> {+ match map.get(key) {+ None | Some(Value::Null) => Err(required(&format!("{path}.{key}"))),+ Some(Value::String(value)) => Ok(value),+ Some(_) => Err(invalid(format!(+ "{path}.{key}: Input should be a valid string"+ ))),+ }+}++fn cache_control(map: &Map<String, Value>, path: &str) -> Result<(), MessagesError> {+ match present(map, "cache_control") {+ None | Some(Value::Object(_)) => Ok(()),+ Some(_) => Err(invalid(format!(+ "{path}.cache_control: Input should be a valid dictionary"+ ))),+ }+}++fn citations(map: &Map<String, Value>, path: &str) -> Result<(), MessagesError> {+ match present(map, "citations") {+ None => Ok(()),+ Some(Value::Array(items)) if items.is_empty() => Ok(()),+ Some(_) => Err(invalid(format!(+ "{path}.citations: citations are not supported"+ ))),+ }+}++/// Text accumulated in one turn, with image parts kept in order.+#[derive(Default)]+struct Parts {+ items: Vec<Part>,+}++enum Part {+ Text(String),+ Image(String),+}++impl Parts {+ fn text(&mut self, text: &str) {+ if text.is_empty() {+ return;+ }+ if let Some(Part::Text(last)) = self.items.last_mut() {+ last.push_str(text);+ } else {+ self.items.push(Part::Text(text.to_string()));+ }+ }++ fn image(&mut self, data_uri: String) {+ self.items.push(Part::Image(data_uri));+ }++ fn is_empty(&self) -> bool {+ self.items.is_empty()+ }++ fn into_content(self) -> Value {+ if self.items.iter().all(|part| matches!(part, Part::Text(_))) {+ let text: String = self+ .items+ .into_iter()+ .map(|part| match part {+ Part::Text(text) => text,+ Part::Image(_) => String::new(),+ })+ .collect();+ return Value::String(text);+ }+ Value::Array(+ self.items+ .into_iter()+ .map(|part| match part {+ Part::Text(text) => json!({"type": "text", "text": text}),+ Part::Image(url) => json!({"type": "image_url", "image_url": {"url": url}}),+ })+ .collect(),+ )+ }+}++/// Translate an Anthropic Messages body into a chat completions body.+///+/// `anthropic_version` is the `anthropic-version` header, absent or+/// `2023-06-01`.+pub(crate) fn messages_to_chat(+ body: &Value,+ anthropic_version: Option<&str>,+) -> Result<ChatTranslation, MessagesError> {+ if anthropic_version.is_some_and(|version| version != SUPPORTED_ANTHROPIC_VERSION) {+ return Err(invalid(format!(+ "anthropic-version: only {SUPPORTED_ANTHROPIC_VERSION} is supported"+ )));+ }+ let Some(body) = body.as_object() else {+ return Err(invalid("body: Input should be a valid dictionary"));+ };+ for key in body.keys() {+ match key.as_str() {+ "model" | "max_tokens" | "messages" | "system" | "stop_sequences" | "temperature"+ | "top_p" | "top_k" | "stream" | "tools" | "tool_choice" | "thinking" | "metadata"+ | "cache_control" => {}+ "output_config" => output_config(body.get(key).unwrap_or(&Value::Null))?,+ "context_management" => return Err(invalid(CONTEXT_MANAGEMENT_REFUSAL)),+ other => return Err(extra(other)),+ }+ }++ let model = match body.get("model") {+ None | Some(Value::Null) => return Err(required("model")),+ Some(Value::String(model)) if !model.is_empty() => model.clone(),+ Some(Value::String(_)) => {+ return Err(invalid("model: String should have at least 1 character"))+ }+ Some(_) => return Err(invalid("model: Input should be a valid string")),+ };+ let max_tokens = match body.get("max_tokens") {+ None | Some(Value::Null) => return Err(required("max_tokens")),+ Some(value) => match value.as_u64() {+ Some(0) => {+ return Err(invalid(+ "max_tokens: Input should be greater than or equal to 1",+ ))+ }+ Some(tokens) if tokens <= u64::from(u32::MAX) => tokens,+ _ if value.as_i64().is_some_and(|tokens| tokens < 1) => {+ return Err(invalid(+ "max_tokens: Input should be greater than or equal to 1",+ ))+ }+ _ => return Err(invalid("max_tokens: Input should be a valid integer")),+ },+ };+ let stream = match body.get("stream") {+ None | Some(Value::Null) => false,+ Some(Value::Bool(stream)) => *stream,+ Some(_) => return Err(invalid("stream: Input should be a valid boolean")),+ };+ let temperature = bounded_number(body, "temperature", 0.0, true)?;+ let top_p = bounded_number(body, "top_p", 0.0, false)?;+ let top_k = match present(body, "top_k") {+ None => None,+ Some(value) => match value.as_u64() {+ Some(k) if (1..=u64::from(u32::MAX)).contains(&k) => Some(k),+ Some(_) => return Err(invalid("top_k: Input should be greater than or equal to 1")),+ None if value.as_i64().is_some() => {+ return Err(invalid("top_k: Input should be greater than or equal to 1"))+ }+ None => return Err(invalid("top_k: Input should be a valid integer")),+ },+ };+ let stop = stop_sequences(body)?;+ metadata(body)?;+ if let Some(value) = present(body, "cache_control") {+ if !value.is_object() {+ return Err(invalid("cache_control: Input should be a valid dictionary"));+ }+ }+ let include_reasoning = thinking(body, max_tokens)?;+ let (tools, tool_names) = tools(body)?;+ let (tool_choice, parallel_tool_calls) = tool_choice(body, &tool_names)?;++ let mut first_image = None;+ let mut chat_messages = Vec::new();+ if let Some(system) = system(body)? {+ chat_messages.push(json!({"role": "system", "content": system}));+ }+ let messages = match body.get("messages") {+ None | Some(Value::Null) => return Err(required("messages")),+ Some(Value::Array(messages)) if messages.is_empty() => {+ return Err(invalid("messages: List should have at least 1 item"))+ }+ Some(Value::Array(messages)) => messages,+ Some(_) => return Err(invalid("messages: Input should be a valid list")),+ };+ for (index, message) in messages.iter().enumerate() {+ translate_message(message, index, &mut chat_messages, &mut first_image)?;+ }+ if messages+ .last()+ .and_then(|message| message.get("role"))+ .and_then(Value::as_str)+ == Some("assistant")+ {+ return Err(invalid(+ "messages: assistant message prefill is not supported; the conversation must end with a user message",+ ));+ }++ let mut chat = Map::new();+ chat.insert("model".into(), json!(model));+ chat.insert("messages".into(), Value::Array(chat_messages));+ chat.insert("max_tokens".into(), json!(max_tokens));+ if let Some(stop) = stop {+ chat.insert("stop".into(), json!(stop));+ }+ if let Some(temperature) = temperature {+ chat.insert("temperature".into(), temperature);+ }+ if let Some(top_p) = top_p {+ chat.insert("top_p".into(), top_p);+ }+ if let Some(top_k) = top_k {+ chat.insert("top_k".into(), json!(top_k));+ }+ chat.insert("stream".into(), json!(stream));+ if stream {+ chat.insert("stream_options".into(), json!({"include_usage": true}));+ }+ if let Some(tools) = tools {+ chat.insert("tools".into(), Value::Array(tools));+ }+ if let Some(tool_choice) = tool_choice {+ chat.insert("tool_choice".into(), tool_choice);+ }+ if let Some(parallel) = parallel_tool_calls {+ chat.insert("parallel_tool_calls".into(), json!(parallel));+ }+ chat.insert("include_reasoning".into(), json!(include_reasoning));+ Ok(ChatTranslation {+ chat: Value::Object(chat),+ model,+ stream,+ first_image,+ })+}++fn output_config(value: &Value) -> Result<(), MessagesError> {+ if value.is_null() {+ return Ok(());+ }+ match object(value, "output_config")?.keys().next() {+ Some(key) => Err(extra(&format!("output_config.{key}"))),+ None => Ok(()),+ }+}++fn bounded_number(+ body: &Map<String, Value>,+ key: &str,+ low: f64,+ low_inclusive: bool,+) -> Result<Option<Value>, MessagesError> {+ let Some(value) = present(body, key) else {+ return Ok(None);+ };+ let Some(number) = value.as_f64().filter(|number| number.is_finite()) else {+ return Err(invalid(format!("{key}: Input should be a valid number")));+ };+ if low_inclusive && number < low {+ return Err(invalid(format!(+ "{key}: Input should be greater than or equal to {low}"+ )));+ }+ if !low_inclusive && number <= low {+ return Err(invalid(format!(+ "{key}: Input should be greater than {low}"+ )));+ }+ if number > 1.0 {+ return Err(invalid(format!(+ "{key}: Input should be less than or equal to 1"+ )));+ }+ Ok(Some(value.clone()))+}++fn stop_sequences(body: &Map<String, Value>) -> Result<Option<Vec<String>>, MessagesError> {+ let Some(value) = present(body, "stop_sequences") else {+ return Ok(None);+ };+ let Some(items) = value.as_array() else {+ return Err(invalid("stop_sequences: Input should be a valid list"));+ };+ let mut stop = Vec::with_capacity(items.len());+ for (index, item) in items.iter().enumerate() {+ match item.as_str() {+ Some(sequence) => stop.push(sequence.to_string()),+ None => {+ return Err(invalid(format!(+ "stop_sequences.{index}: Input should be a valid string"+ )))+ }+ }+ }+ Ok((!stop.is_empty()).then_some(stop))+}++fn metadata(body: &Map<String, Value>) -> Result<(), MessagesError> {+ let Some(value) = present(body, "metadata") else {+ return Ok(());+ };+ let metadata = object(value, "metadata")?;+ only_keys(metadata, &["user_id"], "metadata")?;+ match present(metadata, "user_id") {+ None => Ok(()),+ Some(Value::String(user_id)) if user_id.chars().count() <= MAX_USER_ID_CHARS => Ok(()),+ Some(Value::String(_)) => Err(invalid(format!(+ "metadata.user_id: String should have at most {MAX_USER_ID_CHARS} characters"+ ))),+ Some(_) => Err(invalid("metadata.user_id: Input should be a valid string")),+ }+}++/// Whether the request opts into public reasoning.+fn thinking(body: &Map<String, Value>, max_tokens: u64) -> Result<bool, MessagesError> {+ let Some(value) = present(body, "thinking") else {+ return Ok(false);+ };+ let thinking = object(value, "thinking")?;+ let kind = match thinking.get("type") {+ None | Some(Value::Null) => return Err(required("thinking.type")),+ Some(Value::String(kind)) => kind.as_str(),+ Some(_) => return Err(invalid("thinking.type: Input should be a valid string")),+ };+ let path = format!("thinking.{kind}");+ match kind {+ "enabled" => {+ only_keys(thinking, &["type", "budget_tokens", "display"], &path)?;+ let budget = match thinking.get("budget_tokens") {+ None | Some(Value::Null) => return Err(required(&format!("{path}.budget_tokens"))),+ Some(value) => value.as_u64().ok_or_else(|| {+ invalid(format!(+ "{path}.budget_tokens: Input should be a valid integer"+ ))+ })?,+ };+ if budget < MIN_THINKING_BUDGET {+ return Err(invalid(format!(+ "{path}.budget_tokens: Input should be greater than or equal to {MIN_THINKING_BUDGET}"+ )));+ }+ if budget >= max_tokens {+ return Err(invalid(format!(+ "{path}.budget_tokens: must be less than max_tokens"+ )));+ }+ }+ "adaptive" => only_keys(thinking, &["type", "display"], &path)?,+ "disabled" => {+ only_keys(thinking, &["type"], &path)?;+ return Ok(false);+ }+ "between_tools" => {+ return Err(invalid(+ "\"thinking.type.between_tools\" is not supported for this model.",+ ))+ }+ _ => {+ return Err(invalid(+ "thinking.type: Input should be 'enabled', 'adaptive' or 'disabled'",+ ))+ }+ }+ match present(thinking, "display") {+ None => Ok(true),+ Some(Value::String(display)) if display == "summarized" => Ok(true),+ Some(Value::String(display)) if display == "omitted" => Ok(false),+ Some(_) => Err(invalid(format!(+ "{path}.display: Input should be 'summarized' or 'omitted'"+ ))),+ }+}++fn system(body: &Map<String, Value>) -> Result<Option<String>, MessagesError> {+ let Some(value) = present(body, "system") else {+ return Ok(None);+ };+ let text = match value {+ Value::String(text) => text.clone(),+ Value::Array(blocks) => {+ let mut text = String::new();+ for (index, block) in blocks.iter().enumerate() {+ let path = format!("system.{index}");+ let block = object(block, &path)?;+ match block.get("type").and_then(Value::as_str) {+ Some("text") => {}+ None => return Err(required(&format!("{path}.type"))),+ Some(_) => return Err(invalid(format!("{path}.type: Input should be 'text'"))),+ }+ only_keys(+ block,+ &["type", "text", "cache_control", "citations"],+ &path,+ )?;+ cache_control(block, &path)?;+ citations(block, &path)?;+ text.push_str(string(block, "text", &path)?);+ }+ text+ }+ _ => return Err(invalid("system: Input should be a valid string or list")),+ };+ Ok((!text.is_empty()).then_some(text))+}++fn tools(body: &Map<String, Value>) -> Result<(Option<Vec<Value>>, Vec<String>), MessagesError> {+ let Some(value) = present(body, "tools") else {+ return Ok((None, Vec::new()));+ };+ let Some(items) = value.as_array() else {+ return Err(invalid("tools: Input should be a valid list"));+ };+ if items.len() > MAX_TOOLS {+ return Err(invalid(format!(+ "tools: at most {MAX_TOOLS} tools are supported, got {}",+ items.len()+ )));+ }+ let mut tools = Vec::with_capacity(items.len());+ let mut names = Vec::with_capacity(items.len());+ for (index, item) in items.iter().enumerate() {+ let path = format!("tools.{index}");+ let tool = object(item, &path)?;+ match tool.get("type") {+ None | Some(Value::Null) => {}+ Some(Value::String(kind)) if kind == "custom" => {}+ Some(Value::String(kind)) => {+ return Err(invalid(format!(+ "{path}.type: tool type '{kind}' is not supported; only custom tools with an input_schema are"+ )))+ }+ Some(_) => return Err(invalid(format!("{path}.type: Input should be a valid string"))),+ }+ only_keys(+ tool,+ &[+ "type",+ "name",+ "description",+ "input_schema",+ "cache_control",+ "eager_input_streaming",+ ],+ &path,+ )?;+ cache_control(tool, &path)?;+ match present(tool, "eager_input_streaming") {+ None | Some(Value::Bool(_)) => {}+ Some(_) => {+ return Err(invalid(format!(+ "{path}.eager_input_streaming: Input should be a valid boolean"+ )))+ }+ }+ let name = string(tool, "name", &path)?;+ let valid_chars = !name.is_empty()+ && name+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-');+ if valid_chars && name.len() > MAX_TOOL_NAME_LEN {+ return Err(invalid(format!(+ "{path}.name: tool names longer than {MAX_TOOL_NAME_LEN} characters are not supported"+ )));+ }+ if !valid_chars {+ return Err(invalid(format!(+ "{path}.name: String should match pattern '^[a-zA-Z0-9_-]{{1,{MAX_TOOL_NAME_LEN}}}$'"+ )));+ }+ let mut function = Map::new();+ function.insert("name".into(), json!(name));+ match present(tool, "description") {+ None => {}+ Some(Value::String(description)) => {+ function.insert("description".into(), json!(description));+ }+ Some(_) => {+ return Err(invalid(format!(+ "{path}.description: Input should be a valid string"+ )))+ }+ }+ let schema = match tool.get("input_schema") {+ None | Some(Value::Null) => return Err(required(&format!("{path}.input_schema"))),+ Some(schema @ Value::Object(_)) => schema,+ Some(_) => {+ return Err(invalid(format!(+ "{path}.input_schema: Input should be a valid dictionary"+ )))+ }+ };+ if let GrammarParseResult::Err(_) = parse_grammar(&json!({"json_schema": schema})) {+ return Err(invalid(format!(+ "{path}.input_schema: the schema uses an unsupported JSON Schema keyword (if, then, else, $dynamicRef, unevaluatedProperties, dependentSchemas) or exceeds the size or depth limits"+ )));+ }+ function.insert("parameters".into(), schema.clone());+ tools.push(json!({"type": "function", "function": Value::Object(function)}));+ names.push(name.to_string());+ }+ if tools.is_empty() {+ return Ok((None, names));+ }+ Ok((Some(tools), names))+}++fn tool_choice(+ body: &Map<String, Value>,+ tool_names: &[String],+) -> Result<(Option<Value>, Option<bool>), MessagesError> {+ let Some(value) = present(body, "tool_choice") else {+ return Ok((None, None));+ };+ let choice = object(value, "tool_choice")?;+ let kind = match choice.get("type") {+ None | Some(Value::Null) => return Err(required("tool_choice.type")),+ Some(Value::String(kind)) => kind.as_str(),+ Some(_) => return Err(invalid("tool_choice.type: Input should be a valid string")),+ };+ let path = format!("tool_choice.{kind}");+ let translated = match kind {+ "auto" | "any" | "none" => {+ only_keys(choice, &["type", "disable_parallel_tool_use"], &path)?;+ json!(match kind {+ "auto" => "auto",+ "any" => "required",+ _ => "none",+ })+ }+ "tool" => {+ only_keys(+ choice,+ &["type", "name", "disable_parallel_tool_use"],+ &path,+ )?;+ let name = string(choice, "name", &path)?;+ if !tool_names.iter().any(|declared| declared == name) {+ return Err(invalid(format!(+ "{path}.name: tool '{name}' is not declared in tools"+ )));+ }+ json!({"type": "function", "function": {"name": name}})+ }+ _ => {+ return Err(invalid(+ "tool_choice.type: Input should be 'auto', 'any', 'tool' or 'none'",+ ))+ }+ };+ let parallel = match present(choice, "disable_parallel_tool_use") {+ None => None,+ Some(Value::Bool(disable)) => disable.then_some(false),+ Some(_) => {+ return Err(invalid(format!(+ "{path}.disable_parallel_tool_use: Input should be a valid boolean"+ )))+ }+ };+ if tool_names.is_empty() {+ return match kind {+ "auto" | "none" => Ok((None, None)),+ _ => Err(invalid(format!("{path}: tool_choice requires tools"))),+ };+ }+ Ok((Some(translated), parallel))+}++fn translate_message(+ message: &Value,+ index: usize,+ out: &mut Vec<Value>,+ first_image: &mut Option<String>,+) -> Result<(), MessagesError> {+ let path = format!("messages.{index}");+ let message = object(message, &path)?;+ let role = match message.get("role") {+ None | Some(Value::Null) => return Err(required(&format!("{path}.role"))),+ Some(Value::String(role)) => role.as_str(),+ Some(_) => {+ return Err(invalid(format!(+ "{path}.role: Input should be a valid string"+ )))+ }+ };+ match role {+ "user" | "assistant" => {}+ "system" => return Err(invalid(format!("{path}.role: {SYSTEM_TURN_REFUSAL}"))),+ _ => {+ return Err(invalid(format!(+ "{path}.role: Input should be 'user' or 'assistant'"+ )))+ }+ }+ only_keys(message, &["role", "content"], &path)?;+ let content = match message.get("content") {+ None | Some(Value::Null) => return Err(required(&format!("{path}.content"))),+ Some(Value::String(text)) => {+ out.push(json!({"role": role, "content": text}));+ return Ok(());+ }+ Some(Value::Array(blocks)) if blocks.is_empty() => {+ return Err(invalid(format!(+ "{path}.content: List should have at least 1 item"+ )))+ }+ Some(Value::Array(blocks)) => blocks,+ Some(_) => {+ return Err(invalid(format!(+ "{path}.content: Input should be a valid string or list"+ )))+ }+ };+ if role == "user" {+ user_blocks(content, &path, out, first_image)+ } else {+ assistant_blocks(content, &path, out)+ }+}++fn block_type<'a>(block: &'a Map<String, Value>, path: &str) -> Result<&'a str, MessagesError> {+ match block.get("type") {+ None | Some(Value::Null) => Err(required(&format!("{path}.type"))),+ Some(Value::String(kind)) => Ok(kind),+ Some(_) => Err(invalid(format!(+ "{path}.type: Input should be a valid string"+ ))),+ }+}++fn unsupported_block(path: &str, kind: &str) -> MessagesError {+ match kind {+ "text" | "image" | "tool_result" | "tool_use" | "thinking" | "redacted_thinking"+ | "document" | "search_result" | "container_upload" | "server_tool_use"+ | "web_search_tool_result" | "web_fetch_tool_result" | "code_execution_tool_result"+ | "bash_code_execution_tool_result" | "text_editor_code_execution_tool_result"+ | "tool_search_tool_result" | "mcp_tool_use" | "mcp_tool_result" => invalid(format!(+ "{path}.{kind}: content blocks of type '{kind}' are not supported here"+ )),+ _ => invalid(format!(+ "{path}.type: Input tag '{kind}' found using 'type' does not match any of the expected tags"+ )),+ }+}++fn text_block(block: &Map<String, Value>, path: &str) -> Result<String, MessagesError> {+ let path = format!("{path}.text");+ only_keys(+ block,+ &["type", "text", "cache_control", "citations"],+ &path,+ )?;+ cache_control(block, &path)?;+ citations(block, &path)?;+ Ok(string(block, "text", &path)?.to_string())+}++fn image_block(block: &Map<String, Value>, path: &str) -> Result<String, MessagesError> {+ let path = format!("{path}.image");+ only_keys(block, &["type", "source", "cache_control"], &path)?;+ cache_control(block, &path)?;+ let source = match block.get("source") {+ None | Some(Value::Null) => return Err(required(&format!("{path}.source"))),+ Some(source) => object(source, &format!("{path}.source"))?,+ };+ match source.get("type").and_then(Value::as_str) {+ Some("base64") => {}+ Some("url" | "file") => {+ return Err(invalid(format!(+ "{path}.source: only base64 image sources are supported"+ )))+ }+ Some(_) | None => {+ return Err(invalid(format!(+ "{path}.source.type: Input should be 'base64'"+ )))+ }+ }+ let base64_path = format!("{path}.source.base64");+ only_keys(source, &["type", "media_type", "data"], &base64_path)?;+ let media_type = string(source, "media_type", &base64_path)?;+ if !IMAGE_MEDIA_TYPES.contains(&media_type) {+ return Err(invalid(format!(+ "{base64_path}.media_type: Input should be 'image/jpeg', 'image/png', 'image/gif' or 'image/webp'"+ )));+ }+ let data = string(source, "data", &base64_path)?;+ Ok(format!("data:{media_type};base64,{data}"))+}++fn user_blocks(+ blocks: &[Value],+ path: &str,+ out: &mut Vec<Value>,+ first_image: &mut Option<String>,+) -> Result<(), MessagesError> {+ let mut tool_messages = Vec::new();+ let mut parts = Parts::default();+ let mut tool_images = Parts::default();+ for (index, block) in blocks.iter().enumerate() {+ let block_path = format!("{path}.content.{index}");+ let block = object(block, &block_path)?;+ match block_type(block, &block_path)? {+ "text" => parts.text(&text_block(block, &block_path)?),+ "image" => {+ parts.image(image_block(block, &block_path)?);+ first_image.get_or_insert_with(|| format!("{block_path}.image"));+ }+ "tool_result" => {+ let result_path = format!("{block_path}.tool_result");+ only_keys(+ block,+ &[+ "type",+ "tool_use_id",+ "content",+ "is_error",+ "cache_control",+ ],+ &result_path,+ )?;+ cache_control(block, &result_path)?;+ let tool_use_id = string(block, "tool_use_id", &result_path)?;+ if tool_use_id.is_empty() {+ return Err(invalid(format!(+ "{result_path}.tool_use_id: String should have at least 1 character"+ )));+ }+ match present(block, "is_error") {+ None | Some(Value::Bool(_)) => {}+ Some(_) => {+ return Err(invalid(format!(+ "{result_path}.is_error: Input should be a valid boolean"+ )))+ }+ }+ let text = tool_result_content(+ present(block, "content"),+ &result_path,+ &mut tool_images,+ first_image,+ )?;+ tool_messages.push(json!({+ "role": "tool",+ "tool_call_id": tool_use_id,+ "content": text,+ }));+ }+ kind => return Err(unsupported_block(&block_path, kind)),+ }+ }+ out.extend(tool_messages);+ let mut combined = tool_images;+ combined.items.extend(parts.items);+ if !combined.is_empty() || out.last().is_none_or(|last| last["role"] != "tool") {+ out.push(json!({"role": "user", "content": combined.into_content()}));+ }+ Ok(())+}++fn tool_result_content(+ content: Option<&Value>,+ path: &str,+ images: &mut Parts,+ first_image: &mut Option<String>,+) -> Result<String, MessagesError> {+ let blocks = match content {+ None => return Ok(String::new()),+ Some(Value::String(text)) => return Ok(text.clone()),+ Some(Value::Array(blocks)) => blocks,+ Some(_) => {+ return Err(invalid(format!(+ "{path}.content: Input should be a valid string or list"+ )))+ }+ };+ let mut text = String::new();+ for (index, block) in blocks.iter().enumerate() {+ let block_path = format!("{path}.content.{index}");+ let block = object(block, &block_path)?;+ match block_type(block, &block_path)? {+ "text" => text.push_str(&text_block(block, &block_path)?),+ "image" => {+ images.image(image_block(block, &block_path)?);+ first_image.get_or_insert_with(|| format!("{block_path}.image"));+ }+ kind => return Err(unsupported_block(&block_path, kind)),+ }+ }+ Ok(text)+}++fn assistant_blocks(+ blocks: &[Value],+ path: &str,+ out: &mut Vec<Value>,+) -> Result<(), MessagesError> {+ let mut text = String::new();+ let mut tool_calls = Vec::new();+ for (index, block) in blocks.iter().enumerate() {+ let block_path = format!("{path}.content.{index}");+ let block = object(block, &block_path)?;+ match block_type(block, &block_path)? {+ "text" => text.push_str(&text_block(block, &block_path)?),+ "tool_use" => {+ let use_path = format!("{block_path}.tool_use");+ only_keys(+ block,+ &["type", "id", "name", "input", "cache_control"],+ &use_path,+ )?;+ cache_control(block, &use_path)?;+ let id = string(block, "id", &use_path)?;+ let name = string(block, "name", &use_path)?;+ if id.is_empty() || name.is_empty() {+ let field = if id.is_empty() { "id" } else { "name" };+ return Err(invalid(format!(+ "{use_path}.{field}: String should have at least 1 character"+ )));+ }+ let input = match block.get("input") {+ None | Some(Value::Null) => return Err(required(&format!("{use_path}.input"))),+ Some(input @ Value::Object(_)) => input,+ Some(_) => {+ return Err(invalid(format!(+ "{use_path}.input: Input should be a valid dictionary"+ )))+ }+ };+ tool_calls.push(json!({+ "id": id,+ "type": "function",+ "function": {+ "name": name,+ "arguments": serde_json::to_string(input).unwrap_or_default(),+ },+ }));+ }+ "thinking" => {+ let thinking_path = format!("{block_path}.thinking");+ only_keys(block, &["type", "thinking", "signature"], &thinking_path)?;+ }+ "redacted_thinking" => {+ let redacted_path = format!("{block_path}.redacted_thinking");+ only_keys(block, &["type", "data"], &redacted_path)?;+ }+ kind => return Err(unsupported_block(&block_path, kind)),+ }+ }+ let mut message = Map::new();+ message.insert("role".into(), json!("assistant"));+ if tool_calls.is_empty() {+ message.insert("content".into(), json!(text));+ } else {+ message.insert(+ "content".into(),+ if text.is_empty() {+ Value::Null+ } else {+ json!(text)+ },+ );+ message.insert("tool_calls".into(), Value::Array(tool_calls));+ }+ out.push(Value::Object(message));+ Ok(())+}diff --git a/packages/sie_gateway/src/handlers/messages/response.rs b/packages/sie_gateway/src/handlers/messages/response.rsnew file mode 100644index 000000000..f38d1e8fe--- /dev/null+++ b/packages/sie_gateway/src/handlers/messages/response.rs@@ -0,0 +1,129 @@+//! Buffered response translation: a chat completion into an Anthropic+//! Message.++use serde_json::{json, Map, Value};++/// The signature carried by every `thinking` block SIE answers. SIE does not+/// sign reasoning and ignores the signature of thinking blocks sent back.+pub(crate) const THINKING_SIGNATURE: &str = "sie-unsigned";++/// The Anthropic `stop_reason` for a chat `finish_reason`.+pub(crate) fn stop_reason(finish_reason: Option<&str>, has_tool_use: bool) -> &'static str {+ match finish_reason {+ Some("length") => "max_tokens",+ Some("content_filter") => "refusal",+ Some("tool_calls" | "function_call") => "tool_use",+ _ if has_tool_use => "tool_use",+ _ => "end_turn",+ }+}++/// Anthropic usage from a chat usage block: `input_tokens` excludes the+/// prompt tokens served from the prefix cache, which are reported as+/// `cache_read_input_tokens`, so the two add up to the chat `prompt_tokens`.+pub(crate) fn anthropic_usage(usage: &Value) -> Option<Value> {+ let prompt = usage.get("prompt_tokens")?.as_u64()?;+ let completion = usage.get("completion_tokens")?.as_u64()?;+ let cached = usage+ .get("prompt_tokens_details")+ .and_then(|details| details.get("cached_tokens"))+ .and_then(Value::as_u64)+ .unwrap_or(0)+ .min(prompt);+ Some(json!({+ "input_tokens": prompt - cached,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": cached,+ "output_tokens": completion,+ }))+}++/// The tool input a chat tool call's `arguments` string carries.+pub(crate) fn tool_input(arguments: &str) -> Result<Value, String> {+ if arguments.trim().is_empty() {+ return Ok(Value::Object(Map::new()));+ }+ match serde_json::from_str::<Value>(arguments) {+ Ok(input @ Value::Object(_)) => Ok(input),+ Ok(_) => Err("tool call arguments are not a JSON object".to_string()),+ Err(_) => Err("tool call arguments are not valid JSON".to_string()),+ }+}++/// Translate a chat completion into a Message. `model` is the model id the+/// caller sent; `request_id` the gateway request id.+pub(crate) fn chat_completion_to_message(+ chat: &Value,+ model: &str,+ request_id: &str,+) -> Result<Value, String> {+ let choice = chat+ .get("choices")+ .and_then(Value::as_array)+ .and_then(|choices| choices.first())+ .ok_or("chat completion has no choices")?;+ let message = choice+ .get("message")+ .ok_or("chat completion choice has no message")?;+ let mut content = Vec::new();+ if let Some(reasoning) = message+ .get("reasoning_content")+ .and_then(Value::as_str)+ .filter(|reasoning| !reasoning.is_empty())+ {+ content.push(json!({+ "type": "thinking",+ "thinking": reasoning,+ "signature": THINKING_SIGNATURE,+ }));+ }+ if let Some(text) = message+ .get("content")+ .and_then(Value::as_str)+ .filter(|text| !text.trim().is_empty())+ {+ content.push(json!({"type": "text", "text": text}));+ }+ let mut has_tool_use = false;+ for call in message+ .get("tool_calls")+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ {+ let id = call+ .get("id")+ .and_then(Value::as_str)+ .ok_or("tool call has no id")?;+ let function = call.get("function").ok_or("tool call has no function")?;+ let name = function+ .get("name")+ .and_then(Value::as_str)+ .ok_or("tool call has no name")?;+ let arguments = function+ .get("arguments")+ .and_then(Value::as_str)+ .unwrap_or("");+ content.push(json!({+ "type": "tool_use",+ "id": id,+ "name": name,+ "input": tool_input(arguments)?,+ }));+ has_tool_use = true;+ }+ let usage = chat+ .get("usage")+ .and_then(anthropic_usage)+ .ok_or("chat completion has no usage")?;+ Ok(json!({+ "id": format!("msg_{request_id}"),+ "type": "message",+ "role": "assistant",+ "model": model,+ "content": content,+ "stop_reason": stop_reason(choice.get("finish_reason").and_then(Value::as_str), has_tool_use),+ "stop_sequence": Value::Null,+ "usage": usage,+ }))+}diff --git a/packages/sie_gateway/src/handlers/messages/schema.rs b/packages/sie_gateway/src/handlers/messages/schema.rsnew file mode 100644index 000000000..ce123050e--- /dev/null+++ b/packages/sie_gateway/src/handlers/messages/schema.rs@@ -0,0 +1,143 @@+//! OpenAPI shapes of the Anthropic Messages surface.++use serde::{Deserialize, Serialize};+use serde_json::Value;+use utoipa::ToSchema;++/// Anthropic Messages request, as accepted by ``POST /v1/messages``.+///+/// The request is translated into a ``/v1/chat/completions`` request and+/// served by the chat route, so every chat limit applies. Fields outside this+/// set fail with ``400 invalid_request_error`` and the message+/// ``<field>: Extra inputs are not permitted``. ``metadata`` and every+/// ``cache_control`` are accepted and have no effect: prefix caching is+/// automatic and ``metadata`` is neither logged nor forwarded.+#[derive(Debug, Serialize, Deserialize, ToSchema)]+#[serde(deny_unknown_fields)]+pub struct MessagesRequest {+ /// The model id, used as on ``/v1/chat/completions`` (``model`` or+ /// ``model:profile``, or an operator alias).+ pub model: String,+ /// Output token limit, at least 1 and at most the serving profile's+ /// ``max_output_tokens``.+ #[schema(minimum = 1)]+ pub max_tokens: u32,+ /// ``user`` and ``assistant`` turns. User content blocks: ``text``,+ /// base64 ``image`` and ``tool_result``. Assistant content blocks:+ /// ``text``, ``tool_use``, and ``thinking`` / ``redacted_thinking``,+ /// which are accepted and do not reach the model. ``role: "system"``+ /// turns are refused; system text belongs in ``system``. The last turn+ /// must be a user turn.+ pub messages: Value,+ /// A string or a list of ``text`` blocks, concatenated in order.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub system: Option<Value>,+ /// Custom tools (``name``, ``description``, ``input_schema``), at most+ /// 64, names matching ``^[a-zA-Z0-9_-]{1,64}$``. Anthropic-defined tool+ /// types are refused.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub tools: Option<Value>,+ /// ``auto``, ``any``, ``tool`` (with ``name``) or ``none``, with+ /// ``disable_parallel_tool_use``.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub tool_choice: Option<Value>,+ /// ``enabled`` and ``adaptive`` return the model's reasoning as+ /// ``thinking`` blocks; ``disabled``, ``display: "omitted"`` or an absent+ /// field do not. Whether the model reasons is a property of its serving+ /// profile, and ``budget_tokens`` is validated but does not bound+ /// reasoning.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub thinking: Option<Value>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub stop_sequences: Option<Vec<String>>,+ /// In ``[0, 1]``.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub temperature: Option<f64>,+ /// In ``(0, 1]``.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub top_p: Option<f64>,+ /// At least 1.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schema(minimum = 1)]+ pub top_k: Option<u32>,+ /// Server-sent events: ``message_start``, content block events,+ /// ``message_delta`` with the final usage, ``message_stop``, and ``ping``+ /// whenever no other event was sent for 10 seconds. A failure after the+ /// stream opened is an ``error`` event, and the stream then ends without+ /// ``message_stop``.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub stream: Option<bool>,+ /// Accepted and ignored (``user_id`` only).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub metadata: Option<Value>,+ /// Accepted and ignored.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub cache_control: Option<Value>,+ /// Accepted only empty: every field in it is refused, ``effort`` with+ /// ``output_config.effort: Extra inputs are not permitted``.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub output_config: Option<EmptyOutputConfig>,+}++/// An ``output_config`` with no fields, the only one accepted.+#[derive(Debug, Default, Serialize, Deserialize, ToSchema)]+#[serde(deny_unknown_fields)]+pub struct EmptyOutputConfig {}++/// Token usage of a Message. ``input_tokens`` plus+/// ``cache_read_input_tokens`` equals the prompt tokens the chat route+/// reports; ``cache_creation_input_tokens`` is always 0.+#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct MessagesUsage {+ pub input_tokens: u64,+ pub cache_creation_input_tokens: u64,+ pub cache_read_input_tokens: u64,+ /// Includes reasoning tokens.+ pub output_tokens: u64,+}++/// Anthropic Message answered by ``POST /v1/messages`` without ``stream``.+#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct MessagesResponse {+ /// ``msg_`` followed by the gateway request id.+ pub id: String,+ /// Always ``message``.+ #[serde(rename = "type")]+ pub kind: String,+ /// Always ``assistant``.+ pub role: String,+ pub model: String,+ /// ``thinking`` (when requested and produced), then ``text``, then one+ /// ``tool_use`` per tool call. ``thinking.signature`` is an opaque+ /// constant that SIE does not verify.+ pub content: Value,+ /// ``end_turn``, ``tool_use``, ``max_tokens`` or ``refusal``.+ pub stop_reason: String,+ /// Always ``null``.+ pub stop_sequence: Option<String>,+ pub usage: MessagesUsage,+}++#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct AnthropicErrorBody {+ /// Follows the status: ``invalid_request_error`` (400),+ /// ``authentication_error`` (401), ``billing_error`` (402),+ /// ``permission_error`` (403), ``not_found_error`` (404),+ /// ``request_too_large`` (413), ``rate_limit_error`` (429),+ /// ``api_error`` (500, 502), ``overloaded_error`` (503),+ /// ``timeout_error`` (504).+ #[serde(rename = "type")]+ pub kind: String,+ pub message: String,+}++/// Anthropic error envelope used on ``/v1/messages``. The SIE error code is+/// in the ``X-SIE-Error-Code`` header. ``Retry-After`` is at most 60.+#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct AnthropicErrorEnvelope {+ /// Always ``error``.+ #[serde(rename = "type")]+ pub kind: String,+ pub error: AnthropicErrorBody,+ pub request_id: Option<String>,+}diff --git a/packages/sie_gateway/src/handlers/messages/stream.rs b/packages/sie_gateway/src/handlers/messages/stream.rsnew file mode 100644index 000000000..f5ba20446--- /dev/null+++ b/packages/sie_gateway/src/handlers/messages/stream.rs@@ -0,0 +1,492 @@+//! Streaming translation: chat completion chunks in, Anthropic Messages+//! events out.+//!+//! [`StreamMachine`] is pure: it turns each chat SSE `data` payload into the+//! events it implies. [`stream_body`] drives it over the chat route's SSE body+//! and adds a `ping` whenever no event was sent for the ping interval.+//! Dropping the returned body drops the chat body with it, so a client that+//! goes away cancels the generation the same way a chat client does. An+//! `error` event ends the body the same way, so a stream the translation+//! cannot follow stops generating.++use std::collections::VecDeque;+use std::convert::Infallible;+use std::time::Duration;++use axum::body::Body;+use bytes::Bytes;+use futures_util::StreamExt;+use serde_json::{json, Value};++use super::error::{translate_error_body, ErrorContext};+use super::response::{anthropic_usage, stop_reason, THINKING_SIGNATURE};++pub(crate) const PING_INTERVAL: Duration = Duration::from_secs(10);++/// One Anthropic SSE event.+#[derive(Debug, Clone, PartialEq)]+pub(crate) struct Event {+ pub name: &'static str,+ pub data: Value,+}++impl Event {+ fn new(name: &'static str, data: Value) -> Self {+ Self { name, data }+ }++ pub(crate) fn ping() -> Self {+ Self::new("ping", json!({"type": "ping"}))+ }++ pub(crate) fn encode(&self) -> Bytes {+ Bytes::from(format!("event: {}\ndata: {}\n\n", self.name, self.data))+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum Block {+ Text,+ Thinking,+ ToolUse { chat_index: u64 },+}++/// The chat-chunk to Anthropic-event state machine. One block is open at a+/// time and block indices are contiguous from 0.+#[derive(Debug)]+pub(crate) struct StreamMachine {+ message_id: String,+ model: String,+ next_index: u64,+ open: Option<(Block, u64)>,+ held_whitespace: String,+ tool_indices: Vec<u64>,+ finish_reason: Option<String>,+ usage: Option<Value>,+ started: bool,+ done: bool,+}++fn zero_usage() -> Value {+ json!({+ "input_tokens": 0,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ "output_tokens": 0,+ })+}++/// The HTTP status a mid-stream chat error code stands for, which decides+/// the Anthropic error type.+fn status_for_code(code: &str) -> u16 {+ match code {+ "invalid_request" | "unsupported_field" | "context_exceeded" | "INPUT_TOO_LONG"+ | "grammar_invalid" => 400,+ "PAYLOAD_TOO_LARGE" => 413,+ "rate_limit_exceeded" | "COLD_START_RATE_LIMITED" => 429,+ "RESOURCE_EXHAUSTED" | "QUEUE_FULL" | "MODEL_LOADING" | "LORA_LOADING"+ | "transport_failure" | "provisioning" | "QUEUE_UNAVAILABLE" => 503,+ "first_chunk_timeout"+ | "inter_chunk_timeout"+ | "overall_timeout"+ | "GATEWAY_TIMEOUT"+ | "cancelled" => 504,+ _ => 500,+ }+}++impl StreamMachine {+ pub(crate) fn new(message_id: String, model: String) -> Self {+ Self {+ message_id,+ model,+ next_index: 0,+ open: None,+ held_whitespace: String::new(),+ tool_indices: Vec::new(),+ finish_reason: None,+ usage: None,+ started: false,+ done: false,+ }+ }++ /// Whether `message_stop` or an `error` event has been produced.+ pub(crate) fn is_done(&self) -> bool {+ self.done+ }++ /// The `message_start` event, sent as soon as the chat stream opens.+ pub(crate) fn start(&mut self) -> Vec<Event> {+ if self.started {+ return Vec::new();+ }+ self.started = true;+ vec![Event::new(+ "message_start",+ json!({+ "type": "message_start",+ "message": {+ "id": self.message_id,+ "type": "message",+ "role": "assistant",+ "model": self.model,+ "content": [],+ "stop_reason": Value::Null,+ "stop_sequence": Value::Null,+ "usage": zero_usage(),+ },+ }),+ )]+ }++ /// Feed one chat SSE `data` payload.+ pub(crate) fn on_data(&mut self, data: &str) -> Vec<Event> {+ let mut events = self.start();+ if self.done {+ return events;+ }+ if data == "[DONE]" {+ self.finish(&mut events);+ return events;+ }+ let Ok(chunk) = serde_json::from_str::<Value>(data) else {+ self.fail(+ &mut events,+ "api_error",+ "the generation stream sent a malformed chunk",+ );+ return events;+ };+ if let Some(error) = chunk.get("error").filter(|error| error.is_object()) {+ let code = error.get("code").and_then(Value::as_str).unwrap_or("");+ let status = axum::http::StatusCode::from_u16(status_for_code(code))+ .unwrap_or(axum::http::StatusCode::INTERNAL_SERVER_ERROR);+ let (error_type, message, _) =+ translate_error_body(status, &json!({"error": error}), &ErrorContext::default());+ self.fail(&mut events, error_type, &message);+ return events;+ }+ if let Some(choice) = chunk+ .get("choices")+ .and_then(Value::as_array)+ .and_then(|choices| choices.first())+ {+ let delta = choice.get("delta").unwrap_or(&Value::Null);+ if let Some(reasoning) = delta+ .get("reasoning_content")+ .and_then(Value::as_str)+ .filter(|text| !text.is_empty())+ {+ self.thinking(reasoning, &mut events);+ }+ if let Some(text) = delta+ .get("content")+ .and_then(Value::as_str)+ .filter(|text| !text.is_empty())+ {+ self.text(text, &mut events);+ }+ for call in delta+ .get("tool_calls")+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ {+ if let Err(message) = self.tool_call(call, &mut events) {+ self.fail(&mut events, "api_error", message);+ return events;+ }+ }+ if let Some(finish_reason) = choice.get("finish_reason").and_then(Value::as_str) {+ self.close(&mut events);+ self.held_whitespace.clear();+ self.finish_reason = Some(finish_reason.to_string());+ }+ }+ if let Some(usage) = chunk.get("usage").and_then(anthropic_usage) {+ self.usage = Some(usage);+ }+ if self.finish_reason.is_some() && self.usage.is_some() {+ self.complete(&mut events);+ }+ events+ }++ /// The chat stream ended. A stream that reported a finish completes;+ /// any other ending is an `error` event.+ pub(crate) fn on_end(&mut self) -> Vec<Event> {+ let mut events = self.start();+ if !self.done {+ self.finish(&mut events);+ }+ events+ }++ /// The chat stream broke before it ended.+ pub(crate) fn on_transport_error(&mut self) -> Vec<Event> {+ let mut events = self.start();+ if !self.done {+ self.fail(+ &mut events,+ "api_error",+ "the generation stream ended unexpectedly",+ );+ }+ events+ }++ fn finish(&mut self, events: &mut Vec<Event>) {+ if self.finish_reason.is_some() {+ self.complete(events);+ } else {+ self.fail(+ events,+ "api_error",+ "the generation stream ended without a finish reason",+ );+ }+ }++ fn complete(&mut self, events: &mut Vec<Event>) {+ self.close(events);+ let has_tool_use = !self.tool_indices.is_empty();+ events.push(Event::new(+ "message_delta",+ json!({+ "type": "message_delta",+ "delta": {+ "stop_reason": stop_reason(self.finish_reason.as_deref(), has_tool_use),+ "stop_sequence": Value::Null,+ },+ "usage": self.usage.clone().unwrap_or_else(zero_usage),+ }),+ ));+ events.push(Event::new("message_stop", json!({"type": "message_stop"})));+ self.done = true;+ }++ fn fail(&mut self, events: &mut Vec<Event>, error_type: &str, message: &str) {+ events.push(Event::new(+ "error",+ json!({+ "type": "error",+ "error": {"type": error_type, "message": message},+ }),+ ));+ self.done = true;+ }++ fn open_block(&mut self, block: Block, content_block: Value, events: &mut Vec<Event>) {+ let index = self.next_index;+ self.next_index += 1;+ self.open = Some((block, index));+ events.push(Event::new(+ "content_block_start",+ json!({+ "type": "content_block_start",+ "index": index,+ "content_block": content_block,+ }),+ ));+ }++ fn delta(&self, delta: Value, events: &mut Vec<Event>) {+ if let Some((_, index)) = self.open {+ events.push(Event::new(+ "content_block_delta",+ json!({"type": "content_block_delta", "index": index, "delta": delta}),+ ));+ }+ }++ fn close(&mut self, events: &mut Vec<Event>) {+ let Some((block, index)) = self.open.take() else {+ return;+ };+ if block == Block::Thinking {+ events.push(Event::new(+ "content_block_delta",+ json!({+ "type": "content_block_delta",+ "index": index,+ "delta": {"type": "signature_delta", "signature": THINKING_SIGNATURE},+ }),+ ));+ }+ events.push(Event::new(+ "content_block_stop",+ json!({"type": "content_block_stop", "index": index}),+ ));+ }++ fn thinking(&mut self, text: &str, events: &mut Vec<Event>) {+ if !matches!(self.open, Some((Block::Thinking, _))) {+ self.held_whitespace.clear();+ self.close(events);+ self.open_block(+ Block::Thinking,+ json!({"type": "thinking", "thinking": "", "signature": ""}),+ events,+ );+ }+ self.delta(json!({"type": "thinking_delta", "thinking": text}), events);+ }++ fn text(&mut self, text: &str, events: &mut Vec<Event>) {+ if !matches!(self.open, Some((Block::Text, _))) {+ if text.trim().is_empty() {+ self.held_whitespace.push_str(text);+ return;+ }+ self.close(events);+ self.open_block(Block::Text, json!({"type": "text", "text": ""}), events);+ let mut first = std::mem::take(&mut self.held_whitespace);+ first.push_str(text);+ self.delta(json!({"type": "text_delta", "text": first}), events);+ return;+ }+ self.delta(json!({"type": "text_delta", "text": text}), events);+ }++ fn tool_call(&mut self, call: &Value, events: &mut Vec<Event>) -> Result<(), &'static str> {+ let chat_index = call.get("index").and_then(Value::as_u64).unwrap_or(0);+ let function = call.get("function").unwrap_or(&Value::Null);+ let id = call.get("id").and_then(Value::as_str);+ let name = function.get("name").and_then(Value::as_str);+ if !self.tool_indices.contains(&chat_index) {+ let (Some(id), Some(name)) = (id, name) else {+ return Err("a tool call arrived without its id and name");+ };+ self.held_whitespace.clear();+ self.close(events);+ self.open_block(+ Block::ToolUse { chat_index },+ json!({"type": "tool_use", "id": id, "name": name, "input": {}}),+ events,+ );+ self.tool_indices.push(chat_index);+ }+ let Some(arguments) = function+ .get("arguments")+ .and_then(Value::as_str)+ .filter(|arguments| !arguments.is_empty())+ else {+ return Ok(());+ };+ if self.open.map(|(block, _)| block) != Some(Block::ToolUse { chat_index }) {+ return Err("tool call arguments arrived after another content block started");+ }+ self.delta(+ json!({"type": "input_json_delta", "partial_json": arguments}),+ events,+ );+ Ok(())+ }+}++/// Splits an SSE byte stream into the `data` payloads of its events.+#[derive(Debug, Default)]+pub(crate) struct FrameParser {+ buffer: Vec<u8>,+}++impl FrameParser {+ pub(crate) fn push(&mut self, bytes: &[u8]) -> Vec<String> {+ self.buffer+ .extend(bytes.iter().copied().filter(|byte| *byte != b'\r'));+ let mut payloads = Vec::new();+ while let Some(end) = self.buffer.windows(2).position(|window| window == b"\n\n") {+ let frame: Vec<u8> = self.buffer.drain(..end + 2).collect();+ let frame = String::from_utf8_lossy(&frame);+ let mut data: Option<String> = None;+ for line in frame.split('\n') {+ let Some(rest) = line.strip_prefix("data:") else {+ continue;+ };+ let rest = rest.strip_prefix(' ').unwrap_or(rest);+ match data.as_mut() {+ Some(data) => {+ data.push('\n');+ data.push_str(rest);+ }+ None => data = Some(rest.to_string()),+ }+ }+ payloads.extend(data);+ }+ payloads+ }+}++struct Driver {+ inner: axum::body::BodyDataStream,+ parser: FrameParser,+ machine: StreamMachine,+ pending: VecDeque<Bytes>,+ ping_every: Duration,+ deadline: tokio::time::Instant,+ finished: bool,+}++impl Driver {+ fn queue(&mut self, events: Vec<Event>) {+ self.pending.extend(events.iter().map(Event::encode));+ }+}++/// The Anthropic SSE body for a chat SSE body.+pub(crate) fn stream_body(inner: Body, mut machine: StreamMachine, ping_every: Duration) -> Body {+ let start = machine.start();+ let mut driver = Driver {+ inner: inner.into_data_stream(),+ parser: FrameParser::default(),+ machine,+ pending: VecDeque::new(),+ ping_every,+ deadline: tokio::time::Instant::now() + ping_every,+ finished: false,+ };+ driver.queue(start);+ let stream = futures_util::stream::unfold(driver, |mut driver| async move {+ loop {+ if let Some(bytes) = driver.pending.pop_front() {+ driver.deadline = tokio::time::Instant::now() + driver.ping_every;+ return Some((Ok::<Bytes, Infallible>(bytes), driver));+ }+ if driver.finished {+ return None;+ }+ let pinging = !driver.machine.is_done();+ tokio::select! {+ chunk = driver.inner.next() => match chunk {+ Some(Ok(bytes)) => {+ for payload in driver.parser.push(&bytes) {+ let events = driver.machine.on_data(&payload);+ let failed = events.iter().any(|event| event.name == "error");+ driver.queue(events);+ if failed {+ driver.finished = true;+ break;+ }+ }+ }+ Some(Err(_)) => {+ let events = driver.machine.on_transport_error();+ driver.queue(events);+ driver.finished = true;+ }+ None => {+ let events = driver.machine.on_end();+ driver.queue(events);+ driver.finished = true;+ }+ },+ _ = tokio::time::sleep_until(driver.deadline), if pinging => {+ driver.pending.push_back(Event::ping().encode());+ }+ }+ }+ });+ Body::from_stream(stream)+}diff --git a/packages/sie_gateway/src/handlers/messages/tests.rs b/packages/sie_gateway/src/handlers/messages/tests.rsnew file mode 100644index 000000000..565b635b9--- /dev/null+++ b/packages/sie_gateway/src/handlers/messages/tests.rs@@ -0,0 +1,963 @@+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Arc;+use std::time::Duration;++use axum::body::{to_bytes, Body};+use axum::extract::{Request, State};+use axum::http::{HeaderName, HeaderValue, Method, StatusCode};+use axum::response::Response;+use bytes::Bytes;+use futures_util::StreamExt;+use serde_json::{json, Value};+use tower::ServiceExt;++use super::error::{anthropic_error_response, ErrorContext};+use super::request::{messages_to_chat, MAX_TOOLS};+use super::response::chat_completion_to_message;+use super::stream::{stream_body, FrameParser, StreamMachine};+use super::{messages_dispatch_inputs, proxy_messages};+use crate::handlers::proxy::chat_completions_dispatch_inputs;+use crate::handlers::test_support::{TestGateway, HYBRID_GENERATE_MODEL, LOCAL_LANE};++const CODER_MODEL: &str = "\+sie_id: acme/coder+hf_id: acme/coder+tasks:+ generate:+ max_output_tokens: 64+ capabilities:+ tools: true+profiles:+ default:+ adapter_path: sie_server.adapters.sglang:SGLangAdapter+ max_batch_tokens: 8192+";++fn vectors(name: &str) -> Value {+ let path = format!(+ "{}/../../conformance/anthropic_messages/{name}",+ env!("CARGO_MANIFEST_DIR")+ );+ serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap()+}++fn messages_request(body: Value) -> Request {+ Request::builder()+ .method(Method::POST)+ .uri("/v1/messages?beta=true")+ .header("content-type", "application/json")+ .header("anthropic-version", "2023-06-01")+ .header(+ "anthropic-beta",+ "claude-code-20250219,interleaved-thinking-2025-05-14",+ )+ .body(Body::from(body.to_string()))+ .unwrap()+}++async fn json_body(response: Response) -> Value {+ let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();+ serde_json::from_slice(&bytes).unwrap()+}++fn parse_events(bytes: &[u8]) -> Vec<Value> {+ let text = String::from_utf8(bytes.to_vec()).unwrap();+ text.split("\n\n")+ .filter(|frame| !frame.trim().is_empty())+ .map(|frame| {+ let mut name = "";+ let mut data = Value::Null;+ for line in frame.lines() {+ if let Some(rest) = line.strip_prefix("event: ") {+ name = rest;+ } else if let Some(rest) = line.strip_prefix("data: ") {+ data = serde_json::from_str(rest).unwrap();+ }+ }+ assert_eq!(data["type"], name, "event name and data type agree");+ json!({"event": name, "data": data})+ })+ .collect()+}++async fn events_of(response: Response) -> Vec<Value> {+ let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();+ parse_events(&bytes)+}++fn event_names(events: &[Value]) -> Vec<String> {+ events+ .iter()+ .map(|event| event["event"].as_str().unwrap().to_string())+ .collect()+}++#[test]+fn request_vectors_translate_onto_the_chat_body() {+ let vectors = vectors("request_vectors.json");+ for case in vectors["accepted"].as_array().unwrap() {+ let name = case["name"].as_str().unwrap();+ let version = case.get("anthropic_version").and_then(Value::as_str);+ let translation = messages_to_chat(&case["body"], version)+ .unwrap_or_else(|error| panic!("{name}: {error:?}"));+ assert_eq!(translation.chat, case["chat"], "{name}");+ assert_eq!(+ translation.first_image.as_deref(),+ case.get("first_image").and_then(Value::as_str),+ "{name}"+ );+ assert!(+ chat_completions_dispatch_inputs(&translation.chat).is_ok(),+ "{name}: the chat route accepts the translation"+ );+ }+ for case in vectors["rejected"].as_array().unwrap() {+ let name = case["name"].as_str().unwrap();+ let version = case.get("anthropic_version").and_then(Value::as_str);+ let error = messages_to_chat(&case["body"], version).expect_err(name);+ assert_eq!(error.status, StatusCode::BAD_REQUEST, "{name}");+ assert_eq!(error.message, case["message"].as_str().unwrap(), "{name}");+ }+}++#[test]+fn every_captured_claude_code_request_translates_or_fails_with_the_recovery_wording() {+ let fixture = vectors("claude_code_requests.json");+ let cases = fixture["cases"].as_array().unwrap();+ assert!(!cases.is_empty());+ for case in cases {+ let name = case["name"].as_str().unwrap();+ let version = case["headers"]["anthropic-version"].as_str();+ let expect = &case["expect"];+ match messages_to_chat(&case["body"], version) {+ Ok(translation) => {+ let chat = &expect["chat"];+ assert!(chat.is_object(), "{name}: expected a refusal");+ let roles: Vec<&str> = translation.chat["messages"]+ .as_array()+ .unwrap()+ .iter()+ .map(|message| message["role"].as_str().unwrap())+ .collect();+ let expected_roles: Vec<&str> = chat["roles"]+ .as_array()+ .unwrap()+ .iter()+ .map(|role| role.as_str().unwrap())+ .collect();+ assert_eq!(roles, expected_roles, "{name}");+ assert_eq!(translation.chat["stream"], chat["stream"], "{name}");+ assert_eq!(translation.chat["max_tokens"], chat["max_tokens"], "{name}");+ assert_eq!(+ translation.chat["include_reasoning"], chat["include_reasoning"],+ "{name}"+ );+ assert_eq!(+ translation.chat["tools"].as_array().map_or(0, Vec::len),+ chat["tool_count"].as_u64().unwrap() as usize,+ "{name}"+ );+ assert_eq!(+ translation.chat.get("stop").cloned().unwrap_or(Value::Null),+ chat.get("stop").cloned().unwrap_or(Value::Null),+ "{name}"+ );+ assert!(+ chat_completions_dispatch_inputs(&translation.chat).is_ok(),+ "{name}: the chat route accepts the translation"+ );+ }+ Err(error) => {+ assert_eq!(+ error.message,+ expect["error"]+ .as_str()+ .unwrap_or_else(|| panic!("{name}: unexpected refusal {}", error.message)),+ "{name}"+ );+ }+ }+ }+}++#[test]+fn tool_count_over_the_limit_is_refused() {+ let tools: Vec<Value> = (0..=MAX_TOOLS)+ .map(|index| json!({"name": format!("tool_{index}"), "input_schema": {"type": "object"}}))+ .collect();+ let error = messages_to_chat(+ &json!({"model": "m", "max_tokens": 1, "tools": tools, "messages": [{"role": "user", "content": "x"}]}),+ None,+ )+ .unwrap_err();+ assert_eq!(+ error.message,+ "tools: at most 64 tools are supported, got 65"+ );+}++#[test]+fn response_vectors_translate_the_chat_completion() {+ let vectors = vectors("response_vectors.json");+ for case in vectors["translated"].as_array().unwrap() {+ let name = case["name"].as_str().unwrap();+ let message = chat_completion_to_message(+ &case["chat"],+ case["model"].as_str().unwrap(),+ case["request_id"].as_str().unwrap(),+ )+ .unwrap_or_else(|error| panic!("{name}: {error}"));+ assert_eq!(message, case["message"], "{name}");+ }+ for case in vectors["faults"].as_array().unwrap() {+ let name = case["name"].as_str().unwrap();+ assert!(+ chat_completion_to_message(&case["chat"], "m", "r").is_err(),+ "{name}"+ );+ }+}++fn stream_frames(case: &Value) -> Vec<String> {+ case["frames"]+ .as_array()+ .unwrap()+ .iter()+ .map(|frame| match frame {+ Value::String(text) => text.clone(),+ other => other.to_string(),+ })+ .collect()+}++#[test]+fn stream_vectors_drive_the_state_machine() {+ let vectors = vectors("stream_vectors.json");+ for case in vectors["streams"].as_array().unwrap() {+ let name = case["name"].as_str().unwrap();+ let mut machine = StreamMachine::new(+ case["message_id"].as_str().unwrap().to_string(),+ case["model"].as_str().unwrap().to_string(),+ );+ let mut events = machine.start();+ for frame in stream_frames(case) {+ events.extend(machine.on_data(&frame));+ }+ events.extend(machine.on_end());+ let got: Vec<Value> = events+ .iter()+ .map(|event| json!({"event": event.name, "data": event.data}))+ .collect();+ assert_eq!(&Value::Array(got), &case["events"], "{name}");+ }+}++#[tokio::test]+async fn stream_vectors_survive_the_sse_body_split_at_any_byte() {+ let vectors = vectors("stream_vectors.json");+ for case in vectors["streams"].as_array().unwrap() {+ let name = case["name"].as_str().unwrap();+ let mut sse = String::new();+ for frame in stream_frames(case) {+ sse.push_str(&format!("data: {frame}\n\n"));+ sse.push_str(":\n\n");+ }+ let bytes = sse.into_bytes();+ let pieces: Vec<Result<Bytes, std::io::Error>> = bytes+ .chunks(7)+ .map(|chunk| Ok(Bytes::copy_from_slice(chunk)))+ .collect();+ let inner = Body::from_stream(futures_util::stream::iter(pieces));+ let machine = StreamMachine::new(+ case["message_id"].as_str().unwrap().to_string(),+ case["model"].as_str().unwrap().to_string(),+ );+ let body = stream_body(inner, machine, Duration::from_secs(60));+ let collected = to_bytes(body, usize::MAX).await.unwrap();+ assert_eq!(+ &Value::Array(parse_events(&collected)),+ &case["events"],+ "{name}"+ );+ }+}++#[test]+fn frame_parser_joins_multi_line_data_and_skips_comments() {+ let mut parser = FrameParser::default();+ assert!(parser.push(b": keep-alive\r\n\r\ndata: {\"a\"").is_empty());+ assert_eq!(+ parser.push(b":1}\r\n\r\nevent: x\ndata: one\ndata: two\n\n"),+ vec!["{\"a\":1}".to_string(), "one\ntwo".to_string()]+ );+}++#[tokio::test]+async fn error_vectors_render_the_anthropic_envelope() {+ let vectors = vectors("error_vectors.json");+ for case in vectors["errors"].as_array().unwrap() {+ let name = case["name"].as_str().unwrap();+ let body = match &case["body"] {+ Value::Null => Body::empty(),+ other => Body::from(other.to_string()),+ };+ let mut response = Response::new(body);+ *response.status_mut() =+ StatusCode::from_u16(case["status"].as_u64().unwrap() as u16).unwrap();+ for (header, value) in case+ .get("headers")+ .and_then(Value::as_object)+ .into_iter()+ .flatten()+ {+ response.headers_mut().insert(+ HeaderName::from_bytes(header.as_bytes()).unwrap(),+ HeaderValue::from_str(value.as_str().unwrap()).unwrap(),+ );+ }+ let context = ErrorContext {+ first_image: case+ .get("first_image")+ .and_then(Value::as_str)+ .map(str::to_string),+ };+ let translated = anthropic_error_response(response, &context).await;+ let expect = &case["expect"];+ assert_eq!(+ translated.status().as_u16() as u64,+ expect["status"].as_u64().unwrap(),+ "{name}"+ );+ assert_eq!(+ translated.headers()["content-type"],+ "application/json",+ "{name}"+ );+ for (header, value) in expect+ .get("headers")+ .and_then(Value::as_object)+ .into_iter()+ .flatten()+ {+ assert_eq!(+ translated+ .headers()+ .get(header.as_str())+ .map(|v| v.to_str().unwrap()),+ value.as_str(),+ "{name}: {header}"+ );+ }+ for header in expect+ .get("absent_headers")+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ {+ assert!(+ translated.headers().get(header.as_str().unwrap()).is_none(),+ "{name}: {header}"+ );+ }+ let body = json_body(translated).await;+ assert_eq!(body["type"], "error", "{name}");+ assert_eq!(body["error"]["type"], expect["type"], "{name}");+ assert_eq!(body["error"]["message"], expect["message"], "{name}");+ assert_eq!(+ body["request_id"],+ expect.get("request_id").cloned().unwrap_or(Value::Null),+ "{name}"+ );+ }+}++#[tokio::test]+async fn an_inner_error_keeps_its_response_extensions() {+ let mut response = Response::new(Body::from(+ json!({"error": {"message": "failed", "type": "server_error", "param": null, "code": "x"}})+ .to_string(),+ ));+ *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;+ let response = crate::http_error::GatewayOwnedFault::new("stage").mark(response);+ let translated = anthropic_error_response(response, &ErrorContext::default()).await;+ assert_eq!(+ translated+ .extensions()+ .get::<crate::http_error::GatewayOwnedFault>()+ .map(|fault| fault.stage),+ Some("stage")+ );+}++#[derive(Clone, Copy)]+enum Step {+ Role,+ Text(&'static str),+ Reasoning,+ ToolStart(u64),+ ToolArgs(u64),+ Finish(&'static str),+ Usage,+ Error,+ Done,+}++fn step_frame(step: Step) -> String {+ let chunk = |delta: Value, finish: Value| {+ json!({"choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}).to_string()+ };+ match step {+ Step::Role => chunk(json!({"role": "assistant"}), Value::Null),+ Step::Text(text) => chunk(json!({"content": text}), Value::Null),+ Step::Reasoning => chunk(json!({"reasoning_content": "r"}), Value::Null),+ Step::ToolStart(index) => chunk(+ json!({"tool_calls": [{"index": index, "id": format!("c{index}"), "type": "function", "function": {"name": "f", "arguments": ""}}]}),+ Value::Null,+ ),+ Step::ToolArgs(index) => chunk(+ json!({"tool_calls": [{"index": index, "function": {"arguments": "{}"}}]}),+ Value::Null,+ ),+ Step::Finish(reason) => chunk(json!({}), json!(reason)),+ Step::Usage => json!({"choices": [], "usage": {"prompt_tokens": 3, "completion_tokens": 2, "total_tokens": 5}}).to_string(),+ Step::Error => json!({"choices": [], "error": {"message": "m", "type": "server_error", "param": null, "code": "RESOURCE_EXHAUSTED"}}).to_string(),+ Step::Done => "[DONE]".to_string(),+ }+}++/// Every event sequence starts with `message_start`, opens one block at a+/// time with contiguous indices, sends deltas only to the open block with the+/// block's delta type, and ends with `message_delta` then `message_stop`, or+/// with one `error` event, and nothing after.+fn assert_event_grammar(events: &[Value], context: &str) {+ assert_eq!(events[0]["event"], "message_start", "{context}");+ let mut open: Option<(u64, String)> = None;+ let mut next_index = 0;+ let mut ended = false;+ for (position, event) in events.iter().enumerate().skip(1) {+ assert!(!ended, "{context}: event after the end at {position}");+ let data = &event["data"];+ match event["event"].as_str().unwrap() {+ "content_block_start" => {+ assert!(open.is_none(), "{context}: two open blocks");+ assert_eq!(data["index"], next_index, "{context}");+ next_index += 1;+ open = Some((+ data["index"].as_u64().unwrap(),+ data["content_block"]["type"].as_str().unwrap().to_string(),+ ));+ }+ "content_block_delta" => {+ let (index, kind) = open.clone().expect("delta without an open block");+ assert_eq!(data["index"], index, "{context}");+ let delta = data["delta"]["type"].as_str().unwrap();+ let allowed: &[&str] = match kind.as_str() {+ "text" => &["text_delta"],+ "thinking" => &["thinking_delta", "signature_delta"],+ _ => &["input_json_delta"],+ };+ assert!(allowed.contains(&delta), "{context}: {delta} in {kind}");+ }+ "content_block_stop" => {+ let (index, _) = open.take().expect("stop without an open block");+ assert_eq!(data["index"], index, "{context}");+ }+ "message_delta" => {+ assert!(+ open.is_none(),+ "{context}: message_delta with an open block"+ );+ assert_eq!(events[position + 1]["event"], "message_stop", "{context}");+ }+ "message_stop" => ended = true,+ "error" => ended = true,+ "ping" => {}+ other => panic!("{context}: unexpected event {other}"),+ }+ }+ assert!(ended, "{context}: no terminal event");+}++#[test]+fn any_chat_chunk_sequence_yields_a_valid_event_grammar() {+ let alphabet = [+ Step::Role,+ Step::Text("a"),+ Step::Text(" "),+ Step::Text("\n"),+ Step::Reasoning,+ Step::ToolStart(0),+ Step::ToolStart(1),+ Step::ToolArgs(0),+ Step::ToolArgs(1),+ Step::Finish("stop"),+ Step::Finish("tool_calls"),+ Step::Finish("length"),+ Step::Usage,+ Step::Error,+ Step::Done,+ ];+ let mut seed: u64 = 0x9e37_79b9_7f4a_7c15;+ for round in 0..4000 {+ let length = (round % 12) + 1;+ let mut steps = Vec::with_capacity(length);+ for _ in 0..length {+ seed ^= seed << 13;+ seed ^= seed >> 7;+ seed ^= seed << 17;+ steps.push(alphabet[(seed % alphabet.len() as u64) as usize]);+ }+ let mut machine = StreamMachine::new("msg_x".to_string(), "m".to_string());+ let mut events = machine.start();+ for step in &steps {+ events.extend(machine.on_data(&step_frame(*step)));+ }+ events.extend(machine.on_end());+ let events: Vec<Value> = events+ .iter()+ .map(|event| json!({"event": event.name, "data": event.data}))+ .collect();+ assert_event_grammar(&events, &format!("round {round}"));+ }+}++#[tokio::test]+async fn a_silent_stream_sends_pings_until_output_arrives() {+ let (sender, receiver) = tokio::sync::mpsc::channel::<Result<Bytes, std::io::Error>>(4);+ let inner = Body::from_stream(tokio_stream::wrappers::ReceiverStream::new(receiver));+ let body = stream_body(+ inner,+ StreamMachine::new("msg_p".to_string(), "m".to_string()),+ Duration::from_millis(20),+ );+ tokio::spawn(async move {+ tokio::time::sleep(Duration::from_millis(150)).await;+ for frame in [+ json!({"choices": [{"index": 0, "delta": {"content": "x"}, "finish_reason": "stop"}]})+ .to_string(),+ json!({"choices": [], "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}})+ .to_string(),+ "[DONE]".to_string(),+ ] {+ sender+ .send(Ok(Bytes::from(format!("data: {frame}\n\n"))))+ .await+ .unwrap();+ }+ });+ let events = parse_events(&to_bytes(body, usize::MAX).await.unwrap());+ let names = event_names(&events);+ assert_eq!(names[0], "message_start");+ let pings = names.iter().filter(|name| *name == "ping").count();+ assert!(pings >= 2, "{names:?}");+ let first_block = names+ .iter()+ .position(|name| name == "content_block_start")+ .unwrap();+ assert!(names[..first_block]+ .iter()+ .skip(1)+ .all(|name| name == "ping"));+ assert_eq!(names.last().unwrap(), "message_stop");+}++struct DropFlag(Arc<AtomicBool>);++impl Drop for DropFlag {+ fn drop(&mut self) {+ self.0.store(true, Ordering::SeqCst);+ }+}++#[tokio::test]+async fn an_error_event_ends_the_body_and_drops_the_chat_body() {+ let dropped = Arc::new(AtomicBool::new(false));+ let flag = DropFlag(Arc::clone(&dropped));+ let malformed = futures_util::stream::iter([Ok::<Bytes, std::io::Error>(Bytes::from_static(+ b"data: {not json\n\n",+ ))]);+ let inner_stream = malformed+ .chain(futures_util::stream::pending())+ .map(move |item| {+ let _keep = &flag;+ item+ });+ let body = stream_body(+ Body::from_stream(inner_stream.boxed()),+ StreamMachine::new("msg_e".to_string(), "m".to_string()),+ Duration::from_secs(60),+ );+ let collected = tokio::time::timeout(Duration::from_secs(5), to_bytes(body, usize::MAX))+ .await+ .expect("the body ends after the error event")+ .unwrap();+ assert_eq!(+ event_names(&parse_events(&collected)),+ ["message_start", "error"]+ );+ assert!(dropped.load(Ordering::SeqCst));+}++#[tokio::test]+async fn dropping_the_messages_body_drops_the_chat_body() {+ let dropped = Arc::new(AtomicBool::new(false));+ let flag = DropFlag(Arc::clone(&dropped));+ let inner_stream =+ futures_util::stream::pending::<Result<Bytes, std::io::Error>>().map(move |item| {+ let _keep = &flag;+ item+ });+ let body = stream_body(+ Body::from_stream(inner_stream.boxed()),+ StreamMachine::new("msg_d".to_string(), "m".to_string()),+ Duration::from_secs(60),+ );+ let mut data = body.into_data_stream();+ let first = data.next().await.unwrap().unwrap();+ assert!(String::from_utf8_lossy(&first).starts_with("event: message_start"));+ assert!(!dropped.load(Ordering::SeqCst));+ drop(data);+ assert!(dropped.load(Ordering::SeqCst));+}++async fn chat_gateway(models: &[&str], loaded: &[&str]) -> TestGateway {+ let gateway = TestGateway::new(models).await;+ gateway+ .add_verified_worker("local-1", LOCAL_LANE, loaded)+ .await;+ gateway+}++#[tokio::test]+async fn a_buffered_message_is_served_by_the_chat_route() {+ let gateway = chat_gateway(&[HYBRID_GENERATE_MODEL], &["acme/chat"]).await;+ let response = proxy_messages(+ State(Arc::clone(&gateway.state)),+ messages_request(json!({+ "model": "acme/chat",+ "max_tokens": 16,+ "metadata": {"user_id": "opaque"},+ "system": [{"type": "text", "text": "Be brief.", "cache_control": {"type": "ephemeral"}}],+ "messages": [{"role": "user", "content": [{"type": "text", "text": "hi", "cache_control": {"type": "ephemeral"}}]}],+ })),+ )+ .await;+ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(response.headers()["request-id"], "request-1");+ assert_eq!(response.headers()["x-sie-request-id"], "request-1");+ let body = json_body(response).await;+ assert_eq!(+ body,+ json!({+ "id": "msg_request-1",+ "type": "message",+ "role": "assistant",+ "model": "acme/chat",+ "content": [{"type": "text", "text": "ok"}],+ "stop_reason": "end_turn",+ "stop_sequence": null,+ "usage": {"input_tokens": 1, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "output_tokens": 1},+ })+ );+ let dispatched = gateway.dispatcher.dispatched();+ assert_eq!(dispatched.len(), 1);+ assert_eq!(dispatched[0].endpoint, "generate");+ assert_eq!(dispatched[0].model, "acme/chat");+}++#[tokio::test]+async fn a_streamed_message_is_served_by_the_chat_route() {+ let gateway = chat_gateway(&[HYBRID_GENERATE_MODEL], &["acme/chat"]).await;+ let response = proxy_messages(+ State(Arc::clone(&gateway.state)),+ messages_request(json!({+ "model": "acme/chat",+ "max_tokens": 16,+ "stream": true,+ "thinking": {"type": "adaptive"},+ "messages": [{"role": "user", "content": "hi"}],+ })),+ )+ .await;+ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(response.headers()["content-type"], "text/event-stream");+ assert_eq!(response.headers()["request-id"], "request-1");+ let events = events_of(response).await;+ assert_eq!(+ event_names(&events),+ [+ "message_start",+ "content_block_start",+ "content_block_delta",+ "content_block_stop",+ "message_delta",+ "message_stop"+ ]+ );+ assert_eq!(events[0]["data"]["message"]["id"], "msg_request-1");+ assert_eq!(events[2]["data"]["delta"]["text"], "ok");+ assert_eq!(+ events[4]["data"]["usage"],+ json!({"input_tokens": 1, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "output_tokens": 1})+ );+ assert_eq!(events[4]["data"]["delta"]["stop_reason"], "end_turn");+}++#[tokio::test]+async fn a_worker_failure_after_output_is_an_error_event() {+ let gateway = chat_gateway(&[HYBRID_GENERATE_MODEL], &["acme/chat"]).await;+ gateway.dispatcher.fail_stream(true);+ let response = proxy_messages(+ State(Arc::clone(&gateway.state)),+ messages_request(json!({+ "model": "acme/chat",+ "max_tokens": 16,+ "stream": true,+ "messages": [{"role": "user", "content": "hi"}],+ })),+ )+ .await;+ assert_eq!(response.status(), StatusCode::OK);+ let events = events_of(response).await;+ assert_eq!(+ event_names(&events),+ [+ "message_start",+ "content_block_start",+ "content_block_delta",+ "error"+ ]+ );+ assert_eq!(events[3]["data"]["error"]["type"], "api_error");+}++#[tokio::test]+async fn chat_refusals_come_back_in_the_anthropic_envelope() {+ let gateway = chat_gateway(+ &[HYBRID_GENERATE_MODEL, CODER_MODEL],+ &["acme/chat", "acme/coder"],+ )+ .await;+ let cases = [+ (+ json!({"model": "acme/missing", "max_tokens": 16, "messages": [{"role": "user", "content": "hi"}]}),+ StatusCode::NOT_FOUND,+ "not_found_error",+ None,+ ),+ (+ json!({"model": "acme/chat", "max_tokens": 16, "tools": [{"name": "t", "input_schema": {"type": "object"}}], "messages": [{"role": "user", "content": "hi"}]}),+ StatusCode::BAD_REQUEST,+ "invalid_request_error",+ Some("tools: Model 'acme/chat' does not support tool calling"),+ ),+ (+ json!({"model": "acme/coder", "max_tokens": 100, "messages": [{"role": "user", "content": "hi"}]}),+ StatusCode::BAD_REQUEST,+ "invalid_request_error",+ Some("max_tokens: 100 > 64, which is the maximum allowed number of output tokens for this model"),+ ),+ (+ json!({"model": "acme/chat", "max_tokens": 16, "messages": [{"role": "user", "content": [{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="}}]}]}),+ StatusCode::BAD_REQUEST,+ "invalid_request_error",+ Some("messages.0.content.0.image: Model 'acme/chat' does not support image input"),+ ),+ ];+ for (body, status, error_type, message) in cases {+ let response = proxy_messages(+ State(Arc::clone(&gateway.state)),+ messages_request(body.clone()),+ )+ .await;+ assert_eq!(response.status(), status, "{body}");+ let answer = json_body(response).await;+ assert_eq!(answer["type"], "error", "{body}");+ assert_eq!(answer["error"]["type"], error_type, "{body}");+ if let Some(message) = message {+ assert_eq!(answer["error"]["message"], message, "{body}");+ }+ }+ assert!(gateway.dispatcher.dispatched().is_empty());+}++#[tokio::test]+async fn a_tool_request_on_a_tool_model_is_dispatched() {+ let gateway = chat_gateway(&[CODER_MODEL], &["acme/coder"]).await;+ let response = proxy_messages(+ State(Arc::clone(&gateway.state)),+ messages_request(json!({+ "model": "acme/coder",+ "max_tokens": 64,+ "tools": [{"name": "Read", "input_schema": {"type": "object", "properties": {"file_path": {"type": "string"}}}}],+ "tool_choice": {"type": "auto"},+ "messages": [{"role": "user", "content": "read it"}],+ })),+ )+ .await;+ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(gateway.dispatcher.dispatched().len(), 1);+}++#[tokio::test]+async fn a_translation_refusal_publishes_nothing() {+ let gateway = chat_gateway(&[HYBRID_GENERATE_MODEL], &["acme/chat"]).await;+ let response = proxy_messages(+ State(Arc::clone(&gateway.state)),+ messages_request(json!({+ "model": "acme/chat",+ "max_tokens": 16,+ "output_config": {"effort": "high"},+ "messages": [{"role": "user", "content": "hi"}],+ })),+ )+ .await;+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+ assert_eq!(response.headers()["x-sie-error-code"], "INVALID_REQUEST");+ let body = json_body(response).await;+ assert_eq!(+ body,+ json!({+ "type": "error",+ "error": {"type": "invalid_request_error", "message": "output_config.effort: Extra inputs are not permitted"},+ "request_id": null,+ })+ );+ assert!(gateway.dispatcher.dispatched().is_empty());+}++#[tokio::test]+async fn a_publish_failure_is_an_overloaded_error() {+ let gateway = chat_gateway(&[HYBRID_GENERATE_MODEL], &["acme/chat"]).await;+ gateway.dispatcher.refuse_generation();+ for stream in [false, true] {+ let response = proxy_messages(+ State(Arc::clone(&gateway.state)),+ messages_request(json!({+ "model": "acme/chat",+ "max_tokens": 16,+ "stream": stream,+ "messages": [{"role": "user", "content": "hi"}],+ })),+ )+ .await;+ assert_eq!(+ response.status(),+ StatusCode::SERVICE_UNAVAILABLE,+ "stream={stream}"+ );+ let body = json_body(response).await;+ assert_eq!(body["error"]["type"], "overloaded_error", "stream={stream}");+ }+}++#[tokio::test]+async fn the_router_serves_messages_and_renders_its_refusals() {+ let gateway = chat_gateway(&[HYBRID_GENERATE_MODEL], &["acme/chat"]).await;+ let mut config = (*gateway.state.config).clone();+ config.auth_mode = "token".to_string();+ config.auth_tokens = vec!["secret".to_string()];+ let router = crate::server::create_router(Arc::clone(&gateway.state), Arc::new(config));+ let body = json!({"model": "acme/chat", "max_tokens": 16, "messages": [{"role": "user", "content": "hi"}]});++ let unauthenticated = router+ .clone()+ .oneshot(messages_request(body.clone()))+ .await+ .unwrap();+ assert_eq!(unauthenticated.status(), StatusCode::UNAUTHORIZED);+ assert_eq!(+ json_body(unauthenticated).await["error"]["type"],+ "authentication_error"+ );++ let authorized = |method: Method, uri: &str, body: Value| {+ Request::builder()+ .method(method)+ .uri(uri)+ .header("authorization", "Bearer secret")+ .header("content-type", "application/json")+ .body(Body::from(body.to_string()))+ .unwrap()+ };+ let served = router+ .clone()+ .oneshot(authorized(+ Method::POST,+ "/v1/messages?beta=true",+ body.clone(),+ ))+ .await+ .unwrap();+ assert_eq!(served.status(), StatusCode::OK);+ assert_eq!(json_body(served).await["content"][0]["text"], "ok");++ let count = router+ .clone()+ .oneshot(authorized(+ Method::POST,+ "/v1/messages/count_tokens",+ body.clone(),+ ))+ .await+ .unwrap();+ assert_eq!(count.status(), StatusCode::NOT_FOUND);+ assert_eq!(json_body(count).await["error"]["type"], "not_found_error");++ let wrong_method = router+ .clone()+ .oneshot(authorized(Method::GET, "/v1/messages", Value::Null))+ .await+ .unwrap();+ assert_eq!(wrong_method.status(), StatusCode::METHOD_NOT_ALLOWED);+ assert_eq!(+ json_body(wrong_method).await["error"]["type"],+ "invalid_request_error"+ );++ let other = router+ .oneshot(authorized(Method::POST, "/v1/unknown", body))+ .await+ .unwrap();+ assert_eq!(other.status(), StatusCode::NOT_FOUND);+ let other_body = to_bytes(other.into_body(), usize::MAX).await.unwrap();+ assert!(+ serde_json::from_slice::<Value>(&other_body)+ .map_or(true, |value| value.get("type") != Some(&json!("error"))),+ "only the Messages paths take the Anthropic envelope"+ );+}++#[test]+fn dispatch_inputs_compose_the_translation_with_the_chat_seam() {+ let (model, params) = messages_dispatch_inputs(&json!({+ "model": "acme/chat",+ "max_tokens": 48,+ "messages": [{"role": "user", "content": "hi"}],+ }))+ .unwrap();+ assert_eq!(model, "acme/chat");+ assert_eq!(params.generate.as_ref().unwrap().max_new_tokens, 48);+ let refused = messages_dispatch_inputs(&json!({"model": "acme/chat"})).unwrap_err();+ assert_eq!(refused.status(), StatusCode::BAD_REQUEST);+}++#[tokio::test]+async fn an_oversized_body_is_request_too_large() {+ let gateway = chat_gateway(&[HYBRID_GENERATE_MODEL], &["acme/chat"]).await;+ let padding = "x".repeat(super::MAX_MESSAGES_BODY + 1);+ let response = proxy_messages(+ State(Arc::clone(&gateway.state)),+ Request::builder()+ .method(Method::POST)+ .uri("/v1/messages")+ .body(Body::from(padding))+ .unwrap(),+ )+ .await;+ assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE);+ assert_eq!(+ json_body(response).await["error"]["type"],+ "request_too_large"+ );+}diff --git a/packages/sie_gateway/src/handlers/mod.rs b/packages/sie_gateway/src/handlers/mod.rsindex a4f52cd2c..c2fd04dc3 100644--- a/packages/sie_gateway/src/handlers/mod.rs+++ b/packages/sie_gateway/src/handlers/mod.rs@@ -2,6 +2,7 @@ pub mod audio;pub mod config_api;pub mod grammar;pub mod health;+pub mod messages;pub mod models;pub mod pools;pub mod proxy;diff --git a/packages/sie_gateway/src/middleware/metrics.rs b/packages/sie_gateway/src/middleware/metrics.rsindex 00edce296..4db1c5b7d 100644--- a/packages/sie_gateway/src/middleware/metrics.rs+++ b/packages/sie_gateway/src/middleware/metrics.rs@@ -332,7 +332,7 @@ fn classify_endpoint(path: &str) -> Option<&'static str> {} else if path.starts_with("/v1/generate/")|| matches!(path,- "/v1/chat/completions" | "/v1/completions" | "/v1/responses"+ "/v1/chat/completions" | "/v1/completions" | "/v1/responses" | "/v1/messages"){Some("generate")@@ -890,6 +890,8 @@ mod tests {assert_eq!(classify_endpoint("/v1/chat/completions"), Some("generate"));assert_eq!(classify_endpoint("/v1/completions"), Some("generate"));assert_eq!(classify_endpoint("/v1/responses"), Some("generate"));+ assert_eq!(classify_endpoint("/v1/messages"), Some("generate"));+ assert_eq!(classify_endpoint("/v1/messages/count_tokens"), None);assert_eq!(classify_endpoint("/v1/chat/completions/extra"), None);assert_eq!(classify_endpoint("/v1/embeddings"), Some("embeddings"));assert_eq!(classify_endpoint("/v1/moderations"), Some("moderations"));diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rsindex bb021a03a..7527b8218 100644--- a/packages/sie_gateway/src/openapi.rs+++ b/packages/sie_gateway/src/openapi.rs@@ -60,6 +60,7 @@ static OPENAPI_JSON: LazyLock<String> = LazyLock::new(|| {crate::handlers::proxy::proxy_chat,crate::handlers::proxy::proxy_completions,crate::handlers::proxy::proxy_responses,+ crate::handlers::messages::proxy_messages,crate::handlers::proxy::proxy_moderations,docs_ui),@@ -149,6 +150,12 @@ static OPENAPI_JSON: LazyLock<String> = LazyLock::new(|| {ResponsesRequest,OpenAIErrorBody,OpenAIErrorEnvelope,+ crate::handlers::messages::schema::MessagesRequest,+ crate::handlers::messages::schema::EmptyOutputConfig,+ crate::handlers::messages::schema::MessagesResponse,+ crate::handlers::messages::schema::MessagesUsage,+ crate::handlers::messages::schema::AnthropicErrorBody,+ crate::handlers::messages::schema::AnthropicErrorEnvelope,PoolListResponse,crate::types::pool::PoolSpec,crate::types::pool::PoolStatus,@@ -1438,6 +1445,7 @@ fn inject_remote_control_header(paths: &mut serde_json::Map<String, Value>) {"/v1/chat/completions","/v1/completions","/v1/responses",+ "/v1/messages","/v1/audio/transcriptions",] {let Some(operation) = paths@@ -1537,7 +1545,12 @@ fn inject_inference_response_headers(paths: &mut serde_json::Map<String, Value>)}}- for path in ["/v1/chat/completions", "/v1/completions", "/v1/responses"] {+ for path in [+ "/v1/chat/completions",+ "/v1/completions",+ "/v1/responses",+ "/v1/messages",+ ] {let Some(responses) = paths.get_mut(path).and_then(|path_item| path_item.get_mut("post"))@@ -3906,6 +3919,7 @@ mod tests {("/v1/chat/completions", &["post"][..]),("/v1/completions", &["post"][..]),("/v1/responses", &["post"][..]),+ ("/v1/messages", &["post"][..]),("/v1/moderations", &["post"][..]),("/v1/rerank", &["post"][..]),("/v2/rerank", &["post"][..]),@@ -4151,6 +4165,7 @@ mod tests {"/v1/chat/completions","/v1/completions","/v1/responses",+ "/v1/messages",] {let retryable_503_headers = &spec["paths"][path]["post"]["responses"]["503"]["headers"];assert!(@@ -4189,7 +4204,12 @@ mod tests {"/v1/embeddings 200 missing documented {name} header");}- for path in ["/v1/chat/completions", "/v1/completions", "/v1/responses"] {+ for path in [+ "/v1/chat/completions",+ "/v1/completions",+ "/v1/responses",+ "/v1/messages",+ ] {let headers = &spec["paths"][path]["post"]["responses"]["200"]["headers"];for name in ["X-SIE-Request-Id",diff --git a/packages/sie_gateway/src/server.rs b/packages/sie_gateway/src/server.rsindex c5cebd3f5..005688b32 100644--- a/packages/sie_gateway/src/server.rs+++ b/packages/sie_gateway/src/server.rs@@ -6,7 +6,7 @@ use std::sync::Arc;use std::time::{Duration, SystemTime, UNIX_EPOCH};use crate::config::Config;-use crate::handlers::{audio, config_api, health, models, pools, proxy};+use crate::handlers::{audio, config_api, health, messages, models, pools, proxy};use crate::middleware::audit::AuditLayer;use crate::middleware::auth::AuthLayer;use crate::middleware::metrics::apply_request_telemetry;@@ -640,6 +640,8 @@ pub fn create_router_core(.route("/v1/completions", post(proxy::proxy_completions))// OpenAI Responses API (MVP: string input, non-streaming)..route("/v1/responses", post(proxy::proxy_responses))+ // Anthropic Messages API, translated onto chat completions.+ .route("/v1/messages", post(messages::proxy_messages))// OpenAI moderations surface — registered but not implemented (501)// until a moderation model + governance store land (Tier 0)..route("/v1/moderations", post(proxy::proxy_moderations))@@ -654,7 +656,12 @@ pub fn create_router_core(AuditPlacement::Composition => router,};- router.layer(AuthLayer::new(config)).with_state(state)+ router+ .layer(AuthLayer::new(config))+ .layer(axum::middleware::from_fn(+ messages::anthropic_error_envelope,+ ))+ .with_state(state)}#[cfg(test)]