kcode-k1-chat-codex-state 0.7.5

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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
#![forbid(unsafe_code)]

mod recovery;

pub use kcode_k1_chat_codex_codec::{BoxValue, Call};
pub use kcode_k1_chat_state::{
    AGENT_ATTACHMENT_TYPE, AGENT_MESSAGE_TYPE, AGENT_RESPONSE_TYPE, ActorState, BoxId, ChatBox,
    ProviderGenerated, SYSTEM_MESSAGE_TYPE, TOOL_ATTACHMENT_TYPE, TOOL_CALL_TYPE,
    TOOL_MESSAGE_TYPE, TOOL_RESULT_TYPE, ToolCallId, USER_ATTACHMENT_TYPE, USER_MESSAGE_TYPE,
};
pub use kcode_k1_codex_adapter::{ShimItem, ShimOutput};

use std::sync::Arc;
use std::sync::atomic::AtomicU8;

use kcode_k1_chat_codex_codec::{open_agent_response, project};
use kcode_k1_chat_state::{ProviderCall, StateError};
use recovery::recovered_sequence;

pub const MALFORMED_NATIVE_CALL_METADATA_TYPE: &str = "k1.malformed-native-call.v1";

#[derive(Clone, Debug)]
pub struct Start {
    pub job: u64,
    pub values: Vec<BoxValue>,
    pub attempt: Arc<AtomicU8>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PreparedCall {
    pub tool_call_id: ToolCallId,
    pub name: String,
    pub arguments: String,
    disposition: PreparedCallDisposition,
}
impl PreparedCall {
    pub fn disposition(&self) -> &PreparedCallDisposition {
        &self.disposition
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum PreparedCallDisposition {
    External,
    ImmediateError(Box<ImmediateToolError>),
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ImmediateToolError {
    pub message: String,
    pub native_tool: String,
    pub attempted_ktool: Option<String>,
    pub validation_code: String,
    pub path: String,
    pub expected: String,
    pub received: String,
    pub native_arguments: String,
    pub metadata_type: String,
    pub metadata_contents: String,
}

#[derive(Clone, Debug)]
pub struct PreparedMailboxFlush(Arc<Prepared>);
#[derive(Debug)]
struct Prepared {
    token: u64,
    values: Vec<BoxValue>,
    job: u64,
    external_count: usize,
}
impl PreparedMailboxFlush {
    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,
    ProviderActionAccepted,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Phase {
    ProviderActive,
    ChatendBoundary,
    PendingGeneration,
}
struct Round {
    job: u64,
    accepted_provider_action: bool,
    phase: Phase,
    mailbox_flush_needed: bool,
    restartable: bool,
}
enum Mode {
    Idle,
    Running(Round),
    Stalled(Status, bool),
}

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

impl ConversationState {
    pub fn new(session: [u8; 12]) -> Self {
        Self {
            state: ActorState::new(false),
            session,
            sequence: 0,
            unsubmitted: Vec::new(),
            queued_trigger: false,
            token: 0,
            prepared: None,
            mode: Mode::Idle,
        }
    }
    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 {
            unsubmitted: state.boxes().iter().map(project).collect(),
            state,
            sequence,
            ..Self::new(session)
        })
    }
    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(status, _) => status.clone(),
        }
    }

    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, id: ToolCallId, message: String) -> Result<(), String> {
        self.accept_arrival(false, |state| state.accept_tool_message(id, message))
    }
    pub fn accept_tool_return(
        &mut self,
        id: ToolCallId,
        result: Result<String, String>,
    ) -> Result<(), String> {
        self.accept_arrival(true, |state| state.accept_async_return(id, result))
    }
    pub fn accept_tool_return_v2(
        &mut self,
        id: ToolCallId,
        result: Result<String, String>,
        metadata_type: String,
        metadata_contents: String,
    ) -> Result<(), String> {
        self.accept_arrival(true, |state| {
            state.accept_async_return_v2(id, result, metadata_type, metadata_contents)
        })
    }

