kimi-wire 0.4.2

Typed Rust client for the Kimi Code CLI Wire protocol.
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
use std::time::Duration;

use kimi_wire::{protocol::*, InMemoryWireClient, WireClient, WireError};

// ============================================================================
// InMemoryWireClient basics
// ============================================================================

#[tokio::test]
async fn test_in_memory_client_new() {
    let client = InMemoryWireClient::new();
    assert!(!client.is_handshake_done());
    assert_eq!(client.outgoing().await.len(), 0);
}

#[tokio::test]
async fn test_in_memory_client_with_default_timeout() {
    let client = InMemoryWireClient::new().with_default_timeout(Duration::from_millis(50));
    // Ensure builder method compiles and returns the client.
    assert!(!client.is_handshake_done());
}

#[cfg(feature = "process")]
#[tokio::test]
async fn test_read_response_timeout_via_transport() {
    use kimi_wire::transport::{ChannelTransport, Transport, TransportWireClient};
    let (transport, mut other) = ChannelTransport::pair();
    let mut client =
        TransportWireClient::new(transport).with_default_timeout(Duration::from_millis(10));

    let msg = RawWireMessage {
        jsonrpc: JsonRpcVersion::V2,
        id: Some("other".to_string()),
        method: None,
        params: None,
        result: Some(serde_json::json!({"status": "ok"})),
        error: None,
    };
    other
        .write_line(&serde_json::to_string(&msg).unwrap())
        .await
        .unwrap();

    let result = client.read_response::<PromptResult>("wanted").await;
    assert!(matches!(result, Err(WireError::Timeout(_))));
}

#[tokio::test]
async fn test_next_id_increments() {
    let mut client = InMemoryWireClient::new();
    assert_eq!(client.next_id(), "req-1");
    assert_eq!(client.next_id(), "req-2");
    assert_eq!(client.next_id(), "req-3");
}

// ============================================================================
// send_request / outgoing
// ============================================================================

#[tokio::test]
async fn test_send_request_stores_outgoing() {
    let mut client = InMemoryWireClient::new();
    let req = JsonRpcRequest {
        jsonrpc: JsonRpcVersion::V2,
        method: "prompt".to_string(),
        id: "req-1".to_string(),
        params: PromptParams {
            user_input: UserInput::Text("hello".to_string()),
        },
    };
    client.send_request(&req).await.unwrap();

    let outgoing = client.outgoing().await;
    assert_eq!(outgoing.len(), 1);
    let json = outgoing[0].as_object().unwrap();
    assert_eq!(json["method"], "prompt");
    assert_eq!(json["id"], "req-1");
}

// ============================================================================
// read_raw_message / read_raw_message_timeout
// ============================================================================

#[tokio::test]
async fn test_read_raw_message_returns_injected() {
    let client = InMemoryWireClient::new();
    let msg = RawWireMessage {
        jsonrpc: JsonRpcVersion::V2,
        id: Some("1".to_string()),
        method: None,
        params: None,
        result: Some(serde_json::json!(42)),
        error: None,
    };
    client.inject(msg.clone()).await;

    let mut client = client;
    let read = client.read_raw_message().await.unwrap();
    assert_eq!(read.id, msg.id);
    assert_eq!(read.result, msg.result);
}

#[tokio::test]
async fn test_read_raw_message_empty_queue_returns_stream_closed() {
    let mut client = InMemoryWireClient::new();
    let err = client.read_raw_message().await.unwrap_err();
    assert!(matches!(err, WireError::StreamClosed));
}

// Note: InMemoryWireClient::read_raw_message does not block on an empty queue
// (it returns StreamClosed immediately), so a timeout can only be observed
// when the underlying read operation actually awaits. See transport_test.rs
// for a timeout test against TransportWireClient + ChannelTransport.

#[tokio::test]
async fn test_read_raw_message_timeout_success() {
    let client = InMemoryWireClient::new();
    let msg = RawWireMessage {
        jsonrpc: JsonRpcVersion::V2,
        id: Some("1".to_string()),
        method: None,
        params: None,
        result: Some(serde_json::json!(42)),
        error: None,
    };
    client.inject(msg.clone()).await;

    let mut client = client;
    let read = client
        .read_raw_message_timeout(Duration::from_secs(1))
        .await
        .unwrap();
    assert_eq!(read.id, msg.id);
}

// ============================================================================
// read_response / response matching
// ============================================================================

