crabmate 0.5.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
//! `GET /health`、`GET /status`。

use axum::Json;
use axum::extract::{Query, State};
use axum::response::{IntoResponse, Response};
use crate::cm_api_contract::StatusShellView;
use serde::Deserialize;

use crate::agent::message_pipeline::MESSAGE_PIPELINE_COUNTERS;
use crate::chat_job_queue;
use crate::health;
use crate::tool_registry;
use crate::web::app_state_facets::{WebHealthAppFacet, WebStatusAppFacet};

pub(crate) async fn health_handler(State(facet): State<WebHealthAppFacet>) -> impl IntoResponse {
    let eff = facet.effective_workspace_path().await;
    let (work_dir, auth_mode, probe, probe_cache_secs, api_base) = {
        let g = facet.http.cfg.read().await;
        let wd = if eff.trim().is_empty() {
            std::path::PathBuf::from(g.command_exec.run_command_working_dir.clone())
        } else {
            std::path::PathBuf::from(eff)
        };
        (
            wd,
            g.llm.llm_http_auth_mode,
            g.web_api.health_llm_models_probe,
            g.web_api.health_llm_models_probe_cache_secs,
            g.llm.api_base.clone(),
        )
    };
    let mut report = health::build_health_report(&work_dir, facet.mount_web_ui).await;
    health::append_llm_models_endpoint_probe(
        &mut report,
        health::LlmModelsEndpointProbeParams {
            enabled: probe,
            cache_secs: probe_cache_secs,
            cache_cell: facet.llm_models_health_cache.as_ref(),
            client: &facet.http.client,
            api_base: api_base.as_str(),
            api_key: facet.http.api_key.as_ref(),
            auth_mode,
        },
    )
    .await;
    Json(report)
}

