1use serde::{Deserialize, Deserializer, Serialize, Serializer};
25use serde_json::{Map, Value};
26
27use crate::Principal;
28
29#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
43#[non_exhaustive]
44pub struct CallOrigin {
45 pub carrier: Principal,
47 pub call_key: String,
50 #[serde(default, skip_serializing_if = "Option::is_none")]
53 pub message_position: Option<MessagePosition>,
54}
55
56impl CallOrigin {
57 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 pub fn with_message_position(mut self, position: MessagePosition) -> Self {
69 self.message_position = Some(position);
70 self
71 }
72}
73
74#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
85#[non_exhaustive]
86pub struct MessagePosition {
87 pub message_id: String,
90 pub index: u32,
93}
94
95impl MessagePosition {
96 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#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
107pub struct ToolCallRequest {
108 pub name: String,
110 pub arguments: Value,
114 #[serde(default, skip_serializing_if = "Option::is_none")]
129 pub tool_call_id: Option<String>,
130 #[serde(default, skip_serializing_if = "Option::is_none")]
133 pub progress_token: Option<Value>,
134 #[serde(default, skip_serializing_if = "Option::is_none")]
144 pub call_key: Option<String>,
145 #[serde(default, skip_serializing_if = "Option::is_none")]
152 pub schema_pin: Option<String>,
153 #[serde(default, skip_serializing_if = "Option::is_none")]
164 pub preset: Option<String>,
165 #[serde(default, skip_serializing_if = "Option::is_none")]
170 pub origin: Option<CallOrigin>,
171 #[serde(default, skip_serializing_if = "Option::is_none")]
182 pub output_refs: Option<OutputRefs>,
183}
184
185impl ToolCallRequest {
186 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
204pub const CALL_KEY_FIELD: &str = "call_key";
207
208pub const SCHEMA_PIN_FIELD: &str = "schema_pin";
211
212pub const PRESET_FIELD: &str = "preset";
215
216pub const PRESET_MAX_LEN: usize = 64;
218
219#[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
255pub const ORIGIN_CALL_KEY_FIELD: &str = "origin.call_key";
258
259pub const ORIGIN_MESSAGE_ID_FIELD: &str = "origin.message_position.message_id";
263
264pub const OPAQUE_FIELD_MAX_LEN: usize = 256;
267
268pub const CALL_KEY_MAX_LEN: usize = OPAQUE_FIELD_MAX_LEN;
270
271pub const SCHEMA_PIN_MAX_LEN: usize = OPAQUE_FIELD_MAX_LEN;
273
274#[derive(Clone, Debug, PartialEq, Eq)]
278pub enum OpaqueFieldError {
279 Empty { field: &'static str },
281 TooLong { field: &'static str, length: usize },
283 InvalidCharacter { field: &'static str, index: usize },
285}
286
287pub type CallKeyError = OpaqueFieldError;
290
291impl OpaqueFieldError {
292 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
321pub(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
353pub fn validate_call_key(key: &str) -> Result<(), CallKeyError> {
356 validate_opaque_field(CALL_KEY_FIELD, key)
357}
358
359pub fn validate_schema_pin(pin: &str) -> Result<(), OpaqueFieldError> {
362 validate_opaque_field(SCHEMA_PIN_FIELD, pin)
363}
364
365pub 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
384pub 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
396pub const OUTPUT_REFS_FIELD: &str = "output_refs";
399
400pub const MAX_OUTPUT_REFS_BYTES: usize = 4 * 1024;
404
405#[derive(Clone, Debug, PartialEq, Eq)]
418pub struct OutputRefs(Map<String, Value>);
419
420impl OutputRefs {
421 pub fn new(value: Value) -> Result<Self, OutputRefsError> {
424 let Value::Object(map) = value else {
425 return Err(OutputRefsError::NotAnObject);
426 };
427 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 pub fn as_map(&self) -> &Map<String, Value> {
438 &self.0
439 }
440
441 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#[derive(Clone, Debug, PartialEq, Eq)]
477#[non_exhaustive]
478pub enum OutputRefsError {
479 NotAnObject,
481 TooLarge { length: usize },
484}
485
486impl OutputRefsError {
487 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 #[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 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 #[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 #[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 #[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 #[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}