ironflow-core 2.8.0

Rust workflow engine with Claude Code native agent support
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
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
//! Provider trait and configuration types for agent invocations.
//!
//! The [`AgentProvider`] trait is the primary extension point in ironflow: implement it
//! to plug in any AI backend (local model, HTTP API, mock, etc.) without changing
//! your workflow code.
//!
//! Built-in implementations:
//!
//! * [`ClaudeCodeProvider`](crate::providers::claude::ClaudeCodeProvider) - local `claude` CLI.
//! * `SshProvider` - remote via SSH (requires `transport-ssh` feature).
//! * `DockerProvider` - Docker container (requires `transport-docker` feature).
//! * `K8sEphemeralProvider` - ephemeral K8s pod (requires `transport-k8s` feature).
//! * `K8sPersistentProvider` - persistent K8s pod (requires `transport-k8s` feature).
//! * [`RecordReplayProvider`](crate::providers::record_replay::RecordReplayProvider) -
//!   records and replays fixtures for deterministic testing.

use std::fmt;
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::error::AgentError;
use crate::operations::agent::{Model, PermissionMode};

/// Boxed future returned by [`AgentProvider::invoke`].
pub type InvokeFuture<'a> =
    Pin<Box<dyn Future<Output = Result<AgentOutput, AgentError>> + Send + 'a>>;

// ── Typestate markers ──────────────────────────────────────────────

/// Marker: no tools have been added via the builder.
#[derive(Debug, Clone, Copy)]
pub struct NoTools;

/// Marker: at least one tool has been added via [`AgentConfig::allow_tool`].
#[derive(Debug, Clone, Copy)]
pub struct WithTools;

/// Marker: no JSON schema has been set via the builder.
#[derive(Debug, Clone, Copy)]
pub struct NoSchema;

/// Marker: a JSON schema has been set via [`AgentConfig::output`] or
/// [`AgentConfig::output_schema_raw`].
#[derive(Debug, Clone, Copy)]
pub struct WithSchema;

// ── AgentConfig ────────────────────────────────────────────────────

/// Serializable configuration passed to an [`AgentProvider`] for a single invocation.
///
/// Built by [`Agent::run`](crate::operations::agent::Agent::run) from the builder state.
/// Provider implementations translate these fields into whatever format the underlying
/// backend expects.
///
/// # Typestate: tools vs structured output
///
/// Claude CLI has a [known bug](https://github.com/anthropics/claude-code/issues/18536)
/// where combining `--json-schema` with `--allowedTools` always returns
/// `structured_output: null`. To prevent this at compile time, [`allow_tool`](Self::allow_tool)
/// and [`output`](Self::output) / [`output_schema_raw`](Self::output_schema_raw) are mutually
/// exclusive: using one removes the other from the available API.
///
/// ```
/// use ironflow_core::provider::AgentConfig;
///
/// // OK: tools only
/// let _ = AgentConfig::new("search").allow_tool("WebSearch");
///
/// // OK: structured output only
/// let _ = AgentConfig::new("classify").output_schema_raw(r#"{"type":"object"}"#);
/// ```
///
/// ```compile_fail
/// use ironflow_core::provider::AgentConfig;
/// // COMPILE ERROR: cannot add tools after setting structured output
/// let _ = AgentConfig::new("x").output_schema_raw("{}").allow_tool("Read");
/// ```
///
/// ```compile_fail
/// use ironflow_core::provider::AgentConfig;
/// // COMPILE ERROR: cannot set structured output after adding tools
/// let _ = AgentConfig::new("x").allow_tool("Read").output_schema_raw("{}");
/// ```
///
/// **Workaround**: split the work into two steps -- one agent with tools to
/// gather data, then a second agent with `.output::<T>()` to structure the result.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(bound(serialize = "", deserialize = ""))]
#[non_exhaustive]
pub struct AgentConfig<Tools = NoTools, Schema = NoSchema> {
    /// Optional system prompt that sets the agent's persona or constraints.
    pub system_prompt: Option<String>,

    /// The user prompt - the main instruction to the agent.
    pub prompt: String,

    /// Which model to use for this invocation.
    ///
    /// Accepts any string. Use [`Model`] constants for well-known Claude models
    /// (e.g. `Model::SONNET`), or pass a custom identifier for other providers.
    #[serde(default = "default_model")]
    pub model: String,

    /// Allowlist of tool names the agent may invoke (empty = provider default).
    #[serde(default)]
    pub allowed_tools: Vec<String>,

    /// Denylist of tool names the agent MUST NOT invoke.
    ///
    /// Maps to `--disallowedTools` on the Claude CLI. Unlike
    /// [`allowed_tools`](Self::allowed_tools), this does **not** activate any
    /// tools; it only filters out tools that would otherwise be loaded by
    /// default. As such, it is safe to combine with structured output
    /// ([`output`](Self::output)) without triggering the Claude CLI bug that
    /// affects `--json-schema` + `--allowedTools`.
    #[serde(default)]
    pub disallowed_tools: Vec<String>,