#[derive(serde::Serialize)]
struct StatusResponse {
    status: &'static str,
    model: String,
    api_base: String,
    max_tokens: u32,
    llm_context_tokens: u32,
    temperature: f32,
    /// 默认写入 `chat/completions` 的整数 seed(未配置则为 `null`)。
    llm_seed: Option<i64>,
    /// 当前加载进 API 请求的工具定义数量(`--no-tools` 时为 0)。
    tool_count: usize,
    /// 与模型对话时实际下发的工具名列表。
    tool_names: Vec<String>,
    /// `tool_registry` 中显式声明的分发策略(其余名称运行时走同步 `run_tool`)。
    tool_dispatch_registry: &'static [tool_registry::ToolDispatchMeta],
    reflection_default_max_rounds: usize,
    final_plan_requirement: crate::agent::per_coord::FinalPlanRequirementMode,
    plan_rewrite_max_attempts: usize,
    final_plan_require_strict_workflow_node_coverage: bool,
    final_plan_semantic_check_enabled: bool,
    final_plan_semantic_check_accept_legacy_text: bool,
    final_plan_semantic_check_max_non_readonly_tools: usize,
    final_plan_semantic_check_max_tokens: u32,
    /// 规划器/执行器模式(仅 `single_agent`)。
    planner_executor_mode: &'static str,
    /// 编排档位(运行时恒 `react`)。
    orchestration_profile: &'static str,
    /// 本进程有效编排路径摘要(固定 session_mode / Act 句启发式 → ReAct;不含用户任务级门控)。
    effective_orchestration_path: String,
    /// SyncDefault 工具沙盒:`none` | `docker`。
    sync_default_tool_sandbox_mode: String,
    /// `docker` 模式下的镜像名(可能为空表示未启用或未配置)。
    sync_default_tool_sandbox_docker_image: String,
    /// Docker 沙盒容器进程身份摘要:`effective_uid:gid` | `image_default`(与配置 `current` / `image` 等对应)。
    sync_default_tool_sandbox_docker_user_effective: String,
    max_message_history: usize,
    tool_message_max_chars: usize,
    context_char_budget: usize,
    /// 会话同步管道实际采用的近似字符预算(`context_char_budget` 与按 `llm_context_tokens` 推导值取更小)。
    effective_context_char_budget: usize,
    /// `tiktoken-rs` 计数时采用的 OpenAI 模型 id(配置 `model` 无法识别时回落 `gpt-4` / `gpt-4o`)。
    tiktoken_prompt_counting_model: String,
    /// 新会话仅 `system` 时的 prompt token 粗估(与首轮出站一致;**不含**项目画像 `user`、工具 JSON)。
    /// 键为命名角色 id;空字符串表示未选角色 / 全局默认 `system_prompt`。
    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    tiktoken_new_session_baseline_by_agent_role: std::collections::BTreeMap<String, u32>,
    context_summary_trigger_chars: usize,
    chat_queue_max_concurrent: usize,
    chat_queue_max_pending: usize,
    parallel_readonly_tools_max: usize,
    /// 单轮 `read_file` 缓存容量;`0` 表示关闭。
    read_file_turn_cache_max_entries: usize,
    chat_queue_running: usize,
    chat_queue_completed_ok: u64,
    chat_queue_completed_cancelled: u64,
    chat_queue_completed_err: u64,
    chat_queue_recent_jobs: Vec<chat_job_queue::ChatJobRecord>,
    /// 队列中正在执行的 `/chat`、`/chat/stream` 任务之 PER 镜像(无任务或无非队列调用时为空)。
    #[serde(skip_serializing_if = "Vec::is_empty")]
    per_active_jobs: Vec<chat_job_queue::PerFlightStatusEntry>,
    /// Web `POST /workspace` 允许的工作区根目录个数(未配置 `workspace_allowed_roots` 时为 1,即仅 `run_command_working_dir`)。
    workspace_allowed_roots_count: usize,
    /// 当前会话存储中的条目数(按 `conversation_id`;SQLite 或内存后端均计入)。
    conversation_store_entries: usize,
    /// 配置中是否配置了非空的 `conversation_store_sqlite_path`(与当前进程实际后端可不同)。
    conversation_store_sqlite_path_configured: bool,
    /// 当前进程是否使用 SQLite 作为 Web 会话后端(可被 `POST /config/session/conversation-store` 切换)。
    conversation_store_sqlite_active: bool,
    /// 长期记忆是否启用(配置)。
    long_term_memory_enabled: bool,
    /// 向量后端:`disabled` / `fastembed` 等。
    long_term_memory_vector_backend: String,
    /// 本进程是否已挂载记忆运行时(含与会话库共用 SQLite 或独立库路径)。
    long_term_memory_store_ready: bool,
    /// 异步索引累计失败次数(成功回合不递增;仅排障用)。
    long_term_memory_index_errors: u64,
    /// Web 新会话首轮是否注入自动生成的项目画像 Markdown。
    project_profile_inject_enabled: bool,
    /// 项目画像注入正文最大字符数(0 表示关闭生成)。
    project_profile_inject_max_chars: usize,
    /// 首轮是否追加 `cargo metadata` + package.json 的结构化摘要与 Mermaid workspace 图。
    project_dependency_brief_inject_enabled: bool,
    project_dependency_brief_inject_max_chars: usize,
    /// 是否要求非只读工具在 JSON 中带 `crabmate_explain_why`。
    tool_call_explain_enabled: bool,
    tool_call_explain_min_chars: usize,
    tool_call_explain_max_chars: usize,
    /// 自进程启动以来,同步上下文管道实际触发次数(累计,供排障;非「当前会话」)。
    message_pipeline_trim_count_hits: u64,
    message_pipeline_trim_char_budget_hits: u64,
    message_pipeline_tool_compress_hits: u64,
    message_pipeline_orphan_tool_drops: u64,
    /// 模型 HTTP 鉴权:`bearer` | `none`(如本地 Ollama 可不设 API_KEY)。
    llm_http_auth_mode: &'static str,
    /// 配置中的命名角色 id 列表(升序);未启用多角色时为空。
    #[serde(skip_serializing_if = "Vec::is_empty")]
    agent_role_ids: Vec<String>,
    /// Web/CLI 未指定 `agent_role` 时使用的默认角色 id(`null` 表示用全局 `system_prompt`)。
    #[serde(skip_serializing_if = "Option::is_none")]
    default_agent_role_id: Option<String>,
    /// 全局默认会话工作模式(`ask` / `plan` / `act`)。
    default_session_mode: String,
    /// 各命名角色的默认会话模式(仅含配置了 `default_session_mode` 的角色)。
    #[serde(skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    agent_role_default_session_modes: std::collections::BTreeMap<String, String>,
}

