agent_types/action.rs
1//! Action-currency pure types (M3 ActionExecutor seam): Action, ActionFormat,
2//! ActionOutcome, Observation, ObservationEvent, BatchStatus.
3//!
4//! One set of vocabulary for every action backend — tool calls today, CodeAct
5//! cells tomorrow. These types are the persistable currency of checkpoints
6//! (`BeforeActions`/`AfterActions` payloads) and the runtime currency of the
7//! `ActionExecutor` seam, so they live here with zero runtime dependencies.
8
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11
12use llm_trait::message::ChatMessage;
13
14/// Which protocol an action came from. The format label travels with every
15/// [`Action`] so mixed backends stay distinguishable in persisted payloads.
16#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
17#[serde(rename_all = "snake_case")]
18pub enum ActionFormat {
19 /// A tool call in the OpenAI-style envelope (id, name, args).
20 ToolCall,
21 /// A CodeAct step (intent + code cell).
22 CodeAct,
23}
24
25/// One unit of "something the model asked the runtime to do".
26///
27/// Replaces the bare `(id, name, args)` triple as the kernel currency; the
28/// triple stays internal to the tool-call backend's executor. `identity` is
29/// the counting fingerprint assigned at parse time (tool = name + canonical
30/// args, code = canonical code) so limit middlewares count by semantic unit.
31#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
32pub struct Action {
33 /// Pairing id (tool_call_id / cell id).
34 pub id: String,
35 /// Tool name, or the action kind label for non-tool backends.
36 pub name: String,
37 /// Action arguments. Tool calls carry the provider envelope's argument
38 /// text **byte-for-byte** as a JSON string (`Value::String`) — it may be
39 /// truncated non-JSON, and the history protocol must echo it exactly
40 /// (sanitized downstream). Structured backends use an object, e.g.
41 /// `{"code": …}` for cells. Use [`Action::raw_args`] to read the text.
42 pub args: Value,
43 /// Counting fingerprint computed at parse time by the backend.
44 pub identity: String,
45 /// Backend format label.
46 pub format: ActionFormat,
47}
48
49impl Action {
50 /// Build a tool-call action from the provider envelope. The argument text is
51 /// kept byte-for-byte (`Value::String`); `identity` is the counting
52 /// fingerprint ([`Action::tool_call_identity`]).
53 pub fn from_tool_call(
54 id: impl Into<String>,
55 name: impl Into<String>,
56 args: impl Into<String>,
57 ) -> Self {
58 let name = name.into();
59 let args = args.into();
60 Self {
61 id: id.into(),
62 identity: Self::tool_call_identity(&name, &args),
63 name,
64 args: Value::String(args),
65 format: ActionFormat::ToolCall,
66 }
67 }
68
69 /// Counting fingerprint for a tool call: name + canonical (key-sorted) args.
70 /// The single source of the identity format — limit middlewares count by
71 /// this same unit.
72 pub fn tool_call_identity(name: &str, args: &str) -> String {
73 let canonical = serde_json::from_str::<Value>(args)
74 .map(|v| v.to_string())
75 .unwrap_or_else(|_| args.to_string());
76 format!("{name}::{canonical}")
77 }
78
79 /// Build a CodeAct cell action (intent + code). The code is the counting
80 /// fingerprint verbatim (design D5: 代码=canonical code — a cell has no
81 /// arguments to canonicalize, the source text *is* the semantic unit).
82 /// `args` carries the engine's own block shape `{"intent", "code"}` — one
83 /// vocabulary with the codexec host protocol.
84 pub fn from_code_cell(
85 id: impl Into<String>,
86 intent: impl Into<String>,
87 code: impl Into<String>,
88 ) -> Self {
89 let intent = intent.into();
90 let code = code.into();
91 Self {
92 id: id.into(),
93 name: "code_cell".into(),
94 identity: code.clone(),
95 args: serde_json::json!({ "intent": intent, "code": code }),
96 format: ActionFormat::CodeAct,
97 }
98 }
99
100 /// The action's argument text: string payloads verbatim (tool calls),
101 /// anything else rendered as compact JSON (structured payloads).
102 pub fn raw_args(&self) -> std::borrow::Cow<'_, str> {
103 match &self.args {
104 Value::String(s) => std::borrow::Cow::Borrowed(s.as_str()),
105 other => std::borrow::Cow::Owned(other.to_string()),
106 }
107 }
108}
109
110/// Per-action result — the model-visible fate of one [`Action`] (D9: a policy
111/// refusal lands here, never as a silent drop). Batch-level failure is
112/// `ExecError`; "something went wrong along the way" is an outcome, not an
113/// error.
114#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
115pub struct ActionOutcome {
116 /// Matches [`Action::id`] for pairing.
117 pub action_id: String,
118 /// Action name (tool name / kind label).
119 pub name: String,
120 /// Whether the action completed as intended.
121 pub ok: bool,
122 /// `true` when the failure was an approval denial (not an execution error).
123 #[serde(default)]
124 pub denied: bool,
125 /// Model-visible summary (result text, or why it was refused).
126 pub summary: String,
127 /// Machine-readable metadata for UI consumers (never sent to the LLM).
128 #[serde(default, skip_serializing_if = "Option::is_none")]
129 pub details: Option<Value>,
130}
131
132/// The tax-3 channel: observations become events, big payloads stay behind a
133/// reference (D9: no `Error` variant — refusals and interceptions live in
134/// [`ActionOutcome`]).
135#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
136#[serde(tag = "type", rename_all = "snake_case")]
137pub enum ObservationEvent {
138 /// Inline text.
139 Text { text: String },
140 /// A captured artifact referenced by id; body is fetched on demand.
141 Artifact {
142 capture_id: String,
143 kind: String,
144 summary: String,
145 },
146}
147
148/// Batch-level health of an execution round (D15).
149#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
150#[serde(rename_all = "snake_case")]
151pub enum BatchStatus {
152 /// Every action ran to a fate (success, failure, or denial).
153 Completed,
154 /// The execution environment died mid-batch; completed work is preserved.
155 EnvDied,
156 /// The batch was cut off (crash window) and its fates were reconstructed
157 /// at resume (D3 observation replay) — synthetic, not observed.
158 Interrupted,
159}
160
161/// What the runtime observed after executing a batch of actions (D15: always
162/// returned once anything ran — `ExecError` is reserved for "nothing ran").
163///
164/// `history_messages` is the BACKEND's protocol rendering; the kernel pushes
165/// them verbatim and never interprets them.
166// ChatMessage (llm-trait) has no PartialEq — compare observations via
167// canonical JSON, the family convention (see checkpoint tests).
168#[derive(Clone, Debug, Serialize, Deserialize)]
169pub struct Observation {
170 /// One entry per action, in submission order (ids pair with the batch).
171 pub outcomes: Vec<ActionOutcome>,
172 /// Tax-3 event channel (typed empty until M3c fills it).
173 pub events: Vec<ObservationEvent>,
174 /// Backend-rendered history messages to push as-is.
175 pub history_messages: Vec<ChatMessage>,
176 /// Batch health.
177 pub batch_status: BatchStatus,
178}
179
180#[cfg(test)]
181mod tests {
182 use super::*;
183
184 fn sample_actions() -> Vec<Action> {
185 vec![
186 Action {
187 id: "call_1".into(),
188 name: "weather".into(),
189 // Tool calls carry the envelope's raw argument text.
190 args: Value::String(r#"{"city": "Tokyo"}"#.into()),
191 identity: r#"weather::{"city":"Tokyo"}"#.into(),
192 format: ActionFormat::ToolCall,
193 },
194 Action {
195 id: "cell_1".into(),
196 name: "code_cell".into(),
197 args: serde_json::json!({"code": "print(1)"}),
198 identity: "print(1)".into(),
199 format: ActionFormat::CodeAct,
200 },
201 ]
202 }
203
204 #[test]
205 fn action_raw_args_is_byte_faithful_for_tool_calls() {
206 let actions = sample_actions();
207 // The tool-call payload is echoed exactly (whitespace included).
208 assert_eq!(actions[0].raw_args(), r#"{"city": "Tokyo"}"#);
209 // Structured payloads render as compact JSON.
210 assert_eq!(actions[1].raw_args(), r#"{"code":"print(1)"}"#);
211 }
212
213 #[test]
214 fn from_tool_call_builds_byte_faithful_action_with_identity() {
215 let a = Action::from_tool_call("call_1", "weather", r#"{"city": "Tokyo"}"#);
216 assert_eq!(a.id, "call_1");
217 assert_eq!(a.name, "weather");
218 assert_eq!(a.args, Value::String(r#"{"city": "Tokyo"}"#.into()));
219 // Identity canonicalizes (compacts) the args.
220 assert_eq!(a.identity, r#"weather::{"city":"Tokyo"}"#);
221 assert_eq!(a.format, ActionFormat::ToolCall);
222 }
223
224 #[test]
225 fn from_code_cell_carries_the_engine_block_shape() {
226 let a = Action::from_code_cell("cell_0", "bind x", "x = 1");
227 assert_eq!(a.id, "cell_0");
228 assert_eq!(a.name, "code_cell");
229 // The block shape is the codexec host vocabulary: {"intent", "code"}.
230 assert_eq!(
231 a.args,
232 serde_json::json!({"intent": "bind x", "code": "x = 1"})
233 );
234 // The code is the counting fingerprint, verbatim.
235 assert_eq!(a.identity, "x = 1");
236 assert_eq!(a.format, ActionFormat::CodeAct);
237 }
238
239 #[test]
240 fn tool_call_identity_canonicalizes_key_order_only() {
241 assert_eq!(
242 Action::tool_call_identity("t", r#"{"a":1,"b":2}"#),
243 Action::tool_call_identity("t", r#"{"b":2,"a":1}"#),
244 );
245 // Unparseable args fall back to the raw text.
246 assert_eq!(Action::tool_call_identity("t", "not-json"), "t::not-json");
247 }
248
249 #[test]
250 fn action_round_trips() {
251 for action in sample_actions() {
252 let json = serde_json::to_string(&action).unwrap();
253 let decoded: Action = serde_json::from_str(&json).unwrap();
254 assert_eq!(decoded, action);
255 }
256 }
257
258 #[test]
259 fn action_format_serializes_snake_case() {
260 let json = serde_json::to_string(&ActionFormat::ToolCall).unwrap();
261 assert_eq!(json, "\"tool_call\"");
262 let json = serde_json::to_string(&ActionFormat::CodeAct).unwrap();
263 assert_eq!(json, "\"code_act\"");
264 }
265
266 #[test]
267 fn observation_round_trips_with_all_parts() {
268 let obs = Observation {
269 outcomes: vec![ActionOutcome {
270 action_id: "call_1".into(),
271 name: "weather".into(),
272 ok: true,
273 denied: false,
274 summary: "20C, clear".into(),
275 details: Some(serde_json::json!({"lines": 3})),
276 }],
277 events: vec![
278 ObservationEvent::Text {
279 text: "ran fine".into(),
280 },
281 ObservationEvent::Artifact {
282 capture_id: "cap_9".into(),
283 kind: "stdout".into(),
284 summary: "1.2 KB stdout".into(),
285 },
286 ],
287 history_messages: vec![ChatMessage::tool("call_1", "20C, clear")],
288 batch_status: BatchStatus::Completed,
289 };
290 let json = serde_json::to_string(&obs).unwrap();
291 let decoded: Observation = serde_json::from_str(&json).unwrap();
292 // ChatMessage has no PartialEq, so compare canonical JSON.
293 assert_eq!(
294 serde_json::to_string(&decoded).unwrap(),
295 serde_json::to_string(&obs).unwrap()
296 );
297 }
298
299 #[test]
300 fn outcome_details_optional_field_is_backward_compatible() {
301 // Old payload without `details` must still deserialize (serde default).
302 let old =
303 r#"{"action_id":"call_1","name":"weather","ok":true,"denied":false,"summary":"20C"}"#;
304 let outcome: ActionOutcome = serde_json::from_str(old).unwrap();
305 assert_eq!(outcome.details, None);
306 }
307
308 #[test]
309 fn batch_status_serializes_snake_case() {
310 let json = serde_json::to_string(&BatchStatus::EnvDied).unwrap();
311 assert_eq!(json, "\"env_died\"");
312 }
313}