supercode-harness 0.4.6

The optional native Supercode agent and tool harness
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
//! Tools the agent can call.
//!
//! A [`Tool`] is a named capability with a JSON-Schema input and an async
//! `execute`. The [`ToolRegistry`] holds the set offered to a model; built-ins
//! cover file read/write/edit, directory listing, glob, content search, and
//! shell execution. Every tool can be disabled or re-described per
//! [`crate::Config`], so the capability surface is entirely yours to shape.

mod builtins;
pub(crate) mod tiers;

use std::collections::HashMap;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use async_trait::async_trait;

use crate::config::Config;
use crate::error::Result;
use crate::modules::ModuleId;

pub use builtins::{
    ApplyPatchTool, BashTool, EditFileTool, GlobTool, ListDirTool, PersistentShellTool,
    ReadFileTool, SearchTool, UpdatePlanTool, ViewImageTool, WebFetchTool, WebSearchTool,
    WriteFileTool, WEB_SEARCH_URL_ENV,
};
// P5-1 F4: `crate::agent`'s permissions gate needs to check an
// `apply_patch` envelope's write surface against `protected_paths` — not
// part of the crate's public tool-registration API, so `pub(crate)` rather
// than folded into the `pub use` list above.
pub(crate) use builtins::patch_target_paths;
// P5-6 (§2 module 4 `tools.background`): `crate::agent::Agent`'s
// `background_exec` intrinsic reuses `BashTool`'s own sandboxed-spawn
// builder rather than duplicating it — see that function's doc comment.
pub(crate) use builtins::build_sandboxed_sh;
pub use tiers::{minify as minify_tool_schema, SchemaTier};
// `SandboxPolicy` and `ToolContext` are defined below in this module.

/// P4c (COMPOSABLE-HARNESS-DESIGN.md S1.2/S3.1 `core.tools.read_file
/// multimodal`, S1.2 `view_image`): the sentinel prefix a tool's plain
/// `String` result carries when it is actually an image data URL rather
/// than ordinary text — `Agent::run_loop` detects this prefix (before
/// `cap_tool_output` ever sees it) and builds a `content_parts` image
/// block instead of a plain-text tool result. Using a control character
/// (`\u{1}`, SOH) as part of the marker keeps a false-positive collision
/// with real tool output astronomically unlikely without requiring a new
/// `Tool::execute` return type across all ten built-ins (an L-sized
/// trait-signature change this S-sized catalog item does not call for).
pub const MULTIMODAL_IMAGE_MARKER: &str = "\u{1}SUPERCODE_IMAGE_DATA_URL\u{1}";

/// P4c (S1.2 `core.tools.read_file.multimodal` / `view_image`): recognized
/// image file extensions (lowercase, no dot) — the same set CC/pi treat as
/// "images" for multimodal read (catalog D1 row 2's `✓*`/`✓*` variants).
pub const IMAGE_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp"];

/// Whether `path`'s extension is a recognized image type (case-insensitive).
pub fn is_image_path(path: &Path) -> bool {
    path.extension()
        .and_then(|e| e.to_str())
        .map(|e| IMAGE_EXTENSIONS.contains(&e.to_ascii_lowercase().as_str()))
        .unwrap_or(false)
}

/// The `image/<subtype>` MIME type for a recognized image extension, for
/// the `data:` URL — falls back to `png` for anything [`is_image_path`]
/// didn't already gate (defensive; never actually hit through
/// [`is_image_path`]'s own extension list).
pub fn image_mime_for(path: &Path) -> &'static str {
    match path
        .extension()
        .and_then(|e| e.to_str())
        .map(|e| e.to_ascii_lowercase())
        .as_deref()
    {
        Some("jpg") | Some("jpeg") => "image/jpeg",
        Some("gif") => "image/gif",
        Some("webp") => "image/webp",
        Some("bmp") => "image/bmp",
        _ => "image/png",
    }
}

/// P4c (S1.2 `core.tools.edit_file.notebook_aware`): the extension that
/// gates `EditFileTool`'s Jupyter cell-surgery branch.
pub const NOTEBOOK_EXTENSION: &str = "ipynb";

