crates/atomcode-capabilities/src/provider/ 是 AtomCode 中唯一直接和大模型 HTTP 接口打交道的地方。它把内核(atomcode-kernel)定义的中立契约 LlmProvider 落到四种线协议(wire protocol)上:
| 线协议 | 适配器 | 端点 | 流格式 |
|---|---|---|---|
| OpenAI Chat Completions(含 DeepSeek / GLM / Kimi / Qwen / vLLM / OpenRouter / AtomGit 网关等兼容端) | OpenAiCompatProvider(openai_compat.rs) |
{base}/chat/completions |
data: SSE + [DONE] |
| OpenAI Responses API | ResponsesProvider(responses.rs) |
{base}/responses |
event: response.* 命名 SSE |
| Anthropic Messages(含 DeepSeek Messages 方言及多家兼容网关) | AnthropicProvider(anthropic.rs) |
{base}/v1/messages |
message_start / content_block_* / message_delta / message_stop 事件型 SSE |
| Ollama 原生 | OllamaProvider(ollama.rs) |
{base}/api/chat |
NDJSON(每行一个完整 JSON) |
在这四个适配器之上,本目录还提供:开流重试与退避(retry.rs)、首 token / 空闲看门狗(watchdog.rs)、推理内容回放策略(reasoning.rs)、按请求签名(sign.rs / atomgit_sign.rs)、跟随系统代理的逐请求路由(auto_proxy.rs)、请求体大小闸门(request_size.rs)、只记元数据的诊断(input_profile.rs / latency.rs / content_marker.rs)、模型发现与公共目录(discovery.rs / discovery_catalog.rs),以及保存账户时的端点探测(probe.rs)。
设计主线有三条,贯穿全部文件:
Message / ToolDef / ChatOptions 进,StreamEvent 流出;协议差异全部在线边界消化。serde_json::Map 构建,不含时间戳或 uuid,相同历史永远序列化成相同字节,以最大化上游 prompt cache 命中率。源码根:
/home/jiahua/Desktop/ETC/atomcode/crates/atomcode-capabilities/src/provider/(下文路径均相对此目录,除非另有说明)。
atomcode_kernel::provider::LlmProvider。StreamEvent。docs/reasoning-loop-guard.md。llm-utility、角色模型都在 coding/harness 层,见 docs/mixed-models.md、docs/mode-models.md。atomcode-capabilities 属于 L1,只依赖 L0 atomcode-kernel,以及可选的 atomcode-config / atomcode-auth / atomcode-i18n。atomcode-core。atomcode-auth,需要配置的地方(代理、TLS、自定义头)走 atomcode-config。Cargo.toml 中 provider 是默认 feature(default = ["provider", "tools"])。启用 provider 时拉入的依赖:
provider = [
reqwest(rustls), rustls-native-certs, async-stream, dirs, httpdate,
atomcode-auth, atomcode-config, getrandom, tracing, fs2, hyper, socket2
]
atomcode-kernel (L0)
LlmProvider / ChatOptions / StreamEvent / ProviderError
▲
│ impl
┌────────────────────────┴───────────────────────────────┐
│ atomcode-capabilities::provider (L1) │
│ openai_compat ── responses (复用 open_stream/client) │
│ anthropic ── ollama │
│ retry / watchdog / reasoning / sign / auto_proxy ... │
│ discovery(+catalog) / probe │
└────────────────────────┬───────────────────────────────┘
uses │ uses
atomcode-config (proxy/tls/headers/i18n) atomcode-auth (OAuth, gateway_crypto)
▲
consumers: atomcode-coding(装配 provider)、atomcode-harness、
atomcode-cli / atomcode-daemon(/provider 面板、
discover-models、probe)
开发依赖 wiremock、serial_test、ctor 用于集成测试;ctor 在测试进程启动时隔离 ATOMCODE_HOME。
| 文件 | 行数 | 职责 |
|---|---|---|
mod.rs |
407 | 导出;DEFAULT_USER_AGENT="atomcode";record_request_diagnostics(wire dump);friendly_http_error;apply_account_headers;push_system_coalesced;model_suggests_vision;reason_effort_applicable |
openai_compat.rs |
7563(非测试约 2975) | Chat Completions 适配器、SwappableClient、SseDecoder、schema 规范化、open_stream(被 Responses 复用) |
responses.rs |
1751 | Responses API 适配器、ResponsesSseDecoder |
anthropic.rs |
3570 | Messages API 适配器、AnthropicSseDecoder、prompt cache 标记、DeepSeek Messages 方言、Bearer/x-api-key 鉴权选择 |
ollama.rs |
1547 | /api/chat 适配器、OllamaNdjsonDecoder |
reasoning.rs |
679 | ReasoningPolicy(Include/Preserve/Exclude)、ReasoningField、InlineThink(拆 <think>)、REASONING_PLACEHOLDER |
retry.rs |
1525(非测试约 560 + bounded_open) |
RetryPolicy、可重试状态码/错误分类、Retry-After 解析、退避抖动、bounded_open 总预算、错误文案与代理提示 |
watchdog.rs |
168 | StreamWatchdog:首内容截止 + 空闲截止 |
sign.rs |
66 | RequestSigner trait、SignedAuth、RequestSigningError |
atomgit_sign.rs |
160 | AtomGit 网关签名器(OAuth + gateway_crypto),401 后一次性恢复 |
auto_proxy.rs |
427 | “跟随系统”代理模式的逐请求刷新与死 loopback 代理剔除 |
request_size.rs |
71 | AtomGit 网关 20 MB 请求体闸门 |
input_profile.rs |
356 | 请求体按 JSON 字节分类统计(不记内容) |
latency.rs |
279 | 请求级 tracing span 与阶段计时 |
content_marker.rs |
148 | 识别正文里出现的原生 chat template 标记(MiniMax) |
discovery.rs |
1032 | GET /models 等模型列表发现 |
discovery_catalog.rs |
520 | models.opencode.ai 公共目录补全元数据 |
probe.rs |
689 | 保存账户时 POST /chat/completions 空请求体检 |
bench.rs |
11 | bench feature 下暴露 SSE 解码基准入口 |
定义在 crates/atomcode-kernel/src/provider.rs(trait 约在第 138 行)与 stream.rs(StreamEvent 约在第 113 行):
#[async_trait]
pub trait LlmProvider: Send + Sync {
fn model_name(&self) -> &str;
fn context_window(&self) -> u32; // 0 = 未知
fn supports_vision(&self) -> bool { false }
fn effort_levels(&self) -> Vec<String> { vec![] }
fn replays_reasoning(&self) -> bool { true }
fn bind_session_id(&self, _id: &str) {} // 一次性,OnceLock
async fn chat_stream(&self, messages: &[Message], tools: &[ToolDef],
options: &ChatOptions)
-> Result<BoxStream<'static, StreamEvent>, ProviderError>;
}
pub struct ChatOptions {
pub reasoning_effort: Option<ReasoningEffort>, // Low/Medium/High/XHigh/Max
pub max_tokens: Option<u32>,
pub temperature: Option<f32>,
pub reasoning_loop_guard: ..., // 永不上线
pub tool_choice: ToolChoice, // Auto/Required/Specific/None
pub rate_limit_retry_owner: RateLimitRetryOwner, // Provider/Kernel
pub request_recovery: Option<RequestRecoveryBudget>, // 存在 ⇒ 调用方负责瞬态恢复
}
pub enum StreamEvent {
TextDelta(String), Reasoning(String),
ReasoningSignature { opaque: String, provider: String },
ToolCall(ToolCall),
ToolCallDelta { index, id, name, arguments }, // 仅展示
Usage(TokenUsage), // {prompt, completion, cached},按字段 merge_max
ResponseId(String), ResponseModel(String),
Error(ProviderError), Malformed, Done { truncated: bool },
}
pub struct ProviderError {
pub retryable: bool, pub message: String,
pub http_status: Option<u16>, pub code: Option<String>,
pub retry_after_secs: Option<u64>,
}
几个错误码常量是 provider 与上层的稳定协议:
OPEN_TIMEOUT_CODE="open_timeout"STREAM_TRANSPORT_INTERRUPTED_CODESTREAM_IDLE_TIMEOUT_CODEREQUEST_RECOVERY_EXHAUSTED_CODEprovider 自己还会产出以下码:
upstream_error_bodynot_an_event_streamsse_line_too_largetool_call_delta_limitrequest_body_too_largeauthentication_expired / authentication_unavailable / request_signing_failed / authentication_refresh_transientsystem_proxy_refresh_failed包装器义务:任何包装 LlmProvider 的装饰器都必须转发 supports_vision、effort_levels、replays_reasoning 和 context_window,否则会静默降级。
SwappableClient(openai_compat.rs 约第 611 行)四个适配器都持有 Arc<SwappableClient>,Anthropic 和 Responses 直接复用 openai_compat::SwappableClient::new_with_proxy。结构如下:
RwLock<(reqwest::Client, tls12: bool, proxy: Option<ProxyConfig>)>,加一个 refresh mutex。for_request()
auto_proxy::for_request(),得到当前“跟随系统”代理快照。rebuild(tls12)
IncompleteMessage。pool_idle_timeout = retry::POOL_IDLE_TIMEOUT = 15s:比多数网关的空闲回收更早地回收空闲连接。SSL_CERT_FILE。build_http_client_recovers_from_malformed_ssl_cert_file_via_backstop)。atomcode_config::tls::should_cap_url 决定是否给某些 URL 锁 TLS 1.2。BadRecordMac / DecryptError)时,经 should_try_fallback / latch_managed_tls12 锁存到 TLS 1.2 并重建。redirect::Policy::none())。reqwest 跨主机会丢 Authorization,但不会丢 x-api-key 或自定义头。测试见 tests/provider_headers.rs::custom_credentials_never_follow_a_redirect_to_another_server。skip_tls_verify:映射为 danger_accept_invalid_certs(true),用于自签名的内网网关。DEFAULT_USER_AGENT = "atomcode"。宿主注入 atomcode/<version> 作为 user_agent,用于网关归因。部分网关(如 AtomGit)会拒绝 reqwest 默认 UA。apply_account_headers(mod.rs):把用户配置的 ProviderHeaders 加到请求上,并标记为 sensitive。出错信息经 redact_header_error 脱敏;上游错误体也会经 headers.redact(...) 把回显的凭据替换掉(tests/provider_headers.rs::every_chat_wire_sends_account_headers_and_redacts_echoed_credentials)。bind_session_id,适配器存进 OnceLock,每次请求加 x-atomcode-session-id。目的是让网关把同一会话路由到同一后端,提高前缀缓存命中率。HTTP-Referer: https://gitcode.com/atomgit_atomcode/atomcode 和 X-Title: AtomCode。x-opencode-session。未绑定会话时使用进程级随机 id,由 apply_opencode_session 统一处理,Anthropic 适配器也走它。url_host 会先剥掉 userinfo 再比较主机,防止 https://openrouter.ai@evil 一类误判。RequestSigner(sign.rs)pub struct SignedAuth { pub bearer: Option<String>,
pub headers: Vec<(String, String)>,
pub account_id: Option<String> }
#[async_trait]
pub trait RequestSigner: Send + Sync {
fn sign(&self, body: &[u8]) -> Result<SignedAuth, RequestSigningError>;
async fn recover_unauthorized(&self, rejected: &SignedAuth)
-> Result<bool, RequestSigningError> { Ok(false) }
}
request_signer = None,即普通 bearer_auth(api_key)。atomgit_sign.rs 是唯一的内置实现:
<user_dir>/auth.toml 取有效 OAuth 会话(get_valid_auth_session)。atomcode_auth::gateway_crypto::signer().sign(SignInput{method:"POST", path, body, oauth_token, user_id, ...}),产出签名头。bearer 为 OAuth access token,account_id 为 user_id。recover_unauthorized 在 spawn_blocking 中调用 recover_auth_after_unauthorized(user_dir, rejected_token, expected_user_id)。
account_id 防止恢复期间“意外切换账号”。classify_auth_recovery_error 映射为 RecoveryTransient / ReauthenticationRequired / SigningFailed。recover_unauthorized 并重签重发;第二次 401 返回 authentication_expired。测试为 refreshable_signer_recovers_one_401_and_resigns_retry。atomgit_request_signer(base_url, user_dir) 未登录时直接 Err("AtomGit gateway requires login — run /login first"),path 由 gateway_crypto::canonical_chat_completions_path(base_url) 规范化。is_atomgit_gateway 与 signer_available 供装配层判断。auto_proxy.rs只在 ProxyMode::FollowSystem 下生效。不写进程环境变量,也不持久化:
for_request() 在 blocking 线程池执行 refresh(),总时限 REFRESH_TIMEOUT=2s;超时会 abort 掉排队任务。refresh 内部调用 atomcode_config::proxy::refreshed_follow_system_config()(macOS 上可能拉起 scutil)。without_dead_loopback):
http/https/all 中指向 localhost 或回环 IP 的代理,做 50 ms TCP 探测。ConnectionRefused 时才判死。超时不算死,因为它可能是一个 accept 队列满的活监听。ALL_PROXY,而是直连。socket2 + select 实现非阻塞探测。apply():先 builder.no_proxy() 关掉 reqwest 的环境代理缓存,再只安装本次快照里的 http/https 代理,并带上用户的 no_proxy 绕过列表。代理 URL 可能含凭据,因此出错信息从不拼接源错误。ProxyReadError(retryable 由其决定),错误码 system_proxy_refresh_failed。测试:auto_proxy_requests_switch_to_direct_then_back_and_honor_no_proxy(openai_compat 内)。
retry.rspub struct RetryPolicy { pub max_attempts: u32, pub base_delay: Duration, pub max_delay: Duration }
// Default: 3 次, 500ms 基数, 8s 上限;RetryPolicy::none() = 1 次
| 函数 | 语义 |
|---|---|
policy_for_call(cfg, options) |
options.request_recovery.is_some() 时返回 none(),由调用方统一管理恢复预算,避免两层重试相乘 |
is_retryable_status |
408/425/429/500/502/503/504/529 |
should_retry_open_status(code, owner) |
429 只有当 RateLimitRetryOwner::Provider 时才在 provider 内重试;Kernel 拥有时直接上抛 |
parse_retry_after |
支持 delta-seconds 与 HTTP-date(httpdate) |
compute_backoff(attempt, policy) |
指数退避,±25% 抖动(种子取 subsec nanos) |
is_retryable_reqwest_error |
timeout、connect、陈旧连接(瞬态 io kind 或 hyper IncompleteMessage)、TLS 损坏 |
err_chain / url_without_credentials |
错误链展开并剥离 URL 凭据 |
proxy_unreachable_hint / effective_proxy_env / sanitize_proxy_url |
出现 “failed to create underlying connection” 时提示检查 /proxy 或 no_proxy |
connection_reset_hint |
Windows 10054 专用提示 |
stream_read_error_message |
中文文案,区分“重试耗尽”与“部分响应” |
bounded_open(per_attempt, recovery, fut) |
见下 |
bounded_open(约第 1346 行):把所有 OPEN 尝试和退避加在一起限时。
per_attempt * 2。RequestRecoveryBudget,先 limit_transport_wait(budget),再用快照中的 transport_wait + reserved_wait 扣减已用时间。record_transport_wait。这保证了“运行时上层不会对一个已耗尽预算的请求再重试一轮”。
有意的重放风险:代码注释承认,把陈旧连接或 TLS 损坏视为可重试,理论上可能重放已被服务端接收的 POST。这里取舍为可用性优先,因为 LLM 推理请求是幂等的生成,重复只多计费一次。
StreamWatchdog(watchdog.rs)pub struct StreamWatchdog { first: Option<Duration>, idle: Option<Duration>,
started: Instant, last_content: Option<Instant> }
first(first_token_timeout,默认 120 s),收到后用 idle(idle_timeout,默认 120 s)。Usage / ResponseId 等元数据不刷新,防止网关只发心跳元数据把会话吊死。next() 即使流持续就绪也强制检查截止(测试 expired_deadlines_cannot_be_bypassed_by_ready_events),phase() 返回 first_content 或 stream_idle。docs/reasoning-budget.md 明确推理没有总时长上限,reasoning_timeout_secs 等旧配置被忽略。测试 a_slow_but_progressing_stream_can_outlive_both_timeout_budgets:每 240 s 一块,跑 1200 s 仍不超时。record_request_diagnostics(mod.rs)
input_profile::log(INFO 级才计算)。ATOMCODE_WIRE_DUMP=1 且宿主给了 wire_dump_dir(通常是 <user tree>/wire-dump)时,把完整请求体写到 <seq:06>-<ts>-<safe_model>.req.json。这是唯一会落盘提示词内容的诊断。input_profile.rs
system、tools_core、tools_mcp、tools_array_framing、user_messages、assistant_messages、tool_results、mixed_user_tool_results、messages_array_framing、envelope_and_options。各类相加等于 request_json_bytes。tagged_text_bytes:按 === AVAILABLE SKILLS ===、=== PROJECT INSTRUCTIONS、=== MEMORY ===、SessionStart hook <system-reminder> 等标记分类的 UTF-8 字节。latency.rs
provider_request span,request_id 进程内自增。response_headers、first_reasoning、first_text 打 INFO,其余阶段打 DEBUG。request_end:outcome、字符数、malformed 计数、上游 response id。correlation_id 只接受 ≤128 字节的 [A-Za-z0-9-_.:]。error_class 只输出已知错误码,上游任意字符串一律记为 unclassified,以防泄密。content_marker.rs
choices[0].delta.content 中流式查找 MiniMax 原生 chat-template 标记 ]<]minimax[>[。命中只记一条 warn,不把文本解析成工具调用。contains_native_chat_template_token 对外导出,供生成会话标题等场景判断文本是否可用。request_size.rsserialize(url, body) 是实际发送字节的唯一来源。仅当 host 精确等于 llm-api.atomgit.com 且字节数 > 20,000,000(按十进制 MB 保守估计)时,在发送前拦截,返回 http_status=413、retryable=false、code="request_body_too_large",并附中文建议:用 /compact 压缩、减少附件、分段读取。
保留 413 是为了复用上层已有的“图片预算”恢复路径;同时 is_context_overflow() 为 false,因此不会触发上下文压缩分支。测试 boundary_and_other_providers 覆盖了 llm-api.atomgit.com.evil.example 不被误判。
friendly_http_error(mod.rs)按顺序判断:
content_blocked 识别 data_inspection_failed、content_filter、content_policy_violation、inappropriate content、不安全或敏感内容,走 i18n ProviderContentBlocked,并区分输入审核与输出审核。/login。API key 未授权或已失效(HTTP 401):{detail}。保留 detail,以便区分 invalid_api_key 与 invalid_client_signature。账户余额不足,丢弃 detail。HTTP {code}: {detail}。内核依赖 HTTP 429 前缀识别限流,不可改格式。openai_compat.rs)pub struct OpenAiCompatConfig {
pub api_key: String, pub base_url: String, pub model: String,
pub context_window: u32, // 默认 128_000
pub max_tokens: Option<u32>,
pub supports_reasoning_effort: bool, // 默认 false:不发 reasoning_effort
pub reasoning_policy: ReasoningPolicy,
pub thinking_type: Option<String>, pub thinking_keep: Option<...>, // Kimi `thinking` 对象
pub idle_timeout: Duration, // 120s
pub first_token_timeout: Duration, // 120s
pub connect_timeout: Duration, // 30s
pub open_timeout: Duration, // 300s,单次等待响应头
pub retry: RetryPolicy,
pub request_signer: Option<Arc<dyn RequestSigner>>,
pub user_agent: Option<String>,
pub headers: ProviderHeaders,
pub skip_tls_verify: bool,
pub supports_vision: bool, // 默认 model_suggests_vision(model)
pub effort_levels: Vec<String>,
pub wire_dump_dir: Option<PathBuf>,
}
model_suggests_vision 只看模型 id 最后一个 / 之后的片段,避免 vendor/vision-xxx/text-model 这类路径误判。
client: Arc<SwappableClient>、url = {base}/chat/completions。session_id: OnceLock<String>。effort_unsupported: AtomicBool:若上游 400 且错误文本提到 reasoning_effort,置位。之后本会话请求都不再带 effort,当轮返回一次性中文错误“……请重新发送”(测试 reasoning_effort_400_disables_it_for_session_then_succeeds)。Responses 适配器有同样机制(is_reasoning_rejection,测试 effort_rejection_detection_is_narrow)。reasoning_field: HeardReasoningField:记住上游实际用的字段名(reasoning_content 或 reasoning),回放时用同名字段。chat_stream 主流程(约第 790 行)build_request_body (确定性, BTreeMap)
→ record_request_diagnostics (input_profile / wire dump)
→ request_size::serialize (AtomGit 20MB 闸门)
→ Latency::new() span
→ open_stream = retry::bounded_open(open_timeout, recovery,
open_stream_attempts(...))
→ async_stream! {
'reopen: loop { // 至多 3 次(调用方管恢复时 1 次)
SseDecoder::new(); StreamWatchdog::new(first, idle)
loop { watchdog.next(body) →
Ok(Some(chunk)) → dec.feed → 事件
• 未提交前:ResponseId/Model/Usage 暂存
• 首个“重放敏感”事件 → 提交,此后不可透明重开
Ok(None) EOF → dec.finish()
• 已见 finish_reason 的良性 EOF ⇒ 正常结束
• 否则未提交 ⇒ 退避后 reopen;已提交 ⇒ transport_interrupted
Err(Elapsed) → 类型化 idle/first-token 超时错误
body 错误 → 必要时 rebuild 连接池 → 未提交则 reopen,
否则 stream_read_error_message }
}
}
“重放敏感”(retry::is_replay_sensitive_event)指 Text / Reasoning / Signature / ToolCall / ToolCallDelta。“attempt 元数据”(is_attempt_metadata_event)指 ResponseId / ResponseModel / Usage,可重复,所以先暂存、提交后再发。测试:
midstream_eof_before_any_event_reopens_and_succeedsmidstream_eof_after_an_event_surfaces_error_without_retryopen_stream_attempts(约第 1269 行)每次尝试的步骤:
client.for_request():可能因为代理变化而重建。SignedAuth(bearer + 头),否则 bearer_auth(api_key)。然后叠加账户头、会话头和主机特定头。tokio::time::timeout(open_timeout, send),即响应头 TTFB 看门狗。
rebuild(false) 连接池再重试(治疗静默半开连接,测试 silent_header_timeout_rebuilds_pool_and_recovers)。code=open_timeout,retryable=true。recover_unauthorized 一次,重签重发。共享恢复预算会记一次 authentication_replay。Retry-After 或退避等待后重试。ChatEndpointNotFound,并附“是否漏了 /v1”建议(测试 a_missing_endpoint_names_the_address_and_the_base_url)。ChatModelUnavailable。friendly_http_error。format_messages(约第 1577 行)push_system_coalesced 以 \n\n 合并。supports_vision:content 为数组,包含 {type:"text"} 和 {type:"image_url", image_url:{url:"data:<mt>;base64,..."}}。空数据跳过,空 media_type 记为 application/octet-stream。content 字段。tools::repair::repair_tool_args 修复,仍失败则包成 {"input": <原串>}。ReasoningPolicy:
Include:总带 reasoning_content,空时用占位符 REASONING_PLACEHOLDER = "·"。DeepSeek V4+ 思考模式要求每个 assistant 都带推理字段。Preserve:仅当存在时,以“听到的字段名”回放。Exclude:不回放。DeepSeek R1 / reasoner 回放会 400。role:"tool" 加 tool_call_id;缺 id 的工具结果被丢弃。build_request_body(约第 1731 行)| 字段 | 规则 |
|---|---|
model、messages、stream:true、stream_options.include_usage:true |
总是 |
max_tokens |
options.max_tokens 优先,否则取 cfg |
temperature |
options 有则发 |
tool_choice |
Auto 省略,与“无意见”字节一致。DeepSeek V4+ 系列完全省略(官方不支持,测试 official_deepseek_v4_omits_unsupported_tool_choice) |
reasoning_effort |
仅 supports_reasoning_effort 为真且未被 effort_unsupported 锁存时发送 |
thinking |
Kimi 风格 {type, keep},由 thinking_type/thinking_keep 决定 |
tools |
{type:"function", function:{name, description, parameters}},parameters 经 schema 规范化 |
Schema 规范化(只在线边界做,不改内核里的 ToolDef):
enum 补上 type。properties: {} 与 required: [],以兼容严格网关(测试 object_tool_schemas_gain_properties_for_strict_compatible_gateways)。properties、items、anyOf、$defs 等。shared_normalize_tool_schema 导出给 Responses 复用。确定性测试:body_serialization_is_deterministic、prefix_is_append_only_across_turns(后一轮请求体以前一轮为前缀,只追加)。
SseDecoder(约第 2208 行,process_line 约第 2593 行)| 防御 | 值 / 行为 |
|---|---|
| 单行上限 | 16 MiB(含跨 chunk 的未结束尾巴),超限返回 sse_line_too_large 错误 |
| 工具调用槽 | MAX_TOOL_CALLS = 256,更大 index 丢弃,防恶意 index 导致 OOM |
| 工具增量总数 | MAX_TOOL_CALL_DELTAS = 20000,超限返回 tool_call_delta_limit |
index 归槽;缺 index 时按 id 匹配,再不行归最后一个槽(测试 sse_parallel_tool_calls_without_index_split_by_id)。call_ac_{nanos:x}_{seq:x}。ToolCallDelta 供实时展示,结束时发完整 ToolCall。finish_reason 才算终止。SenseNova 会发 ""(测试 sse_empty_string_finish_reason_does_not_drop_tool_calls)。length:Done{truncated:true},并清空未完成的工具调用。content_filter 或未知原因:走 fail_incomplete,先发 usage 再发错误。[DONE]:finish_completed。data: 后不是 JSON:发 Malformed 并继续。{"error":...}:发 Error;若 code 在 100–599,回填 http_status。data: 行:若是 JSON,返回 upstream_error_body,重试与否由 json_error_retry 的 PERMANENT 列表决定(测试 a_json_error_where_a_stream_should_be_is_passed_on_and_retried);否则返回 not_an_event_stream,通常是 HTML 页面或错误的 base_url。stream_transport_interrupted。delta.reasoning_content 或 delta.reasoning(vLLM),前者优先。content 中内联的 <think>…</think> 由 InlineThink 拆为 Reasoning。ContentMarker 只做观察。map_usage(约第 2853 行)prompt = usage.prompt_tokens (缺失时 = prompt_cache_hit_tokens + prompt_cache_miss_tokens)
completion = usage.completion_tokens
cached = prompt_cache_hit_tokens (DeepSeek)
| cached_tokens (GLM 顶层)
| prompt_tokens_details.cached_tokens (OpenAI)
测试 deepseek_cache_split_recovers_missing_prompt_total。docs/custom-endpoint-guide.md 也要求自定义端点按这几种字段之一回报命中,以便状态栏显示缓存率。
reasoning.rs)pub enum ReasoningPolicy { Include, Preserve, Exclude }
impl ReasoningPolicy {
pub fn derive(model: &str, base_url: &str) -> Self;
pub fn from_config(s: &str) -> Result<Self, String>; // include/preserve/exclude,其他报错
}
derive 规则,自上而下第一条命中:
| 条件 | 策略 |
|---|---|
deepseek-reasoner / deepseek-r1 |
Exclude |
deepseek_thinking_v4_plus:解析 deepseek-v<N> 中 N≥4,或 deepseek-flash |
Include |
模型名或 URL 含 kimi- / moonshot / mimo |
Include |
glm / qwen / qwq |
Preserve |
| 其他 | Exclude |
ReasoningField:ReasoningContent 或 Reasoning;HeardReasoningField 用 AtomicBool 记住流里出现的是哪一个。InlineThink:
<think ...>,以及标签被 chunk 截断的部分匹配。MAX_CARRY = 64 KiB。<think> 当普通文本处理,防止把用户代码里的标签当推理。flush() 把未闭合块作为推理吐出。tests/http_mock.rs::multi_round_reasoning_is_echoed_back_for_deepseek_v4 与 multi_round_reasoning_is_stripped_for_deepseek_r1。responses.rs)不是第二个运行时:ResponsesProvider 直接复用 OpenAiCompatConfig 和 openai_compat::open_stream,共享连接池、TLS、重试、签名和超时,只换 URL、编码器和解码器。
请求体(build_request_body,约第 97 行):
| 内核 | Responses 线上 |
|---|---|
| System 消息 | 顶层 instructions(\n\n 合并;无则省略) |
| User | {type:"message", role:"user", content:[{type:"input_text"}, {type:"input_image"}…]},无视觉能力时降级为纯 input_text |
| Assistant 文本 | {type:"message", role:"assistant", content:[{type:"output_text"}]},空文本或占位符 · 不发 |
| Assistant tool_calls | {type:"function_call", id, call_id, name, arguments},参数同样走修复逻辑(测试 malformed_and_empty_tool_args_are_repaired_on_the_wire) |
| Tool 结果 | {type:"function_call_output", call_id, output} |
max_tokens |
max_output_tokens |
reasoning_effort |
reasoning:{effort},需 supports_reasoning_effort |
| tools | 扁平 {type:"function", name, description, parameters},无 function 包装 |
| tool_choice | "required" / "none" / {type:"function", name} |
| 固定 | store:false,不使用 previous_response_id:内核会话是唯一历史权威(测试 body_is_stateless) |
已知缺口:适配器尚未从流中收集 encrypted_content,不会发 ReasoningSignature,所以 assistant 消息故意不回放推理块。否则 reasoning_blocks 里只可能是别家厂商的 opaque token,回放必 400。源码注释标注为后续功能。
ResponsesSseDecoder(约第 328 行)处理的事件:
response.createdresponse.output_item.added / doneresponse.output_text.deltaresponse.reasoning_summary_text.delta 与 response.reasoning_text.delta:都映射为 Reasoningresponse.function_call_arguments.delta / doneresponse.completedresponse.failed / response.incomplete防御与行为:
MAX_TOOL_SLOTS=4096;单行上限 16 MiB。server_side_items_do_not_crash)。item.added 之前到达的参数增量仍会累积(测试 arguments_delta_before_item_added_still_accumulates)。incomplete:truncated;EOF 而无 completed 也视为 truncated(测试 eof_without_completed_is_truncated)。用量 map_responses_usage:prompt=input_tokens,completion=output_tokens,cached=input_tokens_details.cached_tokens。
anthropic.rs)pub struct AnthropicConfig {
pub api_key: String,
pub deepseek_messages: bool, // 显式方言开关,绝不从 URL 推断
pub base_url: String, // 主机根,不含路径
pub model: String, pub supports_vision: bool,
pub context_window: u32, // 默认 200_000
pub max_tokens: u32, // 默认 4096;Messages API 必填
pub anthropic_version: String, // "2023-06-01"
pub thinking: bool, // 默认 false;开启发 {type:"adaptive"}
pub send_sampling_params: bool,// 默认 false:Opus 4.7+ 发 temperature 会 400
pub idle_timeout, first_token_timeout, connect_timeout, open_timeout,
pub retry, user_agent, headers, skip_tls_verify, effort_levels, wire_dump_dir,
}
URL 规则:deepseek_messages 且 base 以 /v1 结尾时用 {base}/messages,否则用 {base}/v1/messages。
authenticate(约第 493 行)Messages 线协议不等于原生 Anthropic 鉴权。代码按精确主机加路径白名单决定使用 Bearer:
api.longcat.chat:/anthropic/v1/messagesapi.moonshot.cn:/anthropic/v1/messagesapi.siliconflow.cn:/v1/messagesopenrouter.ai:/api/v1/messagesapi.lkeap.cloud.tencent.com:/coding/anthropic/...tokenhub.tencentmaas.com:/plan/anthropic/...ark.cn-beijing.volces.com:/api/coding/v1/...以上各家同时匹配对应的 /models 路径。其余一律用 x-api-key。
default_auth_key:如果用户自定义头里已经有 authorization 或 x-api-key,就不再发默认密钥,避免同一端点收到两种鉴权头(源码中文注释“显式鉴权头优先”)。发现与推理共用同一套鉴权策略。
build_request_body,约第 674 行)model、max_tokens(必填)、stream:true。system:所有 System 消息以 \n\n 合并到顶层;空消息也占位,与参考实现一致(测试 system_join_matches_reference_including_empty_and_interleaved_messages)。tool_choice:
Auto 省略。Required 为 {type:"any"}。Specific 为 {type:"tool", name}。None 为 {type:"none"}。output_config.effort:low|medium|high|xhigh|max。{name, description, input_schema}。temperature 仅在 send_sampling_params 时发送。format_messages_with_cache_boundaries,约第 874 行)content 为字符串,与无块路径保持前缀缓存一致;有图时为 [text, {type:"image", source:{type:"base64", media_type, data}}]。format_assistant_message,约第 1061 行):
tool_use 块。tool_use.input 必须是 JSON 对象,解析失败回退为 {}。ReasoningBlock.provider 必须等于当前 source。原生为 "anthropic";DeepSeek 方言为 "deepseek-messages:<model>",即协议加模型绑定。None 视为外来块,不回放。
redacted_thinking{data},否则为 thinking{thinking, signature}。deepseek_empty_and_unsigned_thinking_are_not_redacted_blocks)。tool_result{tool_use_id, content, is_error} 块。merge_consecutive_user 合并所有相邻 user:
\n\n 连接的字符串。<system-reminder>、压缩摘要紧挨真实 user、多个尾部 hook 叠加(测试 no_consecutive_user_after_tool_fold_then_reminder、no_consecutive_user_post_compaction_summary_beside_user)。仅非 DeepSeek 方言执行。最多用 4 个 cache_control: {type:"ephemeral"} 断点:
[{type:"text", text, cache_control}]。mark_recent_message_boundaries):
synthetic 消息(请求级提醒等)不参与,确保“只对本次请求有效的提醒”落在缓存前缀之外(测试 cache_boundary_separates_real_user_from_request_only_reminders)。text、image、tool_use、tool_result;从不标记签名 thinking(测试 cache_markers_skip_thinking_only_messages_and_trailing_thinking_blocks)。moving_cache_marker_does_not_rejoin_earlier_user_context)。相关测试还有:
cached_tool_result_prefix_survives_the_next_tool_roundparallel_results_cache_the_last_stable_result_before_reminderssynthetic_only_requests_do_not_get_conversation_cache_markerscache_markers_preserve_thinking_and_cover_four_boundaries另有跨层测试 tests/compaction_cache.rs::stub_compaction_keeps_the_wire_prefix_cacheable,验证压缩后线前缀仍可缓存。
参见 docs/deepseek-messages.md:配置 type="deepseek-messages",base_url 为 https://api.deepseek.com/anthropic。
chat_stream 入口先做两项发起连接前的拒绝:
thinking 开启且 effort 为 Medium 或 XHigh 时拒绝,因为只支持 low/high/max(测试 deepseek_rejects_unsupported_effort_before_opening_a_connection)。Required / Specific 强制工具选择不支持,直接拒绝。thinking:{type: enabled|disabled}。output_config.effort="high"。tool_choice;ToolChoice::None 时移除整个 tools。content=="" 的 assistant 消息。content_block_start 就给出完整 input,之后的流式 JSON 会覆盖它(BlockState.initial_input,测试 deepseek_streamed_tool_input_supersedes_initial_input)。签名的 provider 字段带模型名(测试 deepseek_stream_signatures_carry_model_provenance)。AnthropicSseDecoder(约第 1208 行)| 事件 | 行为 |
|---|---|
message_start |
记录 response id/model;usage 取 input_tokens、cache_read_input_tokens、cache_creation_input_tokens |
content_block_start |
按 index 建 BlockState(MAX_BLOCKS=256,越界丢弃);thinking/text 的初始内容立即发出 |
content_block_delta |
text_delta 映射为 TextDelta;thinking_delta 映射为 Reasoning;signature_delta 累积;input_json_delta 累积并同时发 ToolCallDelta |
content_block_stop |
tool_use 发完整 ToolCall;thinking 发 ReasoningSignature{opaque:signature, provider};redacted_thinking 只发签名(data) |
message_delta |
任何 stop_reason 都置 seen_stop;max_tokens 映射为 truncated;增量 usage 覆盖已有字段而非累加(测试 delta_usage_overrides_present_fields_without_double_counting) |
message_stop |
发 Usage 和 Done{truncated} |
error |
发 Error 并终止 |
prompt = input + cache_read + cache_creation,cached = cache_read。只有 cache_creation 的响应也算“有用量”(测试 sse_finish_reports_cache_creation_only_usage)。seen_stop 之后的传输 EOF 视为良性(测试 seen_stop_gates_benign_trailing_eof_swallow)。midstream_reset_twice_before_any_event_reopens_until_success)。ollama.rs)pub struct OllamaConfig {
pub api_key: String, // 可选;为空不发 Authorization
pub base_url: String, // 如 http://localhost:11434
pub model: String, pub supports_vision: bool, pub context_window: u32,
pub max_tokens: Option<u32>, // → options.num_predict
pub num_ctx: Option<u32>, // 仅调用方确知窗口时才发
pub think: bool, // → think:true;有 effort 时 → think:"high" 等字符串
pub idle_timeout, first_token_timeout, connect_timeout, retry, user_agent,
pub headers, skip_tls_verify, effort_levels, wire_dump_dir,
}
num_ctx 的坑:若把回退值(如 128K 默认窗口)当 num_ctx 发出去,会强制守护进程把窗口降到该值。所以只有真正知道运行时窗口(来自 /api/show 或 /api/ps)时才发(测试 body_sends_num_ctx_only_when_pinned)。role:"tool",按顺序匹配;tool_calls[].function.arguments 是 JSON 对象。ollama_call_{n} 供内核配对,但不回传给 Ollama。工具调用一次性完整到达,直接发 ToolCall,不做缓冲。tool_choice 无对应字段,忽略。OllamaNdjsonDecoder:
ndjson_line_too_large)。message.thinking 映射为 Reasoning(无签名);未开启 think 解析的模型把推理写进 content 的 <think>,由 InlineThink 拆出。done:true 行上 prompt_eval_count / eval_count 为用量;done_reason=="length" 为 truncated。{"error":"..."} 发 Error。ollama_connection_failure(discovery.rs)。discovery.rspub async fn discover(base_url: &str, provider_type: &str, transport: &DiscoveryTransport)
-> Result<Vec<DiscoveredModel>, DiscoveryError>;
pub struct DiscoveredModel { id, name, context_window, max_tokens, supports_vision,
reasoning_effort_levels, reasoning_effort, catalog_default_effort, catalog_only }
pub enum DiscoveryError { Unsupported, BadUrl(String), Request(DiscoveryRequestError), NotAListing }
POST /providers/discover-models 与 TUI 的 /provider 面板共用此实现。openai / openai-compat / responses:{base}/modelsanthropic:{base}/v1/models?limit=1000(Anthropic 默认每页 20)ollama:{base}/api/tagsdiscovery_url):
/apps/anthropic 没有 Models API,改用同源 /compatible-mode/v1/models。/v1/models。x-api-key 会跨主机泄漏。discovery_auth):
anthropic-version 头,并复用 anthropic::authenticate 的 Bearer 白名单。normalize_discovered_models:去重和排序(细节待确认)。discovery_catalog.rs:公共元数据补全https://models.opencode.ai/experimental/v2.0/api.json?type=chat,超时 4 s,上限 32 MiB。在 blocking 线程反序列化。auto_proxy。needs_metadata)。allows_catalog_candidates)。此时用目录中 api.base_url 与当前端点匹配的模型作为候选(catalog_only=true)。fill_missing 只填空缺,不覆盖端点自报值。catalog_default_effort 只作提示,不会被保存为请求覆盖。probe.rs:保存账户时的体检POST {base}/chat/completions 发一个没有 messages 的请求。真实端点会以校验错误拒绝,不生成、不计费,从而证明“路径存在且讲这个协议”。GET /models:太多网关不提供,误报会让用户学会无视探测。ProbeVerdict:
ReachableKeyRejected{status}ModelMissing{model}WrongPath{found, fix}:若 base_url 无版本段,会补 /v1 实测一次,成功才给出 fix。Unreachable{reason}Unexpected{status, detail}describe() 经 i18n 输出 ProbeReachable 等文案。ProbeTarget 的 Debug 实现会对 api_key 脱敏,并只显示 display_endpoint。| 名称 | 作用 | 位置 |
|---|---|---|
ATOMCODE_WIRE_DUMP=1 |
把每个请求体写入 wire_dump_dir |
mod.rs::record_request_diagnostics |
SSL_CERT_FILE |
额外 CA;失败回退 webpki | openai_compat.rs 客户端构建 |
HTTP(S)_PROXY / ALL_PROXY / NO_PROXY |
环境代理,用于错误提示(effective_proxy_env);FollowSystem 模式下改由 auto_proxy 显式安装 |
retry.rs、auto_proxy.rs |
RUST_LOG / tracing |
input_profile 仅 INFO 启用时计算 |
input_profile.rs |
配置:provider.type |
openai/responses/anthropic/deepseek-messages/ollama 等,由 coding 层装配映射为上述 Config(待确认具体键名) |
docs/custom-endpoint-guide.md |
配置:reasoning_policy |
include/preserve/exclude,覆盖 derive |
ReasoningPolicy::from_config |
| 配置:超时 | first_token_timeout、idle_timeout、open_timeout、connect_timeout;reasoning_timeout_secs 已废弃并忽略 |
docs/reasoning-budget.md |
配置:headers |
账户自定义头,敏感且会脱敏 | atomcode_config::provider_headers |
配置:skip_tls_verify |
关闭证书校验 | 各 Config |
| 场景 | retryable |
code |
谁来处理 |
|---|---|---|---|
| 响应头超时(单次) | true | open_timeout |
provider 内重试,之后交上层 |
| 开流总预算耗尽 | false | 待确认(文案“累计等待已达到”) | 直接报给用户 |
| 408/425/429/5xx/529 | true | 上游 type | provider 按 RetryPolicy;429 视 owner 而定 |
| 401(无 signer) | false | 上游 | 提示 API key 失效 |
| 401 两次(有 signer) | false | authentication_expired |
提示重新 /login |
| 400 含 reasoning_effort | — | — | 本会话锁存关闭 effort,提示重发 |
| 404/405 非模型 | false | — | ChatEndpointNotFound,附 /v1 建议 |
| 流中途 EOF(未交付内容) | — | — | 透明重开,最多 2 次 |
| 流中途 EOF(已交付) | true | stream_transport_interrupted |
内核或 harness 恢复(request_recovery) |
| 首 token 或空闲超时 | true | stream_idle_timeout |
同上 |
| SSE 单行 > 16 MiB | false | sse_line_too_large |
失败 |
| JSON 错误体代替流 | 视 PERMANENT 列表 | upstream_error_body |
— |
| HTML 页面代替流 | false | not_an_event_stream |
多为 base_url 错误 |
| AtomGit 请求体 > 20MB | false | request_body_too_large(413) |
提示 /compact |
| 内容审核 | false | — | i18n 文案,区分输入与输出 |
#[cfg(test)])
prefix_is_append_only_across_turns、body_serialization_is_deterministicsse_parallel_tool_calls_without_index_split_by_id、sse_empty_string_finish_reason_does_not_drop_tool_callsdeepseek_cache_split_recovers_missing_prompt_total、reasoning_effort_400_disables_it_for_session_then_succeedssilent_header_timeout_rebuilds_pool_and_recovers、refreshable_signer_recovers_one_401_and_resigns_retry、auto_proxy_requests_switch_to_direct_then_back_and_honor_no_proxybuild_http_client_recovers_from_malformed_ssl_cert_file_via_backstopofficial_deepseek_v4_omits_unsupported_tool_choice、object_tool_schemas_gain_properties_for_strict_compatible_gatewaysassistant_signed_thinking_is_echoed_when_enabled、foreign_provider_thinking_block_is_not_echoed、mixed_provider_blocks_echo_only_anthropic_ones_in_ordersse_complete_line_over_cap_is_refused、sse_fragmented_line_over_cap_is_refused、sse_line_exactly_at_cap_is_acceptedsse_hostile_content_block_index_is_dropped_not_ooman_opencode_request_carries_its_session_header、forwards_session_id_and_product_ua_alongside_anthropic_authbody_is_stateless、tool_call_stream_buffers_whole_call、inband_error_recovers_http_status_and_type_code、response_failed_terminal_surfaces_error_after_partial_text、crlf_line_endings_decode_byte_split、emitted_content_events_are_replay_sensitivebody_basics_options_tools_and_think、body_sends_num_ctx_only_when_pinned、body_omits_empty_options_and_tools_and_think,以及 <think> 跨 chunk 拆分a_slow_but_progressing_stream_can_outlive_both_timeout_budgets、expired_deadlines_cannot_be_bypassed_by_ready_eventswire_bytes_include_unicode_and_json_escaping、boundary_and_other_providersopen_budget_tests、content_deadline_tests 两个模块crates/atomcode-capabilities/tests/,wiremock)
http_mock.rs(990 行):
retry_on_transient_500_then_succeeds、retry_exhausts_on_persistent_500_returns_err、auth_4xx_is_not_retriedopen_failure_parses_provider_error_code_and_reason、agent_outcome_carries_structured_error_codemulti_round_tool_loop_executes_tool_and_logs_each_round、round_resets_per_turn_request_id_is_session_globalanthropic_mock.rs:retry_on_transient_500_then_succeeds、open_failure_parses_anthropic_error_type、multi_round_tool_call_then_final_answer、multi_round_signed_thinking_is_echoed_back_verbatim、signed_thinking_not_echoed_when_thinking_disabledollama_mock.rs:retry_on_transient_500_then_succeeds、multi_round_tool_call_then_final_answerprovider_headers.rs:every_chat_wire_sends_account_headers_and_redacts_echoed_credentials、discovery_and_probe_use_headers_without_an_api_key、custom_credentials_never_follow_a_redirect_to_another_servercompaction_cache.rs:stub_compaction_keeps_the_wire_prefix_cacheable、auto_compaction_escalates_to_summary_at_high_utilizationbench feature 加 benches/core.rs 调用 bench::sse_feed(lines, per_chunk)。Map,Auto 类默认值必须省略而不是写默认值,否则会破坏历史前缀字节。deepseek-messages:<model> 作为 provider 标签。换模型后旧签名不会被回放,避免 400。RateLimitRetryOwner 防止 provider 与内核双重退避。request_recovery 存在时 provider 不重试、只重开 1 次:恢复预算由上层统一计算,避免 3×3 指数放大。deepseek_messages 必须显式配置;Bearer 与 x-api-key 用精确“主机+路径”白名单决定,不靠猜。encrypted_content;store:false 时无签名推理不能回放。num_ctx:发回退值会把模型窗口强行缩小。HTTP 429 文本格式被内核依赖。OpenTMD 目前是 internal/provider(工厂:OpenAI 兼容 / Ollama)加 internal/deepseek(HTTP/SSE 客户端),类型在 internal/llm。
internal/deepseek 的流读取循环里区分“已向消费者发出文本/推理/工具调用”与否。未发出时,EOF 或连接重置可以静默重开(最多 2 次);已发出时返回带 code 的结构化错误,交给 internal/agent 的循环决定。firstTokenTimeout(首内容)和 idleTimeout(内容间隔),只有内容刷新;用 time.Timer 包装 bufio.Scanner 读取即可。不要给推理设总时长上限。ProviderError 结构化:{Retryable bool; Message string; HTTPStatus int; Code string; RetryAfter time.Duration},并固定一组错误码常量(open_timeout、stream_idle_timeout、stream_transport_interrupted、not_an_event_stream、upstream_error_body),让 TUI、headless 和 daemon 三个前端统一呈现。bufio.Scanner.Buffer 要显式设大,默认 64 KiB 会直接报 token too long)、工具槽 256、增量总数 2 万;非空 finish_reason 才算终止;“整个响应没有 data: 行”时识别 HTML 或 JSON 错误页,提示检查 base_url。ReasoningPolicy.derive:R1/reasoner 不回放 reasoning_content;V4+ 思考模式每条 assistant 都必须带 reasoning_content(空时用占位符);V4 省略 tool_choice。prompt_cache_hit_tokens/miss,在状态栏显示缓存命中率。encoding/json 对 map 会按键排序,但 struct 字段按声明顺序输出,二者都是确定的;关键是不要在请求体里放时间戳或随机 id,Auto 类选项要用 omitempty 省略。可加一个 prefix_is_append_only_across_turns 风格的单测:第 N+1 轮请求体的 messages 序列化应以第 N 轮为前缀。x-<product>-session-id,配合支持前缀缓存的网关可显著提高命中率,成本几乎为零。properties:{} 与 required:[],枚举补 type,可兼容严格网关,且不改内部 ToolDefinition。tool.RepairToolArgs(OpenTMD 已有,移植自 atomcode)修复;仍失败则包成 {"input": "..."},避免一条坏历史永久卡死会话。http.Transport 同样会遇到半关闭 keep-alive。响应头超时后调用 transport.CloseIdleConnections() 再重试一次,并把 IdleConnTimeout 设为约 15 s。/provider 保存时探测:发一个空 messages 的 POST /chat/completions,按状态码和错误体分类为 Reachable / KeyRejected / ModelMissing / WrongPath(自动试 /v1),比 GET /models 可靠,可放进 opentmd login / opentmd config 流程。OPENTMD_WIRE_DUMP=1 时把请求体写到 ~/.opentmd/wire-dump/,排查网关兼容问题非常有用;平时只记字节分布(system、tools、tool_results 各占多少),可直接指导 /compact 和 skills 列表裁剪。/v1 这几类给出中文可操作提示,并保留 429 前缀供限流逻辑识别。