kcode-k1-chat-boxes 0.2.1

Canonical K1 chat box values and correlated tool metadata
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
#![forbid(unsafe_code)]

pub const SYSTEM_MESSAGE_TYPE: &str = "System Message";
pub const USER_MESSAGE_TYPE: &str = "User Message";
pub const AGENT_MESSAGE_TYPE: &str = "Agent Message";
pub const AGENT_RESPONSE_TYPE: &str = "Agent Response";
pub const USER_ATTACHMENT_TYPE: &str = "User Attachment";
pub const AGENT_ATTACHMENT_TYPE: &str = "Agent Attachment";
pub const TOOL_CALL_TYPE: &str = "Tool Call";
pub const TOOL_MESSAGE_TYPE: &str = "Tool Message";
pub const TOOL_ATTACHMENT_TYPE: &str = "Tool Attachment";
pub const TOOL_RESULT_TYPE: &str = "Tool Result";
pub const ATTACHMENT_TYPE: &str = USER_ATTACHMENT_TYPE;

pub const TOOL_CALL_HIDDEN_TYPE: &str = "k1.tool-call/v1";
pub const TOOL_MESSAGE_HIDDEN_TYPE: &str = "k1.tool-message/v1";
pub const TOOL_MESSAGE_V2_HIDDEN_TYPE: &str = "k1.tool-message/v2";
pub const TOOL_RESULT_HIDDEN_TYPE: &str = "k1.tool-result/v1";
pub const TOOL_RESULT_V2_HIDDEN_TYPE: &str = "k1.tool-result/v2";

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct BoxId(u64);

impl BoxId {
    pub const fn new(value: u64) -> Self {
        Self(value)
    }