#[tokio::test]
async fn test_read_response_matches_id() {
    let mut client = InMemoryWireClient::new();
    let msg = RawWireMessage {
        jsonrpc: JsonRpcVersion::V2,
        id: Some("expected".to_string()),
        method: None,
        params: None,
        result: Some(serde_json::json!({"status": "finished"})),
        error: None,
    };
    client.inject(msg).await;

    let result: PromptResult = client.read_response("expected").await.unwrap();
    assert_eq!(result.status, PromptStatus::Finished);
}

#[tokio::test]
async fn test_read_response_buffers_out_of_order() {
    let mut client = InMemoryWireClient::new();
    let msg1 = RawWireMessage {
        jsonrpc: JsonRpcVersion::V2,
        id: Some("other".to_string()),
        method: None,
        params: None,
        result: Some(serde_json::json!(1)),
        error: None,
    };
    let msg2 = RawWireMessage {
        jsonrpc: JsonRpcVersion::V2,
        id: Some("wanted".to_string()),
        method: None,
        params: None,
        result: Some(serde_json::json!(2)),
        error: None,
    };
    client.inject(msg1).await;
    client.inject(msg2).await;

    let result: serde_json::Value = client.read_response("wanted").await.unwrap();
    assert_eq!(result, serde_json::json!(2));

    // The other message should still be reachable.
    let result: serde_json::Value = client.read_response("other").await.unwrap();
    assert_eq!(result, serde_json::json!(1));
}

#[tokio::test]
async fn test_read_response_empty_queue() {
    let mut client = InMemoryWireClient::new();
    let err = client
        .read_response::<PromptResult>("missing")
        .await
        .unwrap_err();
    assert!(matches!(err, WireError::StreamClosed));
}

#[tokio::test]
async fn test_read_response_json_rpc_error() {
    let mut client = InMemoryWireClient::new();
    let msg = RawWireMessage {
        jsonrpc: JsonRpcVersion::V2,
        id: Some("err".to_string()),
        method: None,
        params: None,
        result: None,
        error: Some(JsonRpcError {
            code: -32600,
            message: "bad request".to_string(),
            data: None,
        }),
    };
    client.inject(msg).await;

    let err = client
        .read_response::<PromptResult>("err")
        .await
        .unwrap_err();
    assert!(
        matches!(err, WireError::RequestFailed { code: -32600, message } if message == "bad request")
    );
}

#[tokio::test]
async fn test_read_response_missing_result() {
    let mut client = InMemoryWireClient::new();
    let msg = RawWireMessage {
        jsonrpc: JsonRpcVersion::V2,
        id: Some("noresult".to_string()),
        method: None,
        params: None,
        result: None,
        error: None,
    };
    client.inject(msg).await;

    let err = client
        .read_response::<PromptResult>("noresult")
        .await
        .unwrap_err();
    assert!(matches!(err, WireError::Internal(_)));
}

// ============================================================================
// send_response / send_error
// ============================================================================

#[tokio::test]
async fn test_send_response_serializes_ok() {
    let mut client = InMemoryWireClient::new();
    let result = PromptResult {
        status: PromptStatus::Finished,
        steps: None,
    };
    client.send_response("id-42", &result).await.unwrap();

    let outgoing = client.outgoing().await;
    assert_eq!(outgoing.len(), 1);
    let s = outgoing[0].as_str().unwrap();
    assert!(s.contains("id-42"));
    assert!(s.contains("finished"));
}

#[tokio::test]
async fn test_send_error_serializes_ok() {
    let mut client = InMemoryWireClient::new();
    client.send_error("id-99", -32600, "oops").await.unwrap();

    let outgoing = client.outgoing().await;
    assert_eq!(outgoing.len(), 1);
    let s = outgoing[0].as_str().unwrap();
    assert!(s.contains("id-99"));
    assert!(s.contains("oops"));
    assert!(s.contains("-32600"));
}

// ============================================================================
// initialize
// ============================================================================

#[tokio::test]
async fn test_initialize_sets_handshake_done() {
    let mut client = InMemoryWireClient::new();
    assert!(!client.is_handshake_done());
    let result = client
        .initialize(InitializeParams::new("1.10"))
        .await
        .unwrap();
    assert!(client.is_handshake_done());
    assert_eq!(result.protocol_version, kimi_wire::WIRE_PROTOCOL_VERSION);
    assert_eq!(result.server.name, "test-server");
}

// ============================================================================
// WireClient high-level methods
// ============================================================================

#[tokio::test]
async fn test_prompt_high_level() {
    let mut client = InMemoryWireClient::new();
    let response = RawWireMessage {
        jsonrpc: JsonRpcVersion::V2,
        id: Some("req-1".to_string()),
        method: None,
        params: None,
        result: Some(serde_json::json!({"status": "finished"})),
        error: None,
    };
    client.inject(response).await;

    let result = client.prompt("hello world").await.unwrap();
    assert_eq!(result.status, PromptStatus::Finished);

    let outgoing = client.outgoing().await;
    assert_eq!(outgoing.len(), 1);
    assert_eq!(outgoing[0]["method"], "prompt");
}

