Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions crates/tw-api/src/ep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ endpoints! {
Fixture: GET "/request/{id}/fixture" [id], () => String, text;
Sessions: GET "/sessions", api::ListQuery => Vec<api::SessionView>;
SessionDetail: GET "/sessions/{id}" [id], () => api::SessionDetail;
/// 一次会话读成一段对话:每一轮新说的话、回答、工具调用和结果(已脱敏)
SessionTranscript: GET "/sessions/{id}/transcript" [id], () => api::Transcript;

// ─────────────────────────────────────────────── 测速、回放、试路由
SpeedQuote: POST "/speed/quote", api::SpeedRunRequest => api::SpeedQuote;
Expand Down
123 changes: 122 additions & 1 deletion crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))]
Expand Down Expand Up @@ -4026,6 +4030,123 @@ pub struct SessionDetail {
pub turns: Vec<TurnView>,
}

/// 一次会话读成一段对话(`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<String>,
/// 和 [`SessionDetail::turns`] 同样的请求,同样的顺序
pub turns: Vec<TranscriptTurn>,
}

/// 对话里的一轮,就是会话里的一个请求。
///
/// 客户端每一轮都把整段历史发上来:请求 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<String>,
/// 这个请求里新的消息。上一轮的回答没有完整读出来时(那一轮的 `gaps` 里有 `response_*`),
/// 客户端记下的那条助手消息也在这里:它是那一轮说过什么的记录
pub input: Vec<TranscriptMessage>,
/// 回答,从存下来的响应里读出来的。失败的请求(上游回了错误)没有回答,也不算缺
pub output: Vec<TranscriptPart>,
/// 这一轮哪些地方读不出来
pub gaps: Vec<TranscriptGap>,
}

/// 请求里的一条消息。
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct TranscriptMessage {
pub role: TranscriptRole,
pub parts: Vec<TranscriptPart>,
}

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<String>,
bytes: Option<u64>,
},
/// 别的块:文件、音频、服务端工具的调用和结果……`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",
}
}

// ---------------------------------------------------------------- 请求重放

/// 把存下来的那条请求,原样发给另一个上游。
Expand Down
52 changes: 52 additions & 0 deletions crates/tw-api/src/ts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<TranscriptTurn>",
] {
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<TranscriptMessage>",
"output: Array<TranscriptPart>",
"gaps: Array<TranscriptGap>",
] {
assert!(turn.contains(field), "{field}: {turn}");
}
assert_eq!(
decl_of(&ts, "TranscriptMessage"),
"export type TranscriptMessage = { role: TranscriptRole, parts: Array<TranscriptPart>, }"
);
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();
Expand Down
40 changes: 34 additions & 6 deletions crates/tw-control/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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<ControlState>,
axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Json<tw_api::Transcript>, 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}")]
Expand Down
Loading
Loading