localharness 0.15.0

A Rust-native agent SDK for Gemini. Streaming, custom tools, safety policies, background triggers — zero external binaries.
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
//! Public boundary types for the SDK.
//!
//! These mirror the Pydantic models in `google/antigravity/types.py` so a
//! payload that round-trips through JSON looks identical on the wire. The
//! Rust port uses owned data (`String`/`Vec`) at the boundary for ergonomic
//! cloning; hot paths in the connection layer use `Bytes` where it pays.

use std::collections::HashSet;

use serde::{Deserialize, Serialize};

// Google's chat model. `gemini-3.x` doesn't exist on the public API
// yet — using a model id the API actually accepts. Bump this when
// Google publishes newer ids (and re-test 400s).
/// Default chat model ID.
pub const DEFAULT_MODEL: &str = "gemini-3.5-flash";
/// Default image generation model ID.
pub const DEFAULT_IMAGE_GENERATION_MODEL: &str = "gemini-2.0-flash-exp-image-generation";

// =============================================================================
// Model configuration
// =============================================================================

/// How much "thinking" (chain-of-thought reasoning) the model produces.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ThinkingLevel {
    /// Least reasoning output.
    Minimal,
    /// Low reasoning output.
    Low,
    /// Moderate reasoning output.
    Medium,
    /// Maximum reasoning output.
    High,
}

/// Model generation parameters.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct GenerationConfig {
    /// Optional thinking level override.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thinking_level: Option<ThinkingLevel>,
}

/// A named model with optional per-model API key and generation settings.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ModelEntry {
    /// Model identifier (e.g. `"gemini-2.5-flash"`).
    pub name: String,
    /// Per-model API key override.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub api_key: Option<String>,
    /// Generation parameters for this model.
    #[serde(default)]
    pub generation: GenerationConfig,
}

impl ModelEntry {
    /// Create a model entry with the given name and default settings.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            api_key: None,
            generation: GenerationConfig::default(),
        }
    }
}

impl Default for ModelEntry {
    fn default() -> Self {
        Self::new(DEFAULT_MODEL)
    }
}

/// Paired model entries for chat and image generation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ModelConfig {
    /// The primary chat model.
    pub default: ModelEntry,
    /// The model used for image generation.
    pub image_generation: ModelEntry,
}

impl Default for ModelConfig {
    fn default() -> Self {
        Self {
            default: ModelEntry::new(DEFAULT_MODEL),
            image_generation: ModelEntry::new(DEFAULT_IMAGE_GENERATION_MODEL),
        }
    }
}

/// Gemini-specific configuration embedded in [`AgentConfig`](crate::AgentConfig).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct GeminiConfig {
    /// Gemini API key.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub api_key: Option<String>,
    /// Chat and image generation model entries.
    #[serde(default)]
    pub models: ModelConfig,
}

// =============================================================================
// System instructions
// =============================================================================

/// One titled section within templated system instructions.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SystemInstructionSection {
    /// The instruction text.
    pub content: String,
    /// Section title shown to the model.
    #[serde(default = "default_section_title")]
    pub title: String,
}

fn default_section_title() -> String {
    "user_system_instructions".to_string()
}

impl Default for SystemInstructionSection {
    fn default() -> Self {
        Self {
            content: String::new(),
            title: default_section_title(),
        }
    }
}

/// Plain-text system instructions.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CustomSystemInstructions {
    /// The raw instruction text.
    pub text: String,
}

/// Structured system instructions with identity and titled sections.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TemplatedSystemInstructions {
    /// Optional identity string for the agent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub identity: Option<String>,
    /// Ordered instruction sections.
    #[serde(default)]
    pub sections: Vec<SystemInstructionSection>,
}

/// System instructions: either a plain string or structured sections.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum SystemInstructions {
    /// Free-form text instructions.
    Custom(CustomSystemInstructions),
    /// Structured instructions with identity and sections.
    Templated(TemplatedSystemInstructions),
}

