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