    /// Maximum number of agentic turns before the provider should stop.
    pub max_turns: Option<u32>,

    /// Maximum spend in USD for this single invocation.
    pub max_budget_usd: Option<f64>,

    /// Working directory for the agent process.
    pub working_dir: Option<String>,

    /// Path to an MCP server configuration file.
    pub mcp_config: Option<String>,

    /// When `true`, pass `--strict-mcp-config` to the Claude CLI so it only
    /// loads MCP servers from [`mcp_config`](Self::mcp_config) and ignores
    /// any global/user MCP configuration (e.g. `~/.claude.json`).
    ///
    /// Useful to prevent global MCP servers from leaking tools into steps
    /// that request `structured_output`, which triggers the Claude CLI bug
    /// where `--json-schema` combined with any active tool returns
    /// `structured_output: null`. See
    /// <https://github.com/anthropics/claude-code/issues/18536>.
    ///
    /// Combine with `mcp_config` set to a file containing
    /// `{"mcpServers":{}}` to disable every MCP server for the invocation.
    #[serde(default)]
    pub strict_mcp_config: bool,

    /// When `true`, pass `--bare` to Claude CLI. Bare mode disables:
    /// - auto-memory (automatic creation of `~/.claude/.../memory/*.md` files)
    /// - `CLAUDE.md` auto-discovery (no global/project `CLAUDE.md` loaded)
    /// - hooks, LSP, plugin sync, attribution, background prefetches
    ///
    /// Recommended for orchestrator agents that should not have any implicit
    /// side effects on the user's filesystem or inherit user-level context.
    ///
    /// # Authentication requirement
    ///
    /// `--bare` is **only compatible with an Anthropic API key**
    /// (`ANTHROPIC_API_KEY` environment variable). It does **not** work with
    /// OAuth authentication (`claude /login` / keychain-stored credentials),
    /// because bare mode disables keychain reads.
    #[serde(default)]
    pub bare: bool,

    /// Permission mode controlling how the agent handles tool-use approvals.
    #[serde(default)]
    pub permission_mode: PermissionMode,

    /// Optional JSON Schema string. When set, the provider should request
    /// structured (typed) output from the model.
    #[serde(alias = "output_schema")]
    pub json_schema: Option<String>,

    /// Optional session ID to resume a previous conversation.
    ///
    /// When set, the provider should continue the conversation from the
    /// specified session rather than starting a new one.
    pub resume_session_id: Option<String>,

    /// Enable verbose/debug mode to capture the full conversation trace.
    ///
    /// When `true`, the provider uses streaming output (`stream-json`) to
    /// record every assistant message and tool call. The resulting
    /// [`AgentOutput::debug_messages`] field will contain the conversation
    /// trace for inspection.
    #[serde(default)]
    pub verbose: bool,

    /// Zero-sized typestate marker (not serialized).
    #[serde(skip)]
    pub(crate) _marker: PhantomData<(Tools, Schema)>,
}

fn default_model() -> String {
    Model::SONNET.to_string()
}

// ── Constructor (base type only) ───────────────────────────────────

impl AgentConfig {
    /// Create an `AgentConfig` with required fields and defaults for the rest.
    pub fn new(prompt: &str) -> Self {
        Self {
            system_prompt: None,
            prompt: prompt.to_string(),
            model: Model::SONNET.to_string(),
            allowed_tools: Vec::new(),
            disallowed_tools: Vec::new(),
            max_turns: None,
            max_budget_usd: None,
            working_dir: None,
            mcp_config: None,
            strict_mcp_config: false,
            bare: false,
            permission_mode: PermissionMode::Default,
            json_schema: None,
            resume_session_id: None,
            verbose: false,
            _marker: PhantomData,
        }
    }
}

// ── Methods available on ALL typestate variants ────────────────────

impl<Tools, Schema> AgentConfig<Tools, Schema> {
    /// Set the system prompt.
    pub fn system_prompt(mut self, prompt: &str) -> Self {
        self.system_prompt = Some(prompt.to_string());
        self
    }

    /// Set the model name.
    pub fn model(mut self, model: &str) -> Self {
        self.model = model.to_string();
        self
    }

    /// Set the maximum budget in USD.
    pub fn max_budget_usd(mut self, budget: f64) -> Self {
        self.max_budget_usd = Some(budget);
        self
    }

    /// Set the maximum number of turns.
    pub fn max_turns(mut self, turns: u32) -> Self {
        self.max_turns = Some(turns);
        self
    }

    /// Set the working directory.
    pub fn working_dir(mut self, dir: &str) -> Self {
        self.working_dir = Some(dir.to_string());
        self
    }