#[derive(Debug, Deserialize)]
pub(crate) struct StatusQuery {
    #[serde(default)]
    view: Option<String>,
}

struct StatusShellBuildInput<'a> {
    cfg: &'a crate::AgentConfig,
    conversation_store_sqlite_path_configured: bool,
    conversation_store_sqlite_active: bool,
    agent_role_ids: &'a [String],
    tiktoken_new_session_baseline_by_agent_role: std::collections::BTreeMap<String, u32>,
}

fn build_status_shell_view(input: StatusShellBuildInput<'_>) -> StatusShellView {
    let StatusShellBuildInput {
        cfg,
        conversation_store_sqlite_path_configured,
        conversation_store_sqlite_active,
        agent_role_ids,
        tiktoken_new_session_baseline_by_agent_role,
    } = input;
    StatusShellView {
        status: StatusShellView::ok_prefix().to_string(),
        model: cfg.llm.model.clone(),
        api_base: cfg.llm.api_base.clone(),
        agent_role_ids: agent_role_ids.to_vec(),
        default_agent_role_id: cfg.roles_prompts.default_agent_role_id.clone(),
        default_session_mode: cfg.roles_prompts.default_session_mode.as_str().to_string(),
        agent_role_default_session_modes: {
            let mut m = std::collections::BTreeMap::new();
            for (id, spec) in cfg.roles_prompts.agent_roles.iter() {
                if let Some(mode) = spec.default_session_mode {
                    m.insert(id.clone(), mode.as_str().to_string());
                }
            }
            m
        },
        context_char_budget: cfg.context_pipeline.context_char_budget,
        llm_context_tokens: cfg.llm_sampling.llm_context_tokens,
        effective_context_char_budget: cfg.effective_context_char_budget_for_pipeline(),
        tiktoken_prompt_counting_model:
            crate::agent::tiktoken_prompt_tokens::tiktoken_model_id_for_config_model(
                cfg.llm.model.as_str(),
            ),
        tiktoken_new_session_baseline_by_agent_role,
        executor_model: cfg.llm.executor_model.clone().unwrap_or_default(),
        executor_api_base: String::new(),
        planner_executor_mode: cfg
            .per_plan_policy
            .planner_executor_mode
            .as_str()
            .to_string(),
        conversation_store_sqlite_path_configured,
        conversation_store_sqlite_active,
    }
}

fn tiktoken_new_session_baselines_by_role(
    cfg: &crate::AgentConfig,
    tool_recorder: &std::sync::Arc<crate::tool_stats::ToolOutcomeRecorder>,
    workspace_root: &std::path::Path,
    agent_role_ids: &[String],
) -> std::collections::BTreeMap<String, u32> {
    let memory_snippet = if cfg.context_bootstrap_inject.agent_memory_file_enabled {
        crate::memory::agent_memory::load_memory_snippet(
            workspace_root,
            cfg.context_bootstrap_inject.agent_memory_file.as_str(),
            cfg.context_bootstrap_inject.agent_memory_file_max_chars,
        )
    } else {
        None
    };
    let mut tiktoken_new_session_baseline_by_agent_role = std::collections::BTreeMap::new();
    let push_baseline = |map: &mut std::collections::BTreeMap<String, u32>,
                         key: String,
                         role: Option<&str>| {
        let system = match crate::context_bootstrap::conversation_turn_bootstrap::augmented_system_for_new_conversation(
            cfg,
            role,
            tool_recorder,
        ) {
            Ok(s) => s,
            Err(_) => return,
        };
        let messages =
            crate::context_bootstrap::conversation_turn_bootstrap::new_session_prompt_baseline_messages(
                cfg,
                &system,
                workspace_root,
                memory_snippet.clone(),
            );
        if let Some(snap) =
            crate::agent::tiktoken_prompt_tokens::prompt_token_count_vendor_shaped_for_session(
                cfg, &messages,
            )
        {
            map.insert(key, snap.prompt_tokens);
        }
    };
    push_baseline(
        &mut tiktoken_new_session_baseline_by_agent_role,
        String::new(),
        None,
    );
    for id in agent_role_ids {
        push_baseline(
            &mut tiktoken_new_session_baseline_by_agent_role,
            id.clone(),
            Some(id.as_str()),
        );
    }
    tiktoken_new_session_baseline_by_agent_role
}

