localharness 0.77.0

Agents that own themselves: one Rust crate that's both an agent SDK (streaming, tools, hooks, policies, triggers, MCP) and a wallet-owning, self-sovereign agent that runs in the browser.
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
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
//! Layer-1 `Agent` facade.
//!
//! Mirrors the Python `Agent` class: a single high-level handle that owns
//! the connection, hook runner, tool runner, trigger runner, and a
//! background dispatcher that routes custom-tool calls through the hooks /
//! policies / runner pipeline back to the harness.
//!
//! Lifecycle:
//!
//! ```rust,ignore
//! let cfg = GeminiAgentConfig::new(api_key).with_system_instructions("You are helpful.");
//! let agent = Agent::start_gemini(cfg).await?;
//! let response = agent.chat("hello").await?;
//! println!("{}", response.text().await?);
//! agent.shutdown().await?;
//! ```

use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use futures_util::stream::StreamExt;
#[cfg(not(target_arch = "wasm32"))]
use tokio::task::JoinHandle;
use tracing::{debug, warn};

use crate::backends::gemini::{GeminiBackendConfig, GeminiConnectionStrategy, GeminiRunners};
use crate::backends::mock::{MockConnectionStrategy, MockRunners};
#[cfg(feature = "anthropic")]
use crate::backends::anthropic::{
    AnthropicBackendConfig, AnthropicConnectionStrategy, AnthropicRunners,
};
#[cfg(feature = "openai")]
use crate::backends::openai::{OpenAiBackendConfig, OpenAiConnectionStrategy, OpenAiRunners};
#[cfg(feature = "local")]
use crate::backends::local::connection::{
    LocalBackendConfig, LocalConnectionStrategy, LocalRunners,
};
use crate::connections::{Connection, ConnectionStrategy};
use crate::content::Content;
use crate::conversation::{ChatResponse, Conversation};
use crate::error::{Error, Result};
use crate::hooks::{HookRunner, SessionContext};
use crate::policy::{self, Policy};
use crate::tools::{Tool, ToolContext, ToolRunner};
use crate::triggers::{Trigger, TriggerRunner};
#[cfg(feature = "native")]
use crate::backends::mcp::McpBridge;
#[cfg(feature = "native")]
use crate::types::McpServerConfig;
use crate::types::{
    BuiltinTool, CapabilitiesConfig, StepStatus, SystemInstructions, ToolCall,
};

// =============================================================================
// Configuration
// =============================================================================

/// Backend-agnostic agent configuration (tools, policies, triggers, workspaces).
#[derive(Default)]
#[non_exhaustive]
#[must_use]
pub struct AgentConfig {
    /// Optional system-level instructions for the model.
    pub system_instructions: Option<SystemInstructions>,
    /// Which built-in tools are enabled or disabled.
    pub capabilities: CapabilitiesConfig,
    /// Custom tools registered into the agent.
    pub tools: Vec<Arc<dyn Tool>>,
    /// Safety policies governing tool execution.
    pub policies: Vec<Policy>,
    /// Background triggers that fire messages into the agent.
    pub triggers: Vec<Arc<dyn Trigger>>,
    /// Filesystem workspace roots for path-containment policies.
    pub workspaces: Vec<PathBuf>,
    /// MCP server configurations (native only).
    #[cfg(feature = "native")]
    pub mcp_servers: Vec<McpServerConfig>,
    /// Resume an existing conversation by ID.
    pub conversation_id: Option<String>,
    /// JSON schema string for structured output via the `finish` tool.
    pub response_schema: Option<String>,
    /// Custom pre-tool-call decide hooks, registered alongside the policy
    /// enforcer. First deny wins — use for cross-cutting guards a static
    /// `Policy` can't express (e.g. duplicate-action suppression).
    pub pre_tool_hooks: Vec<Arc<dyn crate::hooks::PreToolCallDecideHook>>,
    /// Custom post-tool-call inspect hooks, run after each call's result is
    /// known. Inspect-only (cannot block) — use to observe outcomes or undo a
    /// pre-hook's optimistic bookkeeping on failure (e.g. the dedup cleanup).
    pub post_tool_hooks: Vec<Arc<dyn crate::hooks::PostToolCallHook>>,
}

impl AgentConfig {
    /// Create an empty agent configuration with defaults.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the system instructions for the model.
    pub fn with_system_instructions(mut self, instr: impl Into<SystemInstructions>) -> Self {
        self.system_instructions = Some(instr.into());
        self
    }

    /// Configure which built-in tools are enabled.
    pub fn with_capabilities(mut self, cap: CapabilitiesConfig) -> Self {
        self.capabilities = cap;
        self
    }

    /// Register a custom tool.
    pub fn with_tool(mut self, tool: Arc<dyn Tool>) -> Self {
        self.tools.push(tool);
        self
    }

    /// Set the safety policies for tool execution.
    pub fn with_policies(mut self, policies: Vec<Policy>) -> Self {
        self.policies = policies;
        self
    }

    /// Register a custom pre-tool-call decide hook (runs alongside the
    /// policy enforcer; first deny wins). For cross-cutting guards a static
    /// `Policy` can't express — e.g. duplicate-action suppression.
    pub fn with_pre_tool_hook(
        mut self,
        hook: Arc<dyn crate::hooks::PreToolCallDecideHook>,
    ) -> Self {
        self.pre_tool_hooks.push(hook);
        self
    }

    /// Register a custom post-tool-call inspect hook (runs after each call's
    /// result is known; inspect-only). Pairs with a pre-tool hook to undo
    /// optimistic bookkeeping on failure — e.g. reverting a dedup hash insert.
    pub fn with_post_tool_hook(
        mut self,
        hook: Arc<dyn crate::hooks::PostToolCallHook>,
    ) -> Self {
        self.post_tool_hooks.push(hook);
        self
    }

    /// Add a workspace root for path-containment enforcement.
    pub fn with_workspace(mut self, ws: impl Into<PathBuf>) -> Self {
        self.workspaces.push(ws.into());
        self
    }

    /// Register a background trigger.
    pub fn with_trigger(mut self, trigger: Arc<dyn Trigger>) -> Self {
        self.triggers.push(trigger);
        self
    }

    /// Add an MCP server to connect at startup (native only).
    #[cfg(feature = "native")]
    pub fn with_mcp_server(mut self, server: McpServerConfig) -> Self {
        self.mcp_servers.push(server);
        self
    }
}