    /// Set the permission mode.
    pub fn permission_mode(mut self, mode: PermissionMode) -> Self {
        self.permission_mode = mode;
        self
    }

    /// Enable verbose/debug mode.
    pub fn verbose(mut self, enabled: bool) -> Self {
        self.verbose = enabled;
        self
    }

    /// Set the MCP server configuration file path.
    pub fn mcp_config(mut self, config: &str) -> Self {
        self.mcp_config = Some(config.to_string());
        self
    }

    /// Enable strict MCP config mode.
    ///
    /// When `true`, the Claude CLI is invoked with `--strict-mcp-config`,
    /// which disables loading of any MCP server defined outside the
    /// [`mcp_config`](Self::mcp_config) file (the global `~/.claude.json`
    /// and user-level configs are ignored).
    ///
    /// This is the recommended way to prevent global MCP servers from
    /// silently injecting tools into a structured-output step and
    /// triggering the Claude CLI bug that returns `structured_output: null`
    /// whenever any tool is active. See
    /// <https://github.com/anthropics/claude-code/issues/18536>.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_core::provider::AgentConfig;
    /// use schemars::JsonSchema;
    ///
    /// #[derive(serde::Deserialize, JsonSchema)]
    /// struct Out { ok: bool }
    ///
    /// // Isolate the step from any global MCP server so structured output works.
    /// let config = AgentConfig::new("classify this")
    ///     .strict_mcp_config(true)
    ///     .mcp_config(r#"{"mcpServers":{}}"#)
    ///     .output::<Out>();
    /// ```
    pub fn strict_mcp_config(mut self, strict: bool) -> Self {
        self.strict_mcp_config = strict;
        self
    }

    /// Enable bare mode (minimal Claude Code environment, see `--bare`).
    ///
    /// When `true`, the Claude CLI is invoked with `--bare`, which disables:
    /// - auto-memory (no automatic `~/.claude/.../memory/*.md` file creation)
    /// - `CLAUDE.md` auto-discovery (neither global nor project-level)
    /// - hooks, LSP, plugin sync, attribution, background prefetches,
    ///   keychain reads
    ///
    /// Sets `CLAUDE_CODE_SIMPLE=1` in the child process.
    ///
    /// Recommended for orchestrator steps that should not have any implicit
    /// side effects on the user's filesystem or inherit user-level context
    /// (email, preferences, etc.).
    ///
    /// # Authentication requirement
    ///
    /// `--bare` is **only compatible with an Anthropic API key**
    /// (`ANTHROPIC_API_KEY` environment variable). It does **not** work with
    /// OAuth authentication (`claude /login` / keychain-stored credentials),
    /// because bare mode disables keychain reads. Invoking a bare agent on an
    /// OAuth-only host will fail with an authentication error.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_core::provider::AgentConfig;
    ///
    /// let config = AgentConfig::new("classify this")
    ///     .bare(true);
    /// ```
    pub fn bare(mut self, enabled: bool) -> Self {
        self.bare = enabled;
        self
    }

    /// Replace the entire disallowed-tools list.
    ///
    /// Maps to `--disallowedTools` on the Claude CLI. This method is available
    /// on **every** typestate variant (including
    /// [`AgentConfig<NoTools, WithSchema>`]) because, unlike
    /// [`allow_tool`](AgentConfig::allow_tool), `disallowed_tools` does not
    /// activate any tool -- it only filters out tools that would otherwise be
    /// loaded by default.
    ///
    /// As such, it is safe to combine with structured output:
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_core::provider::AgentConfig;
    /// use schemars::JsonSchema;
    ///
    /// #[derive(serde::Deserialize, JsonSchema)]
    /// struct Out { ok: bool }
    ///
    /// let config = AgentConfig::new("classify this")
    ///     .disallowed_tools(["Write", "Edit"])
    ///     .output::<Out>();
    /// ```
    pub fn disallowed_tools<I, S>(mut self, tools: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.disallowed_tools = tools.into_iter().map(Into::into).collect();
        self
    }

    /// Set a session ID to resume a previous conversation.
    pub fn resume(mut self, session_id: &str) -> Self {
        self.resume_session_id = Some(session_id.to_string());
        self
    }

    /// Convert to a different typestate by moving all fields.
    ///
    /// Safe because the marker is a zero-sized [`PhantomData`] -- no
    /// runtime data changes.
    fn change_state<T2, S2>(self) -> AgentConfig<T2, S2> {
        AgentConfig {
            system_prompt: self.system_prompt,
            prompt: self.prompt,
            model: self.model,
            allowed_tools: self.allowed_tools,
            disallowed_tools: self.disallowed_tools,
            max_turns: self.max_turns,
            max_budget_usd: self.max_budget_usd,
            working_dir: self.working_dir,
            mcp_config: self.mcp_config,
            strict_mcp_config: self.strict_mcp_config,
            bare: self.bare,
            permission_mode: self.permission_mode,
            json_schema: self.json_schema,
            resume_session_id: self.resume_session_id,
            verbose: self.verbose,
            _marker: PhantomData,
        }
    }
}

