lutum-protocol 0.1.0

Core traits and request/response types for lutum
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
use std::{borrow::Borrow, fmt};

use serde::{Deserialize, Deserializer, Serialize, Serializer, de::DeserializeOwned};
use serde_json::value::RawValue;
use thiserror::Error;

use crate::transcript::CommittedTurn;

#[derive(Clone, Debug, Default)]
pub struct ModelInput {
    items: Vec<ModelInputItem>,
}

impl ModelInput {
    pub fn new() -> Self {
        Self { items: Vec::new() }
    }

    pub fn from_items(items: Vec<ModelInputItem>) -> Self {
        Self { items }
    }

    pub fn items(&self) -> &[ModelInputItem] {
        &self.items
    }

    pub fn into_items(self) -> Vec<ModelInputItem> {
        self.items
    }

    pub fn push(&mut self, item: ModelInputItem) {
        self.items.push(item);
    }

    pub fn system(mut self, text: impl Into<String>) -> Self {
        self.push(ModelInputItem::text(InputMessageRole::System, text));
        self
    }

    pub fn developer(mut self, text: impl Into<String>) -> Self {
        self.push(ModelInputItem::text(InputMessageRole::Developer, text));
        self
    }

    pub fn user(mut self, text: impl Into<String>) -> Self {
        self.push(ModelInputItem::text(InputMessageRole::User, text));
        self
    }

    pub fn assistant_text(mut self, text: impl Into<String>) -> Self {
        self.push(ModelInputItem::assistant_text(text));
        self
    }

    pub fn assistant_reasoning(mut self, text: impl Into<String>) -> Self {
        self.push(ModelInputItem::assistant_reasoning(text));
        self
    }

    pub fn assistant_refusal(mut self, text: impl Into<String>) -> Self {
        self.push(ModelInputItem::assistant_refusal(text));
        self
    }

    pub fn tool_use(mut self, tool_use: ToolUse) -> Self {
        self.push(ModelInputItem::tool_use(tool_use));
        self
    }

    pub fn validate(&self) -> Result<(), ModelInputValidationError> {
        if self.items.is_empty() {
            return Err(ModelInputValidationError::Empty);
        }

        let mut tool_uses = std::collections::BTreeSet::new();
        for item in &self.items {
            if let ModelInputItem::ToolUse(tool_use) = item
                && !tool_uses.insert(tool_use.id.clone())
            {
                return Err(ModelInputValidationError::DuplicateToolUseId {
                    id: tool_use.id.clone(),
                });
            }
        }

        Ok(())
    }
}

impl From<Vec<ModelInputItem>> for ModelInput {
    fn from(items: Vec<ModelInputItem>) -> Self {
        Self::from_items(items)
    }
}

#[derive(Clone, Debug)]
pub enum ModelInputItem {
    Message {
        role: InputMessageRole,
        content: NonEmpty<MessageContent>,
    },
    Assistant(AssistantInputItem),
    ToolUse(ToolUse),
    Turn(CommittedTurn),
}

impl ModelInputItem {
    pub fn message(role: InputMessageRole, content: NonEmpty<MessageContent>) -> Self {
        Self::Message { role, content }
    }

    pub fn text(role: InputMessageRole, text: impl Into<String>) -> Self {
        Self::Message {
            role,
            content: NonEmpty::one(MessageContent::Text(text.into())),
        }
    }

    pub fn assistant(item: AssistantInputItem) -> Self {
        Self::Assistant(item)
    }

    pub fn assistant_text(text: impl Into<String>) -> Self {
        Self::Assistant(AssistantInputItem::Text(text.into()))
    }

    pub fn assistant_reasoning(text: impl Into<String>) -> Self {
        Self::Assistant(AssistantInputItem::Reasoning(text.into()))
    }

    pub fn assistant_refusal(text: impl Into<String>) -> Self {
        Self::Assistant(AssistantInputItem::Refusal(text.into()))
    }

    pub fn tool_use(tool_use: ToolUse) -> Self {
        Self::ToolUse(tool_use)
    }

    pub fn turn(committed_turn: CommittedTurn) -> Self {
        Self::Turn(committed_turn)
    }

