use serde::{Deserialize, Serialize};
use serde_json::Value;
use llm_trait::message::ChatMessage;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ActionFormat {
ToolCall,
CodeAct,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Action {
pub id: String,
pub name: String,
pub args: Value,
pub identity: String,
pub format: ActionFormat,
}
impl Action {
pub fn from_tool_call(
id: impl Into<String>,
name: impl Into<String>,
args: impl Into<String>,
) -> Self {
let name = name.into();
let args = args.into();
Self {
id: id.into(),
identity: Self::tool_call_identity(&name, &args),
name,
args: Value::String(args),
format: ActionFormat::ToolCall,
}
}
pub fn tool_call_identity(name: &str, args: &str) -> String {
let canonical = serde_json::from_str::<Value>(args)
.map(|v| v.to_string())
.unwrap_or_else(|_| args.to_string());
format!("{name}::{canonical}")
}
pub fn from_code_cell(
id: impl Into<String>,
intent: impl Into<String>,
code: impl Into<String>,
) -> Self {
let intent = intent.into();
let code = code.into();
Self {
id: id.into(),
name: "code_cell".into(),
identity: code.clone(),
args: serde_json::json!({ "intent": intent, "code": code }),
format: ActionFormat::CodeAct,
}
}
pub fn raw_args(&self) -> std::borrow::Cow<'_, str> {
match &self.args {
Value::String(s) => std::borrow::Cow::Borrowed(s.as_str()),
other => std::borrow::Cow::Owned(other.to_string()),
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ActionOutcome {
pub action_id: String,
pub name: String,
pub ok: bool,
#[serde(default)]
pub denied: bool,
pub summary: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub details: Option<Value>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ObservationEvent {
Text { text: String },
Artifact {
capture_id: String,
kind: String,
summary: String,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BatchStatus {
Completed,
EnvDied,
Interrupted,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Observation {
pub outcomes: Vec<ActionOutcome>,
pub events: Vec<ObservationEvent>,
pub history_messages: Vec<ChatMessage>,
pub batch_status: BatchStatus,
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_actions() -> Vec<Action> {
vec![
Action {
id: "call_1".into(),
name: "weather".into(),
args: Value::String(r#"{"city": "Tokyo"}"#.into()),
identity: r#"weather::{"city":"Tokyo"}"#.into(),
format: ActionFormat::ToolCall,
},
Action {
id: "cell_1".into(),
name: "code_cell".into(),
args: serde_json::json!({"code": "print(1)"}),
identity: "print(1)".into(),
format: ActionFormat::CodeAct,
},
]
}
#[test]
fn action_raw_args_is_byte_faithful_for_tool_calls() {
let actions = sample_actions();
assert_eq!(actions[0].raw_args(), r#"{"city": "Tokyo"}"#);
assert_eq!(actions[1].raw_args(), r#"{"code":"print(1)"}"#);
}
#[test]
fn from_tool_call_builds_byte_faithful_action_with_identity() {
let a = Action::from_tool_call("call_1", "weather", r#"{"city": "Tokyo"}"#);
assert_eq!(a.id, "call_1");
assert_eq!(a.name, "weather");
assert_eq!(a.args, Value::String(r#"{"city": "Tokyo"}"#.into()));
assert_eq!(a.identity, r#"weather::{"city":"Tokyo"}"#);
assert_eq!(a.format, ActionFormat::ToolCall);
}
#[test]
fn from_code_cell_carries_the_engine_block_shape() {
let a = Action::from_code_cell("cell_0", "bind x", "x = 1");
assert_eq!(a.id, "cell_0");
assert_eq!(a.name, "code_cell");
assert_eq!(
a.args,
serde_json::json!({"intent": "bind x", "code": "x = 1"})
);
assert_eq!(a.identity, "x = 1");
assert_eq!(a.format, ActionFormat::CodeAct);
}
#[test]
fn tool_call_identity_canonicalizes_key_order_only() {
assert_eq!(
Action::tool_call_identity("t", r#"{"a":1,"b":2}"#),
Action::tool_call_identity("t", r#"{"b":2,"a":1}"#),
);
assert_eq!(Action::tool_call_identity("t", "not-json"), "t::not-json");
}
#[test]
fn action_round_trips() {
for action in sample_actions() {
let json = serde_json::to_string(&action).unwrap();
let decoded: Action = serde_json::from_str(&json).unwrap();
assert_eq!(decoded, action);
}
}
#[test]
fn action_format_serializes_snake_case() {
let json = serde_json::to_string(&ActionFormat::ToolCall).unwrap();
assert_eq!(json, "\"tool_call\"");
let json = serde_json::to_string(&ActionFormat::CodeAct).unwrap();
assert_eq!(json, "\"code_act\"");
}
#[test]
fn observation_round_trips_with_all_parts() {
let obs = Observation {
outcomes: vec![ActionOutcome {
action_id: "call_1".into(),
name: "weather".into(),
ok: true,
denied: false,
summary: "20C, clear".into(),
details: Some(serde_json::json!({"lines": 3})),
}],
events: vec![
ObservationEvent::Text {
text: "ran fine".into(),
},
ObservationEvent::Artifact {
capture_id: "cap_9".into(),
kind: "stdout".into(),
summary: "1.2 KB stdout".into(),
},
],
history_messages: vec![ChatMessage::tool("call_1", "20C, clear")],
batch_status: BatchStatus::Completed,
};
let json = serde_json::to_string(&obs).unwrap();
let decoded: Observation = serde_json::from_str(&json).unwrap();
assert_eq!(
serde_json::to_string(&decoded).unwrap(),
serde_json::to_string(&obs).unwrap()
);
}
#[test]
fn outcome_details_optional_field_is_backward_compatible() {
let old =
r#"{"action_id":"call_1","name":"weather","ok":true,"denied":false,"summary":"20C"}"#;
let outcome: ActionOutcome = serde_json::from_str(old).unwrap();
assert_eq!(outcome.details, None);
}
#[test]
fn batch_status_serializes_snake_case() {
let json = serde_json::to_string(&BatchStatus::EnvDied).unwrap();
assert_eq!(json, "\"env_died\"");
}
}