kcode-k1-chat-codex-codec 0.6.0

Native Codex wrapper validator and open-format K1 ChatBox projector
Documentation
#![forbid(unsafe_code)]

use kcode_k1_chat_chatend::ChatBox;

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

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BoxValue {
    History(String),
    Call(Result<Call, String>),
}

#[derive(Default)]
pub struct Codec;

impl kcode_k1_codex_adapter::BoxCodec for Codec {
    type Box = BoxValue;

    fn tool_call_box(&mut self, call: &kcode_k1_codex_adapter::ToolCall) -> Self::Box {
        if call.name != "call_ktool" {
            return BoxValue::Call(Err("tool name must be call_ktool".into()));
        }
        let serde_json::Value::Object(values) = &call.arguments else {
            return BoxValue::Call(Err("tool arguments must be an object".into()));
        };
        if values.len() != 2 || !values.contains_key("name") || !values.contains_key("arguments") {
            return BoxValue::Call(Err("tool arguments must have name and arguments".into()));
        }
        let Some(serde_json::Value::String(name)) = values.get("name") else {
            return BoxValue::Call(Err("tool arguments name must be a string".into()));
        };
        let Some(arguments) = values.get("arguments") else {
            return BoxValue::Call(Err("tool arguments require arguments".into()));
        };
        let arguments = match serde_json::to_string(arguments) {
            Ok(arguments) => arguments,
            Err(_) => return BoxValue::Call(Err("tool arguments cannot be encoded".into())),
        };
        BoxValue::Call(Ok(Call {
            name: name.clone(),
            arguments,
        }))
    }

    fn box_text<'a>(&self, box_: &'a Self::Box) -> &'a str {
        match box_ {
            BoxValue::History(text) => text,
            BoxValue::Call(_) => "",
        }
    }
}

pub fn project(box_: &ChatBox) -> BoxValue {
    BoxValue::History(format!(
        "[Box {} | {}]\n{}",
        box_.id().get(),
        box_.box_type(),
        box_.contents()
    ))
}