返回 CodeWhale
session.rs
根目录 / crates / engine / src / rlm / session.rs
1 //! Persistent RLM session state for the v0.8.33 head/hands tool surface.
2
3 use std::collections::HashMap;
4 use std::path::{Path, PathBuf};
5 use std::sync::Arc;
6 use std::time::{Duration, Instant};
7
8 use serde::{Deserialize, Serialize};
9 use serde_json::{Value, json};
10 use tokio::sync::Mutex;
11 use uuid::Uuid;
12
13 use codewhale_models::{ContentBlock, Message, SystemPrompt};
14 use codewhale_repl::PythonRuntime;
15
16 pub type SharedRlmSessionStore = Arc<Mutex<HashMap<String, Arc<Mutex<RlmSession>>>>>;
17
18 #[must_use]
19 pub fn new_shared_rlm_session_store() -> SharedRlmSessionStore {
20 Arc::new(Mutex::new(HashMap::new()))
21 }
22
23 #[derive(Debug)]
24 pub struct RlmSession {
25 pub name: String,
26 pub id: String,
27 pub kernel: Option<PythonRuntime>,
28 pub context_meta: ContextMeta,
29 pub config: RlmSessionConfig,
30 pub rpc_count: u32,
31 pub total_duration: Duration,
32 pub peak_var_count: usize,
33 pub final_count: usize,
34 pub created_at: Instant,
35 pub last_used_at: Instant,
36 pub sandbox_policy: Option<codewhale_sandbox::SandboxPolicy>,
37 }
38
39 impl RlmSession {
40 #[must_use]
41 pub fn new(
42 name: String,
43 kernel: PythonRuntime,
44 context_meta: ContextMeta,
45 sandbox_policy: Option<codewhale_sandbox::SandboxPolicy>,
46 ) -> Self {
47 let now = Instant::now();
48 Self {
49 name,
50 id: format!("rlm:{}", Uuid::new_v4().simple()),
51 kernel: Some(kernel),
52 context_meta,
53 config: RlmSessionConfig::default(),
54 rpc_count: 0,
55 total_duration: Duration::ZERO,
56 peak_var_count: 0,
57 final_count: 0,
58 created_at: now,
59 last_used_at: now,
60 sandbox_policy,
61 }
62 }
63 }
64
65 #[derive(Debug, Clone, Serialize, Deserialize)]
66 pub struct ContextMeta {
67 pub length: usize,
68 #[serde(rename = "type")]
69 pub type_name: String,
70 pub preview_500: String,
71 pub sha256: String,
72 }
73
74 impl ContextMeta {
75 #[must_use]
76 pub fn from_body(body: &str, type_name: impl Into<String>) -> Self {
77 Self {
78 length: body.chars().count(),
79 type_name: type_name.into(),
80 preview_500: body.chars().take(500).collect(),
81 sha256: sha256_hex(body.as_bytes()),
82 }
83 }
84 }
85
86 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
87 #[serde(rename_all = "snake_case")]
88 pub enum OutputFeedback {
89 Full,
90 Metadata,
91 }
92
93 #[derive(Debug, Clone, Serialize, Deserialize)]
94 pub struct RlmSessionConfig {
95 pub output_feedback: OutputFeedback,
96 pub sub_rlm_max_depth: u32,
97 pub share_session: bool,
98 }
99
100 impl Default for RlmSessionConfig {
101 fn default() -> Self {
102 Self {
103 output_feedback: OutputFeedback::Full,
104 sub_rlm_max_depth: 1,
105 share_session: false,
106 }
107 }
108 }
109
110 #[derive(Debug, Clone)]
111 pub struct SessionObjectSnapshot {
112 pub session_id: String,
113 pub model: String,
114 pub workspace: PathBuf,
115 pub system_prompt: Option<SystemPrompt>,
116 pub messages: Arc<Vec<Message>>,
117 }
118
119 impl SessionObjectSnapshot {
120 #[must_use]
121 pub fn new(
122 session_id: String,
123 model: String,
124 workspace: PathBuf,
125 system_prompt: Option<SystemPrompt>,
126 messages: impl Into<Arc<Vec<Message>>>,
127 ) -> Self {
128 Self {
129 session_id,
130 model,
131 workspace,
132 system_prompt,
133 messages: messages.into(),
134 }
135 }
136
137 #[must_use]
138 pub fn object_cards(&self) -> Vec<SessionObjectCard> {
139 let mut cards = Vec::new();
140 for object in self.base_objects() {
141 cards.push(SessionObjectCard::from_resolved(&object));
142 }
143 for index in 0..self.messages.len() {
144 if let Some(object) = self.resolve(&format!("session://active/messages/{index}")) {
145 cards.push(SessionObjectCard::from_resolved(&object));
146 }
147 }
148 cards
149 }
150
151 #[must_use]
152 pub fn resolve(&self, object_ref: &str) -> Option<ResolvedSessionObject> {
153 let normalized = normalize_session_object_ref(object_ref);
154 match normalized.as_str() {
155 "session://active/session" => Some(self.session_metadata_object()),
156 "session://active/system_prompt" => self.system_prompt_object(),
157 "session://active/transcript" => Some(self.transcript_object()),
158 "session://active/latest_user" => self.latest_user_object(),
159 _ => self.message_object(&normalized),
160 }
161 }
162
163 fn base_objects(&self) -> Vec<ResolvedSessionObject> {
164 let mut objects = vec![self.session_metadata_object()];
165 if let Some(object) = self.system_prompt_object() {
166 objects.push(object);
167 }
168 objects.push(self.transcript_object());
169 if let Some(object) = self.latest_user_object() {
170 objects.push(object);
171 }
172 objects
173 }
174
175 fn session_metadata_object(&self) -> ResolvedSessionObject {
176 let body = json!({
177 "session_id": self.session_id,
178 "model": self.model,
179 "workspace": self.workspace.display().to_string(),
180 "message_count": self.messages.len(),
181 "object_refs": {
182 "system_prompt": "session://active/system_prompt",
183 "transcript": "session://active/transcript",
184 "latest_user": "session://active/latest_user",
185 "message_prefix": "session://active/messages/"
186 }
187 })
188 .to_string();
189 ResolvedSessionObject::new(
190 "session://active/session",
191 "session_metadata",
192 "Active session metadata",
193 body,
194 )
195 }
196
197 fn system_prompt_object(&self) -> Option<ResolvedSessionObject> {
198 let prompt = self.system_prompt.as_ref()?;
199 Some(ResolvedSessionObject::new(
200 "session://active/system_prompt",
201 "system_prompt",
202 "Active system prompt",
203 render_system_prompt(prompt),
204 ))
205 }
206
207 fn transcript_object(&self) -> ResolvedSessionObject {
208 let body = self
209 .messages
210 .iter()
211 .enumerate()
212 .map(|(index, message)| compact_message_json(index, message).to_string())
213 .collect::<Vec<_>>()
214 .join("\n");
215 ResolvedSessionObject::new(
216 "session://active/transcript",
217 "transcript",
218 "Active transcript as JSONL",
219 body,
220 )
221 }
222
223 fn latest_user_object(&self) -> Option<ResolvedSessionObject> {
224 self.messages
225 .iter()
226 .enumerate()
227 .rev()
228 .find(|(_, message)| message.role == "user")
229 .map(|(index, message)| message_resolved_object(index, message, "Latest user message"))
230 }
231
232 fn message_object(&self, normalized: &str) -> Option<ResolvedSessionObject> {
233 let index = normalized
234 .strip_prefix("session://active/messages/")?
235 .parse::<usize>()
236 .ok()?;
237 self.messages
238 .get(index)
239 .map(|message| message_resolved_object(index, message, "Transcript message"))
240 }
241 }
242
243 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
244 pub struct SessionObjectCard {
245 pub id: String,
246 pub kind: String,
247 pub title: String,
248 pub length: usize,
249 pub preview_500: String,
250 pub sha256: String,
251 }
252
253 impl SessionObjectCard {
254 #[must_use]
255 pub fn from_resolved(object: &ResolvedSessionObject) -> Self {
256 Self {
257 id: object.id.clone(),
258 kind: object.kind.clone(),
259 title: object.title.clone(),
260 length: object.body.chars().count(),
261 preview_500: object.body.chars().take(500).collect(),
262 sha256: sha256_hex(object.body.as_bytes()),
263 }
264 }
265 }
266
267 #[derive(Debug, Clone)]
268 pub struct ResolvedSessionObject {
269 pub id: String,
270 pub kind: String,
271 pub title: String,
272 pub body: String,
273 }
274
275 impl ResolvedSessionObject {
276 fn new(
277 id: impl Into<String>,
278 kind: impl Into<String>,
279 title: impl Into<String>,
280 body: impl Into<String>,
281 ) -> Self {
282 Self {
283 id: id.into(),
284 kind: kind.into(),
285 title: title.into(),
286 body: body.into(),
287 }
288 }
289 }
290
291 fn normalize_session_object_ref(object_ref: &str) -> String {
292 let trimmed = object_ref.trim();
293 if trimmed.starts_with("session://") {
294 trimmed.to_string()
295 } else {
296 format!("session://active/{}", trimmed.trim_start_matches('/'))
297 }
298 }
299
300 fn render_system_prompt(prompt: &SystemPrompt) -> String {
301 match prompt {
302 SystemPrompt::Text(text) => text.clone(),
303 SystemPrompt::Blocks(blocks) => blocks
304 .iter()
305 .map(|block| block.text.as_str())
306 .collect::<Vec<_>>()
307 .join("\n\n"),
308 }
309 }
310
311 fn message_resolved_object(index: usize, message: &Message, title: &str) -> ResolvedSessionObject {
312 ResolvedSessionObject::new(
313 format!("session://active/messages/{index}"),
314 "message",
315 format!("{title} {index} ({})", message.role),
316 compact_message_json(index, message).to_string(),
317 )
318 }
319
320 fn compact_message_json(index: usize, message: &Message) -> Value {
321 json!({
322 "index": index,
323 "role": message.role,
324 "content": message.content.iter().map(compact_content_block).collect::<Vec<_>>(),
325 })
326 }
327
328 fn compact_content_block(block: &ContentBlock) -> Value {
329 match block {
330 ContentBlock::Text { text, .. } => json!({
331 "type": "text",
332 "text": text,
333 }),
334 ContentBlock::Thinking { thinking, .. } => json!({
335 "type": "thinking",
336 "redacted": true,
337 "chars": thinking.chars().count(),
338 "sha256": sha256_hex(thinking.as_bytes()),
339 "preview_240": truncate_chars(thinking, 240),
340 }),
341 ContentBlock::ToolUse {
342 id,
343 name,
344 input,
345 caller,
346 ..
347 } => json!({
348 "type": "tool_use",
349 "id": id,
350 "name": name,
351 "input": input,
352 "caller": caller,
353 }),
354 ContentBlock::ToolResult {
355 tool_use_id,
356 content,
357 is_error,
358 content_blocks,
359 ..
360 } => {
361 let chars = content.chars().count();
362 let large = chars > 2_000;
363 json!({
364 "type": "tool_result",
365 "tool_use_id": tool_use_id,
366 "is_error": is_error,
367 "content": if large { Value::Null } else { Value::String(content.clone()) },
368 "content_preview": truncate_chars(content, 500),
369 "content_chars": chars,
370 "content_sha256": sha256_hex(content.as_bytes()),
371 "content_redacted": large,
372 "content_blocks": crate::image_attach::safe_tool_result_content_blocks(
373 content_blocks.as_deref(),
374 ),
375 })
376 }
377 ContentBlock::ServerToolUse {
378 id, name, input, ..
379 } => json!({
380 "type": "server_tool_use",
381 "id": id,
382 "name": name,
383 "input": input,
384 }),
385 ContentBlock::ToolSearchToolResult {
386 tool_use_id,
387 content,
388 } => json!({
389 "type": "tool_search_tool_result",
390 "tool_use_id": tool_use_id,
391 "content": content,
392 }),
393 ContentBlock::CodeExecutionToolResult {
394 tool_use_id,
395 content,
396 } => json!({
397 "type": "code_execution_tool_result",
398 "tool_use_id": tool_use_id,
399 "content": content,
400 }),
401 ContentBlock::WebSearchToolResult {
402 tool_use_id,
403 content,
404 kind,
405 } => json!({
406 "type": "web_search_tool_result",
407 "tool_use_id": tool_use_id,
408 "content": content,
409 "kind": kind,
410 }),
411 ContentBlock::WebFetchToolResult {
412 tool_use_id,
413 content,
414 kind,
415 signature,
416 } => json!({
417 "type": "web_fetch_tool_result",
418 "tool_use_id": tool_use_id,
419 "content": content,
420 "kind": kind,
421 "signature": signature,
422 }),
423 ContentBlock::WebSearchCall {
424 id, status, kind, ..
425 } => json!({
426 "type": "web_search_call",
427 "id": id,
428 "status": status,
429 "kind": kind,
430 }),
431 ContentBlock::ServerToolCalls { steps } => json!({
432 "type": "server_tool_calls",
433 "steps": steps,
434 }),
435 ContentBlock::File { file_id } => json!({
436 "type": "file",
437 "file_id": file_id,
438 }),
439 ContentBlock::ImageUrl { .. } => serde_json::Value::Null,
440 }
441 }
442
443 fn truncate_chars(text: &str, max_chars: usize) -> String {
444 if text.chars().count() <= max_chars {
445 return text.to_string();
446 }
447 let take = max_chars.saturating_sub(3);
448 let mut out: String = text.chars().take(take).collect();
449 out.push_str("...");
450 out
451 }
452
453 #[must_use]
454 pub fn derive_session_name(source_hint: Option<&str>) -> String {
455 let hint = source_hint
456 .and_then(|raw| {
457 Path::new(raw)
458 .file_name()
459 .and_then(|name| name.to_str())
460 .or(Some(raw))
461 })
462 .unwrap_or("context");
463 let mut out = String::new();
464 for ch in hint.chars() {
465 if ch.is_alphanumeric() {
466 out.extend(ch.to_lowercase());
467 } else if !out.ends_with('_') {
468 out.push('_');
469 }
470 if out.len() >= 48 {
471 break;
472 }
473 }
474 let out = out.trim_matches('_');
475 if out.is_empty() {
476 "context".to_string()
477 } else {
478 out.to_string()
479 }
480 }
481
482 fn sha256_hex(bytes: &[u8]) -> String {
483 codewhale_runtime::hashing::sha256_hex(bytes)
484 }
485
486 #[cfg(test)]
487 mod tests {
488 use super::*;
489 use codewhale_models::Role;
490
491 #[test]
492 fn derive_session_name_slugifies_path() {
493 assert_eq!(
494 derive_session_name(Some("src/Big File.rs")),
495 "big_file_rs".to_string()
496 );
497 assert_eq!(derive_session_name(Some("docs/报告.txt")), "报告_txt");
498 assert_eq!(derive_session_name(Some("docs/总结.txt")), "总结_txt");
499 }
500
501 #[test]
502 fn context_meta_hashes_and_previews_body() {
503 let meta = ContextMeta::from_body("abcdef", "text");
504 assert_eq!(meta.length, 6);
505 assert_eq!(meta.preview_500, "abcdef");
506 assert_eq!(
507 meta.sha256,
508 "bef57ec7f53a6d40beb640a780a639c83bc29ac8a9816f1fc6c5c6dcd93c4721"
509 );
510 }
511
512 #[test]
513 fn session_objects_expose_prompt_and_transcript_cards() {
514 let snapshot = SessionObjectSnapshot::new(
515 "session-1".to_string(),
516 "deepseek-v4-pro".to_string(),
517 PathBuf::from("/tmp/work"),
518 Some(SystemPrompt::Text("system body".to_string())),
519 vec![Message {
520 role: Role::User,
521 content: vec![ContentBlock::Text {
522 text: "hello RLM".to_string(),
523 cache_control: None,
524 }],
525 }],
526 );
527
528 let cards = snapshot.object_cards();
529 assert!(
530 cards
531 .iter()
532 .any(|card| card.id == "session://active/system_prompt")
533 );
534 assert!(
535 cards
536 .iter()
537 .any(|card| card.id == "session://active/messages/0")
538 );
539
540 let transcript = snapshot
541 .resolve("session://active/transcript")
542 .expect("transcript object");
543 assert!(transcript.body.contains("hello RLM"));
544 }
545
546 #[test]
547 fn session_object_transcript_keeps_large_tool_results_compact() {
548 let large = "tool output\n".repeat(400);
549 let snapshot = SessionObjectSnapshot::new(
550 "session-1".to_string(),
551 "deepseek-v4-pro".to_string(),
552 PathBuf::from("/tmp/work"),
553 None,
554 vec![Message {
555 role: Role::User,
556 content: vec![ContentBlock::ToolResult {
557 execution_id: None,
558 tool_use_id: "call_1".to_string(),
559 content: large.clone(),
560 is_error: None,
561 content_blocks: None,
562 }],
563 }],
564 );
565
566 let object = snapshot
567 .resolve("session://active/messages/0")
568 .expect("message object");
569 assert!(object.body.contains("\"content_redacted\":true"));
570 assert!(object.body.len() < large.len());
571 }
572 }
573
573 lines RUST