/// Generates the [`AgentConfig`]-forwarding builder methods that are VERBATIM
/// identical across the per-backend config structs (each owns a
/// `pub agent: AgentConfig` field). The base set (capabilities / tool /
/// policies / pre- and post-tool hooks) is always emitted; `workspace`,
/// `trigger`, and `mcp` are opted into per config so each struct keeps exactly
/// the surface it had. Backend-specific builders (`with_model`,
/// `with_system_instructions`, `resume`, …) stay hand-written — they encode
/// real divergence.
macro_rules! forward_agent_config_builders {
    ($($extra:ident),* $(,)?) => {
        /// Configure which built-in tools are enabled.
        pub fn with_capabilities(mut self, cap: CapabilitiesConfig) -> Self {
            self.agent = self.agent.with_capabilities(cap);
            self
        }

        /// Register a custom tool.
        pub fn with_tool(mut self, tool: Arc<dyn Tool>) -> Self {
            self.agent = self.agent.with_tool(tool);
            self
        }

        /// Set the safety policies for tool execution.
        pub fn with_policies(mut self, policies: Vec<Policy>) -> Self {
            self.agent = self.agent.with_policies(policies);
            self
        }

        /// Register a custom pre-tool-call decide hook (see
        /// [`AgentConfig::with_pre_tool_hook`]).
        pub fn with_pre_tool_hook(
            mut self,
            hook: Arc<dyn crate::hooks::PreToolCallDecideHook>,
        ) -> Self {
            self.agent = self.agent.with_pre_tool_hook(hook);
            self
        }

        /// Register a custom post-tool-call inspect hook (see
        /// [`AgentConfig::with_post_tool_hook`]).
        pub fn with_post_tool_hook(
            mut self,
            hook: Arc<dyn crate::hooks::PostToolCallHook>,
        ) -> Self {
            self.agent = self.agent.with_post_tool_hook(hook);
            self
        }

        $(forward_agent_config_builders!(@extra $extra);)*
    };
    (@extra workspace) => {
        /// Add a workspace root for path-containment enforcement.
        pub fn with_workspace(mut self, ws: impl Into<PathBuf>) -> Self {
            self.agent = self.agent.with_workspace(ws);
            self
        }
    };
    (@extra trigger) => {
        /// Register a background trigger.
        pub fn with_trigger(mut self, trigger: Arc<dyn Trigger>) -> Self {
            self.agent = self.agent.with_trigger(trigger);
            self
        }
    };
    (@extra mcp) => {
        /// Add an MCP server to connect at startup (native only).
        #[cfg(feature = "native")]
        pub fn with_mcp_server(mut self, server: McpServerConfig) -> Self {
            self.agent = self.agent.with_mcp_server(server);
            self
        }
    };
}

/// Configuration for the Rust-native Gemini backend.
///
/// Pairs the generic `AgentConfig` (hooks, tools, policies, triggers)
/// with `GeminiBackendConfig` (model, API key, thinking, etc.).
#[non_exhaustive]
#[must_use]
pub struct GeminiAgentConfig {
    /// Backend-agnostic settings (tools, policies, triggers).
    pub agent: AgentConfig,
    /// Gemini-specific settings (model, API key, thinking).
    pub gemini: GeminiBackendConfig,
    /// Opaque history bytes from a previous session, as returned by
    /// `Agent::history_bytes()`. Applied to the new connection
    /// immediately after `connect()`. Empty / missing means "start fresh."
    pub initial_history: Option<Vec<u8>>,
}

impl GeminiAgentConfig {
    /// Create a new Gemini agent configuration with the given API key.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use localharness::{GeminiAgentConfig, policy};
    ///
    /// // Builders chain; each returns `Self`. A deny-by-default policy turns the
    /// // agent into an allowlist (only the named tools run), and `with_workspace`
    /// // sandboxes the filesystem builtins to that directory.
    /// let cfg = GeminiAgentConfig::new("my-api-key")
    ///     .with_model("gemini-3.6-flash")
    ///     .with_system_instructions("You are a careful coding assistant.")
    ///     .with_workspace("/path/to/project")
    ///     .with_policies(vec![
    ///         policy::deny_all(),
    ///         policy::Policy::allow("view_file"),
    ///     ]);
    /// # let _ = cfg;
    /// ```
    pub fn new(api_key: impl Into<String>) -> Self {
        Self {
            agent: AgentConfig::default(),
            gemini: GeminiBackendConfig::new(api_key),
            initial_history: None,
        }
    }

    /// Seed the new connection with previously-saved history bytes
    /// (obtained from `Agent::history_bytes()`). If the bytes fail to
    /// parse at start time, `Agent::start_gemini` returns an error.
    pub fn with_history_bytes(mut self, bytes: Vec<u8>) -> Self {
        self.initial_history = Some(bytes);
        self
    }

    /// Override the default Gemini model ID.
    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.gemini = self.gemini.with_model(model);
        self
    }

    /// Set the system instructions for the model.
    pub fn with_system_instructions(mut self, instr: impl Into<SystemInstructions>) -> Self {
        let instr = instr.into();
        self.gemini = self.gemini.with_system_instructions(instr.clone());
        self.agent = self.agent.with_system_instructions(instr);
        self
    }

    /// Enable extended thinking at the given level.
    pub fn with_thinking(mut self, level: crate::types::ThinkingLevel) -> Self {
        self.gemini = self.gemini.with_thinking(level);
        self
    }

    /// Cap output tokens (`maxOutputTokens`) per model call. Set this high
    /// enough that a hard task can both reason and emit a final answer in one
    /// call; an unset/low cap lets dynamic thinking starve the text on a 3.x
    /// model, ending the turn `MAX_TOKENS` with no output.
    pub fn with_max_output_tokens(mut self, max: u32) -> Self {
        self.gemini = self.gemini.with_max_output_tokens(max);
        self
    }

    /// Set the sampling temperature (`generationConfig.temperature`). A low
    /// value (e.g. 0.2) favors first-try-valid code/edits; composes with
    /// extended thinking.
    pub fn with_temperature(mut self, t: f32) -> Self {
        self.gemini = self.gemini.with_temperature(t);
        self
    }

    /// Set a JSON schema for structured output via the `finish` tool.
    pub fn with_response_schema(mut self, schema: impl Into<String>) -> Self {
        let s = schema.into();
        self.gemini = self.gemini.with_response_schema(s.clone());
        self.agent.response_schema = Some(s);
        self
    }

    /// Route requests through an alternate base URL (e.g. the
    /// localharness credit proxy) instead of Google's endpoint. In
    /// credits mode the api key carries the proxy auth token.
    pub fn with_base_url(mut self, url: url::Url) -> Self {
        self.gemini = self.gemini.with_base_url(url);
        self
    }

    /// Mint a fresh auth credential for EVERY request instead of reusing
    /// the static api key (which becomes a fallback). Long-lived sessions
    /// against the credit proxy need this — its signed tokens expire after
    /// 5 minutes, so a session-baked token goes stale mid-conversation.
    pub fn with_auth_provider(mut self, provider: crate::backends::KeyProvider) -> Self {
        self.gemini.api_key_provider = Some(crate::backends::AuthTokenProvider(provider));
        self
    }

    /// Attach an extra header to every outbound request (e.g. an `X-PAYMENT`
    /// x402 authorization carried alongside the proxy auth token). No-op when
    /// unset.
    pub fn with_extra_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.gemini = self.gemini.with_extra_header(name, value);
        self
    }

    /// Plug in a custom [`Filesystem`] impl for the 8 fs built-ins.
    /// Without this, native builds use `NativeFilesystem`; wasm builds
    /// have no filesystem and the fs builtins skip registration.
    ///
    /// [`Filesystem`]: crate::filesystem::Filesystem
    pub fn with_filesystem(mut self, fs: crate::filesystem::SharedFilesystem) -> Self {
        self.gemini = self.gemini.with_filesystem(fs);
        self
    }

    forward_agent_config_builders!(workspace, trigger, mcp);

    /// Resume an existing conversation by its ID.
    pub fn resume(mut self, conversation_id: impl Into<String>) -> Self {
        let id = conversation_id.into();
        self.gemini.conversation_id = Some(id.clone());
        self.agent.conversation_id = Some(id);
        self
    }
}