impl From<&str> for SystemInstructions {
    fn from(text: &str) -> Self {
        Self::Custom(CustomSystemInstructions { text: text.into() })
    }
}

impl From<String> for SystemInstructions {
    fn from(text: String) -> Self {
        Self::Custom(CustomSystemInstructions { text })
    }
}

// =============================================================================
// Builtin tools + capability flags
// =============================================================================

/// Identifiers for the SDK's built-in tools.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BuiltinTool {
    /// List a directory's contents.
    ListDirectory,
    /// Regex search within files.
    SearchDirectory,
    /// Find files by glob pattern.
    FindFile,
    /// Read a file's contents.
    ViewFile,
    /// Create a new file.
    CreateFile,
    /// Apply edits to an existing file.
    EditFile,
    /// Delete a file or directory.
    DeleteFile,
    /// Rename or move a file.
    RenameFile,
    /// Execute a shell command.
    RunCommand,
    /// Prompt the user with a question.
    AskQuestion,
    /// Spawn a sub-agent.
    StartSubagent,
    /// Generate an image via the image model.
    GenerateImage,
    /// Call another agent via inter-agent RPC.
    CallAgent,
    /// Compile and run a rustlite program.
    CompileRustlite,
    /// Compile a rustlite cartridge and run it on the visual display.
    RunCartridge,
    /// Render an HTML document onto the visual display (framebuffer).
    RenderHtml,
    /// Read/update this agent's own config manifest (system prompt + tool
    /// allowlist), or reset it to defaults.
    ConfigureAgent,
    /// Signal that the agent's turn is complete.
    Finish,
}

impl BuiltinTool {
    /// Every built-in tool variant.
    pub const ALL: &'static [BuiltinTool] = &[
        Self::ListDirectory,
        Self::SearchDirectory,
        Self::FindFile,
        Self::ViewFile,
        Self::CreateFile,
        Self::EditFile,
        Self::DeleteFile,
        Self::RenameFile,
        Self::RunCommand,
        Self::AskQuestion,
        Self::StartSubagent,
        Self::GenerateImage,
        Self::CallAgent,
        Self::CompileRustlite,
        Self::RunCartridge,
        Self::RenderHtml,
        Self::ConfigureAgent,
        Self::Finish,
    ];

    /// Tools that only read state (no side effects).
    pub const READ_ONLY: &'static [BuiltinTool] = &[
        Self::ListDirectory,
        Self::SearchDirectory,
        Self::FindFile,
        Self::ViewFile,
        Self::Finish,
    ];

    /// Tools that operate on individual files.
    pub const FILE_TOOLS: &'static [BuiltinTool] = &[
        Self::ViewFile,
        Self::CreateFile,
        Self::EditFile,
        Self::DeleteFile,
        Self::RenameFile,
    ];

    /// The snake_case wire name the model uses to invoke this tool.
    pub fn wire_name(self) -> &'static str {
        match self {
            Self::ListDirectory => "list_directory",
            Self::SearchDirectory => "search_directory",
            Self::FindFile => "find_file",
            Self::ViewFile => "view_file",
            Self::CreateFile => "create_file",
            Self::EditFile => "edit_file",
            Self::DeleteFile => "delete_file",
            Self::RenameFile => "rename_file",
            Self::RunCommand => "run_command",
            Self::AskQuestion => "ask_question",
            Self::StartSubagent => "start_subagent",
            Self::GenerateImage => "generate_image",
            Self::CallAgent => "call_agent",
            Self::CompileRustlite => "compile_rustlite",
            Self::RunCartridge => "run_cartridge",
            Self::RenderHtml => "render_html",
            Self::ConfigureAgent => "configure_agent",
            Self::Finish => "finish",
        }
    }
}

