-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconfig.rs
More file actions
3638 lines (3500 loc) · 142 KB
/
Copy pathconfig.rs
File metadata and controls
3638 lines (3500 loc) · 142 KB
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
// Config: CLI flags + env vars + config files. No clap, no toml — hand-rolled.
// Precedence: CLI > env > settings.local.json > settings.json
// > ~/.config/settings.json > managed-settings.json > managed-settings.d/*.json
// Arrays concatenate+deduplicate; objects deep merge; null means delete.
use serde_json::{json, Value};
use std::path::PathBuf;
#[derive(Clone, Debug, PartialEq)]
pub enum Approval {
Never, // auto-approve everything (trust the model fully)
Destructive, // ask only for bash + write_file + edit (default)
Always, // ask for every tool call
}
impl Approval {
pub fn as_str(&self) -> &'static str {
match self {
Approval::Never => "never",
Approval::Destructive => "destructive",
Approval::Always => "always",
}
}
pub fn parse(s: &str) -> Self {
Self::try_parse(s).unwrap_or(Approval::Destructive)
}
/// Strict parse for protocol commands — unknown modes error instead of
/// silently becoming Destructive (CORE_REVIEW).
pub fn try_parse(s: &str) -> Option<Self> {
match s.to_ascii_lowercase().as_str() {
"never" | "off" | "none" | "auto" => Some(Approval::Never),
"always" | "all" | "y" => Some(Approval::Always),
"destructive" | "default" | "" => Some(Approval::Destructive),
_ => None,
}
}
}
/// Permission rule: per-tool, per-content matching with allow/deny/ask behavior.
#[derive(Clone, Debug)]
pub struct PermissionRule {
pub tool_name: String,
pub rule_content: String,
pub behavior: PermissionBehavior,
}
#[derive(Clone, Debug, PartialEq)]
pub enum PermissionBehavior {
Allow,
Deny,
Ask,
}
impl PermissionBehavior {
pub fn parse(s: &str) -> Self {
match s.to_ascii_lowercase().as_str() {
"allow" | "yes" | "true" => PermissionBehavior::Allow,
"deny" | "no" | "false" => PermissionBehavior::Deny,
_ => PermissionBehavior::Ask,
}
}
pub fn as_str(&self) -> &'static str {
match self {
PermissionBehavior::Allow => "allow",
PermissionBehavior::Deny => "deny",
PermissionBehavior::Ask => "ask",
}
}
}
/// Parse a rule string like "Bash(npm test)" or "Edit(//src/**)" into PermissionRule.
/// The format is: ToolName(ruleContent).
pub fn parse_permission_rule(s: &str, behavior: PermissionBehavior) -> Option<PermissionRule> {
let s = s.trim();
let open = s.find('(')?;
let close = s.rfind(')')?;
let tool_name = s[..open].to_string();
let rule_content = s[open + 1..close].to_string();
if tool_name.is_empty() {
return None;
}
Some(PermissionRule {
tool_name,
rule_content,
behavior,
})
}
/**
* Sandbox execution mode.
*
* Replaces the legacy Firejail (Linux) / Seatbelt (macOS `sandbox-exec`) /
* `unshare -n` trio with a single Microsandbox microVM backend that runs on
* Linux/KVM, Apple-Silicon macOS, and Windows/WHP. The user never installs
* Docker, Podman, Firejail, WSL, the `msb` CLI, or a persistent daemon — the
* embedded SDK downloads its own runtime on first use.
*/
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Sandbox {
/// No sandboxing: agent-controlled workloads run directly on the host
/// (denylist + approval gate still apply). Selected only when the user
/// explicitly disables sandboxing.
None,
/// Run agent-controlled workloads inside a Microsandbox microVM. The
/// microVM is created lazily on the first workload and reused for the
/// session so package installs / build caches persist.
Microsandbox,
}
impl Sandbox {
/// Parse a sandbox setting string. Aliases:
/// none, off, false, disabled -> None
/// microsandbox, msb, on, true, enabled -> Microsandbox
/// Legacy values (migrated, not silently downgraded to None):
/// firejail, fj, seatbelt, macos, sandbox-exec -> Microsandbox
pub fn parse(s: &str) -> Self {
match s.to_ascii_lowercase().as_str() {
"microsandbox" | "msb" | "on" | "true" | "enabled" | "enable" => Sandbox::Microsandbox,
"firejail" | "fj" | "seatbelt" | "macos" | "sandbox-exec" => Sandbox::Microsandbox,
_ => Sandbox::None,
}
}
/// Whether `s` is a legacy backend alias (firejail/seatbelt) that we migrate
/// to `Microsandbox`. Returns the legacy backend name for the deprecation
/// notice, or `None` for current/`none` values.
pub fn legacy_alias(s: &str) -> Option<&'static str> {
match s.to_ascii_lowercase().as_str() {
"firejail" | "fj" => Some("firejail"),
"seatbelt" | "macos" | "sandbox-exec" => Some("seatbelt"),
_ => None,
}
}
pub fn as_str(&self) -> &'static str {
match self {
Sandbox::None => "none",
Sandbox::Microsandbox => "microsandbox",
}
}
pub fn is_enabled(self) -> bool {
matches!(self, Sandbox::Microsandbox)
}
}
/// Parse a sandbox setting, emitting a deprecation notice when the user passed
/// a legacy (firejail/seatbelt) value. Returns the resolved mode. The legacy
/// value is preserved as an *intention to enable sandboxing* — it is never
/// silently converted to `none`.
pub fn parse_sandbox_setting(raw: &str) -> Sandbox {
if let Some(legacy) = Sandbox::legacy_alias(raw) {
eprintln!(
"[catalyst-code] deprecation: the '{legacy}' sandbox backend has been replaced by \
Microsandbox. Continuing with sandbox=microsandbox. Update your config to \
\"sandbox\": \"microsandbox\" to silence this notice."
);
}
Sandbox::parse(raw)
}
/// Network egress policy for the Microsandbox guest. Translates the legacy
/// `--no-network` flag (now `None`) and adds restrictive modes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SandboxNetworkMode {
/// No network interface at all (guest cannot reach anything). This is the
/// mode used when `--no-network` / `CATALYST_CODE_NO_NETWORK` is set.
None,
/// Default: network up, but cloud-metadata addresses, host-only services,
/// and (by default) private network ranges are blocked. Public package
/// registries and source hosts are permitted.
Restricted,
/// Network up; only hosts/CIDRs in `sandbox_network_allowlist` are
/// reachable.
Allowlist,
}
impl SandboxNetworkMode {
pub fn parse(s: &str) -> Self {
match s.to_ascii_lowercase().as_str() {
"allowlist" | "allow" => SandboxNetworkMode::Allowlist,
"none" | "off" | "disabled" => SandboxNetworkMode::None,
_ => SandboxNetworkMode::Restricted,
}
}
pub fn as_str(&self) -> &'static str {
match self {
SandboxNetworkMode::None => "none",
SandboxNetworkMode::Restricted => "restricted",
SandboxNetworkMode::Allowlist => "allowlist",
}
}
pub fn from_no_network(no_network: bool) -> Self {
if no_network {
SandboxNetworkMode::None
} else {
SandboxNetworkMode::Restricted
}
}
}
#[derive(Clone, Debug)]
pub struct Config {
pub base_url: String,
pub workspace: PathBuf,
pub approval: Approval,
pub bash_timeout_secs: u64,
pub diag_timeout_secs: u64, // wall-clock timeout for the diagnostics tool (cargo check / tsc / go build)
/// Hard cap for a per-call bash timeout override (the `timeout` arg on the
/// bash tool). A model can request more time for a slow build/test, but it
/// can't escalate past this ceiling (default 600s) without changing config.
pub max_bash_timeout_secs: u64,
/// Allowlist of host glob patterns the `fetch` tool may contact (e.g.
/// `["*.rust-lang.org", "docs.rs", "crates.io"]`). Empty = allow any http(s)
/// host (the tool is still useful out of the box, and works under
/// `--no-network` where bash curl is dead — PROVIDED you populate this
/// allowlist, since `--no-network` + empty allowlist denies fetch to avoid a
/// surprise bypass of the egress block). Populate it to restrict egress.
pub fetch_allowlist: Vec<String>,
/// Wall-clock timeout for the `fetch` tool (default 20s).
pub fetch_timeout_secs: u64,
/// Max response body the `fetch` tool returns (default 256 KiB).
pub fetch_max_bytes: usize,
pub bash_deny: Vec<String>,
pub max_read_bytes: u64,
pub max_read_lines: usize,
pub context_compact_at: f32, // fraction of context_window that triggers compaction
pub context_digest_at: f32, // fraction of context_window that triggers stale-tool-result digesting (sub-threshold reclaim; 0 disables)
pub auto_compact: bool, // automatically compact when context approaches the limit (threshold + idle); manual /compact always works regardless
/// Opt-in JSONL debug log path. Records every tool call with its full
/// arguments (file contents, bash commands) — which may include secrets the
/// model writes (e.g. into a `.env`). User-owned, off by default, rotates at
/// 64 MiB. Enable only when debugging.
pub debug_log: Option<PathBuf>,
/// Full-verbosity debug mode (`--debug` / `CATALYST_CODE_DEBUG=1`). When
/// true, the debug log also records provider HTTP request/response bodies,
/// full tool args+outputs, inbound commands, and a mirror of protocol
/// events. Implies a default `debug_log` path when none is set.
pub debug_verbose: bool,
/// Append-only security audit sidecar (tool decisions, args hashes).
pub audit_log: bool,
pub session_file: Option<PathBuf>,
pub default_model: Option<String>,
// --- production knobs (items 3,4,7) ---
pub sandbox: Sandbox, // Microsandbox microVM (or none)
pub no_network: bool, // legacy --no-network: maps to sandbox_network_mode=None
/// OCI image for the Microsandbox guest. Default is a CatCode-maintained
/// polyglot developer image published via GHCR.
pub sandbox_image: String,
/// vCPUs for the guest (1..=16).
pub sandbox_cpus: u8,
/// Guest memory in MiB (256..=16384).
pub sandbox_memory_mb: u32,
/// Writable overlay disk size in MiB for the guest rootfs (256..=65536).
pub sandbox_disk_mb: u32,
/// Idle timeout before an unused sandbox is stopped (seconds). Reused for
/// the session otherwise so build caches persist.
pub sandbox_idle_timeout_secs: u64,
/// Network egress policy for the guest.
pub sandbox_network_mode: SandboxNetworkMode,
/// Allowlist of domains/CIDRs for `allowlist` mode (and as an explicit
/// permit set in `restricted` mode).
pub sandbox_network_allowlist: Vec<String>,
/// Whether to permit guest access to private network ranges (RFC1918/loopback).
pub sandbox_allow_private_networks: bool,
/// Extra host environment variables to pass into the guest (in addition to
/// the minimal default guest env). Secrets are denied regardless.
pub sandbox_env_allowlist: Vec<String>,
pub idle_timeout_secs: u64, // per-chunk SSE idle timeout
pub max_session_tokens: u64, // hard session token budget (0 = unlimited)
pub summarize_on_compact: bool, // use a model call to summarize dropped turns
pub compact_instructions: Option<String>, // optional guidance woven into the summarize prompt (e.g. "Focus on code samples and API usage"); /compact <instructions> overrides per-call
pub rolling_state: bool, // inject a transient tail work-state summary (KV-cache-aware)
/// OpenAI prompt-cache retention for pre-GPT-5.6 models: "24h" | "in_memory" | "off".
/// Default "24h". Ignored on GPT-5.6+ (uses prompt_cache_options.ttl=30m instead).
pub prompt_cache_retention: Option<String>,
/// Optional OpenAI `service_tier` (e.g. "flex") for cache-friendly bulk work.
pub prompt_cache_service_tier: Option<String>,
/// When true (default), first-party OpenAI hosts get prompt_cache_key + GPT-5.6
/// explicit breakpoints + allowed_tools gating.
pub prompt_cache_enabled: bool,
/// When true (default on first-party OpenAI), send the full built-in tool
/// superset and gate with allowed_tools instead of mutating tools[] via load_tools.
pub prompt_cache_stable_tools: bool,
/// Extra host suffixes that may receive OpenAI prompt_cache_* + allowed_tools.
/// Empty by default — never inferred from kind=openai. Operators who have
/// verified a gateway (e.g. openrouter.ai) add it here.
pub prompt_cache_compatible_hosts: Vec<String>,
/// Auto-reflect: on a non-trivial turn (≥ `auto_reflect_min_tool_calls` tool
/// calls), inject a reflection continuation BEFORE the model writes its
/// completion summary so durable facts get persisted (memory) and recurring
/// patterns get written as skills — without relying on the model remembering
/// to reflect. The model then writes its summary as the final message. The
/// deterministic seam SELF_LEARNING.md §11 deferred. Skips reflect/index
/// turns and trivial turns. Default on.
pub auto_reflect: bool,
/// Minimum non-trivial tool-call count for auto-reflect to fire. 1 = any
/// real work. 0 is treated as 1 (a no-work turn should never reflect).
pub auto_reflect_min_tool_calls: u32,
/// Finish-completeness gate (OMP stop-hook parity): before a turn really
/// completes, deterministically surface unfinished business once - open
/// todo items, still-running async subagent runs, and edits with no
/// bash/diagnostics/eval after the last change - instead of accepting
/// the finish silently. Goal mode is exempt (its verify/replan loop owns
/// completion). Default on.
pub finish_completeness_gate: bool,
pub allow_vision: bool, // accept image_url content in send
// --- permission rules (item 1) ---
pub allow_rules: Vec<PermissionRule>,
pub deny_rules: Vec<PermissionRule>,
pub ask_rules: Vec<PermissionRule>,
// --- plugin system (centerpiece) ---
pub plugin_dir: PathBuf, // directory scanned for plugins
pub plugins_disabled: Vec<String>, // plugin names that are explicitly disabled
pub trust_project_plugins: bool, // Permit repo-shipped plugins under <workspace>/.catalyst-code/plugins. Default false; set only through env/CLI so a repository cannot self-authorize. Plugins installed explicitly through /plugin-install carry a user-installed marker and remain usable without this blanket trust flag.
// --- regex denylist upgrade (quick win) ---
pub bash_deny_regex: Vec<String>, // regex patterns that block bash commands
pub bash_deny_regex_compiled: Vec<regex::Regex>, // pre-compiled at startup
// --- optional second-model advisor ---
pub advisor: AdvisorConfig,
pub subagents: SubagentConfig,
/// Task-aware model routing by agent role (scout→fast, worker→strong, …).
pub routing: RoutingConfig,
// --- custom providers (openai/anthropic endpoints) ---
/// Named, configurable model providers. Empty = legacy single-endpoint mode
/// (uses `base_url` + the runtime key set via `set_key`).
pub providers: Vec<ProviderConfig>,
/// Name of the active provider. None = use the first configured provider, or
/// the legacy default when none are configured.
pub active_provider: Option<String>,
/// Per-provider API keys persisted by the TUI (settings.json `provider_keys`
/// + the legacy `api_key` under "default"). Seeded into `State::api_keys` at
/// startup so they override config/env keys (runtime keys win in provider
/// resolution) and survive restarts — this is what makes persisted keys sticky.
pub persisted_keys: std::collections::HashMap<String, String>,
/// Search-tool API keys (Exa / Tavily) set via `/search-key` and persisted
/// to config.json `search_keys`. Searched by `web_search` before the
/// `EXA_API_KEY` / `TAVILY_API_KEY` env vars (so slash-command keys win).
pub search_keys: std::collections::HashMap<String, String>,
/// MCP servers from user-owned config only; project settings cannot define transports.
pub mcp_servers: Vec<crate::mcp::McpConfig>,
/// Deferred tool groups always enabled at session start (e.g. `["ide","web"]`).
/// Expanded via `deferred_tools::expand_tool_request`. Does not include
/// `goal_write_plan`. Empty by default.
pub always_on_deferred_groups: Vec<String>,
/// When true (default), auto-enable deferred groups matching the user prompt
/// intent (browser/web/ide/…) at turn start so the model need not be asked.
pub auto_load_intent_tools: bool,
}
#[derive(Clone, Debug)]
pub struct AdvisorConfig {
pub enabled: bool,
pub subagents: bool,
pub model: Option<String>,
pub subagent_model: Option<String>,
pub nudge: bool,
/// Optional named watchdog roster. Loaded from WATCHDOG.yml files.
pub watchdog: Vec<WatchdogAdvisor>,
/// Shared WATCHDOG.yml instructions.
pub watchdog_instructions: Option<String>,
}
#[derive(Clone, Debug, Default)]
pub struct WatchdogAdvisor {
pub name: String,
pub enabled: bool,
pub model: Option<String>,
/// Read-only evidence tools requested by this specialist.
pub tools: Vec<String>,
/// Optional path triggers; empty means always eligible.
pub triggers: Vec<String>,
pub instructions: Option<String>,
}
impl Default for AdvisorConfig {
fn default() -> Self {
Self {
enabled: true,
subagents: false,
model: None,
subagent_model: None,
nudge: false,
watchdog: Vec::new(),
watchdog_instructions: None,
}
}
}
/// Intercom bridge mode: controls whether subagents get a coordination channel
/// back to the orchestrator and to each other.
#[derive(Clone, Debug, PartialEq)]
pub enum IntercomBridgeMode {
Off, // no intercom tools injected into subagents
ForkOnly, // only for forked-context runs
Always, // always inject (default)
}
impl IntercomBridgeMode {
pub fn parse(s: &str) -> Self {
match s.to_ascii_lowercase().as_str() {
"off" | "none" => IntercomBridgeMode::Off,
"fork-only" | "fork_only" | "fork" => IntercomBridgeMode::ForkOnly,
_ => IntercomBridgeMode::Always,
}
}
pub fn as_str(&self) -> &'static str {
match self {
IntercomBridgeMode::Off => "off",
IntercomBridgeMode::ForkOnly => "fork-only",
IntercomBridgeMode::Always => "always",
}
}
}
#[derive(Clone, Debug)]
pub struct SubagentConfig {
/// Max nesting depth for subagent delegation (main → sub → sub-sub).
/// 0 blocks all subagents; default 2.
pub max_depth: u32,
/// Whether subagents receive intercom coordination tools + instructions.
pub intercom_bridge_mode: IntercomBridgeMode,
/// Soft advisory max tasks in a top-level parallel run (default 8).
/// Exceeding this no longer rejects the call — tasks queue under the
/// concurrency semaphore. Callers can request larger batches explicitly.
pub parallel_max_tasks: u32,
/// Default concurrency for parallel runs when the caller omits
/// `concurrency`. Explicit requests may exceed this (absolute safety
/// max still applies in `run_parallel`).
pub parallel_concurrency: u32,
/// Top-level calls use background execution when async is not explicitly set.
pub async_by_default: bool,
/// Hide builtin agents from discovery.
pub disable_builtins: bool,
/// Per-builtin agent overrides keyed by agent name.
pub agent_overrides: std::collections::HashMap<String, AgentOverride>,
}
#[derive(Clone, Debug, Default)]
pub struct AgentOverride {
pub model: Option<String>,
pub fallback_models: Vec<String>,
pub thinking: Option<String>,
pub disabled: bool,
}
/// Optional explicit model pins for named jobs (OMP-style roles, smaller set).
/// Empty fields fall back to marker scoring / the selected model.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct NamedRoleModels {
pub main: Option<String>,
pub fast: Option<String>,
pub strong: Option<String>,
pub compact: Option<String>,
pub vision: Option<String>,
pub advisor: Option<String>,
}
/// Task-aware model routing preferences by agent role.
/// Explicit agent.model / override / goal role_models still win.
#[derive(Clone, Debug)]
pub struct RoutingConfig {
/// Prefer cheap/fast models for these agent names (scout, researcher, …).
pub fast_roles: Vec<String>,
/// Prefer strong models for these (worker, reviewer, oracle, …).
pub strong_roles: Vec<String>,
/// Substrings that mark a model as "fast" (case-insensitive).
pub fast_markers: Vec<String>,
/// Substrings that mark a model as "strong".
pub strong_markers: Vec<String>,
pub enabled: bool,
/// Extra model ids to try, in order, when the selected model is rate-limited (429).
/// Never used for auth/billing/5xx. Empty by default — auto-fallback then
/// walks pinned roles + same-provider fast siblings.
pub fallback_models: Vec<String>,
/// Named job pins (main/fast/strong/compact/vision/advisor).
pub role_models: NamedRoleModels,
}
impl Default for RoutingConfig {
fn default() -> Self {
Self {
fast_roles: vec![
"scout".into(),
"researcher".into(),
"context-builder".into(),
],
strong_roles: vec![
"worker".into(),
"reviewer".into(),
"oracle".into(),
"planner".into(),
],
fast_markers: vec![
"haiku".into(),
"flash".into(),
"mini".into(),
"small".into(),
"fast".into(),
"lite".into(),
"nano".into(),
],
strong_markers: vec![
"opus".into(),
"sonnet".into(),
"pro".into(),
"max".into(),
"large".into(),
"ultra".into(),
"glm-5".into(),
],
enabled: true,
fallback_models: Vec::new(),
role_models: NamedRoleModels::default(),
}
}
}
impl RoutingConfig {
pub fn preference_for(&self, agent_name: &str) -> Option<&'static str> {
if !self.enabled {
return None;
}
let n = agent_name.to_ascii_lowercase();
if self.fast_roles.iter().any(|r| r.eq_ignore_ascii_case(&n)) {
Some("fast")
} else if self.strong_roles.iter().any(|r| r.eq_ignore_ascii_case(&n)) {
Some("strong")
} else {
None
}
}
pub fn score_model(&self, model_id: &str, prefer: &str) -> i32 {
let id = model_id.to_ascii_lowercase();
let mut score = 0i32;
let fast_hit = self.fast_markers.iter().any(|m| id.contains(m));
let strong_hit = self.strong_markers.iter().any(|m| id.contains(m));
match prefer {
"fast" => {
if fast_hit {
score += 10;
}
if strong_hit {
score -= 5;
}
}
"strong" => {
if strong_hit {
score += 10;
}
if fast_hit {
score -= 5;
}
}
_ => {}
}
score
}
/// Selected model first, then configured fallbacks, de-duplicated.
pub fn rate_limit_candidates(&self, selected: &str) -> Vec<String> {
let mut out = Vec::new();
let mut seen = std::collections::HashSet::new();
if !selected.is_empty() && seen.insert(selected.to_string()) {
out.push(selected.to_string());
}
for m in &self.fallback_models {
let t = m.trim();
if !t.is_empty() && seen.insert(t.to_string()) {
out.push(t.to_string());
}
}
out
}
/// Explicit pin for a named job role. Aliases: cheap=fast, reasoning=strong,
/// summarize=compact. Empty / unknown → None.
pub fn pinned_role(&self, role: &str) -> Option<&str> {
let v = match role.trim().to_ascii_lowercase().as_str() {
"main" => self.role_models.main.as_deref(),
"fast" | "cheap" => self.role_models.fast.as_deref(),
"strong" | "reasoning" => self.role_models.strong.as_deref(),
"compact" | "summarize" => self.role_models.compact.as_deref(),
"vision" => self.role_models.vision.as_deref(),
"advisor" => self.role_models.advisor.as_deref(),
_ => None,
};
v.map(str::trim).filter(|s| !s.is_empty())
}
/// Resolve a named role to a model id. Pin wins; else score `known_ids`;
/// else `selected`. `main` always returns `selected` unless pinned.
pub fn resolve_role_model(&self, role: &str, selected: &str, known_ids: &[String]) -> String {
if let Some(pin) = self.pinned_role(role) {
return pin.to_string();
}
self.score_role_model(role, selected, known_ids)
}
/// Like [`Self::resolve_role_model`], but a pin on another provider is
/// ignored (falls through to scoring same-provider ids). Unknown pins
/// (not in `registry`) are kept so a user pin still works before discovery.
pub fn resolve_role_model_same_provider(
&self,
role: &str,
selected: &str,
selected_provider: &str,
registry: &[(String, String)],
) -> String {
let same_provider = |id: &str| -> bool {
let prov = selected_provider.trim();
if prov.is_empty() {
return true;
}
registry
.iter()
.any(|(rid, p)| rid == id && p.eq_ignore_ascii_case(prov))
|| !registry.iter().any(|(rid, _)| rid == id)
};
if let Some(pin) = self.pinned_role(role) {
if same_provider(pin) {
return pin.to_string();
}
}
let known: Vec<String> = registry
.iter()
.filter(|(id, _)| same_provider(id))
.map(|(id, _)| id.clone())
.collect();
self.score_role_model(role, selected, &known)
}
fn score_role_model(&self, role: &str, selected: &str, known_ids: &[String]) -> String {
let role = role.trim().to_ascii_lowercase();
if role == "main" || !self.enabled {
return selected.to_string();
}
let prefer = match role.as_str() {
"strong" | "reasoning" => "strong",
_ => "fast",
};
let mut best: Option<(i32, &str)> = None;
for id in known_ids {
let s = self.score_model(id, prefer);
if s <= 0 {
continue;
}
match best {
None => best = Some((s, id.as_str())),
Some((bs, bid)) if s > bs || (s == bs && bid == selected && id != selected) => {
best = Some((s, id.as_str()));
}
_ => {}
}
}
best.map(|(_, id)| id.to_string())
.unwrap_or_else(|| selected.to_string())
}
/// 429 walk: selected first, then explicit `fallback_models` when set.
/// When that list is empty, append pinned fast/compact/strong plus up to
/// three same-provider fast siblings so 429s survive zero-config.
pub fn rate_limit_candidates_auto(
&self,
selected: &str,
selected_provider: &str,
registry: &[(String, String)],
) -> Vec<String> {
let mut out = self.rate_limit_candidates(selected);
if !self.fallback_models.is_empty() {
return out;
}
let mut seen: std::collections::HashSet<String> = out.iter().cloned().collect();
let prov = selected_provider.trim();
let same_provider = |id: &str| -> bool {
if prov.is_empty() {
return true;
}
registry
.iter()
.any(|(rid, p)| rid == id && p.eq_ignore_ascii_case(prov))
|| !registry.iter().any(|(rid, _)| rid == id)
};
for role in ["fast", "compact", "strong"] {
if let Some(m) = self.pinned_role(role) {
if same_provider(m) && seen.insert(m.to_string()) {
out.push(m.to_string());
}
}
}
if !self.enabled {
return out;
}
let mut scored: Vec<(i32, &str)> = registry
.iter()
.filter(|(id, p)| id != selected && (prov.is_empty() || p.eq_ignore_ascii_case(prov)))
.map(|(id, _)| (self.score_model(id, "fast"), id.as_str()))
.filter(|(s, _)| *s > 0)
.collect();
scored.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(b.1)));
for (_, id) in scored.into_iter().take(3) {
if seen.insert(id.to_string()) {
out.push(id.to_string());
}
}
out
}
}
impl Default for SubagentConfig {
fn default() -> Self {
Self {
max_depth: 2,
intercom_bridge_mode: IntercomBridgeMode::Always,
parallel_max_tasks: 8,
parallel_concurrency: 4,
async_by_default: false,
disable_builtins: false,
agent_overrides: std::collections::HashMap::new(),
}
}
}
/// A model provider: a named OpenAI- or Anthropic-compatible endpoint with
/// its own base URL, auth, and wire protocol. Defined in config (JSON/env);
/// switched at runtime via the `set_provider` command.
///
/// The harness keeps the *internal* conversation in OpenAI chat-completions
/// shape (role:"tool", assistant `tool_calls`, ...) because every other layer
/// (compaction, sanitization, subagents, session persistence) understands
/// that shape. The provider abstraction only translates at the HTTP boundary:
/// `kind` decides whether requests/responses are OpenAI-shaped or translated
/// to/from the Anthropic Messages API. This means adding a provider never
/// touches the rest of the harness.
#[derive(Clone, Debug, PartialEq, Default)]
pub enum ProviderKind {
#[default]
OpenAI,
Anthropic,
}
impl ProviderKind {
pub fn parse(s: &str) -> Self {
match s.to_ascii_lowercase().as_str() {
"anthropic" | "claude" => ProviderKind::Anthropic,
_ => ProviderKind::OpenAI,
}
}
pub fn as_str(&self) -> &'static str {
match self {
ProviderKind::OpenAI => "openai",
ProviderKind::Anthropic => "anthropic",
}
}
pub fn is_openai(&self) -> bool {
matches!(self, ProviderKind::OpenAI)
}
pub fn is_anthropic(&self) -> bool {
matches!(self, ProviderKind::Anthropic)
}
}
impl std::fmt::Display for ProviderKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
/// A per-model capability override: refines a single discovered model's
/// context window, max output tokens, reasoning flag, and/or advertised
/// thinking levels. Applied AFTER discovery + models.dev enrichment + the
/// per-provider `context_window` override, so an explicit per-model value wins
/// over everything else. Every field is optional — only the ones present are
/// applied; the rest fall through to the discovered/curated/default caps.
/// This lets a user hand-tune a model the endpoint under-reports (e.g. a local
/// server listing bare ids, or a gateway whose `/v1/models` omits caps) without
/// a code change, while leaving other models on the 200k/8k flat defaults.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ModelOverride {
pub id: String,
/// Force this model's context window (tokens).
pub context_window: Option<u32>,
/// Force this model's max output tokens.
pub max_tokens: Option<u32>,
/// Force whether the model supports extended thinking/reasoning.
pub reasoning: Option<bool>,
/// Force the advertised reasoning effort levels (e.g. ["low","medium","high"]).
/// An empty vec clears the levels (model declares none); `None` leaves them.
pub thinking_levels: Option<Vec<String>>,
/// Force accepted input modalities (e.g. ["text", "image"]).
pub input: Option<Vec<String>>,
/// Force emitted output modalities (e.g. ["text"]).
pub output: Option<Vec<String>>,
/// Force tool/function calling support.
pub tool_call: Option<bool>,
/// Force structured-output support.
pub structured_output: Option<bool>,
}
/// A configured provider as it appears in the config file/env (no resolved
/// runtime key). `api_key` is a literal (user-owned config only, never a
/// project-local file); `api_key_env` names an env var to read instead.
#[derive(Clone, Debug, Default)]
pub struct ProviderConfig {
pub name: String,
pub kind: ProviderKind,
pub base_url: String,
/// Literal API key stored in the (user-owned, 0600) config file. Optional.
pub api_key: Option<String>,
/// Name of an env var holding the API key (resolved at request time).
pub api_key_env: Option<String>,
/// Extra HTTP headers appended to every request (e.g. `HTTP-Referer`).
pub headers: Vec<(String, String)>,
/// Optional per-provider context-window override (tokens). When set, every
/// model discovered from this provider is forced to this window — for
/// local servers (e.g. LM Studio) whose `/v1/models` returns bare ids
/// without a context field, so the harness doesn't oversend past the
/// model's actual loaded context. `None` = use the discovered/curated cap.
pub context_window: Option<u32>,
/// Optional per-model capability overrides. Applied to matching model ids
/// after discovery + models.dev + the per-provider `context_window`. Lets
/// the user hand-tune reasoning levels / context / output for individual
/// models the endpoint under-reports. Empty = no per-model refinement.
pub models_override: Vec<ModelOverride>,
/// Optional custom models-list endpoint path (e.g. `/v1/models`,
/// `/api/models`). When set, discovery hits `{base_url}{models_endpoint}`
/// directly instead of the hardcoded `/models/info` (Umans) → `/models`
/// (OpenAI) fallback chain. Lets a non-standard OpenAI-compatible endpoint
/// work without a code branch. `None` = use the default discovery path.
pub models_endpoint: Option<String>,
}
/// A provider fully resolved for an API call: kind, base URL, the effective API
/// key (runtime override -> config literal -> config env var -> global env),
/// and extra headers. This is what `stream_turn` / `discover_models` /
/// `summarize` consume — it carries everything provider-specific so those
/// functions stop depending on `cfg.base_url` + a bare `api_key` string.
#[derive(Clone, Debug)]
pub struct ResolvedProvider {
pub name: String,
pub kind: ProviderKind,
pub base_url: String,
pub api_key: Option<String>,
pub headers: Vec<(String, String)>,
/// When true, Anthropic streaming/discovery uses `Authorization: Bearer`
/// instead of `x-api-key` (plugin subscription OAuth). Set by
/// `oauth::enrich_oauth` when a plugin token is injected.
pub oauth: bool,
/// Per-provider context-window override carried from `ProviderConfig` so
/// `discover_models` can force it onto every discovered model. `None` =
/// use the discovered/curated context.
pub context_window: Option<u32>,
/// Per-model capability overrides carried from `ProviderConfig` so
/// `discover_models` can refine individual models after discovery. Applied
/// in `apply_models_override` (after `apply_context_window_override`).
pub models_override: Vec<ModelOverride>,
/// Custom models-list endpoint path carried from `ProviderConfig` so
/// discovery can hit a non-standard endpoint without a code branch.
pub models_endpoint: Option<String>,
}
impl ResolvedProvider {
/// The legacy/default provider when none are configured: OpenAI-shaped,
/// `cfg.base_url` for the URL, key resolved only from `runtime_keys["default"]`
/// (set via explicit `/login` / `set_key`). Does **not** scan `UMANS_API_KEY`
/// or other env vars — a fresh install stays signed out until the user
/// provides a key or completes OAuth.
pub fn legacy_default(
cfg: &Config,
runtime_keys: &std::collections::HashMap<String, String>,
) -> Self {
let api_key = runtime_keys
.get("default")
.cloned()
.filter(|s| !s.is_empty());
ResolvedProvider {
name: "default".to_string(),
kind: ProviderKind::OpenAI,
base_url: cfg.base_url.clone(),
api_key,
headers: Vec::new(),
oauth: false,
context_window: None,
models_override: Vec::new(),
models_endpoint: None,
}
}
}
/// A built-in first-party provider template: a known endpoint + the standard
/// API-key env var for that vendor, so a user can add the provider with a
/// single action (`add_provider`) instead of hand-editing JSON. Presets cover
/// the major vendors. The harness always keeps the conversation in OpenAI
/// chat-completions shape internally; a preset's `kind` only decides the wire
/// translation at the HTTP boundary (Gemini exposes an OpenAI-compatible
/// endpoint, so it maps to `OpenAI`).
#[derive(Clone, Debug)]
pub struct ProviderPreset {
pub id: &'static str,
pub label: &'static str,
pub kind: ProviderKind,
pub base_url: &'static str,
/// Primary env var holding the API key (e.g. `OPENAI_API_KEY`).
pub api_key_env: &'static str,
/// Alternate env vars checked in order if the primary is unset
/// (e.g. Gemini accepts `GOOGLE_API_KEY` too).
pub alt_envs: &'static [&'static str],
pub description: &'static str,
}
/// The first-party provider presets. Order is the order shown in pickers.
/// Official provider bundles under `core/providers/` carry provider-specific
/// metadata and documentation so removable vendors stay isolated. Umans is
/// listed first as the default/original provider.
pub const PROVIDER_PRESETS: &[ProviderPreset] = &[
ProviderPreset {
id: "umans",
label: "Umans (GLM-5.2)",
kind: ProviderKind::OpenAI,
// The default Umans endpoint. is_umans() matches `umans.ai` as a parent
// domain, so the GLM-specific wire logic (reasoning_effort,
// /models/info discovery) still applies to this preset's turns.
base_url: "https://api.code.umans.ai/v1",
api_key_env: "UMANS_API_KEY",
alt_envs: &[],
description: "Umans — GLM-5.2, the default provider. Paste your API key via /login (https://app.umans.ai/billing → API Keys).",
},
ProviderPreset {
id: "opencode-go",
label: "OpenCode Go",
kind: ProviderKind::OpenAI,
// OpenCode Go is one subscription/key that serves some models via an
// OpenAI-compatible `/v1/chat/completions` endpoint and others via an
// Anthropic `/v1/messages` endpoint. preset_provider_configs()
// expands this preset into TWO provider configs (opencode-go +
// opencode-go-anthropic) sharing this base URL + key, so each model
// routes to its correct wire protocol. See provider::is_opencode_go.
base_url: "https://opencode.ai/zen/go/v1",
api_key_env: "OPENCODE_GO_API_KEY",
alt_envs: &[],
description: "OpenCode Go — low-cost subscription for popular open coding models (GLM, Kimi, DeepSeek, MiMo, MiniMax, Qwen). One API key; models route to the OpenAI-compatible or Anthropic endpoint automatically. Uses your OPENCODE_GO_API_KEY.",
},
ProviderPreset {
id: "openrouter",
label: "OpenRouter",
kind: ProviderKind::OpenAI,
base_url: "https://openrouter.ai/api/v1",
api_key_env: "OPENROUTER_API_KEY",
alt_envs: &[],
description: "OpenRouter multi-model gateway. Uses OPENROUTER_API_KEY (https://openrouter.ai/settings/keys).",
},
ProviderPreset {
id: "deepseek",
label: "DeepSeek",
kind: ProviderKind::OpenAI,
// DeepSeek's official OpenAI-compatible base URL intentionally does
// not include `/v1`; the API appends `/chat/completions` and `/models`
// directly to this base.
base_url: "https://api.deepseek.com",
api_key_env: "DEEPSEEK_API_KEY",
alt_envs: &[],
description: "DeepSeek API — V4 Pro and V4 Flash with automatic live model discovery. Uses DEEPSEEK_API_KEY (https://platform.deepseek.com/api_keys).",
},
];
/// Look up a first-party preset by id.
pub fn find_preset(id: &str) -> Option<&'static ProviderPreset> {
PROVIDER_PRESETS.iter().find(|p| p.id == id)
}
impl ProviderPreset {
/// Resolve an API key for this preset from its env vars (primary first,
/// then alternates). None when none are set. Empty `api_key_env` means
/// OAuth-only (e.g. xAI SuperGrok) — always returns None.
///
/// Not used for auto-login (auth is explicit via `/login` paste or OAuth).
/// Kept for diagnostics and for callers that intentionally opt into env lookup.
#[allow(dead_code)]
pub fn env_key(&self) -> Option<String> {
if self.api_key_env.is_empty() {
return None;
}
std::env::var(self.api_key_env)
.ok()
.filter(|s| !s.is_empty())
.or_else(|| {
self.alt_envs
.iter()
.find_map(|e| std::env::var(e).ok().filter(|s| !s.is_empty()))
})
}
/// The env var name that actually held a key, or the primary env var when
/// none are set (so a future `export` Just Works without re-adding).
pub fn resolved_env(&self) -> &'static str {
if std::env::var(self.api_key_env)
.ok()
.filter(|s| !s.is_empty())
.is_some()
{
return self.api_key_env;
}