everruns-cli 0.44.0

Command-line interface for Everruns — run and manage agents from your terminal
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
// Agent management commands
//
// The shared package codec materializes portable file/folder/ZIP definitions.
// The legacy upload path below retains explicit hidden-path opt-ins and
// --initial-files-dir for existing CLI users.
//
// Trust boundary (initial_files hidden-path policy): the CLI walks the user's
// local filesystem to assemble `initial_files` and uploads the bytes to the
// server. Hidden (dot-prefixed) path components are gated to prevent accidental
// exfiltration of credentials and host secrets (e.g. `.ssh/`, `.env`,
// `.aws/credentials`) while still letting agents ship their packaging assets
// (e.g. `.github/`, `.vscode/`, `.claude/`, `.mcp.json`). The policy is layered:
//   1. `DENIED_DOT_ENTRIES` is a hard-deny floor — never uploaded, even if a
//      user opts in via the manifest. Covers known credential locations.
//   2. `ALLOWED_DOT_ENTRIES` is the built-in safe default — common dev assets
//      that round-trip cleanly between CLI users and the server.
//   3. The agent manifest may declare `initial_files_allow_hidden: [".foo"]`
//      to extend the allowlist for project-specific tools. Entries in the
//      hard-deny floor are still rejected.
// See `knowledge/foundations/cli.md` (Initial Files Hidden Path Policy) and threat
// `TM-FS-009` in `knowledge/security/threat-model.md`.

use super::sessions::is_prefixed_id;
use crate::output::{OutputFormat, print_field};
use anyhow::{Context, Result};
use clap::Subcommand;
use everruns_core::agent_package::{ALLOWED_DOT_ENTRIES, DENIED_DOT_ENTRIES};
use serde::Deserialize;
use std::path::Path;

const DEFAULT_AGENT_FILE_NAME: &str = "agent.toml";

mod packages;
use packages::print_package_report;
pub use packages::run_local;

#[derive(Subcommand)]
pub enum AgentsCommand {
    /// Import a portable agent file, folder or ZIP
    Import {
        #[arg(value_name = "PATH", conflicts_with = "content")]
        file: Option<String>,
        /// Inline definition (also supported by Platform Chat and MCP)
        #[arg(long, conflicts_with = "file")]
        content: Option<String>,
        /// Explicit existing agent name to update
        #[arg(long)]
        target: Option<String>,
        #[arg(long)]
        format: Option<String>,

        /// Why you are making this change. Recorded in the agent's history
        #[arg(long, value_name = "TEXT")]
        reason: Option<String>,
    },
    /// Export an agent by name without IDs or credentials
    Export {
        agent: String,
        #[arg(long, default_value = "markdown", value_parser = ["markdown", "toml", "yaml", "json", "zip", "folder"])]
        format: String,
        #[arg(long)]
        out: Option<std::path::PathBuf>,
    },
    /// Validate a package locally, or also check destination dependencies
    Validate {
        file: String,
        #[arg(long)]
        remote: bool,
    },
    /// Generate a semantic diff against a local package or a remote agent
    Diff {
        file: String,
        #[arg(long, conflicts_with = "target")]
        against: Option<String>,
        #[arg(long, conflicts_with = "against")]
        target: Option<String>,
    },
    /// Create a new agent (upserts if id: is present in frontmatter)
    Create {
        /// TOML/YAML/JSON/Markdown file with agent definition
        #[arg(short, long)]
        file: Option<String>,

        /// Directory of files to upload as initial_files (read-only by default)
        #[arg(long)]
        initial_files_dir: Option<String>,

        /// Make initial files writable (default: read-only)
        #[arg(long)]
        writable: bool,

        /// Agent name (required if no --file)
        #[arg(long)]
        name: Option<String>,

        /// System prompt (required if no --file)
        #[arg(long = "instructions", alias = "system-prompt")]
        system_prompt: Option<String>,

        /// Agent description
        #[arg(long)]
        description: Option<String>,

        /// Default model ID (e.g. mod_xxx)
        #[arg(long)]
        model: Option<String>,

        /// Harness ID or name (e.g. harness_xxx or "generic").
        /// Omit to default to the org's generic harness.
        #[arg(long, short = 'H')]
        harness: Option<String>,

        /// Tags (repeatable)
        #[arg(long, short)]
        tag: Vec<String>,

        /// Why you are making this change. Recorded in the agent's history
        #[arg(long, value_name = "TEXT")]
        reason: Option<String>,
    },