/// Controls which built-in tools are exposed to the model.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CapabilitiesConfig {
    /// Whether sub-agent spawning is allowed.
    pub enable_subagents: bool,
    /// Explicit allowlist (mutually exclusive with `disabled_tools`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled_tools: Option<Vec<BuiltinTool>>,
    /// Explicit denylist (mutually exclusive with `enabled_tools`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub disabled_tools: Option<Vec<BuiltinTool>>,
    /// History-entry count that triggers auto-compaction.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub compaction_threshold: Option<u32>,
    /// Model ID used for image generation.
    pub image_model: String,
    /// JSON schema for the `finish` tool's structured output.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub finish_tool_schema_json: Option<String>,
}

impl Default for CapabilitiesConfig {
    fn default() -> Self {
        // Python defaults to read-only safety mode unless the caller opts in.
        Self {
            enable_subagents: true,
            enabled_tools: Some(BuiltinTool::READ_ONLY.to_vec()),
            disabled_tools: None,
            compaction_threshold: None,
            image_model: DEFAULT_IMAGE_GENERATION_MODEL.to_string(),
            finish_tool_schema_json: None,
        }
    }
}

impl CapabilitiesConfig {
    /// Unrestricted: exposes every builtin tool to the model. Matches the
    /// Python `CapabilitiesConfig()` no-arg constructor.
    pub fn unrestricted() -> Self {
        Self {
            enable_subagents: true,
            enabled_tools: None,
            disabled_tools: None,
            compaction_threshold: None,
            image_model: DEFAULT_IMAGE_GENERATION_MODEL.to_string(),
            finish_tool_schema_json: None,
        }
    }

    /// Resolve the effective enabled-tool set, given that `enabled_tools` and
    /// `disabled_tools` are mutually exclusive (the validator enforces it).
    pub fn effective_tools(&self) -> HashSet<BuiltinTool> {
        match (&self.enabled_tools, &self.disabled_tools) {
            (Some(en), _) => en.iter().copied().collect(),
            (None, Some(dis)) => {
                let disabled: HashSet<_> = dis.iter().copied().collect();
                BuiltinTool::ALL
                    .iter()
                    .copied()
                    .filter(|t| !disabled.contains(t))
                    .collect()
            }
            (None, None) => BuiltinTool::ALL.iter().copied().collect(),
        }
    }

    /// Verify that `enabled_tools` and `disabled_tools` are not both set.
    pub fn validate(&self) -> Result<(), crate::error::Error> {
        if self.enabled_tools.is_some() && self.disabled_tools.is_some() {
            return Err(crate::error::Error::config(
                "enabled_tools and disabled_tools are mutually exclusive",
            ));
        }
        Ok(())
    }
}

// =============================================================================
// MCP server configuration
// =============================================================================

/// How to connect to an MCP server.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum McpServerConfig {
    /// Launch a child process and communicate over stdin/stdout.
    Stdio {
        /// Command to spawn.
        command: String,
        /// Command-line arguments.
        #[serde(default)]
        args: Vec<String>,
    },
    /// Connect to an SSE-based MCP server (not yet implemented).
    Sse {
        /// Server URL.
        url: String,
        /// Optional HTTP headers.
        #[serde(skip_serializing_if = "Option::is_none")]
        headers: Option<std::collections::BTreeMap<String, String>>,
    },
    /// Connect to an HTTP-based MCP server (not yet implemented).
    Http {
        /// Server URL.
        url: String,
        /// Optional HTTP headers.
        #[serde(skip_serializing_if = "Option::is_none")]
        headers: Option<std::collections::BTreeMap<String, String>>,
        /// Per-call timeout in seconds.
        #[serde(default = "default_http_timeout")]
        timeout_secs: f64,
        /// SSE read timeout in seconds.
        #[serde(default = "default_sse_read_timeout")]
        sse_read_timeout_secs: f64,
        /// Whether to kill the server when the client closes.
        #[serde(default = "default_terminate_on_close")]
        terminate_on_close: bool,
    },
}

