lash-core 0.1.0-alpha.85

Sans-IO turn machine and runtime kernel for the lash agent runtime.
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
//! Golden JSON schema pins for the app-facing [`TurnEvent`] surface and its
//! [`TurnActivity`] envelope.
//!
//! `TurnEvent` is a public streaming DTO consumed across process and protocol
//! boundaries, so its serde shape — tag string, field names, and
//! absent-when-`None` optional fields — is a contract. These tests assert the
//! exact `serde_json::Value` for every variant.
//!
//! Drift guard: [`expected_type_tag`] is an exhaustive `match` with no
//! wildcard, so adding a new `TurnEvent` variant fails to compile here until it
//! is given a tag. [`samples_cover_every_variant`] then fails until a
//! representative sample for the new variant is added to [`sample_events`], so
//! the new shape actually gets pinned rather than silently skipped.

use std::collections::BTreeSet;

use lash_core::runtime::QueuedWorkClaimBoundary;
use lash_core::{
    AcceptedInjectedTurnInput, CheckpointKind, MessageOrigin, MessageRole, PluginMessage,
    PluginRuntimeEvent, TokenUsage, ToolCallOutput, ToolFailure, ToolFailureClass, TurnActivity,
    TurnActivityId, TurnCause, TurnEvent,
};
use serde_json::json;

/// The `type` tag serde writes for this variant. Exhaustive on purpose: a new
/// variant fails to compile until it is mapped, forcing the author here.
fn expected_type_tag(event: &TurnEvent) -> &'static str {
    match event {
        TurnEvent::QueuedWorkStarted { .. } => "queued_work_started",
        TurnEvent::ModelRequestStarted { .. } => "model_request_started",
        TurnEvent::AssistantProseDelta { .. } => "assistant_prose_delta",
        TurnEvent::ReasoningDelta { .. } => "reasoning_delta",
        TurnEvent::CodeBlockStarted { .. } => "code_block_started",
        TurnEvent::CodeBlockCompleted { .. } => "code_block_completed",
        TurnEvent::ToolCallStarted { .. } => "tool_call_started",
        TurnEvent::ToolCallCompleted { .. } => "tool_call_completed",
        TurnEvent::FinalValue { .. } => "final_value",
        TurnEvent::ToolValue { .. } => "tool_value",
        TurnEvent::Usage { .. } => "usage",
        TurnEvent::ChildUsage { .. } => "child_usage",
        TurnEvent::RetryStatus { .. } => "retry_status",
        TurnEvent::PluginRuntime { .. } => "plugin_runtime",
        TurnEvent::QueuedInputAccepted { .. } => "queued_input_accepted",
        TurnEvent::QueuedMessagesCommitted { .. } => "queued_messages_committed",
        TurnEvent::Error { .. } => "error",
    }
}

/// Canonical list of every serialized tag. Paired with [`samples_cover_every_variant`],
/// this catches a variant that gained a tag mapping but no pinned sample.
const ALL_TURN_EVENT_TAGS: &[&str] = &[
    "queued_work_started",
    "model_request_started",
    "assistant_prose_delta",
    "reasoning_delta",
    "code_block_started",
    "code_block_completed",
    "tool_call_started",
    "tool_call_completed",
    "final_value",
    "tool_value",
    "usage",
    "child_usage",
    "retry_status",
    "plugin_runtime",
    "queued_input_accepted",
    "queued_messages_committed",
    "error",
];

fn token_usage_sample() -> TokenUsage {
    TokenUsage {
        input_tokens: 10,
        output_tokens: 5,
        cache_read_input_tokens: 1,
        cache_write_input_tokens: 2,
        reasoning_output_tokens: 3,
    }
}

fn token_usage_json() -> serde_json::Value {
    json!({
        "input_tokens": 10,
        "output_tokens": 5,
        "cache_read_input_tokens": 1,
        "cache_write_input_tokens": 2,
        "reasoning_output_tokens": 3,
    })
}