    /// Update an existing agent from a file definition
    Update {
        /// Agent ID (e.g. agent_xxx). If omitted, uses id from file frontmatter.
        agent_id: Option<String>,

        /// TOML/YAML/JSON/Markdown file with agent definition
        #[arg(short, long)]
        file: Option<String>,

        /// Directory of files to upload as initial_files (read-only by default)
        #[arg(long)]
        initial_files_dir: Option<String>,

        /// Make initial files writable (default: read-only)
        #[arg(long)]
        writable: bool,

        /// Agent name
        #[arg(long)]
        name: Option<String>,

        /// System prompt
        #[arg(long = "instructions", alias = "system-prompt")]
        system_prompt: Option<String>,

        /// Agent description
        #[arg(long)]
        description: Option<String>,

        /// Default model ID (e.g. mod_xxx)
        #[arg(long)]
        model: Option<String>,

        /// Harness ID or name (e.g. harness_xxx or "generic")
        #[arg(long, short = 'H')]
        harness: Option<String>,

        /// Tags (repeatable)
        #[arg(long, short)]
        tag: Vec<String>,

        /// Why you are making this change. Recorded in the agent's history
        #[arg(long, value_name = "TEXT")]
        reason: Option<String>,
    },
}

/// Response from the import API
#[derive(Debug, Deserialize, serde::Serialize)]
struct ImportedAgent {
    id: String,
    name: String,
}

pub async fn run(
    command: AgentsCommand,
    api_url: &str,
    api_key: &str,
    org_id: Option<&str>,
    output: OutputFormat,
    quiet: bool,
) -> Result<()> {
    match command {
        command @ (AgentsCommand::Import { .. }
        | AgentsCommand::Export { .. }
        | AgentsCommand::Validate { .. }
        | AgentsCommand::Diff { .. }) => {
            packages::run(command, api_url, api_key, org_id, output).await
        }
        AgentsCommand::Create {
            file,
            initial_files_dir,
            writable,
            name,
            system_prompt,
            description,
            model,
            harness,
            tag,
            reason,
        } => {
            let use_default_file = name.is_none()
                && system_prompt.is_none()
                && description.is_none()
                && model.is_none()
                && harness.is_none()
                && tag.is_empty();
            let file = resolve_agent_file(file, use_default_file);
            if let Some(path) = file {
                if name.is_some()
                    || system_prompt.is_some()
                    || description.is_some()
                    || model.is_some()
                    || harness.is_some()
                    || !tag.is_empty()
                {
                    eprintln!("Warning: CLI flag overrides are ignored when --file is used");
                }
                import_from_file(
                    api_url,
                    api_key,
                    org_id,
                    &path,
                    initial_files_dir.as_deref(),
                    writable,
                    reason.as_deref(),
                    output,
                    quiet,
                )
                .await
            } else {
                if initial_files_dir.is_some() {
                    anyhow::bail!("--initial-files-dir requires --file");
                }
                let client = super::api::ApiClient::new(api_url, api_key, org_id);
                save_from_flags(
                    &client,
                    None,
                    output,
                    quiet,
                    name,
                    system_prompt,
                    description,
                    model,
                    harness,
                    tag,
                    reason,
                )
                .await
            }
        }
        AgentsCommand::Update {
            agent_id,
            file,
            initial_files_dir,
            writable,
            name,
            system_prompt,
            description,
            model,
            harness,
            tag,
            reason,
        } => {
            let use_default_file = agent_id.is_none()
                && name.is_none()
                && system_prompt.is_none()
                && description.is_none()
                && model.is_none()
                && harness.is_none()
                && tag.is_empty();
            let file = resolve_agent_file(file, use_default_file);
            if let Some(path) = file {
                if agent_id.is_some()
                    || name.is_some()
                    || system_prompt.is_some()
                    || description.is_some()
                    || model.is_some()
                    || harness.is_some()
                    || !tag.is_empty()
                {
                    eprintln!("Warning: CLI flag overrides are ignored when --file is used");
                }
                import_from_file(
                    api_url,
                    api_key,
                    org_id,
                    &path,
                    initial_files_dir.as_deref(),
                    writable,
                    reason.as_deref(),
                    output,
                    quiet,
                )
                .await
            } else {
                if initial_files_dir.is_some() {
                    anyhow::bail!("--initial-files-dir requires --file");
                }
                // Update without file requires agent_id
                let id = agent_id.context("Agent ID is required for update without --file")?;
                let client = super::api::ApiClient::new(api_url, api_key, org_id);
                save_from_flags(
                    &client,
                    Some(&id),
                    output,
                    quiet,
                    name,
                    system_prompt,
                    description,
                    model,
                    harness,
                    tag,
                    reason,
                )
                .await
            }
        }
    }
}

