返回 CodeWhale
handle.rs
根目录 / crates / engine / src / tools / handle.rs
1 //! Symbolic handle storage and bounded reads.
2 //!
3 //! `var_handle` is the shared protocol that lets expensive environments
4 //! (RLM sessions, sub-agent transcripts, large artifacts) hand the parent a
5 //! small symbolic reference instead of copying the whole payload into the
6 //! parent transcript.
7
8 use std::collections::HashMap;
9 use std::sync::Arc;
10
11 use async_trait::async_trait;
12 use serde::{Deserialize, Serialize};
13 use serde_json::{Value, json};
14 use tokio::sync::Mutex;
15
16 use crate::tools::spec::{
17 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
18 };
19
20 /// Ceiling on everything the handle store holds in memory (#5472 findings 4-5).
21 ///
22 /// Handles exist so an expensive payload never enters the parent transcript,
23 /// but the payload still lives here. Eviction was per-session only
24 /// (`evict_session`), driven by sub-agent retirement — so RLM sessions, whose
25 /// producers have no such lifecycle, had no eviction path at all, and a long
26 /// session accumulated every handle it ever minted. Past this budget the
27 /// least-recently-inserted records are dropped; `handle_read` on an evicted
28 /// handle already reports "not found" rather than inventing content.
29 const HANDLE_STORE_MAX_BYTES: usize = 64 * 1024 * 1024;
30
31 const DEFAULT_MAX_CHARS: usize = 12_000;
32 const HARD_MAX_CHARS: usize = 50_000;
33 const REPR_PREVIEW_CHARS: usize = 160;
34 pub(super) const JSONPATH_MAX_PATH_BYTES: usize = 4096;
35 pub(super) const JSONPATH_MAX_BYTES: usize = 1024 * 1024;
36 const JSONPATH_MAX_MATCHES: usize = 1024;
37 const JSONPATH_MAX_STEPS: usize = 128;
38
39 pub type SharedHandleStore = Arc<Mutex<HandleStore>>;
40
41 #[must_use]
42 pub fn new_shared_handle_store() -> SharedHandleStore {
43 Arc::new(Mutex::new(HandleStore::default()))
44 }
45
46 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
47 pub struct VarHandle {
48 pub kind: String,
49 pub session_id: String,
50 pub name: String,
51 #[serde(rename = "type")]
52 pub type_name: String,
53 pub length: usize,
54 pub repr_preview: String,
55 pub sha256: String,
56 }
57
58 impl VarHandle {
59 #[must_use]
60 pub fn key(&self) -> HandleKey {
61 HandleKey {
62 session_id: self.session_id.clone(),
63 name: self.name.clone(),
64 }
65 }
66 }
67
68 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
69 pub struct HandleKey {
70 pub session_id: String,
71 pub name: String,
72 }
73
74 #[derive(Debug, Clone)]
75 pub struct HandleRecord {
76 pub handle: VarHandle,
77 pub value: HandleValue,
78 /// Insertion order, for least-recently-inserted eviction under the store's
79 /// byte budget. `HashMap` has no order of its own.
80 seq: u64,
81 /// Payload size, measured once at insert so the budget sweep does not
82 /// re-serialize every JSON value it inspects.
83 bytes: usize,
84 }
85
86 #[derive(Debug, Clone)]
87 pub enum HandleValue {
88 Text(String),
89 Json(Value),
90 }
91
92 impl HandleValue {
93 fn length(&self) -> usize {
94 match self {
95 Self::Text(text) => text.chars().count(),
96 Self::Json(Value::Array(items)) => items.len(),
97 Self::Json(Value::Object(map)) => map.len(),
98 Self::Json(value) => value.to_string().chars().count(),
99 }
100 }
101
102 fn type_name(&self) -> String {
103 match self {
104 Self::Text(_) => "str".to_string(),
105 Self::Json(Value::Array(_)) => "list".to_string(),
106 Self::Json(Value::Object(_)) => "dict".to_string(),
107 Self::Json(Value::String(_)) => "str".to_string(),
108 Self::Json(Value::Bool(_)) => "bool".to_string(),
109 Self::Json(Value::Number(_)) => "number".to_string(),
110 Self::Json(Value::Null) => "null".to_string(),
111 }
112 }
113
114 fn stable_bytes(&self) -> Vec<u8> {
115 match self {
116 Self::Text(text) => text.as_bytes().to_vec(),
117 Self::Json(value) => serde_json::to_vec(value).unwrap_or_default(),
118 }
119 }
120
121 fn repr_preview(&self) -> String {
122 match self {
123 Self::Text(text) => truncate_chars(text, REPR_PREVIEW_CHARS),
124 Self::Json(value) => truncate_chars(&value.to_string(), REPR_PREVIEW_CHARS),
125 }
126 }
127 }
128
129 #[derive(Debug, Default)]
130 pub struct HandleStore {
131 records: HashMap<HandleKey, HandleRecord>,
132 next_seq: u64,
133 retained_bytes: usize,
134 }
135
136 impl HandleStore {
137 #[must_use]
138 pub fn insert_text(
139 &mut self,
140 session_id: impl Into<String>,
141 name: impl Into<String>,
142 text: impl Into<String>,
143 ) -> VarHandle {
144 self.insert(session_id, name, HandleValue::Text(text.into()))
145 }
146
147 #[must_use]
148 pub fn insert_json(
149 &mut self,
150 session_id: impl Into<String>,
151 name: impl Into<String>,
152 value: Value,
153 ) -> VarHandle {
154 self.insert(session_id, name, HandleValue::Json(value))
155 }
156
157 #[must_use]
158 pub fn get(&self, handle: &VarHandle) -> Option<&HandleRecord> {
159 self.records.get(&handle.key())
160 }
161
162 /// Remove all handles for `session_id`. Called when an agent's records
163 /// are retired so resident transcript payloads are freed without waiting
164 /// for a full session reset (#3885).
165 pub fn evict_session(&mut self, session_id: &str) {
166 let mut freed = 0usize;
167 self.records.retain(|key, record| {
168 if key.session_id == session_id {
169 freed = freed.saturating_add(record.bytes);
170 false
171 } else {
172 true
173 }
174 });
175 self.retained_bytes = self.retained_bytes.saturating_sub(freed);
176 }
177
178 fn insert(
179 &mut self,
180 session_id: impl Into<String>,
181 name: impl Into<String>,
182 value: HandleValue,
183 ) -> VarHandle {
184 let session_id = session_id.into();
185 let name = name.into();
186 let handle = VarHandle {
187 kind: "var_handle".to_string(),
188 session_id: session_id.clone(),
189 name: name.clone(),
190 type_name: value.type_name(),
191 length: value.length(),
192 repr_preview: value.repr_preview(),
193 sha256: sha256_hex(&value.stable_bytes()),
194 };
195 let key = HandleKey { session_id, name };
196 let bytes = value.stable_bytes().len();
197 let seq = self.next_seq;
198 self.next_seq = self.next_seq.wrapping_add(1);
199 if let Some(replaced) = self.records.insert(
200 key,
201 HandleRecord {
202 handle: handle.clone(),
203 value,
204 seq,
205 bytes,
206 },
207 ) {
208 self.retained_bytes = self.retained_bytes.saturating_sub(replaced.bytes);
209 }
210 self.retained_bytes = self.retained_bytes.saturating_add(bytes);
211 self.enforce_byte_budget();
212 handle
213 }
214
215 /// Drop least-recently-inserted records until the store fits its budget.
216 fn enforce_byte_budget(&mut self) {
217 if self.retained_bytes <= HANDLE_STORE_MAX_BYTES {
218 return;
219 }
220 let mut oldest_first: Vec<(u64, HandleKey)> = self
221 .records
222 .iter()
223 .map(|(key, record)| (record.seq, key.clone()))
224 .collect();
225 oldest_first.sort_unstable_by_key(|(seq, _)| *seq);
226 for (_, key) in oldest_first {
227 if self.retained_bytes <= HANDLE_STORE_MAX_BYTES {
228 break;
229 }
230 if let Some(removed) = self.records.remove(&key) {
231 self.retained_bytes = self.retained_bytes.saturating_sub(removed.bytes);
232 }
233 }
234 }
235
236 /// Bytes currently held across every session. Exercised from the
237 /// tests below; no production caller today.
238 #[must_use]
239 pub fn retained_bytes(&self) -> usize {
240 self.retained_bytes
241 }
242 }
243
244 pub struct HandleReadTool;
245
246 #[async_trait]
247 impl ToolSpec for HandleReadTool {
248 fn name(&self) -> &'static str {
249 "handle_read"
250 }
251
252 fn description(&self) -> &'static str {
253 "Read a bounded projection from a var_handle returned by tools such \
254 as RLM sessions or sub-agents. This does not read artifact ids \
255 (`art_...`), tool-call ids (`call_...`), SHA refs, or files; use \
256 retrieve_tool_result for spilled tool results/artifacts and \
257 `read` (path=...) for workspace files. Provide \
258 exactly one projection: `slice` for char/line slices, `range` for \
259 one-based line ranges, `count` for metadata counts, or `jsonpath` \
260 for a small JSON-path projection. This retrieves from the handle's \
261 backing environment instead of asking the parent transcript to hold \
262 the full payload."
263 }
264
265 fn input_schema(&self) -> Value {
266 json!({
267 "type": "object",
268 "required": ["handle"],
269 "properties": {
270 "handle": {
271 "description": "A var_handle object, or a compact `session_id/name` string. Not an `art_...`, `call_...`, SHA, or file path ref.",
272 "oneOf": [
273 {
274 "type": "object",
275 "required": ["kind", "session_id", "name"],
276 "properties": {
277 "kind": { "type": "string", "const": "var_handle" },
278 "session_id": { "type": "string" },
279 "name": { "type": "string" },
280 "type": { "type": "string" },
281 "length": { "type": "integer" },
282 "repr_preview": { "type": "string" },
283 "sha256": { "type": "string" }
284 }
285 },
286 { "type": "string" }
287 ]
288 },
289 "slice": {
290 "type": "object",
291 "description": "Zero-based half-open slice over chars or lines.",
292 "properties": {
293 "start": { "type": "integer", "minimum": 0 },
294 "end": { "type": "integer", "minimum": 0 },
295 "unit": { "type": "string", "enum": ["chars", "lines"], "default": "chars" }
296 }
297 },
298 "range": {
299 "type": "object",
300 "description": "One-based inclusive line range.",
301 "required": ["start", "end"],
302 "properties": {
303 "start": { "type": "integer", "minimum": 1 },
304 "end": { "type": "integer", "minimum": 1 }
305 }
306 },
307 "count": {
308 "type": "boolean",
309 "description": "Return counts for the handle payload."
310 },
311 "jsonpath": {
312 "type": "string",
313 "maxLength": JSONPATH_MAX_PATH_BYTES,
314 "description": "Small JSONPath subset: $, .field, [index], [*], and ['field']. Refuses paths over 4096 bytes, over 128 steps, over 1024 intermediate matches, or results over 1 MiB; narrow the path on refusal."
315 },
316 "introspect": {
317 "type": "boolean",
318 "description": "Return supported projections, size hints, and copy-pasteable examples for this handle."
319 },
320 "max_chars": {
321 "type": "integer",
322 "description": "Maximum characters to return in this projection. Defaults to 12000; hard-capped at 50000."
323 }
324 }
325 })
326 }
327
328 fn capabilities(&self) -> Vec<ToolCapability> {
329 vec![ToolCapability::ReadOnly]
330 }
331
332 fn approval_requirement(&self) -> ApprovalRequirement {
333 ApprovalRequirement::Auto
334 }
335
336 fn supports_parallel(&self) -> bool {
337 true
338 }
339
340 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
341 let handle = parse_handle(
342 input
343 .get("handle")
344 .ok_or_else(|| ToolError::missing_field("handle"))?,
345 )?;
346 let projection = parse_projection(&input)?;
347 let max_chars = input
348 .get("max_chars")
349 .and_then(Value::as_u64)
350 .map(|n| (n as usize).min(HARD_MAX_CHARS))
351 .unwrap_or(DEFAULT_MAX_CHARS);
352
353 let store = context.runtime.handle_store.lock().await;
354 let record = store.get(&handle).ok_or_else(|| {
355 ToolError::invalid_input(format!(
356 "handle_read: no payload found for handle {}/{}",
357 handle.session_id, handle.name
358 ))
359 })?;
360 if !handle.sha256.is_empty() && handle.sha256 != record.handle.sha256 {
361 return Err(ToolError::invalid_input(
362 "handle_read: handle sha256 does not match stored payload",
363 ));
364 }
365
366 let output = match projection {
367 Projection::Count => count_projection(record),
368 Projection::Slice { start, end, unit } => {
369 slice_projection(record, start, end, unit, max_chars)
370 }
371 Projection::Range { start, end } => {
372 line_range_projection(record, start, end, max_chars)
373 }
374 Projection::JsonPath(path) => jsonpath_projection(record, &path, max_chars)?,
375 Projection::Introspect => introspect_projection(record),
376 };
377
378 ToolResult::json(&output).map_err(|e| ToolError::execution_failed(e.to_string()))
379 }
380 }
381
382 #[derive(Debug, Clone, Copy)]
383 enum SliceUnit {
384 Chars,
385 Lines,
386 }
387
388 enum Projection {
389 Count,
390 Slice {
391 start: usize,
392 end: Option<usize>,
393 unit: SliceUnit,
394 },
395 Range {
396 start: usize,
397 end: usize,
398 },
399 JsonPath(String),
400 Introspect,
401 }
402
403 fn parse_handle(value: &Value) -> Result<VarHandle, ToolError> {
404 if let Some(raw) = value.as_str() {
405 if looks_like_tool_result_ref(raw) {
406 return Err(ToolError::invalid_input(
407 "handle_read only accepts var_handle objects or `session_id/name` strings. \
408 This looks like an artifact/tool-result ref; use `retrieve_tool_result` instead.",
409 ));
410 }
411 let Some((session_id, name)) = raw.rsplit_once('/') else {
412 return Err(ToolError::invalid_input(
413 "handle_read: string handles must use `session_id/name`. \
414 For `art_...`, `call_...`, SHA, or file refs, use `retrieve_tool_result`.",
415 ));
416 };
417 return Ok(VarHandle {
418 kind: "var_handle".to_string(),
419 session_id: session_id.to_string(),
420 name: name.to_string(),
421 type_name: String::new(),
422 length: 0,
423 repr_preview: String::new(),
424 sha256: String::new(),
425 });
426 }
427
428 let handle: VarHandle = serde_json::from_value(value.clone()).map_err(|e| {
429 ToolError::invalid_input(format!("handle_read: invalid var_handle object: {e}"))
430 })?;
431 if handle.kind != "var_handle" {
432 return Err(ToolError::invalid_input(
433 "handle_read: handle.kind must be `var_handle`",
434 ));
435 }
436 if handle.session_id.trim().is_empty() || handle.name.trim().is_empty() {
437 return Err(ToolError::invalid_input(
438 "handle_read: handle.session_id and handle.name must be non-empty",
439 ));
440 }
441 Ok(handle)
442 }
443
444 fn looks_like_tool_result_ref(raw: &str) -> bool {
445 let trimmed = raw.trim();
446 let sha_candidate = trimmed
447 .strip_prefix("sha:")
448 .or_else(|| trimmed.strip_prefix("sha_"))
449 .unwrap_or(trimmed);
450 trimmed.starts_with("art_")
451 || trimmed.starts_with("call_")
452 || trimmed.starts_with("tool_result:")
453 || trimmed.ends_with(".txt")
454 || crate::tools::truncate::is_valid_sha256(&sha_candidate.to_ascii_lowercase())
455 }
456
457 fn parse_projection(input: &Value) -> Result<Projection, ToolError> {
458 let mut count = 0usize;
459 count += usize::from(input.get("slice").is_some());
460 count += usize::from(input.get("range").is_some());
461 count += usize::from(input.get("count").and_then(Value::as_bool).unwrap_or(false));
462 count += usize::from(input.get("jsonpath").is_some());
463 count += usize::from(
464 input
465 .get("introspect")
466 .and_then(Value::as_bool)
467 .unwrap_or(false),
468 );
469 if count != 1 {
470 return Err(ToolError::invalid_input(projection_usage_hint()));
471 }
472
473 if input
474 .get("introspect")
475 .and_then(Value::as_bool)
476 .unwrap_or(false)
477 {
478 return Ok(Projection::Introspect);
479 }
480 if input.get("count").and_then(Value::as_bool).unwrap_or(false) {
481 return Ok(Projection::Count);
482 }
483 if let Some(path) = input.get("jsonpath") {
484 let path = path
485 .as_str()
486 .ok_or_else(|| ToolError::invalid_input("handle_read: jsonpath must be a string"))?
487 .trim();
488 if path.is_empty() {
489 return Err(ToolError::invalid_input(
490 "handle_read: jsonpath must not be empty",
491 ));
492 }
493 if path.len() > JSONPATH_MAX_PATH_BYTES {
494 return Err(ToolError::invalid_input(
495 "handle_read: JSONPath exceeds 4096 bytes",
496 ));
497 }
498 return Ok(Projection::JsonPath(path.to_string()));
499 }
500 if let Some(slice) = input.get("slice") {
501 let start = slice.get("start").and_then(Value::as_u64).unwrap_or(0) as usize;
502 let end = slice.get("end").and_then(Value::as_u64).map(|n| n as usize);
503 if let Some(end) = end
504 && end < start
505 {
506 return Err(ToolError::invalid_input(
507 "handle_read: slice.end must be greater than or equal to slice.start",
508 ));
509 }
510 let unit = match slice.get("unit").and_then(Value::as_str).unwrap_or("chars") {
511 "chars" => SliceUnit::Chars,
512 "lines" => SliceUnit::Lines,
513 other => {
514 return Err(ToolError::invalid_input(format!(
515 "handle_read: unsupported slice.unit `{other}`"
516 )));
517 }
518 };
519 return Ok(Projection::Slice { start, end, unit });
520 }
521 let range = input
522 .get("range")
523 .ok_or_else(|| ToolError::invalid_input("handle_read: missing projection"))?;
524 let start = range
525 .get("start")
526 .and_then(Value::as_u64)
527 .ok_or_else(|| ToolError::missing_field("range.start"))? as usize;
528 let end = range
529 .get("end")
530 .and_then(Value::as_u64)
531 .ok_or_else(|| ToolError::missing_field("range.end"))? as usize;
532 if start == 0 || end == 0 || end < start {
533 return Err(ToolError::invalid_input(
534 "handle_read: range is one-based inclusive and end must be >= start",
535 ));
536 }
537 Ok(Projection::Range { start, end })
538 }
539
540 fn projection_usage_hint() -> String {
541 "handle_read: provide exactly one projection: `slice`, `range`, `count: true`, `jsonpath`, or `introspect: true`. \
542 Examples: {\"handle\":{\"kind\":\"var_handle\",\"session_id\":\"rlm:abc\",\"name\":\"final_1\"},\"slice\":{\"start\":0,\"end\":500}}; \
543 {\"handle\":\"rlm:abc/final_1\",\"count\":true}; \
544 {\"handle\":\"rlm:abc/final_1\",\"introspect\":true}."
545 .to_string()
546 }
547
548 fn count_projection(record: &HandleRecord) -> Value {
549 match &record.value {
550 HandleValue::Text(text) => json!({
551 "handle": record.handle,
552 "projection": "count",
553 "chars": text.chars().count(),
554 "lines": text.lines().count(),
555 "bytes": text.len(),
556 }),
557 HandleValue::Json(value) => {
558 let bytes = {
559 let mut cw = codewhale_util::utils::CountingWriter::new();
560 let _ = serde_json::to_writer(&mut cw, value);
561 cw.count()
562 };
563 json!({
564 "handle": record.handle,
565 "projection": "count",
566 "json_type": json_type(value),
567 "length": record.handle.length,
568 "bytes": bytes,
569 })
570 }
571 }
572 }
573
574 fn introspect_projection(record: &HandleRecord) -> Value {
575 let string_handle = format!("{}/{}", record.handle.session_id, record.handle.name);
576 let object_handle = json!(record.handle.clone());
577 let mut projections = vec![
578 json!({"name": "count", "example": {"handle": string_handle, "count": true}}),
579 json!({"name": "slice_chars", "example": {"handle": object_handle.clone(), "slice": {"start": 0, "end": 500}}}),
580 json!({"name": "range_lines", "example": {"handle": object_handle.clone(), "range": {"start": 1, "end": 20}}}),
581 ];
582 if matches!(record.value, HandleValue::Json(_)) {
583 projections.push(
584 json!({"name": "jsonpath", "example": {"handle": object_handle, "jsonpath": "$"}}),
585 );
586 }
587
588 json!({
589 "handle": record.handle,
590 "projection": "introspect",
591 "value_type": match &record.value {
592 HandleValue::Text(_) => "text",
593 HandleValue::Json(value) => json_type(value),
594 },
595 "length": record.handle.length,
596 "repr_preview": record.handle.repr_preview,
597 "projections": projections,
598 })
599 }
600
601 fn slice_projection(
602 record: &HandleRecord,
603 start: usize,
604 end: Option<usize>,
605 unit: SliceUnit,
606 max_chars: usize,
607 ) -> Value {
608 let text = record_text(record);
609 match unit {
610 SliceUnit::Chars => {
611 let total = text.chars().count();
612 let end = end.unwrap_or(total).min(total);
613 let raw = char_slice(&text, start.min(total), end);
614 bounded_text_projection(
615 record,
616 "slice",
617 raw,
618 max_chars,
619 json!({
620 "unit": "chars",
621 "start": start.min(total),
622 "end": end,
623 "total_chars": total,
624 }),
625 )
626 }
627 SliceUnit::Lines => {
628 let lines: Vec<&str> = text.lines().collect();
629 let total = lines.len();
630 let end = end.unwrap_or(total).min(total);
631 let raw = if start >= end {
632 String::new()
633 } else {
634 lines[start.min(total)..end].join("\n")
635 };
636 bounded_text_projection(
637 record,
638 "slice",
639 raw,
640 max_chars,
641 json!({
642 "unit": "lines",
643 "start": start.min(total),
644 "end": end,
645 "total_lines": total,
646 }),
647 )
648 }
649 }
650 }
651
652 fn line_range_projection(
653 record: &HandleRecord,
654 start: usize,
655 end: usize,
656 max_chars: usize,
657 ) -> Value {
658 let text = record_text(record);
659 let lines: Vec<&str> = text.lines().collect();
660 let total = lines.len();
661 let zero_start = start.saturating_sub(1).min(total);
662 let zero_end = end.min(total);
663 let raw = if zero_start >= zero_end {
664 String::new()
665 } else {
666 lines[zero_start..zero_end].join("\n")
667 };
668 bounded_text_projection(
669 record,
670 "range",
671 raw,
672 max_chars,
673 json!({
674 "start": start,
675 "end": end,
676 "shown_start": zero_start + 1,
677 "shown_end": zero_end,
678 "total_lines": total,
679 }),
680 )
681 }
682
683 fn jsonpath_projection(
684 record: &HandleRecord,
685 path: &str,
686 max_chars: usize,
687 ) -> Result<Value, ToolError> {
688 let HandleValue::Json(value) = &record.value else {
689 return Err(ToolError::invalid_input(
690 "handle_read: jsonpath projection requires a JSON handle",
691 ));
692 };
693 let matches = query_jsonpath(value, path)
694 .map_err(|e| ToolError::invalid_input(format!("handle_read: {e}")))?;
695 let mut payload = json!({
696 "handle": record.handle,
697 "projection": "jsonpath",
698 "jsonpath": path,
699 "count": matches.len(),
700 "matches": matches,
701 "truncated": false,
702 });
703 let rendered = serde_json::to_string(&payload).unwrap_or_default();
704 if rendered.chars().count() > max_chars {
705 payload["matches"] = json!([]);
706 payload["preview"] = json!(truncate_chars(&rendered, max_chars));
707 payload["truncated"] = json!(true);
708 }
709 Ok(payload)
710 }
711
712 fn bounded_text_projection(
713 record: &HandleRecord,
714 projection: &str,
715 raw: String,
716 max_chars: usize,
717 extra: Value,
718 ) -> Value {
719 let raw_chars = raw.chars().count();
720 let content = truncate_chars(&raw, max_chars);
721 let shown_chars = content.chars().count();
722 json!({
723 "handle": record.handle,
724 "projection": projection,
725 "content": content,
726 "truncated": shown_chars < raw_chars,
727 "shown_chars": shown_chars,
728 "omitted_chars": raw_chars.saturating_sub(shown_chars),
729 "meta": extra,
730 })
731 }
732
733 fn record_text(record: &HandleRecord) -> std::borrow::Cow<'_, str> {
734 match &record.value {
735 HandleValue::Text(text) => std::borrow::Cow::Borrowed(text),
736 HandleValue::Json(value) => {
737 std::borrow::Cow::Owned(serde_json::to_string_pretty(value).unwrap_or_default())
738 }
739 }
740 }
741
742 pub fn query_jsonpath(root: &Value, path: &str) -> Result<Vec<Value>, String> {
743 query_jsonpath_bounded(root, path, JSONPATH_MAX_BYTES).map(|(values, _)| values)
744 }
745
746 pub(super) fn query_jsonpath_bounded(
747 root: &Value,
748 path: &str,
749 max_bytes: usize,
750 ) -> Result<(Vec<Value>, usize), String> {
751 let (current, _) = eval_jsonpath(root, path, false)?;
752 let mut counter = codewhale_util::utils::CountingWriter::new();
753 serde_json::to_writer(&mut counter, &current)
754 .map_err(|error| format!("jsonpath result measurement failed: {error}"))?;
755 let max_bytes = max_bytes.min(JSONPATH_MAX_BYTES);
756 if counter.count() > max_bytes {
757 return Err(format!(
758 "jsonpath result exceeds the {max_bytes}-byte projection budget; use a narrower projection"
759 ));
760 }
761 Ok((current.into_iter().cloned().collect(), counter.count()))
762 }
763
764 pub(super) fn query_jsonpath_capped(
765 root: &Value,
766 path: &str,
767 ) -> Result<(Vec<Value>, bool), String> {
768 let (current, match_cap_hit) = eval_jsonpath(root, path, true)?;
769 Ok((current.into_iter().cloned().collect(), match_cap_hit))
770 }
771
772 fn eval_jsonpath<'a>(
773 root: &'a Value,
774 path: &str,
775 truncate_on_match_cap: bool,
776 ) -> Result<(Vec<&'a Value>, bool), String> {
777 if path.len() > JSONPATH_MAX_PATH_BYTES {
778 return Err("jsonpath exceeds 4096 bytes".to_string());
779 }
780 if !path.starts_with('$') {
781 return Err("jsonpath must start with `$`".to_string());
782 }
783 let mut idx = 1usize;
784 let bytes = path.as_bytes();
785 let mut current = vec![root];
786 let mut steps = 0usize;
787 let mut match_cap_hit = false;
788 while idx < bytes.len() {
789 steps += 1;
790 if steps > JSONPATH_MAX_STEPS {
791 return Err("jsonpath exceeds 128 steps; use a narrower projection".to_string());
792 }
793 match bytes[idx] {
794 b'.' => {
795 idx += 1;
796 if idx < bytes.len() && bytes[idx] == b'.' {
797 return Err("recursive descent (`..`) is not supported".to_string());
798 }
799 let start = idx;
800 while idx < bytes.len()
801 && (bytes[idx].is_ascii_alphanumeric() || bytes[idx] == b'_')
802 {
803 idx += 1;
804 }
805 if start == idx {
806 return Err("expected field name after `.`".to_string());
807 }
808 let field = &path[start..idx];
809 current = current
810 .into_iter()
811 .filter_map(|value| value.get(field))
812 .collect();
813 }
814 b'[' => {
815 let Some(close_rel) = path[idx + 1..].find(']') else {
816 return Err("unterminated `[` segment".to_string());
817 };
818 let close = idx + 1 + close_rel;
819 let token = path[idx + 1..close].trim();
820 idx = close + 1;
821 current =
822 apply_bracket_token(current, token, truncate_on_match_cap, &mut match_cap_hit)?;
823 }
824 other => {
825 return Err(format!(
826 "unexpected character `{}` in jsonpath",
827 other as char
828 ));
829 }
830 }
831 }
832 Ok((current, match_cap_hit))
833 }
834
835 fn apply_bracket_token<'a>(
836 values: Vec<&'a Value>,
837 token: &str,
838 truncate_on_match_cap: bool,
839 match_cap_hit: &mut bool,
840 ) -> Result<Vec<&'a Value>, String> {
841 if token == "*" {
842 let mut out = Vec::new();
843 let mut push = |item: &'a Value| -> Result<bool, String> {
844 if out.len() == JSONPATH_MAX_MATCHES {
845 if truncate_on_match_cap {
846 *match_cap_hit = true;
847 return Ok(false);
848 }
849 return Err(
850 "jsonpath exceeds 1024 intermediate matches; use a narrower projection"
851 .to_string(),
852 );
853 }
854 out.push(item);
855 Ok(true)
856 };
857 'outer: for value in values {
858 match value {
859 Value::Array(items) => {
860 for item in items {
861 if !push(item)? {
862 break 'outer;
863 }
864 }
865 }
866 Value::Object(map) => {
867 for item in map.values() {
868 if !push(item)? {
869 break 'outer;
870 }
871 }
872 }
873 _ => {}
874 }
875 }
876 return Ok(out);
877 }
878
879 if let Some(field) = quoted_field(token) {
880 return Ok(values
881 .into_iter()
882 .filter_map(|value| value.get(field))
883 .collect());
884 }
885
886 let index = token
887 .parse::<usize>()
888 .map_err(|_| format!("unsupported bracket token `{token}`"))?;
889 Ok(values
890 .into_iter()
891 .filter_map(|value| value.as_array().and_then(|items| items.get(index)))
892 .collect())
893 }
894
895 fn quoted_field(token: &str) -> Option<&str> {
896 if token.len() < 2 {
897 return None;
898 }
899 let bytes = token.as_bytes();
900 let quote = bytes[0];
901 if !matches!(quote, b'\'' | b'"') || bytes[token.len() - 1] != quote {
902 return None;
903 }
904 Some(&token[1..token.len() - 1])
905 }
906
907 fn char_slice(text: &str, start: usize, end: usize) -> String {
908 text.chars()
909 .skip(start)
910 .take(end.saturating_sub(start))
911 .collect()
912 }
913
914 fn truncate_chars(text: &str, max_chars: usize) -> String {
915 let mut out = String::new();
916 for (idx, ch) in text.chars().enumerate() {
917 if idx == max_chars {
918 break;
919 }
920 out.push(ch);
921 }
922 out
923 }
924
925 fn sha256_hex(bytes: &[u8]) -> String {
926 codewhale_runtime::hashing::sha256_hex(bytes)
927 }
928
929 fn json_type(value: &Value) -> &'static str {
930 match value {
931 Value::Null => "null",
932 Value::Bool(_) => "bool",
933 Value::Number(_) => "number",
934 Value::String(_) => "string",
935 Value::Array(_) => "array",
936 Value::Object(_) => "object",
937 }
938 }
939
940 #[cfg(test)]
941 mod tests {
942 use super::*;
943 use serde_json::json;
944
945 fn ctx() -> ToolContext {
946 ToolContext::new(".")
947 }
948
949 #[tokio::test]
950 async fn handle_read_slices_text_by_chars() {
951 let ctx = ctx();
952 let handle = {
953 let mut store = ctx.runtime.handle_store.lock().await;
954 store.insert_text("rlm:test", "matches", "abcdef")
955 };
956
957 let result = HandleReadTool
958 .execute(
959 json!({"handle": handle, "slice": {"start": 1, "end": 4}}),
960 &ctx,
961 )
962 .await
963 .expect("execute");
964 let body: Value = serde_json::from_str(&result.content).expect("json");
965 assert_eq!(body["content"], "bcd");
966 assert_eq!(body["truncated"], false);
967 }
968
969 #[tokio::test]
970 async fn handle_read_ranges_text_by_one_based_lines() {
971 let ctx = ctx();
972 let handle = {
973 let mut store = ctx.runtime.handle_store.lock().await;
974 store.insert_text("agent:test", "transcript", "one\ntwo\nthree\nfour")
975 };
976
977 let result = HandleReadTool
978 .execute(
979 json!({"handle": handle, "range": {"start": 2, "end": 3}}),
980 &ctx,
981 )
982 .await
983 .expect("execute");
984 let body: Value = serde_json::from_str(&result.content).expect("json");
985 assert_eq!(body["content"], "two\nthree");
986 assert_eq!(body["meta"]["shown_start"], 2);
987 assert_eq!(body["meta"]["shown_end"], 3);
988 }
989
990 #[tokio::test]
991 async fn handle_read_counts_json_collections() {
992 let ctx = ctx();
993 let handle = {
994 let mut store = ctx.runtime.handle_store.lock().await;
995 store.insert_json("rlm:test", "items", json!([{"a": 1}, {"a": 2}]))
996 };
997
998 let result = HandleReadTool
999 .execute(json!({"handle": handle, "count": true}), &ctx)
1000 .await
1001 .expect("execute");
1002 let body: Value = serde_json::from_str(&result.content).expect("json");
1003 assert_eq!(body["json_type"], "array");
1004 assert_eq!(body["length"], 2);
1005 }
1006
1007 #[tokio::test]
1008 async fn handle_read_introspects_object_handle_with_examples() {
1009 let ctx = ctx();
1010 let handle = {
1011 let mut store = ctx.runtime.handle_store.lock().await;
1012 store.insert_json("rlm:test", "items", json!({"items": [{"a": 1}]}))
1013 };
1014
1015 let result = HandleReadTool
1016 .execute(json!({"handle": handle, "introspect": true}), &ctx)
1017 .await
1018 .expect("execute");
1019 let body: Value = serde_json::from_str(&result.content).expect("json");
1020 assert_eq!(body["projection"], "introspect");
1021 assert_eq!(body["handle"]["kind"], "var_handle");
1022 assert!(
1023 body["projections"]
1024 .as_array()
1025 .expect("projection examples")
1026 .iter()
1027 .any(|entry| entry["name"] == "jsonpath"),
1028 "json handles should advertise jsonpath examples"
1029 );
1030 }
1031
1032 #[tokio::test]
1033 async fn handle_read_projects_jsonpath_subset() {
1034 let ctx = ctx();
1035 let handle = {
1036 let mut store = ctx.runtime.handle_store.lock().await;
1037 store.insert_json(
1038 "rlm:test",
1039 "items",
1040 json!({"items": [{"name": "a"}, {"name": "b"}]}),
1041 )
1042 };
1043
1044 let result = HandleReadTool
1045 .execute(
1046 json!({"handle": handle, "jsonpath": "$.items[*].name"}),
1047 &ctx,
1048 )
1049 .await
1050 .expect("execute");
1051 let body: Value = serde_json::from_str(&result.content).expect("json");
1052 assert_eq!(body["matches"], json!(["a", "b"]));
1053 assert_eq!(body["count"], 2);
1054 }
1055
1056 #[tokio::test]
1057 async fn handle_read_rejects_unbounded_projection_requests() {
1058 let ctx = ctx();
1059 let handle = {
1060 let mut store = ctx.runtime.handle_store.lock().await;
1061 store.insert_text("rlm:test", "body", "abc")
1062 };
1063
1064 let err = HandleReadTool
1065 .execute(json!({"handle": handle}), &ctx)
1066 .await
1067 .expect_err("projection required");
1068 let message = err.to_string();
1069 assert!(message.contains("exactly one"));
1070 assert!(message.contains("slice"));
1071 assert!(message.contains("introspect"));
1072 }
1073
1074 #[tokio::test]
1075 async fn handle_read_points_artifact_refs_to_tool_result_retrieval() {
1076 let ctx = ctx();
1077 let err = HandleReadTool
1078 .execute(json!({"handle": "art_call_abc123", "count": true}), &ctx)
1079 .await
1080 .expect_err("artifact refs are not var handles");
1081 let message = err.to_string();
1082 assert!(message.contains("retrieve_tool_result"));
1083 assert!(message.contains("artifact/tool-result ref"));
1084 }
1085
1086 // === #5472 findings 4-5: the store is bounded across all sessions ===
1087
1088 #[test]
1089 fn handle_store_evicts_oldest_records_past_its_byte_budget() {
1090 let mut store = HandleStore::default();
1091 // 96 x 1 MiB across distinct sessions — the RLM shape, which had no
1092 // eviction path at all because nothing ever calls `evict_session` for it.
1093 let payload = "z".repeat(1024 * 1024);
1094 for index in 0..96 {
1095 let _ = store.insert_text(format!("rlm-session-{index}"), "value", payload.clone());
1096 }
1097 assert!(
1098 store.retained_bytes() <= HANDLE_STORE_MAX_BYTES,
1099 "store held {} bytes, over the {HANDLE_STORE_MAX_BYTES} budget",
1100 store.retained_bytes()
1101 );
1102 let newest = VarHandle {
1103 kind: "var_handle".to_string(),
1104 session_id: "rlm-session-95".to_string(),
1105 name: "value".to_string(),
1106 type_name: "str".to_string(),
1107 length: payload.chars().count(),
1108 repr_preview: String::new(),
1109 sha256: String::new(),
1110 };
1111 assert!(
1112 store.get(&newest).is_some(),
1113 "the most recent handle must survive — it is the one still referenced"
1114 );
1115 }
1116
1117 #[test]
1118 fn evicting_a_session_returns_its_bytes_to_the_budget() {
1119 let mut store = HandleStore::default();
1120 let _ = store.insert_text("session-a", "value", "a".repeat(4096));
1121 let _ = store.insert_text("session-b", "value", "b".repeat(4096));
1122 let before = store.retained_bytes();
1123 assert_eq!(before, 8192);
1124 store.evict_session("session-a");
1125 assert_eq!(
1126 store.retained_bytes(),
1127 4096,
1128 "per-session eviction must not leave phantom bytes on the budget"
1129 );
1130 }
1131 }
1132
1132 lines RUST