wcode-harness 0.3.5

Minimal, extensible agent harness kernel: event loop, tools, hooks, JSONL sessions
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
use crate::message::{AgentMessage, StopReason, Usage};
use serde::{Deserialize, Serialize};

/// Internal seam between LLM adapter and agent loop. Not serialized.
#[derive(Clone, Debug, PartialEq)]
pub enum LlmStreamEvent {
    TextDelta(String),
    ThinkingDelta(String),
    /// A complete thinking block (provider restates the whole reasoning after
    /// streaming deltas). Replacement semantics: supersedes *all* thinking
    /// accumulated so far in this message — the kernel drops prior thinking
    /// blocks instead of appending, so the context never doubles up.
    ThinkingReplace(String),
    ToolCall {
        id: String,
        name: String,
        arguments: serde_json::Value,
    },
    Done {
        stop_reason: StopReason,
        usage: Option<Usage>,
    },
    /// The adapter is about to retry a failed connect after a transient error.
    /// `attempt` is 1-based; advisory — the loop only surfaces it.
    Retrying {
        attempt: u32,
        max: u32,
        reason: String,
    },
    Error {
        message: String,
        /// True when the failure is of a hard-fatal class (bad request, auth,
        /// schema, build/parse) that retrying or re-feeding cannot fix. The
        /// loop ends the run on a fatal error; a transient-class error that
        /// exhausted its retries (or landed mid-stream after content) is fed
        /// back to the model for a corrective turn instead.
        fatal: bool,
    },
}

/// The status of a [`TodoItem`]. `Cancelled` is deliberately absent in v1: the
/// model drops an item by rewriting the whole list.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum TodoStatus {
    Pending,
    InProgress,
    Completed,
}

