crabmate 0.4.0

Rust AI agent: OpenAI-compatible chat/completions, function calling, HTTP serve, ops CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//! 运行配置:API 地址、模型等,从 `config/default_config.toml`、`config/session.toml`、`config/context_inject.toml`、`config/tools.toml`、`config/sandbox.toml`、`config/planning.toml`、`config/memory.toml` 嵌入默认 + 可选覆盖

pub mod agent_role_spec;
mod agent_roles;
mod assembly;
mod builder;
pub mod cli;
mod cursor_rules;
mod env_override_apply;
mod env_overrides;
mod final_plan_requirement_mode;
mod finalize;
mod gateway_hints;
mod hot_reload;
mod load;
mod orchestration_profile;
mod scheduled_agent_task;
pub mod skills;
pub mod skills_slash;
mod source;
mod text_util;
mod types;
mod user_config_layers;
mod user_config_xdg;
mod validate;
mod web_cors;
mod workspace_roots;
mod xdg;

pub use web_cors::{DEFAULT_SHELL_CORS_ORIGINS, resolve_web_cors_allowed_origins};

pub use final_plan_requirement_mode::FinalPlanRequirementMode;
pub use gateway_hints::{
    default_llm_reasoning_split_for_gateway, fold_system_into_user_for_config,
};
pub use hot_reload::apply_hot_reload_config_subset;
pub use load::{load_config, load_config_for_cli};
pub use orchestration_profile::{OrchestrationProfile, effective_orchestration_path_summary};
pub use user_config_xdg::{
    ENV_SKIP_CONFIG_SEED, SYSTEM_CONFIG_DIR, cwd_has_local_user_config,
    cwd_in_crabmate_source_tree, ensure_user_config_seeded_from,
    ensure_user_config_seeded_from_system, resolve_default_user_config_toml_after_seed,
    resolve_interactive_cli_config_path, should_resolve_xdg_user_config, system_config_toml_path,
    user_config_dir, user_config_toml_path,
};
pub use xdg::{
    ENV_CACHE_DIR, ENV_CONFIG_DIR, ensure_fastembed_cache_dir, ensure_user_cache_subdir,
    user_cache_dir,
};

pub use finalize::{
    embedded_context_summary_system, embedded_context_summary_user_template,
    embedded_session_mode_appendix, embedded_thinking_avoid_echo_appendix,
};

#[allow(unused_imports)] // 部分类型仅对外再导出,本文件内不直接使用
pub use agent_role_spec::AgentRoleSpec;
#[allow(unused_imports)]
pub use types::{
    AgentConfig, AgentThinkingTraceConfig, AgentToolStatsConfig, ChatQueuesCacheConfig,
    CodebaseSemanticConfig, CommandExecConfig, ContextBootstrapInjectConfig, ContextPipelineConfig,
    ConversationPersistenceConfig, CursorRulesConfigSection, ExposeSecret, HttpFetchConfigSection,
    LlmConnectionConfig, LlmHttpAuthMode, LlmHttpRetryConfig, LlmSamplingConfig,
    LlmVendorFlagsConfig, LongTermMemoryConfig, LongTermMemoryScopeMode,
    LongTermMemoryVectorBackend, McpClientConfig, PerPlanPolicyConfig, PlannerExecutorMode,
    RolesPromptsConfig, ScheduledAgentTask, SessionUiConfig, SessionWorkspaceChangelistConfig,
    SkillsConfigSection, SyncDefaultToolSandboxMode, SyncToolSandboxConfig, ThinkingEchoConfig,
    ToolCallExplainConfig, ToolRegistryPolicyConfig, ToolTranscriptConfig, TurnBudgetConfig,
    WeatherToolConfig, WebApiConfig, WebSearchConfigSection, WebSearchProvider,
    WorkspaceRootsConfig,
};

/// 进程内共享的 [`AgentConfig`](`serve` / `repl` / `chat` / `bench`);热重载时 `write` 更新,回合开始时 `read`+`clone` 得快照传入 `run_agent_turn`。
pub type SharedAgentConfig = std::sync::Arc<tokio::sync::RwLock<AgentConfig>>;

#[cfg(test)]
mod embedded_shard_parse_tests {
    use super::assembly;
    use super::builder::ConfigBuilder;