/// Representative construction of every variant paired with its exact expected
/// JSON. Optional fields appear as both `Some` and `None` where meaningful, so
/// the pins cover both the present and absent-when-`None` encodings.
fn sample_events() -> Vec<(&'static str, TurnEvent, serde_json::Value)> {
    vec![
        (
            "queued_work_started",
            TurnEvent::QueuedWorkStarted {
                boundary: QueuedWorkClaimBoundary::Idle,
                batch_ids: vec!["batch-1".to_string()],
                causes: vec![TurnCause {
                    id: "cause-1".to_string(),
                    event_type: "process_wake".to_string(),
                    origin: MessageOrigin::Plugin {
                        plugin_id: "p".to_string(),
                        transient: false,
                    },
                    text: "hello".to_string(),
                }],
            },
            json!({
                "type": "queued_work_started",
                "boundary": "idle",
                "batch_ids": ["batch-1"],
                "causes": [{
                    "id": "cause-1",
                    "event_type": "process_wake",
                    "origin": { "kind": "plugin", "plugin_id": "p" },
                    "text": "hello",
                }],
            }),
        ),
        (
            "model_request_started",
            TurnEvent::ModelRequestStarted {
                protocol_iteration: 2,
            },
            json!({ "type": "model_request_started", "protocol_iteration": 2 }),
        ),
        (
            "assistant_prose_delta",
            TurnEvent::AssistantProseDelta {
                text: "hi".to_string(),
            },
            json!({ "type": "assistant_prose_delta", "text": "hi" }),
        ),
        (
            "reasoning_delta",
            TurnEvent::ReasoningDelta {
                text: "thinking".to_string(),
            },
            json!({ "type": "reasoning_delta", "text": "thinking" }),
        ),
        (
            "code_block_started (graph_key present)",
            TurnEvent::CodeBlockStarted {
                language: "python".to_string(),
                code: "print(1)".to_string(),
                graph_key: Some("effect:s:e".to_string()),
            },
            json!({
                "type": "code_block_started",
                "language": "python",
                "code": "print(1)",
                "graph_key": "effect:s:e",
            }),
        ),
        (
            "code_block_started (graph_key absent)",
            TurnEvent::CodeBlockStarted {
                language: "python".to_string(),
                code: "print(1)".to_string(),
                graph_key: None,
            },
            json!({
                "type": "code_block_started",
                "language": "python",
                "code": "print(1)",
            }),
        ),
        (
            "code_block_completed (error + graph_key present)",
            TurnEvent::CodeBlockCompleted {
                language: "python".to_string(),
                output: "1".to_string(),
                error: Some("boom".to_string()),
                success: false,
                duration_ms: 5,
                tool_call_ids: vec!["call-1".to_string()],
                graph_key: Some("effect:s:e".to_string()),
            },
            json!({
                "type": "code_block_completed",
                "language": "python",
                "output": "1",
                "error": "boom",
                "success": false,
                "duration_ms": 5,
                "tool_call_ids": ["call-1"],
                "graph_key": "effect:s:e",
            }),
        ),
        (
            "code_block_completed (error + graph_key absent)",
            TurnEvent::CodeBlockCompleted {
                language: "python".to_string(),
                output: "1".to_string(),
                error: None,
                success: true,
                duration_ms: 5,
                tool_call_ids: vec![],
                graph_key: None,
            },
            json!({
                "type": "code_block_completed",
                "language": "python",
                "output": "1",
                "success": true,
                "duration_ms": 5,
                "tool_call_ids": [],
            }),
        ),
        (
            "tool_call_started (all options present)",
            TurnEvent::ToolCallStarted {
                call_id: Some("call-1".to_string()),
                name: "read_file".to_string(),
                args: json!({ "path": "x" }),
                graph_key: Some("effect:s:e".to_string()),
                parent_call_id: Some("parent-1".to_string()),
            },
            json!({
                "type": "tool_call_started",
                "call_id": "call-1",
                "name": "read_file",
                "args": { "path": "x" },
                "graph_key": "effect:s:e",
                "parent_call_id": "parent-1",
            }),
        ),
        (
            "tool_call_started (all options absent)",
            TurnEvent::ToolCallStarted {
                call_id: None,
                name: "read_file".to_string(),
                args: json!({ "path": "x" }),
                graph_key: None,
                parent_call_id: None,
            },
            json!({
                "type": "tool_call_started",
                "name": "read_file",
                "args": { "path": "x" },
            }),
        ),
        (
            "tool_call_completed (all options present, success)",
            TurnEvent::ToolCallCompleted {
                call_id: Some("call-1".to_string()),
                name: "read_file".to_string(),
                args: json!({ "path": "x" }),
                output: ToolCallOutput::success("ok"),
                duration_ms: 7,
                graph_key: Some("effect:s:e".to_string()),
                parent_call_id: Some("parent-1".to_string()),
            },
            json!({
                "type": "tool_call_completed",
                "call_id": "call-1",
                "name": "read_file",
                "args": { "path": "x" },
                "output": { "outcome": { "status": "success", "payload": "ok" } },
                "duration_ms": 7,
                "graph_key": "effect:s:e",
                "parent_call_id": "parent-1",
            }),
        ),
        (
            "tool_call_completed (all options absent, failure vocabulary)",
            TurnEvent::ToolCallCompleted {
                call_id: None,
                name: "read_file".to_string(),
                args: json!({ "path": "x" }),
                output: ToolCallOutput::failure(ToolFailure::tool(
                    ToolFailureClass::Execution,
                    "boom",
                    "kaboom",
                )),
                duration_ms: 7,
                graph_key: None,
                parent_call_id: None,
            },
            json!({
                "type": "tool_call_completed",
                "name": "read_file",
                "args": { "path": "x" },
                "output": {
                    "outcome": {
                        "status": "failure",
                        "payload": {
                            "class": "execution",
                            "code": "boom",
                            "message": "kaboom",
                            "source": "tool",
                            "retry": { "type": "never" },
                        },
                    },
                },
                "duration_ms": 7,
            }),
        ),
        (
            "final_value",
            TurnEvent::FinalValue {
                value: json!({ "answer": 42 }),
            },
            json!({ "type": "final_value", "value": { "answer": 42 } }),
        ),
        (
            "tool_value",
            TurnEvent::ToolValue {
                tool_name: "calc".to_string(),
                value: json!(3),
            },
            json!({ "type": "tool_value", "tool_name": "calc", "value": 3 }),
        ),
        (
            "usage",
            TurnEvent::Usage {
                protocol_iteration: 1,
                usage: token_usage_sample(),
                cumulative: token_usage_sample(),
            },
            json!({
                "type": "usage",
                "protocol_iteration": 1,
                "usage": token_usage_json(),
                "cumulative": token_usage_json(),
            }),
        ),
        (
            "child_usage",
            TurnEvent::ChildUsage {
                session_id: "child".to_string(),
                source: "delegate".to_string(),
                model: "m".to_string(),
                protocol_iteration: 1,
                usage: token_usage_sample(),
                cumulative: token_usage_sample(),
            },
            json!({
                "type": "child_usage",
                "session_id": "child",
                "source": "delegate",
                "model": "m",
                "protocol_iteration": 1,
                "usage": token_usage_json(),
                "cumulative": token_usage_json(),
            }),
        ),
        (
            "retry_status",
            TurnEvent::RetryStatus {
                wait_seconds: 3,
                attempt: 1,
                max_attempts: 5,
                reason: "rate_limited".to_string(),
            },
            json!({
                "type": "retry_status",
                "wait_seconds": 3,
                "attempt": 1,
                "max_attempts": 5,
                "reason": "rate_limited",
            }),
        ),
        (
            "plugin_runtime",
            TurnEvent::PluginRuntime {
                plugin_id: "todo".to_string(),
                event: PluginRuntimeEvent::Status {
                    key: "k".to_string(),
                    label: "Working".to_string(),
                    detail: Some("d".to_string()),
                },
            },
            json!({
                "type": "plugin_runtime",
                "plugin_id": "todo",
                "event": {
                    "kind": "status",
                    "key": "k",
                    "label": "Working",
                    "detail": "d",
                },
            }),
        ),
        (
            "queued_input_accepted",
            TurnEvent::QueuedInputAccepted {
                checkpoint: CheckpointKind::AfterWork,
                inputs: vec![AcceptedInjectedTurnInput {
                    id: Some("i".to_string()),
                    message: PluginMessage::text(MessageRole::User, "hi"),
                }],
            },
            json!({
                "type": "queued_input_accepted",
                "checkpoint": "after_work",
                "inputs": [{
                    "id": "i",
                    "message": { "role": "User", "content": "hi" },
                }],
            }),
        ),
        (
            "queued_messages_committed",
            TurnEvent::QueuedMessagesCommitted {
                messages: vec![PluginMessage::text(MessageRole::Assistant, "done")],
                checkpoint: CheckpointKind::BeforeCompletion,
            },
            json!({
                "type": "queued_messages_committed",
                "messages": [{ "role": "Assistant", "content": "done" }],
                "checkpoint": "before_completion",
            }),
        ),
        (
            "error",
            TurnEvent::Error {
                message: "boom".to_string(),
            },
            json!({ "type": "error", "message": "boom" }),
        ),
    ]
}