/// P4c (S2 module 5 `tools.web`, S2.1 dep "network sandbox rules", S17):
/// the network-domain policy a caller (SDK embedder) may install on a
/// [`ToolContext`] so [`crate::tools::WebFetchTool`]/[`crate::tools::WebSearchTool`]
/// respect it — see [`ToolContext::check_network`]. `None` on the context
/// (the default) means no policy is configured, matching today's honest
/// gap (no P5 `capabilities.permissions.sandbox.network` engine exists
/// yet, C3 — tracked, not hidden).
#[derive(Debug, Clone, Default)]
pub struct NetworkPolicy {
    /// Whether the policy is enforced at all. `false` behaves exactly like
    /// `None` on the context.
    pub enabled: bool,
    /// If non-empty, only these hosts (exact match) are allowed.
    pub allow_domains: Vec<String>,
    /// These hosts (exact match) are always denied, even if also present in
    /// `allow_domains`.
    pub deny_domains: Vec<String>,
}

/// Filesystem confinement applied to write-capable tools — the analog of
/// Codex's `read-only` / `workspace-write` / `danger-full-access` sandbox modes.
///
/// Enforced at the tool layer for file operations (`write_file`, `edit_file`,
/// `apply_patch`). Note: this confines the *file tools*; it does not OS-sandbox
/// arbitrary subprocesses (`bash`/`shell`) — true process isolation needs
/// platform primitives (seatbelt/landlock) and is a separate concern. Use
/// [`shell_sandbox_unenforceable`] as the runtime check for whether that gap
/// applies to the current platform and enabled tools.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SandboxPolicy {
    /// No file writes are permitted by the file tools.
    ReadOnly,
    /// Writes are permitted only inside the working directory.
    WorkspaceWrite,
    /// No confinement (default — preserves prior behavior).
    #[default]
    DangerFullAccess,
}

/// P5-9 (design §2 module 20 `checkpoint`, §2.1 D-5 "write-path
/// interception seam shared with `formatters`"): the ONE well-defined
/// interception point around every file-mutating built-in tool
/// (`write_file`/`edit_file`/`apply_patch`) — installed on
/// [`ToolContext::write_observer`], `None` by default. Both hooks fire
/// AFTER [`ToolContext::check_write`] has already approved the call (so an
/// observer never sees a write the sandbox itself refused) and BEFORE/AFTER
/// the actual mutation:
/// - [`Self::before_write`] — pre-image capture. `crate::checkpoint`'s
///   [`crate::checkpoint::CheckpointObserver`] is the only implementation
///   today: it snapshots `path`'s current on-disk content (or records "did
///   not exist") so a later `checkpoint restore` can undo the write.
/// - [`Self::after_write`] — post-write. A true no-op in every
///   implementation shipped so far; reserved for `formatters` (P5-11,
///   design line 510 "shared seam with checkpoint") to run format-on-write
///   from, without needing a SECOND interception point wired through the
///   same three tools.
///
/// `None` (the default — `[capabilities.checkpoint]` off and no formatters
/// module yet) means neither hook is ever consulted: every write-tool
/// call-site's observer check is `if let Some(obs) = &ctx.write_observer`,
/// a branch that's simply never taken, so behavior is byte-identical to
/// before this seam existed.
///
/// P5-11 (§2 modules 28/29 `lsp`/`formatters`, C10): `async_trait` (rather
/// than the plain sync methods P5-9 originally shipped) because BOTH new
/// observers need real async I/O in `after_write` — `formatters` spawns and
/// awaits a subprocess, `lsp` writes/reads framed JSON-RPC over a child's
/// stdio — and neither can block the tokio runtime thread the way a
/// synchronous call from inside an already-`async fn execute()` would.
/// `CheckpointObserver`'s own hooks stay synchronous *internally* (plain
/// blocking `std::fs` calls); wrapping them in `async fn` changes nothing
/// observable for it, since that blocking work already ran on the calling
/// task before this signature changed. `after_write` now RETURNS
/// `Option<String>` — an annotation to append to the calling tool's result
/// string (formatter diff-back content, or LSP diagnostics) — `None` when
/// the observer has nothing to report, which is the only value
/// `CheckpointObserver::after_write` (still a no-op) ever returns, keeping
/// today's tool-result text byte-identical whenever checkpoint is the only
/// observer installed.
#[async_trait]
pub trait WriteObserver: Send + Sync + std::fmt::Debug {
    /// `path` (already resolved + sandbox-checked) is about to be
    /// created/overwritten/deleted. Implementations must be fast and must
    /// never propagate a failure as a tool error — a capture failure should
    /// degrade the OBSERVER (e.g. disable itself with a one-time warning),
    /// never block or fail the user's actual edit.
    async fn before_write(&self, path: &Path);
    /// `path` was just written/deleted successfully. Not called when the
    /// tool call itself failed (e.g. the write errored before completing).
    /// Returns an optional annotation for the calling tool's result text —
    /// see the trait doc comment above.
    async fn after_write(&self, path: &Path) -> Option<String>;
}