    #[test]
    fn malformed_embedded_toml_returns_err_naming_shard() {
        let mut b = ConfigBuilder::default();
        let err =
            assembly::apply_embedded_agent_shard_for_test(&mut b, "test_shard.toml", "[[[not toml")
                .unwrap_err();
        assert!(
            err.contains("test_shard.toml"),
            "expected shard label in error: {err}"
        );
        assert!(
            err.contains("嵌入默认配置"),
            "expected Chinese prefix in error: {err}"
        );
    }
}

#[cfg(test)]
mod web_api_require_bearer_defaults_tests {
    use super::load_config;
    use super::load_config_test_env::without_cm_planner_executor_mode_env;
    use std::fs;
    use std::sync::Mutex;

    /// `load_config` 会读 `CM_WEB_API_REQUIRE_BEARER`(优先级高于 TOML);开发者本机若导出 `0`/`false` 会覆盖嵌入默认,导致「仅测嵌入默认」的断言不稳定。
    static CM_WEB_API_REQUIRE_BEARER_LOCK: Mutex<()> = Mutex::new(());

    fn without_cm_web_api_require_bearer_env<F, R>(f: F) -> R
    where
        F: FnOnce() -> R,
    {
        let _g = CM_WEB_API_REQUIRE_BEARER_LOCK
            .lock()
            .expect("web_api_require_bearer defaults tests must run serialized");
        let prev = std::env::var("CM_WEB_API_REQUIRE_BEARER").ok();
        // SAFETY: `remove_var`/`set_var` are unsafe in Rust 2024; we hold the mutex so no other
        // test in this module touches `CM_WEB_API_REQUIRE_BEARER` during `f()`.
        unsafe {
            std::env::remove_var("CM_WEB_API_REQUIRE_BEARER");
        }
        let out = f();
        unsafe {
            match prev.as_ref() {
                Some(v) => std::env::set_var("CM_WEB_API_REQUIRE_BEARER", v),
                None => std::env::remove_var("CM_WEB_API_REQUIRE_BEARER"),
            }
        }
        out
    }

    #[test]
    fn embedded_default_does_not_require_bearer_without_env_override() {
        without_cm_planner_executor_mode_env(|| {
            without_cm_web_api_require_bearer_env(|| {
                let dir = tempfile::tempdir().expect("tempdir");
                let path = dir.path().join("minimal.toml");
                fs::write(
                    &path,
                    r#"[agent]
api_base = "https://api.deepseek.com/v1"
model = "deepseek-chat"
"#,
                )
                .expect("write");
                let cfg = load_config(Some(path.to_str().unwrap())).expect("load");
                assert!(
                    !cfg.web_api.web_api_require_bearer,
                    "embedded default should allow serve without forcing non-empty web_api_bearer_token"
                );
                assert_eq!(
                    cfg.web_api.web_cors_allowed_origins,
                    crate::cm_config::DEFAULT_SHELL_CORS_ORIGINS
                        .iter()
                        .map(|s| (*s).to_string())
                        .collect::<Vec<_>>(),
                    "embedded default should allow official Client shell Origins"
                );
            });
        });
    }

    #[test]
    fn explicit_true_requires_bearer_secret_at_serve() {
        without_cm_planner_executor_mode_env(|| {
            without_cm_web_api_require_bearer_env(|| {
                let dir = tempfile::tempdir().expect("tempdir");
                let path = dir.path().join("minimal.toml");
                fs::write(
                    &path,
                    r#"[agent]
api_base = "https://api.deepseek.com/v1"
model = "deepseek-chat"
web_api_require_bearer = true
"#,
                )
                .expect("write");
                let cfg = load_config(Some(path.to_str().unwrap())).expect("load");
                assert!(cfg.web_api.web_api_require_bearer);
            });
        });
    }

    #[test]
    fn toml_web_cors_allowed_origins_are_loaded() {
        without_cm_planner_executor_mode_env(|| {
            without_cm_web_api_require_bearer_env(|| {
                let dir = tempfile::tempdir().expect("tempdir");
                let path = dir.path().join("cors.toml");
                fs::write(
                    &path,
                    r#"[agent]
api_base = "https://api.deepseek.com/v1"
model = "deepseek-chat"
web_cors_allowed_origins = ["http://127.0.0.1:8081", "https://ui.example.com"]
"#,
                )
                .expect("write");
                let cfg = load_config(Some(path.to_str().unwrap())).expect("load");
                assert_eq!(
                    cfg.web_api.web_cors_allowed_origins,
                    vec![
                        "http://127.0.0.1:8081".to_string(),
                        "https://ui.example.com".to_string(),
                        "tauri://localhost".to_string(),
                        "http://tauri.localhost".to_string(),
                    ]
                );
            });
        });
    }
}

