Skip to main content

codewhale_protocol/runtime/
mod.rs

1use std::collections::BTreeMap;
2use std::path::PathBuf;
3
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6
7pub const RUNTIME_EVENT_ENVELOPE_SCHEMA_VERSION: u32 = 1;
8pub const RUNTIME_API_VERSION: &str = "1.0";
9
10/// Maximum JSON input (including base64 expansion) for an image turn.
11pub const MAX_RUNTIME_IMAGE_BODY_BYTES: usize = 8 * 1024 * 1024;
12pub const MAX_RUNTIME_IMAGES: usize = 10;
13pub const MAX_RUNTIME_IMAGE_BYTES: usize = 4 * 1024 * 1024;
14pub const MAX_RUNTIME_IMAGE_TOTAL_BYTES: usize = 5 * 1024 * 1024;
15
16/// Inline bytes only: neither host paths nor remote URLs confer attachment authority.
17#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
18#[serde(rename_all = "camelCase", deny_unknown_fields)]
19pub struct RuntimeImageInput {
20    pub mime: String,
21    pub data_base64: String,
22}
23
24#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct RuntimeEventEnvelope {
26    #[serde(default = "default_runtime_event_envelope_schema_version")]
27    pub schema_version: u32,
28    pub seq: u64,
29    pub event: String,
30    pub kind: String,
31    pub thread_id: String,
32    pub turn_id: Option<String>,
33    pub item_id: Option<String>,
34    pub timestamp: String,
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub created_at: Option<String>,
37    pub payload: Value,
38    #[serde(default)]
39    #[serde(flatten)]
40    pub extra: BTreeMap<String, Value>,
41}
42
43fn default_runtime_event_envelope_schema_version() -> u32 {
44    RUNTIME_EVENT_ENVELOPE_SCHEMA_VERSION
45}
46
47// ---------------------------------------------------------------------------
48// Capability advertisement
49// ---------------------------------------------------------------------------
50
51/// Fixed capability map advertised by `GET /v1/runtime/info`.
52///
53/// All fields are required on serialization so clients can rely on the shape.
54#[derive(Debug, Clone, Serialize, Deserialize)]
55pub struct RuntimeCapabilities {
56    #[serde(default)]
57    pub account_session: bool,
58    pub threads: bool,
59    pub turns: bool,
60    /// `POST /v1/threads/{id}/turns` accepts a durable, thread-scoped
61    /// `operation_key` and returns the original turn for exact retries.
62    #[serde(default)]
63    pub turn_operation_idempotency: bool,
64    /// Read-only exact accepted-turn lookup by thread and operation key.
65    #[serde(default)]
66    pub turn_operation_lookup: bool,
67    /// Bounded inline image inputs, persisted and replayed with their turn.
68    #[serde(default)]
69    pub turn_image_inputs: bool,
70    /// Per-turn maxOutputTokens is validated and intersected with the route ceiling.
71    #[serde(default)]
72    pub turn_output_token_limit: bool,
73    pub turn_steer: bool,
74    pub turn_interrupt: bool,
75    pub event_replay: bool,
76    pub external_tools: bool,
77    pub environments: bool,
78    pub worker_runtime: bool,
79    #[serde(default)]
80    pub fleet_run_create: bool,
81    #[serde(default)]
82    pub fleet_run_start: bool,
83    #[serde(default)]
84    pub fleet_event_replay: bool,
85    #[serde(default)]
86    pub fleet_event_stream: bool,
87    #[serde(default)]
88    pub fleet_local_target: bool,
89    /// `GET/PUT/DELETE /v1/threads/{id}/goal` and the `complete`/`block`
90    /// lifecycle actions are available.
91    #[serde(default)]
92    pub thread_goals: bool,
93    /// `GET /v1/memory` and `GET /v1/memory/{id}` are available for
94    /// bounded inspection of the native memory store.  `POST /v1/memory`
95    /// and `DELETE /v1/memory` are also available (auth-gated via the
96    /// standard route layer) for lifecycle controls.
97    #[serde(default)]
98    pub memory: bool,
99    /// Whether the runtime supports create/update/enable/disable/reconnect/delete
100    /// operations on MCP server configuration via the `POST|GET|PATCH|DELETE
101    /// /v1/apps/mcp/servers` family of endpoints.
102    #[serde(default)]
103    pub mcp_server_management: bool,
104    /// Skill lifecycle operations (install, update, uninstall, trust, audit)
105    /// are available via the HTTP API.
106    #[serde(default)]
107    pub skill_lifecycle: bool,
108    /// Plugin bundle and marketplace lifecycle operations (list/detail,
109    /// install/update/uninstall, trust/enable/disable/revoke, marketplace
110    /// add/remove/install) are available via the `/v1/apps/plugins` and
111    /// `/v1/apps/marketplaces` endpoint families.
112    #[serde(default)]
113    pub plugin_management: bool,
114    /// Durable, workspace-scoped cross-task Agent Mail endpoints and events.
115    #[serde(default)]
116    pub agent_mail: bool,
117}
118
119/// Experimental opt-in flags advertised by `GET /v1/runtime/info`.
120///
121/// Fields are additive and default to `false` when omitted by older servers.
122#[derive(Debug, Clone, Default, Serialize, Deserialize)]
123pub struct RuntimeExperimentalCapabilities {
124    #[serde(default)]
125    pub environments: bool,
126}
127
128// ---------------------------------------------------------------------------
129// External Tool Bridge protocol types
130// ---------------------------------------------------------------------------
131
132/// Specification for a dynamic external tool registered by a runtime client.
133///
134/// Example JSON from the spec:
135///
136/// ```json
137/// {
138///   "namespace": "tau_bench",
139///   "name": "get_reservation",
140///   "description": "Look up an airline reservation.",
141///   "input_schema": {
142///     "type": "object",
143///     "properties": {
144///       "reservation_id": { "type": "string" }
145///     },
146///     "required": ["reservation_id"],
147///     "additionalProperties": false
148///   }
149/// }
150/// ```
151#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
152pub struct DynamicToolSpec {
153    /// Optional namespace that groups related tools (e.g. `"tau_bench"`).
154    /// When present, the runtime may expose the tool as
155    /// `<namespace>::<name>` to the model.
156    #[serde(skip_serializing_if = "Option::is_none")]
157    pub namespace: Option<String>,
158
159    /// Short tool name. Combined with `namespace` it forms a unique tool id.
160    pub name: String,
161
162    /// Human-readable description exposed to the model.
163    pub description: String,
164
165    /// JSON Schema describing the tool's input parameters.
166    pub input_schema: Value,
167
168    /// If true, the runtime may defer schema validation / tool loading until
169    /// the model actually calls the tool.
170    ///
171    /// Defaults to `false` so that older clients omitting this field still
172    /// behave the same way.
173    #[serde(default)]
174    pub defer_loading: bool,
175}
176
177/// Lifecycle status of a dynamic tool item shown in thread detail and event
178/// payloads.
179#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
180#[serde(rename_all = "snake_case")]
181pub enum DynamicToolItemStatus {
182    InProgress,
183    Completed,
184    Failed,
185}
186
187/// Parameters identifying a dynamic tool call request emitted by the runtime.
188///
189/// This is the typed payload for `tool_call.requested` events and also the
190/// natural identifier used when the runtime looks up a pending call.
191#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
192pub struct DynamicToolCallParams {
193    pub thread_id: String,
194    pub turn_id: String,
195    pub call_id: String,
196
197    /// Optional namespace that was registered with the tool.
198    #[serde(skip_serializing_if = "Option::is_none")]
199    pub namespace: Option<String>,
200
201    /// Tool name that the model invoked.
202    pub tool: String,
203
204    /// Arguments supplied by the model, validated against `input_schema`.
205    pub arguments: Value,
206}
207
208/// Result submitted by a runtime client after executing a dynamic tool.
209#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
210pub struct DynamicToolCallResult {
211    /// Whether the client-side tool execution succeeded.
212    pub success: bool,
213
214    /// Content fragments returned by the tool.
215    ///
216    /// Defaults to an empty vector when omitted so clients can send a minimal
217    /// `{ "success": false }` payload.
218    #[serde(default)]
219    pub content: Vec<DynamicToolCallContent>,
220}
221
222/// A single content fragment inside a [`DynamicToolCallResult`].
223#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
224#[serde(tag = "type", rename_all = "snake_case")]
225pub enum DynamicToolCallContent {
226    InputText { text: String },
227    InputImage { image_url: String },
228}
229
230// ---------------------------------------------------------------------------
231// Environment targeting protocol types
232// ---------------------------------------------------------------------------
233
234/// Environment target selected for a turn's shell/filesystem work.
235///
236/// Example JSON:
237///
238/// ```json
239/// {
240///   "environment_id": "local",
241///   "cwd": "/workspace"
242/// }
243/// ```
244#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
245pub struct TurnEnvironmentParams {
246    pub environment_id: String,
247    pub cwd: PathBuf,
248}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253    use serde_json::json;
254
255    #[test]
256    fn dynamic_tool_spec_roundtrip() {
257        let spec = DynamicToolSpec {
258            namespace: Some("tau_bench".into()),
259            name: "get_reservation".into(),
260            description: "Look up an airline reservation.".into(),
261            input_schema: json!({
262                "type": "object",
263                "properties": {
264                    "reservation_id": { "type": "string" }
265                },
266                "required": ["reservation_id"],
267                "additionalProperties": false
268            }),
269            defer_loading: false,
270        };
271
272        let serialized = serde_json::to_string(&spec).unwrap();
273        let deserialized: DynamicToolSpec = serde_json::from_str(&serialized).unwrap();
274        assert_eq!(spec, deserialized);
275    }
276
277    #[test]
278    fn dynamic_tool_spec_omits_defer_loading_defaults_false() {
279        let json = r#"{
280            "namespace": "tau_bench",
281            "name": "get_reservation",
282            "description": "Look up an airline reservation.",
283            "input_schema": { "type": "object" }
284        }"#;
285
286        let spec: DynamicToolSpec = serde_json::from_str(json).unwrap();
287        assert_eq!(spec.namespace, Some("tau_bench".into()));
288        assert_eq!(spec.name, "get_reservation");
289        assert!(!spec.defer_loading);
290    }
291
292    #[test]
293    fn dynamic_tool_item_status_snake_case() {
294        assert_eq!(
295            serde_json::to_string(&DynamicToolItemStatus::InProgress).unwrap(),
296            "\"in_progress\""
297        );
298        assert_eq!(
299            serde_json::from_str::<DynamicToolItemStatus>("\"completed\"").unwrap(),
300            DynamicToolItemStatus::Completed
301        );
302        assert_eq!(
303            serde_json::from_str::<DynamicToolItemStatus>("\"failed\"").unwrap(),
304            DynamicToolItemStatus::Failed
305        );
306    }
307
308    #[test]
309    fn dynamic_tool_call_params_roundtrip() {
310        let params = DynamicToolCallParams {
311            thread_id: "thr_123".into(),
312            turn_id: "turn_456".into(),
313            call_id: "call_abc".into(),
314            namespace: Some("tau_bench".into()),
315            tool: "get_reservation".into(),
316            arguments: json!({ "reservation_id": "ABC123" }),
317        };
318
319        let serialized = serde_json::to_string(&params).unwrap();
320        let deserialized: DynamicToolCallParams = serde_json::from_str(&serialized).unwrap();
321        assert_eq!(params, deserialized);
322    }
323
324    #[test]
325    fn dynamic_tool_call_content_roundtrip() {
326        let content = vec![
327            DynamicToolCallContent::InputText {
328                text: "{\"status\":\"confirmed\"}".into(),
329            },
330            DynamicToolCallContent::InputImage {
331                image_url: "http://example.com/receipt.png".into(),
332            },
333        ];
334
335        let value = serde_json::to_value(&content).unwrap();
336        let deserialized: Vec<DynamicToolCallContent> = serde_json::from_value(value).unwrap();
337        assert_eq!(content, deserialized);
338
339        // Verify the exact JSON tag names expected by the spec.
340        assert_eq!(
341            serde_json::to_string(&DynamicToolCallContent::InputText { text: "x".into() }).unwrap(),
342            r#"{"type":"input_text","text":"x"}"#
343        );
344        assert_eq!(
345            serde_json::to_string(&DynamicToolCallContent::InputImage {
346                image_url: "y".into()
347            })
348            .unwrap(),
349            r#"{"type":"input_image","image_url":"y"}"#
350        );
351    }
352
353    #[test]
354    fn dynamic_tool_call_result_defaults_empty_content() {
355        let json = r#"{ "success": false }"#;
356        let result: DynamicToolCallResult = serde_json::from_str(json).unwrap();
357        assert!(!result.success);
358        assert!(result.content.is_empty());
359    }
360
361    #[test]
362    fn dynamic_tool_call_result_roundtrip_with_content() {
363        let result = DynamicToolCallResult {
364            success: true,
365            content: vec![DynamicToolCallContent::InputText {
366                text: "done".into(),
367            }],
368        };
369
370        let serialized = serde_json::to_string(&result).unwrap();
371        let deserialized: DynamicToolCallResult = serde_json::from_str(&serialized).unwrap();
372        assert_eq!(result, deserialized);
373    }
374
375    #[test]
376    fn turn_environment_params_roundtrip() {
377        let env = TurnEnvironmentParams {
378            environment_id: "local".into(),
379            cwd: PathBuf::from("/workspace"),
380        };
381
382        let serialized = serde_json::to_string(&env).unwrap();
383        let deserialized: TurnEnvironmentParams = serde_json::from_str(&serialized).unwrap();
384        assert_eq!(env, deserialized);
385
386        // Verify JSON from the spec deserializes directly.
387        let from_spec = r#"{
388            "environment_id": "local",
389            "cwd": "/workspace"
390        }"#;
391        let parsed: TurnEnvironmentParams = serde_json::from_str(from_spec).unwrap();
392        assert_eq!(parsed.environment_id, "local");
393        assert_eq!(parsed.cwd, PathBuf::from("/workspace"));
394    }
395
396    #[test]
397    fn runtime_capabilities_serializes_expected_shape() {
398        let caps = RuntimeCapabilities {
399            turn_output_token_limit: false,
400            account_session: true,
401            threads: true,
402            turns: true,
403            turn_operation_idempotency: true,
404            turn_operation_lookup: true,
405            turn_image_inputs: true,
406            turn_steer: true,
407            turn_interrupt: true,
408            event_replay: true,
409            external_tools: false,
410            environments: false,
411            worker_runtime: false,
412            fleet_run_create: true,
413            fleet_run_start: true,
414            fleet_event_replay: true,
415            fleet_event_stream: true,
416            fleet_local_target: true,
417            thread_goals: true,
418            memory: true,
419            mcp_server_management: false,
420            skill_lifecycle: false,
421            plugin_management: false,
422            agent_mail: true,
423        };
424        let value = serde_json::to_value(&caps).unwrap();
425        let obj = value.as_object().unwrap();
426        assert_eq!(obj.get("threads").unwrap(), &json!(true));
427        assert_eq!(obj.get("account_session").unwrap(), &json!(true));
428        assert_eq!(obj.get("turn_operation_idempotency").unwrap(), &json!(true));
429        assert_eq!(obj.get("turn_operation_lookup").unwrap(), &json!(true));
430        let mut without_lookup = value.clone();
431        without_lookup
432            .as_object_mut()
433            .unwrap()
434            .remove("turn_operation_lookup");
435        assert!(
436            !serde_json::from_value::<RuntimeCapabilities>(without_lookup)
437                .unwrap()
438                .turn_operation_lookup
439        );
440        assert_eq!(obj.get("turn_image_inputs").unwrap(), &json!(true));
441        let mut legacy = value.clone();
442        legacy.as_object_mut().unwrap().remove("turn_image_inputs");
443        assert!(
444            !serde_json::from_value::<RuntimeCapabilities>(legacy)
445                .unwrap()
446                .turn_image_inputs
447        );
448        assert_eq!(obj.get("external_tools").unwrap(), &json!(false));
449        assert!(obj.contains_key("worker_runtime"));
450        assert_eq!(obj.get("fleet_run_create").unwrap(), &json!(true));
451        assert_eq!(obj.get("fleet_event_stream").unwrap(), &json!(true));
452        assert_eq!(obj.get("thread_goals").unwrap(), &json!(true));
453        assert_eq!(obj.get("memory").unwrap(), &json!(true));
454        assert_eq!(obj.get("plugin_management").unwrap(), &json!(false));
455        assert_eq!(obj.get("agent_mail").unwrap(), &json!(true));
456    }
457
458    #[test]
459    fn runtime_event_envelope_schema_version_default() {
460        let json = r#"{
461            "seq": 1,
462            "event": "test",
463            "kind": "test",
464            "thread_id": "thr_1",
465            "timestamp": "2026-06-12T00:00:00Z",
466            "payload": {}
467        }"#;
468        let envelope: RuntimeEventEnvelope = serde_json::from_str(json).unwrap();
469        assert_eq!(
470            envelope.schema_version,
471            RUNTIME_EVENT_ENVELOPE_SCHEMA_VERSION
472        );
473    }
474}