/// P5-11 (§2 modules 28/29, D-5 "shared write-path interception seam"): an
/// ORDERED chain of [`WriteObserver`]s installed as a single
/// `ToolContext::write_observer`, so the ONE seam P5-9 built keeps
/// supporting exactly one call site per tool while now composing multiple
/// concerns. Order is caller-determined (`crate::agent::build_tool_context`
/// builds it `checkpoint → formatters → lsp`, design's own required
/// ordering: checkpoint must capture the PRE-image before anything mutates
/// the file; formatters must run before lsp so diagnostics reflect the
/// FINAL, formatted file, not the model's pre-format draft).
/// `before_write` runs every observer in order; `after_write` runs every
/// observer in order too and joins any non-empty annotations with a blank
/// line, so a formatter's diff-back and an LSP diagnostics block can both
/// appear in one tool result without one silently discarding the other.
#[derive(Debug)]
pub struct WriteObserverChain(Vec<Arc<dyn WriteObserver>>);

impl WriteObserverChain {
    /// Build a chain that runs `observers` in order for both hooks.
    pub fn new(observers: Vec<Arc<dyn WriteObserver>>) -> Self {
        WriteObserverChain(observers)
    }
}

#[async_trait]
impl WriteObserver for WriteObserverChain {
    async fn before_write(&self, path: &Path) {
        for obs in &self.0 {
            obs.before_write(path).await;
        }
    }
    async fn after_write(&self, path: &Path) -> Option<String> {
        let mut notes: Vec<String> = Vec::new();
        for obs in &self.0 {
            if let Some(note) = obs.after_write(path).await {
                if !note.is_empty() {
                    notes.push(note);
                }
            }
        }
        if notes.is_empty() {
            None
        } else {
            Some(notes.join("\n\n"))
        }
    }
}