    pub fn tool_use_parts(
        id: impl Into<ToolCallId>,
        name: impl Into<ToolName>,
        arguments: RawJson,
        result: RawJson,
    ) -> Self {
        Self::ToolUse(ToolUse::new(id, name, arguments, result))
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub enum InputMessageRole {
    System,
    Developer,
    User,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub enum MessageContent {
    Text(String),
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
/// Assistant-authored request items that can be replayed into a future model input.
///
/// This is intentionally narrower than [`AssistantTurnItem`]: tool calls are represented
/// as [`ToolUse`] at the surrounding [`ModelInputItem`] level so call/result pairs stay bundled.
pub enum AssistantInputItem {
    Text(String),
    Reasoning(String),
    Refusal(String),
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ToolUse {
    pub id: ToolCallId,
    pub name: ToolName,
    pub arguments: RawJson,
    pub result: RawJson,
}

impl ToolUse {
    pub fn new(
        id: impl Into<ToolCallId>,
        name: impl Into<ToolName>,
        arguments: RawJson,
        result: RawJson,
    ) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            arguments,
            result,
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ToolMetadata {
    pub id: ToolCallId,
    pub name: ToolName,
    pub arguments: RawJson,
}

impl ToolMetadata {
    pub fn new(id: impl Into<ToolCallId>, name: impl Into<ToolName>, arguments: RawJson) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            arguments,
        }
    }

    pub fn into_tool_use(self, result: RawJson) -> ToolUse {
        ToolUse::new(self.id, self.name, self.arguments, result)
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
/// Canonical assistant output for a completed turn.
///
/// This remains richer than [`AssistantInputItem`] because the model can emit tool calls that
/// are not yet paired with tool results at response time.
pub struct AssistantTurn {
    items: NonEmpty<AssistantTurnItem>,
}

impl AssistantTurn {
    pub fn new(items: NonEmpty<AssistantTurnItem>) -> Self {
        Self { items }
    }

    pub fn from_items(items: Vec<AssistantTurnItem>) -> Result<Self, EmptyNonEmptyError> {
        Ok(Self::new(NonEmpty::try_from_vec(items)?))
    }

    pub fn items(&self) -> &[AssistantTurnItem] {
        self.items.as_slice()
    }

    pub fn items_non_empty(&self) -> &NonEmpty<AssistantTurnItem> {
        &self.items
    }

    pub fn into_items(self) -> NonEmpty<AssistantTurnItem> {
        self.items
    }

    pub fn text(text: impl Into<String>) -> Self {
        Self::new(NonEmpty::one(AssistantTurnItem::Text(text.into())))
    }

    pub fn reasoning(text: impl Into<String>) -> Self {
        Self::new(NonEmpty::one(AssistantTurnItem::Reasoning(text.into())))
    }

    pub fn refusal(text: impl Into<String>) -> Self {
        Self::new(NonEmpty::one(AssistantTurnItem::Refusal(text.into())))
    }

    pub fn tool_call(
        id: impl Into<ToolCallId>,
        name: impl Into<ToolName>,
        arguments: RawJson,
    ) -> Self {
        Self::new(NonEmpty::one(AssistantTurnItem::ToolCall {
            id: id.into(),
            name: name.into(),
            arguments,
        }))
    }

    pub fn assistant_text(&self) -> String {
        let mut text = String::new();
        for item in self.items() {
            if let AssistantTurnItem::Text(delta) = item {
                text.push_str(delta);
            }
        }
        text
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
/// Canonical assistant output items for a completed turn.
///
/// Tool calls exist only on the response side. Once a call has been paired with a tool result for
/// replay, it is represented as [`ModelInputItem::ToolUse`] instead.
pub enum AssistantTurnItem {
    Text(String),
    Reasoning(String),
    Refusal(String),
    ToolCall {
        id: ToolCallId,
        name: ToolName,
        arguments: RawJson,
    },
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct NonEmpty<T>(Vec<T>);

impl<T> NonEmpty<T> {
    pub fn one(item: T) -> Self {
        Self(vec![item])
    }

    pub fn try_from_vec(items: Vec<T>) -> Result<Self, EmptyNonEmptyError> {
        if items.is_empty() {
            Err(EmptyNonEmptyError)
        } else {
            Ok(Self(items))
        }
    }

    pub fn as_slice(&self) -> &[T] {
        &self.0
    }

    pub fn iter(&self) -> std::slice::Iter<'_, T> {
        self.0.iter()
    }

    pub fn into_vec(self) -> Vec<T> {
        self.0
    }
}

impl<T> TryFrom<Vec<T>> for NonEmpty<T> {
    type Error = EmptyNonEmptyError;

    fn try_from(value: Vec<T>) -> Result<Self, Self::Error> {
        Self::try_from_vec(value)
    }
}

impl<T> From<NonEmpty<T>> for Vec<T> {
    fn from(value: NonEmpty<T>) -> Self {
        value.0
    }
}

impl<T> Serialize for NonEmpty<T>
where
    T: Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.0.serialize(serializer)
    }
}

impl<'de, T> Deserialize<'de> for NonEmpty<T>
where
    T: Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let values = Vec::<T>::deserialize(deserializer)?;
        Self::try_from_vec(values).map_err(serde::de::Error::custom)
    }
}

impl<T> Borrow<[T]> for NonEmpty<T> {
    fn borrow(&self) -> &[T] {
        self.as_slice()
    }
}

#[derive(Debug, Error, Clone, Copy, Eq, PartialEq)]
#[error("non-empty collection must contain at least one element")]
pub struct EmptyNonEmptyError;

#[derive(Debug, Error, Clone, Eq, PartialEq)]
pub enum ModelInputValidationError {
    #[error("model input must contain at least one item")]
    Empty,
    #[error("duplicate tool use id `{id}` in model input")]
    DuplicateToolUseId { id: ToolCallId },
}

#[derive(Debug, Error, Clone, Eq, PartialEq)]
pub enum AssistantTurnInputError {
    #[error("assistant turn references missing tool use `{id}`")]
    MissingToolUse { id: ToolCallId },
    #[error("assistant turn received duplicate tool use `{id}`")]
    DuplicateToolUse { id: ToolCallId },
    #[error("assistant turn received extra tool use `{id}`")]
    ExtraToolUse { id: ToolCallId },
    #[error("assistant turn tool call `{id}` expected tool name `{expected}`, got `{actual}`")]
    MismatchedToolName {
        id: ToolCallId,
        expected: ToolName,
        actual: ToolName,
    },
    #[error("assistant turn tool call `{id}` received mismatched arguments")]
    MismatchedToolArguments {
        id: ToolCallId,
        expected: RawJson,
        actual: RawJson,
    },
}

#[derive(Serialize, Deserialize)]
#[serde(transparent)]
pub struct RawJson(Box<RawValue>);

impl RawJson {
    pub fn parse(json: impl Into<String>) -> Result<Self, serde_json::Error> {
        RawValue::from_string(json.into()).map(Self)
    }

    pub fn from_serializable<T>(value: &T) -> Result<Self, serde_json::Error>
    where
        T: Serialize,
    {
        RawValue::from_string(serde_json::to_string(value)?).map(Self)
    }

    pub fn get(&self) -> &str {
        self.0.get()
    }

    pub fn deserialize<T>(&self) -> Result<T, serde_json::Error>
    where
        T: DeserializeOwned,
    {
        serde_json::from_str(self.get())
    }
}

impl Clone for RawJson {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl fmt::Debug for RawJson {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("RawJson").field(&self.get()).finish()
    }
}

impl PartialEq for RawJson {
    fn eq(&self, other: &Self) -> bool {
        self.get() == other.get()
    }
}

impl Eq for RawJson {}

impl PartialOrd for RawJson {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for RawJson {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.get().cmp(other.get())
    }
}

impl std::hash::Hash for RawJson {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.get().hash(state);
    }
}

impl fmt::Display for RawJson {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.get())
    }
}

impl From<Box<RawValue>> for RawJson {
    fn from(value: Box<RawValue>) -> Self {
        Self(value)
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ToolCallId(String);

impl ToolCallId {
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for ToolCallId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl From<String> for ToolCallId {
    fn from(value: String) -> Self {
        Self(value)
    }
}

impl From<&str> for ToolCallId {
    fn from(value: &str) -> Self {
        Self(value.to_string())
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ToolName(String);

impl ToolName {
    pub fn new(name: impl Into<String>) -> Self {
        Self(name.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for ToolName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl From<String> for ToolName {
    fn from(value: String) -> Self {
        Self(value)
    }
}

impl From<&str> for ToolName {
    fn from(value: &str) -> Self {
        Self(value.to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use schemars::JsonSchema;
    use serde::{Deserialize, Serialize};

    use crate::toolset::ToolInput;

    #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, JsonSchema)]
    struct WeatherArgs {
        city: String,
    }

    #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, JsonSchema)]
    struct WeatherResult {
        forecast: String,
    }

    impl ToolInput for WeatherArgs {
        type Output = WeatherResult;

        const NAME: &'static str = "weather";
        const DESCRIPTION: &'static str = "Get weather";
    }

    #[test]
    fn raw_json_rejects_invalid_json() {
        assert!(RawJson::parse("{").is_err());
        assert_eq!(
            RawJson::parse("{\"ok\":true}").unwrap().get(),
            "{\"ok\":true}"
        );
    }

    #[test]
    fn non_empty_rejects_empty_vectors() {
        assert!(NonEmpty::<String>::try_from_vec(vec![]).is_err());
    }

    #[test]
    fn model_input_validation_rejects_duplicate_tool_use_ids() {
        let input = ModelInput::from_items(vec![
            ModelInputItem::text(InputMessageRole::User, "hello"),
            ModelInputItem::tool_use_parts(
                "call-1",
                "weather",
                RawJson::parse("{\"city\":\"Tokyo\"}").unwrap(),
                RawJson::parse("\"sunny\"").unwrap(),
            ),
            ModelInputItem::tool_use_parts(
                "call-1",
                "weather",
                RawJson::parse("{\"city\":\"Tokyo\"}").unwrap(),
                RawJson::parse("\"rainy\"").unwrap(),
            ),
        ]);

        assert_eq!(
            input.validate().unwrap_err(),
            ModelInputValidationError::DuplicateToolUseId {
                id: ToolCallId::from("call-1"),
            }
        );
    }

    #[test]
    fn tool_input_serializes_result() {
        let tool_use = WeatherArgs::tool_use(
            ToolMetadata::new(
                "call-1",
                "weather",
                RawJson::parse("{\"city\":\"Tokyo\"}").unwrap(),
            ),
            WeatherResult {
                forecast: "sunny".into(),
            },
        )
        .unwrap();

        assert_eq!(tool_use.result.get(), "{\"forecast\":\"sunny\"}");
    }
}