/// One entry in the `todo` tool's session-local checklist. Lives in the harness
/// because it rides the serialized [`AgentEvent`] (the CLI tool reuses it).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
pub struct TodoItem {
    /// What the item is about (non-empty after trim; the tool validates).
    pub content: String,
    pub status: TodoStatus,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AgentEvent {
    AgentStart,
    TurnStart,
    MessageStart {
        message: AgentMessage,
    },
    MessageUpdate {
        message: AgentMessage,
    },
    MessageEnd {
        message: AgentMessage,
    },
    ToolExecutionStart {
        call_id: String,
        name: String,
    },
    ToolExecutionUpdate {
        call_id: String,
        name: String,
        partial: String,
    },
    ToolExecutionEnd {
        call_id: String,
        name: String,
        output: String,
        is_error: bool,
        /// UI-only unified diff (see `ToolOutput::diff`); absent when there is
        /// nothing to show, or on an older peer that predates the field.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        diff: Option<String>,
        /// UI-only path of the changed file (see `ToolOutput::path`); absent
        /// when the tool touched no file, or on an older peer.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        path: Option<String>,
        /// Wall-clock duration of the tool call in milliseconds — `execute` plus
        /// its `after_tool_call` hook. UI-only, like `diff`/`path`: it rides this
        /// event but never enters `ToolOutput`/the model's context. `None` on an
        /// older peer, or a call that never ran (blocked by a hook, or a dead
        /// sink).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        duration_ms: Option<u64>,
    },
    TurnEnd {
        message: AgentMessage,
    },
    /// Auto-compaction summarized `summarized` older messages, keeping `kept`.
    Compaction {
        summarized: usize,
        kept: usize,
    },
    /// Best-effort auto-compaction was attempted (the context was near the
    /// ceiling) but did NOT complete — a summarizer/stream failure. The run
    /// continues. Deliberately NOT [`AgentEvent::Error`], whose contract is a
    /// *stream-level* failure: a TUI renders `Error` as a failed run, so routing
    /// a best-effort compaction miss through it would falsely mark the run
    /// failed. `reason` is the summarizer's error text, for display only — never
    /// fed back to the model and never fatal. Purely additive on the wire
    /// (`{"type":"compaction_skipped","reason":…}`), so
    /// [`crate::protocol::PROTOCOL_VERSION`] need not bump.
    CompactionSkipped {
        reason: String,
    },
    /// The adapter retried a failed connect after a transient error.
    Retrying {
        attempt: u32,
        max: u32,
        reason: String,
    },
    /// A peer delivered a message to this session (`Request::Notify`/
    /// `Interrupt`/`Wake`). `from` is the sender's address (§5.2 — the human is
    /// [`crate::protocol::USER`]); streamed, so a UI can surface an inbound
    /// message. Not a reply.
    MessageReceived {
        from: crate::protocol::SessionId,
        content: String,
    },
    /// Stream-level failure. A fatal-class failure (bad request, auth, schema)
    /// ends the run with `StopReason::Error`; a transient-class failure that
    /// exhausted its retries (or landed mid-stream) is fed back to the model
    /// and the loop continues, still bounded by a consecutive-error cap.
    Error {
        message: String,
    },
    /// Reply: a request with no richer answer succeeded (e.g. `SetModel`).
    /// Never *streamed* — it answers one request, correlated by the transport
    /// (an in-process reply channel today, the envelope's `reply_to` on the
    /// wire).
    Ack,
    /// Reply: the run finished, with why it stopped. Answers a `Submit`. Never
    /// streamed (see [`AgentEvent::Ack`]).
    Stopped {
        stop_reason: StopReason,
    },
    /// Reply: a tool-free side answer to a `Request::SideAsk` (`/btw`). Never
    /// streamed (see [`AgentEvent::Ack`]). Carries the answer text and the
    /// turn's usage (for a `/usage`-style readout); styling is the front-end's.
    SideAnswer {
        text: String,
        usage: Option<Usage>,
    },
    /// Reply: the conversation so far, answering a `Request::GetHistory`. Never
    /// streamed (see [`AgentEvent::Ack`]).
    History {
        messages: Vec<AgentMessage>,
    },
    /// Reply: a compact status — the text of the session's most recent assistant
    /// message — answering a [`crate::protocol::Request::Status`]. Never streamed
    /// (see [`AgentEvent::Ack`]); one small string, not the transcript.
    Status {
        last_assistant_text: Option<String>,
    },
    /// Reply: the model catalog the provider advertises, answering a
    /// [`crate::protocol::Request::ListModels`]. Never streamed (see
    /// [`AgentEvent::Ack`]) — one reply, correlated by the transport, exactly
    /// like [`AgentEvent::Sessions`]. Each entry is a bare model id; ordering
    /// is the provider's (`streamfn::list_models`).
    Models {
        models: Vec<String>,
    },
    /// Reply: the sessions a server serves, in order (root first), each
    /// with the model the server knows for it ([`crate::protocol::SessionInfo`]).
    /// Answers a [`crate::protocol::Request::ListSessions`]. Never streamed (see
    /// [`AgentEvent::Ack`]).
    Sessions {
        sessions: Vec<crate::protocol::SessionInfo>,
    },
    /// Reply: a peer defined a worker and returns its address, answering a
    /// [`crate::protocol::Request::Define`]. Never streamed (see
    /// [`AgentEvent::Ack`]).
    ///
    /// The field is `worker`, not `id`: the envelope already carries a top-level
    /// `id` (the request it replies to), and a flattened duplicate key would not
    /// deserialize.
    Spawned {
        worker: crate::protocol::SessionId,
    },
    /// The `todo` checklist, streamed on every write (mirror `Compaction` /
    /// `Retrying`: a plain state payload the UI reduces). The field is `todos`,
    /// not `id`: the envelope already carries a top-level `id` and a flattened
    /// duplicate key would not deserialize.
    Todo {
        todos: Vec<TodoItem>,
    },
    AgentEnd,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::message::ContentBlock;
    use serde_json::json;

    fn roundtrip(e: AgentEvent, expected_tag: &str) {
        let v = serde_json::to_value(&e).unwrap();
        assert_eq!(v["type"], expected_tag);
        let back: AgentEvent = serde_json::from_value(v.clone()).unwrap();
        let v2 = serde_json::to_value(&back).unwrap();
        assert_eq!(v, v2);
    }

    fn assistant() -> AgentMessage {
        AgentMessage::Assistant {
            content: vec![ContentBlock::Text { text: "a".into() }],
            stop_reason: StopReason::Stop,
            usage: Some(Usage::default()),
            model: None,
        }
    }

    #[test]
    fn agent_event_roundtrip_all_variants() {
        roundtrip(AgentEvent::AgentStart, "agent_start");
        roundtrip(AgentEvent::TurnStart, "turn_start");
        roundtrip(
            AgentEvent::MessageStart {
                message: assistant(),
            },
            "message_start",
        );
        roundtrip(
            AgentEvent::MessageUpdate {
                message: assistant(),
            },
            "message_update",
        );
        roundtrip(
            AgentEvent::MessageEnd {
                message: assistant(),
            },
            "message_end",
        );
        roundtrip(
            AgentEvent::ToolExecutionStart {
                call_id: "t1".into(),
                name: "run".into(),
            },
            "tool_execution_start",
        );
        roundtrip(
            AgentEvent::ToolExecutionUpdate {
                call_id: "t1".into(),
                name: "run".into(),
                partial: "out".into(),
            },
            "tool_execution_update",
        );
        roundtrip(
            AgentEvent::ToolExecutionEnd {
                call_id: "t1".into(),
                name: "run".into(),
                output: "out".into(),
                is_error: false,
                diff: Some("@@ -1 +1 @@".into()),
                path: Some("src/f.rs".into()),
                duration_ms: Some(12),
            },
            "tool_execution_end",
        );
        roundtrip(
            AgentEvent::TurnEnd {
                message: assistant(),
            },
            "turn_end",
        );
        roundtrip(
            AgentEvent::Error {
                message: "boom".into(),
            },
            "error",
        );
        roundtrip(
            AgentEvent::Compaction {
                summarized: 3,
                kept: 2,
            },
            "compaction",
        );
        roundtrip(
            AgentEvent::CompactionSkipped {
                reason: "summarizer 500".into(),
            },
            "compaction_skipped",
        );
        roundtrip(
            AgentEvent::Retrying {
                attempt: 2,
                max: 3,
                reason: "503".into(),
            },
            "retrying",
        );
        roundtrip(AgentEvent::Ack, "ack");
        roundtrip(
            AgentEvent::Stopped {
                stop_reason: StopReason::Aborted,
            },
            "stopped",
        );
        roundtrip(
            AgentEvent::SideAnswer {
                text: "hi".into(),
                usage: None,
            },
            "side_answer",
        );
        roundtrip(
            AgentEvent::History {
                messages: vec![AgentMessage::user_text("hi")],
            },
            "history",
        );
        roundtrip(
            AgentEvent::Status {
                last_assistant_text: Some("last said".into()),
            },
            "status",
        );
        roundtrip(
            AgentEvent::Models { models: vec!["m1".into(), "m2".into()] },
            "models",
        );
        roundtrip(
            AgentEvent::MessageReceived {
                from: crate::protocol::SessionId::new("user"),
                content: "ping".into(),
            },
            "message_received",
        );
        roundtrip(AgentEvent::AgentEnd, "agent_end");
        roundtrip(
            AgentEvent::Sessions {
                sessions: vec![
                    crate::protocol::SessionInfo {
                        id: crate::protocol::SessionId::new("root"),
                        model: Some("m1".into()),
                        effort: Some("high".into()),
                        context_window: Some(200_000),
                        state: crate::protocol::MemberState::Idle,
                    },
                    crate::protocol::SessionInfo {
                        id: crate::protocol::SessionId::agent("w1"),
                        model: None,
                        effort: None,
                        context_window: None,
                        state: crate::protocol::MemberState::Idle,
                    },
                ],
            },
            "sessions",
        );
        roundtrip(
            AgentEvent::Spawned {
                worker: crate::protocol::SessionId::agent("w1"),
            },
            "spawned",
        );
        roundtrip(
            AgentEvent::Todo {
                todos: vec![
                    TodoItem {
                        content: "write tests".into(),
                        status: TodoStatus::Pending,
                    },
                    TodoItem {
                        content: "ship it".into(),
                        status: TodoStatus::Completed,
                    },
                ],
            },
            "todo",
        );
    }

    #[test]
    fn agent_event_shape_matches_tagged_payload() {
        let v = serde_json::to_value(&AgentEvent::ToolExecutionStart {
            call_id: "t1".into(),
            name: "run".into(),
        })
        .unwrap();
        assert_eq!(
            v,
            json!({"type": "tool_execution_start", "call_id": "t1", "name": "run"})
        );

        let m = AgentMessage::user_text("hi");
        let v2 = serde_json::to_value(&AgentEvent::TurnEnd { message: m }).unwrap();
        assert_eq!(v2["type"], "turn_end");
        assert_eq!(v2["message"]["role"], "user");
    }
}