// ── allow_tool: only when no schema is set ─────────────────────────

impl<Tools> AgentConfig<Tools, NoSchema> {
    /// Add an allowed tool.
    ///
    /// Can be called multiple times to allow several tools. Returns an
    /// [`AgentConfig<WithTools, NoSchema>`], which **cannot** call
    /// [`output`](AgentConfig::output) or [`output_schema_raw`](AgentConfig::output_schema_raw).
    ///
    /// This restriction exists because Claude CLI has a
    /// [known bug](https://github.com/anthropics/claude-code/issues/18536)
    /// where `--json-schema` combined with `--allowedTools` always returns
    /// `structured_output: null`.
    ///
    /// **Workaround**: use two sequential agent steps -- one with tools to
    /// gather data, then one with `.output::<T>()` to structure the result.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_core::provider::AgentConfig;
    ///
    /// let config = AgentConfig::new("search the web")
    ///     .allow_tool("WebSearch")
    ///     .allow_tool("WebFetch");
    /// ```
    ///
    /// ```compile_fail
    /// use ironflow_core::provider::AgentConfig;
    /// // ERROR: cannot set structured output after adding tools
    /// let _ = AgentConfig::new("x")
    ///     .allow_tool("Read")
    ///     .output_schema_raw(r#"{"type":"object"}"#);
    /// ```
    pub fn allow_tool(mut self, tool: &str) -> AgentConfig<WithTools, NoSchema> {
        self.allowed_tools.push(tool.to_string());
        self.change_state()
    }
}

// ── output: only when no tools are set ─────────────────────────────

impl<Schema> AgentConfig<NoTools, Schema> {
    /// Set structured output from a Rust type implementing [`JsonSchema`].
    ///
    /// The schema is serialized once at build time. When set, the provider
    /// will request typed output conforming to this schema.
    ///
    /// **Important:** structured output requires `max_turns >= 2`.
    ///
    /// Returns an [`AgentConfig<NoTools, WithSchema>`], which **cannot**
    /// call [`allow_tool`](AgentConfig::allow_tool).
    ///
    /// This restriction exists because Claude CLI has a
    /// [known bug](https://github.com/anthropics/claude-code/issues/18536)
    /// where `--json-schema` combined with `--allowedTools` always returns
    /// `structured_output: null`.
    ///
    /// **Workaround**: use two sequential agent steps -- one with tools to
    /// gather data, then one with `.output::<T>()` to structure the result.
    ///
    /// # Known limitations of Claude CLI structured output
    ///
    /// The Claude CLI does not guarantee strict schema conformance for
    /// structured output. The following upstream bugs affect the behavior:
    ///
    /// - **Schema flattening** ([anthropics/claude-agent-sdk-python#502]):
    ///   a schema like `{"type":"object","properties":{"items":{"type":"array",...}}}`
    ///   may return a bare array instead of the wrapper object. The CLI
    ///   non-deterministically flattens schemas with a single array field.
    /// - **Non-deterministic wrapping** ([anthropics/claude-agent-sdk-python#374]):
    ///   the same prompt can produce differently wrapped output across runs.
    /// - **No conformance guarantee** ([anthropics/claude-code#9058]):
    ///   the CLI does not validate output against the provided JSON schema.
    ///
    /// Because of these bugs, ironflow's provider layer applies multiple
    /// fallback strategies when extracting the structured value (see
    /// [`extract_structured_value`](crate::providers::claude::common::extract_structured_value)).
    ///
    /// [anthropics/claude-agent-sdk-python#502]: https://github.com/anthropics/claude-agent-sdk-python/issues/502
    /// [anthropics/claude-agent-sdk-python#374]: https://github.com/anthropics/claude-agent-sdk-python/issues/374
    /// [anthropics/claude-code#9058]: https://github.com/anthropics/claude-code/issues/9058
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_core::provider::AgentConfig;
    /// use schemars::JsonSchema;
    ///
    /// #[derive(serde::Deserialize, JsonSchema)]
    /// struct Labels { labels: Vec<String> }
    ///
    /// let config = AgentConfig::new("classify this text")
    ///     .output::<Labels>();
    /// ```
    ///
    /// ```compile_fail
    /// use ironflow_core::provider::AgentConfig;
    /// use schemars::JsonSchema;
    /// #[derive(serde::Deserialize, JsonSchema)]
    /// struct Out { x: i32 }
    /// // ERROR: cannot add tools after setting structured output
    /// let _ = AgentConfig::new("x").output::<Out>().allow_tool("Read");
    /// ```
    /// # Panics
    ///
    /// Panics if the schema generated by `schemars` cannot be serialized
    /// to JSON. This indicates a bug in the type's `JsonSchema` derive,
    /// not a recoverable runtime error.
    pub fn output<T: JsonSchema>(mut self) -> AgentConfig<NoTools, WithSchema> {
        let schema = schemars::schema_for!(T);
        let serialized = serde_json::to_string(&schema).unwrap_or_else(|e| {
            panic!(
                "failed to serialize JSON schema for {}: {e}",
                std::any::type_name::<T>()
            )
        });
        self.json_schema = Some(serialized);
        self.change_state()
    }

