megacode-agent-sdk 0.32.0

Drive a MEGA harness agent session from a Rust program.
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
//! The conversation's lines (spec slice-ar R8.5, `docs/headless.md` "A
//! conversation", `docs/protocol/stream-json.schema.json`): the typed events
//! a program reads, and the commands the SDK writes.
//!
//! Reading is lenient (R6.3): an unknown line type is skipped and an unknown
//! field ignored; a known type missing a field it requires is a protocol
//! error.

use serde::Deserialize;
use serde_json::Value;

use crate::error::Error;

/// harness's limit on one command line, newline included
/// (`cli/rpc.rs`'s `LINE_CAP`).
pub(crate) const LINE_LIMIT: usize = 8 * 1024 * 1024;

/// The most bytes an approval's reason carries (R8.5.2).
pub(crate) const REASON_LIMIT: usize = 64 * 1024;

/// A closed list of wire words, read leniently: a word this SDK does not
/// know is `Other` (R6.3).
macro_rules! words {
    ($(#[$m:meta])* $name:ident { $($(#[$vm:meta])* $var:ident = $word:literal,)* }) => {
        $(#[$m])*
        #[derive(Debug, Clone, PartialEq, Eq)]
        #[non_exhaustive]
        pub enum $name {
            $($(#[$vm])* $var,)*
            /// A word this SDK does not know.
            Other(String),
        }

        impl $name {
            /// The wire's word.
            pub fn as_str(&self) -> &str {
                match self {
                    $(Self::$var => $word,)*
                    Self::Other(word) => word,
                }
            }

            #[allow(dead_code)]
            pub(crate) fn from_wire(word: &str) -> Self {
                match word {
                    $($word => Self::$var,)*
                    other => Self::Other(other.to_string()),
                }
            }
        }

        impl<'de> Deserialize<'de> for $name {
            fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
                Ok(Self::from_wire(&String::deserialize(d)?))
            }
        }
    };
}

words! {
    /// `user.kind`.
    UserKind {
        /// A prompt.
        Message = "message",
        /// A steer that landed.
        Steer = "steer",
    }
}

words! {
    /// `tool_result.status`.
    ToolStatus {
        /// The call succeeded.
        Ok = "ok",
        /// The call failed.
        Failed = "failed",
    }
}

words! {
    /// `approval.decision`: what a gate decided.
    ApprovalDecision {
        /// Allowed once.
        AllowedOnce = "allowed_once",
        /// Allowed for the turn.
        AllowedForTurn = "allowed_for_turn",
        /// Allowed for the session (old logs only).
        AllowedForSession = "allowed_for_session",
        /// Denied.
        Denied = "denied",
        /// Denied, and the turn stopped.
        DeniedAndStopped = "denied_and_stopped",
        /// Nobody answered in time.
        TimedOut = "timed_out",
        /// Refused while away.
        Refused = "refused",
    }
}

words! {
    /// `approval_request.kind`: why a gate asks.
    ApprovalKind {
        /// The mode's gate.
        Gate = "gate",
        /// A protected path.
        Protected = "protected",
        /// A removal.
        Removal = "removal",
        /// Decoded text run as a command.
        DecodeAndRun = "decode_and_run",
        /// A credential.
        Credential = "credential",
        /// An escape from the sandbox.
        Escape = "escape",
        /// An MCP call.
        Mcp = "mcp",
        /// The judge flagged it.
        JudgeFlag = "judge_flag",
        /// The judge could not decide.
        JudgeUnavailable = "judge_unavailable",
        /// A client tool marked `ask`.
        ClientTool = "client_tool",
    }
}

words! {
    /// One of an `approval_request`'s `choices`.
    Choice {
        /// `allow_once`
        AllowOnce = "allow_once",
        /// `allow_for_turn`
        AllowForTurn = "allow_for_turn",
        /// `deny`
        Deny = "deny",
        /// `deny_and_stop`
        DenyAndStop = "deny_and_stop",
    }
}

words! {
    /// `result.outcome`: how a turn ended.
    Outcome {
        /// The model answered.
        Completed = "completed",
        /// A tool call failed.
        ToolFailed = "tool_failed",
        /// The model call failed.
        ModelFailed = "model_failed",
        /// The turn hit its iteration limit.
        MaxIterations = "max_iterations",
        /// The turn was interrupted.
        Interrupted = "interrupted",
        /// The reply was cut by its output cap.
        Truncated = "truncated",
        /// The provider blocked the prompt.
        PromptBlocked = "prompt_blocked",
    }
}

words! {
    /// A command's outcome, from its `response` line.
    Disposition {
        /// `started`
        Started = "started",
        /// `queued`
        Queued = "queued",
        /// `accepted`
        Accepted = "accepted",
        /// `dequeued`
        Dequeued = "dequeued",
        /// `idle`
        Idle = "idle",
        /// `stale`
        Stale = "stale",
        /// `interrupting`
        Interrupting = "interrupting",
        /// `answered`
        Answered = "answered",
        /// `done`
        Done = "done",
        /// `set`
        Set = "set",
        /// `quitting`
        Quitting = "quitting",
    }
}

/// One event of a session, one per outbound line type (R8.5.1).
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Event {
    /// The session started (yielded by `query` only).
    Init(Info),
    /// A prompt, or a steer that landed.
    User(UserMessage),
    /// The model's reasoning.
    Reasoning(Text),
    /// The model's visible text.
    Assistant(Text),
    /// A tool call.
    ToolUse(ToolUse),
    /// A tool call's outcome.
    ToolResult(ToolResult),
    /// A gate's decision.
    Approval(Approval),
    /// A gate waiting for an answer.
    ApprovalRequest(ApprovalRequest),
    /// The context was compacted.
    Compacted(Compacted),
    /// The turn ended.
    Result(TurnResult),
}

/// `init`: the session's facts.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[non_exhaustive]
pub struct Info {
    /// The session's id.
    pub session_id: String,
    /// The model the session runs.
    pub model: Option<String>,
    /// The session's mode.
    pub mode: Option<String>,
    /// The session's working folder, where harness reports one.
    pub cwd: Option<String>,
    /// The harness version.
    pub harness_version: String,
    /// The commands this harness takes.
    #[serde(default)]
    pub commands: Vec<String>,
    /// Whether this is a resumed session.
    #[serde(default)]
    pub resumed: bool,
    /// The client tools' names, in order.
    #[serde(default)]
    pub client_tools: Vec<String>,
}

/// `user`: a message that joined the conversation.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[non_exhaustive]
pub struct UserMessage {
    /// The text.
    pub text: String,
    /// A prompt, or a steer that landed.
    pub kind: UserKind,
}

/// `reasoning` and `assistant`: text.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[non_exhaustive]
pub struct Text {
    /// The text.
    pub text: String,
}

/// `tool_use`.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[non_exhaustive]
pub struct ToolUse {
    /// The call's id.
    pub id: String,
    /// The tool's name.
    pub tool: String,
    /// The call's arguments; `null` when they were nested too deeply to
    /// read.
    pub input: Value,
}

/// `tool_result`.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[non_exhaustive]
pub struct ToolResult {
    /// The call's id.
    pub id: String,
    /// The tool's name.
    pub tool: String,
    /// Whether the call succeeded.
    pub status: ToolStatus,
    /// The output, when the call succeeded.
    pub output: Option<Value>,
    /// The error, when it failed.
    pub error: Option<String>,
}

/// `approval`: a gate's decision.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[non_exhaustive]
pub struct Approval {
    /// The call's id.
    pub id: String,
    /// The tool's name.
    pub tool: String,
    /// What the gate decided.
    pub decision: ApprovalDecision,
    /// The reason given, if any.
    pub reason: Option<String>,
    /// A sub-agent's session id.
    pub session: Option<String>,
    /// A sub-agent's name.
    pub agent: Option<String>,
}

/// `approval_request`: a gate waiting for an answer.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[non_exhaustive]
pub struct ApprovalRequest {
    /// The id an answer names.
    pub id: String,
    /// The call's `tool_use` id (empty inside a `script`).
    pub tool_use_id: String,
    /// The tool's name.
    pub tool: String,
    /// Why it asks.
    pub kind: ApprovalKind,
    /// The gate's reason, when it gives one.
    pub reason: Option<String>,
    /// The escape asked for, when the call asks for one.
    pub escape: Option<Escape>,
    /// A one-line summary of the call.
    pub summary: String,
    /// The call's arguments; `null` when they were nested too deeply to
    /// read (`summary` still describes the call).
    pub input: Value,
    /// The decisions on offer.
    pub choices: Vec<Choice>,
    /// Whether `allow_for_turn` leaves calls of this kind out.
    pub turn_grant_skips_kind: bool,
    /// A sub-agent's session id.
    pub session: Option<String>,
    /// A sub-agent's name.
    pub agent: Option<String>,
    /// The session that answers it.
    #[serde(skip)]
    pub(crate) responder: Responder,
}

/// The session an `approval_request` came from, so the event can answer
/// itself (R8.3.3). Weak: an event kept after its session ended holds
/// nothing alive.
#[derive(Clone, Default)]
pub(crate) struct Responder(pub(crate) Option<std::sync::Weak<crate::client::Shared>>);

impl std::fmt::Debug for Responder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Responder")
    }
}

/// Two requests are equal by their fields; where they came from is not
/// one.
impl PartialEq for Responder {
    fn eq(&self, _: &Self) -> bool {
        true
    }
}

/// An `approval_request`'s escape.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[non_exhaustive]
pub struct Escape {
    /// `network` or `outside`.
    pub kind: String,
    /// The model's reason.
    pub reason: String,
}

/// `compacted`.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[non_exhaustive]
pub struct Compacted {
    /// `automatic` or `manual`.
    pub trigger: Option<String>,
    /// The prompt's size before it, in tokens.
    pub pre_tokens: Option<u64>,
}

/// `result`: the end of a turn.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[non_exhaustive]
pub struct TurnResult {
    /// The session's id.
    pub session_id: String,
    /// How the turn ended.
    pub outcome: Option<Outcome>,
    /// Whether the turn failed to answer.
    pub is_error: bool,
    /// The answer.
    pub result: Option<String>,
    /// The error, when the turn failed.
    pub error: Option<String>,
    /// The model that answered.
    pub model: Option<String>,
    /// The turn's length.
    pub duration_ms: u64,
    /// Model calls the turn made.
    pub model_calls: u64,
    /// Tokens the turn used.
    pub usage: Usage,
    /// Calls the gates denied.
    pub denied: Vec<Denied>,
    /// The turn's id.
    pub turn_id: Option<String>,
    /// The id of the prompt that opened the turn.
    pub prompt_id: Option<String>,
    /// What the turn's model calls cost.
    pub cost: Option<Cost>,
}

/// A turn's token counts.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[non_exhaustive]
pub struct Usage {
    /// Input tokens.
    pub input_tokens: u64,
    /// Output tokens.
    pub output_tokens: u64,
    /// Cached input tokens, where the provider reports them.
    pub cached_input_tokens: Option<u64>,
    /// Reasoning tokens.
    pub reasoning_tokens: u64,
}

/// A denied call.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[non_exhaustive]
pub struct Denied {
    /// The tool's name.
    pub tool: String,
    /// The call's summary.
    pub summary: String,
}

/// A turn's cost.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[non_exhaustive]
pub struct Cost {
    /// US dollars, when anything could be priced.
    pub usd: Option<f64>,
    /// Calls priced.
    pub priced: u64,
    /// Calls not priced.
    pub unpriced: u64,
    /// Free calls.
    pub free: u64,
    /// `upper` when the figure is an upper bound.
    pub bound: Option<String>,
    /// `reported`, `list_price` or `mixed`.
    pub basis: Option<String>,
}

/// `get_state`'s data.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[non_exhaustive]
pub struct State {
    /// The session's id.
    pub session_id: String,
    /// The model.
    pub model: Option<String>,
    /// The thinking level.
    pub thinking: Option<String>,
    /// The mode.
    pub mode: Option<String>,
    /// Whether the running or next task is away.
    pub away: bool,
    /// The running turn, if any.
    pub turn: TurnState,
    /// The ids of the open approval requests.
    pub open_requests: Vec<String>,
    /// Prompts waiting for their turn.
    pub queued: u64,
    /// The context's size.
    pub context: ContextState,
}

/// `get_state.turn`.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum TurnState {
    /// No turn is running.
    Idle,
    /// A turn is running (its ids, once known).
    Running {
        /// The turn's id.
        id: Option<String>,
        /// The id of the prompt that opened it.
        prompt_id: Option<String>,
    },
}