/// Import agent from file via server import API.
/// The CLI normalizes TOML into JSON before calling the server import API.
/// When initial_files_dir is provided, files are globbed and injected into the
/// payload as initial_files before sending.
#[allow(clippy::too_many_arguments)]
async fn import_from_file(
    api_url: &str,
    api_key: &str,
    org_id: Option<&str>,
    path: &str,
    initial_files_dir: Option<&str>,
    writable: bool,
    reason: Option<&str>,
    output: OutputFormat,
    quiet: bool,
) -> Result<()> {
    let client = super::api::ApiClient::new(api_url, api_key, org_id);
    let legacy_hidden_policy = std::fs::read_to_string(path)
        .ok()
        .is_some_and(|s| s.contains("initial_files_allow_hidden"));
    if initial_files_dir.is_none() && !legacy_hidden_policy {
        let package = everruns_core::agent_package::AgentPackage::load(path)?;
        let mut payload: serde_json::Value =
            serde_json::from_str(&package.to_string(everruns_core::agent_package::Format::Json)?)?;
        // Explicit legacy update IDs remain accepted; new exports contain none.
        if let Some(id) = package.legacy_id {
            payload
                .as_object_mut()
                .context("manifest")?
                .remove("schema_version");
            payload["id"] = serde_json::json!(id);
        }
        if let Some(id) = package.legacy_model_id {
            payload
                .as_object_mut()
                .context("manifest")?
                .remove("schema_version");
            payload["default_model_id"] = serde_json::json!(id);
        }
        if let Some(id) = package.legacy_harness_id {
            payload
                .as_object_mut()
                .context("manifest")?
                .remove("schema_version");
            payload["harness_id"] = serde_json::json!(id);
        }
        if writable && let Some(files) = payload["files"].as_array_mut() {
            for file in files {
                file["is_readonly"] = serde_json::json!(false);
            }
        }
        let response = client
            .post_with_reason("/v1/agents/import", Some(&payload), reason)
            .await?;
        print_package_report(output, &response);
        return Ok(());
    }
    let file_path = Path::new(path);
    let content =
        std::fs::read_to_string(path).with_context(|| format!("Failed to read file: {}", path))?;

    // Resolve the agent file's parent directory for expanding initial_files globs.
    let file_dir = std::fs::canonicalize(path)
        .with_context(|| format!("Cannot resolve file path: {}", path))?
        .parent()
        .map(|p| p.to_path_buf())
        .unwrap_or_else(|| std::path::PathBuf::from("."));

    // Parse once when possible so TOML conversion and initial_files inspection
    // don't duplicate work before we build the request body.
    let parsed_agent = parse_agent_file_as_json(file_path, &content).ok();
    let has_glob_initial_files = parsed_agent.as_ref().is_some_and(initial_files_has_globs);
    let should_send_json =
        initial_files_dir.is_some() || has_glob_initial_files || is_toml_agent_file(file_path);

    let (body, content_type) = if should_send_json {
        let mut agent = if let Some(agent) = parsed_agent {
            agent
        } else {
            parse_agent_file_as_json(file_path, &content).context("Failed to parse agent file")?
        };

        if let Some(dir) = initial_files_dir {
            let allow_hidden = extract_allow_hidden_extras(&agent);
            let files = glob_initial_files(dir, writable, &allow_hidden)?;
            agent["initial_files"] = serde_json::to_value(&files)?;
        } else if has_glob_initial_files {
            let files = expand_initial_files_globs(&agent, &file_dir, writable)?;
            agent["initial_files"] = serde_json::to_value(&files)?;
        }

        // The opt-in field is only consumed locally to gate the upload.
        // Strip it before sending so the server import payload stays clean.
        if let Some(obj) = agent.as_object_mut() {
            obj.remove("initial_files_allow_hidden");
        }

        (serde_json::to_string(&agent)?, "application/json")
    } else {
        (content, "text/plain")
    };

    let resp = super::api::with_change_reason(
        client.request(reqwest::Method::POST, "/v1/agents/import"),
        reason,
    )
    .header("Content-Type", content_type)
    .body(body)
    .send()
    .await
    .context("Failed to send import request")?;

    let status = resp.status();
    if !status.is_success() {
        let body = resp.text().await.unwrap_or_default();
        anyhow::bail!("Import failed ({}): {}", status, body);
    }

    let was_created = status == reqwest::StatusCode::CREATED;
    let agent: ImportedAgent = resp
        .json()
        .await
        .context("Failed to parse import response")?;

    let verb = if was_created { "Created" } else { "Applied" };

    if output.is_text() {
        if quiet {
            println!("{}", agent.id);
        } else {
            println!("{} agent: {}", verb, agent.id);
            print_field("Name", &agent.name);
        }
    } else {
        let json = serde_json::json!({
            "id": agent.id,
            "name": agent.name,
            "action": verb.to_lowercase(),
        });
        output.print_value(&json);
    }

    Ok(())
}