#[cfg(test)]
pub(crate) mod load_config_test_env {
    use std::sync::Mutex;

    /// `load_config` 会读 `CM_PLANNER_EXECUTOR_MODE`;并行用例若短暂写入废弃值会污染其它 `load_config` 测试。
    static CM_PLANNER_EXECUTOR_MODE_LOCK: Mutex<()> = Mutex::new(());

    pub(crate) fn without_cm_planner_executor_mode_env<F, R>(f: F) -> R
    where
        F: FnOnce() -> R,
    {
        let _g = CM_PLANNER_EXECUTOR_MODE_LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let prev = std::env::var("CM_PLANNER_EXECUTOR_MODE").ok();
        // SAFETY: serialized by mutex for this env key only.
        unsafe {
            std::env::remove_var("CM_PLANNER_EXECUTOR_MODE");
        }
        struct RestoreEnv(Option<String>);
        impl Drop for RestoreEnv {
            fn drop(&mut self) {
                unsafe {
                    match self.0.take() {
                        Some(v) => std::env::set_var("CM_PLANNER_EXECUTOR_MODE", v),
                        None => std::env::remove_var("CM_PLANNER_EXECUTOR_MODE"),
                    }
                }
            }
        }
        let _restore = RestoreEnv(prev);
        f()
    }
}

#[cfg(test)]
mod planner_executor_mode_load_tests {
    use super::load_config;
    use super::load_config_test_env::without_cm_planner_executor_mode_env;
    use std::fs;

    #[test]
    fn load_rejects_removed_planner_executor_mode_aliases() {
        without_cm_planner_executor_mode_env(|| {
            let dir = tempfile::tempdir().expect("tempdir");
            let path = dir.path().join("legacy_mode.toml");
            fs::write(
                &path,
                r#"[agent]
api_base = "https://api.deepseek.com/v1"
model = "deepseek-chat"
planner_executor_mode = "hierarchical"
"#,
            )
            .expect("write");
            let err = load_config(Some(path.to_str().unwrap())).expect_err("legacy mode must fail");
            assert!(
                err.contains("planner_executor_mode") || err.contains("single_agent"),
                "unexpected error: {err}"
            );
        });
    }

    #[test]
    fn load_accepts_explicit_single_agent() {
        without_cm_planner_executor_mode_env(|| {
            let dir = tempfile::tempdir().expect("tempdir");
            let path = dir.path().join("ok_mode.toml");
            fs::write(
                &path,
                r#"[agent]
api_base = "https://api.deepseek.com/v1"
model = "deepseek-chat"
planner_executor_mode = "single_agent"
"#,
            )
            .expect("write");
            let cfg = load_config(Some(path.to_str().unwrap())).expect("load");
            assert_eq!(
                cfg.per_plan_policy.planner_executor_mode.as_str(),
                "single_agent"
            );
        });
    }

    #[test]
    fn load_rejects_removed_mode_from_env() {
        without_cm_planner_executor_mode_env(|| {
            let dir = tempfile::tempdir().expect("tempdir");
            let path = dir.path().join("env_mode.toml");
            fs::write(
                &path,
                r#"[agent]
api_base = "https://api.deepseek.com/v1"
model = "deepseek-chat"
"#,
            )
            .expect("write");
            // SAFETY: mutex held for this key.
            unsafe {
                std::env::set_var("CM_PLANNER_EXECUTOR_MODE", "logical_dual_agent");
            }
            let err =
                load_config(Some(path.to_str().unwrap())).expect_err("legacy env mode must fail");
            assert!(
                err.contains("planner_executor_mode") || err.contains("single_agent"),
                "unexpected error: {err}"
            );
        });
    }
}

#[cfg(test)]
mod llm_reasoning_split_default_tests {
    use super::load_config;
    use super::load_config_test_env::without_cm_planner_executor_mode_env;
    use std::fs;
    use std::sync::Mutex;

