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