    /// Set structured output from a pre-serialized JSON Schema string.
    ///
    /// Returns an [`AgentConfig<NoTools, WithSchema>`], which **cannot**
    /// call [`allow_tool`](AgentConfig::allow_tool). See [`output`](Self::output)
    /// for the rationale and workaround.
    pub fn output_schema_raw(mut self, schema: &str) -> AgentConfig<NoTools, WithSchema> {
        self.json_schema = Some(schema.to_string());
        self.change_state()
    }
}

// ── From conversions to base type ──────────────────────────────────

impl From<AgentConfig<WithTools, NoSchema>> for AgentConfig {
    fn from(config: AgentConfig<WithTools, NoSchema>) -> Self {
        config.change_state()
    }
}

impl From<AgentConfig<NoTools, WithSchema>> for AgentConfig {
    fn from(config: AgentConfig<NoTools, WithSchema>) -> Self {
        config.change_state()
    }
}

// ── AgentOutput ────────────────────────────────────────────────────

/// Raw output returned by an [`AgentProvider`] after a successful invocation.
///
/// Carries the agent's response value together with usage and billing metadata.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[non_exhaustive]
pub struct AgentOutput {
    /// The agent's response. A plain [`Value::String`] for text mode, or an
    /// arbitrary JSON value when a JSON schema was requested.
    pub value: Value,

    /// Provider-assigned session identifier, useful for resuming conversations.
    pub session_id: Option<String>,

    /// Total cost in USD for this invocation, if reported by the provider.
    pub cost_usd: Option<f64>,

    /// Number of input tokens consumed, if reported.
    pub input_tokens: Option<u64>,

    /// Number of output tokens generated, if reported.
    pub output_tokens: Option<u64>,

    /// The concrete model identifier used (e.g. `"claude-sonnet-4-20250514"`).
    pub model: Option<String>,

    /// Wall-clock duration of the invocation in milliseconds.
    pub duration_ms: u64,

    /// Conversation trace captured when [`AgentConfig::verbose`] is `true`.
    ///
    /// Contains every assistant message and tool call made during the
    /// invocation, in chronological order. `None` when verbose mode is off.
    pub debug_messages: Option<Vec<DebugMessage>>,
}

/// A single assistant turn captured during a verbose invocation.
///
/// Each `DebugMessage` represents one assistant response, which may contain
/// free-form text, tool calls, or both.
///
/// # Examples
///
/// ```no_run
/// use ironflow_core::prelude::*;
///
/// # async fn example() -> Result<(), OperationError> {
/// let provider = ClaudeCodeProvider::new();
/// let result = Agent::new()
///     .prompt("List files in src/")
///     .verbose()
///     .run(&provider)
///     .await?;
///
/// if let Some(messages) = result.debug_messages() {
///     for msg in messages {
///         println!("{msg}");
///     }
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DebugMessage {
    /// Free-form text produced by the assistant in this turn, if any.
    pub text: Option<String>,

    /// Extended thinking blocks produced by the model in this turn.
    ///
    /// Available only when the model emits `thinking` content blocks
    /// (Opus 4.7 adaptive thinking, Claude 3.7+ extended thinking, etc.).
    /// The blocks are joined in arrival order.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub thinking: Option<String>,

    /// `true` when the model emitted a `thinking` content block but the
    /// text was redacted (only a signature is provided).
    ///
    /// Opus 4.7 adaptive thinking and the `display: "omitted"` setting both
    /// produce signature-only thinking blocks: the model proves it reasoned
    /// without exposing the chain of thought. The UI should still show a
    /// badge so the user knows thinking happened.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub thinking_redacted: bool,

    /// Tool calls made by the assistant in this turn.
    pub tool_calls: Vec<DebugToolCall>,

    /// Tool results received from the user/runtime for the preceding tool calls.
    ///
    /// In the Claude stream-json format, tool results come as `"type":"user"`
    /// messages whose content is a list of `tool_result` blocks. We attach
    /// them to the turn that emitted the matching `tool_use` so the timeline
    /// stays compact.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tool_results: Vec<DebugToolResult>,

    /// The model's stop reason for this turn (e.g. `"end_turn"`, `"tool_use"`).
    pub stop_reason: Option<String>,

    /// Input tokens consumed by this turn, if reported.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub input_tokens: Option<u64>,

    /// Output tokens generated by this turn, if reported.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output_tokens: Option<u64>,
}