/// Ambient context passed to every tool invocation.
#[derive(Debug, Clone)]
pub struct ToolContext {
    /// The working directory tools resolve relative paths against.
    pub cwd: PathBuf,
    /// Filesystem confinement for write-capable tools.
    pub sandbox: SandboxPolicy,
    /// P4c (S1.2 `core.tools.read_file.multimodal`): whether `read_file`
    /// (and `view_image`, unconditionally) returns a recognized image file
    /// as a model-visible image content block. `false` (the default) is
    /// byte-identical to today's UTF-8-lossy-decode behavior.
    pub multimodal_read: bool,
    /// P4c (S1.2 `core.tools.edit_file.require_read_before_edit`, UNIQUE CC
    /// row): whether `edit_file` refuses a path not yet read this
    /// conversation. `false` (the default) is byte-identical to today's
    /// behavior — [`Self::read_paths`] is simply never consulted.
    pub require_read_before_edit: bool,
    /// P4c: canonicalized paths `read_file` has successfully read so far
    /// this conversation — shared (via `Arc<Mutex<_>>`) across every clone
    /// of this context, since `Agent` constructs one `ToolContext` at
    /// startup and reuses it for every tool call. Consulted by `EditFileTool`
    /// only when [`Self::require_read_before_edit`] is `true`.
    pub read_paths: Arc<Mutex<HashSet<PathBuf>>>,
    /// P4c (S1.2 `core.tools.edit_file.notebook_aware`, UNIQUE CC row
    /// "NotebookEdit"): whether `edit_file` accepts Jupyter cell
    /// replace/insert/delete operations against a `.ipynb` target. `false`
    /// (the default) is byte-identical to today's exact-string-replace-only
    /// behavior.
    pub notebook_aware: bool,
    /// P4c (S1.2 `core.shell_env_snapshot`): the user's captured
    /// interactive-shell environment, if [`crate::Config::shell_env_snapshot`]
    /// is on — `BashTool`/`PersistentShellTool` merge this into the spawned
    /// process's environment. `None` (the default) is byte-identical to
    /// today's behavior: no extra environment is injected.
    pub shell_env: Option<Arc<HashMap<String, String>>>,
    /// P4c (S1.4 `core.nested_instructions`, deferred from P4b): whether a
    /// file-touching tool injects an as-yet-unseen subdirectory's own
    /// `CLAUDE.md`/`AGENTS.md` into its result the first time a path under
    /// it is touched. `false` (the default) is byte-identical to today's
    /// behavior.
    pub nested_instructions: bool,
    /// P4c: subdirectories (relative to [`Self::cwd`]) whose nested
    /// instructions have already been injected this conversation — shared
    /// across clones, same rationale as [`Self::read_paths`]. Consulted only
    /// when [`Self::nested_instructions`] is `true`.
    pub injected_instruction_dirs: Arc<Mutex<HashSet<PathBuf>>>,
    /// P4c (S2 module 5 `tools.web`, S17): the network-domain policy
    /// `web_fetch`/`web_search` must respect, if one is configured. `None`
    /// (the default) means no policy is enforced — see [`NetworkPolicy`]'s
    /// doc comment for the honest-gap rationale.
    pub network_policy: Option<NetworkPolicy>,
    /// P4e (S3.1 `core.tools.bash.timeout_secs`, S14): the DEFAULT
    /// execution timeout (seconds) `BashTool::execute` falls back to when a
    /// model-issued call carries no `timeout_ms` argument of its own -- see
    /// `crate::config::ToolOverride::timeout_secs`. `None` (the default) is
    /// byte-identical to today's behavior: `BashTool`'s built-in
    /// `DEFAULT_BASH_TIMEOUT_MS` (120s) stands.
    pub bash_timeout_secs: Option<u64>,
    /// P5-9 (§2 module 20, D-5 shared write-path interception seam) — see
    /// [`WriteObserver`]'s doc comment. `None` (the default) is a true
    /// no-op: every write-tool call site's `if let Some(obs) = ...` branch
    /// is simply never taken.
    pub write_observer: Option<Arc<dyn WriteObserver>>,
    /// P5-10 (§2 module 12 `permissions.sandbox`): whether the OS-level
    /// backstop (Landlock/seatbelt) is engaged for the `bash`/`shell`
    /// subprocess — see `crate::sandbox::os_sandbox_active`. `None` (the
    /// default) preserves the pre-P5-10 trigger (confine whenever
    /// [`Self::sandbox`] isn't [`SandboxPolicy::DangerFullAccess`]).
    pub sandbox_os_enabled: Option<bool>,
    /// P5-10 (§2 module 12, `escalation`): what to do when a confining fs
    /// tier can't actually be enforced on this platform/kernel — see
    /// `crate::sandbox::SandboxEscalation`. Defaults to `Deny`
    /// (fail-closed).
    pub sandbox_escalation: crate::sandbox::SandboxEscalation,
    /// P5-10 (§2 module 12, `env_policy`): child-process environment
    /// sanitization for the spawned subprocess — see
    /// `crate::sandbox::SandboxEnvPolicy`. Defaults to `Inherit`
    /// (byte-identical to pre-P5-10 behavior).
    pub sandbox_env_policy: crate::sandbox::SandboxEnvPolicy,
    /// P5-10 (§2 module 12, `escalation = "ask"` → `permissions.approvals`,
    /// P5-1): the ambient handler `crate::sandbox::decide_fs` consults for
    /// an `ask`-tier sandbox-unenforceable decision. `None` (the default —
    /// no handler installed) is fail-closed, same posture as the P5-1 rule
    /// engine's own `Ask` tier with no handler.
    pub sandbox_approval_handler: Option<crate::sandbox::SandboxApprovalHandler>,
}

impl ToolContext {
    /// A context rooted at `cwd` with no confinement.
    pub fn new(cwd: impl Into<PathBuf>) -> Self {
        ToolContext {
            cwd: cwd.into(),
            sandbox: SandboxPolicy::DangerFullAccess,
            multimodal_read: false,
            require_read_before_edit: false,
            read_paths: Arc::new(Mutex::new(HashSet::new())),
            notebook_aware: false,
            shell_env: None,
            nested_instructions: false,
            injected_instruction_dirs: Arc::new(Mutex::new(HashSet::new())),
            network_policy: None,
            bash_timeout_secs: None,
            write_observer: None,
            sandbox_os_enabled: None,
            sandbox_escalation: crate::sandbox::SandboxEscalation::default(),
            sandbox_env_policy: crate::sandbox::SandboxEnvPolicy::default(),
            sandbox_approval_handler: None,
        }
    }

    /// P5-10: whether the OS-level backstop is active for this context —
    /// thin wrapper over `crate::sandbox::os_sandbox_active`.
    pub fn os_sandbox_active(&self) -> bool {
        crate::sandbox::os_sandbox_active(self.sandbox, self.sandbox_os_enabled)
    }

    /// P4c: record `path` (canonicalized if possible, else the resolved
    /// path as-is) as having been read this conversation — called by
    /// `ReadFileTool` on every successful read, unconditionally (cheap; the
    /// set is only ever CONSULTED when [`Self::require_read_before_edit`] is
    /// on, but recording it unconditionally means turning the knob on
    /// mid-conversation sees every read that already happened).
    pub fn mark_read(&self, path: &Path) {
        let key = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
        if let Ok(mut set) = self.read_paths.lock() {
            set.insert(key);
        }
    }