impl<'de> Deserialize<'de> for TurnState {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        struct Running {
            id: Option<String>,
            prompt_id: Option<String>,
        }
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Raw {
            Word(String),
            Running(Running),
        }
        match Raw::deserialize(d)? {
            Raw::Word(w) if w == "idle" => Ok(TurnState::Idle),
            Raw::Word(w) => Err(serde::de::Error::custom(format!(
                "unknown turn state {w:?}"
            ))),
            Raw::Running(r) => Ok(TurnState::Running {
                id: r.id,
                prompt_id: r.prompt_id,
            }),
        }
    }
}

/// `get_state.context`.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[non_exhaustive]
pub struct ContextState {
    /// The last turn reply's whole prompt, in tokens.
    pub last_prompt_tokens: Option<u64>,
    /// The model's window, in tokens.
    pub window: Option<u64>,
    /// The share of the window used, in percent.
    pub percent: Option<u64>,
    /// Where automatic compaction starts, in percent.
    pub auto_compact_at_percent: Option<u64>,
}

/// An answer to an approval request (R8.3.1): the protocol's decisions.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Decision {
    /// Run this call.
    AllowOnce,
    /// Run this call and the turn's other calls of the tool.
    AllowForTurn,
    /// Do not run it; the reason reaches the model.
    Deny {
        /// What the model reads, as `The user said: …`.
        reason: Option<String>,
    },
    /// Do not run it, and end the turn.
    DenyAndStop,
}

