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