Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

feat(agents): define the OpenAPI REST contract (#2969)

Jiaqiang Wong5be1f1064f69
diff --git a/apps/api/src/mcp/mcp-tools.spec.ts b/apps/api/src/mcp/mcp-tools.spec.ts
index bc413963e..7a0152f08 100644
--- a/apps/api/src/mcp/mcp-tools.spec.ts
+++ b/apps/api/src/mcp/mcp-tools.spec.ts
@@ -198,6 +198,15 @@ describe('McpTools.register', () => {
* someone decides whether OAuth callers may reach it.
*/
const API_KEY_ONLY = [
+ 'createAgent',
+ 'getAgent',
+ 'getAgentTurn',
+ 'closeAgent',
+ 'sendAgentTurn',
+ 'getAgentEvents',
+ 'respondAgentRequest',
+ 'steerAgentTurn',
+ 'interruptAgentTurn',
'enableSsh',
'configureSsh',
'exportBox',
diff --git a/docs/contributing/investigations/2026-10-28-agent-rest-api-design.md b/docs/contributing/investigations/2026-10-28-agent-rest-api-design.md
index 8f6530353..1a736ae1c 100644
--- a/docs/contributing/investigations/2026-10-28-agent-rest-api-design.md
+++ b/docs/contributing/investigations/2026-10-28-agent-rest-api-design.md
@@ -2,8 +2,13 @@
Expose Box-owned agents and turns through nine HTTP operations, with shared snapshots, resumable events and explicit control actions.
+The [REST implementation design](2026-11-17-agent-rest-implementation.md) supersedes
+the close and interrupt responses below: both return HTTP 204 without a snapshot.
+
## Details
+> **Superseded decisions:** [#2672](https://github.com/boxlite-ai/boxlite/issues/2672) replaces this investigation’s journal replay, `410 cursor_expired`, server-side retry store, and `422` retry-conflict contract. The adapter owns cursor and retry support; BoxLite forwards both and rejects unsupported capabilities. The remaining sections are historical design context.
+
This is a REST contract design for [the agent API](../../reference/agents.md)
and [tracking issue #2140](https://github.com/boxlite-ai/boxlite/issues/2140).
This PR adds no HTTP handlers, OpenAPI paths or REST client implementation.
diff --git a/docs/reference/agents.md b/docs/reference/agents.md
index 952adaa5b..c49b9a765 100644
--- a/docs/reference/agents.md
+++ b/docs/reference/agents.md
@@ -195,7 +195,12 @@ These records define SDK data types. The
[REST design](../contributing/investigations/2026-10-28-agent-rest-api-design.md)
maps them to nine HTTP operations, including snapshot reads, resumable events,
steering and typed replies. It also defines cached getter behavior and retry
-headers. Agent HTTP routes and REST client support are unavailable.
+headers. The OpenAPI contract specifies nine agent HTTP operations, retry-key forwarding,
+SSE events, and HTTP 204 close/interrupt responses. Runtime routes and the REST
+client are unavailable. The OpenAPI components
+define strict request objects and additive response records, including fractional
+retention durations; implementations must validate known response fields while
+accepting additional server fields.
### Go JSON mapping
diff --git a/make/test.mk b/make/test.mk
index 3b4b091f1..210be6adf 100644
--- a/make/test.mk
+++ b/make/test.mk
@@ -576,6 +576,7 @@ test\:unit\:gvproxy:
# error mapping checks. The server target supplies its own Python dependencies.
test\:unit\:openapi:
@$(MAKE) test:unit:openapi:server
+ @. .venv/bin/activate && uv run --with pyyaml --with jsonschema --python .venv/bin/python python -m unittest discover -s openapi/tests -p 'test_*.py' -v
@echo "🧪 Running OpenAPI reference-server unit tests..."
@python3 -m unittest discover -s openapi/reference-server/tests -p 'test_error*.py' -v
diff --git a/openapi/box.openapi.yaml b/openapi/box.openapi.yaml
index f8ea0a3a2..c33ebf418 100644
--- a/openapi/box.openapi.yaml
+++ b/openapi/box.openapi.yaml
@@ -143,6 +143,8 @@ tags:
description: Credential validation and identity lookup
- name: Boxes
description: Box lifecycle management
+ - name: Agents
+ description: Agent conversations and tasks
- name: Execution
description: Command execution and streaming
- name: Files
@@ -1412,6 +1414,276 @@ paths:
schema:
$ref: "#/components/schemas/ErrorResponse"
+ /{prefix}/boxes/{box_id}/agents:
+ parameters:
+ - $ref: "#/components/parameters/prefix"
+ - $ref: "#/components/parameters/boxId"
+ post:
+ operationId: createAgent
+ tags: [Agents]
+ summary: Create an agent
+ description: |
+ Forward creation to the adapter. An empty prefix, as in boxlite serve,
+ removes that segment: /v1/boxes/{box_id}/agents.
+ parameters:
+ - $ref: "#/components/parameters/agentIdempotencyKey"
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/AgentCreateRequest"
+ example: {agent: opencode, options: {cwd: /workspace, config: {model: provider/model}}}
+ responses:
+ "201":
+ description: Agent created
+ headers:
+ Location:
+ description: URL of the created agent
+ schema: {type: string}
+ example: /v1/boxes/box_1/agents/ses_01
+ content:
+ application/json:
+ schema: {$ref: "#/components/schemas/AgentResource"}
+ example: &agentExample
+ id: ses_01
+ agent: opencode
+ state: null
+ config: {tools: [], mcp: [], model: provider/model}
+ capabilities: {operations: [agents.create, agents.get], input_kinds: [text], max_queued_turns: null, max_pending_steering: null, idempotency_retention_seconds: null}
+ "400": {$ref: "#/components/responses/AgentBadRequest"}
+ "401": {$ref: "#/components/responses/AgentUnauthorized"}
+ "404": {$ref: "#/components/responses/AgentNotFound"}
+ "503": {$ref: "#/components/responses/AgentUnavailable"}
+
+ /{prefix}/boxes/{box_id}/agents/{agent_id}:
+ parameters:
+ - $ref: "#/components/parameters/prefix"
+ - $ref: "#/components/parameters/boxId"
+ - $ref: "#/components/parameters/agentId"
+ get:
+ operationId: getAgent
+ tags: [Agents]
+ summary: Get an agent
+ description: A missing agent or an agent belonging to another Box returns 404.
+ responses:
+ "200":
+ description: Agent snapshot
+ content:
+ application/json:
+ schema: {$ref: "#/components/schemas/AgentResource"}
+ example: *agentExample
+ "400": {$ref: "#/components/responses/AgentBadRequest"}
+ "401": {$ref: "#/components/responses/AgentUnauthorized"}
+ "404": {$ref: "#/components/responses/AgentNotFound"}
+ "503": {$ref: "#/components/responses/AgentUnavailable"}
+
+ /{prefix}/boxes/{box_id}/agents/{agent_id}/close:
+ parameters:
+ - $ref: "#/components/parameters/prefix"
+ - $ref: "#/components/parameters/boxId"
+ - $ref: "#/components/parameters/agentId"
+ post:
+ operationId: closeAgent
+ tags: [Agents]
+ summary: Close an agent
+ description: Success means the adapter confirmed the agent loop stopped.
+ parameters:
+ - $ref: "#/components/parameters/agentIdempotencyKey"
+ requestBody:
+ content:
+ application/json:
+ schema: {$ref: "#/components/schemas/AgentEmptyRequest"}
+ example: {}
+ responses:
+ "204":
+ description: Agent closed
+ "400": {$ref: "#/components/responses/AgentCloseBadRequest"}
+ "401": {$ref: "#/components/responses/AgentUnauthorized"}
+ "404": {$ref: "#/components/responses/AgentNotFound"}
+ "409": {$ref: "#/components/responses/AgentConflict"}
+ "503": {$ref: "#/components/responses/AgentUnavailable"}
+
+ /{prefix}/boxes/{box_id}/agents/{agent_id}/turns:
+ parameters:
+ - $ref: "#/components/parameters/prefix"
+ - $ref: "#/components/parameters/boxId"
+ - $ref: "#/components/parameters/agentId"
+ post:
+ operationId: sendAgentTurn
+ tags: [Agents]
+ summary: Send text to an agent
+ parameters:
+ - $ref: "#/components/parameters/agentIdempotencyKey"
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema: {$ref: "#/components/schemas/AgentSendRequest"}
+ example: {text: Review the change, options: {mode: queue}}
+ responses:
+ "201":
+ description: Turn accepted
+ headers:
+ Location:
+ description: URL of the created turn
+ schema: {type: string}
+ example: /v1/boxes/box_1/agents/ses_01/turns/msg_01
+ content:
+ application/json:
+ schema: {$ref: "#/components/schemas/AgentTurnState"}
+ example: &turnExample {id: msg_01, agent_id: ses_01, status: queued, cursor: null, result: null, requests: [], steering: []}
+ "400": {$ref: "#/components/responses/AgentBadRequest"}
+ "401": {$ref: "#/components/responses/AgentUnauthorized"}
+ "404": {$ref: "#/components/responses/AgentNotFound"}
+ "409": {$ref: "#/components/responses/AgentConflict"}
+ "429": {$ref: "#/components/responses/AgentExhausted"}
+ "503": {$ref: "#/components/responses/AgentUnavailable"}
+
+ /{prefix}/boxes/{box_id}/agents/{agent_id}/events:
+ parameters:
+ - $ref: "#/components/parameters/prefix"
+ - $ref: "#/components/parameters/boxId"
+ - $ref: "#/components/parameters/agentId"
+ get:
+ operationId: getAgentEvents
+ tags: [Agents]
+ summary: Stream agent events
+ description: |
+ Send 200 headers only after the adapter stream connects. Last-Event-ID
+ takes precedence over after. Adapters without cursor or turn event
+ support reject those options with 400. Emit an SSE id only for a
+ non-null cursor. After opening, stream errors as an error event and close.
+ parameters:
+ - {name: turn_id, in: query, schema: {type: string}, example: msg_01}
+ - {name: after, in: query, schema: {type: string}, example: cursor_1}
+ - {name: Last-Event-ID, in: header, schema: {type: string}, example: cursor_1}
+ responses:
+ "200":
+ description: Connected event stream
+ content:
+ text/event-stream:
+ schema: {type: string}
+ example: "event: agent\ndata: {\"cursor\":null,\"agent_id\":\"ses_01\",\"turn_id\":\"msg_01\",\"kind\":\"session.status\",\"data\":{\"status\":\"busy\"}}\n\n"
+ "400": {$ref: "#/components/responses/AgentBadRequest"}
+ "401": {$ref: "#/components/responses/AgentUnauthorized"}
+ "404": {$ref: "#/components/responses/AgentNotFound"}
+ "503": {$ref: "#/components/responses/AgentUnavailable"}
+
+ /{prefix}/boxes/{box_id}/agents/{agent_id}/requests/{request_id}/respond:
+ parameters:
+ - $ref: "#/components/parameters/prefix"
+ - $ref: "#/components/parameters/boxId"
+ - $ref: "#/components/parameters/agentId"
+ - {name: request_id, in: path, required: true, schema: {type: string, minLength: 1}, example: req_01}
+ post:
+ operationId: respondAgentRequest
+ tags: [Agents]
+ summary: Respond to an agent request
+ parameters:
+ - $ref: "#/components/parameters/agentIdempotencyKey"
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema: {$ref: "#/components/schemas/AgentRespondRequest"}
+ example: {response: {type: permission, approved: false}}
+ responses:
+ "200":
+ description: Resulting turn snapshot
+ content:
+ application/json:
+ schema: {$ref: "#/components/schemas/AgentTurnState"}
+ example: *turnExample
+ "400": {$ref: "#/components/responses/AgentBadRequest"}
+ "401": {$ref: "#/components/responses/AgentUnauthorized"}
+ "404": {$ref: "#/components/responses/AgentNotFound"}
+ "409": {$ref: "#/components/responses/AgentConflict"}
+ "503": {$ref: "#/components/responses/AgentUnavailable"}
+
+ /{prefix}/boxes/{box_id}/agents/{agent_id}/turns/{turn_id}/steer:
+ parameters:
+ - $ref: "#/components/parameters/prefix"
+ - $ref: "#/components/parameters/boxId"
+ - $ref: "#/components/parameters/agentId"
+ - $ref: "#/components/parameters/agentTurnId"
+ post:
+ operationId: steerAgentTurn
+ tags: [Agents]
+ summary: Steer a running turn
+ parameters:
+ - $ref: "#/components/parameters/agentIdempotencyKey"
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema: {$ref: "#/components/schemas/AgentSteerRequest"}
+ example: {text: Focus on correctness}
+ responses:
+ "200":
+ description: Steering receipt
+ content:
+ application/json:
+ schema: {$ref: "#/components/schemas/AgentSteeringReceipt"}
+ example: {id: steer_01, turn_id: msg_01, status: accepted}
+ "400": {$ref: "#/components/responses/AgentBadRequest"}
+ "401": {$ref: "#/components/responses/AgentUnauthorized"}
+ "404": {$ref: "#/components/responses/AgentNotFound"}
+ "409": {$ref: "#/components/responses/AgentConflict"}
+ "429": {$ref: "#/components/responses/AgentExhausted"}
+ "503": {$ref: "#/components/responses/AgentUnavailable"}
+
+ /{prefix}/boxes/{box_id}/agents/{agent_id}/turns/{turn_id}/interrupt:
+ parameters:
+ - $ref: "#/components/parameters/prefix"
+ - $ref: "#/components/parameters/boxId"
+ - $ref: "#/components/parameters/agentId"
+ - $ref: "#/components/parameters/agentTurnId"
+ post:
+ operationId: interruptAgentTurn
+ tags: [Agents]
+ summary: Interrupt a turn
+ description: Success means the adapter confirmed the stop.
+ parameters:
+ - $ref: "#/components/parameters/agentIdempotencyKey"
+ requestBody:
+ content:
+ application/json:
+ schema: {$ref: "#/components/schemas/AgentEmptyRequest"}
+ example: {}
+ responses:
+ "204":
+ description: Turn interrupted
+ "400": {$ref: "#/components/responses/AgentBadRequest"}
+ "401": {$ref: "#/components/responses/AgentUnauthorized"}
+ "404": {$ref: "#/components/responses/AgentNotFound"}
+ "409": {$ref: "#/components/responses/AgentConflict"}
+ "503": {$ref: "#/components/responses/AgentUnavailable"}
+
+ /{prefix}/boxes/{box_id}/agents/{agent_id}/turns/{turn_id}:
+ parameters:
+ - $ref: "#/components/parameters/prefix"
+ - $ref: "#/components/parameters/boxId"
+ - $ref: "#/components/parameters/agentId"
+ - $ref: "#/components/parameters/agentTurnId"
+ get:
+ operationId: getAgentTurn
+ tags: [Agents]
+ summary: Get an agent turn
+ description: A turn outside the specified agent or Box returns 404.
+ responses:
+ "200":
+ description: Turn snapshot
+ content:
+ application/json:
+ schema: {$ref: "#/components/schemas/AgentTurnState"}
+ example: {id: msg_01, agent_id: ses_01, status: queued, cursor: null, result: null, requests: [], steering: []}
+ "400": {$ref: "#/components/responses/AgentBadRequest"}
+ "401": {$ref: "#/components/responses/AgentUnauthorized"}
+ "404": {$ref: "#/components/responses/AgentNotFound"}
+ "503": {$ref: "#/components/responses/AgentUnavailable"}
+
+
/{prefix}/domains:
parameters:
- $ref: "#/components/parameters/prefix"
@@ -2081,6 +2353,32 @@ components:
schema:
type: string
+ agentId:
+ name: agent_id
+ in: path
+ required: true
+ schema: {type: string, minLength: 1}
+ example: ses_01
+
+ agentTurnId:
+ name: turn_id
+ in: path
+ required: true
+ schema: {type: string, minLength: 1}
+ example: msg_01
+
+ agentIdempotencyKey:
+ name: Idempotency-Key
+ in: header
+ description: |
+ Opaque visible ASCII key forwarded verbatim to the adapter. BoxLite
+ stores nothing and returns no 422 for conflicting keys. Deduplication
+ and retention are adapter-defined; retention is advertised in
+ capabilities.idempotency_retention_seconds, not GET /v1/config.
+ An adapter that cannot deduplicate rejects the key as unsupported.
+ schema: {type: string, minLength: 1, maxLength: 256, pattern: '^[!-~]+$', not: {pattern: '[^!-~]'}}
+ example: retry-create-1
+
idempotencyKey:
name: Idempotency-Key
in: header
@@ -2099,6 +2397,63 @@ components:
# Responses (Error Templates)
# -------------------------------------------------------------------------
responses:
+ AgentCloseBadRequest:
+ description: Invalid argument or unsupported close operation
+ content:
+ application/json:
+ schema: {$ref: "#/components/schemas/ErrorResponse"}
+ examples:
+ unsupported:
+ value: {error: {message: "agent.close is not supported", type: UnsupportedError, code: unsupported, request_id: req_1}}
+
+ AgentBadRequest:
+ description: Invalid argument or unsupported operation
+ content:
+ application/json:
+ schema: {$ref: "#/components/schemas/ErrorResponse"}
+ examples:
+ invalid:
+ value: {error: {message: "invalid agent options", type: InvalidArgumentError, code: invalid_argument, request_id: req_1}}
+
+ AgentUnauthorized:
+ description: Missing or invalid credentials
+ content:
+ application/json:
+ schema: {$ref: "#/components/schemas/ErrorResponse"}
+ example: {error: {message: "invalid credentials", type: AuthError, code: unauthenticated, request_id: req_1}}
+
+ AgentNotFound:
+ description: Box, agent, turn, or request is missing or belongs to another parent
+ content:
+ application/json:
+ schema: {$ref: "#/components/schemas/ErrorResponse"}
+ example: {error: {message: "agent not found", type: NotFoundError, code: not_found, request_id: req_1}}
+
+ AgentConflict:
+ description: Agent or turn state does not permit the operation, or request is resolved
+ content:
+ application/json:
+ schema: {$ref: "#/components/schemas/ErrorResponse"}
+ example: {error: {message: "invalid agent state", type: InvalidStateError, code: invalid_state, request_id: req_1}}
+
+ AgentExhausted:
+ description: Native queue or steering capacity exhausted
+ content:
+ application/json:
+ schema: {$ref: "#/components/schemas/ErrorResponse"}
+ example: {error: {message: "queue full", type: ResourceExhaustedError, code: resource_exhausted, request_id: req_1}}
+
+ AgentUnavailable:
+ description: Agent unreachable or stop unconfirmed
+ content:
+ application/json:
+ schema: {$ref: "#/components/schemas/ErrorResponse"}
+ examples:
+ network:
+ value: {error: {message: "agent unreachable", type: NetworkError, code: network_unavailable, request_id: req_1}}
+ upstream:
+ value: {error: {message: "agent unavailable", type: UpstreamUnavailableError, code: upstream_unavailable, request_id: req_1}}
+
BadRequestError:
description: Invalid request parameters or body
content:
@@ -2203,6 +2558,199 @@ components:
# Schemas
# -------------------------------------------------------------------------
schemas:
+ AgentEmptyRequest:
+ type: object
+ additionalProperties: false
+
+ AgentSendRequest:
+ type: object
+ additionalProperties: false
+ required: [text]
+ properties:
+ text: {type: string}
+ options:
+ type: object
+ additionalProperties: false
+ properties:
+ mode: {type: string, enum: [queue, reject]}
+ data: {}
+
+ AgentSteerRequest:
+ type: object
+ additionalProperties: false
+ required: [text]
+ properties:
+ text: {type: string}
+
+ AgentRespondRequest:
+ type: object
+ additionalProperties: false
+ required: [response]
+ properties:
+ response:
+ oneOf:
+ - type: object
+ additionalProperties: false
+ required: [type, text]
+ properties:
+ type: {const: answer}
+ text: {type: string}
+ data: {}
+ - type: object
+ additionalProperties: false
+ required: [type, approved]
+ properties:
+ type: {const: permission}
+ approved: {type: boolean}
+
+ AgentCreateRequest:
+ type: object
+ additionalProperties: false
+ required: [agent]
+ properties:
+ agent: {type: string}
+ options:
+ type: object
+ additionalProperties: false
+ properties:
+ cwd: {type: string}
+ config:
+ $ref: "#/components/schemas/AgentConfigInput"
+
+ AgentConfigInput:
+ type: object
+ additionalProperties: false
+ description: Optional null config fields are treated as omitted.
+ properties:
+ model: {type: [string, 'null']}
+ reasoning: {type: [string, 'null']}
+ instructions: {type: [string, 'null']}
+ tools: {type: array, items: {type: string}}
+ mcp: {type: array, items: {type: string}}
+ permissions: {}
+ limits: {}
+ output_schema: {}
+
+ AgentResource:
+ type: object
+ required: [id, agent, state, config, capabilities]
+ properties:
+ id: {type: string}
+ agent: {type: string}
+ state:
+ oneOf:
+ - $ref: "#/components/schemas/AgentState"
+ - {type: 'null'}
+ config: {$ref: "#/components/schemas/AgentConfig"}
+ capabilities: {$ref: "#/components/schemas/AgentCapabilities"}
+
+ AgentState:
+ type: object
+ required: [id, status, cursor, active_turn_id, queued_turn_ids, requests, steering]
+ properties:
+ id: {type: string}
+ status: {type: string, enum: [ready, busy, closing, closed, unknown]}
+ cursor: {type: [string, 'null']}
+ active_turn_id: {type: [string, 'null']}
+ queued_turn_ids: {type: array, items: {type: string}}
+ requests: {type: array, items: {$ref: "#/components/schemas/AgentRequest"}}
+ steering: {type: array, items: {$ref: "#/components/schemas/AgentSteeringReceipt"}}
+
+ AgentTurnState:
+ type: object
+ required: [id, agent_id, status, cursor, result, requests, steering]
+ properties:
+ id: {type: string}
+ agent_id: {type: string}
+ status: {$ref: "#/components/schemas/AgentTurnStatus"}
+ cursor: {type: [string, 'null']}
+ result:
+ oneOf:
+ - $ref: "#/components/schemas/AgentResult"
+ - {type: 'null'}
+ requests: {type: array, items: {$ref: "#/components/schemas/AgentRequest"}}
+ steering: {type: array, items: {$ref: "#/components/schemas/AgentSteeringReceipt"}}
+
+ AgentTurnStatus:
+ type: string
+ enum: [queued, running, waiting_input, interrupting, completed, cancelled, failed, unknown]
+
+ AgentResult:
+ type: object
+ required: [turn_id, status, outcome, text, data, artifacts, usage, error]
+ properties:
+ turn_id: {type: string}
+ status: {$ref: "#/components/schemas/AgentTurnStatus"}
+ outcome: {type: [string, 'null'], enum: [answer, question, null]}
+ text: {type: [string, 'null']}
+ data: {}
+ artifacts: {type: array, items: {type: string}}
+ usage: {}
+ error: {type: [string, 'null']}
+
+ AgentConfig:
+ type: object
+ required: [tools, mcp]
+ description: Absent optional fields are omitted from snapshots.
+ properties:
+ tools: {type: array, items: {type: string}}
+ mcp: {type: array, items: {type: string}}
+ model: {type: string}
+ reasoning: {type: string}
+ instructions: {type: string}
+ permissions: {not: {type: 'null'}}
+ limits: {not: {type: 'null'}}
+ output_schema: {not: {type: 'null'}}
+
+ AgentCapabilities:
+ type: object
+ required: [operations, input_kinds, max_queued_turns, max_pending_steering, idempotency_retention_seconds]
+ properties:
+ operations: {type: array, items: {type: string}}
+ input_kinds: {type: array, items: {type: string}}
+ max_queued_turns: {type: [integer, 'null'], minimum: 0}
+ max_pending_steering: {type: [integer, 'null'], minimum: 0}
+ idempotency_retention_seconds: {type: [number, 'null'], minimum: 0}
+
+ AgentRequest:
+ type: object
+ required: [id, turn_id, kind]
+ properties:
+ id: {type: string}
+ turn_id: {type: string}
+ kind:
+ oneOf:
+ - type: object
+ required: [type, text, schema]
+ properties:
+ type: {const: question}
+ text: {type: string}
+ schema: {}
+ - type: object
+ required: [type, tool, arguments]
+ properties:
+ type: {const: permission}
+ tool: {type: string}
+ arguments: {}
+
+ AgentSteeringReceipt:
+ type: object
+ required: [id, turn_id, status]
+ properties:
+ id: {type: string}
+ turn_id: {type: string}
+ status: {type: string, enum: [accepted, applied, unused, unknown]}
+
+ AgentEvent:
+ type: object
+ required: [cursor, agent_id, turn_id, kind, data]
+ properties:
+ cursor: {type: [string, 'null']}
+ agent_id: {type: string}
+ turn_id: {type: [string, 'null']}
+ kind: {type: string}
+ data: {}
+
# =======================================================================
# Configuration
diff --git a/openapi/tests/test_agent_spec.py b/openapi/tests/test_agent_spec.py
new file mode 100644
index 000000000..971ed98c8
--- /dev/null
+++ b/openapi/tests/test_agent_spec.py
@@ -0,0 +1,186 @@
+"""Validate examples and boundaries in the agent OpenAPI contract."""
+import copy
+import json
+import re
+import unittest
+from pathlib import Path
+
+import jsonschema
+import yaml
+
+ROOT = Path(__file__).resolve().parents[2]
+SPEC = yaml.safe_load((ROOT / "openapi/box.openapi.yaml").read_text())
+SCHEMAS = SPEC["components"]["schemas"]
+
+
+def validate(schema, value):
+ jsonschema.Draft202012Validator(
+ {"$ref": f"#/components/schemas/{schema}", "components": SPEC["components"]}
+ ).validate(value)
+
+
+def dereference(value):
+ while "$ref" in value:
+ reference = value["$ref"]
+ value = SPEC
+ for part in reference.split("/")[1:]:
+ value = value[part]
+ return value
+
+
+class AgentSpecTest(unittest.TestCase):
+ def test_all_agent_operations_present(self):
+ operations = {
+ operation["operationId"]
+ for path, item in SPEC["paths"].items() if "/agents" in path
+ for method, operation in item.items()
+ if method in ("get", "post", "put", "delete", "patch")
+ }
+ self.assertEqual(operations, {
+ "createAgent", "getAgent", "getAgentTurn", "closeAgent", "sendAgentTurn",
+ "getAgentEvents", "respondAgentRequest", "steerAgentTurn", "interruptAgentTurn",
+ })
+
+ def test_agent_examples(self):
+ count = 0
+ for path, item in SPEC["paths"].items():
+ if "/agents" not in path:
+ continue
+ for method in ("get", "post", "put", "delete", "patch"):
+ if method not in item:
+ continue
+ operation = item[method]
+ messages = list(operation.get("responses", {}).values())
+ if "requestBody" in operation:
+ messages.append(operation["requestBody"])
+ for message in messages:
+ message = dereference(message)
+ for media in message.get("content", {}).values():
+ schema = media.get("schema")
+ if not schema:
+ continue
+ validator = jsonschema.Draft202012Validator(
+ {**schema, "components": SPEC["components"]}
+ )
+ examples = [media["example"]] if "example" in media else []
+ examples += [v["value"] for v in media.get("examples", {}).values()]
+ for example in examples:
+ validator.validate(example)
+ count += 1
+ self.assertGreaterEqual(count, 10)
+
+ def test_shared_examples_and_parameters(self):
+ components = SPEC["components"]
+ for name, response in components["responses"].items():
+ if not name.startswith("Agent"):
+ continue
+ for media in response["content"].values():
+ validator = jsonschema.Draft202012Validator(
+ {**media["schema"], "components": components}
+ )
+ examples = [media["example"]] if "example" in media else []
+ examples += [v["value"] for v in media.get("examples", {}).values()]
+ self.assertTrue(examples, name)
+ for example in examples:
+ validator.validate(example)
+ for name in ("agentId", "agentTurnId", "agentIdempotencyKey"):
+ parameter = components["parameters"][name]
+ jsonschema.Draft202012Validator(parameter["schema"]).validate(parameter["example"])
+
+ def test_create_boundaries(self):
+ body = {"agent": "coder", "options": {"cwd": "/workspace", "config": {
+ "tools": [], "mcp": [], "permissions": {"allow": False, "count": 0, "nested": [None, {}]}
+ }}}
+ original = copy.deepcopy(body)
+ validate("AgentCreateRequest", body)
+ self.assertEqual(body, original)
+ for bad in ({"agent": "x", "extra": 1}, {"agent": "x", "options": None},
+ {"agent": "x", "options": {"config": None}},
+ {"agent": "x", "options": {"config": {"unknown": 1}}}):
+ with self.subTest(bad=bad), self.assertRaises(jsonschema.ValidationError):
+ validate("AgentCreateRequest", bad)
+ key = SPEC["components"]["parameters"]["agentIdempotencyKey"]["schema"]
+ validator = jsonschema.Draft202012Validator(key)
+ for value in ("", "x" * 257, "é", "a b", "x\n"):
+ self.assertFalse(validator.is_valid(value), value)
+ self.assertTrue(validator.is_valid("x" * 256))
+
+ def test_turn_request_boundaries(self):
+ for schema, body in (
+ ("AgentSendRequest", {"text": "", "options": {"mode": "queue", "data": {"zero": 0, "empty": [], "null": None}}}),
+ ("AgentRespondRequest", {"response": {"type": "permission", "approved": False}}),
+ ("AgentRespondRequest", {"response": {"type": "answer", "text": "ok", "data": {}}}),
+ ("AgentSteerRequest", {"text": "focus"}),
+ ("AgentEmptyRequest", {}),
+ ):
+ with self.subTest(schema=schema):
+ validate(schema, body)
+
+ for schema, body in (
+ ("AgentSendRequest", {"text": "x", "options": None}),
+ ("AgentSendRequest", {"text": "x", "options": {"mode": "unknown"}}),
+ ("AgentRespondRequest", {"response": {"type": "permission", "approved": None}}),
+ ("AgentRespondRequest", {"response": {"type": "unknown"}}),
+ ("AgentSteerRequest", {"text": "x", "extra": True}),
+ ("AgentEmptyRequest", {"extra": True}),
+ ):
+ with self.subTest(schema=schema, body=body), self.assertRaises(jsonschema.ValidationError):
+ validate(schema, body)
+
+ def test_stream_event_example(self):
+ path = "/{prefix}/boxes/{box_id}/agents/{agent_id}/events"
+ example = SPEC["paths"][path]["get"]["responses"]["200"]["content"]["text/event-stream"]["example"]
+ data = next(line[6:] for line in example.splitlines() if line.startswith("data: "))
+ validate("AgentEvent", json.loads(data))
+
+ def test_record_fields_and_fractional_retention(self):
+ records = (ROOT / "src/boxlite/src/agents/records.rs").read_text()
+ functions = dict(re.findall(
+ r"pub fn (\w+)\([^\n]*\).*?\n(.*?)(?=\npub fn |\n///|\nfn |\Z)",
+ records, re.S,
+ ))
+ for schema, function in {
+ "AgentState": "agent_state", "AgentTurnState": "turn_state",
+ "AgentResult": "result", "AgentSteeringReceipt": "receipt",
+ "AgentCapabilities": "capabilities", "AgentEvent": "event",
+ }.items():
+ fields = set(re.findall(r'"(\w+)"\s*:', functions[function]))
+ self.assertEqual(set(SCHEMAS[schema]["properties"]), fields, schema)
+ config_fields = set(re.findall(r'"(\w+)"\s*:', functions["config"]))
+ config_fields.update(re.findall(r'\(\s*"(\w+)"\s*,', functions["config"]))
+ self.assertEqual(set(SCHEMAS["AgentConfig"]["properties"]), config_fields)
+ request = functions["requests"]
+ outer = re.search(r'json!\(\{ "id":.*?\}\)', request).group()
+ self.assertEqual(set(SCHEMAS["AgentRequest"]["properties"]),
+ set(re.findall(r'"(\w+)"\s*:', outer)))
+ for variant in SCHEMAS["AgentRequest"]["properties"]["kind"]["oneOf"]:
+ kind = variant["properties"]["type"]["const"]
+ record = re.search(r'json!\(\{ "type": "' + kind + r'".*?\}\)', request).group()
+ self.assertEqual(set(variant["properties"]), set(re.findall(r'"(\w+)"\s*:', record)))
+ validate("AgentCapabilities", {"operations": [], "input_kinds": [], "max_queued_turns": 0,
+ "max_pending_steering": None, "idempotency_retention_seconds": 0.5})
+ self.assertFalse(jsonschema.Draft202012Validator(SCHEMAS["AgentTurnStatus"]).is_valid("bogus"))
+ validate("AgentEvent", {"cursor": None, "agent_id": "a", "turn_id": None, "kind": "x", "data": {"nested": None}})
+
+ def test_unsupported_examples_name_unadvertised_operation(self):
+ source = (ROOT / "src/boxlite/src/agents/opencode/mod.rs").read_text()
+ capabilities = source.split("fn capabilities() -> AgentCapabilities", 1)[1].split(".map(String::from)", 1)[0]
+ operations = set(re.findall(r'"([a-z_.]+)"', capabilities))
+ checked = 0
+ for name, response in SPEC["components"]["responses"].items():
+ if not name.startswith("Agent"):
+ continue
+ for media in response.get("content", {}).values():
+ examples = ([media["example"]] if "example" in media else [])
+ examples += [v["value"] for v in media.get("examples", {}).values()]
+ for example in examples:
+ error = example["error"]
+ if error["code"] == "unsupported":
+ checked += 1
+ operation = error["message"].split()[0]
+ self.assertNotIn(operation, operations)
+ self.assertGreater(checked, 0)
+
+
+if __name__ == "__main__":
+ unittest.main()