impl Decision {
    /// The wire's word for this decision.
    pub(crate) fn as_wire(&self) -> &'static str {
        match self {
            Decision::AllowOnce => "allow_once",
            Decision::AllowForTurn => "allow_for_turn",
            Decision::Deny { .. } => "deny",
            Decision::DenyAndStop => "deny_and_stop",
        }
    }
}

/// A `response` line.
#[derive(Debug, Clone)]
pub(crate) struct Response {
    pub id: Option<String>,
    /// The command answered, as harness echoes it.
    pub command: String,
    pub ok: bool,
    pub disposition: Option<String>,
    pub data: Option<Value>,
    pub error: Option<(String, String)>,
}

/// One line read from the session.
#[derive(Debug)]
pub(crate) enum Line {
    Init(Box<Info>, u64),
    Event(Box<Event>),
    Response(Response),
    /// `client_tool_call` (R3.3).
    ClientToolCall(ToolCall),
    /// `client_tool_cancel` (R3.3.5): the call's id.
    ClientToolCancel(String),
    /// A line of a type this SDK does not read (R6.3).
    Other,
}

/// A `client_tool_call` line.
#[derive(Debug, Deserialize)]
pub(crate) struct ToolCall {
    pub id: String,
    pub name: String,
    pub input: Value,
    /// The arguments were nested past what this SDK parses; `input` is
    /// null and the call is answered `is_error`.
    #[serde(skip)]
    pub too_deep: bool,
}