    pub const fn get(self) -> u64 {
        self.0
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ToolCallId {
    nonce: [u8; 12],
    sequence: u64,
}

impl ToolCallId {
    pub const fn new(nonce: [u8; 12], sequence: u64) -> Self {
        Self { nonce, sequence }
    }

    pub const fn nonce(self) -> [u8; 12] {
        self.nonce
    }

    pub const fn sequence(self) -> u64 {
        self.sequence
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ChatBox {
    id: BoxId,
    box_type: String,
    contents: String,
    hidden_type: String,
    hidden_contents: String,
}

impl ChatBox {
    pub fn new(
        id: BoxId,
        box_type: String,
        contents: String,
        hidden_type: String,
        hidden_contents: String,
    ) -> Self {
        Self {
            id,
            box_type,
            contents,
            hidden_type,
            hidden_contents,
        }
    }

    pub const fn id(&self) -> BoxId {
        self.id
    }

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

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

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

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

    pub fn tool_call_metadata(&self) -> Result<Option<ProviderCall>, MetadataError> {
        let Some(fields) = self.metadata_fields(TOOL_CALL_TYPE, TOOL_CALL_HIDDEN_TYPE, 4)? else {
            return Ok(None);
        };
        Ok(Some(ProviderCall {
            tool_call_id: parse_tool_call_id(fields[0], fields[1])?,
            name: fields[2].to_owned(),
            arguments: fields[3].to_owned(),
        }))
    }

    pub fn tool_message_metadata(&self) -> Result<Option<ToolMessageMetadata>, MetadataError> {
        let (fields, named) = match self.hidden_type.as_str() {
            TOOL_MESSAGE_HIDDEN_TYPE => (
                self.metadata_fields(TOOL_MESSAGE_TYPE, TOOL_MESSAGE_HIDDEN_TYPE, 5)?
                    .ok_or(MetadataError)?,
                false,
            ),
            TOOL_MESSAGE_V2_HIDDEN_TYPE => {
                if self.box_type.is_empty() {
                    return Err(MetadataError);
                }
                (
                    decode_fields(&self.hidden_contents, 5).ok_or(MetadataError)?,
                    true,
                )
            }
            _ => return Ok(None),
        };
        let message_index = parse_u64(fields[3])?;
        if message_index == 0 || (named && self.contents != fields[4]) {
            return Err(MetadataError);
        }
        Ok(Some(ToolMessageMetadata {
            tool_call_id: parse_tool_call_id(fields[0], fields[1])?,
            originating_call: BoxId::new(parse_u64(fields[2])?),
            message_index,
            message: fields[4].to_owned(),
        }))
    }

    pub fn tool_result_metadata(&self) -> Result<Option<ToolResultMetadata>, MetadataError> {
        let fields = match self.hidden_type.as_str() {
            TOOL_RESULT_HIDDEN_TYPE => {
                self.metadata_fields(TOOL_RESULT_TYPE, TOOL_RESULT_HIDDEN_TYPE, 5)?
            }
            TOOL_RESULT_V2_HIDDEN_TYPE => {
                self.metadata_fields(TOOL_RESULT_TYPE, TOOL_RESULT_V2_HIDDEN_TYPE, 7)?
            }
            _ => None,
        };
        fields
            .map(|fields| parse_result_fields(&fields))
            .transpose()
    }

    pub fn tool_result_v2_metadata(&self) -> Result<Option<ToolResultV2Metadata>, MetadataError> {
        let Some(fields) = self.metadata_fields(TOOL_RESULT_TYPE, TOOL_RESULT_V2_HIDDEN_TYPE, 7)?
        else {
            return Ok(None);
        };
        let parsed = parse_result_fields(&fields)?;
        Ok(Some(ToolResultV2Metadata {
            tool_call_id: parsed.tool_call_id,
            originating_call: parsed.originating_call,
            result: parsed.result,
            metadata_type: fields[5].to_owned(),
            metadata_contents: fields[6].to_owned(),
        }))
    }

    fn metadata_fields<'a>(
        &'a self,
        box_type: &str,
        hidden_type: &str,
        count: usize,
    ) -> Result<Option<Vec<&'a str>>, MetadataError> {
        match (self.hidden_type == hidden_type, self.box_type == box_type) {
            (false, _) => Ok(None),
            (true, false) => Err(MetadataError),
            (true, true) => decode_fields(&self.hidden_contents, count)
                .map(Some)
                .ok_or(MetadataError),
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MetadataError;

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProviderCall {
    pub tool_call_id: ToolCallId,
    pub name: String,
    pub arguments: String,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ToolMessageMetadata {
    pub tool_call_id: ToolCallId,
    pub originating_call: BoxId,
    pub message_index: u64,
    pub message: String,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ToolResultMetadata {
    pub tool_call_id: ToolCallId,
    pub originating_call: BoxId,
    pub result: Result<String, String>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ToolResultV2Metadata {
    pub tool_call_id: ToolCallId,
    pub originating_call: BoxId,
    pub result: Result<String, String>,
    pub metadata_type: String,
    pub metadata_contents: String,
}

pub fn tool_call_box(call: &ProviderCall) -> ChatBox {
    let call_id = format_tool_call_id(call.tool_call_id);
    let nonce = encode_nonce(call.tool_call_id.nonce);
    let sequence = call.tool_call_id.sequence.to_string();
    let hidden_contents = encode_fields(&[&nonce, &sequence, &call.name, &call.arguments]);
    ChatBox::new(
        BoxId::new(0),
        TOOL_CALL_TYPE.to_owned(),
        format!(
            "Call ID: {call_id}\nCall Name: {}\nArguments:\n{}",
            call.name, call.arguments
        ),
        TOOL_CALL_HIDDEN_TYPE.to_owned(),
        hidden_contents,
    )
}

pub fn tool_message_box(metadata: &ToolMessageMetadata) -> Result<ChatBox, MetadataError> {
    let hidden_contents = tool_message_hidden_contents(metadata)?;
    let call_id = format_tool_call_id(metadata.tool_call_id);
    let origin = metadata.originating_call.get();
    let index = metadata.message_index;
    Ok(ChatBox::new(
        BoxId::new(0),
        TOOL_MESSAGE_TYPE.to_owned(),
        format!(
            "Call ID: {call_id}\nOriginating Call Box ID: {origin}\nMessage Index: {index}\nMessage:\n{}",
            metadata.message
        ),
        TOOL_MESSAGE_HIDDEN_TYPE.to_owned(),
        hidden_contents,
    ))
}

pub fn named_tool_message_box(
    metadata: &ToolMessageMetadata,
    title: &str,
) -> Result<ChatBox, MetadataError> {
    if title.is_empty() {
        return Err(MetadataError);
    }
    let hidden_contents = tool_message_hidden_contents(metadata)?;
    Ok(ChatBox::new(
        BoxId::new(0),
        title.to_owned(),
        metadata.message.clone(),
        TOOL_MESSAGE_V2_HIDDEN_TYPE.to_owned(),
        hidden_contents,
    ))
}

fn tool_message_hidden_contents(metadata: &ToolMessageMetadata) -> Result<String, MetadataError> {
    if metadata.message_index == 0 {
        return Err(MetadataError);
    }
    let nonce = encode_nonce(metadata.tool_call_id.nonce);
    let sequence = metadata.tool_call_id.sequence.to_string();
    let origin = metadata.originating_call.get().to_string();
    let index = metadata.message_index.to_string();
    Ok(encode_fields(&[
        &nonce,
        &sequence,
        &origin,
        &index,
        &metadata.message,
    ]))
}

pub fn tool_result_box(
    tool_call_id: ToolCallId,
    originating_call: BoxId,
    result: Result<String, String>,
) -> ChatBox {
    tool_result_box_inner(tool_call_id, originating_call, &result, None)
}

pub fn tool_result_v2_box(metadata: &ToolResultV2Metadata) -> ChatBox {
    tool_result_box_inner(
        metadata.tool_call_id,
        metadata.originating_call,
        &metadata.result,
        Some((&metadata.metadata_type, &metadata.metadata_contents)),
    )
}

fn tool_result_box_inner(
    tool_call_id: ToolCallId,
    originating_call: BoxId,
    result: &Result<String, String>,
    metadata: Option<(&str, &str)>,
) -> ChatBox {
    let call_id = format_tool_call_id(tool_call_id);
    let nonce = encode_nonce(tool_call_id.nonce);
    let sequence = tool_call_id.sequence.to_string();
    let origin = originating_call.get().to_string();
    let (hidden_status, visible_status, raw_result) = match result {
        Ok(contents) => ("ok", "ok", contents),
        Err(contents) => ("err", "error", contents),
    };
    let mut fields = vec![
        nonce.as_str(),
        sequence.as_str(),
        origin.as_str(),
        hidden_status,
        raw_result.as_str(),
    ];
    if let Some((metadata_type, metadata_contents)) = metadata {
        fields.extend([metadata_type, metadata_contents]);
    }
    let hidden_contents = encode_fields(&fields);
    let hidden_type = metadata
        .map(|_| TOOL_RESULT_V2_HIDDEN_TYPE)
        .unwrap_or(TOOL_RESULT_HIDDEN_TYPE);
    ChatBox::new(
        BoxId::new(0),
        TOOL_RESULT_TYPE.to_owned(),
        format!(
            "Call ID: {call_id}\nOriginating Call Box ID: {origin}\nStatus: {visible_status}\nResult:\n{raw_result}"
        ),
        hidden_type.to_owned(),
        hidden_contents,
    )
}

fn parse_result_fields(fields: &[&str]) -> Result<ToolResultMetadata, MetadataError> {
    let result = match fields[3] {
        "ok" => Ok(fields[4].to_owned()),
        "err" => Err(fields[4].to_owned()),
        _ => return Err(MetadataError),
    };
    Ok(ToolResultMetadata {
        tool_call_id: parse_tool_call_id(fields[0], fields[1])?,
        originating_call: BoxId::new(parse_u64(fields[2])?),
        result,
    })
}

fn parse_tool_call_id(nonce: &str, sequence: &str) -> Result<ToolCallId, MetadataError> {
    let nonce = decode_nonce(nonce).ok_or(MetadataError)?;
    Ok(ToolCallId::new(nonce, parse_u64(sequence)?))
}

fn parse_u64(value: &str) -> Result<u64, MetadataError> {
    value.parse::<u64>().map_err(|_| MetadataError)
}

fn format_tool_call_id(tool_call_id: ToolCallId) -> String {
    format!(
        "{}/{}",
        encode_nonce(tool_call_id.nonce),
        tool_call_id.sequence
    )
}

fn encode_fields(fields: &[&str]) -> String {
    let mut encoded = String::new();
    for field in fields {
        encoded.push_str(&field.len().to_string());
        encoded.push(':');
        encoded.push_str(field);
    }
    encoded
}

fn decode_fields(input: &str, count: usize) -> Option<Vec<&str>> {
    let mut fields = Vec::with_capacity(count);
    let mut cursor = 0;
    for _ in 0..count {
        let colon_offset = input
            .as_bytes()
            .get(cursor..)?
            .iter()
            .position(|byte| *byte == b':')?;
        let colon = cursor.checked_add(colon_offset)?;
        let length = input.get(cursor..colon)?.parse::<usize>().ok()?;
        let start = colon.checked_add(1)?;
        let end = start.checked_add(length)?;
        fields.push(input.get(start..end)?);
        cursor = end;
    }
    (cursor == input.len()).then_some(fields)
}

fn encode_nonce(nonce: [u8; 12]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut encoded = String::with_capacity(24);
    for byte in nonce {
        encoded.push(char::from(HEX[usize::from(byte >> 4)]));
        encoded.push(char::from(HEX[usize::from(byte & 0x0f)]));
    }
    encoded
}

fn decode_nonce(value: &str) -> Option<[u8; 12]> {
    if value.len() != 24 {
        return None;
    }
    let mut nonce = [0; 12];
    for (slot, digits) in nonce.iter_mut().zip(value.as_bytes().chunks_exact(2)) {
        let digits = std::str::from_utf8(digits).ok()?;
        *slot = u8::from_str_radix(digits, 16).ok()?;
    }
    Some(nonce)
}

#[cfg(test)]
mod tests;