1#![forbid(unsafe_code)]
2
3use kcode_k1_access_kmap::K1AccessKmap;
4use kcode_k1_chat_persistence::Session;
5pub use kcode_k1_chat_state::BoxId;
6use kcode_k1_chat_state::{AGENT_MESSAGE_TYPE, USER_MESSAGE_TYPE};
7use kcode_k1_chat_thread_actions::ChatThreadActions;
8pub use kcode_k1_chat_thread_actions::{AccessContext, AccessPolicy, ProfileId};
9pub use kcode_k1_chat_thread_durable_turn::{
10 BoxValue, ChatBox, EventRecord, ModelUsage, PreparedCall, PreparedMailboxFlush, Status,
11 TokenBreakdown, ToolCallId,
12};
13use kcode_k1_chat_thread_durable_turn::{DurableTurn, RestartError, ShimOutput};
14use serde_json::Value;
15use std::sync::Arc;
16
17#[derive(Clone, Debug, Eq, PartialEq)]
18pub enum TransitionError {
19 Unauthorized,
20 NotStalled,
21 NotRestartable,
22 Internal(String),
23}
24
25pub struct DurableThread {
26 turn: DurableTurn,
27 actions: ChatThreadActions,
28 authorized: bool,
29}
30
31impl DurableThread {
32 pub fn recover(session: Session, kmap: Arc<K1AccessKmap>) -> Result<Self, String> {
33 Ok(Self {
34 turn: DurableTurn::recover(session)?,
35 actions: ChatThreadActions::new(kmap),
36 authorized: false,
37 })
38 }
39
40 pub fn boxes(&self) -> &[ChatBox] {
41 self.turn.boxes()
42 }
43
44 pub fn events(&self) -> Vec<EventRecord> {
45 self.turn.events()
46 }
47
48 pub fn status(&self) -> Status {
49 self.turn.status()
50 }
51
52 pub fn accept_box(
53 &mut self,
54 box_type: String,
55 contents: String,
56 hidden_type: String,
57 hidden_contents: String,
58 ) -> Result<(), String> {
59 self.turn
60 .accept(box_type, contents, hidden_type, hidden_contents)
61 }
62
63 pub fn accept_user(
64 &mut self,
65 context: AccessContext,
66 profile_id: ProfileId,
67 policy: AccessPolicy,
68 contents: String,
69 ) -> Result<(), TransitionError> {
70 let installed = self.bind_authorization(context, profile_id, policy)?;
71 match self.turn.accept(
72 USER_MESSAGE_TYPE.into(),
73 contents,
74 String::new(),
75 String::new(),
76 ) {
77 Ok(()) => Ok(()),
78 Err(error) => {
79 if installed {
80 self.clear_authorization();
81 }
82 Err(TransitionError::Internal(error))
83 }
84 }
85 }
86
87 pub fn accept_return(
88 &mut self,
89 id: ToolCallId,
90 result: Result<String, String>,
91 ) -> Result<(), String> {
92 self.turn.accept_tool_return(id, result)
93 }
94
95 pub fn prepare_stage(
96 &mut self,
97 job: u64,
98 text: String,
99 boxes: Vec<BoxValue>,
100 ) -> Result<Vec<PreparedCall>, String> {
101 self.turn.prepare_stage(job, text, boxes)
102 }
103
104 pub fn launch_action(&mut self, name: &str, arguments: &str) -> Result<String, String> {
105 if name == "SendMessage" {
106 launch_send_message(&mut self.turn, arguments)
107 } else {
108 self.actions.launch(name, arguments)
109 }
110 }
111
112 pub fn accept_tool_message(&mut self, id: ToolCallId, contents: String) -> Result<(), String> {
113 self.turn.accept_tool_message(id, contents)
114 }
115
116 pub fn accept_tool_return(
117 &mut self,
118 id: ToolCallId,
119 result: Result<String, String>,
120 ) -> Result<(), String> {
121 self.turn.accept_tool_return(id, result)
122 }
123
124 pub fn accept_tool_return_v2(
125 &mut self,
126 id: ToolCallId,
127 result: Result<String, String>,
128 metadata_type: String,
129 metadata_contents: String,
130 ) -> Result<(), String> {
131 self.turn
132 .accept_tool_return_v2(id, result, metadata_type, metadata_contents)
133 }
134
135 pub fn prepare_mailbox_flush(
136 &mut self,
137 job: u64,
138 ) -> Result<Option<PreparedMailboxFlush>, String> {
139 self.turn.prepare_mailbox_flush(job)
140 }
141
142 pub fn prepared_input(&self, prepared: &PreparedMailboxFlush) -> Result<String, String> {
143 self.turn.validate_mailbox_flush(prepared)?;
144 render_input(prepared.values())
145 }
146
147 pub fn commit_mailbox_flush(&mut self, prepared: PreparedMailboxFlush) -> Result<(), String> {
148 self.turn.commit_mailbox_flush(prepared)
149 }
150
151 pub fn begin_input(&mut self) -> Result<Option<(u64, String)>, String> {
152 let Some(start) = self.turn.begin()? else {
153 return Ok(None);
154 };
155 Ok(Some((start.job, render_input(&start.values)?)))
156 }
157
158 pub fn complete(&mut self, job: u64, output: ShimOutput<BoxValue>) -> Result<bool, String> {
159 self.turn.complete(job, output)
160 }
161
162 pub fn record_model_usage(
163 &mut self,
164 connected_box_id: u64,
165 usage: ModelUsage,
166 ) -> Result<(), String> {
167 self.turn.record_model_usage(connected_box_id, usage)
168 }
169
170 pub fn fail(&mut self, job: u64, error: String, restartable: bool) {
171 self.turn.fail(job, error, restartable);
172 self.clear_authorization();
173 }
174
175 pub fn restart(
176 &mut self,
177 context: AccessContext,
178 profile_id: ProfileId,
179 policy: AccessPolicy,
180 ) -> Result<(), TransitionError> {
181 let installed = self.bind_authorization(context, profile_id, policy)?;
182 if let Err(error) = self.turn.restart().map_err(|error| match error {
183 RestartError::NotStalled => TransitionError::NotStalled,
184 RestartError::ProviderActionAccepted => TransitionError::NotRestartable,
185 }) {
186 if installed {
187 self.clear_authorization();
188 }
189 return Err(error);
190 }
191 Ok(())
192 }
193
194 pub fn clear_authorization(&mut self) {
195 self.actions.clear_authorization();
196 self.authorized = false;
197 }
198
199 fn bind_authorization(
200 &mut self,
201 context: AccessContext,
202 profile_id: ProfileId,
203 policy: AccessPolicy,
204 ) -> Result<bool, TransitionError> {
205 let installed = !self.authorized;
206 if self
207 .actions
208 .bind_authorization(context, profile_id, policy)
209 .is_err()
210 {
211 if installed {
212 self.actions.clear_authorization();
213 }
214 return Err(TransitionError::Unauthorized);
215 }
216 self.authorized = true;
217 Ok(installed)
218 }
219}
220
221fn launch_send_message(turn: &mut DurableTurn, arguments: &str) -> Result<String, String> {
222 let parsed: Value = serde_json::from_str(arguments).map_err(|_| invalid_send_message())?;
223 let Value::Object(mut fields) = parsed else {
224 return Err(invalid_send_message());
225 };
226 if fields.len() != 1 {
227 return Err(invalid_send_message());
228 }
229 let Some(Value::String(message)) = fields.remove("message") else {
230 return Err(invalid_send_message());
231 };
232 if message.is_empty() {
233 return Err(invalid_send_message());
234 }
235 turn.accept(
236 AGENT_MESSAGE_TYPE.into(),
237 message,
238 String::new(),
239 String::new(),
240 )?;
241 Ok("success".into())
242}
243
244fn invalid_send_message() -> String {
245 "invalid SendMessage arguments".into()
246}
247
248fn render_input(values: &[BoxValue]) -> Result<String, String> {
249 let mut output = String::new();
250 for value in values {
251 let BoxValue::History(section) = value else {
252 return Err("Codex provider input contains a non-history value".into());
253 };
254 if section.is_empty() {
255 continue;
256 }
257 if !output.is_empty() && !output.ends_with('\n') {
258 output.push('\n');
259 }
260 output.push_str(section);
261 }
262 Ok(output)
263}
264
265#[cfg(test)]
266mod tests {
267 use super::*;
268 use kcode_k1_access::K1Access;
269 use kcode_k1_chat_codex_state::Call;
270 use kcode_k1_chat_persistence::{K1ChatPersistence, Session};
271 use kcode_k1_chat_state::{AGENT_RESPONSE_TYPE, TOOL_CALL_TYPE, TOOL_RESULT_TYPE};
272 use kcode_k1_groups::K1Groups;
273 use kcode_k1_kmap::K1Kmap;
274 use kcode_k1_peering::K1Peering;
275 use kcode_k1_txn_ordering::K1TxnOrdering;
276 use tempfile::TempDir;
277
278 fn fixture() -> (TempDir, Session, Arc<K1AccessKmap>) {
279 let root = TempDir::new().unwrap();
280 let ordering = Arc::new(K1TxnOrdering::open(&root.path().join("ordering")).unwrap());
281 let peering =
282 Arc::new(K1Peering::open(&root.path().join("peering"), Arc::clone(&ordering)).unwrap());
283 let groups = Arc::new(
284 K1Groups::open(
285 &root.path().join("groups"),
286 Arc::clone(&ordering),
287 Arc::clone(&peering),
288 )
289 .unwrap(),
290 );
291 let access = Arc::new(
292 K1Access::open(
293 &root.path().join("access"),
294 Arc::clone(&ordering),
295 Arc::clone(&peering),
296 groups,
297 )
298 .unwrap(),
299 );
300 let kmap = Arc::new(
301 K1Kmap::open(
302 &root.path().join("kmap"),
303 Arc::clone(&ordering),
304 Arc::clone(&peering),
305 )
306 .unwrap(),
307 );
308 let access_kmap = Arc::new(K1AccessKmap::open(access, kmap).unwrap());
309 let persistence =
310 K1ChatPersistence::open(&root.path().join("persistence"), ordering, peering).unwrap();
311 let (session, original) = persistence.session([11; 12]).unwrap();
312 assert!(original.records.is_empty());
313 (root, session, access_kmap)
314 }
315
316 #[test]
317 fn send_message_is_durable_ordered_and_recovered_once() {
318 let (_root, session, access_kmap) = fixture();
319 let mut thread = DurableThread::recover(session.clone(), Arc::clone(&access_kmap)).unwrap();
320 thread
321 .accept_box(
322 USER_MESSAGE_TYPE.into(),
323 "hello".into(),
324 String::new(),
325 String::new(),
326 )
327 .unwrap();
328 let (job, _) = thread.begin_input().unwrap().unwrap();
329 let arguments = r#"{"message":"WORKING_MESSAGE"}"#;
330 let calls = thread
331 .prepare_stage(
332 job,
333 String::new(),
334 vec![BoxValue::Call(Ok(Call {
335 name: "SendMessage".into(),
336 arguments: arguments.into(),
337 }))],
338 )
339 .unwrap();
340 assert_eq!(calls.len(), 1);
341 let result = thread.launch_action("SendMessage", arguments);
342 assert_eq!(result, Ok("success".into()));
343 thread
344 .accept_tool_return(calls[0].tool_call_id, result)
345 .unwrap();
346
347 let prepared = thread.prepare_mailbox_flush(job).unwrap().unwrap();
348 let input = thread.prepared_input(&prepared).unwrap();
349 let call_at = input.find("| Tool Call]").unwrap();
350 let message_at = input.find("| Agent Message]").unwrap();
351 let result_at = input.find("| Tool Result]").unwrap();
352 assert!(call_at < message_at && message_at < result_at);
353 assert!(input.ends_with("| Agent Response]\n"));
354 assert_eq!(
355 thread
356 .boxes()
357 .iter()
358 .map(ChatBox::box_type)
359 .collect::<Vec<_>>(),
360 [
361 USER_MESSAGE_TYPE,
362 AGENT_RESPONSE_TYPE,
363 TOOL_CALL_TYPE,
364 AGENT_MESSAGE_TYPE,
365 TOOL_RESULT_TYPE,
366 ]
367 );
368 let message = thread
369 .boxes()
370 .iter()
371 .find(|value| value.box_type() == AGENT_MESSAGE_TYPE)
372 .unwrap();
373 assert_eq!(message.contents(), "WORKING_MESSAGE");
374 assert_eq!((message.hidden_type(), message.hidden_contents()), ("", ""));
375
376 thread.commit_mailbox_flush(prepared).unwrap();
377 assert!(
378 !thread
379 .complete(job, ShimOutput { items: Vec::new() })
380 .unwrap()
381 );
382 drop(thread);
383
384 let mut recovered = DurableThread::recover(session, access_kmap).unwrap();
385 assert_eq!(
386 recovered
387 .boxes()
388 .iter()
389 .filter(|value| value.box_type() == AGENT_MESSAGE_TYPE)
390 .count(),
391 1
392 );
393 let before = recovered.boxes().len();
394 assert!(recovered.launch_action("CurrentTime", "{}").is_ok());
395 assert_eq!(recovered.boxes().len(), before);
396 }
397
398 #[test]
399 fn send_message_rejects_invalid_arguments_without_a_message() {
400 let (_root, session, access_kmap) = fixture();
401 let mut thread = DurableThread::recover(session, access_kmap).unwrap();
402 for arguments in [
403 "",
404 "{",
405 "null",
406 "[]",
407 "{}",
408 r#"{"message":""}"#,
409 r#"{"message":1}"#,
410 r#"{"message":"x","extra":true}"#,
411 ] {
412 let before = thread.boxes().len();
413 assert_eq!(
414 thread.launch_action("SendMessage", arguments),
415 Err("invalid SendMessage arguments".into())
416 );
417 assert_eq!(thread.boxes().len(), before);
418 }
419 }
420}