Skip to main content

subc_protocol/
tool_call.rs

1//! The body of a tool-call `REQUEST` frame on a bound route.
2//!
3//! The daemon splices route frames without reading their bodies, so this
4//! shape is a contract between consumers (the MCP gateway, model runners)
5//! and provider modules, not something the daemon enforces. Before this
6//! type existed every consumer carried its own struct and every provider its
7//! own reader, and the fields drifted: the gateway sent `progress_token`,
8//! a model runner sent only `name` and `arguments`, and a provider that
9//! needed the caller's tool-call id had no field to read it from.
10//!
11//! Decoding is deliberately tolerant of unknown members: a provider must
12//! never refuse a call because a newer consumer added a key it does not
13//! know. Omitted optionals decode as `None`; `None` optionals are omitted on
14//! the wire, so a body carrying no optionals serializes exactly as the
15//! two-field shape older consumers already send — this type is drop-in for
16//! them without a wire change.
17//!
18//! Since 0.33.0 a call may also carry `output_refs`, the llm-runner's
19//! descriptor of the stored tool-output snapshots an agent's references
20//! resolved to. It is a top-level member beside the arguments, carried as an
21//! opaque JSON object of at most [`MAX_OUTPUT_REFS_BYTES`] bytes; see
22//! [`OutputRefs`].
23
24use serde::{Deserialize, Deserializer, Serialize, Serializer};
25use serde_json::{Map, Value};
26
27use crate::Principal;
28
29/// Who really asked for a call that another module relays.
30///
31/// When a module forwards a tool call on behalf of a different caller, the
32/// provider sees the forwarding module as the route's principal and the
33/// forwarder's own `call_key`. This records the caller behind it, so the
34/// provider can attribute the call in its logs and ledgers.
35///
36/// It is a claim made by the forwarding module, not something the daemon
37/// checks: a provider may record it but must never grant or refuse anything
38/// because of it. Authority stays with the route's own principal.
39///
40/// `#[non_exhaustive]` so a later member is an additive change; build it with
41/// [`CallOrigin::new`].
42#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
43#[non_exhaustive]
44pub struct CallOrigin {
45    /// The original caller, in the same form the daemon stamps on a route.
46    pub carrier: Principal,
47    /// The original caller's key for the call, with the same bounds as
48    /// [`ToolCallRequest::call_key`]; check it with [`validate_call_origin`].
49    pub call_key: String,
50    /// Where the call sits in the model message that asked for it, when the
51    /// forwarder knows. `None` means unknown, never "first" or "alone".
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub message_position: Option<MessagePosition>,
54}
55
56impl CallOrigin {
57    /// An origin naming `carrier` as the caller and `call_key` as its key, with
58    /// no message position.
59    pub fn new(carrier: Principal, call_key: impl Into<String>) -> Self {
60        Self {
61            carrier,
62            call_key: call_key.into(),
63            message_position: None,
64        }
65    }
66
67    /// Set where the call sits in the model message that asked for it.
68    pub fn with_message_position(mut self, position: MessagePosition) -> Self {
69        self.message_position = Some(position);
70        self
71    }
72}
73
74/// A relayed call's place among the tool calls of one model message.
75///
76/// A host may run one message's tool calls concurrently, so a provider whose
77/// actions must follow the model's intended order (for example input events on
78/// a shared screen) reads this to sequence them. The message id and the index
79/// travel together, because an index means nothing without the message it
80/// counts within; a position missing either one does not decode.
81///
82/// Like the rest of [`CallOrigin`], it is a claim by the forwarding module and
83/// never authority.
84#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
85#[non_exhaustive]
86pub struct MessagePosition {
87    /// The model message's id, an opaque token with the same bounds as
88    /// [`ToolCallRequest::call_key`].
89    pub message_id: String,
90    /// The call's 0-based position among that message's tool calls, in the
91    /// order the model wrote them.
92    pub index: u32,
93}
94
95impl MessagePosition {
96    /// The call at `index` (0-based) among the tool calls of `message_id`.
97    pub fn new(message_id: impl Into<String>, index: u32) -> Self {
98        Self {
99            message_id: message_id.into(),
100            index,
101        }
102    }
103}
104
105/// A tool invocation as carried on a route `REQUEST` frame.
106#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
107pub struct ToolCallRequest {
108    /// The provider's bare manifest tool name (no gateway prefix).
109    pub name: String,
110    /// The arguments exactly as the caller supplied them; consumers never
111    /// translate them, and the provider's manifest schema is what accepts
112    /// or rejects their shape.
113    pub arguments: Value,
114    /// The consumer's own identifier for this call, minted by whatever
115    /// dispatched it (a model runner's WAL intent id, a gateway request id).
116    /// Opaque to the daemon and to subc; unique per call on the consumer's
117    /// side, so a provider's at-most-once fence can key on it directly
118    /// instead of synthesizing an id from the call's contents.
119    ///
120    /// `None` is a statement about the PRODUCER, not the call: it means this
121    /// consumer did not supply an id, never that the call has no identity.
122    /// A reader must not collapse the two — the moment a legacy producer is
123    /// on the other end, treating `None` as "no id exists" and synthesizing
124    /// one silently reproduces exactly the failure this field exists to end.
125    /// A reader that synthesizes a fallback id when this is `None` must
126    /// record that the fallback fired (a fallback that never reports firing
127    /// is indistinguishable from a working component that is quietly wrong).
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub tool_call_id: Option<String>,
130    /// An MCP progress token the consumer wants progress notifications
131    /// correlated to, when the caller requested progress. Opaque here.
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub progress_token: Option<Value>,
134    /// A key the consumer chose for this call, which a provider may use to
135    /// recognise the same call arriving twice. Opaque to the daemon; a
136    /// provider checks only its shape, with [`validate_call_key`], and answers
137    /// a malformed one with `invalid_request` naming the field
138    /// [`CALL_KEY_FIELD`].
139    ///
140    /// This struct is deliberately not `#[non_exhaustive]`: a consumer that
141    /// builds it field by field must decide what key, if any, to send, so a
142    /// new field here is meant to stop its struct literal compiling.
143    #[serde(default, skip_serializing_if = "Option::is_none")]
144    pub call_key: Option<String>,
145    /// Which version of the tool's schema the consumer built its arguments
146    /// against, so a provider can tell a call made against a schema it no
147    /// longer serves. Opaque here: the tool-provider role defines what it
148    /// holds. A provider checks only its shape, with [`validate_schema_pin`],
149    /// and answers a malformed one with `invalid_request` naming the field
150    /// [`SCHEMA_PIN_FIELD`].
151    #[serde(default, skip_serializing_if = "Option::is_none")]
152    pub schema_pin: Option<String>,
153    /// The session's tool preset, assigned by the module that owns the session
154    /// and forwarded by its carrier on every call, outside the model's
155    /// arguments. Opaque to the
156    /// daemon. A provider checks its shape with [`validate_preset`] and answers
157    /// a malformed value with `invalid_request` naming [`PRESET_FIELD`].
158    ///
159    /// Absent means the caller did not say: a provider must decide explicitly
160    /// what an absent preset gets, and must not default it to the most capable
161    /// preset. A provider refuses a preset it does not serve, by name, rather
162    /// than falling back to a default.
163    #[serde(default, skip_serializing_if = "Option::is_none")]
164    pub preset: Option<String>,
165    /// The caller behind this call when the consumer is relaying it for
166    /// someone else; `None` when the consumer is the caller. For attribution
167    /// only, never authority: see [`CallOrigin`]. A provider checks it with
168    /// [`validate_call_origin`].
169    #[serde(default, skip_serializing_if = "Option::is_none")]
170    pub origin: Option<CallOrigin>,
171    /// The llm-runner's output-refs descriptor for this call: which stored set
172    /// of tool-output snapshots the agent's references resolved to, so the
173    /// provider can read those snapshots back from the runner. See
174    /// [`OutputRefs`] for what this crate checks and what it leaves to the
175    /// llm-runner contract.
176    ///
177    /// It sits beside the arguments, never inside them, so the model cannot
178    /// write it. A runner attaches it only to a call whose provider declares
179    /// `output_refs: true`; `None` means the runner sent no descriptor, and the
180    /// member is then left out of the encoding. The daemon never reads it.
181    #[serde(default, skip_serializing_if = "Option::is_none")]
182    pub output_refs: Option<OutputRefs>,
183}
184
185impl ToolCallRequest {
186    /// A call with no consumer id, no progress token, no call key, no schema
187    /// pin, no preset, no origin and no output refs — the shape older
188    /// two-field consumers send.
189    pub fn new(name: impl Into<String>, arguments: Value) -> Self {
190        Self {
191            name: name.into(),
192            arguments,
193            tool_call_id: None,
194            progress_token: None,
195            call_key: None,
196            schema_pin: None,
197            preset: None,
198            origin: None,
199            output_refs: None,
200        }
201    }
202}
203
204/// The wire name of [`ToolCallRequest::call_key`], for the `field` of the
205/// `invalid_request` error a provider returns when the key is malformed.
206pub const CALL_KEY_FIELD: &str = "call_key";
207
208/// The wire name of [`ToolCallRequest::schema_pin`], for the `field` of the
209/// `invalid_request` error a provider returns when the pin is malformed.
210pub const SCHEMA_PIN_FIELD: &str = "schema_pin";
211
212/// The wire name of [`ToolCallRequest::preset`], for a provider's
213/// `invalid_request` error's `field`.
214pub const PRESET_FIELD: &str = "preset";
215
216/// The longest preset accepted, in ASCII characters.
217pub const PRESET_MAX_LEN: usize = 64;
218
219/// Why a tool preset was refused. Each error names [`PRESET_FIELD`], so a
220/// provider can use the same `invalid_request` path as for a schema pin.
221#[derive(Clone, Debug, PartialEq, Eq)]
222#[non_exhaustive]
223pub enum PresetError {
224    Empty,
225    TooLong { length: usize },
226    InvalidCharacter { index: usize },
227}
228
229impl PresetError {
230    pub fn field(&self) -> &'static str {
231        PRESET_FIELD
232    }
233}
234
235impl std::fmt::Display for PresetError {
236    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
237        match self {
238            Self::Empty => write!(f, "preset must not be empty"),
239            Self::TooLong { length } => write!(
240                f,
241                "preset is {length} bytes; at most {PRESET_MAX_LEN} are allowed"
242            ),
243            Self::InvalidCharacter { index } => {
244                write!(
245                    f,
246                    "preset has a character at byte {index} outside [a-z0-9_-]"
247                )
248            }
249        }
250    }
251}
252
253impl std::error::Error for PresetError {}
254
255/// The wire path of [`CallOrigin::call_key`] inside a request, for the `field`
256/// of the `invalid_request` error a provider returns when it is malformed.
257pub const ORIGIN_CALL_KEY_FIELD: &str = "origin.call_key";
258
259/// The wire path of [`MessagePosition::message_id`] inside a request, for the
260/// `field` of the `invalid_request` error a provider returns when it is
261/// malformed.
262pub const ORIGIN_MESSAGE_ID_FIELD: &str = "origin.message_position.message_id";
263
264/// The longest opaque token field accepted, in bytes (every accepted byte is
265/// one ASCII character). Shared by `call_key`, `schema_pin` and scope `flow_id`.
266pub const OPAQUE_FIELD_MAX_LEN: usize = 256;
267
268/// The longest `call_key` accepted.
269pub const CALL_KEY_MAX_LEN: usize = OPAQUE_FIELD_MAX_LEN;
270
271/// The longest `schema_pin` accepted.
272pub const SCHEMA_PIN_MAX_LEN: usize = OPAQUE_FIELD_MAX_LEN;
273
274/// Why an opaque token field (`call_key`, `schema_pin`, `flow_id`) was refused. Every
275/// variant names the request field it is about, so a provider can put it in
276/// its `invalid_request` error without tracking which check ran.
277#[derive(Clone, Debug, PartialEq, Eq)]
278pub enum OpaqueFieldError {
279    /// The value was the empty string. An absent value is `None`, never `""`.
280    Empty { field: &'static str },
281    /// The value was longer than [`OPAQUE_FIELD_MAX_LEN`] bytes.
282    TooLong { field: &'static str, length: usize },
283    /// The byte at `index` is not printable, non-space ASCII.
284    InvalidCharacter { field: &'static str, index: usize },
285}
286
287/// The error [`validate_call_key`] returns. Kept as a name so code that only
288/// formats the error or reads [`OpaqueFieldError::field`] keeps compiling.
289pub type CallKeyError = OpaqueFieldError;
290
291impl OpaqueFieldError {
292    /// The request field the error is about.
293    pub fn field(&self) -> &'static str {
294        match self {
295            Self::Empty { field }
296            | Self::TooLong { field, .. }
297            | Self::InvalidCharacter { field, .. } => field,
298        }
299    }
300}
301
302impl std::fmt::Display for OpaqueFieldError {
303    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
304        match self {
305            Self::Empty { field } => write!(f, "{field} must not be empty"),
306            Self::TooLong { field, length } => write!(
307                f,
308                "{field} is {length} bytes; at most {OPAQUE_FIELD_MAX_LEN} are allowed"
309            ),
310            Self::InvalidCharacter { field, index } => write!(
311                f,
312                "{field} has a character at byte {index} outside printable ASCII \
313                 (0x21 to 0x7E; space is not allowed)"
314            ),
315        }
316    }
317}
318
319impl std::error::Error for OpaqueFieldError {}
320
321/// Check an opaque token field: 1 to [`OPAQUE_FIELD_MAX_LEN`] characters, each
322/// printable ASCII from 0x21 to 0x7E. `field` is the wire name the error
323/// reports.
324///
325/// Space (0x20) is refused. Providers compare these values byte for byte and
326/// write them into logs and ledgers, where a leading or trailing space is
327/// invisible: two values that differ only by one would read as the same value
328/// and act as different ones. Every other printable character is allowed, so
329/// a consumer can use its existing ids (UUIDs, `prefix:id` forms, base64,
330/// digests) unchanged.
331pub(crate) fn validate_opaque_field(
332    field: &'static str,
333    value: &str,
334) -> Result<(), OpaqueFieldError> {
335    if value.is_empty() {
336        return Err(OpaqueFieldError::Empty { field });
337    }
338    if value.len() > OPAQUE_FIELD_MAX_LEN {
339        return Err(OpaqueFieldError::TooLong {
340            field,
341            length: value.len(),
342        });
343    }
344    if let Some(index) = value
345        .bytes()
346        .position(|byte| !(0x21..=0x7e).contains(&byte))
347    {
348        return Err(OpaqueFieldError::InvalidCharacter { field, index });
349    }
350    Ok(())
351}
352
353/// Check a `call_key` with the shared opaque-field rule; errors name
354/// [`CALL_KEY_FIELD`].
355pub fn validate_call_key(key: &str) -> Result<(), CallKeyError> {
356    validate_opaque_field(CALL_KEY_FIELD, key)
357}
358
359/// Check a `schema_pin` with the shared opaque-field rule; errors name
360/// [`SCHEMA_PIN_FIELD`].
361pub fn validate_schema_pin(pin: &str) -> Result<(), OpaqueFieldError> {
362    validate_opaque_field(SCHEMA_PIN_FIELD, pin)
363}
364
365/// Check a preset: 1 to [`PRESET_MAX_LEN`] ASCII characters in `[a-z0-9_-]`.
366/// Errors name [`PRESET_FIELD`]. An absent preset is `None`, not an empty string.
367pub fn validate_preset(preset: &str) -> Result<(), PresetError> {
368    if preset.is_empty() {
369        return Err(PresetError::Empty);
370    }
371    if preset.len() > PRESET_MAX_LEN {
372        return Err(PresetError::TooLong {
373            length: preset.len(),
374        });
375    }
376    if let Some(index) = preset.bytes().position(|byte| {
377        !(byte.is_ascii_lowercase() || byte.is_ascii_digit() || b"_-".contains(&byte))
378    }) {
379        return Err(PresetError::InvalidCharacter { index });
380    }
381    Ok(())
382}
383
384/// Check a [`CallOrigin`]: its `call_key`, and its message position's
385/// `message_id` when present, must pass the shared opaque-field rule. Errors
386/// name [`ORIGIN_CALL_KEY_FIELD`] or [`ORIGIN_MESSAGE_ID_FIELD`]. Every
387/// [`Principal`] is accepted as the carrier, and every `u32` as the index.
388pub fn validate_call_origin(origin: &CallOrigin) -> Result<(), OpaqueFieldError> {
389    validate_opaque_field(ORIGIN_CALL_KEY_FIELD, &origin.call_key)?;
390    if let Some(position) = &origin.message_position {
391        validate_opaque_field(ORIGIN_MESSAGE_ID_FIELD, &position.message_id)?;
392    }
393    Ok(())
394}
395
396/// The wire name of [`ToolCallRequest::output_refs`], for the `field` of the
397/// `invalid_request` error a provider returns when the descriptor is refused.
398pub const OUTPUT_REFS_FIELD: &str = "output_refs";
399
400/// The most bytes an [`OutputRefs`] descriptor may take, measured as compact
401/// JSON. The llm-runner contract bounds its descriptor to the same 4,096
402/// bytes; the check is repeated here so decoding refuses a larger one.
403pub const MAX_OUTPUT_REFS_BYTES: usize = 4 * 1024;
404
405/// The llm-runner's output-refs descriptor, carried opaquely.
406///
407/// When an agent refers to earlier tool output, the llm-runner resolves those
408/// references into a stored set of snapshots and describes that set with a
409/// descriptor. The descriptor's schema belongs to the llm-runner contract (the
410/// `cortexkit-role-llm-runner` crate in the CortexKit commons repository), and
411/// a provider decodes it with that crate's type. This crate does not copy the
412/// schema, so the two cannot drift: it checks only that the value is a JSON
413/// object of at most [`MAX_OUTPUT_REFS_BYTES`] bytes, and refuses anything
414/// else, both when building one with [`OutputRefs::new`] and when decoding.
415/// The daemon relays route bodies without reading them, so it never reads
416/// this.
417#[derive(Clone, Debug, PartialEq, Eq)]
418pub struct OutputRefs(Map<String, Value>);
419
420impl OutputRefs {
421    /// Accept `value` as a descriptor if it is a JSON object whose compact
422    /// encoding is at most [`MAX_OUTPUT_REFS_BYTES`] bytes.
423    pub fn new(value: Value) -> Result<Self, OutputRefsError> {
424        let Value::Object(map) = value else {
425            return Err(OutputRefsError::NotAnObject);
426        };
427        // Encoding a map of JSON values cannot fail: every key is a string.
428        let length = serde_json::to_vec(&map).map_or(usize::MAX, |bytes| bytes.len());
429        if length > MAX_OUTPUT_REFS_BYTES {
430            return Err(OutputRefsError::TooLarge { length });
431        }
432        Ok(Self(map))
433    }
434
435    /// The descriptor's members, for a provider to decode with the llm-runner
436    /// contract's type.
437    pub fn as_map(&self) -> &Map<String, Value> {
438        &self.0
439    }
440
441    /// The descriptor as a JSON object value.
442    pub fn into_value(self) -> Value {
443        Value::Object(self.0)
444    }
445}
446
447impl TryFrom<Value> for OutputRefs {
448    type Error = OutputRefsError;
449
450    fn try_from(value: Value) -> Result<Self, Self::Error> {
451        Self::new(value)
452    }
453}
454
455impl From<OutputRefs> for Value {
456    fn from(refs: OutputRefs) -> Self {
457        refs.into_value()
458    }
459}
460
461impl Serialize for OutputRefs {
462    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
463        self.0.serialize(serializer)
464    }
465}
466
467impl<'de> Deserialize<'de> for OutputRefs {
468    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
469        let value = Value::deserialize(deserializer)?;
470        Self::new(value).map_err(serde::de::Error::custom)
471    }
472}
473
474/// Why a value was refused as an [`OutputRefs`] descriptor. Every variant is
475/// about [`OUTPUT_REFS_FIELD`].
476#[derive(Clone, Debug, PartialEq, Eq)]
477#[non_exhaustive]
478pub enum OutputRefsError {
479    /// The value was not a JSON object.
480    NotAnObject,
481    /// The object's compact JSON encoding was `length` bytes, more than
482    /// [`MAX_OUTPUT_REFS_BYTES`].
483    TooLarge { length: usize },
484}
485
486impl OutputRefsError {
487    /// The request field the error is about.
488    pub fn field(&self) -> &'static str {
489        OUTPUT_REFS_FIELD
490    }
491}
492
493impl std::fmt::Display for OutputRefsError {
494    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
495        match self {
496            Self::NotAnObject => write!(f, "{OUTPUT_REFS_FIELD} must be a JSON object"),
497            Self::TooLarge { length } => write!(
498                f,
499                "{OUTPUT_REFS_FIELD} is {length} bytes as compact JSON; at most \
500                 {MAX_OUTPUT_REFS_BYTES} are allowed"
501            ),
502        }
503    }
504}
505
506impl std::error::Error for OutputRefsError {}
507
508#[cfg(test)]
509mod tests {
510    use super::*;
511    use serde_json::json;
512
513    #[test]
514    fn omitted_optionals_decode_as_none() {
515        let request: ToolCallRequest =
516            serde_json::from_value(json!({ "name": "grep", "arguments": { "q": "x" } }))
517                .expect("two-field body decodes");
518        assert_eq!(request.tool_call_id, None);
519        assert_eq!(request.progress_token, None);
520        assert_eq!(request.call_key, None);
521        assert_eq!(request.schema_pin, None);
522        assert_eq!(request.preset, None);
523        assert_eq!(request.origin, None);
524    }
525
526    #[test]
527    fn call_key_round_trips_as_a_top_level_member() {
528        let request = ToolCallRequest {
529            name: "grep".to_string(),
530            arguments: json!({ "q": "x" }),
531            tool_call_id: None,
532            progress_token: None,
533            call_key: Some("run-7:call-3".to_string()),
534            schema_pin: None,
535            preset: None,
536            origin: None,
537            output_refs: None,
538        };
539        let encoded = serde_json::to_value(&request).expect("encode");
540        assert_eq!(
541            encoded,
542            json!({ "name": "grep", "arguments": { "q": "x" }, "call_key": "run-7:call-3" })
543        );
544        let decoded: ToolCallRequest = serde_json::from_value(encoded).expect("decode");
545        assert_eq!(decoded, request);
546    }
547
548    #[test]
549    fn a_request_without_a_call_key_omits_the_member_and_round_trips() {
550        let request = ToolCallRequest::new("grep", json!({}));
551        let encoded = serde_json::to_value(&request).expect("encode");
552        assert!(encoded.get("call_key").is_none(), "{encoded}");
553        let decoded: ToolCallRequest = serde_json::from_value(encoded).expect("decode");
554        assert_eq!(decoded.call_key, None);
555        assert_eq!(decoded, request);
556    }
557
558    /// The same bounds for both fields, with each refusal naming its own
559    /// field: one validator, two names.
560    #[test]
561    fn opaque_field_bounds_are_one_to_256_printable_non_space_ascii() {
562        type Validate = fn(&str) -> Result<(), OpaqueFieldError>;
563        let validators: [(&str, Validate); 2] = [
564            (CALL_KEY_FIELD, validate_call_key),
565            (SCHEMA_PIN_FIELD, validate_schema_pin),
566        ];
567        for (field, validate) in validators {
568            assert_eq!(validate(""), Err(OpaqueFieldError::Empty { field }));
569            assert_eq!(validate("k"), Ok(()));
570            assert_eq!(validate(&"k".repeat(256)), Ok(()));
571            assert_eq!(
572                validate(&"k".repeat(257)),
573                Err(OpaqueFieldError::TooLong { field, length: 257 })
574            );
575            assert_eq!(validate("!~"), Ok(()), "both ends of 0x21..=0x7E");
576            for bad in ["ké", "a\tb", "a\u{7f}", "a b"] {
577                assert_eq!(
578                    validate(bad),
579                    Err(OpaqueFieldError::InvalidCharacter { field, index: 1 }),
580                    "{field}: {bad:?}"
581                );
582            }
583            let error = validate("").unwrap_err();
584            assert_eq!(error.field(), field);
585            assert!(error.to_string().starts_with(field), "{error}");
586        }
587    }
588
589    #[test]
590    fn schema_pin_round_trips_as_a_top_level_member() {
591        let request = ToolCallRequest {
592            schema_pin: Some("sha256:0f1e2d".to_string()),
593            ..ToolCallRequest::new("grep", json!({ "q": "x" }))
594        };
595        let encoded = serde_json::to_value(&request).expect("encode");
596        assert_eq!(
597            encoded,
598            json!({ "name": "grep", "arguments": { "q": "x" }, "schema_pin": "sha256:0f1e2d" })
599        );
600        let decoded: ToolCallRequest = serde_json::from_value(encoded).expect("decode");
601        assert_eq!(decoded, request);
602    }
603
604    #[test]
605    fn preset_round_trips_outside_arguments_and_absence_keeps_the_bytes() {
606        let mut request = ToolCallRequest::new("grep", json!({ "q": "x" }));
607        let absent = serde_json::to_string(&request).unwrap();
608        assert_eq!(absent, r#"{"name":"grep","arguments":{"q":"x"}}"#);
609        let decoded: ToolCallRequest = serde_json::from_str(&absent).unwrap();
610        assert_eq!(decoded, request);
611        assert_eq!(decoded.preset, None);
612
613        request.preset = Some("read_only-2".to_string());
614        let encoded = serde_json::to_value(&request).unwrap();
615        assert_eq!(
616            encoded,
617            json!({
618                "name": "grep", "arguments": { "q": "x" }, "preset": "read_only-2"
619            })
620        );
621        assert_eq!(
622            serde_json::from_value::<ToolCallRequest>(encoded).unwrap(),
623            request
624        );
625    }
626
627    #[test]
628    fn preset_bounds_are_one_to_64_lowercase_digits_underscore_or_hyphen() {
629        assert_eq!(validate_preset(""), Err(PresetError::Empty));
630        assert_eq!(validate_preset("a"), Ok(()));
631        assert_eq!(validate_preset(&"a".repeat(64)), Ok(()));
632        assert_eq!(
633            validate_preset(&"a".repeat(65)),
634            Err(PresetError::TooLong { length: 65 })
635        );
636        assert_eq!(validate_preset("a0_-z9"), Ok(()));
637        for bad in ["A", ".", "é", " "] {
638            let error = validate_preset(bad).unwrap_err();
639            assert_eq!(error, PresetError::InvalidCharacter { index: 0 });
640            assert_eq!(error.field(), "preset");
641            assert!(error.to_string().starts_with("preset"));
642            let refusal =
643                crate::ErrorBody::new(crate::error_codes::INVALID_REQUEST, error.to_string())
644                    .with_detail(json!({ "field": error.field() }));
645            assert_eq!(refusal.code, "invalid_request");
646            assert_eq!(refusal.detail.unwrap()["field"], "preset");
647        }
648    }
649
650    #[test]
651    fn a_request_without_a_schema_pin_omits_the_member_and_round_trips() {
652        let request = ToolCallRequest::new("grep", json!({}));
653        let encoded = serde_json::to_value(&request).expect("encode");
654        assert!(encoded.get("schema_pin").is_none(), "{encoded}");
655        let decoded: ToolCallRequest = serde_json::from_value(encoded).expect("decode");
656        assert_eq!(decoded.schema_pin, None);
657        assert_eq!(decoded, request);
658    }
659
660    #[test]
661    fn none_optionals_are_omitted_so_the_wire_matches_the_two_field_shape() {
662        let request = ToolCallRequest::new("grep", json!({ "q": "x" }));
663        let encoded = serde_json::to_value(&request).expect("encode");
664        assert_eq!(
665            encoded,
666            json!({ "name": "grep", "arguments": { "q": "x" } })
667        );
668    }
669
670    #[test]
671    fn tool_call_id_round_trips() {
672        let request = ToolCallRequest {
673            name: "grep".to_string(),
674            arguments: json!({ "q": "x" }),
675            tool_call_id: Some("wal-intent-42".to_string()),
676            progress_token: None,
677            call_key: None,
678            schema_pin: None,
679            preset: None,
680            origin: None,
681            output_refs: None,
682        };
683        let encoded = serde_json::to_value(&request).expect("encode");
684        assert_eq!(encoded["tool_call_id"], json!("wal-intent-42"));
685        let decoded: ToolCallRequest = serde_json::from_value(encoded).expect("decode");
686        assert_eq!(decoded, request);
687    }
688
689    #[test]
690    fn unknown_members_do_not_fail_a_provider_decode() {
691        // A newer consumer added a key this provider has never heard of; the
692        // call must still decode rather than refuse.
693        let request: ToolCallRequest = serde_json::from_value(json!({
694            "name": "grep",
695            "arguments": {},
696            "some_future_key": { "nested": true }
697        }))
698        .expect("unknown members are tolerated");
699        assert_eq!(request.name, "grep");
700    }
701
702    fn relayed_origin() -> CallOrigin {
703        CallOrigin::new(
704            Principal::Reserved {
705                module_id: "broca".to_string(),
706            },
707            "broca:run-7/call-3",
708        )
709    }
710
711    /// The carrier travels as the tagged `Principal` object the daemon stamps
712    /// on a route, never as a bare string.
713    #[test]
714    fn origin_round_trips_as_a_top_level_member_with_a_tagged_carrier() {
715        let request = ToolCallRequest {
716            call_key: Some("pf:relay/991".to_string()),
717            origin: Some(relayed_origin()),
718            ..ToolCallRequest::new("grep", json!({ "q": "x" }))
719        };
720        let encoded = serde_json::to_value(&request).expect("encode");
721        assert_eq!(
722            encoded,
723            json!({
724                "name": "grep",
725                "arguments": { "q": "x" },
726                "call_key": "pf:relay/991",
727                "origin": {
728                    "carrier": { "kind": "reserved", "module_id": "broca" },
729                    "call_key": "broca:run-7/call-3"
730                }
731            })
732        );
733        let decoded: ToolCallRequest = serde_json::from_value(encoded).expect("decode");
734        assert_eq!(decoded, request);
735    }
736
737    /// The position travels inside `origin` as one object, and an origin without
738    /// one keeps exactly the bytes it had before positions existed.
739    #[test]
740    fn message_position_round_trips_and_is_omitted_when_unknown() {
741        let origin = relayed_origin().with_message_position(MessagePosition::new("msg_01AbC", 2));
742        let encoded = serde_json::to_value(&origin).expect("encode");
743        assert_eq!(
744            encoded,
745            json!({
746                "carrier": { "kind": "reserved", "module_id": "broca" },
747                "call_key": "broca:run-7/call-3",
748                "message_position": { "message_id": "msg_01AbC", "index": 2 }
749            })
750        );
751        let decoded: CallOrigin = serde_json::from_value(encoded).expect("decode");
752        assert_eq!(decoded, origin);
753
754        let without = serde_json::to_value(relayed_origin()).expect("encode");
755        assert!(without.get("message_position").is_none(), "{without}");
756        let decoded: CallOrigin = serde_json::from_value(without).expect("decode");
757        assert_eq!(decoded.message_position, None);
758    }
759
760    /// An index means nothing without its message, so a position missing either
761    /// member is refused at decode rather than read as a half-known order.
762    #[test]
763    fn a_message_position_missing_either_member_does_not_decode() {
764        for position in [json!({ "index": 0 }), json!({ "message_id": "m" })] {
765            let body = json!({
766                "carrier": { "kind": "direct" },
767                "call_key": "k",
768                "message_position": position
769            });
770            assert!(
771                serde_json::from_value::<CallOrigin>(body.clone()).is_err(),
772                "{body}"
773            );
774        }
775    }
776
777    /// Unknown members inside a message position are ignored when decoding, so
778    /// a reader tolerates members a later version adds.
779    #[test]
780    fn unknown_members_inside_a_message_position_are_tolerated() {
781        let decoded: CallOrigin = serde_json::from_value(json!({
782            "carrier": { "kind": "direct" },
783            "call_key": "k",
784            "message_position": { "message_id": "m", "index": 4, "later": true }
785        }))
786        .expect("unknown members inside a position are tolerated");
787        assert_eq!(decoded.message_position, Some(MessagePosition::new("m", 4)));
788    }
789
790    #[test]
791    fn a_malformed_message_id_is_refused_by_its_field() {
792        for bad in [
793            String::new(),
794            "has space".to_string(),
795            "x".repeat(OPAQUE_FIELD_MAX_LEN + 1),
796        ] {
797            let origin = CallOrigin::new(Principal::Direct, "k")
798                .with_message_position(MessagePosition::new(bad.clone(), 0));
799            let error = validate_call_origin(&origin).expect_err(&bad);
800            assert_eq!(error.field(), ORIGIN_MESSAGE_ID_FIELD, "{bad:?}");
801        }
802        let good = CallOrigin::new(Principal::Direct, "k")
803            .with_message_position(MessagePosition::new("msg_01AbC", u32::MAX));
804        assert_eq!(validate_call_origin(&good), Ok(()));
805    }
806
807    #[test]
808    fn a_request_without_an_origin_omits_the_member_and_decodes_as_none() {
809        let request = ToolCallRequest::new("grep", json!({}));
810        let encoded = serde_json::to_value(&request).expect("encode");
811        assert!(encoded.get("origin").is_none(), "{encoded}");
812        let decoded: ToolCallRequest = serde_json::from_value(encoded).expect("decode");
813        assert_eq!(decoded.origin, None);
814        assert_eq!(decoded, request);
815    }
816
817    #[test]
818    fn a_request_with_an_origin_and_an_unknown_member_still_decodes() {
819        let request: ToolCallRequest = serde_json::from_value(json!({
820            "name": "grep",
821            "arguments": {},
822            "origin": {
823                "carrier": { "kind": "direct" },
824                "call_key": "k",
825                "some_future_origin_key": 1
826            },
827            "some_future_key": { "nested": true }
828        }))
829        .expect("unknown members are tolerated");
830        assert_eq!(
831            request.origin,
832            Some(CallOrigin::new(Principal::Direct, "k"))
833        );
834    }
835
836    #[test]
837    fn call_origin_key_refusals_name_the_origin_call_key_field() {
838        let carrier = Principal::Direct;
839        let field = ORIGIN_CALL_KEY_FIELD;
840        assert_eq!(field, "origin.call_key");
841        let cases = [
842            (String::new(), OpaqueFieldError::Empty { field }),
843            (
844                "k".repeat(257),
845                OpaqueFieldError::TooLong { field, length: 257 },
846            ),
847            (
848                "pf:relay 991".to_string(),
849                OpaqueFieldError::InvalidCharacter { field, index: 8 },
850            ),
851        ];
852        for (key, expected) in cases {
853            let error = validate_call_origin(&CallOrigin::new(carrier.clone(), key.clone()))
854                .expect_err("malformed origin key is refused");
855            assert_eq!(error, expected, "{key:?}");
856            assert_eq!(error.field(), "origin.call_key", "{key:?}");
857        }
858    }
859
860    #[test]
861    fn call_origin_accepts_every_carrier_kind() {
862        let carriers = [
863            Principal::Reserved {
864                module_id: "prefrontal-core".to_string(),
865            },
866            Principal::Direct,
867            Principal::Unverified,
868        ];
869        for carrier in carriers {
870            assert_eq!(
871                validate_call_origin(&CallOrigin::new(carrier.clone(), "pf:relay/991")),
872                Ok(()),
873                "{carrier:?}"
874            );
875        }
876    }
877}