    /// P4c: whether `path` was previously recorded via [`Self::mark_read`].
    pub fn was_read(&self, path: &Path) -> bool {
        let key = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
        self.read_paths
            .lock()
            .map(|set| set.contains(&key))
            .unwrap_or(false)
    }

    /// P4c (S2.1 S17): does `url` pass `Self::network_policy`, if one is
    /// configured? `Ok(())` when no policy is set (the honest-gap default)
    /// or the policy is present-but-disabled; `Err` names the reason
    /// otherwise. A URL with no parseable host is denied whenever a policy
    /// is actively enforced (fail closed — an unparseable host can't be
    /// matched against an allowlist).
    pub fn check_network(&self, url: &str) -> Result<()> {
        check_network_policy(self.network_policy.as_ref(), url)
    }

    /// Resolve a possibly-relative path against the working directory.
    pub fn resolve(&self, path: &str) -> PathBuf {
        let p = PathBuf::from(path);
        if p.is_absolute() {
            p
        } else {
            self.cwd.join(p)
        }
    }

    /// Enforce the sandbox policy for a write to `path`. `Err` if denied.
    pub fn check_write(&self, path: &Path) -> Result<()> {
        match self.sandbox {
            SandboxPolicy::DangerFullAccess => Ok(()),
            SandboxPolicy::ReadOnly => Err(crate::error::Error::tool(
                "sandbox",
                "write denied: sandbox is read-only",
            )),
            SandboxPolicy::WorkspaceWrite => {
                if path_within(&self.cwd, path) {
                    Ok(())
                } else {
                    Err(crate::error::Error::tool(
                        "sandbox",
                        format!(
                            "write denied: {} is outside the workspace {}",
                            path.display(),
                            self.cwd.display()
                        ),
                    ))
                }
            }
        }
    }
}

/// P5-2 (§2 module 15, security note "remote MCP over http/sse: respect the
/// NetworkPolicy from P5-1 if one is active"): the same policy-and-url check
/// [`ToolContext::check_network`] performs, factored out to a free function
/// so `crate::mcp::McpClient::connect_http`/`connect_sse` can enforce the
/// identical allow/deny/SSRF floor a `web_fetch` call would get — one
/// enforcement point, not a second parallel one that could silently drift
/// from it.
pub(crate) fn check_network_policy(policy: Option<&NetworkPolicy>, url: &str) -> Result<()> {
    let Some(policy) = policy else {
        return Ok(());
    };
    if !policy.enabled {
        return Ok(());
    }
    check_host_against_policy(policy, url_host(url).as_deref())
}

/// P4c-review (MEDIUM/LOW follow-up, dep 8's neighboring `tools.web` SSRF
/// gap): the SAME allow/deny decision [`ToolContext::check_network`] applies
/// to the INITIAL url, factored out so [`network_checked_redirect_policy`]
/// can apply it to every REDIRECT hop too. Without this, `check_network`
/// validated only the url the caller passed in — once a real network policy
/// is wired up (P5), a denied host reachable only via an allowed host's HTTP
/// redirect (reqwest follows up to 10 by default) bypassed the check
/// entirely. `host: None` (unparseable/absent) fails closed, exactly like
/// `check_network`'s own prior inline behavior.
fn check_host_against_policy(policy: &NetworkPolicy, host: Option<&str>) -> Result<()> {
    let Some(host) = host else {
        return Err(crate::error::Error::tool(
            "network",
            "cannot determine host from url; denied under an active network policy",
        ));
    };
    let host = host.to_ascii_lowercase();
    if policy.deny_domains.iter().any(|d| d == &host) {
        return Err(crate::error::Error::tool(
            "network",
            format!("host `{host}` is denied by the active network policy"),
        ));
    }
    if !policy.allow_domains.is_empty() && !policy.allow_domains.iter().any(|d| d == &host) {
        return Err(crate::error::Error::tool(
            "network",
            format!("host `{host}` is not on the network policy's allowlist"),
        ));
    }
    Ok(())
}