fn default_http_timeout() -> f64 {
    30.0
}
fn default_sse_read_timeout() -> f64 {
    300.0
}
fn default_terminate_on_close() -> bool {
    true
}

// =============================================================================
// Tool calls + results
// =============================================================================

/// A tool invocation requested by the model.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolCall {
    /// Wire name of the tool.
    pub name: String,
    /// JSON arguments the model supplied.
    #[serde(default)]
    pub args: serde_json::Value,
    /// Backend-assigned call ID for correlating results.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub id: Option<String>,
    /// Resolved filesystem path (set by file tools for policy evaluation).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub canonical_path: Option<String>,
}

/// The outcome of executing a [`ToolCall`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolResult {
    /// Wire name of the tool that was called.
    pub name: String,
    /// Call ID this result corresponds to.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub id: Option<String>,
    /// JSON value on success.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub result: Option<serde_json::Value>,
    /// Error message on failure.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub error: Option<String>,
}

impl ToolResult {
    /// Build a successful tool result.
    pub fn ok(name: impl Into<String>, id: Option<String>, value: serde_json::Value) -> Self {
        Self {
            name: name.into(),
            id,
            result: Some(value),
            error: None,
        }
    }

    /// Build a failed tool result with an error message.
    pub fn err(name: impl Into<String>, id: Option<String>, message: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            id,
            result: None,
            error: Some(message.into()),
        }
    }
}

// =============================================================================
// Usage metadata
// =============================================================================

/// Token usage statistics from the backend.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct UsageMetadata {
    /// Tokens in the prompt.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub prompt_token_count: Option<i32>,
    /// Tokens served from cache.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub cached_content_token_count: Option<i32>,
    /// Tokens in the model's response.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub candidates_token_count: Option<i32>,
    /// Tokens used for chain-of-thought reasoning.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub thoughts_token_count: Option<i32>,
    /// Total tokens (prompt + response + thoughts).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub total_token_count: Option<i32>,
}

impl UsageMetadata {
    /// Fold `other` into `self`. Missing fields on either side are treated as
    /// zero so the accumulator only advances when the backend reports usage.
    pub fn accumulate(&mut self, other: &UsageMetadata) {
        fn add(a: &mut Option<i32>, b: Option<i32>) {
            if let Some(v) = b {
                *a = Some(a.unwrap_or(0).saturating_add(v));
            }
        }
        add(&mut self.prompt_token_count, other.prompt_token_count);
        add(
            &mut self.cached_content_token_count,
            other.cached_content_token_count,
        );
        add(
            &mut self.candidates_token_count,
            other.candidates_token_count,
        );
        add(&mut self.thoughts_token_count, other.thoughts_token_count);
        add(&mut self.total_token_count, other.total_token_count);
    }
}

// =============================================================================
// Steps
// =============================================================================

/// The kind of event a step represents.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum StepType {
    /// Model-generated text response.
    #[serde(rename = "TEXT_RESPONSE")]
    TextResponse,
    /// Model requesting a tool call.
    #[serde(rename = "TOOL_CALL")]
    ToolCall,
    /// System-generated message.
    #[serde(rename = "SYSTEM_MESSAGE")]
    SystemMessage,
    /// History compaction event.
    #[serde(rename = "COMPACTION")]
    Compaction,
    /// Agent signaling completion.
    #[serde(rename = "FINISH")]
    Finish,
    /// Unrecognized step type.
    #[serde(rename = "UNKNOWN")]
    Unknown,
}

/// Who produced a step.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum StepSource {
    /// Generated by the system/SDK.
    #[serde(rename = "SYSTEM")]
    System,
    /// Originated from the user.
    #[serde(rename = "USER")]
    User,
    /// Produced by the model.
    #[serde(rename = "MODEL")]
    Model,
    /// Unknown origin.
    #[serde(rename = "UNKNOWN")]
    Unknown,
}