fn resolve_agent_file(file: Option<String>, use_default: bool) -> Option<String> {
    file.or_else(|| {
        if use_default && Path::new(DEFAULT_AGENT_FILE_NAME).is_file() {
            Some(DEFAULT_AGENT_FILE_NAME.to_string())
        } else {
            None
        }
    })
}

/// Represents a file to be uploaded as an initial file for an agent.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct CollectedFile {
    path: String,
    content: String,
    encoding: String,
    is_readonly: bool,
}

/// Extract user-declared hidden-path opt-ins from the agent manifest's
/// `initial_files_allow_hidden` field. Each entry must be a single normal path
/// component (basename) — entries containing `/` or `\\`, equal to `.` or
/// `..`, missing the leading dot, or matching a hard-denied basename in
/// `DENIED_DOT_ENTRIES` are filtered out.
fn extract_allow_hidden_extras(agent: &serde_json::Value) -> Vec<String> {
    let Some(arr) = agent
        .get("initial_files_allow_hidden")
        .and_then(|v| v.as_array())
    else {
        return Vec::new();
    };
    arr.iter()
        .filter_map(|v| v.as_str().map(|s| s.to_string()))
        .filter(|s| is_valid_basename_extra(s))
        .filter(|s| !DENIED_DOT_ENTRIES.contains(&s.as_str()))
        .collect()
}

/// True when `s` is a single hidden basename (starts with `.`, contains no
/// path separator, and is not the relative-path placeholders `.` / `..`).
fn is_valid_basename_extra(s: &str) -> bool {
    if !s.starts_with('.') || s == "." || s == ".." {
        return false;
    }
    !s.contains('/') && !s.contains('\\')
}

/// Precomputed allow/deny lookup for the hidden-path policy. Built once per
/// import so repeated calls during directory walks avoid allocating a fresh
/// `Vec` on every component check.
struct HiddenPathPolicy {
    allowed: std::collections::HashSet<String>,
}

impl HiddenPathPolicy {
    fn new(extras: &[String]) -> Self {
        let mut allowed: std::collections::HashSet<String> = ALLOWED_DOT_ENTRIES
            .iter()
            .map(|s| (*s).to_string())
            .collect();
        for extra in extras {
            if is_valid_basename_extra(extra) && !DENIED_DOT_ENTRIES.contains(&extra.as_str()) {
                allowed.insert(extra.clone());
            }
        }
        Self { allowed }
    }

    /// Iterator over the names of allow-walkable dot directories that the
    /// extras-aware walker should descend into in addition to the default
    /// non-hidden tree.
    fn allow_walk_names(&self) -> impl Iterator<Item = &String> {
        self.allowed.iter()
    }

    /// True when a single path component is hidden and either (a) hard-denied,
    /// or (b) not in the effective allowlist.
    fn component_is_disallowed(&self, component: &str) -> bool {
        if !component.starts_with('.') {
            return false;
        }
        if DENIED_DOT_ENTRIES.contains(&component) {
            return true;
        }
        !self.allowed.contains(component)
    }

    /// True when any path component is disallowed under the policy. Walks
    /// every `Normal` component so denied entries nested inside an allowlisted
    /// root (e.g. `.github/.env`) are still rejected.
    fn path_has_disallowed_component(&self, path: &Path) -> bool {
        path.components().any(|component| {
            let std::path::Component::Normal(name) = component else {
                return false;
            };
            self.component_is_disallowed(&name.to_string_lossy())
        })
    }
}

