kcode-k1-chat-codex-state 0.6.0

Deterministic open-format Codex K1 conversation state
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
#![forbid(unsafe_code)]

pub use kcode_k1_chat_codex_codec::{BoxValue, Call};
pub use kcode_k1_chat_state::{
    AGENT_ATTACHMENT_TYPE, AGENT_MESSAGE_TYPE, BoxId, ChatBox, SYSTEM_MESSAGE_TYPE,
    TOOL_ATTACHMENT_TYPE, TOOL_CALL_TYPE, TOOL_MESSAGE_TYPE, TOOL_RESULT_TYPE, ToolCallId,
    USER_ATTACHMENT_TYPE, USER_MESSAGE_TYPE,
};

use std::sync::Arc;

use kcode_k1_chat_codex_codec::project;
use kcode_k1_chat_state::{ActorState, ProviderCall, StateError};
use kcode_k1_codex_adapter::{ShimItem, ShimOutput};

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Start {
    pub job: u64,
    pub boxes: Vec<BoxValue>,
}

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

#[derive(Clone, Debug)]
pub struct PreparedSteer(Arc<Prepared>);

#[derive(Debug)]
struct Prepared {
    values: Vec<BoxValue>,
    job: u64,
    generation: u64,
}

impl PreparedSteer {
    pub fn values(&self) -> &[BoxValue] {
        &self.0.values
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Status {
    Running,
    Quiet,
    Stalled { message: String, restartable: bool },
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RestartError {
    NotStalled,
    NotRestartable,
}

struct Round {
    job: u64,
    accepted_call_wave: bool,
}

enum Mode {
    Idle,
    Running(Round),
    Stalled { message: String, restartable: bool },
}

pub struct ConversationState {
    state: ActorState,
    session: [u8; 12],
    sequence: u64,
    unsubmitted: Vec<BoxValue>,
    queued_trigger: bool,
    steer_required: bool,
    generation: u64,
    prepared: Option<Arc<Prepared>>,
    mode: Mode,
}

impl ConversationState {
    pub fn new(session: [u8; 12]) -> Self {
        Self::from_actor(ActorState::new(false), session, 0)
    }

    pub fn recover(session: [u8; 12], boxes: Vec<ChatBox>, force: bool) -> Result<Self, String> {
        let sequence = recovered_sequence(session, &boxes)?;
        let state = ActorState::recover(boxes, force).map_err(debug)?;
        Ok(Self::from_actor(state, session, sequence))
    }

    pub fn boxes(&self) -> &[ChatBox] {
        self.state.boxes()
    }

    pub fn status(&self) -> Status {
        match &self.mode {
            Mode::Running(_) => Status::Running,
            Mode::Idle if self.state.quiet() => Status::Quiet,
            Mode::Idle => Status::Running,
            Mode::Stalled {
                message,
                restartable,
            } => Status::Stalled {
                message: message.clone(),
                restartable: *restartable,
            },
        }
    }

    pub fn accept(
        &mut self,
        box_type: String,
        contents: String,
        hidden_type: String,
        hidden_contents: String,
    ) -> Result<(), String> {
        self.accept_arrival(true, |state| {
            state.accept_box(box_type, contents, hidden_type, hidden_contents)
        })
    }

    pub fn accept_tool_message(
        &mut self,
        tool_call_id: ToolCallId,
        message: String,
    ) -> Result<(), String> {
        self.accept_arrival(false, |state| {
            state.accept_tool_message(tool_call_id, message)
        })
    }

    pub fn accept_tool_return(
        &mut self,
        tool_call_id: ToolCallId,
        result: Result<String, String>,
    ) -> Result<(), String> {
        self.accept_arrival(true, |state| {
            state.accept_async_return(tool_call_id, result)
        })
    }

    pub fn accept_tool_return_v2(
        &mut self,
        tool_call_id: ToolCallId,
        result: Result<String, String>,
        metadata_type: String,
        metadata_contents: String,
    ) -> Result<(), String> {
        self.accept_arrival(true, |state| {
            state.accept_async_return_v2(tool_call_id, result, metadata_type, metadata_contents)
        })
    }

    pub fn begin(&mut self) -> Result<Option<Start>, String> {
        if !matches!(self.mode, Mode::Idle) {
            return Ok(None);
        }
        let Some(start) = self.state.begin_inference().map_err(debug)? else {
            return Ok(None);
        };
        let boxes = std::mem::take(&mut self.unsubmitted);
        self.steer_required = self.queued_trigger;
        self.mode = Mode::Running(Round {
            job: start.job,
            accepted_call_wave: false,
        });
        Ok(Some(Start {
            job: start.job,
            boxes,
        }))
    }

    pub fn prepare_stage(
        &mut self,
        job: u64,
        text: String,
        values: Vec<BoxValue>,
    ) -> Result<Vec<PreparedCall>, String> {
        let calls = values
            .into_iter()
            .map(|value| match value {
                BoxValue::Call(Ok(call)) => Ok(call),
                _ => Err("stage contains a malformed tool call".to_owned()),
            })
            .collect::<Result<Vec<_>, _>>()?;
        if !matches!(&self.mode, Mode::Running(round) if round.job == job) {
            return Err("stale Codex inference stage".to_owned());
        }
        if self.prepared.is_some() {
            return Err("a Codex steer remains uncommitted".to_owned());
        }
        let mut sequence = self.sequence;
        let mut prepared = Vec::with_capacity(calls.len());
        let mut provider_calls = Vec::with_capacity(calls.len());
        for call in calls {
            sequence = sequence
                .checked_add(1)
                .ok_or_else(|| "ToolCallId space was exhausted".to_owned())?;
            let tool_call_id = ToolCallId::new(self.session, sequence);
            provider_calls.push(ProviderCall {
                tool_call_id,
                name: call.name.clone(),
                arguments: call.arguments.clone(),
            });
            prepared.push(PreparedCall {
                tool_call_id,
                name: call.name,
                arguments: call.arguments,
            });
        }
        self.state
            .append_stage(job, text, provider_calls)
            .map_err(debug)?;
        self.sequence = sequence;
        if !prepared.is_empty()
            && let Mode::Running(round) = &mut self.mode
        {
            round.accepted_call_wave = true;
        }
        Ok(prepared)
    }

    pub fn flush_active_arrivals(&mut self, job: u64) -> Result<Vec<ChatBox>, String> {
        let boxes = self.state.flush_active_arrivals(job).map_err(debug)?;
        self.unsubmitted.extend(boxes.iter().map(project));
        if !boxes.is_empty() {
            self.queued_trigger = false;
        }
        Ok(boxes)
    }

    pub fn prepare_steer(&mut self, job: u64) -> Result<Option<PreparedSteer>, String> {
        if !matches!(&self.mode, Mode::Running(round) if round.job == job) {
            return Err("stale Codex inference steer".to_owned());
        }
        if let Some(prepared) = &self.prepared {
            return Ok(Some(PreparedSteer(Arc::clone(prepared))));
        }
        self.flush_active_arrivals(job)?;
        if !self.steer_required {
            return Ok(None);
        }
        if self.unsubmitted.is_empty() {
            return Err("Codex steer trigger has no pending arrival".to_owned());
        }
        let generation = self
            .generation
            .checked_add(1)
            .ok_or_else(|| "Codex steer generation was exhausted".to_owned())?;
        let prepared = Arc::new(Prepared {
            values: self.unsubmitted.clone(),
            job,
            generation,
        });
        self.generation = generation;
        self.steer_required = false;
        self.prepared = Some(Arc::clone(&prepared));
        Ok(Some(PreparedSteer(prepared)))
    }

    pub fn validate_steer(&self, prepared: &PreparedSteer) -> Result<(), String> {
        let prepared = &prepared.0;
        let valid = matches!(&self.mode, Mode::Running(round) if round.job == prepared.job)
            && self.generation == prepared.generation
            && self.unsubmitted.starts_with(&prepared.values)
            && self
                .prepared
                .as_ref()
                .is_some_and(|value| Arc::ptr_eq(value, prepared));
        if valid {
            Ok(())
        } else {
            Err("stale or invalid Codex steer".to_owned())
        }
    }

    pub fn commit_steer(&mut self, prepared: PreparedSteer) -> Result<(), String> {
        self.validate_steer(&prepared)?;
        self.unsubmitted.drain(..prepared.0.values.len());
        self.prepared = None;
        Ok(())
    }

    pub fn complete(&mut self, job: u64, output: ShimOutput<BoxValue>) -> Result<(), String> {
        let round = self.take_round(job)?;
        if self.prepared.is_some() {
            let message = "Codex inference completed with an uncommitted steer".to_owned();
            self.preserve(round, message.clone(), false);
            return Err(message);
        }
        let mut text = String::new();
        for item in output.items {
            match item {
                ShimItem::Text(value) => text.push_str(&value),
                ShimItem::Box(_) => {
                    let message = "terminal Codex output contains a box".to_owned();
                    self.preserve(round, message.clone(), false);
                    return Err(message);
                }
            }
        }
        if self.steer_required {
            self.state.force_inference();
        }
        let before = self.state.boxes().len();
        if let Err(error) = self.state.complete_inference(job, text).map_err(debug) {
            self.preserve(round, error.clone(), false);
            return Err(error);
        }
        self.unsubmitted
            .extend(self.state.boxes()[before..].iter().map(project));
        self.queued_trigger = false;
        self.steer_required = false;
        self.mode = Mode::Idle;
        Ok(())
    }

    pub fn fail(&mut self, job: u64, message: String, restartable_before_launch: bool) {
        if let Ok(round) = self.take_round(job) {
            self.preserve(round, message, restartable_before_launch);
        }
    }

    pub fn restart(&mut self) -> Result<(), RestartError> {
        match self.mode {
            Mode::Stalled {
                restartable: true, ..
            } => {}
            Mode::Stalled { .. } => return Err(RestartError::NotRestartable),
            _ => return Err(RestartError::NotStalled),
        }
        self.state
            .restart()
            .map_err(|_| RestartError::NotRestartable)?;
        self.unsubmitted = self.state.boxes().iter().map(project).collect();
        self.steer_required = false;
        self.prepared = None;
        self.mode = Mode::Idle;
        Ok(())
    }

    fn from_actor(state: ActorState, session: [u8; 12], sequence: u64) -> Self {
        let unsubmitted = state.boxes().iter().map(project).collect();
        Self {
            state,
            session,
            sequence,
            unsubmitted,
            queued_trigger: false,
            steer_required: false,
            generation: 0,
            prepared: None,
            mode: Mode::Idle,
        }
    }

    fn accept_arrival<F>(&mut self, triggering: bool, accept: F) -> Result<(), String>
    where
        F: FnOnce(&mut ActorState) -> Result<(), StateError>,
    {
        let before = self.state.boxes().len();
        accept(&mut self.state).map_err(debug)?;
        let appended = &self.state.boxes()[before..];
        self.unsubmitted.extend(appended.iter().map(project));
        self.queued_trigger |= triggering && appended.is_empty();
        self.steer_required |= triggering && matches!(self.mode, Mode::Running(_));
        Ok(())
    }

    fn take_round(&mut self, job: u64) -> Result<Round, String> {
        let mode = std::mem::replace(&mut self.mode, Mode::Idle);
        match mode {
            Mode::Running(round) if round.job == job => Ok(round),
            other => {
                self.mode = other;
                Err("stale Codex inference completion".to_owned())
            }
        }
    }

    fn preserve(&mut self, round: Round, message: String, restartable_before_launch: bool) {
        self.prepared = None;
        if round.accepted_call_wave {
            let _ = self.state.complete_inference(round.job, String::new());
            let _ = self.state.halt(message.clone());
            self.mode = Mode::Stalled {
                message,
                restartable: false,
            };
        } else {
            let stalled = self
                .state
                .stall_inference(round.job, message.clone())
                .is_ok();
            self.mode = Mode::Stalled {
                message,
                restartable: stalled && restartable_before_launch,
            };
        }
    }
}

fn recovered_sequence(session: [u8; 12], boxes: &[ChatBox]) -> Result<u64, String> {
    let mut maximum = 0;
    for box_ in boxes {
        if let Some(call) = box_.tool_call_metadata().map_err(debug)? {
            record_sequence(session, call.tool_call_id, &mut maximum)?;
        }
        if let Some(result) = box_.tool_result_metadata().map_err(debug)? {
            record_sequence(session, result.tool_call_id, &mut maximum)?;
        }
        if let Some(result) = box_.tool_result_v2_metadata().map_err(debug)? {
            record_sequence(session, result.tool_call_id, &mut maximum)?;
        }
    }
    Ok(maximum)
}

fn record_sequence(session: [u8; 12], id: ToolCallId, maximum: &mut u64) -> Result<(), String> {
    if id.nonce() != session {
        return Err("recovered ToolCallId belongs to another session".to_owned());
    }
    *maximum = (*maximum).max(id.sequence());
    Ok(())
}

fn debug(error: impl std::fmt::Debug) -> String {
    format!("{error:?}")
}