From a78daefb0266f53ef78925ba4e677b4d12dfb001 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Fri, 2 Oct 2026 16:22:21 +0800 Subject: [PATCH] feat(control): read a session as a conversation transcript GET /sessions/{id}/transcript turns a session's stored request and response bodies into the conversation the desktop app shows: per turn, the messages new in that request, the answer decoded from the stored response, and what could not be shown (gaps). Control-plane protocol 32. Clients resend the whole history every turn, so a request's new messages are what is left after the previous readable request's messages, compared by fingerprint with cache_control, signatures, key order and reasoning ignored (some clients drop earlier reasoning from the history). The first leftover assistant message is the previous turn's answer and is dropped, unless that answer could not be read in full. No prefix match, or an unreadable request before it, restarts with the whole history. Requests are read from the client's own JSON instead of tw-dialect's IR: the IR drops exactly what a transcript needs (where a system message sits, tool-only messages, server-tool blocks, files). Answers reuse tw-dialect's per-format stream parsers, and the blocks those skip are recognized on the same frame. Every string is masked with mask_body on the way out; images carry only their type and size. 300 turns at about 1.2 MB a request build in about 0.7 s (release). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/tw-api/src/ep.rs | 2 + crates/tw-api/src/lib.rs | 123 +- crates/tw-api/src/ts.rs | 52 + crates/tw-control/src/lib.rs | 40 +- crates/tw-control/tests/transcript.rs | 222 +++ crates/tw-store/Cargo.toml | 2 + crates/tw-store/src/db.rs | 10 + crates/tw-store/src/lib.rs | 1 + crates/tw-store/src/transcript/answer.rs | 432 +++++ crates/tw-store/src/transcript/mod.rs | 1932 ++++++++++++++++++++++ crates/tw-store/src/transcript/read.rs | 786 +++++++++ scripts/smoke.sh | 31 + 13 files changed, 3627 insertions(+), 7 deletions(-) create mode 100644 crates/tw-control/tests/transcript.rs create mode 100644 crates/tw-store/src/transcript/answer.rs create mode 100644 crates/tw-store/src/transcript/mod.rs create mode 100644 crates/tw-store/src/transcript/read.rs diff --git a/Cargo.lock b/Cargo.lock index 426e1d7b..fa4f78e9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2974,6 +2974,7 @@ dependencies = [ name = "tw-store" version = "0.57.1" dependencies = [ + "blake3", "bytes", "rusqlite", "serde", diff --git a/crates/tw-api/src/ep.rs b/crates/tw-api/src/ep.rs index 9802c143..cf15a809 100644 --- a/crates/tw-api/src/ep.rs +++ b/crates/tw-api/src/ep.rs @@ -60,6 +60,8 @@ endpoints! { Fixture: GET "/request/{id}/fixture" [id], () => String, text; Sessions: GET "/sessions", api::ListQuery => Vec; SessionDetail: GET "/sessions/{id}" [id], () => api::SessionDetail; + /// 一次会话读成一段对话:每一轮新说的话、回答、工具调用和结果(已脱敏) + SessionTranscript: GET "/sessions/{id}/transcript" [id], () => api::Transcript; // ─────────────────────────────────────────────── 测速、回放、试路由 SpeedQuote: POST "/speed/quote", api::SpeedRunRequest => api::SpeedQuote; diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 7fb6c5db..178cc46a 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -671,7 +671,11 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt"); /// 31 起出站脱敏有**身份证号和银行卡号**两条出厂就开的规则:[`Matcher`] 多了 /// `cn-resident-id` 和 `bank-card`([`CardNetwork`]、[`CardPrefix`]),[`SecretKind`] 多了 /// `personal`。照 30 写的界面说不出这两条规则按什么认。 -pub const CONTROL_API_VERSION: u32 = 31; +/// +/// **32 起会话能读成一段对话**:新端点 `GET /sessions/{id}/transcript`([`Transcript`]) +/// 从存下来的正文里读出每一轮新说的话、回答、推理、工具调用和结果,读不到的地方逐轮说出来 +/// ([`TranscriptGap`])。照 31 写的界面只有每一轮的用量和金额。 +pub const CONTROL_API_VERSION: u32 = 32; #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] @@ -4026,6 +4030,123 @@ pub struct SessionDetail { pub turns: Vec, } +/// 一次会话读成一段对话(`GET /sessions/{id}/transcript`):每一轮新说的话、回答、推理、 +/// 工具调用和工具结果。 +/// +/// **从存下来的正文里读出来**,不是另记的一份:正文只留几天(`retention.body_days`), +/// 太大的只留开头,没存下来的也有。读不到的地方,那一轮的 `gaps` 说出来。 +/// +/// **已脱敏**,和请求详情里的正文同一套打码。图片只说类型和大小,从不带数据。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct Transcript { + pub session: String, + /// 第一个读得懂的请求里的系统提示:Anthropic 的 `system`、Responses 的 `instructions`、 + /// Gemini 的 `systemInstruction`,Chat 和 Responses 还有开头连着的 system、developer + /// 消息,几段之间空一行。没有是 null + pub system: Option, + /// 和 [`SessionDetail::turns`] 同样的请求,同样的顺序 + pub turns: Vec, +} + +/// 对话里的一轮,就是会话里的一个请求。 +/// +/// 客户端每一轮都把整段历史发上来:请求 i 的消息 = 请求 i-1 的消息 + 上一轮的回答 + 新的 +/// 用户消息或工具结果。`input` 只放新的那几条;上一轮的回答已经在上一轮的 `output` 里。 +/// +/// **不生成回答的调用**(数 token、Responses 的压缩)也在这里占一轮,`input`、`output` +/// 都是空的,也不和前后的请求比对:它们问的是这段对话,不是对话里的一句。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct TranscriptTurn { + /// 请求号,写成十进制的字符串。和 [`TurnView::id`] 是同一条请求 + pub id: String, + /// 这个请求带的历史没有接着上一个读得懂的请求:压缩过、改过历史,或者它是一串读不懂 + /// 的请求之后第一个读得懂的。这时 `input` 是它的整段历史 + pub restart: bool, + /// 系统提示和上一个读得懂的请求不一样了:新的那一份(去掉了的是空串)。没变是 null + pub system_changed: Option, + /// 这个请求里新的消息。上一轮的回答没有完整读出来时(那一轮的 `gaps` 里有 `response_*`), + /// 客户端记下的那条助手消息也在这里:它是那一轮说过什么的记录 + pub input: Vec, + /// 回答,从存下来的响应里读出来的。失败的请求(上游回了错误)没有回答,也不算缺 + pub output: Vec, + /// 这一轮哪些地方读不出来 + pub gaps: Vec, +} + +/// 请求里的一条消息。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct TranscriptMessage { + pub role: TranscriptRole, + pub parts: Vec, +} + +slug_enum! { + /// 一条消息是谁说的。 + pub enum TranscriptRole { + User = "user", + Assistant = "assistant", + /// 只装着工具结果的消息:Anthropic 全是 `tool_result` 的用户消息、Chat 的 `tool` + /// 消息、Responses 的 `function_call_output` + Tool = "tool", + /// 对话中途的 system、developer 消息 + System = "system", + } +} + +/// 消息或回答里的一块。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum TranscriptPart { + Text { + text: String, + }, + /// 推理。只有签名、或者被打码的推理,`text` 是空串 + Thinking { + text: String, + }, + /// `input` 是参数的 JSON 文本;自由格式的工具(Codex 的 `apply_patch`)是它的原文 + ToolCall { + id: String, + name: String, + input: String, + }, + /// `call_id` 和它回应的那个 `tool_call` 的 `id` 是同一个 + ToolResult { + call_id: String, + text: String, + is_error: bool, + }, + /// 图片。**只有类型和大小,从不带数据**;给的是地址的不知道大小 + Image { + media_type: Option, + bytes: Option, + }, + /// 别的块:文件、音频、服务端工具的调用和结果……`label` 是它的类型名,原样 + Other { + label: String, + }, +} + +slug_enum! { + /// 一轮里读不出来的地方。 + pub enum TranscriptGap { + /// 请求体没有存下来,或者已经清掉了 + RequestMissing = "request_missing", + /// 请求体只存了开头,或者解析不了 + RequestTruncated = "request_truncated", + /// 回答没有存下来,或者已经清掉了 + ResponseMissing = "response_missing", + /// 回答只存了开头:`output` 是读得出来的那一段 + ResponseTruncated = "response_truncated", + /// 回答存下来了,但读不懂 + ResponseUnreadable = "response_unreadable", + } +} + // ---------------------------------------------------------------- 请求重放 /// 把存下来的那条请求,原样发给另一个上游。 diff --git a/crates/tw-api/src/ts.rs b/crates/tw-api/src/ts.rs index 0fd9ad1b..f2f28142 100644 --- a/crates/tw-api/src/ts.rs +++ b/crates/tw-api/src/ts.rs @@ -282,6 +282,58 @@ mod tests { assert!(event.contains("answered_model?: string"), "{event}"); } + /// 对话记录:请求号是字符串;可以为空的是 null(必有的字段,不是省掉);块是按 `kind` + /// 分的联合,角色和缺口是字面量 + #[test] + fn a_transcript_is_turns_of_messages_and_parts() { + let ts = typescript(); + assert!(ts.contains(" SessionTranscript: { req: null; res: Transcript };")); + assert!(ts.contains( + " SessionTranscript: { method: \"GET\", path: \"/sessions/{id}/transcript\", params: [\"id\"], format: \"json\" }," + )); + let transcript = decl_of(&ts, "Transcript"); + for field in [ + "session: string", + "system: string | null", + "turns: Array", + ] { + assert!(transcript.contains(field), "{field}: {transcript}"); + } + let turn = decl_of(&ts, "TranscriptTurn"); + for field in [ + "id: string", + "restart: boolean", + "system_changed: string | null", + "input: Array", + "output: Array", + "gaps: Array", + ] { + assert!(turn.contains(field), "{field}: {turn}"); + } + assert_eq!( + decl_of(&ts, "TranscriptMessage"), + "export type TranscriptMessage = { role: TranscriptRole, parts: Array, }" + ); + assert_eq!( + decl_of(&ts, "TranscriptPart"), + "export type TranscriptPart = { \"kind\": \"text\", text: string, } \ + | { \"kind\": \"thinking\", text: string, } \ + | { \"kind\": \"tool_call\", id: string, name: string, input: string, } \ + | { \"kind\": \"tool_result\", call_id: string, text: string, is_error: boolean, } \ + | { \"kind\": \"image\", media_type: string | null, bytes: number | null, } \ + | { \"kind\": \"other\", label: string, }" + ); + assert_eq!( + decl_of(&ts, "TranscriptRole"), + "export type TranscriptRole = \"user\" | \"assistant\" | \"tool\" | \"system\"" + ); + assert_eq!( + decl_of(&ts, "TranscriptGap"), + "export type TranscriptGap = \"request_missing\" | \"request_truncated\" \ + | \"response_missing\" | \"response_truncated\" | \"response_unreadable\"" + ); + } + #[test] fn every_endpoint_is_in_the_table() { let ts = typescript(); diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 72208457..e99265d6 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -131,6 +131,7 @@ pub fn router(state: ControlState) -> Router { .at(ep::ReplayRun, replay::run) .at(ep::Sessions, sessions) .at(ep::SessionDetail, session_detail) + .at(ep::SessionTranscript, session_transcript) .at(ep::DryRun, dryrun::dry_run) // 为客户端发专用密钥。接管本身在桌面端做 .at(ep::ClientKey, clients::client_key) @@ -1501,12 +1502,7 @@ async fn session_detail( .iter() .find(|x| x.id == id) .map(session_view) - .ok_or_else(|| { - fail( - StatusCode::NOT_FOUND, - msg!("control.session_not_found", id = id.clone() => "There is no session {id}."), - ) - })?; + .ok_or_else(|| no_such_session(&id))?; let turns = g .db() .turns(&id) @@ -1517,6 +1513,38 @@ async fn session_detail( Ok(Json(tw_api::SessionDetail { session, turns })) } +fn no_such_session(id: &str) -> Fail { + fail( + StatusCode::NOT_FOUND, + msg!("control.session_not_found", id = id.to_string() => "There is no session {id}."), + ) +} + +/// 一次会话读成一段对话(见 `tw_store::transcript`)。 +/// +/// **放到阻塞线程上跑**,库只在取行的时候锁一下:几百轮的会话要读几百份正文、解析几百 MB +/// 的 JSON,和按正文找是同一个道理(见 [`history_search`])—— 记录和正文落盘走的是同一把锁。 +async fn session_transcript( + State(s): State, + axum::extract::Path(id): axum::extract::Path, +) -> Result, Fail> { + let store = need_store(&s)?; + let (rows, blobs) = { + let g = store.lock().await; + let rows = g.db().session_requests(&id).map_err(records)?; + // 正文目录只是一个路径,读它不需要锁 + (rows, tw_store::Blobs::new(g.blobs().root().to_path_buf())) + }; + if rows.is_empty() { + return Err(no_such_session(&id)); + } + let transcript = + tokio::task::spawn_blocking(move || tw_store::transcript::build(&id, &rows, &blobs)) + .await + .map_err(internal)?; + Ok(Json(transcript)) +} + #[derive(Debug, thiserror::Error)] pub enum ControlError { #[error("the control-plane socket {path} could not be started: {source}")] diff --git a/crates/tw-control/tests/transcript.rs b/crates/tw-control/tests/transcript.rs new file mode 100644 index 00000000..8a11dde4 --- /dev/null +++ b/crates/tw-control/tests/transcript.rs @@ -0,0 +1,222 @@ +//! 对话记录端点(`GET /sessions/{id}/transcript`)的形状。 +//! +//! 四种格式怎么读、前后两个请求怎么比在 tw-store 里测;这里盯的是**界面拿到的那份 +//! JSON**,一个字段一个字段地钉住:桌面端照着它写,改了哪个字段名那边就悄悄读不到了。 + +use std::sync::Arc; + +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use serde_json::{Value, json}; +use tower::ServiceExt; +use tw_control::{ConfigManager, ControlState}; +use tw_store::Which; + +const BASE: &str = "version: 1\nlisten:\n control:\n key: c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00\nclients:\n - name: 我\n key: tw-一把钥匙就够\nproviders:\n - name: 官方\n base_url: https://api.anthropic.com\n key: sk-x\n"; + +/// Claude Code 的一轮 +fn turn(id: i64) -> tw_store::db::RequestRow { + tw_store::db::RequestRow { + session_log_bytes: None, + key_masked: None, + peer: None, + id, + at_ms: 1_790_000_000_000 + id, + client: "claude-code".into(), + client_hint: None, + session: Some("s1".into()), + provider: "官方".into(), + model: "claude-sonnet-4-5".into(), + sent_model: "claude-sonnet-4-5".into(), + answered_model: None, + path: "/v1/messages".into(), + status: Some(200), + ttfb_ms: Some(100), + ttft_ms: None, + duration_ms: Some(200), + tokens_per_sec: None, + bytes: Some(10), + input_tokens: Some(50), + output_tokens: Some(20), + cache_read_tokens: None, + cache_write_tokens: None, + input_estimate: None, + cost_micros: Some(1_000), + cost_estimated: false, + error: None, + local: false, + cancelled: false, + routing: None, + billing: tw_api::Billing::PerToken, + cache_saved_micros: None, + price_source: None, + translated: None, + } +} + +/// 一个带着请求库和正文的控制面。`bodies`:哪一条、请求体、回答(没存下的是 None) +fn app( + rows: &[tw_store::db::RequestRow], + bodies: &[(i64, Option, Option)], +) -> (tempfile::TempDir, axum::Router) { + let d = tempfile::tempdir().unwrap(); + let p = d.path().join("config.yaml"); + std::fs::write(&p, BASE).unwrap(); + let db = tw_store::Db::open(&d.path().join("data.db")).unwrap(); + for r in rows { + db.insert(r).unwrap(); + } + let blobs = tw_store::Blobs::new(d.path().join("blobs")); + for (id, request, response) in bodies { + let at = rows.iter().find(|r| r.id == *id).unwrap().at_ms; + for (which, body) in [(Which::Request, request), (Which::Response, response)] { + if let Some(b) = body { + assert!(blobs.put(at, *id, which, b.to_string().as_bytes())); + } + } + } + let rec = tw_store::Recorder::new( + db, + blobs, + tw_pricing::shared(tw_pricing::PriceBook::builtin().unwrap()), + ); + let cfg: tw_config::Config = serde_yaml_ng::from_str(BASE).unwrap(); + let gw = tw_gateway::AppState::new(cfg).unwrap(); + let bus = gw.bus.clone(); + let state = ControlState { + shutdown: Default::default(), + remote: Default::default(), + cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), + gateway: gw, + store: Some(Arc::new(tokio::sync::Mutex::new(rec))), + started: std::time::Instant::now(), + price_updater: Default::default(), + chatgpt: Default::default(), + zai: Default::default(), + }; + (d, tw_control::router(state)) +} + +async fn get(app: &axum::Router, path: &str) -> (StatusCode, Value) { + let r = app + .clone() + .oneshot(Request::builder().uri(path).body(Body::empty()).unwrap()) + .await + .unwrap(); + let st = r.status(); + let b = axum::body::to_bytes(r.into_body(), 1 << 20).await.unwrap(); + (st, serde_json::from_slice(&b).unwrap()) +} + +/// 每一种块、每一个字段都在:请求号是字符串,可以为空的字段写成 null 而不是省掉, +/// 块和缺口是界面认的那几个词。工具结果里的密钥打了码,图片只有类型和大小 +#[tokio::test] +async fn the_transcript_is_the_shape_the_desktop_app_reads() { + let png = "QUJD".repeat(2); + let first = json!({"model": "claude-sonnet-4-5", "system": "sys", "messages": [ + {"role": "user", "content": [ + {"type": "text", "text": "hi"}, + {"type": "image", "source": {"type": "url", "url": "https://example.com/a.png"}} + ]} + ]}); + let answer = json!({"type": "message", "content": [ + {"type": "redacted_thinking", "data": "abc"}, + {"type": "server_tool_use", "id": "srvtoolu_1", "name": "web_search", "input": {}}, + {"type": "text", "text": "hello"}, + {"type": "tool_use", "id": "t1", "name": "Read", "input": {"p": 1}} + ]}); + let second = json!({"model": "claude-sonnet-4-5", "system": "sys", "messages": [ + {"role": "user", "content": [ + {"type": "text", "text": "hi"}, + {"type": "image", "source": {"type": "url", "url": "https://example.com/a.png"}} + ]}, + {"role": "assistant", "content": answer["content"]}, + {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": [ + {"type": "text", "text": "key sk-ant-api03-SECRETSECRETSECRET"}, + {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": png}} + ]}]} + ]}); + let (_d, app) = app( + &[turn(1), turn(2)], + &[(1, Some(first), Some(answer)), (2, Some(second), None)], + ); + + let (st, t) = get(&app, "/sessions/s1/transcript").await; + assert_eq!(st, StatusCode::OK, "{t}"); + assert_eq!( + t, + json!({ + "session": "s1", + "system": "sys", + "turns": [ + { + "id": "1", + "restart": false, + "system_changed": null, + "input": [{"role": "user", "parts": [ + {"kind": "text", "text": "hi"}, + {"kind": "image", "media_type": null, "bytes": null} + ]}], + "output": [ + {"kind": "thinking", "text": ""}, + {"kind": "other", "label": "server_tool_use"}, + {"kind": "text", "text": "hello"}, + {"kind": "tool_call", "id": "t1", "name": "Read", "input": "{\"p\":1}"} + ], + "gaps": [] + }, + { + "id": "2", + "restart": false, + "system_changed": null, + "input": [{"role": "tool", "parts": [ + {"kind": "tool_result", "call_id": "t1", "text": "key sk-an…CRET", "is_error": false}, + {"kind": "image", "media_type": "image/png", "bytes": 6} + ]}], + "output": [], + "gaps": ["response_missing"] + } + ] + }) + ); + + // 和会话详情是同样的请求、同样的顺序 + let (_, detail) = get(&app, "/sessions/s1").await; + let ids: Vec = detail["turns"] + .as_array() + .unwrap() + .iter() + .map(|x| x["id"].to_string()) + .collect(); + assert_eq!(ids, ["1", "2"]); +} + +/// 没有这次会话:404,和会话详情同一个码 +#[tokio::test] +async fn an_unknown_session_is_not_found() { + let (_d, app) = app(&[turn(1)], &[]); + let (st, body) = get(&app, "/sessions/nope/transcript").await; + assert_eq!(st, StatusCode::NOT_FOUND); + assert_eq!(body["code"], "control.session_not_found"); + assert_eq!(body["args"]["id"], "nope"); + let (st, body) = get(&app, "/sessions/nope").await; + assert_eq!(st, StatusCode::NOT_FOUND); + assert_eq!(body["code"], "control.session_not_found"); +} + +/// 正文都清掉了的会话照样有它的每一轮,每一轮说出缺了什么 +#[tokio::test] +async fn a_session_whose_bodies_are_gone_still_lists_its_turns() { + let (_d, app) = app(&[turn(1), turn(2)], &[]); + let (st, t) = get(&app, "/sessions/s1/transcript").await; + assert_eq!(st, StatusCode::OK); + assert_eq!(t["system"], Value::Null); + for x in t["turns"].as_array().unwrap() { + assert_eq!( + x["gaps"], + json!(["request_missing", "response_missing"]), + "{x}" + ); + assert_eq!(x["input"], json!([])); + } +} diff --git a/crates/tw-store/Cargo.toml b/crates/tw-store/Cargo.toml index 4e7784bf..ec40258c 100644 --- a/crates/tw-store/Cargo.toml +++ b/crates/tw-store/Cargo.toml @@ -18,6 +18,8 @@ tw-pricing = { workspace = true } tw-dialect = { workspace = true } # 按正文找时交出去的那一小段要和详情抽屉同一套打码 tw-secret = { workspace = true } +# 对话记录比对前后两个请求的历史:每条消息只留一个指纹,不留正文 +blake3 = { workspace = true } bytes = { workspace = true } # functions:搜索要一个 SQL 函数,按界面同一种小写规则比子串(见 `search::sql`)。 # 只是打开 rusqlite 已有的接口,不多编任何东西 diff --git a/crates/tw-store/src/db.rs b/crates/tw-store/src/db.rs index 5c20a108..9f247eb3 100644 --- a/crates/tw-store/src/db.rs +++ b/crates/tw-store/src/db.rs @@ -574,6 +574,16 @@ impl Db { })?; Ok(rows.collect::, _>>()?) } + + /// 一次会话里的每一个请求,整行。**和 [`Db::turns`] 同样的筛法、同样的顺序**:对话记录 + /// ([`crate::transcript`])一轮对一轮地跟着会话详情走。 + pub fn session_requests(&self, session: &str) -> Result, DbError> { + let mut st = self.conn.prepare( + "SELECT * FROM requests WHERE session = ?1 AND local = 0 ORDER BY at_ms, id", + )?; + let rows = st.query_map([session], row_from)?; + Ok(rows.collect::, _>>()?) + } } impl Db { diff --git a/crates/tw-store/src/lib.rs b/crates/tw-store/src/lib.rs index 59c911b2..dd1dcff7 100644 --- a/crates/tw-store/src/lib.rs +++ b/crates/tw-store/src/lib.rs @@ -15,6 +15,7 @@ pub mod model_name; pub mod recorder; pub mod search; pub mod task; +pub mod transcript; pub use blobs::{Blobs, Which}; pub use db::{Db, DbError, Latency, RequestRow, SecurityEvent, Summary, TokenRate}; diff --git a/crates/tw-store/src/transcript/answer.rs b/crates/tw-store/src/transcript/answer.rs new file mode 100644 index 00000000..81c9d98d --- /dev/null +++ b/crates/tw-store/src/transcript/answer.rs @@ -0,0 +1,432 @@ +//! 回答:存下来的上游原话读成一块一块。 +//! +//! `body` 是回答它的那一家的原话:整包的 JSON、SSE 的流(Bedrock 的二进制帧在网关进门时 +//! 已经转成了 SSE),或者 Gemini 不带 `alt=sse` 时那个逐步写出的 JSON 数组。按开头的字节 +//! 分辨,不看请求要没要流:上游只给流、客户端要整包的时候,存下来的是流(和按正文找的 +//! `search::text::answer` 同一个分法)。 +//! +//! - **整包**和请求里的助手消息是同一个形状,按 [`super::read`] 读; +//! - **流**按 tw-dialect 各家的流解析器读成事件再拼回来 —— 网关转换格式时读的就是它们。 +//! 解析器只认得各家之间对应得上的块,服务端工具的块、Gemini 的代码执行这些它跳过, +//! 这里在同一帧上另外认出来,记成 `other`,位置不乱。 + +use std::collections::{HashMap, HashSet}; + +use serde_json::Value; +use tw_api::TranscriptPart; +use tw_dialect::frame::{self, Frame}; +use tw_dialect::ir::{Block, BlockKind, Delta, Dialect, Event, ToolInput}; + +use super::read; + +/// 读出来的回答。 +#[derive(Debug, Default)] +pub(super) struct Answer { + pub(super) parts: Vec, + /// 认出了这家格式的回答没有。存着东西却认不出来,是 `response_unreadable` + pub(super) recognized: bool, +} + +/// 读一份回答。`freeform` 是客户端定义成自由格式的工具:别的格式的上游把它们的原文包在 +/// `{"input": …}` 里,拆出来,和客户端自己记下的一样。 +pub(super) fn read(body: &[u8], upstream: Dialect, freeform: &HashSet) -> Answer { + let mut a = match body.iter().find(|b| !b.is_ascii_whitespace()) { + None => Answer::default(), + Some(b'{') => whole(body, upstream), + Some(b'[') if upstream == Dialect::Gemini => gemini_array(body), + Some(_) => stream(body, upstream), + }; + tidy(&mut a.parts, upstream, freeform); + a +} + +/// 整包的回答。JSON 都解析不了的(截断了的)什么都读不出来 +fn whole(body: &[u8], upstream: Dialect) -> Answer { + let Ok(v) = serde_json::from_slice::(body) else { + return Answer::default(); + }; + let mut pieces = Vec::new(); + // 认得出是这家的回答就算读懂了,哪怕里面什么都没有(被拦下的提示、空的回答) + let says = |key: &str, prefix: &str| { + v.get(key) + .and_then(Value::as_str) + .is_some_and(|s| s.starts_with(prefix)) + }; + let recognized = match upstream { + Dialect::Anthropic => { + if let Some(blocks) = v.get("content").and_then(Value::as_array) { + read::anthropic_blocks(blocks, &mut pieces); + } + v.get("content").is_some() || says("type", "message") + } + Dialect::Chat => { + if let Some(m) = v + .get("choices") + .and_then(|c| c.get(0)) + .and_then(|c| c.get("message")) + { + pieces = read::chat_assistant(m); + } + v.get("choices").is_some() || says("object", "chat.completion") + } + Dialect::Responses => { + for it in v + .get("output") + .and_then(Value::as_array) + .into_iter() + .flatten() + { + pieces.extend(read::responses_item(it).pieces); + } + v.get("output").is_some() || says("object", "response") + } + Dialect::Gemini => { + if let Some(parts) = v + .get("candidates") + .and_then(|c| c.get(0)) + .and_then(|c| c.get("content")) + .and_then(|c| c.get("parts")) + .and_then(Value::as_array) + { + read::gemini_parts(parts, &mut pieces); + } + ["candidates", "promptFeedback", "usageMetadata"] + .iter() + .any(|k| v.get(*k).is_some()) + } + // 客户端不说 Converse,没有它的消息读法:整包交给 tw-dialect 解 + Dialect::Bedrock => { + if v.get("output").and_then(|o| o.get("message")).is_none() { + return Answer::default(); + } + let parts = tw_dialect::bedrock::decode_response(&v) + .blocks + .into_iter() + .map(block) + .collect(); + return Answer { + parts, + recognized: true, + }; + } + }; + Answer { + parts: pieces.iter().map(super::part).collect(), + recognized, + } +} + +fn block(b: Block) -> TranscriptPart { + match b { + Block::Text(text) => TranscriptPart::Text { text }, + Block::Thinking(t) => TranscriptPart::Thinking { text: t.text }, + Block::ToolCall(c) => TranscriptPart::ToolCall { + id: c.id, + name: c.name, + input: match c.input { + ToolInput::Text(s) => s, + json => json.to_json_text(), + }, + }, + } +} + +/// 流里的事件拼回一块一块。块按第一次出现的先后排 +#[derive(Default)] +struct Assembly { + parts: Vec, + /// 块号 → 在 `parts` 里的位置 + at: HashMap, + recognized: bool, +} + +impl Assembly { + fn other(&mut self, label: &str) { + self.push(TranscriptPart::Other { + label: label.to_string(), + }); + } + + /// 解析器不认、这里另外认出来的一块。**之后的字另起一块**:解析器那边的文字块可能还 + /// 开着(Gemini 每帧都往同一块里接),接回前面那块的话,字就跑到这一块前头去了 + fn push(&mut self, part: TranscriptPart) { + self.recognized = true; + self.parts.push(part); + let parts = &self.parts; + self.at.retain(|_, &mut i| { + !matches!( + parts[i], + TranscriptPart::Text { .. } | TranscriptPart::Thinking { .. } + ) + }); + } + + fn events(&mut self, events: Vec) { + for e in events { + self.event(e); + } + } + + fn event(&mut self, e: Event) { + self.recognized = true; + match e { + Event::BlockStart { index, kind } => { + self.at.insert(index, self.parts.len()); + self.parts.push(match kind { + BlockKind::Text => TranscriptPart::Text { + text: String::new(), + }, + BlockKind::Thinking => TranscriptPart::Thinking { + text: String::new(), + }, + BlockKind::ToolCall { id, name } => TranscriptPart::ToolCall { + id, + name, + input: String::new(), + }, + }); + } + Event::Delta { index, delta } => { + if let Some(&i) = self.at.get(&index) + && append(&mut self.parts[i], &delta) + { + return; + } + // 没报开始的块(Bedrock 的文字和推理就不报):第一段增量到了就算开了一块 + self.at.insert(index, self.parts.len()); + self.parts.push(match delta { + Delta::Text(text) => TranscriptPart::Text { text }, + Delta::Thinking(text) => TranscriptPart::Thinking { text }, + Delta::Signature(_) => TranscriptPart::Thinking { + text: String::new(), + }, + Delta::ToolInput(input) => TranscriptPart::ToolCall { + id: String::new(), + name: String::new(), + input, + }, + }); + } + // 用量、结束原因、上游在流里报的错:不是回答的内容。错误在会话详情里有 + Event::Start { .. } + | Event::BlockStop { .. } + | Event::Usage(_) + | Event::Stop(_) + | Event::Error { .. } => {} + } + } + + fn finish(self) -> Answer { + Answer { + parts: self.parts, + recognized: self.recognized, + } + } +} + +/// 一段增量接到它那一块上。块的种类对不上的接不上 +fn append(part: &mut TranscriptPart, delta: &Delta) -> bool { + match (part, delta) { + (TranscriptPart::Text { text }, Delta::Text(d)) + | (TranscriptPart::Thinking { text }, Delta::Thinking(d)) + | (TranscriptPart::ToolCall { input: text, .. }, Delta::ToolInput(d)) => { + text.push_str(d); + true + } + // 签名不交出去:只有签名的推理块是一块空的推理 + (TranscriptPart::Thinking { .. }, Delta::Signature(_)) => true, + _ => false, + } +} + +/// tw-dialect 各家的流解析器 +enum Parser { + Anthropic(tw_dialect::anthropic::stream::Parser), + Chat(tw_dialect::chat::stream::Parser), + Responses(tw_dialect::responses::stream::Parser), + Gemini(tw_dialect::gemini::stream::Parser), + Bedrock(tw_dialect::bedrock::stream::Parser), +} + +impl Parser { + fn new(upstream: Dialect) -> Parser { + match upstream { + Dialect::Anthropic => Parser::Anthropic(Default::default()), + Dialect::Chat => Parser::Chat(Default::default()), + Dialect::Responses => Parser::Responses(Default::default()), + Dialect::Gemini => Parser::Gemini(Default::default()), + Dialect::Bedrock => Parser::Bedrock(Default::default()), + } + } + + fn finish(&mut self, out: &mut Vec) { + match self { + Parser::Anthropic(_) => {} + Parser::Chat(p) => p.finish(out), + Parser::Responses(p) => p.finish(out), + Parser::Gemini(p) => p.finish(out), + Parser::Bedrock(p) => p.finish(out), + } + } +} + +/// SSE 的流。**截断了的读到哪儿算哪儿**:最后半帧解析不了,就停在它前面 +fn stream(body: &[u8], upstream: Dialect) -> Answer { + let mut asm = Assembly::default(); + let mut parser = Parser::new(upstream); + let mut rest = body; + while !rest.is_empty() { + // 整份都在手里,不必像收流时那样攒着:按帧的边界一段一段切 + let (raw, next) = match frame::frame_end(rest) { + Some((end, sep)) => (&rest[..end], &rest[end + sep..]), + None => (rest, &rest[rest.len()..]), + }; + rest = next; + let Some(f) = frame::parse(raw) else { + continue; + }; + let mut events = Vec::new(); + match &mut parser { + Parser::Anthropic(p) => { + if let Some(label) = anthropic_other(&f) { + asm.other(&label); + } + p.frame(&f, &mut events); + } + Parser::Responses(p) => { + if let Some(label) = responses_other(&f) { + asm.other(&label); + } + p.frame(&f, &mut events); + } + Parser::Gemini(p) => { + // 自己解析这一帧,解析器也用这一份:不解析两遍 + if let Ok(v) = serde_json::from_str::(&f.data) { + gemini_chunk(&v, p, &mut asm, &mut events); + } + } + Parser::Chat(p) => p.frame(&f, &mut events), + Parser::Bedrock(p) => p.frame(&f, &mut events), + } + asm.events(events); + } + let mut events = Vec::new(); + parser.finish(&mut events); + asm.events(events); + asm.finish() +} + +/// 解析器跳过的块(服务端工具的调用和结果、MCP……):在它开始的那一帧上认出来 +fn anthropic_other(f: &Frame) -> Option { + if !f.data.contains("\"content_block_start\"") { + return None; + } + let v: Value = serde_json::from_str(&f.data).ok()?; + let kind = v.get("content_block")?.get("type")?.as_str()?; + (!matches!(kind, "text" | "thinking" | "redacted_thinking" | "tool_use")) + .then(|| kind.to_string()) +} + +/// 解析器跳过的输出项(托管工具的调用:web_search_call、image_generation_call……) +fn responses_other(f: &Frame) -> Option { + if !f.data.contains("\"response.output_item.added\"") { + return None; + } + let v: Value = serde_json::from_str(&f.data).ok()?; + let kind = v.get("item")?.get("type")?.as_str()?; + (!matches!( + kind, + "message" | "reasoning" | "function_call" | "custom_tool_call" + )) + .then(|| kind.to_string()) +} + +/// Gemini 的一帧(数组里的一个元素)。解析器只认文字、推理和函数调用;图片和代码执行 +/// 在这里认,排在这一帧的文字前面 +fn gemini_chunk( + v: &Value, + p: &mut tw_dialect::gemini::stream::Parser, + asm: &mut Assembly, + events: &mut Vec, +) { + let parts = v + .get("candidates") + .and_then(|c| c.get(0)) + .and_then(|c| c.get("content")) + .and_then(|c| c.get("parts")) + .and_then(Value::as_array) + .map(Vec::as_slice) + .unwrap_or(&[]); + let mut pieces = Vec::new(); + read::gemini_parts(parts, &mut pieces); + for piece in &pieces { + if matches!(piece, read::Piece::Image { .. } | read::Piece::Other(_)) { + asm.push(super::part(piece)); + } + } + p.chunk(v, events); +} + +/// 不带 `alt=sse` 的 Gemini 流:一个逐步写出的 JSON 数组,一个元素是一帧。截断了的 +/// 读到最后一个完整的元素 +fn gemini_array(body: &[u8]) -> Answer { + let mut asm = Assembly::default(); + let mut parser = tw_dialect::gemini::stream::Parser::default(); + let start = body + .iter() + .position(|b| *b == b'[') + .map_or(body.len(), |i| i + 1); + let mut rest = &body[start..]; + loop { + let skip = rest + .iter() + .position(|b| !(b.is_ascii_whitespace() || *b == b',')) + .unwrap_or(rest.len()); + rest = &rest[skip..]; + if rest.first().is_none_or(|b| *b == b']') { + break; + } + let mut one = serde_json::Deserializer::from_slice(rest).into_iter::(); + let Some(Ok(v)) = one.next() else { + break; + }; + let used = one.byte_offset(); + let mut events = Vec::new(); + gemini_chunk(&v, &mut parser, &mut asm, &mut events); + asm.events(events); + rest = &rest[used..]; + } + let mut events = Vec::new(); + parser.finish(&mut events); + asm.events(events); + asm.finish() +} + +/// 收拾一下:空的文字块不算;没有参数的函数调用是 `{}`;别的格式的上游包起来的自由格式 +/// 原文拆出来(和网关转换时一样,见 tw-dialect 的 `Normalizer`) +fn tidy(parts: &mut Vec, upstream: Dialect, freeform: &HashSet) { + parts.retain(|p| !matches!(p, TranscriptPart::Text { text } if text.is_empty())); + for p in parts { + let TranscriptPart::ToolCall { name, input, .. } = p else { + continue; + }; + if freeform.contains(name.as_str()) { + if upstream != Dialect::Responses { + *input = unwrap_freeform(input); + } + } else if input.trim().is_empty() { + *input = "{}".into(); + } + } +} + +fn unwrap_freeform(json_text: &str) -> String { + match serde_json::from_str::(json_text) { + Ok(Value::Object(o)) => match o.get("input") { + Some(Value::String(s)) => s.clone(), + _ => json_text.to_string(), + }, + Ok(Value::String(s)) => s, + _ => json_text.to_string(), + } +} diff --git a/crates/tw-store/src/transcript/mod.rs b/crates/tw-store/src/transcript/mod.rs new file mode 100644 index 00000000..d5a8e676 --- /dev/null +++ b/crates/tw-store/src/transcript/mod.rs @@ -0,0 +1,1932 @@ +//! 一次会话读成一段对话(`GET /sessions/{id}/transcript`)。 +//! +//! Claude Code 这类客户端每一轮都把整段历史发上来:请求 i 的消息 = 请求 i-1 的消息 + 上一轮 +//! 的回答 + 新的用户消息或工具结果。所以按会话里的顺序一个一个往下读,**每个请求只交出它 +//! 新带来的那几条**;回答从存下来的响应里读(见 [`answer`])。 +//! +//! # 怎么认「新的那几条」 +//! +//! 上一个读得懂的请求的消息是这一个的开头(逐条比指纹),剩下的就是新的;剩下的第一条是 +//! 助手消息的话,它是上一轮的回答,已经在上一轮的 `output` 里了,去掉。对不上(压缩过、 +//! 改过历史),或者上一个请求读不懂,就交出这个请求的整段历史,标 `restart`。 +//! +//! 比的是规整过的样子(见 [`read::Piece`]):缓存断点、推理签名、键的顺序都不算。**推理 +//! 整个不算**:有的客户端到了下一轮就把前面的推理去掉(接口本来也不读它们),算上的话, +//! 这样的客户端每一轮都对不上。 +//! +//! # 读多少、留多少 +//! +//! 几百轮的会话,每个请求几 MB。每份正文读一次、解析一次,读完这一轮就丢;从一个请求留到 +//! 下一个的只有每条消息 16 字节的指纹和系统提示。 + +mod answer; +mod read; + +use std::collections::HashSet; + +use serde_json::Value; +use tw_api::{TranscriptGap, TranscriptMessage, TranscriptPart, TranscriptRole, TranscriptTurn}; +use tw_dialect::ir::Dialect; + +use crate::blobs::{Blobs, Which}; +use crate::db::RequestRow; +use crate::search::text::{client_dialect, dialect_of}; +use read::{Input, Piece, Role}; + +/// 读成一段对话。`rows` 是这次会话的请求,和会话详情同样的顺序 +/// ([`crate::Db::session_requests`])。 +/// +/// **已脱敏**,和请求详情里的正文同一套打码(`tw_secret::mask_body`)。 +pub fn build(session: &str, rows: &[RequestRow], blobs: &Blobs) -> tw_api::Transcript { + let mut t = tw_api::Transcript { + session: session.to_string(), + system: None, + turns: Vec::with_capacity(rows.len()), + }; + let mut chain = Chain::default(); + for row in rows { + chain.turn(row, blobs, &mut t); + } + mask(&mut t); + t +} + +/// 一条消息比对用的指纹 +type Fp = [u8; 16]; + +/// 读到哪儿了:上一个读得懂的请求留下来的东西。 +#[derive(Default)] +struct Chain { + /// 它的每条消息的指纹(只有推理的消息不比,不在里面)。还没有读得懂的请求是 None + prev: Option>, + /// 它的系统提示 + system: Option, + /// 它之后有没有读不懂的请求 + broken: bool, + /// 它是第几轮,回答完整地交出去了没有 + last: Option<(usize, bool)>, +} + +impl Chain { + fn turn(&mut self, row: &RequestRow, blobs: &Blobs, t: &mut tw_api::Transcript) { + let mut turn = TranscriptTurn { + id: row.id.to_string(), + restart: false, + system_changed: None, + input: Vec::new(), + output: Vec::new(), + gaps: Vec::new(), + }; + // 不生成回答的调用(数 token、Responses 的压缩):问的是这段对话,不是对话里的一句。 + // 不读,也不和前后比 + let Some(client) = client_dialect(&row.path) else { + t.turns.push(turn); + return; + }; + let mut freeform = HashSet::new(); + let readable = match request(row, blobs) { + Ok(v) => { + self.read(client, &v, &mut turn, t, &mut freeform); + true + } + Err(gap) => { + turn.gaps.push(gap); + self.broken = true; + false + } + }; + let (output, gap) = output(row, blobs, upstream_of(row, client), &freeform); + turn.output = output; + turn.gaps.extend(gap); + if readable { + let shown = !turn.output.is_empty() + && !turn.gaps.iter().any(|g| { + matches!( + g, + TranscriptGap::ResponseMissing + | TranscriptGap::ResponseTruncated + | TranscriptGap::ResponseUnreadable + ) + }); + self.last = Some((t.turns.len(), shown)); + } + t.turns.push(turn); + } + + /// 读得懂的请求:系统提示,新的消息 + fn read( + &mut self, + client: Dialect, + v: &Value, + turn: &mut TranscriptTurn, + t: &mut tw_api::Transcript, + freeform: &mut HashSet, + ) { + let read::Body { + system, + items, + freeform: tools, + } = read::body(client, v); + freeform.extend(tools); + let system = system + .iter() + .map(|s| s.as_ref()) + .filter(|s| !s.is_empty()) + .collect::>() + .join("\n\n"); + match &self.system { + None => t.system = (!system.is_empty()).then(|| system.clone()), + Some(prev) if *prev != system => turn.system_changed = Some(system.clone()), + Some(_) => {} + } + + let messages = merge(items); + let fps: Vec<(usize, Fp)> = messages + .iter() + .enumerate() + .filter_map(|(i, m)| fp(m).map(|f| (i, f))) + .collect(); + let start = match (&self.prev, self.broken) { + // 前面有读不懂的:它带来的那几条没交出去过,从头交 + (_, true) => None, + (None, false) => Some(0), + (Some(prev), false) => continues(prev, &fps), + }; + turn.restart = start.is_none(); + let mut new = &messages[start.unwrap_or(0)..]; + // 剩下的第一条助手消息是上一轮的回答,已经在上一轮的 `output` 里。**那一轮的回答没有 + // 完整交出去的不去掉**(没存下、只存了开头、读不懂):这一条就是它说过什么的记录 + if start.is_some() + && let Some((at, true)) = self.last + && let Some(said) = new.first().filter(|m| m.role == Role::Assistant) + { + same_calls(&mut t.turns[at].output, said); + new = &new[1..]; + } + turn.input = new.iter().map(message).collect(); + + self.prev = Some(fps.into_iter().map(|(_, f)| f).collect()); + self.system = Some(system); + self.broken = false; + } +} + +/// 读请求体:没存下来的、只存了开头的、解析不了的各是一种缺口。 +fn request(row: &RequestRow, blobs: &Blobs) -> Result { + let raw = blobs + .get(row.at_ms, row.id, Which::Request) + .ok_or(TranscriptGap::RequestMissing)?; + if blobs + .original_len(row.at_ms, row.id, Which::Request) + .is_some_and(|n| n > raw.len()) + { + return Err(TranscriptGap::RequestTruncated); + } + serde_json::from_slice(&raw).map_err(|_| TranscriptGap::RequestTruncated) +} + +/// 回答它的那一家说的格式:转换过的记在行上,直通的就是客户端那一种(和按正文找一样) +fn upstream_of(row: &RequestRow, client: Dialect) -> Dialect { + row.translated + .as_deref() + .and_then(|j| serde_json::from_str::(j).ok()) + .map_or(client, |t| dialect_of(t.to)) +} + +/// 这一轮的回答,和读不出来的那个缺口。 +fn output( + row: &RequestRow, + blobs: &Blobs, + upstream: Dialect, + freeform: &HashSet, +) -> (Vec, Option) { + // 上游接下了、回了 2xx 的才有回答可读 + let answered = row.status.is_some_and(|s| (200..300).contains(&s)); + let Some(body) = blobs.get(row.at_ms, row.id, Which::Response) else { + // 没走到上游的、上游回了错误的,本来就没有回答;一个字节都没收到客户端就走了的也是 + let missing = answered && row.bytes != Some(0); + return ( + Vec::new(), + missing.then_some(TranscriptGap::ResponseMissing), + ); + }; + // 上游回了错误:存下来的是错误,不是回答。失败在会话详情里已经有了,这里不重复 + if !answered { + return (Vec::new(), None); + } + let truncated = blobs + .original_len(row.at_ms, row.id, Which::Response) + .is_some_and(|n| n > body.len()); + let a = answer::read(&body, upstream, freeform); + let gap = if truncated { + Some(TranscriptGap::ResponseTruncated) + } else if !a.recognized { + Some(TranscriptGap::ResponseUnreadable) + } else { + None + }; + (a.parts, gap) +} + +/// 一条消息。同一个角色连着的几条并成一条:Responses 里推理、文字、几个调用是几个输入项, +/// 可它们是同一次回答;Chat 里几个调用的结果是几条 `tool` 消息。用户和系统消息不并 +struct Message<'a> { + role: Role, + pieces: Vec>, +} + +fn merge(items: Vec>) -> Vec> { + let mut out: Vec = Vec::with_capacity(items.len()); + for it in items { + if it.pieces.is_empty() { + continue; + } + match out.last_mut() { + Some(last) + if last.role == it.role && matches!(it.role, Role::Assistant | Role::Tool) => + { + last.pieces.extend(it.pieces) + } + _ => out.push(Message { + role: it.role, + pieces: it.pieces, + }), + } + } + out +} + +/// 一条消息比对用的指纹。推理不算(见模块的说明);除了推理什么都没有的消息不比,是 None。 +fn fp(m: &Message) -> Option { + fn field(h: &mut blake3::Hasher, s: &str) { + h.update(&(s.len() as u64).to_le_bytes()); + h.update(s.as_bytes()); + } + let mut h = blake3::Hasher::new(); + h.update(&[m.role as u8]); + let mut any = false; + for p in &m.pieces { + match p { + Piece::Thinking(_) => continue, + Piece::Text(t) => { + h.update(&[1]); + field(&mut h, t); + } + Piece::ToolCall { id, name, input } => { + h.update(&[2]); + field(&mut h, id); + field(&mut h, name); + match input { + Input::Args(s) | Input::Raw(s) => { + h.update(&[0]); + field(&mut h, s); + } + // 键按字母排着写出来(serde_json 的对象就是这么存的):顺序不算 + Input::Json(v) => { + h.update(&[1]); + let _ = serde_json::to_writer(&mut h, v); + } + } + } + Piece::ToolResult { + call_id, + text, + is_error, + } => { + h.update(&[3, *is_error as u8]); + field(&mut h, call_id); + field(&mut h, text); + } + Piece::Image { + media_type, + bytes, + data, + } => { + h.update(&[4]); + field(&mut h, media_type.unwrap_or_default()); + h.update(&bytes.unwrap_or(u64::MAX).to_le_bytes()); + field(&mut h, data.unwrap_or_default()); + } + Piece::Other(label) => { + h.update(&[5]); + field(&mut h, label); + } + } + any = true; + } + let mut out = [0; 16]; + out.copy_from_slice(&h.finalize().as_bytes()[..16]); + any.then_some(out) +} + +/// 上一个请求的消息是不是这一个的开头。是的话,新的从第几条开始 +fn continues(prev: &[Fp], cur: &[(usize, Fp)]) -> Option { + if cur.len() < prev.len() || cur.iter().zip(prev).any(|((_, a), b)| a != b) { + return None; + } + Some(prev.len().checked_sub(1).map_or(0, |last| cur[last].0 + 1)) +} + +/// 上一轮回答里工具调用的号,换成客户端记下的那个。 +/// +/// 转换过格式的回答里,号是上游给的(Gemini 根本不给,网关和这里各自现编一个);下一轮的 +/// 工具结果认的是客户端拿到的那个号。名字一个一个对得上才换。 +fn same_calls(output: &mut [TranscriptPart], said: &Message) { + let theirs: Vec<(&str, &str)> = said + .pieces + .iter() + .filter_map(|p| match p { + Piece::ToolCall { id, name, .. } => Some((id.as_ref(), name.as_ref())), + _ => None, + }) + .collect(); + let mine: Vec<(&mut String, &mut String)> = output + .iter_mut() + .filter_map(|p| match p { + TranscriptPart::ToolCall { id, name, .. } => Some((id, name)), + _ => None, + }) + .collect(); + if mine.len() != theirs.len() + || mine + .iter() + .zip(&theirs) + .any(|((_, name), (_, said))| name.as_str() != *said) + { + return; + } + for ((id, _), (said, _)) in mine.into_iter().zip(theirs) { + if id != said { + *id = said.to_string(); + } + } +} + +fn message(m: &Message) -> TranscriptMessage { + TranscriptMessage { + role: match m.role { + Role::User => TranscriptRole::User, + Role::Assistant => TranscriptRole::Assistant, + Role::Tool => TranscriptRole::Tool, + Role::System => TranscriptRole::System, + }, + parts: m.pieces.iter().map(part).collect(), + } +} + +/// 一块交出去的样子。**还没打码**:打码在最后一起做 +fn part(p: &Piece) -> TranscriptPart { + match p { + Piece::Text(t) => TranscriptPart::Text { + text: t.to_string(), + }, + Piece::Thinking(t) => TranscriptPart::Thinking { + text: t.to_string(), + }, + Piece::ToolCall { id, name, input } => TranscriptPart::ToolCall { + id: id.to_string(), + name: name.to_string(), + input: input.text(), + }, + Piece::ToolResult { + call_id, + text, + is_error, + } => TranscriptPart::ToolResult { + call_id: call_id.to_string(), + text: text.to_string(), + is_error: *is_error, + }, + Piece::Image { + media_type, bytes, .. + } => TranscriptPart::Image { + media_type: media_type.map(str::to_string), + bytes: *bytes, + }, + Piece::Other(label) => TranscriptPart::Other { + label: label.to_string(), + }, + } +} + +/// 打码,和请求详情里的正文同一套。**最后一起做**:前后比对、换工具调用的号都要原文 +fn mask(t: &mut tw_api::Transcript) { + fn m(s: &mut String) { + if !s.is_empty() { + *s = tw_secret::mask_body(s); + } + } + if let Some(s) = &mut t.system { + m(s); + } + for turn in &mut t.turns { + if let Some(s) = &mut turn.system_changed { + m(s); + } + let parts = turn + .input + .iter_mut() + .flat_map(|msg| msg.parts.iter_mut()) + .chain(turn.output.iter_mut()); + for p in parts { + match p { + TranscriptPart::Text { text } | TranscriptPart::Thinking { text } => m(text), + TranscriptPart::ToolCall { id, name, input } => { + m(id); + m(name); + m(input); + } + TranscriptPart::ToolResult { call_id, text, .. } => { + m(call_id); + m(text); + } + TranscriptPart::Image { media_type, .. } => { + if let Some(s) = media_type { + m(s); + } + } + TranscriptPart::Other { label } => m(label), + } + } + } +} + +#[cfg(test)] +mod tests { + use serde_json::{Value, json}; + use tw_api::{ + Transcript, TranscriptGap as Gap, TranscriptMessage, TranscriptPart as P, + TranscriptRole as R, + }; + + use super::*; + use crate::db::Db; + use crate::db::tests::row; + + const NOW: i64 = 1_790_000_000_000; + + /// 一份测试用的盘:请求库和正文目录,记录都归在会话 `s` 里 + struct Disk { + _dir: tempfile::TempDir, + db: Db, + blobs: Blobs, + next: i64, + } + + impl Disk { + fn new() -> Disk { + let dir = tempfile::tempdir().unwrap(); + Disk { + blobs: Blobs::new(dir.path().join("blobs")), + db: Db::in_memory().unwrap(), + _dir: dir, + next: 0, + } + } + + /// 一轮:请求体和回答都存下了 + fn turn(&mut self, path: &str, request: &Value, response: &[u8]) -> i64 { + let request = request.to_string(); + self.put(path, Some(request.as_bytes()), Some(response), |_| {}) + } + + /// 一轮,存下了哪些自己定;`edit` 改这一行的记录 + fn put( + &mut self, + path: &str, + request: Option<&[u8]>, + response: Option<&[u8]>, + edit: impl FnOnce(&mut RequestRow), + ) -> i64 { + self.next += 1; + let id = self.next; + let mut r = row(id, NOW + id * 1000); + r.path = path.into(); + r.session = Some("s".into()); + edit(&mut r); + self.db.insert(&r).unwrap(); + if let Some(b) = request { + assert!(self.blobs.put(r.at_ms, id, Which::Request, b)); + } + if let Some(b) = response { + assert!(self.blobs.put(r.at_ms, id, Which::Response, b)); + } + id + } + + /// 存下来的只是开头:原本有 `len` 那么长 + fn cut(&self, id: i64, which: Which, len: usize) { + let at = NOW + id * 1000; + let body = self.blobs.get(at, id, which).unwrap(); + assert!(self.blobs.put_with_len(at, id, which, &body, len)); + } + + fn transcript(&self) -> Transcript { + let rows = self.db.session_requests("s").unwrap(); + build("s", &rows, &self.blobs) + } + } + + fn sse(frames: &[(&str, Value)]) -> Vec { + let mut s = String::new(); + for (event, data) in frames { + if !event.is_empty() { + s.push_str(&format!("event: {event}\n")); + } + s.push_str(&format!("data: {data}\n\n")); + } + s.into_bytes() + } + + /// 一段字切成两半,按字符切 + fn halves(s: &str) -> (String, String) { + let n = s.chars().count() / 2; + (s.chars().take(n).collect(), s.chars().skip(n).collect()) + } + + /// Anthropic 的流:给几块内容,写成每块的开始、两段增量、结束。服务端工具那样的块只有 + /// 开始和结束 + fn anthropic_stream(blocks: &[Value]) -> Vec { + let mut f = vec![( + "message_start", + json!({"type": "message_start", "message": {"id": "msg_1", "model": "claude-sonnet-4-5", + "usage": {"input_tokens": 10}}}), + )]; + for (i, b) in blocks.iter().enumerate() { + let delta = |d: Value| { + ( + "content_block_delta", + json!({"type": "content_block_delta", "index": i, "delta": d}), + ) + }; + let start = |block: Value| { + ( + "content_block_start", + json!({"type": "content_block_start", "index": i, "content_block": block}), + ) + }; + match b["type"].as_str().unwrap() { + "text" => { + f.push(start(json!({"type": "text", "text": ""}))); + let (a, z) = halves(b["text"].as_str().unwrap()); + f.push(delta(json!({"type": "text_delta", "text": a}))); + f.push(delta(json!({"type": "text_delta", "text": z}))); + } + "thinking" => { + f.push(start(json!({"type": "thinking", "thinking": ""}))); + f.push(delta( + json!({"type": "thinking_delta", "thinking": b["thinking"]}), + )); + f.push(delta( + json!({"type": "signature_delta", "signature": b["signature"]}), + )); + } + "tool_use" => { + f.push(start( + json!({"type": "tool_use", "id": b["id"], "name": b["name"], "input": {}}), + )); + let (a, z) = halves(&b["input"].to_string()); + f.push(delta( + json!({"type": "input_json_delta", "partial_json": a}), + )); + f.push(delta( + json!({"type": "input_json_delta", "partial_json": z}), + )); + } + _ => f.push(start(b.clone())), + } + f.push(( + "content_block_stop", + json!({"type": "content_block_stop", "index": i}), + )); + } + f.push(( + "message_delta", + json!({"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 9}}), + )); + f.push(("message_stop", json!({"type": "message_stop"}))); + sse(&f) + } + + fn text(t: &str) -> P { + P::Text { text: t.into() } + } + + fn thinking(t: &str) -> P { + P::Thinking { text: t.into() } + } + + fn call(id: &str, name: &str, input: &str) -> P { + P::ToolCall { + id: id.into(), + name: name.into(), + input: input.into(), + } + } + + fn result(call_id: &str, t: &str) -> P { + P::ToolResult { + call_id: call_id.into(), + text: t.into(), + is_error: false, + } + } + + fn msg(role: R, parts: Vec

) -> TranscriptMessage { + TranscriptMessage { role, parts } + } + + fn user(t: &str) -> Value { + json!({"role": "user", "content": t}) + } + + fn assistant(t: &str) -> Value { + json!({"role": "assistant", "content": t}) + } + + /// Anthropic 的一轮:一段 system、给出的消息,流式回答一段话 + fn anthropic(messages: &[Value]) -> Value { + json!({"model": "claude-sonnet-4-5", "system": "你是助手", "stream": true, "messages": messages}) + } + + fn says(t: &str) -> Vec { + anthropic_stream(&[json!({"type": "text", "text": t})]) + } + + fn with_cache(mut m: Value) -> Value { + if let Some(last) = m["content"].as_array_mut().and_then(|c| c.last_mut()) { + last["cache_control"] = json!({"type": "ephemeral"}); + } + m + } + + // ───────────────────────────────────────────────── 四种客户端格式 + + /// 照 Claude Code 的样子:系统提示是几块,缓存断点每一轮挪到最后一条上,推理带着签名, + /// 工具调用和结果,结果里有一张截图。每一轮只交出新的那几条 + #[test] + fn a_claude_code_session_reads_turn_by_turn() { + let mut d = Disk::new(); + let system = json!([ + {"type": "text", "text": "x-anthropic-billing-header: cc_version=2.0.0"}, + {"type": "text", "text": "You are Claude Code.", "cache_control": {"type": "ephemeral"}} + ]); + let tools = json!([{"name": "Read", "input_schema": {"type": "object"}}, + {"name": "Edit", "input_schema": {"type": "object"}}]); + let body = |messages: Vec| { + json!({"model": "claude-sonnet-4-5", "system": system, "tools": tools, "max_tokens": 32000, + "stream": true, "messages": messages}) + }; + let u1 = json!({"role": "user", "content": [ + {"type": "text", "text": "上下文"}, + {"type": "text", "text": "修一下 main.rs 里的 bug"} + ]}); + let a1 = |signature: &str| { + json!({"role": "assistant", "content": [ + {"type": "thinking", "thinking": "先读文件", "signature": signature}, + {"type": "text", "text": "我先看看文件。"}, + {"type": "tool_use", "id": "toolu_1", "name": "Read", "input": {"file_path": "src/main.rs"}} + ]}) + }; + let r1 = json!({"role": "user", "content": [{"type": "tool_result", "tool_use_id": "toolu_1", + "content": "fn main() {\n let key = \"sk-ant-api03-SECRETSECRETSECRET\";\n}"}]}); + let a2 = |with_thinking: bool| { + let mut blocks = vec![ + json!({"type": "text", "text": "密钥写死了,我来改。"}), + json!({"type": "tool_use", "id": "toolu_2", "name": "Edit", + "input": {"file_path": "src/main.rs", "old": "let key", "new": "let key = env()"}}), + ]; + if with_thinking { + blocks.insert( + 0, + json!({"type": "thinking", "thinking": "要改成读环境变量", "signature": "sig-2"}), + ); + } + json!({"role": "assistant", "content": blocks}) + }; + let png = "QUJD".repeat(10); + let r2 = json!({"role": "user", "content": [ + {"type": "tool_result", "tool_use_id": "toolu_2", "content": [ + {"type": "text", "text": "已修改"}, + {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": png}} + ]}, + {"type": "text", "text": "看起来不错,再跑一下测试"} + ]}); + + d.turn( + "/v1/messages", + &body(vec![with_cache(u1.clone())]), + &anthropic_stream(&[ + json!({"type": "thinking", "thinking": "先读文件", "signature": "sig-1"}), + json!({"type": "text", "text": "我先看看文件。"}), + json!({"type": "tool_use", "id": "toolu_1", "name": "Read", "input": {"file_path": "src/main.rs"}}), + ]), + ); + d.turn( + "/v1/messages", + &body(vec![u1.clone(), a1("sig-1"), with_cache(r1.clone())]), + &anthropic_stream(&[ + json!({"type": "thinking", "thinking": "要改成读环境变量", "signature": "sig-2"}), + json!({"type": "text", "text": "密钥写死了,我来改。"}), + json!({"type": "tool_use", "id": "toolu_2", "name": "Edit", + "input": {"file_path": "src/main.rs", "old": "let key", "new": "let key = env()"}}), + ]), + ); + // 第三轮:第一轮推理的签名换了一个,第二轮的推理被客户端去掉了 —— 都不算改过历史 + d.turn( + "/v1/messages", + &body(vec![u1, a1("sig-1-again"), r1, a2(false), with_cache(r2)]), + &says("好的。"), + ); + + let t = d.transcript(); + assert_eq!(t.session, "s"); + assert_eq!( + t.system.as_deref(), + Some("x-anthropic-billing-header: cc_version=2.0.0\n\nYou are Claude Code.") + ); + assert_eq!(t.turns.len(), 3); + assert_eq!( + t.turns.iter().map(|x| x.id.as_str()).collect::>(), + ["1", "2", "3"] + ); + for x in &t.turns { + assert!(!x.restart, "{x:?}"); + assert_eq!(x.system_changed, None); + assert!(x.gaps.is_empty(), "{x:?}"); + } + + let first = &t.turns[0]; + assert_eq!( + first.input, + [msg( + R::User, + vec![ + text("上下文"), + text("修一下 main.rs 里的 bug") + ] + )] + ); + assert_eq!( + first.output, + [ + thinking("先读文件"), + text("我先看看文件。"), + call("toolu_1", "Read", r#"{"file_path":"src/main.rs"}"#) + ] + ); + + // 第二轮新的只有工具结果:上一轮的回答已经在上一轮里了。结果里的密钥打了码 + let second = &t.turns[1]; + assert_eq!(second.input.len(), 1, "{:?}", second.input); + assert_eq!(second.input[0].role, R::Tool); + let P::ToolResult { + call_id, + text: said, + is_error, + } = &second.input[0].parts[0] + else { + panic!("{:?}", second.input) + }; + assert_eq!((call_id.as_str(), *is_error), ("toolu_1", false)); + assert!(said.contains("sk-an…CRET"), "{said}"); + assert!(!said.contains("SECRETSECRET"), "{said}"); + assert_eq!(second.output[1], text("密钥写死了,我来改。")); + assert!(matches!(&second.output[2], P::ToolCall { name, .. } if name == "Edit")); + + // 第三轮:工具结果、结果里的截图(只有类型和大小)、一句话。有文字就不只是工具结果 + assert_eq!( + t.turns[2].input, + [msg( + R::User, + vec![ + result("toolu_2", "已修改"), + P::Image { + media_type: Some("image/png".into()), + bytes: Some(30) + }, + text("看起来不错,再跑一下测试") + ] + )] + ); + assert_eq!(t.turns[2].output, [text("好的。")]); + + // 图片的数据、推理的签名都不出门 + let wire = serde_json::to_string(&t).unwrap(); + assert!(!wire.contains(&png), "{wire}"); + assert!(!wire.contains("sig-1"), "{wire}"); + } + + /// Chat:`tool_calls` 和 `tool` 消息,对话中途的系统消息照原位置留着,回答有流式的也有整包的 + #[test] + fn an_openai_chat_session_with_tool_calls() { + let mut d = Disk::new(); + let sys = json!({"role": "system", "content": "你是助手"}); + let ask = user("列一下文件"); + let a1 = json!({"role": "assistant", "content": "我来看看", "reasoning_content": "想一想", + "tool_calls": [{"id": "call_1", "type": "function", + "function": {"name": "ls", "arguments": "{\"dir\":\".\"}"}}]}); + let r1 = json!({"role": "tool", "tool_call_id": "call_1", "content": "README.md"}); + let a2 = assistant("有一个 README.md。"); + let body = |messages: Vec| json!({"model": "deepseek-chat", "stream": true, "messages": messages}); + let chunk = |delta: Value, finish: Value| { + ( + "", + json!({"id": "c", "choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}), + ) + }; + let mut stream = sse(&[ + chunk( + json!({"role": "assistant", "reasoning_content": "想一想"}), + Value::Null, + ), + chunk(json!({"content": "我来"}), Value::Null), + chunk(json!({"content": "看看"}), Value::Null), + chunk( + json!({"tool_calls": [{"index": 0, "id": "call_1", "type": "function", + "function": {"name": "ls", "arguments": ""}}]}), + Value::Null, + ), + chunk( + json!({"tool_calls": [{"index": 0, "function": {"arguments": "{\"dir\":"}}]}), + Value::Null, + ), + chunk( + json!({"tool_calls": [{"index": 0, "function": {"arguments": "\".\"}"}}]}), + Value::Null, + ), + chunk(json!({}), json!("tool_calls")), + ]); + stream.extend_from_slice(b"data: [DONE]\n\n"); + let whole = |t: &str| { + json!({"choices": [{"message": {"role": "assistant", "content": t}, "finish_reason": "stop"}]}) + .to_string() + .into_bytes() + }; + d.turn( + "/v1/chat/completions", + &body(vec![sys.clone(), ask.clone()]), + &stream, + ); + d.turn( + "/v1/chat/completions", + &body(vec![sys.clone(), ask.clone(), a1.clone(), r1.clone()]), + &whole("有一个 README.md。"), + ); + d.turn( + "/v1/chat/completions", + &body(vec![ + sys, + ask, + a1, + r1, + a2, + json!({"role": "system", "content": "之后用英文回答"}), + user("谢谢"), + ]), + &whole("You're welcome."), + ); + + let t = d.transcript(); + assert_eq!(t.system.as_deref(), Some("你是助手")); + assert_eq!(t.turns[0].input, [msg(R::User, vec![text("列一下文件")])]); + assert_eq!( + t.turns[0].output, + [ + thinking("想一想"), + text("我来看看"), + call("call_1", "ls", r#"{"dir":"."}"#) + ] + ); + assert_eq!( + t.turns[1].input, + [msg(R::Tool, vec![result("call_1", "README.md")])] + ); + assert_eq!(t.turns[1].output, [text("有一个 README.md。")]); + assert_eq!( + t.turns[2].input, + [ + msg(R::System, vec![text("之后用英文回答")]), + msg(R::User, vec![text("谢谢")]) + ] + ); + assert_eq!(t.turns[2].output, [text("You're welcome.")]); + assert!(t.turns.iter().all(|x| !x.restart && x.gaps.is_empty())); + } + + /// Responses(Codex):instructions 和开头的 developer 消息是系统提示;推理项、函数调用、 + /// 结果是一个个输入项,一次回答的几项并成一条;托管工具的调用是 `other` + #[test] + fn a_codex_session_on_the_responses_format() { + let mut d = Disk::new(); + let dev = json!({"type": "message", "role": "developer", + "content": [{"type": "input_text", "text": "sandbox: workspace-write"}]}); + let env = json!({"type": "message", "role": "user", + "content": [{"type": "input_text", "text": "cwd"}]}); + let ask = json!({"type": "message", "role": "user", + "content": [{"type": "input_text", "text": "修好构建"}]}); + let args = r#"{"command":["cargo","build"]}"#; + let rs1 = json!({"type": "reasoning", "id": "rs_1", + "summary": [{"type": "summary_text", "text": "看看报错"}], "encrypted_content": "gAAA1"}); + let fc1 = + json!({"type": "function_call", "call_id": "c1", "name": "shell", "arguments": args}); + let out1 = json!({"type": "function_call_output", "call_id": "c1", + "output": "error[E0308]: mismatched types"}); + let patch = "*** Begin Patch\n*** End Patch"; + let rs2 = + json!({"type": "reasoning", "id": "rs_2", "summary": [], "encrypted_content": "gAAA2"}); + let ws = json!({"type": "web_search_call", "id": "ws_1", "status": "completed", + "action": {"type": "search", "query": "E0308"}}); + let cc = json!({"type": "custom_tool_call", "call_id": "c2", "name": "apply_patch", "input": patch}); + let out2 = json!({"type": "custom_tool_call_output", "call_id": "c2", "output": "Done!"}); + let body = |input: Vec| { + json!({"model": "gpt-5.5", "instructions": "You are Codex.", "input": input, "stream": true, + "tools": [{"type": "function", "name": "shell", "parameters": {"type": "object"}}, + {"type": "custom", "name": "apply_patch"}]}) + }; + let ev = |name: &str, mut data: Value| { + data["type"] = json!(name); + (name.to_string(), data) + }; + let stream = |frames: Vec<(String, Value)>| { + let frames: Vec<(&str, Value)> = frames + .iter() + .map(|(n, v)| (n.as_str(), v.clone())) + .collect(); + sse(&frames) + }; + let first = stream(vec![ + ev( + "response.created", + json!({"response": {"id": "resp_1", "model": "gpt-5.5"}}), + ), + ev( + "response.output_item.added", + json!({"output_index": 0, "item": {"type": "reasoning", "id": "rs_1", "summary": []}}), + ), + ev( + "response.reasoning_summary_text.delta", + json!({"output_index": 0, "summary_index": 0, "delta": "看看报错"}), + ), + ev( + "response.output_item.done", + json!({"output_index": 0, "item": rs1}), + ), + ev( + "response.output_item.added", + json!({"output_index": 1, "item": {"type": "function_call", "call_id": "c1", "name": "shell", "arguments": ""}}), + ), + ev( + "response.function_call_arguments.delta", + json!({"output_index": 1, "delta": "{\"command\":"}), + ), + ev( + "response.function_call_arguments.delta", + json!({"output_index": 1, "delta": "[\"cargo\",\"build\"]}"}), + ), + ev( + "response.output_item.done", + json!({"output_index": 1, "item": fc1}), + ), + ev( + "response.completed", + json!({"response": {"usage": {"input_tokens": 1, "output_tokens": 2}}}), + ), + ]); + // 第二轮:推理只有密文(没有摘要),一次网页搜索,一个自由格式的工具调用 + let second = stream(vec![ + ev( + "response.created", + json!({"response": {"id": "resp_2", "model": "gpt-5.5"}}), + ), + ev( + "response.output_item.added", + json!({"output_index": 0, "item": {"type": "reasoning", "id": "rs_2", "summary": []}}), + ), + ev( + "response.output_item.done", + json!({"output_index": 0, "item": rs2}), + ), + ev( + "response.output_item.added", + json!({"output_index": 1, "item": {"type": "web_search_call", "id": "ws_1", "status": "in_progress"}}), + ), + ev( + "response.output_item.done", + json!({"output_index": 1, "item": ws}), + ), + ev( + "response.output_item.added", + json!({"output_index": 2, "item": {"type": "custom_tool_call", "call_id": "c2", "name": "apply_patch", "input": ""}}), + ), + ev( + "response.custom_tool_call_input.delta", + json!({"output_index": 2, "delta": "*** Begin Patch\n"}), + ), + ev( + "response.custom_tool_call_input.delta", + json!({"output_index": 2, "delta": "*** End Patch"}), + ), + ev( + "response.output_item.done", + json!({"output_index": 2, "item": cc}), + ), + ev( + "response.completed", + json!({"response": {"usage": {"input_tokens": 1, "output_tokens": 2}}}), + ), + ]); + let whole = json!({"output": [{"type": "message", "role": "assistant", + "content": [{"type": "output_text", "text": "构建好了。"}]}]}); + let path = "/backend-api/codex/responses"; + d.turn( + path, + &body(vec![dev.clone(), env.clone(), ask.clone()]), + &first, + ); + d.turn( + path, + &body(vec![ + dev.clone(), + env.clone(), + ask.clone(), + rs1.clone(), + fc1.clone(), + out1.clone(), + ]), + &second, + ); + d.turn( + path, + &body(vec![dev, env, ask, rs1, fc1, out1, rs2, ws, cc, out2]), + whole.to_string().as_bytes(), + ); + + let t = d.transcript(); + assert_eq!( + t.system.as_deref(), + Some("You are Codex.\n\nsandbox: workspace-write") + ); + // 用户消息不并:环境说明和要求是两条 + assert_eq!( + t.turns[0].input, + [ + msg( + R::User, + vec![text("cwd")] + ), + msg(R::User, vec![text("修好构建")]) + ] + ); + assert_eq!( + t.turns[0].output, + [thinking("看看报错"), call("c1", "shell", args)] + ); + assert_eq!( + t.turns[1].input, + [msg( + R::Tool, + vec![result("c1", "error[E0308]: mismatched types")] + )] + ); + // 只有密文的推理是一块空的推理 + assert_eq!( + t.turns[1].output, + [ + thinking(""), + P::Other { + label: "web_search_call".into() + }, + call("c2", "apply_patch", patch) + ] + ); + // 推理、搜索、调用三项是同一次回答,并成一条,作为上一轮的回答去掉 + assert_eq!( + t.turns[2].input, + [msg(R::Tool, vec![result("c2", "Done!")])] + ); + assert_eq!(t.turns[2].output, [text("构建好了。")]); + assert!(t.turns.iter().all(|x| !x.restart && x.gaps.is_empty())); + } + + /// Gemini:`functionCall` / `functionResponse`,没有调用号的按函数名对上;推理是带 + /// `thought` 的文字 + #[test] + fn a_gemini_session_with_function_calls() { + let mut d = Disk::new(); + let path = "/v1beta/models/gemini-2.5-pro:streamGenerateContent"; + let sys = json!({"parts": [{"text": "You are a coding agent"}]}); + let ask = json!({"role": "user", "parts": [{"text": "跑一下测试"}]}); + let said = json!({"role": "model", "parts": [{"text": "好,我来跑"}, + {"functionCall": {"name": "run_shell_command", "args": {"command": "npm test"}}}]}); + let ran = json!({"role": "user", "parts": [{"functionResponse": {"name": "run_shell_command", + "response": {"output": "3 passed"}}}]}); + let chunk = |parts: Value| { + ( + "", + json!({"candidates": [{"content": {"role": "model", "parts": parts}}]}), + ) + }; + d.turn( + path, + &json!({"systemInstruction": sys, "contents": [ask.clone()]}), + &sse(&[ + chunk(json!([{"text": "好,"}])), + chunk(json!([{"text": "我来跑"}, + {"functionCall": {"name": "run_shell_command", "args": {"command": "npm test"}}}])), + ]), + ); + d.turn( + path, + &json!({"system_instruction": sys, "contents": [ask, said, ran]}), + &sse(&[ + chunk(json!([{"text": "测试都过了", "thought": true}])), + chunk(json!([{"text": "全部通过。"}])), + ]), + ); + + let t = d.transcript(); + assert_eq!(t.system.as_deref(), Some("You are a coding agent")); + assert_eq!(t.turns[0].input, [msg(R::User, vec![text("跑一下测试")])]); + // 上游没给调用号:回答里读的时候现编了一个,下一轮里客户端记下的是按函数名认的那个,换成它 + assert_eq!( + t.turns[0].output, + [ + text("好,我来跑"), + call( + "run_shell_command", + "run_shell_command", + r#"{"command":"npm test"}"# + ) + ] + ); + assert_eq!( + t.turns[1].input, + [msg(R::Tool, vec![result("run_shell_command", "3 passed")])] + ); + assert_eq!( + t.turns[1].output, + [thinking("测试都过了"), text("全部通过。")] + ); + assert!(t.turns.iter().all(|x| !x.restart && x.gaps.is_empty())); + } + + // ───────────────────────────────────────────────── 前后两个请求怎么比 + + /// 压缩过、改过历史:对不上了,交出整段历史,标 `restart` + #[test] + fn a_compacted_or_edited_history_restarts_with_the_whole_history() { + let mut d = Disk::new(); + d.turn("/v1/messages", &anthropic(&[user("一")]), &says("回一")); + d.turn( + "/v1/messages", + &anthropic(&[user("一"), assistant("回一"), user("二")]), + &says("回二"), + ); + // 压缩:前文换成了一段摘要 + d.turn( + "/v1/messages", + &anthropic(&[user("前文摘要:说过一和二"), user("三")]), + &says("回三"), + ); + // 接着压缩之后的那段往下说 + d.turn( + "/v1/messages", + &anthropic(&[ + user("前文摘要:说过一和二"), + user("三"), + assistant("回三"), + user("四"), + ]), + &says("回四"), + ); + // 改过历史:早先的一条工具结果被清掉了(Claude Code 的 microcompact 就这么做) + d.turn( + "/v1/messages", + &anthropic(&[ + user("前文摘要:说过一和二"), + user("三(已清空)"), + assistant("回三"), + user("四"), + assistant("回四"), + user("五"), + ]), + &says("回五"), + ); + + let t = d.transcript(); + let restart: Vec = t.turns.iter().map(|x| x.restart).collect(); + assert_eq!(restart, [false, false, true, false, true]); + assert_eq!(t.turns[1].input, [msg(R::User, vec![text("二")])]); + // 连着的两条用户消息不并 + assert_eq!( + t.turns[2].input, + [ + msg(R::User, vec![text("前文摘要:说过一和二")]), + msg(R::User, vec![text("三")]) + ] + ); + assert_eq!(t.turns[3].input, [msg(R::User, vec![text("四")])]); + // 整段历史,连同里面的助手消息 + assert_eq!(t.turns[4].input.len(), 6); + assert_eq!(t.turns[4].input[2], msg(R::Assistant, vec![text("回三")])); + } + + /// 系统提示变了:那一轮说出新的那一份;`system` 是第一轮的 + #[test] + fn a_changed_system_prompt_is_said_on_the_turn_it_changed() { + let mut d = Disk::new(); + let with = |system: &str, messages: &[Value]| json!({"model": "m", "system": [{"type": "text", "text": system}], "messages": messages}); + d.turn( + "/v1/messages", + &with("计划模式", &[user("一")]), + &says("回一"), + ); + d.turn( + "/v1/messages", + &with("执行模式", &[user("一"), assistant("回一"), user("开始改")]), + &says("回二"), + ); + d.turn( + "/v1/messages", + &with( + "执行模式", + &[ + user("一"), + assistant("回一"), + user("开始改"), + assistant("回二"), + user("三"), + ], + ), + &says("回三"), + ); + let t = d.transcript(); + assert_eq!(t.system.as_deref(), Some("计划模式")); + let changed: Vec> = t + .turns + .iter() + .map(|x| x.system_changed.as_deref()) + .collect(); + assert_eq!(changed, [None, Some("执行模式"), None]); + // 系统提示变了不等于历史断了 + assert!(t.turns.iter().all(|x| !x.restart)); + assert_eq!(t.turns[1].input, [msg(R::User, vec![text("开始改")])]); + } + + /// 数 token 的请求也是会话里的一轮,但不是对话里的一句:空的,不打断前后的比对 + #[test] + fn a_count_tokens_call_is_an_empty_turn_that_does_not_break_the_chain() { + let mut d = Disk::new(); + d.turn("/v1/messages", &anthropic(&[user("一")]), &says("回一")); + let history = [user("一"), assistant("回一"), user("二")]; + d.turn( + "/v1/messages/count_tokens", + &json!({"model": "m", "messages": history}), + br#"{"input_tokens": 12}"#, + ); + d.turn("/v1/messages", &anthropic(&history), &says("回二")); + let t = d.transcript(); + assert_eq!(t.turns.len(), 3); + let side = &t.turns[1]; + assert!( + side.input.is_empty() + && side.output.is_empty() + && side.gaps.is_empty() + && !side.restart + ); + assert!(!t.turns[2].restart); + assert_eq!(t.turns[2].input, [msg(R::User, vec![text("二")])]); + assert_eq!(t.turns[2].output, [text("回二")]); + } + + /// 失败了的请求没有回答也不算缺;客户端照原样重发,没有新的东西 + #[test] + fn a_failed_turn_has_no_answer_and_its_retry_adds_nothing() { + let mut d = Disk::new(); + let history = [user("一")]; + d.put( + "/v1/messages", + Some(anthropic(&history).to_string().as_bytes()), + Some(br#"{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}"#), + |r| { + r.status = Some(529); + r.error = Some(crate::db::tests::upstream_failed("overloaded")); + }, + ); + d.turn("/v1/messages", &anthropic(&history), &says("回一")); + let t = d.transcript(); + assert!(t.turns[0].output.is_empty() && t.turns[0].gaps.is_empty()); + assert_eq!(t.turns[0].input, [msg(R::User, vec![text("一")])]); + assert!(!t.turns[1].restart); + assert!(t.turns[1].input.is_empty(), "{:?}", t.turns[1].input); + assert_eq!(t.turns[1].output, [text("回一")]); + } + + // ───────────────────────────────────────────────── 读不出来的地方 + + /// 请求体没存下、只存了开头:那一轮没有 `input`,下一个读得懂的从头交出整段历史 + #[test] + fn missing_and_truncated_requests_are_gaps_and_the_next_turn_restarts() { + let mut d = Disk::new(); + d.turn("/v1/messages", &anthropic(&[user("一")]), &says("回一")); + d.put("/v1/messages", None, Some(says("回二").as_slice()), |_| {}); + let h3 = [ + user("一"), + assistant("回一"), + user("二"), + assistant("回二"), + user("三"), + ]; + d.turn("/v1/messages", &anthropic(&h3), &says("回三")); + // 只存了开头:存下来的那一段解析不了 + let mut h4 = h3.to_vec(); + h4.extend([assistant("回三"), user("四")]); + let full = anthropic(&h4).to_string(); + let id = d.put( + "/v1/messages", + Some(&full.as_bytes()[..full.len() / 2]), + Some(says("回四").as_slice()), + |_| {}, + ); + d.cut(id, Which::Request, full.len()); + let mut h5 = h4.clone(); + h5.extend([assistant("回四"), user("五")]); + d.turn("/v1/messages", &anthropic(&h5), &says("回五")); + + let t = d.transcript(); + let gaps: Vec<&[Gap]> = t.turns.iter().map(|x| x.gaps.as_slice()).collect(); + assert_eq!( + gaps, + [ + &[][..], + &[Gap::RequestMissing], + &[], + &[Gap::RequestTruncated], + &[] + ] + ); + let restart: Vec = t.turns.iter().map(|x| x.restart).collect(); + assert_eq!(restart, [false, false, true, false, true]); + // 读不懂的那一轮回答照样读 + assert!(t.turns[1].input.is_empty()); + assert_eq!(t.turns[1].output, [text("回二")]); + assert_eq!(t.turns[2].input.len(), 5); + assert_eq!(t.turns[3].output, [text("回四")]); + assert_eq!(t.turns[4].input.len(), 9); + } + + /// 回答没存下、只存了开头、读不懂:各是一种缺口。没交全的回答,下一轮里客户端记下的那条 + /// 助手消息留着 —— 它是那一轮说过什么的唯一记录 + #[test] + fn missing_truncated_and_unreadable_answers_are_gaps() { + let mut d = Disk::new(); + let mut h = vec![user("一")]; + // 回答没存下:上游回了 200,收到了字节 + d.put( + "/v1/messages", + Some(anthropic(&h).to_string().as_bytes()), + None, + |_| {}, + ); + h.extend([assistant("回一"), user("二")]); + // 只存了开头:读得出第一块,第二块断在半路 + let long = anthropic_stream(&[ + json!({"type": "text", "text": "前一半"}), + json!({"type": "text", "text": "后一半"}), + ]); + let cut = String::from_utf8(long.clone()).unwrap(); + let keep = cut.find("后").unwrap(); + let id = d.put( + "/v1/messages", + Some(anthropic(&h).to_string().as_bytes()), + Some(&long[..keep]), + |_| {}, + ); + d.cut(id, Which::Response, long.len()); + h.extend([assistant("前一半后一半"), user("三")]); + // 读不懂:上游回了 200,正文却是一页 HTML + d.put( + "/v1/messages", + Some(anthropic(&h).to_string().as_bytes()), + Some(b"502 Bad Gateway"), + |_| {}, + ); + h.extend([assistant("回三"), user("四")]); + // 客户端在第一个字节之前就走了:没有回答,也不算缺 + d.put( + "/v1/messages", + Some(anthropic(&h).to_string().as_bytes()), + None, + |r| { + r.cancelled = true; + r.bytes = Some(0); + }, + ); + + let t = d.transcript(); + let gaps: Vec<&[Gap]> = t.turns.iter().map(|x| x.gaps.as_slice()).collect(); + assert_eq!( + gaps, + [ + &[Gap::ResponseMissing][..], + &[Gap::ResponseTruncated], + &[Gap::ResponseUnreadable], + &[] + ] + ); + assert!(t.turns[0].output.is_empty()); + assert_eq!(t.turns[1].output, [text("前一半")]); + assert!(t.turns[2].output.is_empty() && t.turns[3].output.is_empty()); + // 上一轮的回答没交全:客户端记下的那条助手消息留在新的这几条里 + assert!(t.turns.iter().all(|x| !x.restart)); + assert_eq!( + t.turns[1].input, + [ + msg(R::Assistant, vec![text("回一")]), + msg(R::User, vec![text("二")]) + ] + ); + assert_eq!( + t.turns[2].input, + [ + msg(R::Assistant, vec![text("前一半后一半")]), + msg(R::User, vec![text("三")]) + ] + ); + assert_eq!(t.turns[3].input[0].role, R::Assistant); + } + + // ───────────────────────────────────────────────── 打码 + + /// 密钥在工具结果里、在一行的开头(JSON 里它前面是 `\n` 的转义),交出去之前都打了码; + /// 系统提示和回答里的也一样 + #[test] + fn secrets_come_out_masked_wherever_they_are() { + let mut d = Disk::new(); + let key = "sk-ant-api03-SECRETSECRETSECRET"; + let body = json!({"model": "m", "system": format!("备用的 key:{key}"), "messages": [ + user("读一下 .env"), + json!({"role": "assistant", "content": [{"type": "tool_use", "id": "t1", "name": "Read", + "input": {"file_path": ".env", "note": key}}]}), + json!({"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", + "content": format!("# 配置\n{key}\nGITHUB=ghp_bbbbbbbbbbbbbbbbbbbb")}]}) + ]}); + d.turn("/v1/messages", &body, &says(&format!("找到了 {key}"))); + let t = d.transcript(); + let wire = serde_json::to_string(&t).unwrap(); + assert!(!wire.contains("SECRETSECRET"), "{wire}"); + assert!(!wire.contains("bbbbbbbbbbbbbbbb"), "{wire}"); + assert!(wire.contains("sk-an…CRET"), "{wire}"); + let P::ToolResult { text: said, .. } = &t.turns[0].input[2].parts[0] else { + panic!("{:?}", t.turns[0].input) + }; + assert_eq!(said, "# 配置\nsk-an…CRET\nGITHUB=ghp_b…bbbb"); + } + + // ───────────────────────────────────────────────── 转换过格式的 + + /// 客户端说 Anthropic、上游说 Chat 或 Responses:请求按客户端的格式读,回答按上游的 + #[test] + fn a_translated_turn_reads_the_answer_in_the_upstream_format() { + let mut d = Disk::new(); + let translated = |to: &str| { + Some( + json!({"provider": "relay", "from": "anthropic", "to": to, "dropped": []}) + .to_string(), + ) + }; + let chat = sse(&[ + ( + "", + json!({"choices": [{"index": 0, "delta": {"content": "我来查"}}]}), + ), + ( + "", + json!({"choices": [{"index": 0, "delta": {"tool_calls": [{"index": 0, + "type": "function", "function": {"name": "Grep", "arguments": "{\"pattern\":\"TODO\"}"}}]}}]}), + ), + ( + "", + json!({"choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}]}), + ), + ]); + d.put( + "/v1/messages", + Some(anthropic(&[user("找 TODO")]).to_string().as_bytes()), + Some(&chat), + |r| r.translated = translated("openai-chat"), + ); + // 下一轮里客户端记下的调用号,是网关转换时编的那个 + let said = json!({"role": "assistant", "content": [{"type": "text", "text": "我来查"}, + {"type": "tool_use", "id": "call_gateway", "name": "Grep", "input": {"pattern": "TODO"}}]}); + let found = json!({"role": "user", "content": [{"type": "tool_result", "tool_use_id": "call_gateway", + "content": "src/a.rs:1: TODO"}]}); + let responses = sse(&[ + ( + "response.output_item.added", + json!({"type": "response.output_item.added", "output_index": 0, + "item": {"type": "message", "role": "assistant", "content": []}}), + ), + ( + "response.output_text.delta", + json!({"type": "response.output_text.delta", "output_index": 0, "content_index": 0, + "delta": "只有一处。"}), + ), + ( + "response.completed", + json!({"type": "response.completed", "response": {"usage": {"input_tokens": 1, "output_tokens": 1}}}), + ), + ]); + d.put( + "/v1/messages", + Some( + anthropic(&[user("找 TODO"), said, found]) + .to_string() + .as_bytes(), + ), + Some(&responses), + |r| r.translated = translated("openai-responses"), + ); + + let t = d.transcript(); + assert!(t.turns.iter().all(|x| x.gaps.is_empty() && !x.restart)); + assert_eq!( + t.turns[0].output, + [ + text("我来查"), + call("call_gateway", "Grep", r#"{"pattern":"TODO"}"#) + ] + ); + assert_eq!( + t.turns[1].input, + [msg( + R::Tool, + vec![result("call_gateway", "src/a.rs:1: TODO")] + )] + ); + assert_eq!(t.turns[1].output, [text("只有一处。")]); + } + + /// Codex 走 Anthropic 的上游:自由格式的 `apply_patch` 被包成了 `{"input": …}`,拆回原文 + #[test] + fn a_freeform_call_answered_by_another_format_is_unwrapped() { + let mut d = Disk::new(); + let patch = "*** Begin Patch\n*** End Patch"; + d.put( + "/v1/responses", + Some( + json!({"model": "claude-sonnet-4-5", "input": "改一下", + "tools": [{"type": "custom", "name": "apply_patch"}]}) + .to_string() + .as_bytes(), + ), + Some(&anthropic_stream(&[json!({"type": "tool_use", "id": "toolu_1", + "name": "apply_patch", "input": {"input": patch}})])), + |r| { + r.translated = Some( + json!({"provider": "anthropic", "from": "openai-responses", "to": "anthropic", "dropped": []}) + .to_string(), + ) + }, + ); + let t = d.transcript(); + assert_eq!(t.turns[0].input, [msg(R::User, vec![text("改一下")])]); + assert_eq!(t.turns[0].output, [call("toolu_1", "apply_patch", patch)]); + } + + /// Bedrock 的二进制帧在网关进门时转成了 SSE;整包的 Converse 也读得出来 + #[test] + fn a_bedrock_answer_is_read_streamed_or_whole() { + let mut d = Disk::new(); + let bedrock = || { + Some( + json!({"provider": "bedrock", "from": "anthropic", "to": "bedrock", "dropped": []}) + .to_string(), + ) + }; + let stream = sse(&[ + ("messageStart", json!({"role": "assistant"})), + ( + "contentBlockDelta", + json!({"contentBlockIndex": 0, "delta": {"reasoningContent": {"text": "想"}}}), + ), + ( + "contentBlockDelta", + json!({"contentBlockIndex": 0, "delta": {"reasoningContent": {"signature": "sig"}}}), + ), + ("contentBlockStop", json!({"contentBlockIndex": 0})), + ( + "contentBlockDelta", + json!({"contentBlockIndex": 1, "delta": {"text": "基岩"}}), + ), + ("contentBlockStop", json!({"contentBlockIndex": 1})), + ( + "contentBlockStart", + json!({"contentBlockIndex": 2, "start": {"toolUse": {"toolUseId": "t1", "name": "Bash"}}}), + ), + ( + "contentBlockDelta", + json!({"contentBlockIndex": 2, "delta": {"toolUse": {"input": "{\"command\":\"ls\"}"}}}), + ), + ("contentBlockStop", json!({"contentBlockIndex": 2})), + ("messageStop", json!({"stopReason": "tool_use"})), + ]); + d.put( + "/v1/messages", + Some(anthropic(&[user("一")]).to_string().as_bytes()), + Some(&stream), + |r| r.translated = bedrock(), + ); + let whole = json!({"output": {"message": {"role": "assistant", "content": [{"text": "整包"}]}}, + "stopReason": "end_turn"}); + d.put( + "/v1/messages", + Some(anthropic(&[user("另一段")]).to_string().as_bytes()), + Some(whole.to_string().as_bytes()), + |r| r.translated = bedrock(), + ); + let t = d.transcript(); + assert_eq!( + t.turns[0].output, + [ + thinking("想"), + text("基岩"), + call("t1", "Bash", r#"{"command":"ls"}"#) + ] + ); + assert_eq!(t.turns[1].output, [text("整包")]); + assert!(t.turns.iter().all(|x| x.gaps.is_empty())); + } + + /// 不带 `alt=sse` 的 Gemini 流是一个 JSON 数组;截断了的读到最后一个完整的元素 + #[test] + fn a_gemini_answer_written_as_a_json_array_is_read_element_by_element() { + let mut d = Disk::new(); + let path = "/v1beta/models/gemini-2.5-pro:streamGenerateContent"; + let body = json!({"contents": [{"role": "user", "parts": [{"text": "画一只猫"}]}]}); + let array = json!([ + {"candidates": [{"content": {"role": "model", "parts": [{"text": "画好了"}]}}]}, + {"candidates": [{"content": {"role": "model", "parts": [ + {"inlineData": {"mimeType": "image/png", "data": "QUJD".repeat(4)}}, + {"executableCode": {"language": "PYTHON", "code": "print(1)"}}]}}]}, + {"candidates": [{"content": {"role": "model", "parts": [{"text": "。"}]}}]} + ]) + .to_string(); + d.turn(path, &body, array.as_bytes()); + let id = d.put( + path, + Some(body.to_string().as_bytes()), + Some(&array.as_bytes()[..array.len() - 30]), + |_| {}, + ); + d.cut(id, Which::Response, array.len()); + + let t = d.transcript(); + let image = P::Image { + media_type: Some("image/png".into()), + bytes: Some(12), + }; + let code = P::Other { + label: "executableCode".into(), + }; + assert_eq!( + t.turns[0].output, + [text("画好了"), image.clone(), code.clone(), text("。")] + ); + assert!(t.turns[0].gaps.is_empty()); + assert_eq!(t.turns[1].output, [text("画好了"), image, code]); + assert_eq!(t.turns[1].gaps, [Gap::ResponseTruncated]); + } + + /// 和会话详情同样的请求、同样的顺序:本地应答的不在,同一刻的按请求号 + #[test] + fn the_turns_are_the_same_requests_in_the_same_order_as_the_session_detail() { + let mut d = Disk::new(); + d.turn("/v1/messages", &anthropic(&[user("一")]), &says("回一")); + d.put("/v1/messages", None, None, |r| { + r.local = true; + }); + d.put("/v1/messages", None, None, |r| r.at_ms = NOW); + d.put("/v1/messages", None, None, |r| r.at_ms = NOW); + let t = d.transcript(); + let want: Vec = + d.db.turns("s") + .unwrap() + .iter() + .map(|r| r.id.to_string()) + .collect(); + assert_eq!(want, ["3", "4", "1"]); + assert_eq!( + t.turns.iter().map(|x| x.id.clone()).collect::>(), + want + ); + } + + /// 别家没有对应物的块不丢:文件、音频、服务端工具的调用和结果、压缩过的前文,按类型名 + /// 记成 `other`,位置不变。图片只说类型和大小,给的是地址的不知道大小 + #[test] + fn blocks_without_a_counterpart_are_named_in_place() { + let mut d = Disk::new(); + let jpeg = format!("data:image/jpeg;base64,{}", "QUJD".repeat(5)); + d.turn( + "/v1/chat/completions", + &json!({"model": "m", "messages": [{"role": "user", "content": [ + {"type": "text", "text": "看图听音"}, + {"type": "image_url", "image_url": {"url": jpeg}}, + {"type": "image_url", "image_url": {"url": "https://example.com/a.png"}}, + {"type": "input_audio", "input_audio": {"data": "UklGRg==", "format": "wav"}}, + {"type": "file", "file": {"file_data": "data:application/pdf;base64,JVBERi0="}} + ]}]}), + br#"{"choices":[{"message":{"role":"assistant","content":"ok"}}]}"#, + ); + let t = d.transcript(); + assert_eq!( + t.turns[0].input, + [msg( + R::User, + vec![ + text("看图听音"), + P::Image { + media_type: Some("image/jpeg".into()), + bytes: Some(15) + }, + P::Image { + media_type: None, + bytes: None + }, + P::Other { + label: "input_audio".into() + }, + P::Other { + label: "file".into() + } + ] + )] + ); + let wire = serde_json::to_string(&t).unwrap(); + assert!(!wire.contains("QUJD") && !wire.contains("UklGRg") && !wire.contains("JVBERi0")); + + // Anthropic:网页搜索是服务端工具,调用和结果都是助手消息里的块;回答的流里也一样 + let mut d = Disk::new(); + let search = json!({"type": "server_tool_use", "id": "srvtoolu_1", "name": "web_search", + "input": {"query": "rust 2024"}}); + let found = json!({"type": "web_search_tool_result", "tool_use_id": "srvtoolu_1", + "content": [{"type": "web_search_result", "url": "https://x", "title": "x", "encrypted_content": "e"}]}); + d.turn( + "/v1/messages", + &anthropic(&[json!({"role": "user", "content": [ + {"type": "document", "source": {"type": "text", "media_type": "text/plain", "data": "合同全文"}}, + {"type": "text", "text": "查一下"} + ]})]), + &anthropic_stream(&[ + search.clone(), + found.clone(), + json!({"type": "text", "text": "查到了"}), + ]), + ); + let t = d.transcript(); + assert_eq!( + t.turns[0].input, + [msg( + R::User, + vec![ + P::Other { + label: "document".into() + }, + text("查一下") + ] + )] + ); + assert_eq!( + t.turns[0].output, + [ + P::Other { + label: "server_tool_use".into() + }, + P::Other { + label: "web_search_tool_result".into() + }, + text("查到了") + ] + ); + + // Responses:压缩过的前文像一条系统消息;引用服务端内容的项是 `other` + let mut d = Disk::new(); + d.turn( + "/v1/responses", + &json!({"model": "m", "input": [ + {"type": "compaction", "encrypted_content": "gAAAA"}, + {"type": "item_reference", "id": "msg_1"}, + {"role": "user", "content": "接着来"} + ]}), + br#"{"output":[]}"#, + ); + let t = d.transcript(); + assert_eq!( + t.turns[0].input, + [ + msg( + R::System, + vec![P::Other { + label: "compaction".into() + }] + ), + msg( + R::User, + vec![P::Other { + label: "item_reference".into() + }] + ), + msg(R::User, vec![text("接着来")]) + ] + ); + assert!(t.turns[0].output.is_empty() && t.turns[0].gaps.is_empty()); + } + + // ───────────────────────────────────────────────── 量一量 + + /// 读一次几百轮的会话要多久:照 Claude Code 的样子造一段 300 轮的对话,每一轮的请求带着 + /// 整段历史(平均 1 MB 上下,工具结果每条 2.5 KB 上下),流式的回答里有推理、文字和工具调用。 + /// + /// 默认不跑:要写三百多 MB 的正文。发布构建下跑: + /// `cargo test --release -p tw-store transcript_cost -- --ignored --nocapture` + #[test] + #[ignore] + fn transcript_cost() { + let mut d = Disk::new(); + let system = "You are Claude Code. ".repeat(1000); + let tools: Vec = (0..40) + .map(|i| { + json!({"name": format!("Tool{i}"), "description": "x".repeat(600), + "input_schema": {"type": "object", "properties": {"path": {"type": "string"}}}}) + }) + .collect(); + let file = "fn main() { println!(\"hello\"); }\n".repeat(75); + let pair = |k: usize| { + [ + json!({"role": "assistant", "content": [ + {"type": "thinking", "thinking": format!("第 {k} 步先读一下"), "signature": "s".repeat(300)}, + {"type": "text", "text": format!("第 {k} 步我来读 src/{k}.rs")}, + {"type": "tool_use", "id": format!("toolu_{k}"), "name": "Read", + "input": {"file_path": format!("src/{k}.rs")}}]}), + json!({"role": "user", "content": [{"type": "tool_result", "tool_use_id": format!("toolu_{k}"), + "content": format!("{file}// 第 {k} 个文件")}]}), + ] + }; + // 开头已经聊了两百轮 + let mut messages = vec![json!({"role": "user", "content": "把这个仓库的 bug 都修了"})]; + for k in 0..200 { + messages.extend(pair(k)); + } + let mut bytes = 0usize; + for turn in 0..300 { + let mut sent = messages.clone(); + if let Some(last) = sent.last_mut() { + *last = with_cache(last.clone()); + } + let body = json!({"model": "claude-sonnet-4-5", "system": system, "tools": tools, + "max_tokens": 32000, "stream": true, "messages": sent}) + .to_string(); + let k = 200 + turn; + let answer = anthropic_stream(&[ + json!({"type": "thinking", "thinking": format!("第 {k} 步先读一下"), "signature": "s".repeat(300)}), + json!({"type": "text", "text": format!("第 {k} 步我来读 src/{k}.rs")}), + json!({"type": "tool_use", "id": format!("toolu_{k}"), "name": "Read", + "input": {"file_path": format!("src/{k}.rs")}}), + ]); + bytes += body.len() + answer.len(); + d.put("/v1/messages", Some(body.as_bytes()), Some(&answer), |_| {}); + messages.extend(pair(k)); + } + let rows = d.db.session_requests("s").unwrap(); + eprintln!( + "{} requests, {} MB of bodies ({} KB per request on average)", + rows.len(), + bytes / 1_000_000, + bytes / rows.len() / 1000 + ); + for _ in 0..3 { + let t0 = std::time::Instant::now(); + let t = build("s", &rows, &d.blobs); + let took = t0.elapsed(); + let wire = serde_json::to_string(&t).unwrap(); + eprintln!( + "built in {took:?} ({:?} per request), {} KB of JSON", + took / rows.len() as u32, + wire.len() / 1000 + ); + assert!( + t.turns + .iter() + .skip(1) + .all(|x| !x.restart && x.input.len() == 1) + ); + assert!( + t.turns + .iter() + .all(|x| x.gaps.is_empty() && x.output.len() == 3) + ); + } + } +} diff --git a/crates/tw-store/src/transcript/read.rs b/crates/tw-store/src/transcript/read.rs new file mode 100644 index 00000000..5f88faf4 --- /dev/null +++ b/crates/tw-store/src/transcript/read.rs @@ -0,0 +1,786 @@ +//! 四种客户端格式里的消息怎么读成对话里的一块一块。 +//! +//! **不经过 tw-dialect 的中间表示。**中间表示只装四种格式之间对应得上的东西:对话中途的 +//! 系统消息并进了系统提示,只装着工具结果的消息和用户说的话是同一个角色,服务端工具的 +//! 调用和结果、文件、音频解码时直接丢掉 —— 转换格式时那样是对的,可对话记录要的恰恰是 +//! 这些:谁在哪一处说了什么,哪里有一块转不过去的东西。所以这里照客户端自己的格式读 +//! JSON,只读消息这一层;取哪个字段和 tw-dialect 的解码器保持一致。 +//! +//! 整包的回答和请求里的消息是同一个形状(Anthropic 的 `content`、Chat 的 `message`、 +//! Responses 的 `output`、Gemini 的 `content`),也按这里读。 + +use std::borrow::Cow; + +use serde_json::Value; +use tw_dialect::ir::Dialect; + +/// 一条消息是谁说的。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum Role { + User, + Assistant, + /// 只装着工具结果 + Tool, + /// 对话中途的 system、developer 消息 + System, +} + +/// 读出来的一块,借着解析好的 JSON。 +/// +/// **已经是规整过的样子**:缓存断点和推理签名不在里面,键的顺序也无所谓了 —— 前后两个 +/// 请求比对时,这些本来就不该算(Claude Code 每一轮都把缓存断点挪到最后一条消息上)。 +#[derive(Debug, Clone)] +pub(super) enum Piece<'a> { + Text(Cow<'a, str>), + /// 推理。只有签名、被打码的,是空串 + Thinking(Cow<'a, str>), + ToolCall { + id: Cow<'a, str>, + name: Cow<'a, str>, + input: Input<'a>, + }, + ToolResult { + call_id: Cow<'a, str>, + text: Cow<'a, str>, + is_error: bool, + }, + /// `data` 只进指纹,**从不交出去** + Image { + media_type: Option<&'a str>, + bytes: Option, + data: Option<&'a str>, + }, + /// 别的块,类型名原样 + Other(&'a str), +} + +/// 工具调用的参数。 +#[derive(Debug, Clone)] +pub(super) enum Input<'a> { + /// 函数工具的参数,模型写出来的 JSON 文本。空的当 `{}` + Args(&'a str), + /// 自由格式工具的原文(Codex 的 `apply_patch`),一个字不改 + Raw(&'a str), + /// 已经是 JSON 的参数(Anthropic、Gemini) + Json(&'a Value), +} + +impl Input<'_> { + /// 交出去的样子:JSON 文本,自由格式的是原文 + pub(super) fn text(&self) -> String { + match self { + Input::Args(s) if s.trim().is_empty() => "{}".into(), + Input::Args(s) | Input::Raw(s) => s.to_string(), + Input::Json(v) => v.to_string(), + } + } +} + +/// 一条消息(Responses 里是一个输入项)读出来的样子。 +#[derive(Debug, Clone)] +pub(super) struct Item<'a> { + pub(super) role: Role, + pub(super) pieces: Vec>, +} + +/// 一个请求体里对话记录要的东西。 +#[derive(Debug, Default)] +pub(super) struct Body<'a> { + /// 系统提示,按出现的先后 + pub(super) system: Vec>, + pub(super) items: Vec>, + /// 定义成自由格式的工具。别的格式的上游会把它们的原文包进 `{"input": …}` + pub(super) freeform: Vec, +} + +/// 按客户端的格式读一个请求体。不是对象、没有对话的读出来是空的,不算读不懂。 +pub(super) fn body(dialect: Dialect, v: &Value) -> Body<'_> { + match dialect { + Dialect::Anthropic => anthropic(v), + Dialect::Chat => chat(v), + Dialect::Responses => responses(v), + Dialect::Gemini => gemini(v), + // 客户端不说 Converse(见 `tw_api::Dialect::Bedrock`) + Dialect::Bedrock => Body::default(), + } +} + +// ───────────────────────────────────────────────────────── 小工具 + +fn str_of<'a>(v: &'a Value, key: &str) -> Option<&'a str> { + v.get(key).and_then(Value::as_str) +} + +fn arr_of<'a>(v: &'a Value, key: &str) -> &'a [Value] { + v.get(key) + .and_then(Value::as_array) + .map(Vec::as_slice) + .unwrap_or(&[]) +} + +/// 一个 `string | [{type: "text", text}]` 形状的内容里的字,几段之间换行。 +fn text_of(v: &Value) -> Cow<'_, str> { + match v { + Value::String(s) => Cow::Borrowed(s), + Value::Array(parts) => { + let texts: Vec<&str> = parts.iter().filter_map(|p| str_of(p, "text")).collect(); + match texts.as_slice() { + [] => Cow::Borrowed(""), + [one] => Cow::Borrowed(one), + many => Cow::Owned(many.join("\n")), + } + } + _ => Cow::Borrowed(""), + } +} + +/// 块的类型名。没写的叫 `unknown` +fn kind_of(v: &Value) -> &str { + str_of(v, "type").unwrap_or("unknown") +} + +/// base64 解出来有多少字节 +fn base64_len(data: &str) -> u64 { + let d = data.trim_end(); + let pad = d.bytes().rev().take_while(|b| *b == b'=').count() as u64; + (d.len() as u64 * 3 / 4).saturating_sub(pad) +} + +/// 一张以 URI 给的图片:`data:` URI 说得出类型和大小,网址说不出 +fn image_uri(uri: &str) -> Piece<'_> { + if let Some(rest) = uri.strip_prefix("data:") + && let Some((head, data)) = rest.split_once(',') + { + let (mime, base64) = match head.strip_suffix(";base64") { + Some(m) => (m, true), + None => (head.split(';').next().unwrap_or_default(), false), + }; + return Piece::Image { + media_type: (!mime.is_empty()).then_some(mime), + bytes: base64.then(|| base64_len(data)), + data: Some(data), + }; + } + Piece::Image { + media_type: None, + bytes: None, + data: Some(uri), + } +} + +/// 文字,空的不算一块 +fn text_piece<'a>(t: Cow<'a, str>, out: &mut Vec>) { + if !t.is_empty() { + out.push(Piece::Text(t)); + } +} + +// ───────────────────────────────────────────────────────── Anthropic Messages + +fn anthropic(v: &Value) -> Body<'_> { + let mut system = Vec::new(); + match v.get("system") { + Some(Value::String(s)) => system.push(Cow::Borrowed(s.as_str())), + Some(Value::Array(blocks)) => system.extend( + blocks + .iter() + .filter_map(|b| str_of(b, "text")) + .map(Cow::Borrowed), + ), + _ => {} + } + Body { + system, + items: arr_of(v, "messages") + .iter() + .map(anthropic_message) + .collect(), + freeform: Vec::new(), + } +} + +fn anthropic_message(m: &Value) -> Item<'_> { + let mut pieces = Vec::new(); + let mut only_results = false; + match m.get("content") { + Some(Value::String(s)) => text_piece(Cow::Borrowed(s), &mut pieces), + Some(Value::Array(blocks)) => { + only_results = !blocks.is_empty() + && blocks + .iter() + .all(|b| str_of(b, "type") == Some("tool_result")); + anthropic_blocks(blocks, &mut pieces); + } + _ => {} + } + let role = match str_of(m, "role") { + Some("assistant") => Role::Assistant, + // DeepSeek Harness 在消息里放的 system 角色 + Some("system") => Role::System, + _ if only_results => Role::Tool, + _ => Role::User, + }; + Item { role, pieces } +} + +/// 一串内容块:消息的 `content`,也是整包回答的 `content`。 +pub(super) fn anthropic_blocks<'a>(blocks: &'a [Value], out: &mut Vec>) { + for b in blocks { + match kind_of(b) { + "text" => text_piece(Cow::Borrowed(str_of(b, "text").unwrap_or_default()), out), + "thinking" => out.push(Piece::Thinking(Cow::Borrowed( + str_of(b, "thinking").unwrap_or_default(), + ))), + "redacted_thinking" => out.push(Piece::Thinking(Cow::Borrowed(""))), + "tool_use" => out.push(Piece::ToolCall { + id: Cow::Borrowed(str_of(b, "id").unwrap_or_default()), + name: Cow::Borrowed(str_of(b, "name").unwrap_or_default()), + input: b.get("input").map_or(Input::Args(""), Input::Json), + }), + "tool_result" => anthropic_result(b, out), + "image" => out.push(anthropic_image(b)), + // document、search_result,服务端工具的 server_tool_use、web_search_tool_result…… + other => out.push(Piece::Other(other)), + } + } +} + +fn anthropic_image(b: &Value) -> Piece<'_> { + let src = b.get("source").unwrap_or(&Value::Null); + match str_of(src, "type") { + Some("base64") => { + let data = str_of(src, "data").unwrap_or_default(); + Piece::Image { + media_type: str_of(src, "media_type"), + bytes: Some(base64_len(data)), + data: Some(data), + } + } + Some("url") => Piece::Image { + media_type: None, + bytes: None, + data: str_of(src, "url"), + }, + // Files API 里的文件:只有一个文件号 + _ => Piece::Image { + media_type: None, + bytes: None, + data: str_of(src, "file_id"), + }, + } +} + +/// 工具结果:里面的字连起来成一块,图片和别的块跟在它后面。 +fn anthropic_result<'a>(b: &'a Value, out: &mut Vec>) { + let mut extra = Vec::new(); + let text = match b.get("content") { + Some(Value::String(s)) => Cow::Borrowed(s.as_str()), + Some(Value::Array(items)) => { + let mut texts = Vec::new(); + for i in items { + match kind_of(i) { + "text" => texts.push(str_of(i, "text").unwrap_or_default()), + "image" => extra.push(anthropic_image(i)), + other => extra.push(Piece::Other(other)), + } + } + match texts.as_slice() { + [one] => Cow::Borrowed(*one), + many => Cow::Owned(many.join("\n")), + } + } + _ => Cow::Borrowed(""), + }; + out.push(Piece::ToolResult { + call_id: Cow::Borrowed(str_of(b, "tool_use_id").unwrap_or_default()), + text, + is_error: b.get("is_error").and_then(Value::as_bool).unwrap_or(false), + }); + out.extend(extra); +} + +// ───────────────────────────────────────────────────────── OpenAI Chat Completions + +fn chat(v: &Value) -> Body<'_> { + let mut system = Vec::new(); + let mut items = Vec::new(); + // 开头连着的 system、developer 消息就是系统提示;对话中途的照原位置留着 + let mut leading = true; + for m in arr_of(v, "messages") { + let role = str_of(m, "role").unwrap_or_default(); + if leading && matches!(role, "system" | "developer") { + system.push(text_of(m.get("content").unwrap_or(&Value::Null))); + continue; + } + leading = false; + items.push(chat_message(m)); + } + Body { + system, + items, + freeform: arr_of(v, "tools") + .iter() + .filter(|t| str_of(t, "type") == Some("custom")) + .filter_map(|t| t.get("custom").and_then(|c| str_of(c, "name"))) + .map(str::to_string) + .collect(), + } +} + +fn chat_message(m: &Value) -> Item<'_> { + let content = m.get("content").unwrap_or(&Value::Null); + match str_of(m, "role").unwrap_or_default() { + "system" | "developer" => { + let mut pieces = Vec::new(); + text_piece(text_of(content), &mut pieces); + Item { + role: Role::System, + pieces, + } + } + "assistant" => Item { + role: Role::Assistant, + pieces: chat_assistant(m), + }, + "tool" => Item { + role: Role::Tool, + pieces: vec![Piece::ToolResult { + call_id: Cow::Borrowed(str_of(m, "tool_call_id").unwrap_or_default()), + text: text_of(content), + is_error: false, + }], + }, + // 旧的函数调用:结果按函数名认 + "function" => Item { + role: Role::Tool, + pieces: vec![Piece::ToolResult { + call_id: Cow::Borrowed(str_of(m, "name").unwrap_or_default()), + text: text_of(content), + is_error: false, + }], + }, + _ => { + let mut pieces = Vec::new(); + match content { + Value::String(s) => text_piece(Cow::Borrowed(s), &mut pieces), + Value::Array(parts) => { + for p in parts { + match kind_of(p) { + "text" => text_piece( + Cow::Borrowed(str_of(p, "text").unwrap_or_default()), + &mut pieces, + ), + "image_url" => { + let url = p + .get("image_url") + .and_then(|i| i.as_str().or_else(|| str_of(i, "url"))); + pieces.push(url.map_or( + Piece::Image { + media_type: None, + bytes: None, + data: None, + }, + image_uri, + )); + } + // input_audio、file…… + other => pieces.push(Piece::Other(other)), + } + } + } + _ => {} + } + Item { + role: Role::User, + pieces, + } + } + } +} + +/// 助手消息:请求里的历史,也是整包回答的 `choices[0].message`。 +pub(super) fn chat_assistant(m: &Value) -> Vec> { + let mut pieces = Vec::new(); + // DeepSeek、Kimi、GLM 这些的推理字段(OpenRouter 叫 `reasoning`) + if let Some(t) = str_of(m, "reasoning_content") + .or_else(|| str_of(m, "reasoning")) + .filter(|t| !t.is_empty()) + { + pieces.push(Piece::Thinking(Cow::Borrowed(t))); + } + match m.get("content") { + Some(Value::String(s)) => text_piece(Cow::Borrowed(s), &mut pieces), + Some(Value::Array(parts)) => { + for p in parts { + match str_of(p, "text").or_else(|| str_of(p, "refusal")) { + Some(t) => text_piece(Cow::Borrowed(t), &mut pieces), + None => pieces.push(Piece::Other(kind_of(p))), + } + } + } + _ => {} + } + if let Some(r) = str_of(m, "refusal") { + text_piece(Cow::Borrowed(r), &mut pieces); + } + for c in arr_of(m, "tool_calls") { + let id = Cow::Borrowed(str_of(c, "id").unwrap_or_default()); + match str_of(c, "type") { + Some("custom") => { + let x = c.get("custom").unwrap_or(&Value::Null); + pieces.push(Piece::ToolCall { + id, + name: Cow::Borrowed(str_of(x, "name").unwrap_or_default()), + input: Input::Raw(str_of(x, "input").unwrap_or_default()), + }); + } + _ => { + let f = c.get("function").unwrap_or(&Value::Null); + pieces.push(Piece::ToolCall { + id, + name: Cow::Borrowed(str_of(f, "name").unwrap_or_default()), + input: Input::Args(str_of(f, "arguments").unwrap_or_default()), + }); + } + } + } + // 旧的函数调用:没有调用号 + if let Some(f) = m.get("function_call") { + pieces.push(Piece::ToolCall { + id: Cow::Borrowed(""), + name: Cow::Borrowed(str_of(f, "name").unwrap_or_default()), + input: Input::Args(str_of(f, "arguments").unwrap_or_default()), + }); + } + if m.get("audio").is_some_and(|a| !a.is_null()) { + pieces.push(Piece::Other("audio")); + } + pieces +} + +// ───────────────────────────────────────────────────────── OpenAI Responses + +fn responses(v: &Value) -> Body<'_> { + let mut system = Vec::new(); + match v.get("instructions") { + Some(Value::String(s)) => system.push(Cow::Borrowed(s.as_str())), + Some(a @ Value::Array(_)) => system.push(text_of(a)), + _ => {} + } + let mut items = Vec::new(); + match v.get("input") { + Some(Value::String(s)) => { + let mut pieces = Vec::new(); + text_piece(Cow::Borrowed(s), &mut pieces); + items.push(Item { + role: Role::User, + pieces, + }); + } + Some(Value::Array(input)) => { + // 开头连着的 system、developer 消息算系统提示,和 Chat 一样 + let mut leading = true; + for it in input { + if leading + && str_of(it, "type").unwrap_or("message") == "message" + && matches!(str_of(it, "role"), Some("system" | "developer")) + { + system.push(text_of(it.get("content").unwrap_or(&Value::Null))); + continue; + } + leading = false; + items.push(responses_item(it)); + } + } + _ => {} + } + let mut freeform = Vec::new(); + for t in arr_of(v, "tools") { + match str_of(t, "type") { + Some("custom") => freeform.extend(str_of(t, "name").map(str::to_string)), + Some("namespace") => { + let ns = str_of(t, "name"); + freeform.extend( + arr_of(t, "tools") + .iter() + .filter(|x| str_of(x, "type") == Some("custom")) + .filter_map(|x| str_of(x, "name")) + .map(|n| flat_name(ns, n).into_owned()), + ); + } + _ => {} + } + } + Body { + system, + items, + freeform, + } +} + +/// namespace 里的工具展开成 `namespace__名字`,和转换给别家时的名字一样 +fn flat_name<'a>(namespace: Option<&str>, name: &'a str) -> Cow<'a, str> { + match namespace { + Some(ns) if !ns.is_empty() => Cow::Owned(format!("{ns}__{name}")), + _ => Cow::Borrowed(name), + } +} + +/// 一个输入项:请求里的历史,也是整包回答的 `output` 里的一项。 +pub(super) fn responses_item(it: &Value) -> Item<'_> { + let kind = str_of(it, "type").unwrap_or("message"); + let one = |role, piece| Item { + role, + pieces: vec![piece], + }; + match kind { + "message" => { + let role = match str_of(it, "role") { + Some("assistant") => Role::Assistant, + Some("system" | "developer") => Role::System, + _ => Role::User, + }; + let mut pieces = Vec::new(); + match it.get("content") { + Some(Value::String(s)) => text_piece(Cow::Borrowed(s), &mut pieces), + Some(Value::Array(parts)) => responses_parts(parts, &mut pieces), + _ => {} + } + Item { role, pieces } + } + "reasoning" => { + let texts = |key: &str| -> Vec<&str> { + arr_of(it, key) + .iter() + .filter_map(|x| str_of(x, "text")) + .collect() + }; + // 推理原文优先,没有就是摘要;几段之间空一行(和 tw-dialect 一样) + let mut t = texts("content"); + if t.is_empty() { + t = texts("summary"); + } + let text = match t.as_slice() { + [] => Cow::Borrowed(""), + [one] => Cow::Borrowed(*one), + many => Cow::Owned(many.join("\n\n")), + }; + one(Role::Assistant, Piece::Thinking(text)) + } + "function_call" | "custom_tool_call" => { + let name = flat_name( + str_of(it, "namespace"), + str_of(it, "name").unwrap_or_default(), + ); + let input = if kind == "function_call" { + Input::Args(str_of(it, "arguments").unwrap_or_default()) + } else { + Input::Raw(str_of(it, "input").unwrap_or_default()) + }; + one( + Role::Assistant, + Piece::ToolCall { + id: Cow::Borrowed(str_of(it, "call_id").unwrap_or_default()), + name, + input, + }, + ) + } + "function_call_output" | "custom_tool_call_output" | "local_shell_call_output" => { + let mut extra = Vec::new(); + let text = match it.get("output") { + Some(Value::String(s)) => Cow::Borrowed(s.as_str()), + Some(Value::Array(parts)) => { + let mut texts = Vec::new(); + for p in parts { + match kind_of(p) { + "input_text" | "output_text" => { + texts.push(str_of(p, "text").unwrap_or_default()) + } + "input_image" => extra.push(responses_image(p)), + other => extra.push(Piece::Other(other)), + } + } + match texts.as_slice() { + [one] => Cow::Borrowed(*one), + many => Cow::Owned(many.join("\n")), + } + } + _ => Cow::Borrowed(""), + }; + let mut pieces = vec![Piece::ToolResult { + call_id: Cow::Borrowed(str_of(it, "call_id").unwrap_or_default()), + text, + is_error: false, + }]; + pieces.extend(extra); + Item { + role: Role::Tool, + pieces, + } + } + // 压缩过的前文:只有 OpenAI 读得懂的一段密文,在对话里的位置像一条系统消息 + "compaction" => one(Role::System, Piece::Other(kind)), + // 别的工具结果(computer_call_output……) + k if k.ends_with("_output") => one(Role::Tool, Piece::Other(k)), + // 托管工具的调用(web_search_call、image_generation_call、mcp_call、local_shell_call……) + k if k.ends_with("_call") || matches!(k, "mcp_list_tools" | "mcp_approval_request") => { + one(Role::Assistant, Piece::Other(k)) + } + // item_reference、mcp_approval_response…… + other => one(Role::User, Piece::Other(other)), + } +} + +fn responses_parts<'a>(parts: &'a [Value], out: &mut Vec>) { + for p in parts { + match kind_of(p) { + "input_text" | "output_text" => { + text_piece(Cow::Borrowed(str_of(p, "text").unwrap_or_default()), out) + } + "refusal" => text_piece(Cow::Borrowed(str_of(p, "refusal").unwrap_or_default()), out), + "input_image" => out.push(responses_image(p)), + // input_file、input_audio…… + other => out.push(Piece::Other(other)), + } + } +} + +fn responses_image(p: &Value) -> Piece<'_> { + match str_of(p, "image_url") { + Some(u) => image_uri(u), + None => Piece::Image { + media_type: None, + bytes: None, + data: str_of(p, "file_id"), + }, + } +} + +// ───────────────────────────────────────────────────────── Gemini + +/// 按驼峰名取字段,取不到再试下划线写法:Gemini 的 REST 接口两种都收 +fn field<'a>(v: &'a Value, camel: &str) -> Option<&'a Value> { + v.get(camel).or_else(|| { + let mut snake = String::with_capacity(camel.len() + 4); + for c in camel.chars() { + if c.is_ascii_uppercase() { + snake.push('_'); + snake.push(c.to_ascii_lowercase()); + } else { + snake.push(c); + } + } + v.get(snake) + }) +} + +fn fstr<'a>(v: &'a Value, camel: &str) -> Option<&'a str> { + field(v, camel).and_then(Value::as_str) +} + +fn gemini(v: &Value) -> Body<'_> { + let mut system = Vec::new(); + match field(v, "systemInstruction") { + Some(Value::String(s)) => system.push(Cow::Borrowed(s.as_str())), + Some(sys) => system.push(text_of(sys.get("parts").unwrap_or(&Value::Null))), + None => {} + } + Body { + system, + items: arr_of(v, "contents").iter().map(gemini_content).collect(), + freeform: Vec::new(), + } +} + +fn gemini_content(c: &Value) -> Item<'_> { + let parts = arr_of(c, "parts"); + let mut pieces = Vec::new(); + gemini_parts(parts, &mut pieces); + let role = match str_of(c, "role") { + Some("model") => Role::Assistant, + Some("function") => Role::Tool, + Some("system") => Role::System, + _ if !parts.is_empty() && parts.iter().all(|p| field(p, "functionResponse").is_some()) => { + Role::Tool + } + _ => Role::User, + }; + Item { role, pieces } +} + +/// 一串 part:请求里的一条消息,也是回答里候选的 `content.parts`。 +/// +/// 没有调用号的函数调用和结果按函数名对上(Gemini 自己不要求调用号)。 +pub(super) fn gemini_parts<'a>(parts: &'a [Value], out: &mut Vec>) { + for p in parts { + if let Some(t) = fstr(p, "text") { + if p.get("thought").and_then(Value::as_bool) == Some(true) { + out.push(Piece::Thinking(Cow::Borrowed(t))); + } else { + text_piece(Cow::Borrowed(t), out); + } + } else if let Some(blob) = field(p, "inlineData") { + let mime = fstr(blob, "mimeType").unwrap_or_default(); + let data = fstr(blob, "data").unwrap_or_default(); + out.push(if mime.starts_with("image/") { + Piece::Image { + media_type: Some(mime), + bytes: Some(base64_len(data)), + data: Some(data), + } + } else { + Piece::Other("inlineData") + }); + } else if let Some(file) = field(p, "fileData") { + let mime = fstr(file, "mimeType").unwrap_or_default(); + out.push(if mime.starts_with("image/") { + Piece::Image { + media_type: Some(mime), + bytes: None, + data: fstr(file, "fileUri"), + } + } else { + Piece::Other("fileData") + }); + } else if let Some(call) = field(p, "functionCall") { + let name = fstr(call, "name").unwrap_or_default(); + out.push(Piece::ToolCall { + id: Cow::Borrowed(fstr(call, "id").unwrap_or(name)), + name: Cow::Borrowed(name), + input: call.get("args").map_or(Input::Args(""), Input::Json), + }); + } else if let Some(resp) = field(p, "functionResponse") { + let name = fstr(resp, "name").unwrap_or_default(); + let body = resp.get("response").unwrap_or(&Value::Null); + out.push(Piece::ToolResult { + call_id: Cow::Borrowed(fstr(resp, "id").unwrap_or(name)), + text: gemini_response_text(body), + is_error: body.get("error").is_some() && body.get("output").is_none(), + }); + } else if field(p, "executableCode").is_some() { + out.push(Piece::Other("executableCode")); + } else if field(p, "codeExecutionResult").is_some() { + out.push(Piece::Other("codeExecutionResult")); + } + // 只带着推理签名的空块、视频片段的说明这些:没有可看的 + } +} + +/// 函数结果写成字:只有一项 `output`(或 `result`、`content`、`error`)且是字符串的取那个 +/// 字符串,别的写成 JSON。和 tw-dialect 转给别家时的写法一样 +fn gemini_response_text(v: &Value) -> Cow<'_, str> { + if let Some(o) = v.as_object() + && o.len() == 1 + && let Some(s) = ["output", "result", "content", "error"] + .iter() + .find_map(|k| o.get(*k).and_then(Value::as_str)) + { + return Cow::Borrowed(s); + } + match v { + Value::String(s) => Cow::Borrowed(s), + Value::Null => Cow::Borrowed(""), + other => Cow::Owned(other.to_string()), + } +} diff --git a/scripts/smoke.sh b/scripts/smoke.sh index 66b48729..36e59999 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -524,6 +524,37 @@ else bad "按密钥里的字找到了东西($C)" "$(head -c 400 "$TMP/out")" fi +# 会话读成一段对话。**每一次会话都读得出来**,和会话详情一轮对一轮,密钥打了码。数据面 +# 那一节发过的请求都在里面:整包的、流式的、被切断的、中途走掉的、转去 Bedrock 的 —— +# Bedrock 的二进制帧在网关进门时转成 SSE 存下来,这里要从存下的那一份里读回那句话 +SIDS=$(ctl /sessions | python3 -c 'import json,sys;print(" ".join(s["id"] for s in json.load(sys.stdin)))') +TURNS=0; WRONG=""; ALL="" +for SID in $SIDS; do + C=$(get "/sessions/$SID/transcript") + cp "$TMP/out" "$TMP/transcript.json" + ctl "/sessions/$SID" > "$TMP/detail.json" + GOT=$(python3 -c 'import json, sys +raw = open(sys.argv[1]).read() +t, d = json.loads(raw), json.load(open(sys.argv[2])) +same = [x["id"] for x in t["turns"]] == [str(x["id"]) for x in d["turns"]] +print(len(t["turns"]) if same and "SMOKEKEYAAAA" not in raw else raw[:400])' \ + "$TMP/transcript.json" "$TMP/detail.json" 2>&1) + if [ "$C" = "200" ] && [[ "$GOT" =~ ^[0-9]+$ ]]; then + TURNS=$((TURNS + GOT)); ALL="$ALL$(cat "$TMP/transcript.json")" + else + WRONG="$WRONG $SID($C):$GOT" + fi +done +if [ -z "$SIDS" ]; then + bad "一次会话都没有,读不了对话记录" +elif [ -n "$WRONG" ]; then + bad "GET /sessions/{id}/transcript 不对" "$WRONG" +elif ! grep -q '"text":"bedrock-stream"' <<<"$ALL"; then + bad "对话记录里没读出 Bedrock 流式回答的那句话" "$(head -c 600 <<<"$ALL")" +else + ok "GET /sessions/{id}/transcript:$(wc -w <<<"$SIDS" | tr -d ' ') 次会话、$TURNS 轮都读得出来,和会话详情一轮对一轮,密钥打了码" +fi + # ---------------------------------------------------------------- 诊断包 step "诊断包不带密钥出门" get /diagnostics >/dev/null