/// Recursively collect text files from a directory, including allowed
/// dotfile directories (e.g. `.agents/`). Returns them as initial_files
/// entries with paths relative to /workspace.
fn glob_initial_files(
    dir: &str,
    writable: bool,
    allow_hidden_extras: &[String],
) -> Result<Vec<CollectedFile>> {
    let base =
        std::fs::canonicalize(dir).with_context(|| format!("Cannot resolve directory: {}", dir))?;
    if !base.is_dir() {
        anyhow::bail!("Not a directory: {}", base.display());
    }

    let policy = HiddenPathPolicy::new(allow_hidden_extras);

    // hidden(true) prunes most dotfiles/dirs during traversal for performance.
    // We do a second walk of policy.allow_walk_names() below to include them.
    let walker = ignore::WalkBuilder::new(&base)
        .hidden(true) // skip dotfiles by default (perf: avoids traversing .git/)
        .git_ignore(true) // respect .gitignore (repo-local)
        .git_global(false) // ignore global gitignore for predictable behavior
        .git_exclude(false) // ignore repo exclude files for predictable behavior
        .build();

    // Also walk allowed dot-directories that hidden(true) would skip.
    // Each candidate file is filtered through the policy below so that nested
    // hard-denied components (e.g. `.github/.env`) are still rejected even
    // under an allowlisted root.
    let dot_walkers: Vec<_> = policy
        .allow_walk_names()
        .filter_map(|name| {
            let dot_path = base.join(name);
            if dot_path.is_dir() {
                Some(
                    ignore::WalkBuilder::new(&dot_path)
                        .hidden(false) // include nested dotfiles within allowed dirs
                        .git_ignore(true)
                        .git_global(false)
                        .git_exclude(false)
                        .build(),
                )
            } else {
                None
            }
        })
        .collect();

    let mut files = Vec::new();
    let all_entries = walker.chain(dot_walkers.into_iter().flatten());
    for entry in all_entries {
        let entry = entry.context("Failed to read directory entry")?;
        let path = entry.path();
        if !path.is_file() {
            continue;
        }

        // Canonicalize each file to prevent symlink escapes outside the base dir
        let canonical = std::fs::canonicalize(path)
            .with_context(|| format!("Cannot resolve file: {}", path.display()))?;
        if !canonical.starts_with(&base) {
            eprintln!(
                "Warning: skipping symlink outside base directory: {}",
                path.display()
            );
            continue;
        }

        let rel = canonical
            .strip_prefix(&base)
            .context("File outside base directory")?;

        // Defense in depth: enforce the deny floor on every component, even
        // for files surfaced via the allowlisted-root walkers.
        if policy.path_has_disallowed_component(rel) {
            eprintln!(
                "Warning: skipping hidden path: {} (allowed: {:?})",
                canonical.display(),
                ALLOWED_DOT_ENTRIES
            );
            continue;
        }

        // Normalize path separators to POSIX-style for workspace paths
        let rel_normalized = rel.to_string_lossy().replace('\\', "/");
        let workspace_path = format!("/workspace/{}", rel_normalized);

        // Read as text; skip binary files
        match std::fs::read_to_string(path) {
            Ok(content) => {
                files.push(CollectedFile {
                    path: workspace_path,
                    content,
                    encoding: "text".to_string(),
                    is_readonly: !writable,
                });
            }
            Err(_) => {
                eprintln!(
                    "Warning: skipping binary or unreadable file: {}",
                    path.display()
                );
            }
        }
    }

    if files.is_empty() {
        anyhow::bail!("No files found in directory: {}", dir);
    }

    files.sort_by(|a, b| a.path.cmp(&b.path));
    Ok(files)
}

/// Quick check whether parsed initial_files contains glob patterns (strings)
/// rather than fully-specified InitialFile objects.
fn initial_files_has_globs(agent: &serde_json::Value) -> bool {
    let Some(arr) = agent.get("initial_files").and_then(|v| v.as_array()) else {
        return false;
    };
    arr.iter().any(|v| v.is_string())
}

fn is_toml_agent_file(path: &Path) -> bool {
    path.extension()
        .and_then(|ext| ext.to_str())
        .is_some_and(|ext| ext.eq_ignore_ascii_case("toml"))
}