/// A line's top-level object with its `input` skipped (as null): the
/// reading of a line whose `input` is nested past serde_json's recursion
/// limit. `IgnoredAny` skips a value without recursing.
struct WithoutInput(serde_json::Map<String, Value>);

impl<'de> Deserialize<'de> for WithoutInput {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        struct Visit;
        impl<'de> serde::de::Visitor<'de> for Visit {
            type Value = WithoutInput;
            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str("a JSON object")
            }
            fn visit_map<A: serde::de::MapAccess<'de>>(
                self,
                mut map: A,
            ) -> Result<WithoutInput, A::Error> {
                let mut out = serde_json::Map::new();
                while let Some(key) = map.next_key::<String>()? {
                    let value = if key == "input" {
                        map.next_value::<serde::de::IgnoredAny>()?;
                        Value::Null
                    } else {
                        map.next_value::<Value>()?
                    };
                    out.insert(key, value);
                }
                Ok(WithoutInput(out))
            }
        }
        d.deserialize_map(Visit)
    }
}

fn field<T: serde::de::DeserializeOwned>(ty: &str, v: Value) -> Result<T, Error> {
    serde_json::from_value(v).map_err(|e| Error::Protocol(format!("a `{ty}` line: {e}")))
}

/// Parses one line (without its newline).
///
/// A model's arguments may nest as deep as harness accepts them, one level
/// past serde_json's recursion limit once a line wraps them: such a line is
/// read again with its `input` skipped, so `tool_use` and `approval_request`
/// carry `input: null` and a `client_tool_call` is answered `is_error`.
pub(crate) fn parse(line: &[u8]) -> Result<Line, Error> {
    let not_json = |e: serde_json::Error| {
        Error::Protocol(format!(
            "a line that is not JSON ({e}): {}",
            String::from_utf8_lossy(&line[..line.len().min(200)])
        ))
    };
    let (value, too_deep) = match serde_json::from_slice::<Value>(line) {
        Ok(value) => (value, false),
        Err(e) if e.to_string().starts_with("recursion limit exceeded") => {
            let WithoutInput(map) = serde_json::from_slice(line).map_err(not_json)?;
            (Value::Object(map), true)
        }
        Err(e) => return Err(not_json(e)),
    };
    let Value::Object(map) = value else {
        return Err(Error::Protocol("a line that is not a JSON object".into()));
    };
    let Some(ty) = map.get("type").and_then(Value::as_str).map(str::to_string) else {
        return Err(Error::Protocol("a line with no string `type`".into()));
    };
    let v = Value::Object(map);
    Ok(match ty.as_str() {
        "init" => {
            let version = v
                .get("v")
                .and_then(Value::as_u64)
                .ok_or_else(|| Error::Protocol("an `init` line with no `v`".into()))?;
            Line::Init(Box::new(field(&ty, v)?), version)
        }
        "user" => Line::Event(Box::new(Event::User(field(&ty, v)?))),
        "reasoning" => Line::Event(Box::new(Event::Reasoning(field(&ty, v)?))),
        "assistant" => Line::Event(Box::new(Event::Assistant(field(&ty, v)?))),
        "tool_use" => Line::Event(Box::new(Event::ToolUse(field(&ty, v)?))),
        "tool_result" => Line::Event(Box::new(Event::ToolResult(field(&ty, v)?))),
        "approval" => Line::Event(Box::new(Event::Approval(field(&ty, v)?))),
        "approval_request" => Line::Event(Box::new(Event::ApprovalRequest(field(&ty, v)?))),
        "compacted" => Line::Event(Box::new(Event::Compacted(field(&ty, v)?))),
        "result" => Line::Event(Box::new(Event::Result(field(&ty, v)?))),
        "client_tool_call" => {
            let mut call: ToolCall = field(&ty, v)?;
            call.too_deep = too_deep;
            Line::ClientToolCall(call)
        }
        "client_tool_cancel" => {
            #[derive(Deserialize)]
            struct Cancel {
                id: String,
            }
            Line::ClientToolCancel(field::<Cancel>(&ty, v)?.id)
        }
        "response" => {
            #[derive(Deserialize)]
            struct ErrorBody {
                code: String,
                message: String,
            }
            #[derive(Deserialize)]
            struct Raw {
                #[serde(default)]
                id: Value,
                command: String,
                ok: bool,
                disposition: Option<String>,
                data: Option<Value>,
                error: Option<ErrorBody>,
            }
            let raw: Raw = field(&ty, v)?;
            Line::Response(Response {
                id: raw.id.as_str().map(str::to_string),
                command: raw.command,
                ok: raw.ok,
                disposition: raw.disposition,
                data: raw.data,
                error: raw.error.map(|e| (e.code, e.message)),
            })
        }
        _ => Line::Other,
    })
}