/// P4c-review (MEDIUM/LOW follow-up): a `reqwest::redirect::Policy` for
/// `WebFetchTool`/`WebSearchTool`'s client that re-runs
/// [`check_host_against_policy`] (the exact same check
/// [`ToolContext::check_network`] applies to the initial url) against every
/// redirect hop's target host, refusing to follow one that a network policy
/// denies. `policy: None` (no policy configured) or a present-but-disabled
/// one behaves like reqwest's own default policy — follow, capped at the
/// same 10-hop limit `redirect::Policy::default()` uses (the crate's `custom`
/// variant does NOT enforce a redirect cap on its own — see its doc comment
/// — so this reimplements that cap by hand).
pub(crate) fn network_checked_redirect_policy(
    policy: Option<NetworkPolicy>,
) -> reqwest::redirect::Policy {
    const MAX_REDIRECTS: usize = 10; // matches reqwest::redirect::Policy::default()
    reqwest::redirect::Policy::custom(move |attempt| {
        if attempt.previous().len() >= MAX_REDIRECTS {
            return attempt.error("too many redirects");
        }
        if let Some(policy) = &policy {
            if policy.enabled {
                if let Err(e) = check_host_against_policy(policy, attempt.url().host_str()) {
                    return attempt.error(e.to_string());
                }
            }
        }
        attempt.follow()
    })
}

/// P4c (S2.1 S17): extract the host from an `http(s)://` URL — the smallest
/// parser that satisfies [`ToolContext::check_network`]'s needs without a
/// new `url`-crate dependency (matches this crate's existing `glob_match`
/// precedent of hand-rolling a small parser rather than reaching for a
/// dependency for an S-sized need). Returns `None` for anything that isn't
/// `http://`/`https://` or has an empty host component.
fn url_host(url: &str) -> Option<String> {
    let rest = url
        .strip_prefix("https://")
        .or_else(|| url.strip_prefix("http://"))?;
    let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
    let authority = &rest[..end];
    // Strip a `user:pass@` prefix and a `:port` suffix, keeping the host.
    let host_and_port = authority.rsplit('@').next().unwrap_or(authority);
    let host = host_and_port.split(':').next().unwrap_or(host_and_port);
    if host.is_empty() {
        None
    } else {
        Some(host.to_ascii_lowercase())
    }
}

/// True when the requested sandbox policy cannot be enforced for shell
/// subprocesses: a confining policy, a platform without an OS sandbox
/// primitive wired up (only macOS/seatbelt is, via `sandbox-exec`), and at
/// least one shell tool (`"bash"` or `"shell"`) enabled.
///
/// This is a pure function so it's mechanically testable on any host OS:
/// callers pass the platform (typically `std::env::consts::OS`) and the set
/// of enabled tool names rather than relying on `cfg!`/`target_os`. It does
/// not itself sandbox anything — it only tells embedders/CLIs whether the
/// gap documented on [`SandboxPolicy`] applies right now, so they can warn.
/// P5-10 (§2 module 12): `landlock_available` is the caller's REAL Linux
/// Landlock-availability probe (`crate::sandbox::landlock_available()`,
/// typically) — a PARAMETER, not an internal `cfg!`/probe call, same "pure,
/// mechanically testable" contract this function already had. Before
/// P5-10, `platform == "linux"` always meant "unenforceable" (no OS
/// primitive existed yet); now it means "unenforceable UNLESS Landlock is
/// actually available on this kernel" — a confining tier on a
/// Landlock-capable Linux box is REAL enforcement, not a gap, so this must
/// say `false` for it (never claim a gap that no longer exists).
/// `platform == "macos"` is unconditionally `false` regardless of this
/// parameter (seatbelt, a separate primitive, always exists there); every
/// other platform (including `platform == "linux"` with
/// `landlock_available == false`) is unaffected by this parameter and
/// keeps the pre-P5-10 "no primitive" answer.
pub fn shell_sandbox_unenforceable(
    policy: SandboxPolicy,
    platform: &str,
    tools_enabled: &[&str],
    landlock_available: bool,
) -> bool {
    policy != SandboxPolicy::DangerFullAccess
        && platform != "macos"
        && !(platform == "linux" && landlock_available)
        && tools_enabled.iter().any(|t| *t == "bash" || *t == "shell")
}

/// Whether `path` is inside `root`. SECURITY (safe-path consolidation,
/// LOWER-URGENCY fix folded into the permissions-gate CRITICAL fix): this
/// used to compare only LEXICALLY-normalized paths (`..` traversal caught,
/// but a pre-existing in-workspace symlink pointing outside `root` was NOT —
/// `link -> /etc` plus a write to `link/passwd` lexically normalizes to
/// `<root>/link/passwd`, which "starts with" `root` even though it actually
/// resolves outside it). Now delegates to `crate::safe_path::contained`,
/// which ALSO resolves symlinks along the longest existing ancestor (the
/// same proven dual lexical+resolved check `crate::checkpoint`'s P5-9 fix
/// uses), so a symlink escape is caught here too. A non-existent target
/// (e.g. a file about to be created) is still handled correctly.
fn path_within(root: &Path, path: &Path) -> bool {
    crate::safe_path::contained(root, path)
}