// =============================================================================
// Mock agent config (always available — offline testing)
// =============================================================================

/// Configuration for the deterministic, offline mock backend.
///
/// Pairs the generic [`AgentConfig`] (hooks, tools, policies, triggers) with a
/// scripted [`MockConnectionStrategy`] so an [`Agent`] can be driven entirely
/// offline — no network, no API key, no LLM. The parallel of
/// [`GeminiAgentConfig`], always available (no feature flag). Build the
/// strategy with [`MockConnection::builder`].
///
/// [`MockConnectionStrategy`]: crate::backends::mock::MockConnectionStrategy
/// [`MockConnection::builder`]: crate::backends::mock::MockConnection::builder
///
/// # Examples
///
/// ```rust,no_run
/// use localharness::{Agent, policy};
/// use localharness::backends::mock::{MockAgentConfig, MockConnection};
///
/// # async fn run() -> localharness::Result<()> {
/// let backend = MockConnection::builder()
///     .turn(|t| t.text("the scripted answer"))
///     .build();
/// let agent = Agent::start_mock(MockAgentConfig::new(backend)).await?;
/// assert_eq!(agent.chat("anything").await?.text().await?, "the scripted answer");
/// agent.shutdown().await?;
/// # Ok(())
/// # }
/// ```
#[non_exhaustive]
#[must_use]
pub struct MockAgentConfig {
    /// Backend-agnostic settings (tools, policies, triggers).
    pub agent: AgentConfig,
    /// The scripted mock backend strategy.
    pub mock: MockConnectionStrategy,
}

impl MockAgentConfig {
    /// Create a mock agent configuration from a scripted backend strategy
    /// (built via [`MockConnection::builder`]).
    ///
    /// [`MockConnection::builder`]: crate::backends::mock::MockConnection::builder
    pub fn new(mock: MockConnectionStrategy) -> Self {
        Self {
            agent: AgentConfig::default(),
            mock,
        }
    }

    /// Set the system instructions (recorded on the agent config; the mock
    /// ignores them — its turns are scripted, not generated).
    pub fn with_system_instructions(mut self, instr: impl Into<SystemInstructions>) -> Self {
        self.agent = self.agent.with_system_instructions(instr);
        self
    }

    forward_agent_config_builders!(workspace, trigger);
}

// =============================================================================
// Anthropic agent config (feature = "anthropic")
// =============================================================================

/// Configuration for the Rust-native Anthropic (Claude Messages) backend.
///
/// Pairs the generic `AgentConfig` (hooks, tools, policies, triggers) with
/// `AnthropicBackendConfig` (model, API key, thinking, max_tokens). The
/// parallel of [`GeminiAgentConfig`]; additive — `start_gemini` and the
/// neutral `AgentConfig` are untouched.
#[cfg(feature = "anthropic")]
#[non_exhaustive]
#[must_use]
pub struct AnthropicAgentConfig {
    /// Backend-agnostic settings (tools, policies, triggers).
    pub agent: AgentConfig,
    /// Anthropic-specific settings (model, API key, thinking, max_tokens).
    pub anthropic: AnthropicBackendConfig,
    /// Opaque history bytes from a previous session
    /// (`Agent::history_bytes()`), applied immediately after `connect()`.
    pub initial_history: Option<Vec<u8>>,
}

#[cfg(feature = "anthropic")]
impl AnthropicAgentConfig {
    /// Create a new Anthropic agent configuration with the given API key
    /// (BYOK — talks directly to `api.anthropic.com`).
    pub fn new(api_key: impl Into<String>) -> Self {
        Self {
            agent: AgentConfig::default(),
            anthropic: AnthropicBackendConfig::new(api_key),
            initial_history: None,
        }
    }

    /// Seed the new connection with previously-saved history bytes.
    pub fn with_history_bytes(mut self, bytes: Vec<u8>) -> Self {
        self.initial_history = Some(bytes);
        self
    }

    /// Override the Anthropic model ID (e.g. sonnet / opus).
    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.anthropic = self.anthropic.with_model(model);
        self
    }

    /// Set the system instructions for the model.
    pub fn with_system_instructions(mut self, instr: impl Into<SystemInstructions>) -> Self {
        let instr = instr.into();
        self.anthropic = self.anthropic.with_system_instructions(instr.clone());
        self.agent = self.agent.with_system_instructions(instr);
        self
    }

    /// Enable extended thinking at the given level.
    pub fn with_thinking(mut self, level: crate::types::ThinkingLevel) -> Self {
        self.anthropic = self.anthropic.with_thinking(level);
        self
    }

    /// Set the sampling temperature.
    pub fn with_temperature(mut self, t: f32) -> Self {
        self.anthropic = self.anthropic.with_temperature(t);
        self
    }

    /// Set `max_tokens` for the response (Anthropic requires it; defaults
    /// to 8192 otherwise).
    pub fn with_max_tokens(mut self, n: u32) -> Self {
        self.anthropic = self.anthropic.with_max_tokens(n);
        self
    }

    /// Route requests through an alternate base URL (future credit proxy).
    pub fn with_base_url(mut self, url: url::Url) -> Self {
        self.anthropic = self.anthropic.with_base_url(url);
        self
    }

    /// Mint a fresh auth credential for EVERY request instead of reusing
    /// the static api key (which becomes a fallback) — see
    /// [`GeminiAgentConfig::with_auth_provider`].
    pub fn with_auth_provider(mut self, provider: crate::backends::KeyProvider) -> Self {
        self.anthropic.api_key_provider = Some(crate::backends::AuthTokenProvider(provider));
        self
    }

    /// Attach an extra header to every outbound request (e.g. an `X-PAYMENT`
    /// x402 authorization carried alongside the proxy auth token). No-op when
    /// unset.
    pub fn with_extra_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.anthropic = self.anthropic.with_extra_header(name, value);
        self
    }

    /// Plug in a custom [`Filesystem`] impl for the fs built-ins.
    ///
    /// [`Filesystem`]: crate::filesystem::Filesystem
    pub fn with_filesystem(mut self, fs: crate::filesystem::SharedFilesystem) -> Self {
        self.anthropic = self.anthropic.with_filesystem(fs);
        self
    }

    forward_agent_config_builders!(workspace, trigger, mcp);

    /// Resume an existing conversation by its ID.
    pub fn resume(mut self, conversation_id: impl Into<String>) -> Self {
        let id = conversation_id.into();
        self.anthropic.conversation_id = Some(id.clone());
        self.agent.conversation_id = Some(id);
        self
    }
}