/// Intended audience of a step.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum StepTarget {
    /// Addressed to the user.
    #[serde(rename = "TARGET_USER")]
    User,
    /// Addressed to the environment (tools).
    #[serde(rename = "TARGET_ENVIRONMENT")]
    Environment,
    /// No specific target.
    #[serde(rename = "TARGET_UNSPECIFIED")]
    Unspecified,
    /// Unknown target.
    #[serde(rename = "UNKNOWN")]
    Unknown,
}

/// Lifecycle state of a step.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum StepStatus {
    /// Turn is still in progress.
    #[serde(rename = "ACTIVE")]
    Active,
    /// Turn completed successfully.
    #[serde(rename = "DONE")]
    Done,
    /// Waiting for user input.
    #[serde(rename = "WAITING_FOR_USER")]
    WaitingForUser,
    /// Turn ended with an error.
    #[serde(rename = "ERROR")]
    Error,
    /// Turn was canceled.
    #[serde(rename = "CANCELED")]
    Canceled,
    /// Unknown status.
    #[serde(rename = "UNKNOWN")]
    Unknown,
}

/// One event in the agent's response stream.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Step {
    /// Backend-assigned step identifier.
    #[serde(default)]
    pub id: String,
    /// Zero-based index within the current turn.
    #[serde(default)]
    pub step_index: u32,
    /// What kind of event this step represents.
    #[serde(rename = "type", default = "Step::default_type")]
    pub kind: StepType,
    /// Who produced this step.
    #[serde(default = "Step::default_source")]
    pub source: StepSource,
    /// Intended audience.
    #[serde(default = "Step::default_target")]
    pub target: StepTarget,
    /// Lifecycle state.
    #[serde(default = "Step::default_status")]
    pub status: StepStatus,
    /// Accumulated text content.
    #[serde(default)]
    pub content: String,
    /// Incremental text delta since the last step.
    #[serde(default)]
    pub content_delta: String,
    /// Accumulated thinking (reasoning) text.
    #[serde(default)]
    pub thinking: String,
    /// Incremental thinking delta.
    #[serde(default)]
    pub thinking_delta: String,
    /// Tool calls the model is requesting.
    #[serde(default)]
    pub tool_calls: Vec<ToolCall>,
    /// Error message, if any.
    #[serde(default)]
    pub error: String,
    /// Explicit flag that this step ends the turn.
    #[serde(default)]
    pub is_complete_response: Option<bool>,
    /// Structured JSON output from the `finish` tool.
    #[serde(default)]
    pub structured_output: Option<serde_json::Value>,
    /// Token usage for this step.
    #[serde(default)]
    pub usage_metadata: Option<UsageMetadata>,
}

impl Step {
    fn default_type() -> StepType {
        StepType::Unknown
    }
    fn default_source() -> StepSource {
        StepSource::Unknown
    }
    fn default_target() -> StepTarget {
        StepTarget::Unknown
    }
    fn default_status() -> StepStatus {
        StepStatus::Unknown
    }

    /// A turn-terminating step: model-sourced, user-facing, status DONE, with
    /// content. Mirrors `is_complete_response` semantics in the Python SDK.
    pub fn is_terminal_response(&self) -> bool {
        self.is_complete_response.unwrap_or(false)
            || (self.source == StepSource::Model
                && self.target == StepTarget::User
                && self.status == StepStatus::Done
                && !self.content.is_empty())
    }
}

// =============================================================================
// Hooks
// =============================================================================

/// The decision from a decide-hook: allow or deny, with a reason.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HookResult {
    /// `true` to proceed, `false` to block.
    pub allow: bool,
    /// Human-readable reason for the decision.
    #[serde(default)]
    pub message: String,
}

impl HookResult {
    /// Allow with no message.
    pub fn allow() -> Self {
        Self {
            allow: true,
            message: String::new(),
        }
    }