/// Strip glob metacharacters from a pattern to find the directory prefix.
/// e.g. ".agents/*" → ".agents", "src/**/*.rs" → "src", "." → "."
fn glob_base_dir(pattern: &str) -> &str {
    // Find the first glob metacharacter
    if let Some(pos) = pattern.find(['*', '?', '[']) {
        // Walk back to the last path separator before the metacharacter
        let prefix = &pattern[..pos];
        prefix.trim_end_matches('/').trim_end_matches('\\')
    } else {
        pattern
    }
}

/// Expand initial_files glob patterns from agent frontmatter into CollectedFile entries.
/// String entries are treated as relative paths resolved against `base_dir`.
/// All workspace paths are computed relative to `base_dir` so subdirectory
/// prefixes are preserved (e.g. ".agents/config.json" → "/workspace/.agents/config.json").
/// Object entries (already-expanded InitialFile) are passed through as-is.
fn expand_initial_files_globs(
    agent: &serde_json::Value,
    base_dir: &Path,
    writable: bool,
) -> Result<Vec<CollectedFile>> {
    let Some(arr) = agent.get("initial_files").and_then(|v| v.as_array()) else {
        return Ok(vec![]);
    };

    let allow_hidden_extras = extract_allow_hidden_extras(agent);
    let policy = HiddenPathPolicy::new(&allow_hidden_extras);
    let base_canonical = std::fs::canonicalize(base_dir)?;
    let mut all_files: Vec<CollectedFile> = Vec::new();

    for entry in arr {
        if let Some(pattern) = entry.as_str() {
            // Strip glob metacharacters to find the actual directory/file path.
            // e.g. ".agents/*" → ".agents", "." → "."
            let clean_path = glob_base_dir(pattern);
            let resolved = base_dir.join(clean_path);
            let resolved = std::fs::canonicalize(&resolved).with_context(|| {
                format!(
                    "Cannot resolve initial_files path: {} (relative to {})",
                    pattern,
                    base_dir.display()
                )
            })?;

            if resolved.is_dir() {
                // Reject hidden directory roots unless explicitly allowlisted.
                let rel = resolved.strip_prefix(&base_canonical)?;
                if policy.path_has_disallowed_component(rel) {
                    eprintln!(
                        "Warning: skipping hidden directory: {} (allowed: {:?}; user opt-ins: {:?})",
                        resolved.display(),
                        ALLOWED_DOT_ENTRIES,
                        allow_hidden_extras,
                    );
                    continue;
                }
                // Directory: collect all files, computing workspace paths relative to base_dir
                collect_dir_files(
                    &resolved,
                    &base_canonical,
                    writable,
                    &policy,
                    &mut all_files,
                )?;
            } else if resolved.is_file() {
                // Single file — reject disallowed hidden files
                collect_single_file(
                    &resolved,
                    &base_canonical,
                    writable,
                    &policy,
                    &mut all_files,
                )?;
            } else {
                anyhow::bail!(
                    "initial_files pattern resolved to non-existent path: {}",
                    resolved.display()
                );
            }
        } else if entry.is_object() {
            // Already a full InitialFile object — pass through
            let file: CollectedFile = serde_json::from_value(entry.clone())
                .context("Invalid initial_files entry object")?;
            all_files.push(file);
        } else {
            anyhow::bail!("initial_files entries must be strings (paths/globs) or objects");
        }
    }

    // Deduplicate by path (first occurrence wins)
    let mut seen = std::collections::HashSet::new();
    all_files.retain(|f| seen.insert(f.path.clone()));

    if all_files.is_empty() {
        anyhow::bail!("initial_files patterns matched no files");
    }

    all_files.sort_by(|a, b| a.path.cmp(&b.path));
    Ok(all_files)
}