// =============================================================================
// OpenAI agent config (feature = "openai")
// =============================================================================

/// Configuration for the Rust-native OpenAI (Chat Completions) backend.
///
/// Pairs the generic `AgentConfig` (hooks, tools, policies, triggers) with
/// `OpenAiBackendConfig` (model, API key, temperature, max_tokens). The
/// parallel of [`GeminiAgentConfig`] / [`AnthropicAgentConfig`]; additive —
/// `start_gemini` and the neutral `AgentConfig` are untouched.
#[cfg(feature = "openai")]
#[non_exhaustive]
#[must_use]
pub struct OpenAiAgentConfig {
    /// Backend-agnostic settings (tools, policies, triggers).
    pub agent: AgentConfig,
    /// OpenAI-specific settings (model, API key, temperature, max_tokens).
    pub openai: OpenAiBackendConfig,
    /// Opaque history bytes from a previous session
    /// (`Agent::history_bytes()`), applied immediately after `connect()`.
    pub initial_history: Option<Vec<u8>>,
}

#[cfg(feature = "openai")]
impl OpenAiAgentConfig {
    /// Create a new OpenAI agent configuration with the given API key
    /// (BYOK — talks directly to `api.openai.com`).
    pub fn new(api_key: impl Into<String>) -> Self {
        Self {
            agent: AgentConfig::default(),
            openai: OpenAiBackendConfig::new(api_key),
            initial_history: None,
        }
    }

    /// Seed the new connection with previously-saved history bytes.
    pub fn with_history_bytes(mut self, bytes: Vec<u8>) -> Self {
        self.initial_history = Some(bytes);
        self
    }

    /// Override the OpenAI model ID (e.g. `gpt-5-mini` / `gpt-5-pro` / any
    /// other string — model ids are NOT validated).
    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.openai = self.openai.with_model(model);
        self
    }

    /// Set the system instructions for the model.
    pub fn with_system_instructions(mut self, instr: impl Into<SystemInstructions>) -> Self {
        let instr = instr.into();
        self.openai = self.openai.with_system_instructions(instr.clone());
        self.agent = self.agent.with_system_instructions(instr);
        self
    }

    /// Set the sampling temperature.
    pub fn with_temperature(mut self, t: f32) -> Self {
        self.openai = self.openai.with_temperature(t);
        self
    }

    /// Set `max_completion_tokens` for the response.
    pub fn with_max_tokens(mut self, n: u32) -> Self {
        self.openai = self.openai.with_max_tokens(n);
        self
    }

    /// Route requests through an alternate base URL (the credit proxy, which
    /// already forwards `/v1/chat/completions`).
    pub fn with_base_url(mut self, url: url::Url) -> Self {
        self.openai = self.openai.with_base_url(url);
        self
    }

    /// Mint a fresh auth credential for EVERY request instead of reusing the
    /// static api key (which becomes a fallback) — see
    /// [`GeminiAgentConfig::with_auth_provider`].
    pub fn with_auth_provider(mut self, provider: crate::backends::KeyProvider) -> Self {
        self.openai.api_key_provider = Some(crate::backends::AuthTokenProvider(provider));
        self
    }

    /// Plug in a custom [`Filesystem`] impl for the fs built-ins.
    ///
    /// [`Filesystem`]: crate::filesystem::Filesystem
    pub fn with_filesystem(mut self, fs: crate::filesystem::SharedFilesystem) -> Self {
        self.openai = self.openai.with_filesystem(fs);
        self
    }

    forward_agent_config_builders!(workspace, trigger, mcp);

    /// Resume an existing conversation by its ID.
    pub fn resume(mut self, conversation_id: impl Into<String>) -> Self {
        let id = conversation_id.into();
        self.openai.conversation_id = Some(id.clone());
        self.agent.conversation_id = Some(id);
        self
    }
}

// =============================================================================
// Local agent config (feature = "local")
// =============================================================================

/// Configuration for the in-browser local (Gemma 3 270M / Burn-wgpu) backend.
///
/// Pairs the generic `AgentConfig` with [`LocalBackendConfig`]. The parallel of
/// [`GeminiAgentConfig`] / [`AnthropicAgentConfig`]; additive and feature-gated.
/// There is no API key — the model runs fully on-device; weights are read from
/// the supplied [`Filesystem`] (OPFS in the browser).
///
/// [`Filesystem`]: crate::filesystem::Filesystem
#[cfg(feature = "local")]
#[non_exhaustive]
#[must_use]
pub struct LocalAgentConfig {
    /// Backend-agnostic settings (tools, policies, triggers).
    pub agent: AgentConfig,
    /// Local-backend settings (model label, OPFS paths, filesystem).
    pub local: LocalBackendConfig,
    /// Opaque history bytes from a previous session, applied after `connect()`.
    pub initial_history: Option<Vec<u8>>,
}

#[cfg(feature = "local")]
impl LocalAgentConfig {
    /// Create a new local agent configuration for the given model label.
    pub fn new(model: impl Into<String>) -> Self {
        Self {
            agent: AgentConfig::default(),
            local: LocalBackendConfig::new(model),
            initial_history: None,
        }
    }

    /// Seed the new connection with previously-saved history bytes.
    pub fn with_history_bytes(mut self, bytes: Vec<u8>) -> Self {
        self.initial_history = Some(bytes);
        self
    }

    /// Set the model id label.
    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.local = self.local.with_model(model);
        self
    }

    /// Set the system instructions for the model.
    pub fn with_system_instructions(mut self, instr: impl Into<SystemInstructions>) -> Self {
        let instr = instr.into();
        self.local = self.local.with_system_instructions(instr.clone());
        self.agent = self.agent.with_system_instructions(instr);
        self
    }

    /// Plug in the [`Filesystem`] the weights/tokenizer are read from.
    ///
    /// [`Filesystem`]: crate::filesystem::Filesystem
    pub fn with_filesystem(mut self, fs: crate::filesystem::SharedFilesystem) -> Self {
        self.local = self.local.with_filesystem(fs);
        self
    }

    // NOTE: `with_capabilities` used to ALSO copy into `self.local` here; the
    // backend copy now happens once at the `Agent::start_local` bootstrap.
    forward_agent_config_builders!();

    /// Resume an existing conversation by its ID.
    pub fn resume(mut self, conversation_id: impl Into<String>) -> Self {
        let id = conversation_id.into();
        self.local.conversation_id = Some(id.clone());
        self.agent.conversation_id = Some(id);
        self
    }
}