pub(crate) async fn status_handler(
    State(state): State<WebStatusAppFacet>,
    Query(query): Query<StatusQuery>,
) -> Response {
    let cfg = state.http.cfg.read().await;
    let mp = MESSAGE_PIPELINE_COUNTERS.snapshot();
    let conversation_store_entries = state.conversation_count().await;
    let conversation_store_sqlite_path_configured = !cfg
        .conversation_persistence
        .conversation_store_sqlite_path
        .trim()
        .is_empty();
    let conversation_store_sqlite_active = {
        let b = state.conversation.conversation_backing.read().await;
        b.is_sqlite()
    };
    let (ltm_ready, ltm_idx_err) = match state.long_term_memory.as_ref() {
        Some(l) => (
            true,
            l.index_errors.load(std::sync::atomic::Ordering::Relaxed),
        ),
        None => (false, 0u64),
    };
    let tool_names: Vec<String> = state
        .http
        .tools
        .iter()
        .map(|t| t.function.name.clone())
        .collect();
    let mut agent_role_ids: Vec<String> = cfg.roles_prompts.agent_roles.keys().cloned().collect();
    agent_role_ids.sort();
    let tool_recorder = &state.process_handles.tool_outcome_recorder;
    let workspace_root = std::path::PathBuf::from(state.effective_workspace_path().await);
    let tiktoken_new_session_baseline_by_agent_role = tiktoken_new_session_baselines_by_role(
        &cfg,
        tool_recorder,
        workspace_root.as_path(),
        &agent_role_ids,
    );
    let effective_orchestration_path = crate::cm_config::effective_orchestration_path_summary(
        cfg.per_plan_policy.planner_executor_mode.as_str(),
        cfg.per_plan_policy.orchestration_profile,
    );
    if query.view.as_deref() == Some("shell") {
        return Json(build_status_shell_view(StatusShellBuildInput {
            cfg: &cfg,
            conversation_store_sqlite_path_configured,
            conversation_store_sqlite_active,
            agent_role_ids: &agent_role_ids,
            tiktoken_new_session_baseline_by_agent_role,
        }))
        .into_response();
    }
    Json(StatusResponse {
        status: "ok",
        model: cfg.llm.model.clone(),
        api_base: cfg.llm.api_base.clone(),
        max_tokens: cfg.llm_sampling.max_tokens,
        llm_context_tokens: cfg.llm_sampling.llm_context_tokens,
        temperature: cfg.llm_sampling.temperature,
        llm_seed: cfg.llm_sampling.llm_seed,
        tool_count: tool_names.len(),
        tool_names,
        tool_dispatch_registry: tool_registry::all_dispatch_metadata(),
        reflection_default_max_rounds: cfg.per_plan_policy.reflection_default_max_rounds,
        final_plan_requirement: cfg.per_plan_policy.final_plan_requirement,
        plan_rewrite_max_attempts: cfg.per_plan_policy.plan_rewrite_max_attempts,
        final_plan_require_strict_workflow_node_coverage: cfg
            .per_plan_policy
            .final_plan_require_strict_workflow_node_coverage,
        final_plan_semantic_check_enabled: cfg.per_plan_policy.final_plan_semantic_check_enabled,
        final_plan_semantic_check_accept_legacy_text: cfg
            .per_plan_policy
            .final_plan_semantic_check_accept_legacy_text,
        final_plan_semantic_check_max_non_readonly_tools: cfg
            .per_plan_policy
            .final_plan_semantic_check_max_non_readonly_tools,
        final_plan_semantic_check_max_tokens: cfg
            .per_plan_policy
            .final_plan_semantic_check_max_tokens,
        planner_executor_mode: cfg.per_plan_policy.planner_executor_mode.as_str(),
        orchestration_profile: cfg.per_plan_policy.orchestration_profile.as_str(),
        effective_orchestration_path,
        sync_default_tool_sandbox_mode: cfg
            .sync_tool_sandbox
            .sync_default_tool_sandbox_mode
            .as_str()
            .to_string(),
        sync_default_tool_sandbox_docker_image: cfg
            .sync_tool_sandbox
            .sync_default_tool_sandbox_docker_image
            .clone(),
        sync_default_tool_sandbox_docker_user_effective: match cfg
            .sync_tool_sandbox
            .sync_default_tool_sandbox_docker_user
            .as_docker_user_string()
        {
            Some(s) => s.to_string(),
            None => "image_default".to_string(),
        },
        max_message_history: cfg.session_ui.max_message_history,
        tool_message_max_chars: cfg.tool_transcript.tool_message_max_chars,
        context_char_budget: cfg.context_pipeline.context_char_budget,
        effective_context_char_budget: cfg.effective_context_char_budget_for_pipeline(),
        tiktoken_prompt_counting_model:
            crate::agent::tiktoken_prompt_tokens::tiktoken_model_id_for_config_model(
                cfg.llm.model.as_str(),
            ),
        tiktoken_new_session_baseline_by_agent_role,
        context_summary_trigger_chars: cfg.context_pipeline.context_summary_trigger_chars,
        chat_queue_max_concurrent: state.chat_queue.max_concurrent(),
        chat_queue_max_pending: state.chat_queue.max_pending(),
        parallel_readonly_tools_max: cfg.chat_queues_cache.parallel_readonly_tools_max,
        read_file_turn_cache_max_entries: cfg.chat_queues_cache.read_file_turn_cache_max_entries,
        chat_queue_running: state.chat_queue.running_count(),
        chat_queue_completed_ok: state.chat_queue.completed_ok(),
        chat_queue_completed_cancelled: state.chat_queue.completed_cancelled(),
        chat_queue_completed_err: state.chat_queue.completed_err(),
        chat_queue_recent_jobs: state.chat_queue.recent_jobs(),
        per_active_jobs: state.chat_queue.active_per_jobs(),
        workspace_allowed_roots_count: cfg.workspace_roots.workspace_allowed_roots.len(),
        conversation_store_entries,
        conversation_store_sqlite_path_configured,
        conversation_store_sqlite_active,
        long_term_memory_enabled: cfg.long_term_memory.long_term_memory_enabled,
        long_term_memory_vector_backend: cfg
            .long_term_memory
            .long_term_memory_vector_backend
            .as_str()
            .to_string(),
        long_term_memory_store_ready: ltm_ready,
        long_term_memory_index_errors: ltm_idx_err,
        project_profile_inject_enabled: cfg.context_bootstrap_inject.project_profile_inject_enabled,
        project_profile_inject_max_chars: cfg
            .context_bootstrap_inject
            .project_profile_inject_max_chars,
        project_dependency_brief_inject_enabled: cfg
            .context_bootstrap_inject
            .project_dependency_brief_inject_enabled,
        project_dependency_brief_inject_max_chars: cfg
            .context_bootstrap_inject
            .project_dependency_brief_inject_max_chars,
        tool_call_explain_enabled: cfg.tool_call_explain.tool_call_explain_enabled,
        tool_call_explain_min_chars: cfg.tool_call_explain.tool_call_explain_min_chars,
        tool_call_explain_max_chars: cfg.tool_call_explain.tool_call_explain_max_chars,
        message_pipeline_trim_count_hits: mp.trim_count_hits,
        message_pipeline_trim_char_budget_hits: mp.trim_char_budget_hits,
        message_pipeline_tool_compress_hits: mp.tool_compress_hits,
        message_pipeline_orphan_tool_drops: mp.orphan_tool_drops,
        llm_http_auth_mode: cfg.llm.llm_http_auth_mode.as_str(),
        agent_role_ids,
        default_agent_role_id: cfg.roles_prompts.default_agent_role_id.clone(),
        default_session_mode: cfg.roles_prompts.default_session_mode.as_str().to_string(),
        agent_role_default_session_modes: {
            let mut m = std::collections::BTreeMap::new();
            for (id, spec) in cfg.roles_prompts.agent_roles.iter() {
                if let Some(mode) = spec.default_session_mode {
                    m.insert(id.clone(), mode.as_str().to_string());
                }
            }
            m
        },
    })
    .into_response()
}