kcode-k1-codex-conversations 0.1.0

Transport-independent Codex conversation protocol state for K1
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
use serde_json::{Value, json};
use std::{
    collections::{HashMap, HashSet},
    fmt,
    path::PathBuf,
    sync::{Arc, Mutex},
};

pub type ToolToken = (String, u64, String);

#[derive(Clone, Debug)]
pub struct Config {
    pub executable: PathBuf,
    pub working_directory: String,
    pub model: String,
    pub reasoning_effort: Option<String>,
    pub base_instructions: String,
    pub tools: Vec<DynamicTool>,
}

impl Config {
    pub fn validate(&self) -> Result<(), Error> {
        validate_config(self)
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct DynamicTool {
    pub name: String,
    pub description: String,
    pub input_schema: Value,
}

#[derive(Clone, Debug, PartialEq)]
pub struct ToolCall {
    pub call_id: String,
    pub name: String,
    pub arguments: Value,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ToolResult {
    pub success: bool,
    pub output: String,
}

#[derive(Clone, Debug, PartialEq)]
pub enum Event {
    TextDelta(String),
    ToolCall(ToolCall),
    Done,
    Error(Error),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ErrorKind {
    Busy,
    Interrupted,
    InvalidToolResult,
    LaunchRejected,
    Protocol,
    Server,
    Unavailable,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Error {
    pub kind: ErrorKind,
    pub message: String,
    pub diagnostics: Vec<u8>,
}

impl Error {
    pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            message: message.into(),
            diagnostics: Vec::new(),
        }
    }

    pub fn with_diagnostics(mut self, diagnostics: Vec<u8>) -> Self {
        self.diagnostics = diagnostics;
        self
    }

    pub fn server(value: &Value, diagnostics: &Diagnostics) -> Self {
        let detail = value
            .get("message")
            .and_then(Value::as_str)
            .or_else(|| value.pointer("/error/message").and_then(Value::as_str));
        let message = detail.map_or_else(
            || "Codex app-server error".to_owned(),
            |detail| format!("Codex app-server error: {detail}"),
        );
        diagnostics.error(ErrorKind::Server, message)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl std::error::Error for Error {}

#[derive(Clone, Debug, Default)]
pub struct Diagnostics(Arc<Mutex<Vec<u8>>>);

impl Diagnostics {
    pub fn new(bytes: Vec<u8>) -> Self {
        Self(Arc::new(Mutex::new(bytes)))
    }

    pub fn snapshot(&self) -> Vec<u8> {
        self.0
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .clone()
    }

    pub fn replace(&self, bytes: Vec<u8>) {
        *self
            .0
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()) = bytes;
    }

    pub fn error(&self, kind: ErrorKind, message: impl Into<String>) -> Error {
        Error {
            kind,
            message: message.into(),
            diagnostics: self.snapshot(),
        }
    }
}

pub struct Active<S> {
    pub serial: u64,
    pub turn: Option<String>,
    pub sink: Option<S>,
    pub early: Vec<Value>,
    pub cancelled: bool,
    pub interrupt_sent: bool,
    pub failure: Option<Value>,
}

pub struct Conversation<S> {
    pub thread: Option<String>,
    pub active: Option<Active<S>>,
    pub closing: bool,
}

impl<S> Default for Conversation<S> {
    fn default() -> Self {
        Self {
            thread: None,
            active: None,
            closing: false,
        }
    }
}

pub enum Pending<R> {
    Thread {
        key: String,
        serial: u64,
        input: String,
    },
    Turn {
        key: String,
        serial: u64,
    },
    Close {
        key: String,
        thread: String,
        reply: R,
    },
    Interrupt,
}

#[derive(Clone, Debug, PartialEq)]
pub struct PendingTool {
    pub id: Value,
    pub rpc_key: String,
}

pub struct State<S, R> {
    pub conversations: HashMap<String, Conversation<S>>,
    pub by_thread: HashMap<String, String>,
    pub pending: HashMap<u64, Pending<R>>,
    pub tools: HashMap<ToolToken, PendingTool>,
    pub rpc_ids: HashSet<String>,
    pub next_id: u64,
    pub next_turn: u64,
}

impl<S, R> Default for State<S, R> {
    fn default() -> Self {
        Self {
            conversations: HashMap::new(),
            by_thread: HashMap::new(),
            pending: HashMap::new(),
            tools: HashMap::new(),
            rpc_ids: HashSet::new(),
            next_id: 1,
            next_turn: 1,
        }
    }
}

impl<S, R> State<S, R> {
    pub fn allocate_request_id(&mut self) -> Result<u64, Error> {
        let id = self.next_id;
        self.next_id = id
            .checked_add(1)
            .ok_or_else(|| Error::new(ErrorKind::Protocol, "client request id space exhausted"))?;
        Ok(id)
    }

    pub fn allocate_turn_id(&mut self) -> Result<u64, Error> {
        let id = self.next_turn;
        self.next_turn = id
            .checked_add(1)
            .ok_or_else(|| Error::new(ErrorKind::Protocol, "turn serial space exhausted"))?;
        Ok(id)
    }

    pub fn begin_turn(&mut self, key: impl Into<String>, sink: S) -> Result<u64, Error> {
        let key = key.into();
        if self
            .conversations
            .get(&key)
            .is_some_and(|conversation| conversation.active.is_some() || conversation.closing)
        {
            return Err(Error::new(
                ErrorKind::Busy,
                "conversation already has an active turn",
            ));
        }
        let serial = self.allocate_turn_id()?;
        self.conversations.entry(key).or_default().active = Some(Active {
            serial,
            turn: None,
            sink: Some(sink),
            early: Vec::new(),
            cancelled: false,
            interrupt_sent: false,
            failure: None,
        });
        Ok(serial)
    }

    pub fn take_active(&mut self, key: &str, serial: u64) -> Option<Active<S>> {
        let conversation = self.conversations.get_mut(key)?;
        if conversation
            .active
            .as_ref()
            .is_some_and(|active| active.serial == serial)
        {
            conversation.active.take()
        } else {
            None
        }
    }

    pub fn set_native_turn(
        &mut self,
        key: &str,
        serial: u64,
        turn: impl Into<String>,
    ) -> Option<Vec<Value>> {
        let active = self
            .conversations
            .get_mut(key)?
            .active
            .as_mut()
            .filter(|active| active.serial == serial)?;
        active.turn = Some(turn.into());
        Some(std::mem::take(&mut active.early))
    }

    pub fn interrupt_target(&mut self, key: &str, serial: u64) -> Option<(String, String)> {
        let conversation = self.conversations.get_mut(key)?;
        let thread = conversation.thread.clone()?;
        let active = conversation.active.as_mut()?;
        if active.serial != serial || active.interrupt_sent {
            return None;
        }
        let turn = active.turn.clone()?;
        active.interrupt_sent = true;
        Some((thread, turn))
    }

    pub fn take_sinks(&mut self) -> Vec<S> {
        self.conversations
            .values_mut()
            .filter_map(|conversation| conversation.active.take()?.sink)
            .collect()
    }

    pub fn thread(&self, key: &str) -> Option<&str> {
        self.conversations.get(key)?.thread.as_deref()
    }

    pub fn owner(&self, thread: &str) -> Option<&str> {
        self.by_thread.get(thread).map(String::as_str)
    }

    pub fn set_thread(&mut self, key: &str, thread: impl Into<String>) -> Result<(), Error> {
        let thread = thread.into();
        if self
            .by_thread
            .get(&thread)
            .is_some_and(|owner| owner != key)
        {
            return Err(Error::new(
                ErrorKind::Protocol,
                "thread/start reused another conversation thread",
            ));
        }
        let old = self
            .conversations
            .entry(key.to_owned())
            .or_default()
            .thread
            .replace(thread.clone());
        if let Some(old) = old.filter(|old| old != &thread) {
            self.by_thread.remove(&old);
        }
        self.by_thread.insert(thread, key.to_owned());
        Ok(())
    }

    pub fn begin_close(&mut self, key: &str) -> Result<Option<String>, Error> {
        let Some(conversation) = self.conversations.get(key) else {
            return Ok(None);
        };
        if conversation.active.is_some() || conversation.closing {
            return Err(Error::new(
                ErrorKind::Busy,
                "conversation is active or already closing",
            ));
        }
        let Some(thread) = conversation.thread.clone() else {
            self.conversations.remove(key);
            return Ok(None);
        };
        self.conversations
            .get_mut(key)
            .expect("conversation exists")
            .closing = true;
        Ok(Some(thread))
    }

    pub fn cancel_close(&mut self, key: &str) {
        if let Some(conversation) = self.conversations.get_mut(key) {
            conversation.closing = false;
        }
    }

    pub fn finish_close(&mut self, key: &str, thread: &str) -> Result<(), Error> {
        let valid = self.conversations.get(key).is_some_and(|conversation| {
            conversation.thread.as_deref() == Some(thread)
                && conversation.active.is_none()
                && conversation.closing
        });
        if !valid {
            return Err(Error::new(
                ErrorKind::Protocol,
                "thread/unsubscribe response did not match closing conversation",
            ));
        }
        self.by_thread.remove(thread);
        self.conversations.remove(key);
        Ok(())
    }

    pub fn insert_pending(&mut self, id: u64, pending: Pending<R>) -> Result<(), Error> {
        if self.pending.insert(id, pending).is_some() {
            return Err(Error::new(
                ErrorKind::Protocol,
                "duplicate client request id",
            ));
        }
        Ok(())
    }

    pub fn take_pending(&mut self, id: u64) -> Result<Pending<R>, Error> {
        self.pending.remove(&id).ok_or_else(|| {
            Error::new(
                ErrorKind::Protocol,
                "unexpected or duplicate app-server response id",
            )
        })
    }

    pub fn track_tool(
        &mut self,
        key: &str,
        serial: u64,
        call: impl Into<String>,
        id: &Value,
    ) -> Result<ToolToken, Error> {
        let (id, rpc_key) = parse_rpc_id(id)?;
        let token = (key.to_owned(), serial, call.into());
        if self.rpc_ids.contains(&rpc_key) {
            return Err(Error::new(
                ErrorKind::Protocol,
                "duplicate app-server request id",
            ));
        }
        if self.tools.contains_key(&token) {
            return Err(Error::new(
                ErrorKind::Protocol,
                "duplicate dynamic tool call id",
            ));
        }
        self.rpc_ids.insert(rpc_key.clone());
        self.tools
            .insert(token.clone(), PendingTool { id, rpc_key });
        Ok(token)
    }

    pub fn take_tool(&mut self, token: &ToolToken) -> Option<PendingTool> {
        let pending = self.tools.remove(token)?;
        self.rpc_ids.remove(&pending.rpc_key);
        Some(pending)
    }

    pub fn take_turn_tools(&mut self, key: &str, serial: u64) -> Vec<(ToolToken, PendingTool)> {
        let tokens: Vec<_> = self
            .tools
            .keys()
            .filter(|(owner, turn, _)| owner == key && *turn == serial)
            .cloned()
            .collect();
        tokens
            .into_iter()
            .filter_map(|token| self.take_tool(&token).map(|pending| (token, pending)))
            .collect()
    }

    pub fn resolve_tool(&mut self, id: &Value) -> Result<Option<ToolToken>, Error> {
        let (_, rpc_key) = parse_rpc_id(id)?;
        let token = self
            .tools
            .iter()
            .find_map(|(token, pending)| (pending.rpc_key == rpc_key).then(|| token.clone()));
        if let Some(token) = &token {
            self.take_tool(token);
        }
        Ok(token)
    }
}

pub fn validate_config(config: &Config) -> Result<(), Error> {
    let mut names = HashSet::new();
    for tool in &config.tools {
        if tool.name.is_empty() {
            return Err(Error::new(
                ErrorKind::Protocol,
                "dynamic tool names must not be empty",
            ));
        }
        if !names.insert(&tool.name) {
            return Err(Error::new(
                ErrorKind::Protocol,
                format!("duplicate dynamic tool name: {}", tool.name),
            ));
        }
    }
    Ok(())
}

pub fn thread_start_params(config: &Config) -> Value {
    let tools: Vec<_> = config
        .tools
        .iter()
        .map(|tool| {
            json!({
                "name": tool.name,
                "description": tool.description,
                "inputSchema": tool.input_schema
            })
        })
        .collect();
    json!({
        "model": config.model,
        "cwd": config.working_directory,
        "approvalPolicy": "never",
        "sandbox": "readOnly",
        "baseInstructions": config.base_instructions,
        "serviceName": "kcode-k1-codex-adapter",
        "dynamicTools": tools
    })
}

pub fn turn_start_params(thread: &str, input: impl Into<String>) -> Value {
    json!({"threadId": thread, "input": [{"type": "text", "text": input.into()}]})
}

pub fn parse_scope(params: Option<&Value>) -> Result<(&str, &str), Error> {
    let params =
        params.ok_or_else(|| Error::new(ErrorKind::Protocol, "scoped message omitted params"))?;
    let thread = params
        .get("threadId")
        .and_then(Value::as_str)
        .ok_or_else(|| Error::new(ErrorKind::Protocol, "scoped message omitted threadId"))?;
    let turn = params
        .get("turnId")
        .and_then(Value::as_str)
        .or_else(|| params.pointer("/turn/id").and_then(Value::as_str))
        .ok_or_else(|| Error::new(ErrorKind::Protocol, "scoped message omitted turn id"))?;
    Ok((thread, turn))
}

pub fn parse_rpc_id(id: &Value) -> Result<(Value, String), Error> {
    match id {
        Value::String(value) => Ok((id.clone(), format!("s:{value}"))),
        Value::Number(value) => Ok((id.clone(), format!("n:{value}"))),
        _ => Err(Error::new(
            ErrorKind::Protocol,
            "server request id must be a string or number",
        )),
    }
}

pub fn is_model_reroute(method: &str) -> bool {
    let method = method.to_ascii_lowercase();
    method.contains("model") && method.contains("rerout")
}