    /// `load_config` 会读 `CM_LLM_REASONING_SPLIT`;本机/CI 若导出 `0` 会覆盖「省略键时按网关推断」的断言。
    static CM_LLM_REASONING_SPLIT_LOCK: Mutex<()> = Mutex::new(());

    /// 临时清除 `CM_LLM_REASONING_SPLIT`,避免本机/CI 导出干扰;结束或 panic 后恢复原值。
    ///
    /// 使用 `catch_unwind`:断言失败时仍释放 [`Mutex`],避免毒化导致后续用例 `PoisonError`。
    fn without_cm_llm_reasoning_split_env<F, R>(f: F) -> R
    where
        F: FnOnce() -> R,
    {
        let result = {
            let _guard = CM_LLM_REASONING_SPLIT_LOCK
                .lock()
                .unwrap_or_else(|e| e.into_inner());
            let prev = std::env::var("CM_LLM_REASONING_SPLIT").ok();
            // SAFETY: `remove_var`/`set_var` are unsafe in Rust 2024.
            unsafe {
                std::env::remove_var("CM_LLM_REASONING_SPLIT");
            }
            struct RestoreEnv(Option<String>);
            impl Drop for RestoreEnv {
                fn drop(&mut self) {
                    unsafe {
                        match self.0.take() {
                            Some(v) => std::env::set_var("CM_LLM_REASONING_SPLIT", v),
                            None => std::env::remove_var("CM_LLM_REASONING_SPLIT"),
                        }
                    }
                }
            }
            let _restore = RestoreEnv(prev);
            let mut f_opt = Some(f);
            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                let fun = f_opt
                    .take()
                    .expect("without_cm_llm_reasoning_split_env closure");
                fun()
            }))
        };

        match result {
            Ok(v) => v,
            Err(payload) => std::panic::resume_unwind(payload),
        }
    }

    #[test]
    fn finalize_respects_omitted_reasoning_split_for_non_minimax() {
        assert!(
            !crate::cm_config::gateway_hints::default_llm_reasoning_split_for_gateway(
                "deepseek-chat",
                "https://api.deepseek.com/v1",
            )
        );
    }

    #[test]
    fn minimax_user_toml_without_key_defaults_true() {
        // 先拿 planner-mode 锁,避免与 `load_rejects_removed_mode_from_env` 并行污染。
        without_cm_planner_executor_mode_env(|| {
            without_cm_llm_reasoning_split_env(|| {
                let dir = tempfile::tempdir().expect("tempdir");
                let path = dir.path().join("agent.toml");
                fs::write(
                    &path,
                    r#"[agent]
api_base = "https://api.minimaxi.com/v1"
model = "MiniMax-M2.7"
"#,
                )
                .expect("write");
                let cfg = load_config(Some(path.to_str().unwrap())).expect("load");
                assert!(
                    cfg.llm_vendor_flags.llm_reasoning_split,
                    "MiniMax 网关未写 llm_reasoning_split 时应默认 true"
                );
                assert!(
                    crate::cm_config::gateway_hints::fold_system_into_user_for_config(
                        &cfg.llm.model,
                        &cfg.llm.api_base
                    ),
                    "MiniMax 应自动折叠 system→user"
                );
            });
        });
    }

    #[test]
    fn minimax_user_toml_explicit_false() {
        without_cm_planner_executor_mode_env(|| {
            without_cm_llm_reasoning_split_env(|| {
                let dir = tempfile::tempdir().expect("tempdir");
                let path = dir.path().join("agent.toml");
                fs::write(
                    &path,
                    r#"[agent]
api_base = "https://api.minimaxi.com/v1"
model = "MiniMax-M2.7"
llm_reasoning_split = false
"#,
                )
                .expect("write");
                let cfg = load_config(Some(path.to_str().unwrap())).expect("load");
                assert!(!cfg.llm_vendor_flags.llm_reasoning_split);
            });
        });
    }
}

#[cfg(test)]
mod hot_reload_tests {
    use super::ScheduledAgentTask;
    use super::load_config_test_env::without_cm_planner_executor_mode_env;
    use super::{apply_hot_reload_config_subset, load_config};