/// Collect all text files from a directory into the CollectedFile list.
/// Workspace paths are computed relative to `workspace_base` (the agent file's
/// parent directory), preserving subdirectory prefixes.
fn collect_dir_files(
    dir: &Path,
    workspace_base: &Path,
    writable: bool,
    policy: &HiddenPathPolicy,
    files: &mut Vec<CollectedFile>,
) -> Result<()> {
    // Main walker skips hidden files for security (.env, .ssh, etc.)
    let walker = ignore::WalkBuilder::new(dir)
        .hidden(true)
        .git_ignore(true)
        .git_global(false)
        .git_exclude(false)
        .build();

    // Also walk allowed dot-directories that hidden(true) would skip.
    // Each candidate file is filtered by the policy below so nested hard-denied
    // components (e.g. `.github/.env`) are still rejected.
    let dot_walkers: Vec<_> = policy
        .allow_walk_names()
        .filter_map(|name| {
            let dot_path = dir.join(name);
            if dot_path.is_dir() {
                Some(
                    ignore::WalkBuilder::new(&dot_path)
                        .hidden(false)
                        .git_ignore(true)
                        .git_global(false)
                        .git_exclude(false)
                        .build(),
                )
            } else {
                None
            }
        })
        .collect();

    let all_entries = walker.chain(dot_walkers.into_iter().flatten());
    for entry in all_entries {
        let entry = entry.context("Failed to read directory entry")?;
        let path = entry.path();
        if !path.is_file() {
            continue;
        }

        let canonical = std::fs::canonicalize(path)
            .with_context(|| format!("Cannot resolve file: {}", path.display()))?;
        if !canonical.starts_with(workspace_base) {
            eprintln!(
                "Warning: skipping symlink outside base directory: {}",
                path.display()
            );
            continue;
        }

        // Compute workspace path relative to workspace_base (agent file dir)
        let rel = canonical
            .strip_prefix(workspace_base)
            .context("File outside base directory")?;

        // Defense in depth: re-check every component against the deny floor,
        // since the allowlisted-root walkers descend with `hidden(false)`.
        if policy.path_has_disallowed_component(rel) {
            eprintln!(
                "Warning: skipping hidden path: {} (allowed: {:?})",
                canonical.display(),
                ALLOWED_DOT_ENTRIES
            );
            continue;
        }

        let rel_normalized = rel.to_string_lossy().replace('\\', "/");
        let workspace_path = format!("/workspace/{}", rel_normalized);

        match std::fs::read_to_string(path) {
            Ok(content) => {
                files.push(CollectedFile {
                    path: workspace_path,
                    content,
                    encoding: "text".to_string(),
                    is_readonly: !writable,
                });
            }
            Err(_) => {
                eprintln!(
                    "Warning: skipping binary or unreadable file: {}",
                    path.display()
                );
            }
        }
    }

    Ok(())
}

/// Collect a single file into the CollectedFile list.
/// Rejects hidden files not in the effective allowlist (see
/// `HiddenPathPolicy`). Hard-denied entries from `DENIED_DOT_ENTRIES` are
/// always rejected, even if the user opts in.
fn collect_single_file(
    file_path: &Path,
    workspace_base: &Path,
    writable: bool,
    policy: &HiddenPathPolicy,
    files: &mut Vec<CollectedFile>,
) -> Result<()> {
    let canonical = std::fs::canonicalize(file_path)
        .with_context(|| format!("Cannot resolve file: {}", file_path.display()))?;

    if !canonical.starts_with(workspace_base) {
        eprintln!(
            "Warning: skipping file outside base directory: {}",
            file_path.display()
        );
        return Ok(());
    }

    // Check for disallowed hidden path components (e.g. .env, .ssh/config)
    let rel = canonical.strip_prefix(workspace_base)?;
    if policy.path_has_disallowed_component(rel) {
        eprintln!(
            "Warning: skipping hidden file: {} (allowed: {:?})",
            file_path.display(),
            ALLOWED_DOT_ENTRIES,
        );
        return Ok(());
    }

    let rel_normalized = rel.to_string_lossy().replace('\\', "/");
    let workspace_path = format!("/workspace/{}", rel_normalized);

    match std::fs::read_to_string(file_path) {
        Ok(content) => {
            files.push(CollectedFile {
                path: workspace_path,
                content,
                encoding: "text".to_string(),
                is_readonly: !writable,
            });
        }
        Err(_) => {
            eprintln!(
                "Warning: skipping binary or unreadable file: {}",
                file_path.display()
            );
        }
    }
    Ok(())
}