// =============================================================================
// Agent
// =============================================================================

/// High-level agent handle: connect, chat, shutdown.
///
/// Owns the connection, runners, and background dispatcher. Drop aborts
/// background tasks; call [`Agent::shutdown`] for a clean teardown.
///
/// # Examples
///
/// ```rust,no_run
/// use localharness::{Agent, GeminiAgentConfig};
///
/// # async fn run() -> localharness::Result<()> {
/// let agent = Agent::start_gemini(
///     GeminiAgentConfig::new("key")
///         .with_system_instructions("Be concise."),
/// ).await?;
/// let resp = agent.chat("Hello").await?;
/// println!("{}", resp.text().await?);
/// agent.shutdown().await?;
/// # Ok(())
/// # }
/// ```
pub struct Agent {
    conversation: Conversation,
    /// The live backend session. The session surface (`history_bytes`,
    /// `compact`, `transcript`, per-turn overrides, …) rides the
    /// [`Connection`] trait, so no typed per-backend handle is needed.
    connection: Arc<dyn Connection>,
    hook_runner: Arc<HookRunner>,
    tool_runner: Arc<ToolRunner>,
    trigger_runner: Option<Arc<TriggerRunner>>,
    #[cfg(feature = "native")]
    mcp_bridge: Option<Arc<McpBridge>>,
    session_ctx: SessionContext,
    #[cfg(not(target_arch = "wasm32"))]
    dispatcher: parking_lot::Mutex<Option<JoinHandle<()>>>,
    shutdown_flag: Arc<AtomicBool>,
}

impl Agent {
    /// Start an `Agent` backed by the Rust-native Gemini runtime.
    pub async fn start_gemini(mut config: GeminiAgentConfig) -> Result<Self> {
        Self::bootstrap(&mut config.agent, Some(&mut config.gemini.capabilities))?;
        // The Gemini strategy is bound to the agent's runners so that
        // function-call dispatch can run through hooks + policies +
        // tool_runner without round-tripping through `send_tool_results`.
        let gemini_config = config.gemini;
        let initial_history = config.initial_history.take();
        let agent = Self::start_with_factory(config.agent, move |hooks, tools, ctx| {
            GeminiConnectionStrategy::new(gemini_config).with_runners(GeminiRunners {
                tool_runner: Some(tools),
                hook_runner: Some(hooks),
                session_ctx: Some(ctx),
            })
        })
        .await?;
        if let Some(bytes) = initial_history {
            agent.connection.set_history_bytes(&bytes)?;
        }
        Ok(agent)
    }