/// A command's line, measured against harness's limit (R8.5.2): the encoded
/// line with its newline must fit, else `TooLarge`.
pub(crate) fn encode(command: &Value) -> Result<String, Error> {
    let mut line = serde_json::to_string(command).map_err(|e| Error::Protocol(e.to_string()))?;
    if line.len() + 1 > LINE_LIMIT {
        return Err(Error::TooLarge);
    }
    line.push('\n');
    Ok(line)
}

/// `text` cut to at most `limit` bytes, on a character boundary.
pub(crate) fn cut(text: &str, limit: usize) -> &str {
    if text.len() <= limit {
        return text;
    }
    let mut end = limit;
    while !text.is_char_boundary(end) {
        end -= 1;
    }
    &text[..end]
}

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

    #[test]
    fn an_unknown_type_and_field_are_tolerated() {
        let line = parse(br#"{"type":"assistant","text":"hi","new":1}"#).unwrap();
        assert!(
            matches!(line, Line::Event(e) if matches!(&*e, Event::Assistant(t) if t.text == "hi"))
        );
        let line = parse(br#"{"type":"brand_new","x":1}"#).unwrap();
        assert!(matches!(line, Line::Other));
    }

    #[test]
    fn a_missing_required_field_or_not_json_is_a_protocol_error() {
        assert!(matches!(
            parse(br#"{"type":"tool_use","id":"a","tool":"t"}"#),
            Err(Error::Protocol(_))
        ));
        assert!(matches!(parse(b"not json"), Err(Error::Protocol(_))));
        assert!(matches!(parse(b"[1]"), Err(Error::Protocol(_))));
    }

    #[test]
    fn a_line_at_the_limit_fits_and_one_byte_over_does_not() {
        // `{"t":"…"}` is 8 bytes around the text, plus the newline.
        let fits = "a".repeat(LINE_LIMIT - 9);
        assert!(encode(&json!({ "t": fits })).is_ok());
        let over = "a".repeat(LINE_LIMIT - 8);
        assert_eq!(encode(&json!({ "t": over })), Err(Error::TooLarge));
    }

    #[test]
    fn the_client_tool_lines_parse_and_a_missing_field_is_a_protocol_error() {
        let line = parse(
            br#"{"type":"client_tool_call","id":"c","name":"pay","input":{"n":1},"turn_id":"t"}"#,
        )
        .unwrap();
        assert!(
            matches!(line, Line::ClientToolCall(c) if c.id == "c" && c.name == "pay" && c.input == json!({"n": 1}))
        );
        let line =
            parse(br#"{"type":"client_tool_cancel","id":"c","reason":"timed_out"}"#).unwrap();
        assert!(matches!(line, Line::ClientToolCancel(id) if id == "c"));
        assert!(matches!(
            parse(br#"{"type":"client_tool_call","id":"c","input":{}}"#),
            Err(Error::Protocol(_))
        ));
    }

    /// Review Focus 2: arguments at harness's deepest (127 levels) put the
    /// lines that carry them one past serde_json's limit; each is still read.
    #[test]
    fn lines_with_input_nested_127_deep_are_read_without_it() {
        let input = format!("{}1{}", "[".repeat(127), "]".repeat(127));
        let call = format!(
            r#"{{"type":"client_tool_call","id":"c","name":"pay","input":{input},"turn_id":"t"}}"#
        );
        match parse(call.as_bytes()).unwrap() {
            Line::ClientToolCall(c) => {
                assert!(c.too_deep && c.input.is_null() && c.id == "c" && c.name == "pay");
            }
            other => panic!("{other:?}"),
        }
        let tool_use = format!(r#"{{"type":"tool_use","id":"u","tool":"pay","input":{input}}}"#);
        assert!(matches!(
            parse(tool_use.as_bytes()).unwrap(),
            Line::Event(e) if matches!(&*e, Event::ToolUse(u) if u.input.is_null() && u.id == "u")
        ));
        let request = format!(
            r#"{{"type":"approval_request","id":"r","tool_use_id":"u","tool":"pay","kind":"client_tool","summary":"pay","input":{input},"choices":["deny"],"turn_grant_skips_kind":false}}"#
        );
        assert!(matches!(
            parse(request.as_bytes()).unwrap(),
            Line::Event(e) if matches!(&*e, Event::ApprovalRequest(r) if r.input.is_null() && r.id == "r")
        ));
        // A shallower one keeps its input.
        let shallow = format!(
            r#"{{"type":"client_tool_call","id":"c","name":"pay","input":{}1{}}}"#,
            "[".repeat(100),
            "]".repeat(100)
        );
        assert!(
            matches!(parse(shallow.as_bytes()).unwrap(), Line::ClientToolCall(c) if !c.too_deep)
        );
    }

    #[test]
    fn cut_keeps_whole_characters() {
        assert_eq!(cut("aé", 2), "a");
        assert_eq!(cut("abc", 5), "abc");
    }

    #[test]
    fn get_state_parses() {
        let s: State = serde_json::from_value(json!({"away":false,"context":{"auto_compact_at_percent":80,"last_prompt_tokens":null,"percent":null,"window":null},"mode":"manual","model":"m","open_requests":[],"queued":0,"session_id":"s","thinking":"medium","turn":{"id":null,"prompt_id":"p"}})).unwrap();
        assert_eq!(
            s.turn,
            TurnState::Running {
                id: None,
                prompt_id: Some("p".into())
            }
        );
    }
}

#[cfg(test)]
mod word_tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn a_known_word_is_typed_and_an_unknown_one_kept() {
        let r: ApprovalRequest = serde_json::from_value(json!({
            "id": "r", "tool_use_id": "t", "tool": "pay", "kind": "client_tool",
            "summary": "pay", "input": {}, "choices": ["allow_once", "brand_new"],
            "turn_grant_skips_kind": false,
        }))
        .unwrap();
        assert_eq!(r.kind, ApprovalKind::ClientTool);
        assert_eq!(
            r.choices,
            vec![Choice::AllowOnce, Choice::Other("brand_new".into())]
        );
        assert_eq!(Choice::Other("x".into()).as_str(), "x");
        assert_eq!(Outcome::from_wire("completed"), Outcome::Completed);
    }
}

#[cfg(test)]
mod conformance_tests {
    use super::*;

    /// R7.3: the SDK reads every line harness wrote in every committed
    /// transcript (`sdk/conformance`, kept equal to the binary's output by
    /// `scripts/sdk/regen-transcripts.sh --check`) into the type its `type`
    /// names. The transcripts are read, not replayed through a `Client`:
    /// their `"invalid"` inbound lines (raw text, unknown commands) are
    /// ones a `Client` cannot send. Inbound lines are not the SDK's to read.
    #[test]
    fn every_outbound_transcript_line_parses_into_its_type() {
        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../conformance");
        let mut files = 0;
        let mut types = std::collections::BTreeSet::new();
        for entry in std::fs::read_dir(&dir).unwrap().flatten() {
            let path = entry.path();
            if path.extension().is_none_or(|e| e != "jsonl") {
                continue;
            }
            files += 1;
            let name = path.file_stem().unwrap().to_string_lossy().into_owned();
            for line in std::fs::read_to_string(&path).unwrap().lines() {
                let entry: Value = serde_json::from_str(line).unwrap();
                if entry["dir"] != "out" {
                    continue;
                }
                assert!(entry.get("invalid").is_none(), "{name}: {entry}");
                let ty = entry["line"]["type"].as_str().unwrap().to_string();
                let text = entry["line"].to_string();
                let got = parse(text.as_bytes()).unwrap_or_else(|e| panic!("{name}: {text}: {e}"));
                let ok = match (&got, ty.as_str()) {
                    (Line::Init(..), "init")
                    | (Line::Response(_), "response")
                    | (Line::ClientToolCall(_), "client_tool_call")
                    | (Line::ClientToolCancel(_), "client_tool_cancel")
                    | (Line::Other, "text_delta") => true,
                    (Line::Event(e), ty) => matches!(
                        (&**e, ty),
                        (Event::User(_), "user")
                            | (Event::Reasoning(_), "reasoning")
                            | (Event::Assistant(_), "assistant")
                            | (Event::ToolUse(_), "tool_use")
                            | (Event::ToolResult(_), "tool_result")
                            | (Event::Approval(_), "approval")
                            | (Event::ApprovalRequest(_), "approval_request")
                            | (Event::Compacted(_), "compacted")
                            | (Event::Result(_), "result")
                    ),
                    _ => false,
                };
                assert!(ok, "{name}: `{ty}` was read as {got:?}");
                types.insert(ty);
            }
        }
        let scripts = std::fs::read_dir(dir.join("scripts")).unwrap().count();
        assert_eq!(files, scripts, "a script without a transcript");
        // The cli crate's `every_outbound_line_type_is_an_event_or_consumed`
        // holds this set equal to `LINE_TYPES`.
        let seen: Vec<&str> = types.iter().map(String::as_str).collect();
        assert_eq!(
            seen,
            [
                "approval",
                "approval_request",
                "assistant",
                "client_tool_call",
                "client_tool_cancel",
                "compacted",
                "init",
                "reasoning",
                "response",
                "result",
                "text_delta",
                "tool_result",
                "tool_use",
                "user"
            ]
        );
    }
}