kcode_k1_chat_codex_codec/
lib.rs1#![forbid(unsafe_code)]
2
3use kcode_k1_chat_chatend::ChatBox;
4
5#[derive(Clone, Debug, Eq, PartialEq)]
6pub struct Call {
7 pub name: String,
8 pub arguments: String,
9}
10
11#[derive(Clone, Debug, Eq, PartialEq)]
12pub enum BoxValue {
13 History(String),
14 Call(Result<Call, String>),
15}
16
17#[derive(Default)]
18pub struct Codec;
19
20impl kcode_k1_codex_adapter::BoxCodec for Codec {
21 type Box = BoxValue;
22
23 fn tool_call_box(&mut self, call: &kcode_k1_codex_adapter::ToolCall) -> Self::Box {
24 if call.name != "call_ktool" {
25 return BoxValue::Call(Err("tool name must be call_ktool".into()));
26 }
27 let serde_json::Value::Object(values) = &call.arguments else {
28 return BoxValue::Call(Err("tool arguments must be an object".into()));
29 };
30 if values.len() != 2 || !values.contains_key("name") || !values.contains_key("arguments") {
31 return BoxValue::Call(Err("tool arguments must have name and arguments".into()));
32 }
33 let Some(serde_json::Value::String(name)) = values.get("name") else {
34 return BoxValue::Call(Err("tool arguments name must be a string".into()));
35 };
36 let Some(arguments) = values.get("arguments") else {
37 return BoxValue::Call(Err("tool arguments require arguments".into()));
38 };
39 let arguments = match serde_json::to_string(arguments) {
40 Ok(arguments) => arguments,
41 Err(_) => return BoxValue::Call(Err("tool arguments cannot be encoded".into())),
42 };
43 BoxValue::Call(Ok(Call {
44 name: name.clone(),
45 arguments,
46 }))
47 }
48
49 fn box_text<'a>(&self, box_: &'a Self::Box) -> &'a str {
50 match box_ {
51 BoxValue::History(text) => text,
52 BoxValue::Call(_) => "",
53 }
54 }
55}
56
57pub fn project(box_: &ChatBox) -> BoxValue {
58 BoxValue::History(format!(
59 "[Box {} | {}]\n{}",
60 box_.id().get(),
61 box_.box_type(),
62 box_.contents()
63 ))
64}