impl fmt::Display for DebugMessage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(ref thinking) = self.thinking {
            writeln!(f, "[thinking] {thinking}")?;
        } else if self.thinking_redacted {
            writeln!(f, "[thinking redacted]")?;
        }
        if let Some(ref text) = self.text {
            writeln!(f, "[assistant] {text}")?;
        }
        for tc in &self.tool_calls {
            write!(f, "{tc}")?;
        }
        for tr in &self.tool_results {
            write!(f, "{tr}")?;
        }
        Ok(())
    }
}

/// A single tool call captured during a verbose invocation.
///
/// Records the tool name and its input arguments as a raw JSON value.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DebugToolCall {
    /// Stable identifier assigned by the model (`tool_use_id`).
    ///
    /// Used to correlate a call with its subsequent [`DebugToolResult`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,

    /// Name of the tool invoked (e.g. `"Read"`, `"Bash"`, `"Grep"`).
    pub name: String,

    /// Input arguments passed to the tool, as raw JSON.
    pub input: Value,
}

impl fmt::Display for DebugToolCall {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "  [tool_use] {} -> {}", self.name, self.input)
    }
}

/// A tool result returned to the model after a tool call.
///
/// Carries the tool output (any JSON value: string, object, array) and
/// an error flag if the tool failed.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DebugToolResult {
    /// The `tool_use_id` this result answers, matching [`DebugToolCall::id`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tool_use_id: Option<String>,

    /// Raw content returned by the tool.
    pub content: Value,

    /// Whether the tool reported an error.
    #[serde(default)]
    pub is_error: bool,
}

impl fmt::Display for DebugToolResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let kind = if self.is_error {
            "tool_error"
        } else {
            "tool_result"
        };
        writeln!(f, "  [{kind}] {}", self.content)
    }
}

impl AgentOutput {
    /// Create an `AgentOutput` with the given value and sensible defaults.
    pub fn new(value: Value) -> Self {
        Self {
            value,
            session_id: None,
            cost_usd: None,
            input_tokens: None,
            output_tokens: None,
            model: None,
            duration_ms: 0,
            debug_messages: None,
        }
    }
}

// ── Provider trait ─────────────────────────────────────────────────

