返回 CodeWhale
rlm.rs
根目录 / crates / engine / src / tools / rlm.rs
1 //! Persistent RLM session tool.
2 //!
3 //! One `rlm` tool with a head/hands surface: action `open` creates a named
4 //! Python kernel over a large context, `eval` runs bounded probes against it,
5 //! `configure` adjusts runtime feedback, and `close` tears it down.
6
7 use std::sync::Arc;
8 use std::time::{Duration, Instant};
9
10 use async_trait::async_trait;
11 use serde_json::{Value, json};
12
13 use crate::rlm::RlmBridge;
14 use crate::rlm::bridge::wait_for_deadline;
15 use crate::rlm::session::{ContextMeta, OutputFeedback, RlmSession, derive_session_name};
16 use crate::tools::fetch_url::FetchUrlTool;
17 use crate::tools::spec::{
18 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
19 };
20
21 /// Registered name of the persistent RLM session tool.
22 pub const RLM_TOOL_NAME: &str = "rlm";
23 const MAX_INLINE_CONTENT_CHARS: usize = 200_000;
24 const FULL_STDOUT_HEAD_CHARS: usize = 4_096;
25 const FULL_STDOUT_TAIL_CHARS: usize = 1_024;
26
27 /// When `rlm_eval` stdout exceeds this many characters the full body is
28 /// stored as a `var_handle` instead of inlined into the parent transcript.
29 /// The model retrieves the body via `handle_read` using the returned handle.
30 const STDOUT_HANDLE_THRESHOLD_CHARS: usize = 1_000;
31 const HARD_SUB_RLM_DEPTH_CAP: u32 = 3;
32
33 const ALL_ACTIONS: &[&str] = &["session_objects", "open", "eval", "configure", "close"];
34
35 fn rlm_kernel_error_result(
36 error: &str,
37 elapsed: Duration,
38 usage_batch: &crate::cost_status::RuntimeUsageBatch,
39 nested_events: &[Value],
40 ) -> ToolResult {
41 let mut metadata = json!({
42 // The registered tool is `rlm`; `eval` is its action. Naming a
43 // retired `rlm_eval` tool here taught the model a call it cannot
44 // make (2026-08-04 audit).
45 "tool": "rlm",
46 "action": "eval",
47 "duration_ms": elapsed.as_millis() as u64,
48 "kernel_error": true,
49 });
50 crate::cost_status::attach_child_usage_batch_metadata(&mut metadata, usage_batch);
51 ToolResult::error(
52 json!({
53 "tool": "rlm", "action": "eval", "error": error,
54 "nested_events": nested_events,
55 })
56 .to_string(),
57 )
58 .with_metadata(metadata)
59 }
60
61 /// Unified RLM session tool.
62 ///
63 /// One input schema and the existing per-session Python store. Provider RPCs
64 /// require the caller receipt attached by Core to the actual ToolContext.
65 pub struct RlmTool {
66 name: &'static str,
67 }
68
69 impl RlmTool {
70 #[must_use]
71 pub fn new(name: &'static str) -> Self {
72 Self { name }
73 }
74
75 fn resolve_action<'a>(&'a self, input: &'a Value) -> Result<&'a str, ToolError> {
76 let action = input.get("action").and_then(Value::as_str).ok_or_else(|| {
77 ToolError::invalid_input(format!(
78 "rlm: missing `action` (one of: {})",
79 ALL_ACTIONS.join(", ")
80 ))
81 })?;
82 if ALL_ACTIONS.contains(&action) {
83 Ok(action)
84 } else {
85 Err(ToolError::invalid_input(format!(
86 "rlm: invalid action `{action}` (one of: {})",
87 ALL_ACTIONS.join(", ")
88 )))
89 }
90 }
91
92 /// Without concrete input, open may fetch a URL. Input-specific approval
93 /// below keeps local/inline reads automatic and inherits fetch_url's
94 /// outbound-payload approval for URL sources.
95 fn action_requires_approval(action: &str) -> bool {
96 matches!(action, "eval" | "open")
97 }
98
99 /// `open` and `eval` execute code, so only session_objects / configure /
100 /// close count as read-only.
101 fn action_is_read_only(action: &str) -> bool {
102 matches!(action, "session_objects" | "configure" | "close")
103 }
104 }
105
106 #[async_trait]
107 impl ToolSpec for RlmTool {
108 fn name(&self) -> &'static str {
109 self.name
110 }
111
112 fn description(&self) -> &'static str {
113 "Persistent RLM sessions over large contexts. Actions: \"session_objects\" \
114 (list active prompt/history/session symbolic objects as compact cards), \
115 \"open\" (load file_path/content/url/session_object into a named Python \
116 kernel; returns only metadata so the parent transcript holds a handle, \
117 not the body), \"eval\" (run one bounded Python REPL block against a \
118 named context; approval required; FINAL/finalize values and large \
119 stdout/stderr become var_handles retrievable with handle_read), \
120 \"configure\" (output feedback, child timeout, sub-RLM depth, session \
121 sharing), \"close\" (tear down the kernel and return usage metadata)."
122 }
123
124 fn input_schema(&self) -> Value {
125 json!({
126 "type": "object",
127 "properties": {
128 "action": {
129 "type": "string",
130 "enum": ALL_ACTIONS,
131 "description": "Action to perform."
132 },
133 "name": {
134 "type": "string",
135 "description": "RLM context name, unique within this parent session (action=open: optional, defaults to a slug from the source). Required for action=eval/configure/close."
136 },
137 "file_path": {
138 "type": "string",
139 "description": "Workspace-relative file to load (action=open; exactly one of file_path/content/url/session_object)."
140 },
141 "content": {
142 "type": "string",
143 "description": "Inline content to load. Capped at 200k chars. (action=open)"
144 },
145 "url": {
146 "type": "string",
147 "description": "HTTP/HTTPS URL to fetch (through the same path as Web action=\"fetch\") and load. (action=open)"
148 },
149 "session_object": {
150 "type": "string",
151 "description": "Stable symbolic active-session ref from action=session_objects, for example session://active/system_prompt or session://active/messages/0. (action=open)"
152 },
153 "code": {
154 "type": "string",
155 "description": "Raw Python executed against the context (no markdown fences). The loaded source is in scope as `content`; call FINAL(value)/finalize(...) to return a result handle. Example: print(len(content)). (action=eval)"
156 },
157 "output_feedback": {
158 "type": "string",
159 "enum": ["full", "metadata"],
160 "description": "(action=configure)"
161 },
162 "sub_rlm_max_depth": {
163 "type": "integer",
164 "minimum": 0,
165 "maximum": 3,
166 "description": "(action=configure)"
167 },
168 "share_session": {
169 "type": "boolean",
170 "description": "(action=configure)"
171 }
172 },
173 "additionalProperties": false
174 })
175 }
176
177 fn capabilities(&self) -> Vec<ToolCapability> {
178 vec![
179 ToolCapability::Network,
180 ToolCapability::ExecutesCode,
181 ToolCapability::RequiresApproval,
182 ]
183 }
184
185 fn approval_requirement(&self) -> ApprovalRequirement {
186 ApprovalRequirement::Required
187 }
188
189 fn approval_requirement_for(&self, input: &Value) -> ApprovalRequirement {
190 match self.resolve_action(input) {
191 Ok("open") if rlm_open_source_field(input, "url").is_some() => {
192 FetchUrlTool.approval_requirement_for(&json!({"url": input["url"]}))
193 }
194 Ok("open") => ApprovalRequirement::Auto,
195 Ok(action) if Self::action_requires_approval(action) => ApprovalRequirement::Required,
196 Ok(_) => ApprovalRequirement::Auto,
197 Err(_) => self.approval_requirement(),
198 }
199 }
200
201 fn is_read_only_for(&self, input: &Value) -> bool {
202 match self.resolve_action(input) {
203 Ok(action) => Self::action_is_read_only(action),
204 Err(_) => self.is_read_only(),
205 }
206 }
207
208 fn supports_parallel_for(&self, input: &Value) -> bool {
209 matches!(self.resolve_action(input), Ok("session_objects"))
210 }
211
212 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
213 match self.resolve_action(&input)? {
214 "session_objects" => self.execute_session_objects(context).await,
215 "open" => self.execute_open(&input, context).await,
216 "eval" => self.execute_eval(&input, context).await,
217 "configure" => self.execute_configure(&input, context).await,
218 "close" => self.execute_close(&input, context).await,
219 action => Err(ToolError::invalid_input(format!(
220 "rlm: invalid action `{action}`"
221 ))),
222 }
223 }
224 }
225
226 impl RlmTool {
227 async fn execute_session_objects(
228 &self,
229 context: &ToolContext,
230 ) -> Result<ToolResult, ToolError> {
231 let snapshot = context.session_objects.as_ref().ok_or_else(|| {
232 ToolError::not_available("rlm_session_objects: active session snapshot unavailable")
233 })?;
234 ToolResult::json(&json!({
235 "objects": snapshot.object_cards(),
236 "open_with": {
237 "tool": "rlm",
238 "action": "open",
239 "field": "session_object",
240 "example": {
241 "name": "active_prompt",
242 "session_object": "session://active/system_prompt"
243 }
244 },
245 "redaction": "Large tool results and thinking blocks are represented by compact metadata in transcript objects; call handle_read on returned handles for bounded payload projections."
246 }))
247 .map_err(|e| ToolError::execution_failed(e.to_string()))
248 }
249
250 async fn execute_open(
251 &self,
252 input: &Value,
253 context: &ToolContext,
254 ) -> Result<ToolResult, ToolError> {
255 let deadline = context.turn_deadline;
256 if deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline) {
257 return Err(ToolError::execution_failed(
258 "RLM parent turn deadline exhausted before opening context",
259 ));
260 }
261 let open = async {
262 let source_count = rlm_open_source_count(input);
263 if source_count != 1 {
264 let mut msg = String::from(
265 "rlm_open: provide exactly one of `file_path` (local file), `content` (inline text), `url`, or `session_object`",
266 );
267 // "did you mean" for common misnamings (#2655).
268 if let Some(obj) = input.as_object() {
269 let seen: Vec<&str> = [
270 "prompt",
271 "resident_file",
272 "text",
273 "body",
274 "path",
275 "file",
276 "source",
277 ]
278 .into_iter()
279 .filter(|k| obj.contains_key(*k))
280 .collect();
281 if !seen.is_empty() {
282 msg.push_str(&format!(
283 ". Saw {seen:?} — did you mean file_path/content/url/session_object? (to evaluate against an existing context, pass its name to rlm action='eval', or use `session_object`)"
284 ));
285 }
286 }
287 return Err(ToolError::invalid_input(msg));
288 }
289
290 let (body, source_type, source_hint) = load_source(input, context).await?;
291 if body.trim().is_empty() {
292 return Err(ToolError::invalid_input(
293 "rlm_open: input is empty after loading",
294 ));
295 }
296
297 let name = input
298 .get("name")
299 .and_then(Value::as_str)
300 .map(str::trim)
301 .filter(|name| !name.is_empty())
302 .map(ToOwned::to_owned)
303 .unwrap_or_else(|| derive_session_name(source_hint.as_deref()));
304
305 {
306 let sessions = context.runtime.rlm_sessions.lock().await;
307 if sessions.contains_key(&name) {
308 return Err(ToolError::invalid_input(format!(
309 "rlm_open: context name `{name}` already exists"
310 )));
311 }
312 }
313
314 let kernel = crate::rlm::kernel::spawn_kernel(context, Some(&body), None)
315 .await
316 .map_err(|e| ToolError::execution_failed(format!("rlm_open: {e}")))?;
317 let context_meta = ContextMeta::from_body(&body, source_type);
318 let session = RlmSession::new(
319 name.clone(),
320 kernel,
321 context_meta.clone(),
322 context.elevated_sandbox_policy.clone(),
323 );
324 let id = session.id.clone();
325
326 let mut sessions = context.runtime.rlm_sessions.lock().await;
327 sessions.insert(name.clone(), Arc::new(tokio::sync::Mutex::new(session)));
328
329 ToolResult::json(&json!({
330 "name": name,
331 "id": id,
332 "length": context_meta.length,
333 "type": context_meta.type_name,
334 "preview_500": context_meta.preview_500,
335 "sha256": context_meta.sha256,
336 }))
337 .map_err(|e| ToolError::execution_failed(e.to_string()))
338 };
339 tokio::select! {
340 biased;
341 () = async {
342 if let Some(cancel) = context.cancel_token.as_ref() {
343 cancel.cancelled().await;
344 } else {
345 std::future::pending::<()>().await;
346 }
347 } => Err(ToolError::cancelled("RLM originating turn cancelled while opening context")),
348 () = wait_for_deadline(deadline) => Err(ToolError::execution_failed("RLM parent turn deadline exhausted opening context")),
349 result = open => result,
350 }
351 }
352
353 async fn execute_eval(
354 &self,
355 input: &Value,
356 context: &ToolContext,
357 ) -> Result<ToolResult, ToolError> {
358 crate::tools::execution_envelope::enforce_tool_denial(context, "rlm_eval", input)?;
359 let name = required_non_empty_str(input, "name")?;
360 let code = required_non_empty_str(input, "code").map_err(|_| {
361 ToolError::invalid_input(
362 "rlm_eval: `code` is required and runs raw Python against the RLM context (no markdown fences). \
363 Example: {\"name\": \"<ctx>\", \"code\": \"print(len(content))\"}; call FINAL(value) to return a result handle.",
364 )
365 })?;
366 let deadline = context.turn_deadline;
367 if deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline) {
368 return Err(ToolError::execution_failed(
369 "RLM parent turn deadline exhausted before execution",
370 ));
371 }
372 let original_cancel = context.cancel_token.clone();
373 let wait_for_cancel = || async {
374 if let Some(cancel) = original_cancel.as_ref() {
375 cancel.cancelled().await;
376 } else {
377 std::future::pending::<()>().await;
378 }
379 };
380 let mut session = tokio::select! {
381 biased;
382 () = wait_for_cancel() => return Err(ToolError::cancelled("RLM originating turn cancelled while waiting for context")),
383 () = wait_for_deadline(deadline) => return Err(ToolError::execution_failed("RLM parent turn deadline exhausted waiting for context")),
384 result = async {
385 let session = get_session(context, name).await?;
386 Ok::<_, ToolError>(session.lock_owned().await)
387 } => result?,
388 };
389 let config = session.config.clone();
390 if session.sandbox_policy != context.elevated_sandbox_policy {
391 session.kernel = None;
392 drop(session);
393 context.runtime.rlm_sessions.lock().await.remove(name);
394 return Err(ToolError::invalid_input(format!(
395 "rlm_eval: context `{name}` was closed because the sandbox policy changed after it was opened; open it again"
396 )));
397 }
398
399 if let Some(caller) = context.rlm_caller.as_deref() {
400 caller.validate_context(context)?;
401 }
402 // The active round owns the existing interpreter. Dropping this
403 // future kills unknown running code rather than leaving it in the
404 // persistent map; only a completed round restores the same kernel.
405 let Some(mut kernel) = session.kernel.take() else {
406 return Err(ToolError::invalid_input(format!(
407 "rlm_eval: context `{name}` is closed"
408 )));
409 };
410
411 let started = Instant::now();
412 let (round, child_usage_batch, nested_events) = if let Some(caller) =
413 context.rlm_caller.as_deref()
414 {
415 let bridge =
416 RlmBridge::new(caller, config.sub_rlm_max_depth.min(HARD_SUB_RLM_DEPTH_CAP))
417 .with_deadline(deadline)
418 .with_gate(context.execution.nested_call_gate.clone());
419 let round_result = tokio::select! {
420 biased;
421 () = wait_for_cancel() => Err("RLM evaluation cancelled by its originating turn".into()),
422 () = wait_for_deadline(bridge.deadline()) => Err("RLM evaluation reached the parent turn deadline".into()),
423 result = kernel.run(code, Some(&bridge)) => result,
424 };
425 let usage = bridge.usage_snapshot().await;
426 let round = match round_result {
427 Ok(round) => round,
428 Err(error) => {
429 // A bridge request may have completed and accrued usage
430 // before the Python kernel times out or closes stdout.
431 // Return a failed ToolResult (rather than a bare ToolError)
432 // so ToolCallComplete still carries the immutable child
433 // receipt and the runtime can durably account for it.
434 // Cancellation may leave Python running. Discard the
435 // owned interpreter rather than reusing unknown state.
436 session.kernel = None;
437 session.last_used_at = Instant::now();
438 return Ok(rlm_kernel_error_result(
439 &error.to_string(),
440 started.elapsed(),
441 &crate::cost_status::RuntimeUsageBatch {
442 decisions: Vec::new(),
443 records: usage.records,
444 drop_records: usage.drop_records,
445 dropped_records: usage.dropped_records,
446 },
447 &usage.nested_events,
448 ));
449 }
450 };
451 (
452 round,
453 crate::cost_status::RuntimeUsageBatch {
454 decisions: Vec::new(),
455 records: usage.records,
456 drop_records: usage.drop_records,
457 dropped_records: usage.dropped_records,
458 },
459 usage.nested_events,
460 )
461 } else {
462 let round = tokio::select! {
463 biased;
464 () = wait_for_cancel() => return Err(ToolError::cancelled("RLM evaluation cancelled by its originating turn")),
465 () = wait_for_deadline(deadline) => return Err(ToolError::execution_failed("RLM evaluation reached the parent turn deadline")),
466 result = kernel.run(code, None::<&RlmBridge<'_>>) => result.map_err(|e| ToolError::execution_failed(format!("rlm_eval: {e}")))?,
467 };
468 (
469 round,
470 crate::cost_status::RuntimeUsageBatch::default(),
471 Vec::new(),
472 )
473 };
474
475 session.kernel = Some(kernel);
476 session.rpc_count = session.rpc_count.saturating_add(round.rpc_count);
477 session.total_duration += round.elapsed;
478 session.last_used_at = Instant::now();
479
480 let final_handle = if let Some(value_json) = round.final_json.clone() {
481 session.final_count = session.final_count.saturating_add(1);
482 let handle_name = format!("final_{}", session.final_count);
483 let handle = {
484 let mut store = context.runtime.handle_store.lock().await;
485 match value_json {
486 Value::String(value) => {
487 store.insert_text(session.id.clone(), handle_name, value)
488 }
489 other => store.insert_json(session.id.clone(), handle_name, other),
490 }
491 };
492 Some(handle)
493 } else {
494 None
495 };
496
497 let had_error = round.has_error;
498 let rpc_count = round.rpc_count;
499 let duration_ms = round.elapsed.as_millis() as u64;
500 // Route large stdout/stderr into a var_handle to avoid bloat in
501 // the parent transcript. The model calls handle_read for bounded
502 // projections; a short inline note describes availability.
503 fn route_output(
504 text: &str,
505 feedback: &OutputFeedback,
506 store: &mut crate::tools::handle::HandleStore,
507 session_id: &str,
508 tag: &str,
509 ) -> (Option<String>, Option<crate::tools::handle::VarHandle>) {
510 let threshold = STDOUT_HANDLE_THRESHOLD_CHARS;
511 match (feedback, text.len()) {
512 (OutputFeedback::Full, len) if len <= threshold => {
513 (Some(preview_output(text)), None)
514 }
515 (OutputFeedback::Full, _) if !text.trim().is_empty() => {
516 // Store full body as a handle for out-of-band retrieval
517 let name = format!("{tag}_{}", 0); // single counter is fine
518 let handle = store.insert_text(session_id, name, text);
519 (
520 Some(format!("{} chars; retrieve via handle_read", text.len())),
521 Some(handle),
522 )
523 }
524 _ => (None, None),
525 }
526 }
527
528 let (stdout_preview, stdout_handle) = route_output(
529 &round.full_stdout,
530 &config.output_feedback,
531 &mut *context.runtime.handle_store.lock().await,
532 &session.id,
533 "stdout",
534 );
535 let (stderr_preview, stderr_handle) = route_output(
536 &round.stderr,
537 &config.output_feedback,
538 &mut *context.runtime.handle_store.lock().await,
539 &session.id,
540 "stderr",
541 );
542
543 let mut output = json!({
544 "name": session.name,
545 "id": session.id,
546 "duration_ms": duration_ms,
547 "rpc_count": rpc_count,
548 "had_error": had_error,
549 "new_vars": [],
550 "nested_events": nested_events,
551 "final": final_handle,
552 });
553 if let Some(ref stdout_preview) = stdout_preview {
554 output["stdout_preview"] = json!(stdout_preview);
555 }
556 if let Some(ref stderr_preview) = stderr_preview {
557 output["stderr_preview"] = json!(stderr_preview);
558 }
559 if let (Some(h), Some(_)) = (stdout_handle, &stdout_preview) {
560 output["stdout_handle"] = json!(h);
561 }
562 if let (Some(h), Some(_)) = (stderr_handle, &stderr_preview) {
563 output["stderr_handle"] = json!(h);
564 }
565 if let Some(confidence) = round.final_confidence.clone() {
566 output["confidence"] = confidence;
567 }
568
569 let mut metadata = json!({
570 "tool": "rlm_eval",
571 "duration_ms": started.elapsed().as_millis() as u64,
572 });
573 // Every RLM provider call keeps its own dispatch timestamp and frozen
574 // quote. The preferred batch format prevents a fan-out from being
575 // retroactively priced as one aggregate call on the first route.
576 crate::cost_status::attach_child_usage_batch_metadata(&mut metadata, &child_usage_batch);
577
578 Ok(ToolResult::json(&output)
579 .map_err(|e| ToolError::execution_failed(e.to_string()))?
580 .with_metadata(metadata))
581 }
582
583 async fn execute_configure(
584 &self,
585 input: &Value,
586 context: &ToolContext,
587 ) -> Result<ToolResult, ToolError> {
588 let name = required_non_empty_str(input, "name")?;
589 // No cross-session authority exists in this surface. Refuse before
590 // mutating any other setting, rather than retaining an inert true bit.
591 if input.get("share_session").and_then(Value::as_bool) == Some(true) {
592 return Err(ToolError::invalid_input(
593 "rlm_configure: share_session=true is unsupported; contexts remain caller-session scoped",
594 ));
595 }
596 let session = get_session(context, name).await?;
597 let mut session = session.lock().await;
598
599 if let Some(value) = input.get("output_feedback").and_then(Value::as_str) {
600 session.config.output_feedback = match value {
601 "full" => OutputFeedback::Full,
602 "metadata" => OutputFeedback::Metadata,
603 other => {
604 return Err(ToolError::invalid_input(format!(
605 "rlm_configure: invalid output_feedback `{other}`"
606 )));
607 }
608 };
609 }
610 if let Some(depth) = input.get("sub_rlm_max_depth").and_then(Value::as_u64) {
611 session.config.sub_rlm_max_depth = (depth as u32).min(HARD_SUB_RLM_DEPTH_CAP);
612 }
613 if input.get("share_session").and_then(Value::as_bool) == Some(false) {
614 session.config.share_session = false;
615 }
616
617 let mut result = json!({
618 "name": session.name,
619 "current_config": session.config,
620 });
621 if input.get("sub_query_timeout_secs").is_some() {
622 result["ignored_limit_fields"] = json!(["sub_query_timeout_secs"]);
623 result["limits_note"] = json!(
624 "Recursive work inherits the owner's deadline; model-selected subquery time limits are retired."
625 );
626 }
627 ToolResult::json(&result).map_err(|e| ToolError::execution_failed(e.to_string()))
628 }
629
630 async fn execute_close(
631 &self,
632 input: &Value,
633 context: &ToolContext,
634 ) -> Result<ToolResult, ToolError> {
635 let name = required_non_empty_str(input, "name")?;
636 let removed = {
637 let mut sessions = context.runtime.rlm_sessions.lock().await;
638 sessions.remove(name)
639 };
640 let Some(session) = removed else {
641 return Err(ToolError::invalid_input(format!(
642 "rlm_close: unknown context `{name}`"
643 )));
644 };
645
646 let mut session = session.lock().await;
647 let kernel = session.kernel.take();
648 let output = json!({
649 "name": session.name,
650 "id": session.id,
651 "rpc_count": session.rpc_count,
652 "total_duration_ms": session.total_duration.as_millis() as u64,
653 "peak_var_count": session.peak_var_count,
654 "created_ms_ago": session.created_at.elapsed().as_millis() as u64,
655 });
656 drop(session);
657
658 if let Some(kernel) = kernel {
659 kernel.shutdown().await;
660 }
661
662 ToolResult::json(&output).map_err(|e| ToolError::execution_failed(e.to_string()))
663 }
664 }
665
666 async fn load_source(
667 input: &Value,
668 context: &ToolContext,
669 ) -> Result<(String, String, Option<String>), ToolError> {
670 if let Some(path) = rlm_open_source_field(input, "file_path").map(str::trim) {
671 let plan =
672 crate::tools::file::resolve_read_open_plan(context, path, "rlm_open", false, false)
673 .await?;
674 let display_path = plan.file_path.clone();
675 let (bytes, _fd_path) =
676 crate::tools::file::open_and_read_verified_bytes(plan, None, true, "rlm_open: read")
677 .await?
678 .ok_or_else(|| {
679 ToolError::execution_failed(format!(
680 "rlm_open: read {}: file not found",
681 display_path.display()
682 ))
683 })?;
684 let body = String::from_utf8(bytes).map_err(|e| {
685 ToolError::execution_failed(format!("rlm_open: read {}: {e}", display_path.display()))
686 })?;
687 return Ok((body, "file".to_string(), Some(path.to_string())));
688 }
689
690 if let Some(content) = rlm_open_source_field(input, "content") {
691 if content.chars().count() > MAX_INLINE_CONTENT_CHARS {
692 return Err(ToolError::invalid_input(format!(
693 "rlm_open: inline content is {} chars (cap {MAX_INLINE_CONTENT_CHARS})",
694 content.chars().count()
695 )));
696 }
697 return Ok((content.to_string(), "content".to_string(), None));
698 }
699
700 if let Some(object_ref) = rlm_open_source_field(input, "session_object") {
701 let snapshot = context.session_objects.as_ref().ok_or_else(|| {
702 ToolError::not_available("rlm_open: active session snapshot unavailable")
703 })?;
704 let object = snapshot.resolve(object_ref).ok_or_else(|| {
705 ToolError::invalid_input(format!("rlm_open: unknown session object `{object_ref}`"))
706 })?;
707 return Ok((
708 object.body,
709 format!("session_object:{}", object.kind),
710 Some(object.id),
711 ));
712 }
713
714 let url = rlm_open_source_field(input, "url")
715 .map(str::trim)
716 .ok_or_else(|| ToolError::invalid_input("rlm_open: missing source"))?;
717 crate::tools::execution_envelope::enforce_tool_denial(context, "fetch_url", input)?;
718 let result = FetchUrlTool
719 .execute(json!({"url": url, "format": "raw"}), context)
720 .await?;
721 let parsed: Value = serde_json::from_str(&result.content).map_err(|e| {
722 ToolError::execution_failed(format!("rlm_open: fetch_url returned invalid JSON: {e}"))
723 })?;
724 let body = parsed
725 .get("content")
726 .and_then(Value::as_str)
727 .ok_or_else(|| ToolError::execution_failed("rlm_open: fetched body missing content"))?
728 .to_string();
729 let source_type = parsed
730 .get("content_type")
731 .and_then(Value::as_str)
732 .unwrap_or("url")
733 .to_string();
734 Ok((body, source_type, Some(url.to_string())))
735 }
736
737 fn rlm_open_source_count(input: &Value) -> usize {
738 ["file_path", "content", "url", "session_object"]
739 .iter()
740 .filter(|field| rlm_open_source_field(input, field).is_some())
741 .count()
742 }
743
744 fn rlm_open_source_field<'a>(input: &'a Value, field: &str) -> Option<&'a str> {
745 input
746 .get(field)
747 .and_then(Value::as_str)
748 .filter(|value| !value.trim().is_empty())
749 }
750
751 async fn get_session(
752 context: &ToolContext,
753 name: &str,
754 ) -> Result<Arc<tokio::sync::Mutex<RlmSession>>, ToolError> {
755 let sessions = context.runtime.rlm_sessions.lock().await;
756 sessions.get(name).cloned().ok_or_else(|| {
757 ToolError::invalid_input(format!(
758 "unknown RLM context `{name}`; open it first with rlm action='open'"
759 ))
760 })
761 }
762
763 fn required_non_empty_str<'a>(input: &'a Value, field: &str) -> Result<&'a str, ToolError> {
764 let value = input
765 .get(field)
766 .and_then(Value::as_str)
767 .ok_or_else(|| ToolError::missing_field(field))?
768 .trim();
769 if value.is_empty() {
770 return Err(ToolError::invalid_input(format!(
771 "rlm: `{field}` must not be empty"
772 )));
773 }
774 Ok(value)
775 }
776
777 fn preview_output(text: &str) -> String {
778 let total = text.chars().count();
779 if total <= FULL_STDOUT_HEAD_CHARS + FULL_STDOUT_TAIL_CHARS {
780 return text.to_string();
781 }
782 let head: String = text.chars().take(FULL_STDOUT_HEAD_CHARS).collect();
783 let tail: String = text
784 .chars()
785 .skip(total.saturating_sub(FULL_STDOUT_TAIL_CHARS))
786 .collect();
787 format!(
788 "{head}\n... [{} chars truncated, retrieve via handle_read when returned as a handle] ...\n{tail}",
789 total.saturating_sub(FULL_STDOUT_HEAD_CHARS + FULL_STDOUT_TAIL_CHARS),
790 )
791 }
792
793 #[cfg(test)]
794 mod tests {
795 use super::*;
796 use crate::rlm::session::SessionObjectSnapshot;
797 use crate::tools::handle::HandleReadTool;
798 use crate::tools::spec::ToolContext;
799 use codewhale_models::Role;
800 use codewhale_models::{ContentBlock, Message, SystemPrompt};
801 use std::path::PathBuf;
802
803 /// #6747: runtime text pointing at `handle_read` names no hidden tool.
804 #[test]
805 fn handle_read_pointers_name_only_callable_tools() {
806 let long = "x".repeat(FULL_STDOUT_HEAD_CHARS + FULL_STDOUT_TAIL_CHARS + 10);
807 let preview = preview_output(&long);
808 let preview_footer = preview
809 .lines()
810 .find(|line| line.contains("chars truncated"))
811 .expect("truncation footer");
812 crate::tools::canonical_action_test_support::assert_text_names_only_callable_tools(
813 "rlm preview footer",
814 preview_footer,
815 );
816 }
817
818 fn ctx() -> ToolContext {
819 ToolContext::new(".")
820 }
821
822 fn ctx_with_session_objects() -> ToolContext {
823 ToolContext::new(".").with_session_objects(SessionObjectSnapshot::new(
824 "session-1".to_string(),
825 "deepseek-v4-pro".to_string(),
826 PathBuf::from("."),
827 Some(SystemPrompt::Text("You are CodeWhale.".to_string())),
828 vec![
829 Message {
830 role: Role::User,
831 content: vec![ContentBlock::Text {
832 text: "Please inspect the RLM surface.".to_string(),
833 cache_control: None,
834 }],
835 },
836 Message {
837 role: Role::Assistant,
838 content: vec![ContentBlock::Text {
839 text: "I will use symbolic session objects.".to_string(),
840 cache_control: None,
841 }],
842 },
843 ],
844 ))
845 }
846
847 #[test]
848 fn canonical_rlm_tool_is_model_visible_and_offers_every_action() {
849 let canonical = RlmTool::new("rlm");
850 assert!(canonical.model_visible());
851 assert_eq!(canonical.name(), "rlm");
852 let actions = canonical.input_schema()["properties"]["action"]["enum"]
853 .as_array()
854 .expect("action enum")
855 .clone();
856 for action in ["session_objects", "open", "eval", "configure", "close"] {
857 assert!(
858 actions.iter().any(|value| value.as_str() == Some(action)),
859 "canonical schema must offer action {action}"
860 );
861 }
862 }
863
864 #[test]
865 fn kernel_failure_result_retains_child_usage_receipt() {
866 let route = crate::cost_status::EffectiveRouteEnvelope::capture(
867 None,
868 codewhale_config::ProviderKind::Deepseek,
869 codewhale_config::ProviderKind::Deepseek.as_str(),
870 "deepseek-v4-flash",
871 Some(
872 codewhale_config::ProviderKind::Deepseek
873 .provider()
874 .default_base_url(),
875 ),
876 chrono::Utc::now(),
877 );
878 let usage = codewhale_models::Usage {
879 input_tokens: 23,
880 output_tokens: 5,
881 reasoning_replay_tokens: Some(7),
882 ..Default::default()
883 };
884 let record = crate::cost_status::RuntimeUsageRecord::legacy(
885 "rlm:test:request:0".to_string(),
886 crate::cost_status::EffectiveRouteUsage {
887 route: route.clone(),
888 usage: usage.clone(),
889 },
890 );
891 let drop_record = crate::cost_status::RuntimeUsageDropRecord {
892 reason: crate::cost_status::RuntimeUsageMissingReason::default(),
893 source_id: "rlm:test:request:1".to_string(),
894 route: route.clone(),
895 };
896 let result = rlm_kernel_error_result(
897 "kernel stdout closed",
898 Duration::from_millis(11),
899 &crate::cost_status::RuntimeUsageBatch {
900 decisions: Vec::new(),
901 records: vec![record],
902 drop_records: vec![drop_record],
903 dropped_records: 1,
904 },
905 &[],
906 );
907
908 assert!(!result.success);
909 let metadata = result
910 .metadata
911 .expect("usage metadata on failed tool result");
912 let batch = crate::cost_status::child_usage_records_from_metadata(&metadata)
913 .expect("preferred routed batch");
914 assert_eq!(batch.dropped_records, 1);
915 assert_eq!(batch.records.len(), 1);
916 assert_eq!(batch.drop_records.len(), 1);
917 assert_eq!(batch.records[0].usage.route, route);
918 assert_eq!(batch.records[0].usage.usage, usage);
919 assert_eq!(batch.drop_records[0].route, route);
920 }
921
922 #[test]
923 fn rlm_eval_requires_approval() {
924 // Evaluation requires approval; concrete open inputs are classified below.
925 let canonical = RlmTool::new("rlm");
926 assert!(
927 canonical
928 .capabilities()
929 .contains(&ToolCapability::RequiresApproval)
930 );
931 assert_eq!(
932 canonical.approval_requirement_for(&json!({"action": "eval"})),
933 ApprovalRequirement::Required
934 );
935 assert_eq!(
936 canonical.approval_requirement_for(&json!({"action": "open"})),
937 ApprovalRequirement::Auto
938 );
939 assert_eq!(
940 canonical.approval_requirement_for(&json!({"action": "session_objects"})),
941 ApprovalRequirement::Auto
942 );
943 }
944
945 #[test]
946 fn rlm_open_requires_outbound_approval_but_keeps_local_reads_automatic() {
947 let tool = RlmTool::new("rlm");
948 assert_eq!(tool.approval_requirement(), ApprovalRequirement::Required);
949 for source in [
950 json!({"url": "https://example.com/document"}),
951 json!({"url": " https://example.com/document ", "content": ""}),
952 ] {
953 let mut input = source;
954 input["action"] = json!("open");
955 assert_eq!(
956 tool.approval_requirement_for(&input),
957 ApprovalRequirement::Required
958 );
959 }
960 for source in [
961 json!({"content": "local fixture"}),
962 json!({"file_path": "fixture.txt"}),
963 json!({"session_object": "fixture-object"}),
964 json!({"content": "local fixture", "url": " "}),
965 ] {
966 let mut input = source;
967 input["action"] = json!("open");
968 assert_eq!(
969 tool.approval_requirement_for(&input),
970 ApprovalRequirement::Auto
971 );
972 }
973 }
974
975 #[test]
976 fn read_only_and_parallel_flags_follow_the_action() {
977 let canonical = RlmTool::new("rlm");
978 assert!(canonical.is_read_only_for(&json!({"action": "session_objects"})));
979 assert!(canonical.supports_parallel_for(&json!({"action": "session_objects"})));
980 assert!(!canonical.supports_parallel_for(&json!({"action": "eval"})));
981 assert!(canonical.is_read_only_for(&json!({"action": "configure"})));
982 assert!(!canonical.is_read_only_for(&json!({"action": "open"})));
983 assert!(!canonical.is_read_only_for(&json!({"action": "eval"})));
984 }
985
986 #[test]
987 fn canonical_rejects_unknown_or_missing_action() {
988 let tool = RlmTool::new("rlm");
989 let err = tool
990 .resolve_action(&json!({}))
991 .expect_err("missing action must fail");
992 assert!(err.to_string().contains("missing `action`"));
993 let err = tool
994 .resolve_action(&json!({"action": "explode"}))
995 .expect_err("unknown action must fail");
996 assert!(err.to_string().contains("invalid action"));
997 }
998
999 #[test]
1000 fn rlm_open_source_count_ignores_empty_string_defaults() {
1001 assert_eq!(
1002 rlm_open_source_count(
1003 &json!({"name": "url-doc", "file_path": "", "content": "", "url": "https://example.com/doc"})
1004 ),
1005 1
1006 );
1007 assert_eq!(
1008 rlm_open_source_count(
1009 &json!({"name": "inline-doc", "file_path": "", "content": "body", "url": ""})
1010 ),
1011 1
1012 );
1013 assert_eq!(
1014 rlm_open_source_count(&json!({"content": "body", "url": "https://example.com/doc"})),
1015 2
1016 );
1017 assert_eq!(
1018 rlm_open_source_count(
1019 &json!({"content": "body", "session_object": "session://active/system_prompt"})
1020 ),
1021 2
1022 );
1023 }
1024
1025 #[tokio::test]
1026 async fn rlm_session_objects_lists_active_prompt_object() {
1027 let ctx = ctx_with_session_objects();
1028 let result = RlmTool::new("rlm")
1029 .execute(json!({"action": "session_objects"}), &ctx)
1030 .await
1031 .expect("list session objects");
1032 let body: Value = serde_json::from_str(&result.content).expect("json");
1033 let objects = body["objects"].as_array().expect("objects array");
1034
1035 assert!(objects.iter().any(|object| {
1036 object["id"] == "session://active/system_prompt" && object["kind"] == "system_prompt"
1037 }));
1038 assert!(objects.iter().any(|object| {
1039 object["id"] == "session://active/messages/0" && object["kind"] == "message"
1040 }));
1041 }
1042
1043 #[tokio::test]
1044 async fn rlm_open_loads_active_session_prompt_object() {
1045 let ctx = ctx_with_session_objects();
1046 let open = RlmTool::new("rlm")
1047 .execute(
1048 json!({"action": "open", "name": "active_prompt", "session_object": "session://active/system_prompt"}),
1049 &ctx,
1050 )
1051 .await
1052 .expect("open prompt object");
1053 let open_json: Value = serde_json::from_str(&open.content).expect("open json");
1054 assert_eq!(open_json["type"], "session_object:system_prompt");
1055 assert!(
1056 open_json["preview_500"]
1057 .as_str()
1058 .unwrap()
1059 .contains("CodeWhale")
1060 );
1061
1062 RlmTool::new("rlm")
1063 .execute(json!({"action": "close", "name": "active_prompt"}), &ctx)
1064 .await
1065 .expect("close");
1066 }
1067
1068 #[tokio::test]
1069 async fn rlm_open_loads_transcript_message_object() {
1070 let ctx = ctx_with_session_objects();
1071 let open = RlmTool::new("rlm")
1072 .execute(
1073 json!({"action": "open", "name": "first_message", "session_object": "session://active/messages/0"}),
1074 &ctx,
1075 )
1076 .await
1077 .expect("open transcript slice");
1078 let open_json: Value = serde_json::from_str(&open.content).expect("open json");
1079 assert_eq!(open_json["type"], "session_object:message");
1080 assert!(
1081 open_json["preview_500"]
1082 .as_str()
1083 .unwrap()
1084 .contains("RLM surface")
1085 );
1086
1087 RlmTool::new("rlm")
1088 .execute(json!({"action": "close", "name": "first_message"}), &ctx)
1089 .await
1090 .expect("close");
1091 }
1092
1093 #[tokio::test]
1094 async fn rlm_open_ignores_blank_source_defaults_from_schema_fillers() {
1095 let ctx = ctx();
1096 RlmTool::new("rlm")
1097 .execute(
1098 json!({"action": "open", "name": "blank-defaults", "file_path": "", "content": "body", "url": ""}),
1099 &ctx,
1100 )
1101 .await
1102 .expect("open with blank sibling source fields");
1103
1104 RlmTool::new("rlm")
1105 .execute(json!({"action": "close", "name": "blank-defaults"}), &ctx)
1106 .await
1107 .expect("close");
1108 }
1109
1110 #[tokio::test]
1111 async fn rlm_open_misnamed_source_field_gets_did_you_mean_hint() {
1112 // #2655: a wrong source field name yields actionable guidance, not just
1113 // the canonical "provide exactly one" message.
1114 let ctx = ctx();
1115 let err = RlmTool::new("rlm")
1116 .execute(
1117 json!({"action": "open", "name": "doc", "prompt": "summarize this"}),
1118 &ctx,
1119 )
1120 .await
1121 .expect_err("misnamed source field should fail");
1122 let msg = err.to_string();
1123 assert!(msg.contains("file_path"), "names the real fields: {msg}");
1124 assert!(
1125 msg.contains("`url`, or `session_object`"),
1126 "names session_object in the valid source field list: {msg}"
1127 );
1128 assert!(msg.contains("prompt"), "echoes the wrong field: {msg}");
1129 }
1130
1131 #[tokio::test]
1132 async fn rlm_eval_missing_code_explains_raw_python() {
1133 // #2655: the missing-code error should teach the tool, with an example.
1134 let ctx = ctx();
1135 let err = RlmTool::new("rlm")
1136 .execute(json!({"action": "eval", "name": "doc"}), &ctx)
1137 .await
1138 .expect_err("missing code should fail");
1139 let msg = err.to_string();
1140 assert!(msg.contains("raw Python"), "explains it runs Python: {msg}");
1141 assert!(
1142 msg.contains("print(len(content))") || msg.contains("FINAL"),
1143 "includes an example: {msg}"
1144 );
1145 }
1146
1147 #[test]
1148 fn rlm_eval_schema_names_the_runtime_content_variable() {
1149 let schema = RlmTool::new("rlm").input_schema();
1150 let description = schema["properties"]["code"]["description"]
1151 .as_str()
1152 .expect("rlm_eval code description");
1153
1154 assert!(description.contains("`content`"));
1155 assert!(description.contains("print(len(content))"));
1156 assert!(!description.contains("SOURCE"));
1157 }
1158
1159 #[tokio::test]
1160 async fn nested_rlm_receipts_survive_tool_result_save_and_reopen_even_on_kernel_failure() {
1161 use wiremock::matchers::method;
1162 use wiremock::{Mock, MockServer, ResponseTemplate};
1163 let server = MockServer::start().await;
1164 Mock::given(method("POST")).respond_with(ResponseTemplate::new(200).set_body_json(json!({
1165 "id": "nested-model-response", "object": "chat.completion",
1166 "model": "deepseek-v4-flash",
1167 "choices": [{"index": 0, "message": {"role": "assistant",
1168 "content": "```repl\nFINAL('durable nested answer')\n```"}, "finish_reason": "stop"}],
1169 "usage": {"prompt_tokens": 7, "completion_tokens": 9, "total_tokens": 16}
1170 }))).expect(2).mount(&server).await;
1171 let mut config = crate::core::engine::tests::rlm_host::fixture_config("deepseek-v4-flash");
1172 let identity = config.active_provider_identity().unwrap();
1173 config.provider_config_for_mut(&identity).unwrap().base_url = Some(server.uri());
1174 let client = Arc::new(crate::client::CodewhaleClient::new(&config).unwrap());
1175 let tool = RlmTool::new("rlm");
1176 let temp = tempfile::tempdir().unwrap();
1177 let mut context = ToolContext::new(temp.path());
1178 context.execution.nested_call_gate =
1179 Some(crate::tools::codemode::NestedCallGate::admitting_for_test());
1180 context = crate::core::engine::tests::rlm_host::context_for_replies(
1181 &config,
1182 "deepseek-v4-flash",
1183 &context,
1184 client,
1185 );
1186 tool.execute(
1187 json!({"action": "open", "name": "receipts", "content": "fixture context"}),
1188 &context,
1189 )
1190 .await
1191 .unwrap();
1192 for (failed, code) in [
1193 (false, "print(rlm_query('nested context'))"),
1194 (true, "print(rlm_query('nested context')); _os._exit(2)"),
1195 ] {
1196 let result = tool
1197 .execute(
1198 json!({"action": "eval", "name": "receipts", "code": code}),
1199 &context,
1200 )
1201 .await
1202 .unwrap();
1203 assert_eq!(result.success, !failed);
1204 let output: Value = serde_json::from_str(&result.content).unwrap();
1205 let events = output["nested_events"]
1206 .as_array()
1207 .expect("retained nested events");
1208 assert_eq!(
1209 events
1210 .iter()
1211 .filter(|entry| entry["kind"] == "code")
1212 .count(),
1213 1
1214 );
1215 assert!(events.iter().any(|entry| {
1216 entry["content"]
1217 .as_str()
1218 .is_some_and(|line| line.contains("FINAL('durable nested answer')"))
1219 }));
1220 assert!(events.iter().any(|entry| {
1221 entry["content"]
1222 .as_str()
1223 .is_some_and(|line| line.contains("RLM finished: Final"))
1224 }));
1225 let messages = vec![
1226 Message {
1227 role: Role::Assistant,
1228 content: vec![ContentBlock::ToolUse {
1229 id: "rlm-call".into(),
1230 name: "rlm".into(),
1231 input: json!({"action": "eval", "name": "receipts", "code": code}),
1232 execution_id: Some("rlm-execution".into()),
1233 caller: None,
1234 thought_signature: None,
1235 }],
1236 },
1237 Message {
1238 role: Role::User,
1239 content: vec![ContentBlock::ToolResult {
1240 tool_use_id: "rlm-call".into(),
1241 execution_id: Some("rlm-execution".into()),
1242 content: result.content,
1243 is_error: Some(failed),
1244 content_blocks: None,
1245 }],
1246 },
1247 ];
1248 let manager =
1249 crate::session_manager::SessionManager::new(temp.path().join("sessions")).unwrap();
1250 let saved = crate::session_manager::create_saved_session(
1251 &messages,
1252 "deepseek-v4-flash",
1253 temp.path(),
1254 16,
1255 None,
1256 );
1257 manager.save_session(&saved).unwrap();
1258 let reopened = manager.load_session(&saved.metadata.id).unwrap();
1259 let ContentBlock::ToolResult { content, .. } = &reopened.messages[1].content[0] else {
1260 panic!("saved tool result");
1261 };
1262 let replay: Value = serde_json::from_str(content).unwrap();
1263 assert_eq!(&replay["nested_events"], &output["nested_events"]);
1264 }
1265 assert!(
1266 get_session(&context, "receipts")
1267 .await
1268 .unwrap()
1269 .lock()
1270 .await
1271 .kernel
1272 .is_none(),
1273 "a failed interpreter must not be reused"
1274 );
1275 }
1276
1277 #[tokio::test]
1278 async fn persistent_open_obeys_original_cancel_and_deadline_without_installing_a_kernel() {
1279 let temp = tempfile::tempdir().unwrap();
1280 let tool = RlmTool::new("rlm");
1281 for cancelled in [true, false] {
1282 let mut context = ToolContext::new(temp.path());
1283 let cancel = tokio_util::sync::CancellationToken::new();
1284 context.cancel_token = Some(cancel.clone());
1285 context.turn_deadline =
1286 (!cancelled).then(|| tokio::time::Instant::now() + Duration::from_millis(40));
1287 let sessions = context.runtime.rlm_sessions.lock().await;
1288 let input = json!({"action": "open", "name": "never-installed", "content": "fixture"});
1289 let mut open = tool.execute(input, &context);
1290 assert!(
1291 tokio::time::timeout(Duration::from_millis(10), &mut open)
1292 .await
1293 .is_err()
1294 );
1295 if cancelled {
1296 cancel.cancel();
1297 }
1298 let error = tokio::time::timeout(Duration::from_secs(1), &mut open)
1299 .await
1300 .expect("original cancellation and deadline both release a contended open")
1301 .unwrap_err();
1302 if cancelled {
1303 assert!(matches!(error, ToolError::Cancelled { .. }));
1304 } else {
1305 assert!(
1306 error
1307 .to_string()
1308 .contains("deadline exhausted opening context")
1309 );
1310 }
1311 assert!(
1312 sessions.is_empty(),
1313 "no interpreter is installed while admission waits"
1314 );
1315 drop(open);
1316 drop(sessions);
1317 assert!(context.runtime.rlm_sessions.lock().await.is_empty());
1318 }
1319 }
1320
1321 #[tokio::test]
1322 async fn parent_deadline_bounds_rlm_session_lock_waits() {
1323 let temp = tempfile::tempdir().unwrap();
1324 let mut context = ToolContext::new(temp.path());
1325 let tool = RlmTool::new("rlm");
1326 tool.execute(
1327 json!({"action": "open", "name": "contended", "content": "fixture"}),
1328 &context,
1329 )
1330 .await
1331 .unwrap();
1332 let session = get_session(&context, "contended").await.unwrap();
1333 let marker = temp.path().join("must-not-exist");
1334 let code = format!(
1335 "open({}, 'w').write('ran')",
1336 serde_json::to_string(&marker.to_string_lossy()).unwrap()
1337 );
1338 for registry_locked in [true, false] {
1339 context.turn_deadline = Some(tokio::time::Instant::now() + Duration::from_millis(50));
1340 let registry_guard = if registry_locked {
1341 Some(context.runtime.rlm_sessions.lock().await)
1342 } else {
1343 None
1344 };
1345 let session_guard = if registry_locked {
1346 None
1347 } else {
1348 Some(session.lock().await)
1349 };
1350 let error = tokio::time::timeout(
1351 Duration::from_secs(2),
1352 tool.execute(
1353 json!({"action": "eval", "name": "contended", "code": code}),
1354 &context,
1355 ),
1356 )
1357 .await
1358 .expect("lock waits must obey the parent deadline")
1359 .unwrap_err();
1360 assert!(
1361 error
1362 .to_string()
1363 .contains("deadline exhausted waiting for context")
1364 );
1365 assert!(!marker.exists());
1366 drop(session_guard);
1367 drop(registry_guard);
1368 }
1369 tool.execute(json!({"action": "close", "name": "contended"}), &context)
1370 .await
1371 .unwrap();
1372 }
1373
1374 #[tokio::test]
1375 async fn expired_parent_deadline_prevents_rlm_python_side_effects() {
1376 let temp = tempfile::tempdir().unwrap();
1377 let mut context = ToolContext::new(temp.path());
1378 let tool = RlmTool::new("rlm");
1379 tool.execute(
1380 json!({"action": "open", "name": "expired", "content": "fixture"}),
1381 &context,
1382 )
1383 .await
1384 .unwrap();
1385 context.turn_deadline = Some(tokio::time::Instant::now());
1386 let marker = temp.path().join("must-not-exist");
1387 let code = format!(
1388 "open({}, 'w').write('ran')",
1389 serde_json::to_string(&marker.to_string_lossy()).unwrap()
1390 );
1391 let error = tool
1392 .execute(
1393 json!({"action": "eval", "name": "expired", "code": code}),
1394 &context,
1395 )
1396 .await
1397 .unwrap_err();
1398 assert!(error.to_string().contains("deadline exhausted"));
1399 assert!(!marker.exists());
1400 tool.execute(json!({"action": "close", "name": "expired"}), &context)
1401 .await
1402 .unwrap();
1403 }
1404
1405 #[tokio::test]
1406 async fn rlm_canonical_action_routing_runs_full_lifecycle() {
1407 // The visible surface: one `rlm` tool, action-parameterized.
1408 let ctx = ctx();
1409 let tool = RlmTool::new("rlm");
1410 tool.execute(
1411 json!({"action": "open", "name": "canonical", "content": "body"}),
1412 &ctx,
1413 )
1414 .await
1415 .expect("open via canonical action");
1416
1417 let eval = tool
1418 .execute(
1419 json!({"action": "eval", "name": "canonical", "code": "print('ok')"}),
1420 &ctx,
1421 )
1422 .await
1423 .expect("eval via canonical action");
1424 let eval_json: Value = serde_json::from_str(&eval.content).expect("eval json");
1425 let stdout_preview = eval_json["stdout_preview"]
1426 .as_str()
1427 .expect("stdout_preview")
1428 .replace("\r\n", "\n");
1429 assert_eq!(stdout_preview, "ok\n");
1430
1431 let close = tool
1432 .execute(json!({"action": "close", "name": "canonical"}), &ctx)
1433 .await
1434 .expect("close via canonical action");
1435 assert!(close.content.contains("canonical"));
1436 }
1437
1438 #[tokio::test]
1439 async fn rlm_eval_final_returns_handle() {
1440 let ctx = ctx();
1441 RlmTool::new("rlm")
1442 .execute(
1443 json!({"action": "open", "name": "finals", "content": "body"}),
1444 &ctx,
1445 )
1446 .await
1447 .expect("open");
1448
1449 let eval = RlmTool::new("rlm")
1450 .execute(
1451 json!({"action": "eval", "name": "finals", "code": "finalize('done', confidence=0.8)"}),
1452 &ctx,
1453 )
1454 .await
1455 .expect("eval");
1456 let eval_json: Value = serde_json::from_str(&eval.content).expect("eval json");
1457 assert_eq!(eval_json["final"]["kind"], "var_handle");
1458 assert_eq!(eval_json["final"]["name"], "final_1");
1459 assert_eq!(eval_json["confidence"], 0.8);
1460
1461 RlmTool::new("rlm")
1462 .execute(json!({"action": "close", "name": "finals"}), &ctx)
1463 .await
1464 .expect("close");
1465 }
1466
1467 #[tokio::test]
1468 async fn rlm_eval_final_preserves_json_handle() {
1469 let ctx = ctx();
1470 RlmTool::new("rlm")
1471 .execute(
1472 json!({"action": "open", "name": "json-final", "content": "body"}),
1473 &ctx,
1474 )
1475 .await
1476 .expect("open");
1477
1478 let eval = RlmTool::new("rlm")
1479 .execute(
1480 json!({"action": "eval", "name": "json-final", "code": "finalize({'answer': 42, 'items': ['a', 'b']})"}),
1481 &ctx,
1482 )
1483 .await
1484 .expect("eval");
1485 let eval_json: Value = serde_json::from_str(&eval.content).expect("eval json");
1486 assert_eq!(eval_json["final"]["kind"], "var_handle");
1487 assert_eq!(eval_json["final"]["type"], "dict");
1488 assert_eq!(eval_json["final"]["length"], 2);
1489
1490 let read = HandleReadTool
1491 .execute(
1492 json!({"handle": eval_json["final"].clone(), "jsonpath": "$.items[*]"}),
1493 &ctx,
1494 )
1495 .await
1496 .expect("read final handle");
1497 let read_json: Value = serde_json::from_str(&read.content).expect("read json");
1498 assert_eq!(read_json["matches"], json!(["a", "b"]));
1499
1500 RlmTool::new("rlm")
1501 .execute(json!({"action": "close", "name": "json-final"}), &ctx)
1502 .await
1503 .expect("close");
1504 }
1505
1506 #[tokio::test]
1507 async fn rlm_configure_metadata_omits_stdout() {
1508 let ctx = ctx();
1509 RlmTool::new("rlm")
1510 .execute(
1511 json!({"action": "open", "name": "quiet", "content": "body"}),
1512 &ctx,
1513 )
1514 .await
1515 .expect("open");
1516 RlmTool::new("rlm")
1517 .execute(
1518 json!({"action": "configure", "name": "quiet", "output_feedback": "metadata", "sub_rlm_max_depth": 99}),
1519 &ctx,
1520 )
1521 .await
1522 .expect("configure");
1523
1524 let eval = RlmTool::new("rlm")
1525 .execute(
1526 json!({"action": "eval", "name": "quiet", "code": "print('hidden')"}),
1527 &ctx,
1528 )
1529 .await
1530 .expect("eval");
1531 let eval_json: Value = serde_json::from_str(&eval.content).expect("eval json");
1532 assert!(eval_json.get("stdout_preview").is_none());
1533
1534 RlmTool::new("rlm")
1535 .execute(json!({"action": "close", "name": "quiet"}), &ctx)
1536 .await
1537 .expect("close");
1538 }
1539 #[tokio::test]
1540 async fn shared_session_refusal_is_atomic_and_persistent_kernel_owns_no_caller() {
1541 let workspace = tempfile::tempdir().unwrap();
1542 let base = ToolContext::new(workspace.path());
1543 let model = "captured-kernel-model";
1544 let config = crate::core::engine::tests::rlm_host::fixture_config(model);
1545 let mock = Arc::new(crate::llm_client::mock::MockLlmClient::new(Vec::new()));
1546 let context = crate::core::engine::tests::rlm_host::context_for_replies(
1547 &config,
1548 model,
1549 &base,
1550 mock.clone(),
1551 );
1552 let weak_caller = Arc::downgrade(context.rlm_caller.as_ref().unwrap());
1553 let sessions = context.runtime.rlm_sessions.clone();
1554 let tool = RlmTool::new("rlm");
1555 tool.execute(
1556 json!({"action":"open", "name":"lifetime", "content":"long local context"}),
1557 &context,
1558 )
1559 .await
1560 .unwrap();
1561 let before = serde_json::to_value(
1562 get_session(&context, "lifetime")
1563 .await
1564 .unwrap()
1565 .lock()
1566 .await
1567 .config
1568 .clone(),
1569 )
1570 .unwrap();
1571 let error = tool.execute(json!({"action":"configure", "name":"lifetime", "share_session":true, "sub_query_timeout_secs":1, "output_feedback":"metadata"}), &context).await.unwrap_err();
1572 assert!(
1573 error
1574 .to_string()
1575 .contains("share_session=true is unsupported")
1576 );
1577 let after = serde_json::to_value(
1578 get_session(&context, "lifetime")
1579 .await
1580 .unwrap()
1581 .lock()
1582 .await
1583 .config
1584 .clone(),
1585 )
1586 .unwrap();
1587 assert_eq!(
1588 before, after,
1589 "unsupported session authority refuses before any settings change"
1590 );
1591 drop(context);
1592 assert!(
1593 weak_caller.upgrade().is_none(),
1594 "persistent kernels must not retain model authority or their borrowed callback"
1595 );
1596 assert_eq!(
1597 sessions.lock().await.len(),
1598 1,
1599 "the actual kernel map is still live"
1600 );
1601 assert_eq!(mock.call_count(), 0);
1602 sessions.lock().await.clear();
1603 }
1604 #[tokio::test]
1605 async fn persistent_eval_drop_and_original_cancel_kill_running_kernel_without_retaining_caller()
1606 {
1607 for cancel_original in [false, true] {
1608 let workspace = tempfile::tempdir().unwrap();
1609 let base = ToolContext::new(workspace.path());
1610 let model = "captured-kernel-model";
1611 let config = crate::core::engine::tests::rlm_host::fixture_config(model);
1612 let mock = Arc::new(crate::llm_client::mock::MockLlmClient::new(Vec::new()));
1613 let context = crate::core::engine::tests::rlm_host::context_for_replies(
1614 &config,
1615 model,
1616 &base,
1617 mock.clone(),
1618 );
1619 let weak_caller = Arc::downgrade(context.rlm_caller.as_ref().unwrap());
1620 let cancel = context.cancel_token.as_ref().unwrap().clone();
1621 let tool = RlmTool::new("rlm");
1622 tool.execute(
1623 json!({"action":"open", "name":"running", "content":"local long context"}),
1624 &context,
1625 )
1626 .await
1627 .unwrap();
1628 let marker = workspace.path().join("started.txt");
1629 let release = workspace.path().join("release.txt");
1630 let effect = workspace.path().join("must-not-run.txt");
1631 let code = format!(
1632 r#"import pathlib, time
1633 started = pathlib.Path({})
1634 release = pathlib.Path({})
1635 started.touch()
1636 while not release.exists():
1637 time.sleep(0.01)
1638 pathlib.Path({}).write_text('effect after cancellation')"#,
1639 serde_json::to_string(&marker.to_string_lossy()).unwrap(),
1640 serde_json::to_string(&release.to_string_lossy()).unwrap(),
1641 serde_json::to_string(&effect.to_string_lossy()).unwrap(),
1642 );
1643 let input = json!({"action":"eval", "name":"running", "code":code});
1644 let mut call = Box::pin(tool.execute(input, &context));
1645 tokio::time::timeout(Duration::from_secs(30), async {
1646 tokio::select! {
1647 result = &mut call => panic!("running eval finished before its marker: {result:?}"),
1648 () = async {
1649 while !marker.exists() {
1650 tokio::time::sleep(Duration::from_millis(5)).await;
1651 }
1652 } => {},
1653 }
1654 }).await.expect("actual persistent Python round starts");
1655 if cancel_original {
1656 cancel.cancel();
1657 let result = tokio::time::timeout(Duration::from_secs(1), &mut call)
1658 .await
1659 .expect("origin cancellation hands back promptly")
1660 .unwrap();
1661 assert!(!result.success);
1662 assert!(result.content.contains("cancelled by its originating turn"));
1663 }
1664 drop(call);
1665 let session = get_session(&context, "running").await.unwrap();
1666 assert!(session.lock().await.kernel.is_none());
1667 drop(context);
1668 assert!(weak_caller.upgrade().is_none());
1669 std::fs::write(&release, b"continue").unwrap();
1670 tokio::time::sleep(Duration::from_millis(1200)).await;
1671 assert!(
1672 !effect.exists(),
1673 "unknown Python code cannot outlive dropped/cancelled eval"
1674 );
1675 assert_eq!(mock.call_count(), 0);
1676 }
1677 }
1678
1679 #[tokio::test]
1680 async fn rlm_open_refuses_read_only_root_and_outside_hardlink() {
1681 let workspace = tempfile::tempdir().expect("workspace");
1682 let ro_root = tempfile::tempdir().expect("read-only root");
1683 let ro_file = ro_root.path().join("ro.txt");
1684 std::fs::write(&ro_file, "read-only body\n").expect("write ro");
1685 let ro_canon = ro_root.path().canonicalize().expect("canon ro");
1686 let ctx = ToolContext::new(workspace.path()).with_read_only_roots(vec![ro_canon]);
1687 let ro_err = RlmTool::new("rlm")
1688 .execute(
1689 json!({"action": "open", "name": "ro", "file_path": ro_file.to_string_lossy()}),
1690 &ctx,
1691 )
1692 .await
1693 .expect_err("read_only_roots must not be admitted by rlm_open");
1694 assert!(matches!(ro_err, ToolError::PathEscape { .. }), "{ro_err:?}");
1695
1696 #[cfg(unix)]
1697 {
1698 let outside = tempfile::tempdir().expect("outside");
1699 let original = outside.path().join("orig.txt");
1700 let linked = outside.path().join("alias.txt");
1701 std::fs::write(&original, "secret\n").expect("write orig");
1702 std::fs::hard_link(&original, &linked).expect("hardlink");
1703 let trusted_ctx = ToolContext::new(workspace.path()).with_trust_mode(true);
1704 let link_err = RlmTool::new("rlm")
1705 .execute(
1706 json!({"action": "open", "name": "hl", "file_path": linked.to_string_lossy()}),
1707 &trusted_ctx,
1708 )
1709 .await
1710 .expect_err("outside hardlink must be refused by verified-handle reader");
1711 assert!(
1712 matches!(link_err, ToolError::PermissionDenied { .. }),
1713 "{link_err:?}"
1714 );
1715 }
1716 }
1717 }
1718
1718 lines RUST