    /// Allow with a diagnostic message.
    pub fn allow_with(message: impl Into<String>) -> Self {
        Self {
            allow: true,
            message: message.into(),
        }
    }

    /// Deny with a reason message.
    pub fn deny(message: impl Into<String>) -> Self {
        Self {
            allow: false,
            message: message.into(),
        }
    }
}

// =============================================================================
// Ask-question (interactive) primitives
// =============================================================================

/// One selectable option in an interactive question.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AskQuestionOption {
    /// Machine-readable identifier.
    pub id: String,
    /// Display text.
    pub text: String,
}

/// A single question with a set of options.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AskQuestionEntry {
    /// The question text.
    pub question: String,
    /// Available answer choices.
    pub options: Vec<AskQuestionOption>,
    /// Whether multiple options can be selected.
    #[serde(default)]
    pub is_multi_select: bool,
}

/// A batch of interactive questions for the user.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AskQuestionInteractionSpec {
    /// The questions to present.
    pub questions: Vec<AskQuestionEntry>,
}

/// The user's answer to an interactive question.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct QuestionResponse {
    /// IDs of the selected options.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub selected_option_ids: Option<Vec<String>>,
    /// Free-text answer.
    #[serde(default)]
    pub freeform_response: String,
    /// Whether the user skipped the question.
    #[serde(default)]
    pub skipped: bool,
}

// =============================================================================
// Trigger delivery semantics
// =============================================================================

/// When a trigger's message is delivered to the agent.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TriggerDelivery {
    /// Deliver immediately, even mid-turn.
    SendImmediately,
    /// Wait until the agent is idle before delivering.
    #[default]
    WaitIdle,
}

// =============================================================================
// Stream chunks
// =============================================================================

/// A single semantic event emitted while a turn is in flight.
///
/// `Text` and `Thought` carry incremental deltas (already split into
/// human-readable chunks). `ToolCall` and `ToolResult` carry strongly typed
/// dispatches so consumers can render spinners without parsing JSON.
#[derive(Debug, Clone, PartialEq)]
pub enum StreamChunk {
    /// Incremental conversational text delta.
    Text {
        /// Index of the step that produced this chunk.
        step_index: u32,
        /// The text fragment.
        text: String,
    },
    /// Incremental reasoning/thinking delta.
    Thought {
        /// Index of the step that produced this chunk.
        step_index: u32,
        /// The thinking fragment.
        text: String,
    },
    /// The model is requesting a tool call.
    ToolCall(ToolCall),
    /// A tool call completed with a result.
    ToolResult(ToolResult),
}

// =============================================================================
// Persisted transcript
// =============================================================================

/// User-visible role of a [`TranscriptEntry`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TranscriptRole {
    /// Message from the user.
    User,
    /// Message from the model.
    Assistant,
}

impl TranscriptRole {
    /// Lowercase string representation (`"user"` or `"assistant"`).
    pub fn as_str(&self) -> &'static str {
        match self {
            TranscriptRole::User => "user",
            TranscriptRole::Assistant => "assistant",
        }
    }
}

/// One turn-or-message in a flattened, user-visible transcript.
///
/// Produced by [`Agent::transcript`] — includes tool-call activity
/// so restored sessions show what the agent did, not just what it said.
///
/// [`Agent::transcript`]: crate::Agent::transcript
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TranscriptEntry {
    /// Who sent this message.
    pub role: TranscriptRole,
    /// The textual content of the message.
    pub text: String,
    /// Tool calls made during this turn (assistant only).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tool_calls: Vec<TranscriptToolCall>,
}

/// A tool call as recorded in the transcript.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TranscriptToolCall {
    /// Tool name.
    pub name: String,
    /// Arguments the model supplied.
    pub args: serde_json::Value,
    /// Result value, if the call succeeded.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub result: Option<serde_json::Value>,
    /// Error message, if the call failed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}