/// Trait for AI agent backends.
///
/// Implement this trait to provide a custom AI backend for [`Agent`](crate::operations::agent::Agent).
/// The only required method is [`invoke`](AgentProvider::invoke), which takes an
/// [`AgentConfig`] and returns an [`AgentOutput`] (or an [`AgentError`]).
///
/// # Examples
///
/// ```no_run
/// use ironflow_core::provider::{AgentConfig, AgentOutput, AgentProvider, InvokeFuture};
///
/// struct MyProvider;
///
/// impl AgentProvider for MyProvider {
///     fn invoke<'a>(&'a self, config: &'a AgentConfig) -> InvokeFuture<'a> {
///         Box::pin(async move {
///             // Call your custom backend here...
///             todo!()
///         })
///     }
/// }
/// ```
pub trait AgentProvider: Send + Sync {
    /// Execute a single agent invocation with the given configuration.
    ///
    /// # Errors
    ///
    /// Returns [`AgentError`] if the underlying backend process fails,
    /// times out, or produces output that does not match the requested schema.
    fn invoke<'a>(&'a self, config: &'a AgentConfig) -> InvokeFuture<'a>;
}

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

    fn full_config() -> AgentConfig {
        AgentConfig {
            system_prompt: Some("you are helpful".to_string()),
            prompt: "do stuff".to_string(),
            model: Model::OPUS.to_string(),
            allowed_tools: vec!["Read".to_string(), "Write".to_string()],
            disallowed_tools: vec!["Bash".to_string()],
            max_turns: Some(10),
            max_budget_usd: Some(2.5),
            working_dir: Some("/tmp".to_string()),
            mcp_config: Some("{}".to_string()),
            strict_mcp_config: true,
            bare: true,
            permission_mode: PermissionMode::Auto,
            json_schema: Some(r#"{"type":"object"}"#.to_string()),
            resume_session_id: None,
            verbose: false,
            _marker: PhantomData,
        }
    }

    #[test]
    fn agent_config_serialize_deserialize_roundtrip() {
        let config = full_config();
        let json = serde_json::to_string(&config).unwrap();
        let back: AgentConfig = serde_json::from_str(&json).unwrap();

        assert_eq!(back.system_prompt, Some("you are helpful".to_string()));
        assert_eq!(back.prompt, "do stuff");
        assert_eq!(back.allowed_tools, vec!["Read", "Write"]);
        assert_eq!(back.max_turns, Some(10));
        assert_eq!(back.max_budget_usd, Some(2.5));
        assert_eq!(back.working_dir, Some("/tmp".to_string()));
        assert_eq!(back.mcp_config, Some("{}".to_string()));
        assert_eq!(back.json_schema, Some(r#"{"type":"object"}"#.to_string()));
    }

    #[test]
    fn agent_config_with_all_optional_fields_none() {
        let config: AgentConfig = AgentConfig {
            system_prompt: None,
            prompt: "hello".to_string(),
            model: Model::HAIKU.to_string(),
            allowed_tools: vec![],
            disallowed_tools: vec![],
            max_turns: None,
            max_budget_usd: None,
            working_dir: None,
            mcp_config: None,
            strict_mcp_config: false,
            bare: false,
            permission_mode: PermissionMode::Default,
            json_schema: None,
            resume_session_id: None,
            verbose: false,
            _marker: PhantomData,
        };
        let json = serde_json::to_string(&config).unwrap();
        let back: AgentConfig = serde_json::from_str(&json).unwrap();

        assert_eq!(back.system_prompt, None);
        assert_eq!(back.prompt, "hello");
        assert!(back.allowed_tools.is_empty());
        assert_eq!(back.max_turns, None);
        assert_eq!(back.max_budget_usd, None);
        assert_eq!(back.working_dir, None);
        assert_eq!(back.mcp_config, None);
        assert_eq!(back.json_schema, None);
    }

    #[test]
    fn agent_output_serialize_deserialize_roundtrip() {
        let output = AgentOutput {
            value: json!({"key": "value"}),
            session_id: Some("sess-abc".to_string()),
            cost_usd: Some(0.01),
            input_tokens: Some(500),
            output_tokens: Some(200),
            model: Some("claude-sonnet".to_string()),
            duration_ms: 3000,
            debug_messages: None,
        };
        let json = serde_json::to_string(&output).unwrap();
        let back: AgentOutput = serde_json::from_str(&json).unwrap();

        assert_eq!(back.value, json!({"key": "value"}));
        assert_eq!(back.session_id, Some("sess-abc".to_string()));
        assert_eq!(back.cost_usd, Some(0.01));
        assert_eq!(back.input_tokens, Some(500));
        assert_eq!(back.output_tokens, Some(200));
        assert_eq!(back.model, Some("claude-sonnet".to_string()));
        assert_eq!(back.duration_ms, 3000);
    }

    #[test]
    fn agent_config_new_has_correct_defaults() {
        let config = AgentConfig::new("test prompt");
        assert_eq!(config.prompt, "test prompt");
        assert_eq!(config.system_prompt, None);
        assert_eq!(config.model, Model::SONNET);
        assert!(config.allowed_tools.is_empty());
        assert_eq!(config.max_turns, None);
        assert_eq!(config.max_budget_usd, None);
        assert_eq!(config.working_dir, None);
        assert_eq!(config.mcp_config, None);
        assert!(matches!(config.permission_mode, PermissionMode::Default));
        assert_eq!(config.json_schema, None);
        assert_eq!(config.resume_session_id, None);
        assert!(!config.verbose);
    }

    #[test]
    fn agent_output_new_has_correct_defaults() {
        let output = AgentOutput::new(json!("test"));
        assert_eq!(output.value, json!("test"));
        assert_eq!(output.session_id, None);
        assert_eq!(output.cost_usd, None);
        assert_eq!(output.input_tokens, None);
        assert_eq!(output.output_tokens, None);
        assert_eq!(output.model, None);
        assert_eq!(output.duration_ms, 0);
        assert!(output.debug_messages.is_none());
    }

    #[test]
    fn agent_config_resume_session_roundtrip() {
        let mut config = AgentConfig::new("test");
        config.resume_session_id = Some("sess-xyz".to_string());
        let json = serde_json::to_string(&config).unwrap();
        let back: AgentConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(back.resume_session_id, Some("sess-xyz".to_string()));
    }

    #[test]
    fn agent_output_debug_does_not_panic() {
        let output = AgentOutput {
            value: json!(null),
            session_id: None,
            cost_usd: None,
            input_tokens: None,
            output_tokens: None,
            model: None,
            duration_ms: 0,
            debug_messages: None,
        };
        let debug_str = format!("{:?}", output);
        assert!(!debug_str.is_empty());
    }

    #[test]
    fn allow_tool_transitions_to_with_tools() {
        let config = AgentConfig::new("test").allow_tool("Read");
        assert_eq!(config.allowed_tools, vec!["Read"]);

        // Can add more tools
        let config = config.allow_tool("Write");
        assert_eq!(config.allowed_tools, vec!["Read", "Write"]);
    }

    #[test]
    fn output_schema_raw_transitions_to_with_schema() {
        let config = AgentConfig::new("test").output_schema_raw(r#"{"type":"object"}"#);
        assert_eq!(config.json_schema.as_deref(), Some(r#"{"type":"object"}"#));
    }

    #[test]
    fn with_tools_converts_to_base_type() {
        let typed = AgentConfig::new("test").allow_tool("Read");
        let base: AgentConfig = typed.into();
        assert_eq!(base.allowed_tools, vec!["Read"]);
    }

    #[test]
    fn with_schema_converts_to_base_type() {
        let typed = AgentConfig::new("test").output_schema_raw(r#"{"type":"object"}"#);
        let base: AgentConfig = typed.into();
        assert_eq!(base.json_schema.as_deref(), Some(r#"{"type":"object"}"#));
    }

    #[test]
    fn serde_roundtrip_ignores_marker() {
        let config = AgentConfig::new("test").allow_tool("Read");
        let json = serde_json::to_string(&config).unwrap();
        assert!(!json.contains("marker"));

        let back: AgentConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(back.allowed_tools, vec!["Read"]);
    }

    #[test]
    fn bare_defaults_to_false() {
        let config = AgentConfig::new("hello");
        assert!(!config.bare, "bare must default to false");
    }

    #[test]
    fn bare_builder_sets_flag() {
        let config = AgentConfig::new("hello").bare(true);
        assert!(config.bare, "bare(true) must enable the flag");

        let config = config.bare(false);
        assert!(!config.bare, "bare(false) must disable the flag");
    }

    #[test]
    fn bare_serde_default_when_missing() {
        let raw = r#"{"prompt":"hello","model":"sonnet"}"#;
        let config: AgentConfig = serde_json::from_str(raw).unwrap();
        assert!(
            !config.bare,
            "bare must default to false when absent from serialized payload"
        );
    }

    #[test]
    fn bare_serde_roundtrip() {
        let mut config = AgentConfig::new("hello");
        config.bare = true;
        let json = serde_json::to_string(&config).unwrap();
        assert!(
            json.contains("\"bare\":true"),
            "serialized form must contain bare:true, got: {json}"
        );

        let back: AgentConfig = serde_json::from_str(&json).unwrap();
        assert!(back.bare, "bare must survive a serde roundtrip");
    }

    #[test]
    fn disallowed_tools_defaults_to_empty() {
        let config = AgentConfig::new("hello");
        assert!(
            config.disallowed_tools.is_empty(),
            "disallowed_tools must default to empty"
        );
    }

    #[test]
    fn disallowed_tools_builder_replaces_list() {
        let config = AgentConfig::new("hello").disallowed_tools(["Write", "Edit"]);
        assert_eq!(config.disallowed_tools, vec!["Write", "Edit"]);

        // Subsequent call fully replaces the list.
        let config = config.disallowed_tools(["Bash"]);
        assert_eq!(config.disallowed_tools, vec!["Bash"]);

        // Empty input clears the list.
        let config = config.disallowed_tools(std::iter::empty::<String>());
        assert!(config.disallowed_tools.is_empty());
    }

    #[test]
    fn disallowed_tools_compatible_with_output() {
        #[derive(serde::Deserialize, JsonSchema)]
        #[allow(dead_code)]
        struct Out {
            ok: bool,
        }

        // Typestate compile check: .disallowed_tools(...) must be callable
        // before AND after .output::<T>() because it lives on
        // impl<Tools, Schema>, not impl<Tools, NoSchema>.
        let before: AgentConfig<NoTools, WithSchema> = AgentConfig::new("classify")
            .disallowed_tools(["Write", "Edit"])
            .output::<Out>();
        assert_eq!(before.disallowed_tools, vec!["Write", "Edit"]);
        assert!(before.json_schema.is_some());

        let after: AgentConfig<NoTools, WithSchema> = AgentConfig::new("classify")
            .output::<Out>()
            .disallowed_tools(["Write"]);
        assert_eq!(after.disallowed_tools, vec!["Write"]);
        assert!(after.json_schema.is_some());
    }

    #[test]
    fn disallowed_tools_serde_default_when_missing() {
        let raw = r#"{"prompt":"hello","model":"sonnet"}"#;
        let config: AgentConfig = serde_json::from_str(raw).unwrap();
        assert!(
            config.disallowed_tools.is_empty(),
            "disallowed_tools must default to empty when absent from serialized payload"
        );
    }

    #[test]
    fn disallowed_tools_serde_roundtrip() {
        let config = AgentConfig::new("hello").disallowed_tools(["Write", "Edit"]);
        let json = serde_json::to_string(&config).unwrap();
        assert!(
            json.contains("\"disallowed_tools\":[\"Write\",\"Edit\"]"),
            "serialized form must contain the disallowed_tools array, got: {json}"
        );

        let back: AgentConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(back.disallowed_tools, vec!["Write", "Edit"]);
    }
}