base/context/config.rs
1//! 引擎只读配置 + 模型窗口推断。
2
3use crate::permission::PermissionMode;
4
5/// 引擎只读配置。从 settings.json + CLI flags 合并出来后,整个会话不再变。
6#[derive(Debug, Clone)]
7pub struct EngineConfig {
8 /// Provider id (e.g. "anthropic", "deepseek", "xai").
9 pub provider: Option<String>,
10 pub model: String,
11 pub max_tokens: u32,
12 /// How long a tool call waits for a permission answer before denying.
13 /// `0` = wait indefinitely. See
14 /// the `permissions.prompt_timeout_secs` setting.
15 pub permission_prompt_timeout_secs: u64,
16 /// How long a tool call still running when its turn is cancelled is given
17 /// to stop on its own before it is dropped and answered as cancelled.
18 pub tool_cancel_grace: std::time::Duration,
19 /// Maximum number of concurrency-safe tools to run in parallel
20 /// within a single batch. 0 = unlimited. Default 10.
21 pub max_parallelism: usize,
22 /// +** — per-turn API call budget. Default **200**.
23 /// When exceeded, engine returns gracefully with
24 /// `StopReason::MaxTurns` instead of an error — partial work
25 /// is preserved and surfaced to the caller. Lower this for sub-
26 /// agents you want to cap (e.g. compactors at 1, memory-extractors
27 /// at 5).
28 pub max_api_calls_per_turn: u32,
29 /// Auto-routing: optional "strong" tier model. When set,
30 /// the engine starts each turn at `model` (cheap/fast tier, e.g.
31 /// `ds-v4-flash`) and **escalates to `strong_model`** mid-turn on any
32 /// of these signals:
33 /// - `tool_calls_so_far >= 3` (multi-step exploration)
34 /// - previous tool_result was an error (need smarter retry)
35 /// - turn message count >= 8 (deep conversation)
36 ///
37 /// Once escalated, stays at strong for rest of the turn.
38 /// `None` = no routing (use `model` for everything; current default).
39 /// User-facing API: surface as `--strong-model` CLI flag, or in
40 /// `~/.agix/scenes/<scope>/settings.json`.
41 pub strong_model: Option<String>,
42
43 pub permission_mode: PermissionMode,
44 /// The session's sandbox settings; every policy a command runs under is
45 /// derived from these.
46 pub sandbox: std::sync::Arc<crate::interface::exec::SandboxSettings>,
47 /// `Settings.skills.allow_shell`, the other way round — read by the skill
48 /// expansion's `` !`cmd` `` step via `ToolContext.config`.
49 pub disable_skill_shell_execution: bool,
50 /// Whether the project tier is in effect (`LoadedSettings::trust`); an
51 /// untrusted project's skill `` !`cmd` `` is not run.
52 pub project_trust: crate::permission::ProjectTrust,
53 /// How the engine reads the files it puts in front of the model.
54 pub prompt_files: crate::paths::PromptFiles,
55 /// What the instance names its directories, for the tools that make one
56 /// or name one to the model.
57 pub layout: crate::paths::Layout,
58 /// Mirrors `Settings.sandbox.env`.
59 pub subprocess_env: crate::interface::exec::SubprocessEnv,
60
61 /// File read/write byte/line limits. Sub-config keeps related field
62 /// values together so cross-tool tuning (Read/Write/Edit) is one
63 /// import path.
64 pub file_limits: FileLimits,
65
66 /// system prompt overrides + extras (AGENTS.md walk, output styles,
67 /// append/override). All affect what gets baked into block [1-5] of
68 /// the system prompt.
69 pub system_prompt: SystemPromptSettings,
70
71 /// 最大 agent 嵌套深度。主 agent 深度 0,每经 AgentTool spawn 加 1。
72 /// 超限时 AgentTool 返回 tool error(防模型在子 agent prompt 中写"用 AgentTool"
73 /// 导致无限递归)。默认 3。设 0 禁用 AgentTool。
74 pub max_agent_depth: u32,
75
76 /// 是否保留完整工具结果文本。默认 false —— 工具结果会被截断到
77 /// 2KB 再送回给模型。设 true 时原样透传(长输出场景可能显著消耗 context)。
78 pub verbose_tool_results: bool,
79 /// See [`PathStyle`]; mirrors `Settings.path_style`.
80 pub path_style: PathStyle,
81 /// Tools advertised to the model by name and description only, their
82 /// schema fetched through `ToolSearch` — the scene's
83 /// `ToolSurface::deferred`, fixed when the session is built. A property
84 /// of the session rather than of the tool, so an MCP tool that arrives
85 /// mid-session is deferred like one that was there from the start.
86 pub deferred_tools: std::sync::Arc<std::collections::HashSet<String>>,
87 /// Where a tool result too long for the conversation is kept.
88 pub tool_results: ToolResultLimits,
89 /// What the model may set going for itself beyond the turn it is asked
90 /// in.
91 pub model_autonomy: ModelAutonomy,
92}
93
94/// The ceilings on what the model starts running for itself: the goals it
95/// sets (`goal.*`) and the jobs it schedules (`schedule.*`). A host acting
96/// for a person is not held to them.
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub struct ModelAutonomy {
99 /// The most rounds a goal the model sets or edits may have.
100 pub goal_max_rounds: u32,
101 /// The most scheduled jobs the model may hold in a session at once.
102 pub max_jobs: u32,
103 /// The fewest minutes between two fires of a recurring job the model
104 /// schedules.
105 pub min_job_interval_minutes: u32,
106}
107
108impl Default for ModelAutonomy {
109 fn default() -> Self {
110 Self {
111 goal_max_rounds: crate::context::goal::MAX_ROUNDS_LIMIT,
112 max_jobs: 20,
113 min_job_interval_minutes: 1,
114 }
115 }
116}
117
118/// How long a tool result may be before it is saved to a file and the model
119/// is given a preview. A session's delegates write into the root session's
120/// directory.
121#[derive(Debug, Clone, PartialEq, Eq)]
122pub struct ToolResultLimits {
123 /// Characters; `0` keeps every result in the conversation.
124 pub inline_chars: usize,
125 /// `None` when there is nowhere to write: results are then cut by the
126 /// per-result budget instead.
127 pub dir: Option<std::path::PathBuf>,
128}
129
130impl ToolResultLimits {
131 pub const DEFAULT_INLINE_CHARS: usize = 30_000;
132}
133
134impl Default for ToolResultLimits {
135 fn default() -> Self {
136 Self {
137 inline_chars: Self::DEFAULT_INLINE_CHARS,
138 dir: None,
139 }
140 }
141}
142
143/// File-op limits sub-config: the "tuning the FileRead/Write envelope"
144/// cluster as one knob.
145#[derive(Debug, Clone)]
146pub struct FileLimits {
147 /// 文件读 / 写的字节上限。FileRead 检查 metadata.len() 用。
148 pub max_file_read_bytes: u64,
149 /// 单次 FileRead 默认行数(offset/limit 没填时)
150 pub default_read_lines: usize,
151 /// 单行字符数上限(超了截断 + `[truncated]` 标记)
152 pub max_line_chars: usize,
153}
154
155impl Default for FileLimits {
156 fn default() -> Self {
157 Self {
158 max_file_read_bytes: 10 * 1024 * 1024,
159 default_read_lines: 2000,
160 max_line_chars: 2000,
161 }
162 }
163}
164
165/// System-prompt assembly knobs sub-config.
166#[derive(Debug, Clone, Default)]
167pub struct SystemPromptSettings {
168 /// Preferred response language. None = use the user's language/context.
169 pub language: Option<String>,
170 /// Enable Anthropic prompt-caching `scope: "global"` for the static system
171 /// prompt prefix. Requires the prompt-caching-scope beta header and may not
172 /// be supported by non-Anthropic-compatible endpoints.
173 pub global_cache_scope: bool,
174 /// True when at least one connected MCP tool is rendered in the tool list.
175 /// MCP tools are per-user/session, so system prompt global caching is
176 /// downgraded to normal org/provider caching in this case.
177 pub mcp_tools_present: bool,
178 /// Instructions returned by connected MCP servers during initialize.
179 pub mcp_instructions: Vec<McpServerInstruction>,
180 /// 是否在 cwd 之上向上爬找 AGENTS.md。默认 true。
181 /// monorepo 子目录不想吃父级 monorepo 上下文时设 false。
182 pub memory_walk_up: bool,
183 /// 选中的 output style 名称(user/project 级别均可)。
184 /// 引擎在 collect FrozenContext 时按此名称从
185 /// `~/.agix/scenes/<scope>/output-styles/<name>.md` 或 `<cwd>/.agix/output-styles/<name>.md`
186 /// 读取内容,注入 system prompt 末段。None = 不注入额外 style。
187 pub output_style: Option<String>,
188 /// When true (default), use TaskCreate/Update/List/Get/Stop instead of
189 /// TodoWrite for task tracking. When false, TodoWrite is used and the V2 Task tools are hidden.
190 pub todo_v2_enabled: bool,
191 /// When true, register TeamCreate/TeamDelete for multi-agent orchestration.
192 /// Default false.
193 pub agent_teams_enabled: bool,
194}
195
196#[derive(Debug, Clone, PartialEq, Eq, Hash)]
197pub struct McpServerInstruction {
198 pub name: String,
199 pub instructions: String,
200}
201
202/// How file tools word the paths the model reads: in tool descriptions and in
203/// the paths Grep, Glob, Write and Edit print. Resolving a path the model
204/// passes in is the same in both styles (relative against the working
205/// directory, absolute as is).
206#[derive(
207 Debug,
208 Clone,
209 Copy,
210 PartialEq,
211 Eq,
212 Default,
213 serde::Serialize,
214 serde::Deserialize,
215 schemars::JsonSchema,
216)]
217#[serde(rename_all = "snake_case")]
218pub enum PathStyle {
219 #[default]
220 Absolute,
221 Relative,
222}
223
224impl PathStyle {
225 /// `path` as the model should see it: under `cwd` and relative in
226 /// `Relative`, otherwise exactly `path.display()`.
227 pub fn render(self, path: &std::path::Path, cwd: &std::path::Path) -> String {
228 if self == PathStyle::Relative {
229 if let Ok(rel) = path.strip_prefix(cwd) {
230 return if rel.as_os_str().is_empty() {
231 ".".to_string()
232 } else {
233 rel.display().to_string()
234 };
235 }
236 }
237 path.display().to_string()
238 }
239}
240
241impl EngineConfig {
242 /// 合理默认值;具体使用方根据 CLI 与 settings 覆盖。
243 pub fn defaults_for(model: impl Into<String>) -> Self {
244 let model = model.into();
245 Self {
246 // model / runtime
247 provider: None,
248 model,
249 max_tokens: 16384,
250 permission_prompt_timeout_secs: 300,
251 tool_cancel_grace: std::time::Duration::from_secs(2),
252 max_parallelism: 10,
253 max_api_calls_per_turn: 25,
254 strong_model: None,
255
256 // permission / sandbox
257 permission_mode: PermissionMode::Default,
258 sandbox: Default::default(),
259 disable_skill_shell_execution: false,
260 project_trust: crate::permission::ProjectTrust::default(),
261 prompt_files: crate::paths::PromptFiles::unscoped(),
262 layout: Default::default(),
263 subprocess_env: Default::default(),
264
265 // grouped sub-configs
266 file_limits: FileLimits::default(),
267 system_prompt: SystemPromptSettings {
268 memory_walk_up: true,
269 todo_v2_enabled: true,
270 agent_teams_enabled: false,
271 ..Default::default()
272 },
273
274 // misc
275 max_agent_depth: 3,
276 verbose_tool_results: false,
277 path_style: PathStyle::default(),
278 deferred_tools: Default::default(),
279 tool_results: ToolResultLimits::default(),
280 model_autonomy: ModelAutonomy::default(),
281 }
282 }
283}
284
285/// 依据模型名推断其上下文窗口大小。
286///
287/// 依据"模型能装多少"来确定 auto-compact / blocking limit 阈值,
288/// 而非对所有模型使用相同的固定值。
289///
290/// 当前实现是保守启发式,允许用户通过 CLI / settings 覆盖。
291pub fn infer_context_window_tokens(model: &str) -> usize {
292 let m = model.to_ascii_lowercase();
293 if m.contains("deepseek") || m.starts_with("ds-v") || m.starts_with("ds_") {
294 1_000_000
295 } else if m.contains("codex") {
296 400_000
297 } else {
298 200_000
299 }
300}
301
302#[cfg(test)]
303mod tests {
304 use super::*;
305
306 #[test]
307 fn render_is_relative_only_under_the_working_directory() {
308 use std::path::Path;
309 let cwd = Path::new("/ws");
310 let inside = Path::new("/ws/src/a.rs");
311 assert_eq!(PathStyle::Absolute.render(inside, cwd), "/ws/src/a.rs");
312 assert_eq!(PathStyle::Relative.render(inside, cwd), "src/a.rs");
313 assert_eq!(PathStyle::Relative.render(cwd, cwd), ".");
314 assert_eq!(
315 PathStyle::Relative.render(Path::new("/other/a.rs"), cwd),
316 "/other/a.rs"
317 );
318 }
319}