    /// Start an `Agent` backed by the deterministic, offline [mock backend].
    ///
    /// The agent runs entirely offline — no network, no API key, no LLM. The
    /// model's turns are scripted via [`MockConnection::builder`]; scripted
    /// tool calls dispatch inline through the SAME hooks + policies + tool
    /// runner the live backends use, so this exercises real agent logic (the
    /// tool loop) against a deterministic model. Always available (no feature
    /// flag) — built for unit-testing agents.
    ///
    /// [mock backend]: crate::backends::mock
    /// [`MockConnection::builder`]: crate::backends::mock::MockConnection::builder
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use localharness::{Agent, policy};
    /// use localharness::backends::mock::{MockAgentConfig, MockConnection};
    ///
    /// # async fn run() -> localharness::Result<()> {
    /// let backend = MockConnection::builder()
    ///     .turn(|t| t.text("hello from the mock"))
    ///     .build();
    /// let agent = Agent::start_mock(MockAgentConfig::new(backend)).await?;
    /// assert_eq!(agent.chat("hi").await?.text().await?, "hello from the mock");
    /// agent.shutdown().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn start_mock(mut config: MockAgentConfig) -> Result<Self> {
        Self::bootstrap(&mut config.agent, None)?;
        let mock = config.mock;
        Self::start_with_factory(config.agent, move |hooks, tools, ctx| {
            mock.with_runners(MockRunners {
                tool_runner: Some(tools),
                hook_runner: Some(hooks),
                session_ctx: Some(ctx),
            })
        })
        .await
    }

    /// Start an `Agent` backed by the Rust-native Anthropic (Claude Messages)
    /// runtime. Parallels [`Agent::start_gemini`]; additive and
    /// non-breaking. BYOK — `AnthropicAgentConfig::new(key)` talks directly
    /// to `api.anthropic.com`.
    #[cfg(feature = "anthropic")]
    pub async fn start_anthropic(mut config: AnthropicAgentConfig) -> Result<Self> {
        Self::bootstrap(&mut config.agent, Some(&mut config.anthropic.capabilities))?;
        let anthropic_config = config.anthropic;
        let initial_history = config.initial_history.take();
        let agent = Self::start_with_factory(config.agent, move |hooks, tools, ctx| {
            AnthropicConnectionStrategy::new(anthropic_config).with_runners(AnthropicRunners {
                tool_runner: Some(tools),
                hook_runner: Some(hooks),
                session_ctx: Some(ctx),
            })
        })
        .await?;
        if let Some(bytes) = initial_history {
            agent.connection.set_history_bytes(&bytes)?;
        }
        Ok(agent)
    }

    /// Start an `Agent` backed by the Rust-native OpenAI (Chat Completions)
    /// runtime. Parallels [`Agent::start_anthropic`]; additive and
    /// non-breaking. BYOK — `OpenAiAgentConfig::new(key)` talks directly to
    /// `api.openai.com`; `with_base_url` routes through the credit proxy.
    #[cfg(feature = "openai")]
    pub async fn start_openai(mut config: OpenAiAgentConfig) -> Result<Self> {
        Self::bootstrap(&mut config.agent, Some(&mut config.openai.capabilities))?;
        let openai_config = config.openai;
        let initial_history = config.initial_history.take();
        let agent = Self::start_with_factory(config.agent, move |hooks, tools, ctx| {
            OpenAiConnectionStrategy::new(openai_config).with_runners(OpenAiRunners {
                tool_runner: Some(tools),
                hook_runner: Some(hooks),
                session_ctx: Some(ctx),
            })
        })
        .await?;
        if let Some(bytes) = initial_history {
            agent.connection.set_history_bytes(&bytes)?;
        }
        Ok(agent)
    }

    /// Start an `Agent` backed by the in-browser local (Gemma 3 270M / Burn-wgpu)
    /// runtime. Parallels [`Agent::start_gemini`]; additive and non-breaking. No
    /// API key — the model runs fully on-device, reading weights from the
    /// supplied filesystem (OPFS in the browser).
    #[cfg(feature = "local")]
    pub async fn start_local(mut config: LocalAgentConfig) -> Result<Self> {
        Self::bootstrap(&mut config.agent, Some(&mut config.local.capabilities))?;
        let local_config = config.local;
        let initial_history = config.initial_history.take();
        let agent = Self::start_with_factory(config.agent, move |hooks, tools, ctx| {
            LocalConnectionStrategy::new(local_config).with_runners(LocalRunners {
                tool_runner: Some(tools),
                hook_runner: Some(hooks),
                session_ctx: Some(ctx),
            })
        })
        .await?;
        if let Some(bytes) = initial_history {
            agent.connection.set_history_bytes(&bytes)?;
        }
        Ok(agent)
    }

    /// Start an `Agent` on a caller-supplied [`ConnectionStrategy`] — the
    /// public entry point for custom backends behind the L3 seam. The
    /// strategy's [`connect`](ConnectionStrategy::connect) opens the session;
    /// tool calls the backend surfaces out-of-band (non-`Done` tool-call
    /// steps) are executed by the agent's dispatcher through the same hooks +
    /// policies + tool runner the built-in backends use, with results pushed
    /// back via [`Connection::send_tool_results`]. Backends that dispatch
    /// tools inline (like the shipped ones) simply emit `Done` steps.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use localharness::{Agent, AgentConfig};
    /// use localharness::backends::mock::MockConnection;
    ///
    /// # async fn run() -> localharness::Result<()> {
    /// // Any ConnectionStrategy works — here the offline mock backend's.
    /// let strategy = MockConnection::builder().turn(|t| t.text("hi")).build();
    /// let agent = Agent::start_with_strategy(AgentConfig::new(), strategy).await?;
    /// assert_eq!(agent.chat("hello").await?.text().await?, "hi");
    /// agent.shutdown().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn start_with_strategy<S>(mut config: AgentConfig, strategy: S) -> Result<Self>
    where
        S: ConnectionStrategy + 'static,
    {
        Self::bootstrap(&mut config, None)?;
        Self::start_with_factory(config, move |_hooks, _tools, _ctx| strategy).await
    }

    /// Token usage accumulated across every turn in this agent's
    /// conversation. Surfaced in the browser app's Usage tab.
    pub fn cumulative_usage(&self) -> crate::types::UsageMetadata {
        self.conversation.cumulative_usage()
    }

    /// Cooperatively cancel the in-flight turn (e.g. a UI stop button).
    /// The backend stops at its next safe boundary — between streamed
    /// chunks or before the next model call / tool dispatch — so no more
    /// tokens are spent and no further tools run. No-op when idle.
    pub fn cancel_turn(&self) {
        self.conversation.cancel_turn();
    }

    /// Opaque snapshot of the current conversation history. Returns
    /// `Ok(None)` for backends that keep no snapshottable history (mock).
    /// Round-trips through the matching `with_history_bytes` for session
    /// resume. Delegates to [`Connection::history_bytes`].
    pub fn history_bytes(&self) -> Result<Option<Vec<u8>>> {
        self.connection.history_bytes()
    }

    /// Set (or clear, with `None`) a PER-TURN thinking-budget override for the
    /// NEXT turn — the difficulty-router seam. The in-tab agent classifies each
    /// turn (greeting vs build/debug) and lowers the thinking budget for routine
    /// turns instead of always running the session's configured level. Applies
    /// to the Gemini and (with the `anthropic` feature) Anthropic backends; a
    /// no-op for the mock / local backends (no thinking control). `None` (the
    /// default) restores the configured level. Cheap — does NOT rebuild the
    /// connection or touch history.
    ///
    /// This overrides only the thinking BUDGET; per-turn MODEL selection is the
    /// separate [`set_model_override`](Self::set_model_override) seam.
    /// Delegates to [`Connection::set_thinking_override`].
    pub fn set_thinking_override(&self, level: Option<crate::types::ThinkingLevel>) {
        self.connection.set_thinking_override(level);
    }

    /// Set (or clear, with `None`) a PER-TURN MODEL override for the NEXT turn —
    /// the difficulty-router model seam (#7), parallel to
    /// [`set_thinking_override`](Self::set_thinking_override). The in-tab router
    /// classifies each turn and may route a routine turn to a cheaper SAME-
    /// BACKEND model (e.g. a Light turn on a Claude-Opus session → Haiku),
    /// clamped so it never exceeds the user's selected model. Applies to the
    /// Gemini and (with the `anthropic` feature) Anthropic backends; a no-op for
    /// the mock / local backends. `None` (the default) restores the configured
    /// model. Cheap — does NOT rebuild the connection or touch history; it works
    /// because the credit proxy routes every model to the SAME endpoint (the
    /// model is just a request field).
    ///
    /// SAFETY: the caller MUST pass a model id in the SAME provider family as
    /// the session's model (a Gemini session must not get a `claude-*` id and
    /// vice-versa) — cross-backend switching would corrupt the wire history.
    /// [`crate::difficulty::route_model`] enforces this. Delegates to
    /// [`Connection::set_model_override`].
    pub fn set_model_override(&self, model: Option<String>) {
        self.connection.set_model_override(model);
    }

    /// Manually trigger context compaction. Summarises older history
    /// entries and replaces them with a single synthetic turn, freeing
    /// context-window budget. Returns `true` if compaction changed the
    /// history, `false` if it was too short or not applicable (mock/local).
    /// Delegates to [`Connection::compact`].
    pub async fn compact(&self) -> bool {
        self.connection.compact().await
    }

    /// Wipe the conversation history, returning the agent to a fresh, empty
    /// context — the in-tab `clear_context` tool / a "clear the chat"
    /// request. Synchronous (clearing a `Vec` needs no network). Delegates
    /// to [`Connection::clear_history`].
    pub fn clear_history(&self) {
        self.connection.clear_history();
    }

    /// Human-readable transcript of the current session, including tool-call
    /// activity — see [`TranscriptEntry`] for the shape. Returns an empty
    /// vec for backends without history (mock). Delegates to
    /// [`Connection::transcript`].
    ///
    /// [`TranscriptEntry`]: crate::types::TranscriptEntry
    pub fn transcript(&self) -> Vec<crate::types::TranscriptEntry> {
        self.connection.transcript()
    }

    /// Internal: shared bootstrap. The `factory` closure receives the
    /// fully-wired hook/tool runners and session context so backends
    /// that dispatch tools inline (Gemini) can inject them.
    async fn start_with_factory<S, F>(agent_config: AgentConfig, factory: F) -> Result<Self>
    where
        S: ConnectionStrategy + 'static,
        F: FnOnce(Arc<HookRunner>, Arc<ToolRunner>, SessionContext) -> S,
    {
        let hook_runner = Arc::new(HookRunner::new());
        let tool_runner = Arc::new(ToolRunner::new());

        for t in &agent_config.tools {
            tool_runner.register(t.clone());
        }

        // Build the effective policy list. Mirror Python's safety check:
        // write tools or MCP servers require either a policy list or a
        // user-installed pre-tool-call hook.
        let mut active_policies = agent_config.policies;
        if !agent_config.workspaces.is_empty() {
            let mut ws_policies = policy::workspace_only(agent_config.workspaces.clone());
            ws_policies.extend(active_policies);
            active_policies = ws_policies;
        }
        // Roadmap Phase 0b — close the custom-tool safety bypass. The old guard
        // only inspected `effective_tools()` (the BuiltinTool set), so a config
        // with custom `ClosureTool`s (e.g. the autonomous loop's `qa_*` tools)
        // and no policy passed with ZERO enforcement — the safety story would be
        // a prompt-level honor system. Now ANY custom tool also requires an
        // explicit policy or a pre-tool-call hook, enforced at the ToolRunner.
        let has_custom_tools = !agent_config.tools.is_empty();
        // Inspect the CONFIG's pre-tool hooks, not `hook_runner` — the hooks are
        // only registered into the runner below (after this check), so testing the
        // runner here made the "policy OR user hook" branch dead (always empty) and
        // wrongly rejected a consumer who supplied a `with_pre_tool_hook` guard.
        if requires_safety_policy(&agent_config.capabilities, has_custom_tools)
            && active_policies.is_empty()
            && agent_config.pre_tool_hooks.is_empty()
        {
            return Err(Error::config(
                "write or custom tools are enabled but no safety policies are \
                 configured. Add policy::allow_all() to approve all calls, or \
                 [policy::deny_all(), policy::Policy::allow(\"tool_name\")] to scope.",
            ));
        }
        if !active_policies.is_empty() {
            hook_runner.register_pre_tool_call_decide(policy::enforce(active_policies));
        }
        for hook in &agent_config.pre_tool_hooks {
            hook_runner.register_pre_tool_call_decide(hook.clone());
        }
        for hook in &agent_config.post_tool_hooks {
            hook_runner.register_post_tool_call(hook.clone());
        }

        // MCP servers: connect, register their tools BEFORE the
        // strategy spins up so the GeminiConnection captures them in
        // its FunctionDeclarations.
        #[cfg(feature = "native")]
        let mcp_bridge = if agent_config.mcp_servers.is_empty() {
            None
        } else {
            let mut bridge = McpBridge::new();
            for cfg in &agent_config.mcp_servers {
                bridge.connect(cfg).await?;
            }
            let registered = bridge.register_into(&tool_runner);
            if !registered.is_empty() {
                tracing::debug!(?registered, "registered MCP tools");
            }
            Some(Arc::new(bridge))
        };

        let session_ctx = SessionContext::new();
        let strategy = factory(hook_runner.clone(), tool_runner.clone(), session_ctx.clone());
        let connection = strategy.connect().await?;

        hook_runner.dispatch_session_start(&session_ctx).await;

        tool_runner.set_context(Arc::new(ToolContext::new(connection.clone())));

        let conversation = Conversation::new(connection.clone());

        let shutdown_flag = Arc::new(AtomicBool::new(false));
        #[cfg(not(target_arch = "wasm32"))]
        let dispatcher = spawn_tool_dispatcher(
            connection.clone(),
            tool_runner.clone(),
            hook_runner.clone(),
            session_ctx.clone(),
            shutdown_flag.clone(),
        );
        #[cfg(target_arch = "wasm32")]
        spawn_tool_dispatcher(
            connection.clone(),
            tool_runner.clone(),
            hook_runner.clone(),
            session_ctx.clone(),
            shutdown_flag.clone(),
        );

        let trigger_runner = if agent_config.triggers.is_empty() {
            None
        } else {
            let runner = Arc::new(TriggerRunner::new(
                agent_config.triggers,
                connection.clone(),
            ));
            runner.start()?;
            Some(runner)
        };

        Ok(Self {
            conversation,
            connection,
            hook_runner,
            tool_runner,
            trigger_runner,
            #[cfg(feature = "native")]
            mcp_bridge,
            session_ctx,
            #[cfg(not(target_arch = "wasm32"))]
            dispatcher: parking_lot::Mutex::new(Some(dispatcher)),
            shutdown_flag,
        })
    }

    /// Shared per-start bootstrap: validate the capability config, wire the
    /// response schema into the `finish` tool, and — the ONE copy point —
    /// sync the backend's `CapabilitiesConfig` from the agent's so
    /// `register_builtins` enables the right set (the four per-start
    /// hand-copies used to drift; `LocalAgentConfig::with_capabilities` even
    /// double-copied at build time).
    fn bootstrap(
        agent: &mut AgentConfig,
        backend_capabilities: Option<&mut CapabilitiesConfig>,
    ) -> Result<()> {
        agent.capabilities.validate()?;
        if let Some(schema) = agent.response_schema.take() {
            agent.capabilities.finish_tool_schema_json = Some(schema);
        }
        if let Some(caps) = backend_capabilities {
            *caps = agent.capabilities.clone();
        }
        Ok(())
    }

    /// The underlying conversation session.
    pub fn conversation(&self) -> &Conversation {
        &self.conversation
    }

    /// The backend-assigned conversation identifier.
    pub fn conversation_id(&self) -> String {
        self.connection.conversation_id().to_string()
    }

    /// The hook runner; use to register additional hooks after start.
    pub fn hooks(&self) -> &HookRunner {
        &self.hook_runner
    }

    /// The tool runner; use to register additional tools after start.
    pub fn tools(&self) -> &ToolRunner {
        &self.tool_runner
    }

    /// Send a prompt and return a streaming [`ChatResponse`].
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use localharness::Agent;
    /// # async fn run(agent: &Agent) -> localharness::Result<()> {
    /// let response = agent.chat("What is Rust?").await?;
    /// println!("{}", response.text().await?);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn chat(&self, content: impl Into<Content>) -> Result<ChatResponse> {
        self.conversation.chat(content).await
    }

    /// Cleanly shut down the agent, aborting triggers and dispatchers.
    pub async fn shutdown(self) -> Result<()> {
        self.shutdown_flag.store(true, Ordering::Release);
        #[cfg(not(target_arch = "wasm32"))]
        {
            let handle = self.dispatcher.lock().take();
            if let Some(handle) = handle {
                handle.abort();
                let _ = handle.await;
            }
        }
        if let Some(triggers) = self.trigger_runner.as_ref() {
            triggers.stop().await;
        }
        self.hook_runner.dispatch_session_end(&self.session_ctx).await;
        self.connection.shutdown().await?;
        #[cfg(feature = "native")]
        if let Some(bridge) = self.mcp_bridge.as_ref() {
            bridge.shutdown().await;
        }
        Ok(())
    }
}