/// `pub(crate)`: also the lexical-`..`-collapse step
/// [`crate::checkpoint`]'s containment check builds on (P5-9) — one
/// normalizer, not a second hand-rolled one.
pub(crate) fn normalize(path: &Path) -> Option<PathBuf> {
    use std::path::Component;
    // Make absolute against CWD if needed (paths are already joined to cwd by
    // resolve(), but be defensive).
    let abs = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir().ok()?.join(path)
    };
    let mut out = PathBuf::new();
    for c in abs.components() {
        match c {
            Component::ParentDir => {
                out.pop();
            }
            Component::CurDir => {}
            other => out.push(other.as_os_str()),
        }
    }
    Some(out)
}

/// A callable capability.
#[async_trait]
pub trait Tool: Send + Sync {
    /// Stable, unique tool name (what the model calls).
    fn name(&self) -> &str;

    /// The built-in description. May be overridden via [`crate::Config`].
    fn description(&self) -> &str;

    /// JSON Schema describing the tool's input object.
    fn parameters(&self) -> serde_json::Value;

    /// Run the tool. Returns text to feed back to the model.
    async fn execute(&self, args: serde_json::Value, ctx: &ToolContext) -> Result<String>;
}

/// An ordered set of tools offered to the model.
#[derive(Default)]
pub struct ToolRegistry {
    tools: Vec<Box<dyn Tool>>,
}

impl ToolRegistry {
    /// An empty registry.
    pub fn new() -> Self {
        ToolRegistry::default()
    }

    /// A registry pre-populated with all built-in tools.
    pub fn with_builtins() -> Self {
        let mut r = ToolRegistry::new();
        r.register(ReadFileTool);
        r.register(WriteFileTool);
        r.register(EditFileTool);
        r.register(ListDirTool);
        r.register(GlobTool);
        r.register(SearchTool);
        r.register(ApplyPatchTool);
        r.register(BashTool::default());
        r.register(PersistentShellTool::default());
        r.register(UpdatePlanTool::default());
        r
    }

    /// P3 (COMPOSABLE-HARNESS-DESIGN.md §5.2 phase P3): build a registry
    /// from a resolved [`Config`]'s module-activation set, the intended
    /// replacement for unconditional [`Self::with_builtins`] call sites.
    ///
    /// **Mandatory risk-2 mitigation (§5.3 risk 2 — "land P3 behind
    /// `[experimental] module_registry = true`"):** when
    /// [`Config::module_registry`] is `false` (the default), this returns
    /// EXACTLY [`Self::with_builtins`] — same 10 tools, same order, zero
    /// behavior change. Only when the flag is explicitly on does
    /// [`Config::module_activation`]/[`Config::core_tools_enabled`] start
    /// shaping which tool objects get registered AT ALL: a disabled module
    /// contributes no tool (never registered, so never advertised and never
    /// mentioned anywhere) — e.g. `todos` off means `update_plan` is not in
    /// this registry; `tools_search` off (or its `list_dir`/`glob`/
    /// `content_search` sub-flags off) means the corresponding tool is
    /// absent too.
    pub fn from_config(config: &Config) -> Self {
        if !config.module_registry {
            return Self::with_builtins();
        }
        let mut r = ToolRegistry::new();
        let core_has = |name: &str| config.core_tools_enabled.iter().any(|t| t == name);
        let act = &config.module_activation;

        // Same relative order as `with_builtins()` for everything both paths
        // can register, so a partial activation set stays predictable.
        if core_has("read_file") {
            r.register(ReadFileTool);
        }
        if core_has("write_file") {
            r.register(WriteFileTool);
        }
        if core_has("edit_file") {
            r.register(EditFileTool);
        }
        // P4c (S1.2 `view_image`, S12): a fifth OPTIONAL default-tool name —
        // "recognized alongside read_file/bash/edit_file/write_file as a
        // fifth optional default-tool name, not a new module" — so it's
        // read from the SAME `core_tools_enabled` list as the other four,
        // not a `ModuleId`. Absent from the list by default (today's
        // `["read_file","bash","edit_file","write_file"]` default), so this
        // is a no-op unless a caller explicitly adds `"view_image"`.
        if core_has("view_image") {
            r.register(ViewImageTool);
        }
        if act.is_active(ModuleId::ToolsSearch) {
            if act.tools_search_list_dir {
                r.register(ListDirTool);
            }
            if act.tools_search_glob {
                r.register(GlobTool);
            }
            if act.tools_search_content_search {
                r.register(SearchTool);
            }
        }
        if act.is_active(ModuleId::ToolsApplyPatch) {
            r.register(ApplyPatchTool);
        }
        if core_has("bash") {
            r.register(BashTool::default());
        }
        if act.is_active(ModuleId::ToolsPersistentShell) {
            r.register(PersistentShellTool::default());
        }
        if act.is_active(ModuleId::Todos) {
            r.register(UpdatePlanTool::default());
        }
        // P4c (S2 module 5 `tools.web`, S4a "trivially addable"): single
        // tool each, gated by the module's own `fetch`/`search` sub-flags
        // (S3.1: `[capabilities.tools_web] { enabled = false, fetch = true,
        // search = true }`) exactly like `tools_search`'s three sub-flags.
        if act.is_active(ModuleId::ToolsWeb) {
            if act.tools_web_fetch {
                r.register(WebFetchTool);
            }
            if act.tools_web_search {
                r.register(WebSearchTool);
            }
        }
        r
    }

