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    /// Device client tokens have immutable watch/drive intent. Watch cannot
57    /// mutate Runtime state, acquire control, or forward display input.
58    #[serde(default)]
59    pub client_token_intents: bool,
60    #[serde(default)]
61    pub account_session: bool,
62    pub threads: bool,
63    /// Explicit per-thread shell opt-in is checked against loaded policy and
64    /// cannot broaden a conversation while it has an active turn.
65    #[serde(default)]
66    pub thread_shell_consent: bool,
67    pub turns: bool,
68    /// `POST /v1/threads/{id}/turns` accepts a durable, thread-scoped
69    /// `operation_key` and returns the original turn for exact retries.
70    #[serde(default)]
71    pub turn_operation_idempotency: bool,
72    /// Read-only exact accepted-turn lookup by thread and operation key.
73    #[serde(default)]
74    pub turn_operation_lookup: bool,
75    /// Bounded inline image inputs, persisted and replayed with their turn.
76    #[serde(default)]
77    pub turn_image_inputs: bool,
78    /// Per-turn maxOutputTokens is validated and intersected with the route ceiling.
79    #[serde(default)]
80    pub turn_output_token_limit: bool,
81    /// Account profile snapshots and Engine-owned constitution preview.
82    #[serde(default)]
83    pub profile_constitution: bool,
84    pub turn_steer: bool,
85    pub turn_interrupt: bool,
86    pub event_replay: bool,
87    pub external_tools: bool,
88    pub environments: bool,
89    pub worker_runtime: bool,
90    #[serde(default)]
91    pub fleet_run_create: bool,
92    #[serde(default)]
93    pub fleet_run_start: bool,
94    #[serde(default)]
95    pub fleet_event_replay: bool,
96    #[serde(default)]
97    pub fleet_event_stream: bool,
98    #[serde(default)]
99    pub fleet_local_target: bool,
100    /// `GET/PUT/DELETE /v1/threads/{id}/goal` and the `complete`/`block`
101    /// lifecycle actions are available.
102    #[serde(default)]
103    pub thread_goals: bool,
104    /// `GET /v1/memory` and `GET /v1/memory/{id}` are available for
105    /// bounded inspection of the native memory store.  `POST /v1/memory`
106    /// and `DELETE /v1/memory` are also available (auth-gated via the
107    /// standard route layer) for lifecycle controls.
108    #[serde(default)]
109    pub memory: bool,
110    /// Whether the runtime supports create/update/enable/disable/reconnect/delete
111    /// operations on MCP server configuration via the `POST|GET|PATCH|DELETE
112    /// /v1/apps/mcp/servers` family of endpoints.
113    #[serde(default)]
114    pub mcp_server_management: bool,
115    /// Skill lifecycle operations (install, update, uninstall, trust, audit)
116    /// are available via the HTTP API.
117    #[serde(default)]
118    pub skill_lifecycle: bool,
119    /// `GET /v1/skills/{name}` returns one skill's full body and routing
120    /// metadata, so a client can compose an activation instruction for its
121    /// next turn. `GET /v1/skills` rows also carry `invocation`, `aliases`,
122    /// and `bundled_tier` routing fields when this flag is set.
123    #[serde(default)]
124    pub skill_detail: bool,
125    /// Plugin bundle and marketplace lifecycle operations (list/detail,
126    /// install/update/uninstall, trust/enable/disable/revoke, marketplace
127    /// add/remove/install) are available via the `/v1/apps/plugins` and
128    /// `/v1/apps/marketplaces` endpoint families.
129    #[serde(default)]
130    pub plugin_management: bool,
131    /// Durable, workspace-scoped cross-task Agent Mail endpoints and events.
132    #[serde(default)]
133    pub agent_mail: bool,
134    /// `GET /v1/terminal/{name}/output` — the resumable byte stream over a
135    /// persistent Engine-owned terminal session, with absolute cursors.
136    #[serde(default)]
137    pub terminal_stream: bool,
138    /// `POST /v1/terminal/{name}/input` — bytes into the live session.
139    #[serde(default)]
140    pub terminal_input: bool,
141    /// `POST /v1/terminal/{name}/resize` — the window the child draws for.
142    #[serde(default)]
143    pub terminal_resize: bool,
144    /// `POST /v1/terminal/{name}/kill` — end the live session.
145    #[serde(default)]
146    pub terminal_kill: bool,
147    /// `GET /v1/threads/{id}/events` puts the durable `seq` on every journal
148    /// frame as the SSE `id:` and resumes from a `Last-Event-ID` header, so a
149    /// browser `EventSource` reconnects without a cursor in the query string.
150    #[serde(default)]
151    pub event_stream_resume: bool,
152}
153
154/// Experimental opt-in flags advertised by `GET /v1/runtime/info`.
155///
156/// Fields are additive and default to `false` when omitted by older servers.
157#[derive(Debug, Clone, Default, Serialize, Deserialize)]
158pub struct RuntimeExperimentalCapabilities {
159    #[serde(default)]
160    pub environments: bool,
161}
162
163// ---------------------------------------------------------------------------
164// External Tool Bridge protocol types
165// ---------------------------------------------------------------------------
166
167/// Specification for a dynamic external tool registered by a runtime client.
168///
169/// Example JSON from the spec:
170///
171/// ```json
172/// {
173///   "namespace": "tau_bench",
174///   "name": "get_reservation",
175///   "description": "Look up an airline reservation.",
176///   "input_schema": {
177///     "type": "object",
178///     "properties": {
179///       "reservation_id": { "type": "string" }
180///     },
181///     "required": ["reservation_id"],
182///     "additionalProperties": false
183///   }
184/// }
185/// ```
186#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
187pub struct DynamicToolSpec {
188    /// Optional namespace that groups related tools (e.g. `"tau_bench"`).
189    /// When present, the runtime may expose the tool as
190    /// `<namespace>::<name>` to the model.
191    #[serde(skip_serializing_if = "Option::is_none")]
192    pub namespace: Option<String>,
193
194    /// Short tool name. Combined with `namespace` it forms a unique tool id.
195    pub name: String,
196
197    /// Human-readable description exposed to the model.
198    pub description: String,
199
200    /// JSON Schema describing the tool's input parameters.
201    pub input_schema: Value,
202
203    /// If true, the runtime may defer schema validation / tool loading until
204    /// the model actually calls the tool.
205    ///
206    /// Defaults to `false` so that older clients omitting this field still
207    /// behave the same way.
208    #[serde(default)]
209    pub defer_loading: bool,
210}
211
212/// Lifecycle status of a dynamic tool item shown in thread detail and event
213/// payloads.
214#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
215#[serde(rename_all = "snake_case")]
216pub enum DynamicToolItemStatus {
217    InProgress,
218    Completed,
219    Failed,
220}
221
222/// Parameters identifying a dynamic tool call request emitted by the runtime.
223///
224/// This is the typed payload for `tool_call.requested` events and also the
225/// natural identifier used when the runtime looks up a pending call.
226#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
227pub struct DynamicToolCallParams {
228    pub thread_id: String,
229    pub turn_id: String,
230    pub call_id: String,
231
232    /// Optional namespace that was registered with the tool.
233    #[serde(skip_serializing_if = "Option::is_none")]
234    pub namespace: Option<String>,
235
236    /// Tool name that the model invoked.
237    pub tool: String,
238
239    /// Arguments supplied by the model, validated against `input_schema`.
240    pub arguments: Value,
241}
242
243/// Result submitted by a runtime client after executing a dynamic tool.
244#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
245pub struct DynamicToolCallResult {
246    /// Whether the client-side tool execution succeeded.
247    pub success: bool,
248
249    /// Content fragments returned by the tool.
250    ///
251    /// Defaults to an empty vector when omitted so clients can send a minimal
252    /// `{ "success": false }` payload.
253    #[serde(default)]
254    pub content: Vec<DynamicToolCallContent>,
255}
256
257/// A single content fragment inside a [`DynamicToolCallResult`].
258#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
259#[serde(tag = "type", rename_all = "snake_case")]
260pub enum DynamicToolCallContent {
261    InputText { text: String },
262    InputImage { image_url: String },
263}
264
265// ---------------------------------------------------------------------------
266// Environment targeting protocol types
267// ---------------------------------------------------------------------------
268
269/// Environment target selected for a turn's shell/filesystem work.
270///
271/// Example JSON:
272///
273/// ```json
274/// {
275///   "environment_id": "local",
276///   "cwd": "/workspace"
277/// }
278/// ```
279#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
280pub struct TurnEnvironmentParams {
281    pub environment_id: String,
282    pub cwd: PathBuf,
283}
284
285#[cfg(test)]
286mod tests {
287    use super::*;
288    use serde_json::json;
289
290    #[test]
291    fn dynamic_tool_spec_roundtrip() {
292        let spec = DynamicToolSpec {
293            namespace: Some("tau_bench".into()),
294            name: "get_reservation".into(),
295            description: "Look up an airline reservation.".into(),
296            input_schema: json!({
297                "type": "object",
298                "properties": {
299                    "reservation_id": { "type": "string" }
300                },
301                "required": ["reservation_id"],
302                "additionalProperties": false
303            }),
304            defer_loading: false,
305        };
306
307        let serialized = serde_json::to_string(&spec).unwrap();
308        let deserialized: DynamicToolSpec = serde_json::from_str(&serialized).unwrap();
309        assert_eq!(spec, deserialized);
310    }
311
312    #[test]
313    fn dynamic_tool_spec_omits_defer_loading_defaults_false() {
314        let json = r#"{
315            "namespace": "tau_bench",
316            "name": "get_reservation",
317            "description": "Look up an airline reservation.",
318            "input_schema": { "type": "object" }
319        }"#;
320
321        let spec: DynamicToolSpec = serde_json::from_str(json).unwrap();
322        assert_eq!(spec.namespace, Some("tau_bench".into()));
323        assert_eq!(spec.name, "get_reservation");
324        assert!(!spec.defer_loading);
325    }
326
327    #[test]
328    fn dynamic_tool_item_status_snake_case() {
329        assert_eq!(
330            serde_json::to_string(&DynamicToolItemStatus::InProgress).unwrap(),
331            "\"in_progress\""
332        );
333        assert_eq!(
334            serde_json::from_str::<DynamicToolItemStatus>("\"completed\"").unwrap(),
335            DynamicToolItemStatus::Completed
336        );
337        assert_eq!(
338            serde_json::from_str::<DynamicToolItemStatus>("\"failed\"").unwrap(),
339            DynamicToolItemStatus::Failed
340        );
341    }
342
343    #[test]
344    fn dynamic_tool_call_params_roundtrip() {
345        let params = DynamicToolCallParams {
346            thread_id: "thr_123".into(),
347            turn_id: "turn_456".into(),
348            call_id: "call_abc".into(),
349            namespace: Some("tau_bench".into()),
350            tool: "get_reservation".into(),
351            arguments: json!({ "reservation_id": "ABC123" }),
352        };
353
354        let serialized = serde_json::to_string(&params).unwrap();
355        let deserialized: DynamicToolCallParams = serde_json::from_str(&serialized).unwrap();
356        assert_eq!(params, deserialized);
357    }
358
359    #[test]
360    fn dynamic_tool_call_content_roundtrip() {
361        let content = vec![
362            DynamicToolCallContent::InputText {
363                text: "{\"status\":\"confirmed\"}".into(),
364            },
365            DynamicToolCallContent::InputImage {
366                image_url: "http://example.com/receipt.png".into(),
367            },
368        ];
369
370        let value = serde_json::to_value(&content).unwrap();
371        let deserialized: Vec<DynamicToolCallContent> = serde_json::from_value(value).unwrap();
372        assert_eq!(content, deserialized);
373
374        // Verify the exact JSON tag names expected by the spec.
375        assert_eq!(
376            serde_json::to_string(&DynamicToolCallContent::InputText { text: "x".into() }).unwrap(),
377            r#"{"type":"input_text","text":"x"}"#
378        );
379        assert_eq!(
380            serde_json::to_string(&DynamicToolCallContent::InputImage {
381                image_url: "y".into()
382            })
383            .unwrap(),
384            r#"{"type":"input_image","image_url":"y"}"#
385        );
386    }
387
388    #[test]
389    fn dynamic_tool_call_result_defaults_empty_content() {
390        let json = r#"{ "success": false }"#;
391        let result: DynamicToolCallResult = serde_json::from_str(json).unwrap();
392        assert!(!result.success);
393        assert!(result.content.is_empty());
394    }
395
396    #[test]
397    fn dynamic_tool_call_result_roundtrip_with_content() {
398        let result = DynamicToolCallResult {
399            success: true,
400            content: vec![DynamicToolCallContent::InputText {
401                text: "done".into(),
402            }],
403        };
404
405        let serialized = serde_json::to_string(&result).unwrap();
406        let deserialized: DynamicToolCallResult = serde_json::from_str(&serialized).unwrap();
407        assert_eq!(result, deserialized);
408    }
409
410    #[test]
411    fn turn_environment_params_roundtrip() {
412        let env = TurnEnvironmentParams {
413            environment_id: "local".into(),
414            cwd: PathBuf::from("/workspace"),
415        };
416
417        let serialized = serde_json::to_string(&env).unwrap();
418        let deserialized: TurnEnvironmentParams = serde_json::from_str(&serialized).unwrap();
419        assert_eq!(env, deserialized);
420
421        // Verify JSON from the spec deserializes directly.
422        let from_spec = r#"{
423            "environment_id": "local",
424            "cwd": "/workspace"
425        }"#;
426        let parsed: TurnEnvironmentParams = serde_json::from_str(from_spec).unwrap();
427        assert_eq!(parsed.environment_id, "local");
428        assert_eq!(parsed.cwd, PathBuf::from("/workspace"));
429    }
430
431    #[test]
432    fn runtime_capabilities_serializes_expected_shape() {
433        let caps = RuntimeCapabilities {
434            client_token_intents: true,
435            turn_output_token_limit: false,
436            profile_constitution: false,
437            account_session: true,
438            threads: true,
439            thread_shell_consent: true,
440            turns: true,
441            turn_operation_idempotency: true,
442            turn_operation_lookup: true,
443            turn_image_inputs: true,
444            turn_steer: true,
445            turn_interrupt: true,
446            event_replay: true,
447            external_tools: false,
448            environments: false,
449            worker_runtime: false,
450            fleet_run_create: true,
451            fleet_run_start: true,
452            fleet_event_replay: true,
453            fleet_event_stream: true,
454            fleet_local_target: true,
455            thread_goals: true,
456            memory: true,
457            mcp_server_management: false,
458            skill_lifecycle: false,
459            skill_detail: false,
460            plugin_management: false,
461            agent_mail: true,
462            terminal_stream: false,
463            terminal_input: false,
464            terminal_resize: false,
465            terminal_kill: false,
466            event_stream_resume: true,
467        };
468        let value = serde_json::to_value(&caps).unwrap();
469        let obj = value.as_object().unwrap();
470        assert_eq!(obj.get("client_token_intents"), Some(&json!(true)));
471        let mut legacy_intents = value.clone();
472        legacy_intents
473            .as_object_mut()
474            .unwrap()
475            .remove("client_token_intents");
476        assert!(
477            !serde_json::from_value::<RuntimeCapabilities>(legacy_intents)
478                .unwrap()
479                .client_token_intents
480        );
481        assert_eq!(obj.get("threads").unwrap(), &json!(true));
482        assert_eq!(obj.get("thread_shell_consent"), Some(&json!(true)));
483        assert!(
484            serde_json::from_value::<RuntimeCapabilities>(value.clone())
485                .unwrap()
486                .thread_shell_consent
487        );
488        let mut legacy_shell = value.clone();
489        legacy_shell
490            .as_object_mut()
491            .unwrap()
492            .remove("thread_shell_consent");
493        assert!(
494            !serde_json::from_value::<RuntimeCapabilities>(legacy_shell)
495                .unwrap()
496                .thread_shell_consent
497        );
498
499        assert_eq!(obj.get("account_session").unwrap(), &json!(true));
500        assert_eq!(obj.get("turn_operation_idempotency").unwrap(), &json!(true));
501        assert_eq!(obj.get("turn_operation_lookup").unwrap(), &json!(true));
502        let mut without_lookup = value.clone();
503        without_lookup
504            .as_object_mut()
505            .unwrap()
506            .remove("turn_operation_lookup");
507        assert!(
508            !serde_json::from_value::<RuntimeCapabilities>(without_lookup)
509                .unwrap()
510                .turn_operation_lookup
511        );
512        assert_eq!(obj.get("turn_image_inputs").unwrap(), &json!(true));
513        let mut legacy = value.clone();
514        legacy.as_object_mut().unwrap().remove("turn_image_inputs");
515        assert!(
516            !serde_json::from_value::<RuntimeCapabilities>(legacy)
517                .unwrap()
518                .turn_image_inputs
519        );
520        assert_eq!(obj.get("external_tools").unwrap(), &json!(false));
521        assert!(obj.contains_key("worker_runtime"));
522        assert_eq!(obj.get("fleet_run_create").unwrap(), &json!(true));
523        assert_eq!(obj.get("fleet_event_stream").unwrap(), &json!(true));
524        assert_eq!(obj.get("thread_goals").unwrap(), &json!(true));
525        assert_eq!(obj.get("memory").unwrap(), &json!(true));
526        assert_eq!(obj.get("plugin_management").unwrap(), &json!(false));
527        assert_eq!(obj.get("agent_mail").unwrap(), &json!(true));
528    }
529
530    #[test]
531    fn runtime_event_envelope_schema_version_default() {
532        let json = r#"{
533            "seq": 1,
534            "event": "test",
535            "kind": "test",
536            "thread_id": "thr_1",
537            "timestamp": "2026-06-12T00:00:00Z",
538            "payload": {}
539        }"#;
540        let envelope: RuntimeEventEnvelope = serde_json::from_str(json).unwrap();
541        assert_eq!(
542            envelope.schema_version,
543            RUNTIME_EVENT_ENVELOPE_SCHEMA_VERSION
544        );
545    }
546}