impl Drop for Agent {
    fn drop(&mut self) {
        self.shutdown_flag.store(true, Ordering::Release);
        #[cfg(not(target_arch = "wasm32"))]
        if let Some(handle) = self.dispatcher.lock().take() {
            handle.abort();
        }
    }
}

/// Whether the agent's safety guard must require an explicit policy or a
/// pre-tool-call hook before start: true if any WRITE builtin OR any custom
/// tool is enabled. Custom tools (`ClosureTool`s) bypassed the old
/// `effective_tools()`-only check — closing that is roadmap Phase 0b, so the
/// autonomous loop can't register `qa_*` tools and run them with zero policy.
fn requires_safety_policy(capabilities: &CapabilitiesConfig, has_custom_tools: bool) -> bool {
    has_custom_tools
        || capabilities
            .effective_tools()
            .iter()
            .any(|t| !BuiltinTool::READ_ONLY.contains(t))
}

// =============================================================================
// Tool dispatcher
// =============================================================================

/// The shared tool-dispatcher loop body (ONE copy for both targets). Subscribes
/// to the connection's step stream and re-runs any non-`Done` tool-call step
/// whose tool name is registered — the inline-dispatch backends emit `Done`
/// steps (skipped here), so this fires only for backends that surface tool
/// calls out-of-band. The cfg wrappers below differ ONLY in how they spawn it:
/// native keeps the `JoinHandle`, wasm fire-and-forgets.
async fn run_tool_dispatcher(
    connection: Arc<dyn Connection>,
    tool_runner: Arc<ToolRunner>,
    hook_runner: Arc<HookRunner>,
    session_ctx: SessionContext,
    shutdown: Arc<AtomicBool>,
) {
    let registered: std::collections::HashSet<String> =
        tool_runner.names().into_iter().collect();
    let mut stream = connection.subscribe_steps();
    while let Some(step) = stream.next().await {
        if shutdown.load(Ordering::Acquire) {
            return;
        }
        let step = match step {
            Ok(s) => s,
            Err(e) => {
                warn!(error = %e, "tool dispatcher stream error");
                continue;
            }
        };
        if step.tool_calls.is_empty() {
            continue;
        }
        if matches!(step.status, StepStatus::Done) {
            continue;
        }

        let custom_calls: Vec<ToolCall> = step
            .tool_calls
            .into_iter()
            .filter(|tc| registered.contains(&tc.name))
            .collect();
        if custom_calls.is_empty() {
            continue;
        }

        let turn_ctx = session_ctx.child();
        let mut results = Vec::with_capacity(custom_calls.len());
        for call in custom_calls {
            let (decision, op_ctx) = hook_runner.dispatch_pre_tool_call(&turn_ctx, &call).await;
            if !decision.allow {
                let r = crate::types::ToolResult::err(
                    call.name.clone(),
                    call.id.clone(),
                    decision.message.clone(),
                );
                hook_runner.dispatch_post_tool_call(&op_ctx, &r).await;
                results.push(r);
                continue;
            }
            let r = match tool_runner.execute(&call.name, call.args.clone()).await {
                Ok(v) => crate::types::ToolResult::ok(call.name.clone(), call.id.clone(), v),
                Err(e) => {
                    crate::types::ToolResult::err(call.name.clone(), call.id.clone(), e.to_string())
                }
            };
            hook_runner.dispatch_post_tool_call(&op_ctx, &r).await;
            results.push(r);
        }

        if let Err(e) = connection.send_tool_results(results).await {
            warn!(error = %e, "failed to send tool results");
        }
    }
    debug!("tool dispatcher exiting");
}