#[test]
fn every_variant_serializes_to_pinned_json() {
    for (label, event, expected) in sample_events() {
        let actual =
            serde_json::to_value(&event).unwrap_or_else(|err| panic!("serialize {label}: {err}"));
        assert_eq!(actual, expected, "serialized shape drifted for `{label}`");

        // The pinned `type` tag is the single source of truth shared with the
        // exhaustive drift guard.
        assert_eq!(
            expected["type"],
            expected_type_tag(&event),
            "tag disagrees with expected_type_tag for `{label}`"
        );

        // The pinned JSON decodes back to the same event (confirms optional
        // fields default to `None` when absent), and re-serializes identically.
        let round_trip: TurnEvent = serde_json::from_value(expected.clone())
            .unwrap_or_else(|err| panic!("deserialize {label}: {err}"));
        assert_eq!(
            serde_json::to_value(&round_trip).unwrap(),
            expected,
            "round-trip drifted for `{label}`"
        );
    }
}

#[test]
fn samples_cover_every_variant() {
    let sampled: BTreeSet<&str> = sample_events()
        .iter()
        .map(|(_, event, _)| expected_type_tag(event))
        .collect();
    let canonical: BTreeSet<&str> = ALL_TURN_EVENT_TAGS.iter().copied().collect();
    assert_eq!(
        sampled, canonical,
        "sample_events must pin exactly one representative per TurnEvent variant"
    );
}

#[test]
fn turn_activity_envelope_flattens_event() {
    let activity = TurnActivity {
        id: TurnActivityId::new("act-1"),
        correlation_id: TurnActivityId::new("corr-1"),
        event: TurnEvent::Error {
            message: "boom".to_string(),
        },
    };

    let json = serde_json::to_value(&activity).expect("serialize activity");
    // `id` and `correlation_id` sit alongside the flattened event fields: the
    // event is not nested under its own key.
    assert_eq!(
        json,
        json!({
            "id": "act-1",
            "correlation_id": "corr-1",
            "type": "error",
            "message": "boom",
        })
    );
    assert!(
        json.get("event").is_none(),
        "the event payload must be flattened into the envelope, not nested"
    );

    let round_trip: TurnActivity = serde_json::from_value(json.clone()).expect("deserialize");
    assert_eq!(serde_json::to_value(&round_trip).unwrap(), json);
}