#[tokio::test]
async fn test_start_prompt_returns_id() {
    let mut client = InMemoryWireClient::new();
    let id = client.start_prompt("foo").await.unwrap();
    assert_eq!(id, "req-1");

    let outgoing = client.outgoing().await;
    assert_eq!(outgoing[0]["params"]["user_input"], "foo");
}

#[tokio::test]
async fn test_replay_high_level() {
    let mut client = InMemoryWireClient::new();
    let response = RawWireMessage {
        jsonrpc: JsonRpcVersion::V2,
        id: Some("req-1".to_string()),
        method: None,
        params: None,
        result: Some(serde_json::json!({"status": "finished", "events": 3, "requests": 2 })),
        error: None,
    };
    client.inject(response).await;

    let result = client.replay().await.unwrap();
    assert_eq!(result.status, ReplayStatus::Finished);
    assert_eq!(result.events, 3);
}

#[tokio::test]
async fn test_steer_high_level() {
    let mut client = InMemoryWireClient::new();
    let response = RawWireMessage {
        jsonrpc: JsonRpcVersion::V2,
        id: Some("req-1".to_string()),
        method: None,
        params: None,
        result: Some(serde_json::json!({"status": "steered"})),
        error: None,
    };
    client.inject(response).await;

    let result = client.steer("do it differently").await.unwrap();
    assert_eq!(result.status, SteerStatus::Steered);
}

#[tokio::test]
async fn test_set_plan_mode_high_level() {
    let mut client = InMemoryWireClient::new();
    let response = RawWireMessage {
        jsonrpc: JsonRpcVersion::V2,
        id: Some("req-1".to_string()),
        method: None,
        params: None,
        result: Some(serde_json::json!({"status": "ok", "plan_mode": true})),
        error: None,
    };
    client.inject(response).await;

    let result = client.set_plan_mode(true).await.unwrap();
    assert_eq!(result.status, SetPlanModeStatus::Ok);
    assert!(result.plan_mode);
}

#[tokio::test]
async fn test_cancel_high_level() {
    let mut client = InMemoryWireClient::new();
    let response = RawWireMessage {
        jsonrpc: JsonRpcVersion::V2,
        id: Some("req-1".to_string()),
        method: None,
        params: None,
        result: Some(serde_json::json!({})),
        error: None,
    };
    client.inject(response).await;

    client.cancel().await.unwrap();

    let outgoing = client.outgoing().await;
    assert_eq!(outgoing[0]["method"], "cancel");
}

// ============================================================================
// shutdown
// ============================================================================

#[tokio::test]
async fn test_shutdown_ok() {
    let client = InMemoryWireClient::new();
    client.shutdown().await.unwrap();
}

// ============================================================================
// read_raw_message from pending queue
// ============================================================================

#[tokio::test]
async fn test_read_raw_message_drains_pending() {
    let mut client = InMemoryWireClient::new();
    let msg1 = RawWireMessage {
        jsonrpc: JsonRpcVersion::V2,
        id: Some("other".to_string()),
        method: None,
        params: None,
        result: Some(serde_json::json!(1)),
        error: None,
    };
    client.inject(msg1.clone()).await;

    // read_response buffers msg1 into pending because id does not match.
    let err = client
        .read_response::<PromptResult>("wanted")
        .await
        .unwrap_err();
    assert!(matches!(err, WireError::StreamClosed));

    // read_raw_message should drain pending first.
    let raw = client.read_raw_message().await.unwrap();
    assert_eq!(raw.id, msg1.id);
}

#[tokio::test]
async fn test_in_memory_client_pending_cap() {
    use kimi_wire::transport::MAX_PENDING_MESSAGES;

    let mut client = InMemoryWireClient::new();

    // Inject MAX_PENDING_MESSAGES + 1 unrelated messages.
    for i in 0..=MAX_PENDING_MESSAGES {
        let msg = RawWireMessage {
            jsonrpc: JsonRpcVersion,
            id: Some(format!("msg-{i}")),
            method: None,
            params: None,
            result: Some(serde_json::json!(i)),
            error: None,
        };
        client.inject(msg).await;
    }

    let err = client
        .read_response::<serde_json::Value>("wanted")
        .await
        .unwrap_err();
    assert!(
        matches!(&err, WireError::Internal(msg) if msg.contains("buffer overflow")),
        "expected buffer overflow error, got {err:?}"
    );
}