#[cfg(not(target_arch = "wasm32"))]
fn spawn_tool_dispatcher(
    connection: Arc<dyn Connection>,
    tool_runner: Arc<ToolRunner>,
    hook_runner: Arc<HookRunner>,
    session_ctx: SessionContext,
    shutdown: Arc<AtomicBool>,
) -> JoinHandle<()> {
    tokio::spawn(run_tool_dispatcher(
        connection,
        tool_runner,
        hook_runner,
        session_ctx,
        shutdown,
    ))
}

#[cfg(target_arch = "wasm32")]
fn spawn_tool_dispatcher(
    connection: Arc<dyn Connection>,
    tool_runner: Arc<ToolRunner>,
    hook_runner: Arc<HookRunner>,
    session_ctx: SessionContext,
    shutdown: Arc<AtomicBool>,
) {
    crate::runtime::spawn(run_tool_dispatcher(
        connection,
        tool_runner,
        hook_runner,
        session_ctx,
        shutdown,
    ));
}

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

    fn caps(enabled: Vec<BuiltinTool>) -> CapabilitiesConfig {
        CapabilitiesConfig {
            enabled_tools: Some(enabled),
            ..Default::default()
        }
    }

    #[test]
    fn custom_tools_require_a_safety_policy() {
        // No builtins, no custom tools → no policy required.
        assert!(!requires_safety_policy(&caps(vec![]), false));
        // A custom tool ALONE now requires a policy (the closed Phase-0b bypass).
        assert!(requires_safety_policy(&caps(vec![]), true));
        // A write builtin requires a policy (unchanged behavior).
        assert!(requires_safety_policy(&caps(vec![BuiltinTool::CreateFile]), false));
        // Read-only builtins alone do not.
        assert!(!requires_safety_policy(
            &caps(BuiltinTool::READ_ONLY.to_vec()),
            false
        ));
    }

    /// A user-installed pre-tool-call hook satisfies the safety requirement — the
    /// documented "policy OR hook" contract. Regression: the guard used to inspect
    /// the still-empty `hook_runner` (hooks are registered AFTER the check), so a
    /// consumer wiring `with_pre_tool_hook(...)` and no explicit policy was wrongly
    /// rejected with "no safety policies are configured".
    #[cfg(not(target_arch = "wasm32"))]
    #[tokio::test]
    async fn a_user_pre_tool_hook_satisfies_the_safety_requirement() {
        use crate::backends::mock::MockConnection;
        use crate::tools::ClosureTool;

        let custom_tool = || {
            ClosureTool::new(
                "noop",
                "does nothing",
                serde_json::json!({"type": "object"}),
                |_args, _ctx| async move { Ok(serde_json::json!({})) },
            )
        };

        // Custom tool, NO policy, NO hook → rejected (the Phase-0b bypass stays closed).
        let unguarded = MockAgentConfig::new(MockConnection::builder().turn(|t| t.text("hi")).build())
            .with_tool(custom_tool());
        assert!(Agent::start_mock(unguarded).await.is_err());

        // SAME config + a user pre-tool-call hook (no explicit policy) → accepted.
        let with_hook = MockAgentConfig::new(MockConnection::builder().turn(|t| t.text("hi")).build())
            .with_tool(custom_tool())
            .with_pre_tool_hook(crate::policy::enforce(vec![crate::policy::allow_all()]));
        assert!(Agent::start_mock(with_hook).await.is_ok());
    }
}