    pub fn accept_idle_context_box(
        &mut self,
        box_type: String,
        contents: String,
        hidden_type: String,
        hidden_contents: String,
    ) -> Result<(), String> {
        self.accept_idle(|state| {
            state
                .accept_idle_context_box(box_type, contents, hidden_type, hidden_contents)
                .map(|_| ())
        })
    }
    pub fn accept_idle_context_tool_call(
        &mut self,
        name: String,
        arguments: String,
    ) -> Result<ToolCallId, String> {
        let sequence = next_sequence(self.sequence)?;
        let id = ToolCallId::new(self.session, sequence);
        self.accept_idle(|state| {
            state
                .accept_idle_context_tool_call(ProviderCall {
                    tool_call_id: id,
                    name,
                    arguments,
                })
                .map(|_| ())
        })?;
        self.sequence = sequence;
        Ok(id)
    }
    pub fn accept_idle_context_tool_return(
        &mut self,
        id: ToolCallId,
        result: Result<String, String>,
    ) -> Result<(), String> {
        self.accept_idle(|state| {
            state
                .accept_idle_context_tool_return(id, result)
                .map(|_| ())
        })
    }

    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 promised_id = self.promised_id()?;
        let mut values = std::mem::take(&mut self.unsubmitted);
        values.push(open_agent_response(promised_id));
        let mailbox_flush_needed = std::mem::take(&mut self.queued_trigger);
        self.mode = Mode::Running(Round {
            job: start.job,
            accepted_provider_action: false,
            phase: Phase::ProviderActive,
            mailbox_flush_needed,
            restartable: true,
        });
        Ok(Some(Start {
            job: start.job,
            values,
            attempt: start.attempt,
        }))
    }

    pub fn prepare_stage(
        &mut self,
        job: u64,
        text: String,
        values: Vec<BoxValue>,
    ) -> Result<Vec<PreparedCall>, String> {
        if !matches!(&self.mode,Mode::Running(round) if round.job==job&&round.phase==Phase::ProviderActive)
        {
            return Err("stale Codex inference stage".into());
        }
        if self.prepared.is_some() {
            return Err("a Codex mailbox flush remains uncommitted".into());
        }
        let accepted_provider_action = !values.is_empty();
        let mut sequence = self.sequence;
        let mut generated = Vec::with_capacity(values.len());
        let mut prepared = Vec::new();
        for value in values {
            match value {
                BoxValue::AgentMessage(Ok(contents)) => {
                    generated.push(ProviderGenerated::AgentMessage { contents })
                }
                BoxValue::Call(Ok(call)) => {
                    sequence = next_sequence(sequence)?;
                    let id = ToolCallId::new(self.session, sequence);
                    generated.push(ProviderGenerated::ToolCall(ProviderCall {
                        tool_call_id: id,
                        name: call.name.clone(),
                        arguments: call.arguments.clone(),
                    }));
                    prepared.push(PreparedCall {
                        tool_call_id: id,
                        name: call.name,
                        arguments: call.arguments,
                        disposition: PreparedCallDisposition::External,
                    });
                }
                BoxValue::MalformedNativeAction(action) => {
                    sequence = next_sequence(sequence)?;
                    let id = ToolCallId::new(self.session, sequence);
                    let name = action
                        .attempted_ktool()
                        .unwrap_or_else(|| action.native_tool())
                        .to_owned();
                    let arguments = action.native_arguments_json();
                    let error = ImmediateToolError {
                        message: action.diagnostic(),
                        native_tool: action.native_tool().to_owned(),
                        attempted_ktool: action.attempted_ktool().map(str::to_owned),
                        validation_code: action.validation_code().to_owned(),
                        path: action.path().to_owned(),
                        expected: action.expected().to_owned(),
                        received: action.received().to_owned(),
                        native_arguments: arguments.clone(),
                        metadata_type: MALFORMED_NATIVE_CALL_METADATA_TYPE.to_owned(),
                        metadata_contents: action.diagnostic_json(),
                    };
                    generated.push(ProviderGenerated::ToolCall(ProviderCall {
                        tool_call_id: id,
                        name: name.clone(),
                        arguments: arguments.clone(),
                    }));
                    prepared.push(PreparedCall {
                        tool_call_id: id,
                        name,
                        arguments,
                        disposition: PreparedCallDisposition::ImmediateError(Box::new(error)),
                    });
                }
                _ => return Err("stage contains a malformed provider action".into()),
            }
        }
        let before = self.state.boxes().len();
        self.state
            .append_stage(job, text, generated)
            .map_err(debug)?;
        self.unsubmitted.extend(
            self.state.boxes()[before..]
                .iter()
                .filter(|b| b.box_type() == TOOL_CALL_TYPE)
                .map(project),
        );
        self.sequence = sequence;
        if let Mode::Running(round) = &mut self.mode {
            round.accepted_provider_action |= accepted_provider_action;
            round.phase = Phase::ChatendBoundary;
            round.mailbox_flush_needed = true;
            round.restartable = false;
        }
        Ok(prepared)
    }

    pub fn mailbox_flush(&mut self, job: u64) -> Result<Vec<ChatBox>, String> {
        if !matches!(&self.mode,Mode::Running(round) if round.job==job&&round.phase==Phase::ChatendBoundary)
        {
            return Err("stale Codex active-arrival mailbox flush".into());
        }
        let boxes = self.state.flush_active_arrivals(job).map_err(debug)?;
        self.unsubmitted.extend(boxes.iter().map(project));
        if let Mode::Running(round) = &mut self.mode {
            round.phase = Phase::PendingGeneration;
        }
        Ok(boxes)
    }
    pub fn prepare_mailbox_flush(
        &mut self,
        job: u64,
    ) -> Result<Option<PreparedMailboxFlush>, String> {
        let (needed, phase) = match &self.mode {
            Mode::Running(round) if round.job == job => (round.mailbox_flush_needed, round.phase),
            _ => return Err("stale Codex inference mailbox flush".into()),
        };
        if let Some(value) = &self.prepared {
            return Ok(Some(PreparedMailboxFlush(Arc::clone(value))));
        }
        if !needed {
            return Ok(None);
        }
        if phase == Phase::ProviderActive {
            return Ok(None);
        }
        if phase == Phase::ChatendBoundary {
            self.mailbox_flush(job)?;
        }
        let token = self
            .token
            .checked_add(1)
            .ok_or_else(|| "Codex mailbox-flush token space was exhausted".to_owned())?;
        let external_count = self.unsubmitted.len();
        let mut values = self.unsubmitted.clone();
        values.push(open_agent_response(self.promised_id()?));
        let prepared = Arc::new(Prepared {
            token,
            values,
            job,
            external_count,
        });
        self.token = token;
        self.prepared = Some(Arc::clone(&prepared));
        if let Mode::Running(round) = &mut self.mode {
            round.mailbox_flush_needed = false;
        }
        Ok(Some(PreparedMailboxFlush(prepared)))
    }
    pub fn validate_mailbox_flush(&self, value: &PreparedMailboxFlush) -> Result<(), String> {
        let p = &value.0;
        let prefix =
            self.unsubmitted.get(..p.external_count) == Some(&p.values[..p.external_count]);
        let valid = matches!(&self.mode,Mode::Running(round) if round.job==p.job&&round.phase==Phase::PendingGeneration)
            && self.token == p.token
            && prefix
            && self
                .prepared
                .as_ref()
                .is_some_and(|current| Arc::ptr_eq(current, p));
        if valid {
            Ok(())
        } else {
            Err("stale or invalid Codex mailbox flush".into())
        }
    }
    pub fn commit_mailbox_flush(&mut self, value: PreparedMailboxFlush) -> Result<(), String> {
        self.validate_mailbox_flush(&value)?;
        self.unsubmitted.drain(..value.0.external_count);
        self.prepared = None;
        if let Mode::Running(round) = &mut self.mode {
            round.phase = Phase::ProviderActive;
        }
        Ok(())
    }

    pub fn complete(&mut self, job: u64, output: ShimOutput<BoxValue>) -> Result<(), String> {
        let mut round = self.take_round(job)?;
        if round.phase != Phase::ProviderActive {
            let m = "Codex inference completed outside a provider generation".to_owned();
            self.preserve(round, m.clone(), false);
            return Err(m);
        }
        if self.prepared.is_some() {
            let m = "Codex inference completed with an uncommitted mailbox flush".to_owned();
            self.preserve(round, m.clone(), false);
            return Err(m);
        }
        let mut text = String::new();
        for item in output.items {
            match item {
                ShimItem::Text(value) => text.push_str(&value),
                ShimItem::Box(_) => {
                    round.accepted_provider_action = true;
                    let m = "terminal Codex output contains a box".to_owned();
                    self.preserve(round, m.clone(), false);
                    return Err(m);
                }
            }
        }
        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().skip(1).map(project));
        self.queued_trigger = false;
        self.mode = Mode::Idle;
        Ok(())
    }
    pub fn fail(&mut self, job: u64, message: String, restartable: bool) {
        if let Ok(round) = self.take_round(job) {
            self.preserve(round, message, restartable)
        }
    }
    pub fn restart(&mut self) -> Result<(), RestartError> {
        match &self.mode {
            Mode::Stalled(_, true) => return Err(RestartError::ProviderActionAccepted),
            Mode::Stalled(
                Status::Stalled {
                    restartable: true, ..
                },
                false,
            ) => {}
            _ => return Err(RestartError::NotStalled),
        }
        self.state.restart().map_err(|_| RestartError::NotStalled)?;
        self.unsubmitted = self.state.boxes().iter().map(project).collect();
        self.queued_trigger = false;
        self.prepared = None;
        self.mode = Mode::Idle;
        Ok(())
    }

    fn accept_idle<F>(&mut self, accept: F) -> Result<(), String>
    where
        F: FnOnce(&mut ActorState) -> Result<(), StateError>,
    {
        if !matches!(self.mode, Mode::Idle) || self.prepared.is_some() {
            return Err("startup context requires an idle conversation".into());
        }
        let before = self.state.boxes().len();
        accept(&mut self.state).map_err(debug)?;
        self.unsubmitted
            .extend(self.state.boxes()[before..].iter().map(project));
        Ok(())
    }
    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));
        match &mut self.mode {
            Mode::Running(round) => round.mailbox_flush_needed |= triggering,
            Mode::Idle if appended.is_empty() => self.queued_trigger |= triggering,
            Mode::Idle => self.queued_trigger = false,
            Mode::Stalled(_, _) => {}
        }
        Ok(())
    }
    fn promised_id(&self) -> Result<BoxId, String> {
        let prior = self.state.boxes().last().map_or(0, |b| b.id().get());
        prior
            .checked_add(1)
            .map(BoxId::new)
            .ok_or_else(|| "BoxId space was exhausted".into())
    }
    fn take_round(&mut self, job: u64) -> Result<Round, String> {
        match std::mem::replace(&mut self.mode, Mode::Idle) {
            Mode::Running(round) if round.job == job => Ok(round),
            other => {
                self.mode = other;
                Err("stale Codex inference completion".into())
            }
        }
    }
    fn preserve(&mut self, round: Round, message: String, restartable_before_launch: bool) {
        self.prepared = None;
        let restartable = restartable_before_launch
            && round.restartable
            && !round.accepted_provider_action
            && self
                .state
                .stall_inference(round.job, message.clone())
                .is_ok();
        if !restartable {
            let _ = self.state.halt(message.clone());
        }
        self.mode = Mode::Stalled(
            Status::Stalled {
                message,
                restartable,
            },
            round.accepted_provider_action,
        );
    }
}
fn next_sequence(value: u64) -> Result<u64, String> {
    value
        .checked_add(1)
        .ok_or_else(|| "ToolCallId space was exhausted".into())
}
fn debug(error: impl std::fmt::Debug) -> String {
    format!("{error:?}")
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn idle_startup_context_is_ordered_nontriggering_and_correlated() {
        let mut state = ConversationState::new([7; 12]);
        state
            .accept_idle_context_box(
                SYSTEM_MESSAGE_TYPE.into(),
                "prefix".into(),
                String::new(),
                String::new(),
            )
            .unwrap();
        let id = state
            .accept_idle_context_tool_call("KmapOpenNode".into(), "{}".into())
            .unwrap();
        state
            .accept_idle_context_tool_return(id, Ok("loaded".into()))
            .unwrap();
        assert_eq!(state.status(), Status::Quiet);
        assert!(state.begin().unwrap().is_none());
        state
            .accept(
                USER_MESSAGE_TYPE.into(),
                "kickoff".into(),
                String::new(),
                String::new(),
            )
            .unwrap();
        assert!(state.begin().unwrap().is_some());
        assert_eq!(
            state
                .boxes()
                .iter()
                .map(ChatBox::box_type)
                .collect::<Vec<_>>(),
            [
                SYSTEM_MESSAGE_TYPE,
                TOOL_CALL_TYPE,
                TOOL_RESULT_TYPE,
                USER_MESSAGE_TYPE
            ]
        );
    }
}