    /// Add a tool. A later registration with the same name shadows the earlier.
    pub fn register(&mut self, tool: impl Tool + 'static) {
        self.tools.push(Box::new(tool));
    }

    /// Look up a tool by name (last registration wins).
    pub fn get(&self, name: &str) -> Option<&dyn Tool> {
        self.tools
            .iter()
            .rev()
            .find(|t| t.name() == name)
            .map(|b| b.as_ref())
    }

    /// Iterate all tools.
    pub fn iter(&self) -> impl Iterator<Item = &dyn Tool> {
        self.tools.iter().map(|b| b.as_ref())
    }

    /// Number of registered tools.
    pub fn len(&self) -> usize {
        self.tools.len()
    }

    /// Whether the registry is empty.
    pub fn is_empty(&self) -> bool {
        self.tools.is_empty()
    }
}

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

    /// Truth table for [`shell_sandbox_unenforceable`]. Pure inputs — no
    /// `cfg!`/`target_os` gating — so this passes identically on macOS,
    /// Linux, and Windows CI hosts. P5-10 added the `landlock_available`
    /// parameter: a Linux host WITH Landlock is no longer a gap (this box
    /// IS one — see `sandbox::tests`/the integration test for the REAL
    /// enforcement proof); a Linux host WITHOUT it still is.
    #[test]
    fn shell_sandbox_unenforceable_truth_table() {
        // Confining policy + non-macOS + a shell tool enabled + Landlock
        // NOT available => true (still an honest gap).
        assert!(shell_sandbox_unenforceable(
            SandboxPolicy::ReadOnly,
            "linux",
            &["bash"],
            false,
        ));
        assert!(shell_sandbox_unenforceable(
            SandboxPolicy::WorkspaceWrite,
            "linux",
            &["shell"],
            false,
        ));
        // No Landlock concept on Windows at all — `landlock_available` is
        // irrelevant there (still unenforceable regardless of its value).
        assert!(shell_sandbox_unenforceable(
            SandboxPolicy::WorkspaceWrite,
            "windows",
            &["bash", "shell"],
            true,
        ));

        // P5-10: Linux WITH real Landlock support => NOT a gap anymore —
        // enforcement now exists, so this must say `false` (never claim a
        // gap that no longer applies).
        assert!(!shell_sandbox_unenforceable(
            SandboxPolicy::ReadOnly,
            "linux",
            &["bash"],
            true,
        ));
        assert!(!shell_sandbox_unenforceable(
            SandboxPolicy::WorkspaceWrite,
            "linux",
            &["shell"],
            true,
        ));

        // DangerFullAccess => false regardless of platform/tools/landlock.
        assert!(!shell_sandbox_unenforceable(
            SandboxPolicy::DangerFullAccess,
            "linux",
            &["bash", "shell"],
            false,
        ));

        // macOS => false regardless of policy (seatbelt sandboxes the
        // shell) — even with `landlock_available = true` passed in (an
        // impossible-in-practice combination, but the function must still
        // ignore it, since macOS's own primitive is what actually applies).
        assert!(!shell_sandbox_unenforceable(
            SandboxPolicy::ReadOnly,
            "macos",
            &["bash", "shell"],
            true,
        ));

        // No bash/shell in tools_enabled => false.
        assert!(!shell_sandbox_unenforceable(
            SandboxPolicy::ReadOnly,
            "linux",
            &[],
            false,
        ));
        assert!(!shell_sandbox_unenforceable(
            SandboxPolicy::ReadOnly,
            "linux",
            &["write_file"],
            false,
        ));
    }
}