/// Parse agent file content (Markdown/TOML/YAML/JSON) into a JSON Value.
/// This is minimal parsing to allow injecting initial_files before sending
/// to the server import API.
fn parse_agent_file_as_json(path: &Path, content: &str) -> Result<serde_json::Value> {
    let content = content.trim();

    // Markdown with front matter: require `---` delimiters on their own lines
    {
        let mut lines = content.lines();
        if let Some(first) = lines.next()
            && first.trim() == "---"
        {
            let mut frontmatter_lines = Vec::new();
            let mut found_end = false;

            for line in &mut lines {
                if line.trim() == "---" {
                    found_end = true;
                    break;
                }
                frontmatter_lines.push(line);
            }

            if found_end {
                let frontmatter = frontmatter_lines.join("\n");
                let body: String = lines.collect::<Vec<_>>().join("\n");
                let body = body.trim();

                let mut obj: serde_json::Value = serde_yaml::from_str(&frontmatter)
                    .context("Failed to parse YAML frontmatter")?;

                if !obj.is_object() {
                    anyhow::bail!(
                        "Agent file frontmatter must be a YAML mapping, not a scalar or array"
                    );
                }

                // If there's a markdown body and no system_prompt in frontmatter, use it
                if !body.is_empty()
                    && (obj.get("system_prompt").is_none()
                        || obj["system_prompt"].as_str().is_none_or(|s| s.is_empty()))
                {
                    obj["system_prompt"] = serde_json::Value::String(body.to_string());
                }

                return Ok(obj);
            }
        }
    }

    // JSON
    if content.starts_with('{') {
        return serde_json::from_str(content).context("Failed to parse JSON");
    }

    if is_toml_agent_file(path) {
        let val: toml::Value = toml::from_str(content).context("Failed to parse TOML")?;
        let val = serde_json::to_value(val).context("Failed to convert TOML to JSON")?;
        if !val.is_object() {
            anyhow::bail!("Agent file must be a TOML object");
        }
        return Ok(val);
    }

    // YAML
    let val: serde_json::Value = serde_yaml::from_str(content).context("Failed to parse YAML")?;
    if !val.is_object() {
        anyhow::bail!("Agent file must be a YAML/JSON object");
    }
    Ok(val)
}

/// Create an agent from CLI flags (`create_agent`), or apply them to
/// `agent_id` (`upsert_agent`, which replaces the definition by id).
#[allow(clippy::too_many_arguments)]
async fn save_from_flags(
    client: &super::api::ApiClient<'_>,
    agent_id: Option<&str>,
    output: OutputFormat,
    quiet: bool,
    name: Option<String>,
    system_prompt: Option<String>,
    description: Option<String>,
    model: Option<String>,
    harness: Option<String>,
    tags: Vec<String>,
    reason: Option<String>,
) -> Result<()> {
    let without_file = if agent_id.is_some() {
        " for update without --file"
    } else {
        ""
    };
    let name = name.with_context(|| format!("--name is required{without_file}"))?;
    let system_prompt =
        system_prompt.with_context(|| format!("--system-prompt is required{without_file}"))?;

    let params = crate::contract::with_reason(
        agent_params(
            agent_id,
            name,
            system_prompt,
            description,
            model,
            harness,
            tags,
        ),
        reason.as_deref(),
    );
    let command = if agent_id.is_some() {
        "upsert_agent"
    } else {
        "create_agent"
    };
    let agent = crate::contract::execute(client, command, params).await?;

    if output.is_text() {
        let id = agent["id"].as_str().unwrap_or_default();
        if quiet {
            println!("{id}");
        } else {
            let verb = if agent_id.is_some() {
                "Applied"
            } else {
                "Created"
            };
            println!("{verb} agent: {id}");
            print_field("Name", agent["name"].as_str().unwrap_or_default());
        }
    } else {
        output.print_value(&agent);
    }

    Ok(())
}

/// `create_agent` params from CLI flags. `--harness` takes a strict harness id
/// (`harness_<32-hex>`) or an addressable name (e.g. `generic`), detected the
/// same way as `sessions create --harness`.
fn agent_params(
    agent_id: Option<&str>,
    name: String,
    system_prompt: String,
    description: Option<String>,
    model: Option<String>,
    harness: Option<String>,
    tags: Vec<String>,
) -> serde_json::Value {
    let mut params = serde_json::json!({ "name": name, "system_prompt": system_prompt });
    if let Some(id) = agent_id {
        params["id"] = id.into();
    }
    if let Some(description) = description {
        params["description"] = description.into();
    }
    if let Some(model) = model {
        params["default_model_id"] = model.into();
    }
    match harness {
        Some(h) if is_prefixed_id(&h, "harness") => params["harness_id"] = h.into(),
        Some(h) => params["harness_name"] = h.into(),
        None => {}
    }
    if !tags.is_empty() {
        params["tags"] = tags.into();
    }
    params
}

#[cfg(test)]
mod tests;