    #[test]
    fn apply_hot_reload_keeps_conversation_store_path() {
        let base =
            without_cm_planner_executor_mode_env(|| load_config(None).expect("default config"));
        let mut dst = base.clone();
        let frozen = dst
            .conversation_persistence
            .conversation_store_sqlite_path
            .clone();
        let mut src = dst.clone();
        src.conversation_persistence.conversation_store_sqlite_path =
            "/tmp/should_not_apply.sqlite".to_string();
        apply_hot_reload_config_subset(&mut dst, &src);
        assert_eq!(
            dst.conversation_persistence.conversation_store_sqlite_path,
            frozen
        );
    }

    /// 组合式配置下:各子结构应从 `src` 整段替换;仅会话库路径保留 `dst` 原值。
    #[test]
    fn apply_hot_reload_updates_sections_but_not_sqlite_path() {
        let mut dst =
            without_cm_planner_executor_mode_env(|| load_config(None).expect("default config"));
        let frozen_store = dst
            .conversation_persistence
            .conversation_store_sqlite_path
            .clone();
        let mut src = dst.clone();
        src.llm.model = "hot-reload-model-snapshot".to_string();
        src.session_ui.max_message_history = src.session_ui.max_message_history.saturating_add(3);
        src.weather_tool.weather_timeout_secs =
            src.weather_tool.weather_timeout_secs.saturating_add(11);
        src.conversation_persistence.conversation_store_sqlite_path =
            "/tmp/ignored_on_hot_reload.sqlite".to_string();
        apply_hot_reload_config_subset(&mut dst, &src);
        assert_eq!(
            dst.conversation_persistence.conversation_store_sqlite_path,
            frozen_store
        );
        assert_eq!(dst.llm.model, src.llm.model);
        assert_eq!(
            dst.session_ui.max_message_history,
            src.session_ui.max_message_history
        );
        assert_eq!(
            dst.weather_tool.weather_timeout_secs,
            src.weather_tool.weather_timeout_secs
        );
    }

    #[test]
    fn apply_hot_reload_updates_scheduled_tasks_from_src() {
        let mut dst =
            without_cm_planner_executor_mode_env(|| load_config(None).expect("default config"));
        dst.conversation_persistence.scheduled_agent_tasks.clear();
        let mut src = dst.clone();
        src.conversation_persistence.scheduled_agent_tasks = vec![ScheduledAgentTask {
            id: "cron_smoke".to_string(),
            schedule: "0 0 * * * *".to_string(),
            message: "hello".to_string(),
            conversation_id: None,
            new_conversation: false,
            agent_role: None,
        }];
        apply_hot_reload_config_subset(&mut dst, &src);
        assert_eq!(dst.conversation_persistence.scheduled_agent_tasks.len(), 1);
        assert_eq!(
            dst.conversation_persistence.scheduled_agent_tasks[0].id,
            "cron_smoke"
        );
    }
}

#[cfg(test)]
mod context_budget_warning_tests {
    use super::finalize::context_budget_vs_history_suspicious;

    #[test]
    fn suspicious_when_budget_on_and_min_ge_max_history() {
        assert!(context_budget_vs_history_suspicious(8, 100_000, 8));
        assert!(context_budget_vs_history_suspicious(8, 1, 10));
    }

    #[test]
    fn not_suspicious_when_budget_off() {
        assert!(!context_budget_vs_history_suspicious(8, 0, 100));
    }

    #[test]
    fn not_suspicious_when_min_below_max_history() {
        assert!(!context_budget_vs_history_suspicious(32, 50_000, 4));
    }
}

#[cfg(test)]
mod numeric_validate_tests {
    use super::builder::ConfigBuilder;
    use super::validate;
    use std::collections::HashMap;

    #[test]
    fn rejects_temperature_above_two() {
        let mut b = ConfigBuilder::default();
        b.llm_sampling.temperature = Some(3.0);
        let err = validate::validate_builder_numeric_ranges(&b).unwrap_err();
        assert!(err.contains("temperature"), "err: {err}");
    }

    #[test]
    fn parallel_wall_timeout_out_of_range() {
        let mut m = HashMap::new();
        m.insert("http_fetch_spawn_timeout".into(), 100_000u64);
        let mut b = ConfigBuilder::default();
        b.tool_registry_policy
            .tool_registry_parallel_wall_timeout_secs = m;
        let err = validate::validate_builder_numeric_ranges(&b).unwrap_err();
        assert!(err.contains("parallel_wall_timeout_secs"), "err: {err}");
    }
}