Skip to main content

atman_runtime/tools/
tool_output.rs

1use std::path::{Path, PathBuf};
2use std::sync::Arc;
3
4use crate::error::RuntimeError;
5use crate::message::{Message, MessageOrigin, MessagePart, MessageRole};
6use crate::tool::{BoxFut, Tier, Tool, ToolArgs, ToolCtx, ToolResult};
7use crate::value::Value;
8
9#[derive(Clone, Default)]
10pub struct OutputStore {
11    session_dir: Option<Arc<PathBuf>>,
12}
13
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct OutputPage {
16    pub content: String,
17    pub mode: &'static str,
18    pub offset: usize,
19    pub next_offset: usize,
20    pub total_lines: usize,
21    pub total_bytes: usize,
22    pub has_more: bool,
23}
24
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct OutputSearchHit {
27    pub line: usize,
28    pub snippet: String,
29}
30
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct OutputSearchResult {
33    pub query: String,
34    pub total_matches: usize,
35    pub hits: Vec<OutputSearchHit>,
36    pub has_more: bool,
37    pub next_match: usize,
38}
39
40impl OutputStore {
41    pub fn at(session_dir: impl Into<PathBuf>) -> Self {
42        Self {
43            session_dir: Some(Arc::new(session_dir.into())),
44        }
45    }
46
47    pub fn register(&self, _label: &str, content: &str) -> Option<String> {
48        let session_dir = self.session_dir.as_deref()?;
49        let output_id = format!("out_{}", uuid::Uuid::now_v7().simple());
50        write_output_file(session_dir, &output_id, content)?;
51        Some(output_id)
52    }
53
54    pub fn read_lines(
55        &self,
56        output_id: &str,
57        offset: usize,
58        limit: usize,
59        budget: ToolOutputBudget,
60    ) -> Result<OutputPage, RuntimeError> {
61        let content = self.read_registered(output_id)?;
62        let lines: Vec<&str> = content.split_inclusive('\n').collect();
63        let start = offset.min(lines.len());
64        let requested_end = start
65            .saturating_add(limit.min(budget.max_lines))
66            .min(lines.len());
67        let mut end = requested_end;
68        while end > start {
69            let candidate = lines[start..end].concat();
70            if bounded_prefix_len(&candidate, budget) == candidate.len() {
71                break;
72            }
73            end -= 1;
74        }
75        if end == start && start < lines.len() {
76            return Err(RuntimeError::ToolFailed(
77                "output.read: the next line exceeds the output budget; use byte_offset + byte_limit".into(),
78            ));
79        }
80        let requested = lines[start..end].concat();
81        Ok(OutputPage {
82            content: requested,
83            mode: "lines",
84            offset: start,
85            next_offset: end,
86            total_lines: lines.len(),
87            total_bytes: content.len(),
88            has_more: end < lines.len(),
89        })
90    }
91
92    pub fn search(
93        &self,
94        output_id: &str,
95        query: &str,
96        match_index: usize,
97        match_limit: usize,
98    ) -> Result<OutputSearchResult, RuntimeError> {
99        if query.is_empty() {
100            return Err(RuntimeError::ToolFailed(
101                "output.read: query must not be empty".into(),
102            ));
103        }
104        let content = self.read_registered(output_id)?;
105        let lines: Vec<&str> = content.lines().collect();
106        let matches: Vec<OutputSearchHit> = lines
107            .iter()
108            .enumerate()
109            .filter(|(_, line)| line.contains(query))
110            .map(|(index, line)| OutputSearchHit {
111                line: index + 1,
112                snippet: line.chars().take(240).collect(),
113            })
114            .collect();
115        let start = match_index.min(matches.len());
116        let end = start.saturating_add(match_limit).min(matches.len());
117        Ok(OutputSearchResult {
118            query: query.to_string(),
119            total_matches: matches.len(),
120            hits: matches[start..end].to_vec(),
121            has_more: end < matches.len(),
122            next_match: end,
123        })
124    }
125
126    pub fn read_bytes(
127        &self,
128        output_id: &str,
129        offset: usize,
130        limit: usize,
131        budget: ToolOutputBudget,
132    ) -> Result<OutputPage, RuntimeError> {
133        let content = self.read_registered(output_id)?;
134        if offset > content.len() || !content.is_char_boundary(offset) {
135            return Err(RuntimeError::ToolFailed(
136                "output.read: byte_offset is not a valid UTF-8 boundary".into(),
137            ));
138        }
139        let mut end = offset
140            .saturating_add(limit.min(budget.max_bytes).min(budget.max_line_bytes))
141            .min(content.len());
142        while end > offset && !content.is_char_boundary(end) {
143            end -= 1;
144        }
145        Ok(OutputPage {
146            content: content[offset..end].to_string(),
147            mode: "bytes",
148            offset,
149            next_offset: end,
150            total_lines: content.split_inclusive('\n').count(),
151            total_bytes: content.len(),
152            has_more: end < content.len(),
153        })
154    }
155
156    pub(crate) fn validates_total_bytes(&self, output_id: &str, total_bytes: usize) -> bool {
157        self.read_registered(output_id)
158            .is_ok_and(|content| content.len() == total_bytes)
159    }
160
161    pub(crate) fn validates_pagination(
162        &self,
163        output_id: &str,
164        mode: &str,
165        offset: usize,
166        total_bytes: usize,
167        total_lines: Option<usize>,
168        has_more: bool,
169    ) -> bool {
170        let Ok(content) = self.read_registered(output_id) else {
171            return false;
172        };
173        if total_bytes != content.len() {
174            return false;
175        }
176        match mode {
177            "bytes" => has_more == (offset < content.len()) && offset <= content.len(),
178            "lines" => {
179                let actual_lines = content.split_inclusive('\n').count();
180                total_lines == Some(actual_lines)
181                    && has_more == (offset < actual_lines)
182                    && offset <= actual_lines
183            }
184            _ => false,
185        }
186    }
187
188    fn read_registered(&self, output_id: &str) -> Result<String, RuntimeError> {
189        if !output_id.starts_with("out_")
190            || output_id.len() != 36
191            || !output_id[4..].chars().all(|c| c.is_ascii_hexdigit())
192        {
193            return Err(RuntimeError::ToolFailed(
194                "output.read: unknown output_id".into(),
195            ));
196        }
197        let session_dir = self.session_dir.as_deref().ok_or_else(|| {
198            RuntimeError::ToolFailed("output.read: no session output store available".into())
199        })?;
200        let path = output_dir(session_dir).join(format!("{output_id}.txt"));
201        std::fs::read_to_string(path)
202            .map_err(|_| RuntimeError::ToolFailed("output.read: unknown output_id".into()))
203    }
204}
205
206pub struct OutputRead;
207
208impl Tool for OutputRead {
209    fn name(&self) -> &str {
210        "output.read"
211    }
212
213    fn tier(&self) -> Tier {
214        Tier::Zero
215    }
216
217    fn description(&self) -> Option<&str> {
218        Some(
219            "Read a registered oversized tool output from the current session. Use line_offset + line_limit for page-by-line continuation, byte_offset + byte_limit for byte continuation, or query + match_index + match_limit to search matching lines. The returned next_offset/next_match fields are ready for the next call; output_id cannot address arbitrary paths.",
220        )
221    }
222
223    fn input_schema(&self) -> serde_json::Value {
224        serde_json::json!({
225            "type": "object",
226            "properties": {
227                "output_id": {"type": "string", "description": "Opaque ID returned by a truncated tool result."},
228                "query": {"type": "string", "description": "Literal text to search for. Returns matching 1-based line numbers and snippets."},
229                "match_index": {"type": "integer", "minimum": 0, "description": "Zero-based matching-line offset for search pagination."},
230                "match_limit": {"type": "integer", "minimum": 1, "description": "Maximum matching lines to return."},
231                "line_offset": {"type": "integer", "minimum": 0, "description": "Zero-based line offset."},
232                "line_limit": {"type": "integer", "minimum": 1, "description": "Maximum lines to return."},
233                "byte_offset": {"type": "integer", "minimum": 0, "description": "Zero-based UTF-8 byte offset."},
234                "byte_limit": {"type": "integer", "minimum": 1, "description": "Maximum bytes to return."}
235            },
236            "required": ["output_id"]
237        })
238    }
239
240    fn call<'a>(&'a self, args: ToolArgs, ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
241        Box::pin(async move {
242            let output_id = string_arg(&args, "output_id")?;
243            let store = ctx.output_store.as_ref().ok_or_else(|| {
244                RuntimeError::ToolFailed("output.read: no session output store available".into())
245            })?;
246            let query = optional_string(&args, "query")?;
247            let match_index = optional_usize(&args, "match_index")?.unwrap_or(0);
248            let match_limit = optional_positive_usize(&args, "match_limit")?
249                .unwrap_or(ctx.tool_output_budget.max_lines);
250            let line_offset = optional_usize(&args, "line_offset")?;
251            let line_limit = optional_positive_usize(&args, "line_limit")?;
252            let byte_offset = optional_usize(&args, "byte_offset")?;
253            let byte_limit = optional_positive_usize(&args, "byte_limit")?;
254            let uses_lines = line_offset.is_some() || line_limit.is_some();
255            let uses_bytes = byte_offset.is_some() || byte_limit.is_some();
256            if query.is_some() && (uses_lines || uses_bytes) {
257                return Err(RuntimeError::ToolFailed(
258                    "output.read: choose search, line pagination, or byte pagination".into(),
259                ));
260            }
261            if uses_lines && uses_bytes {
262                return Err(RuntimeError::ToolFailed(
263                    "output.read: choose line pagination or byte pagination, not both".into(),
264                ));
265            }
266            if let Some(query) = query {
267                return Ok(output_search_value(store.search(
268                    &output_id,
269                    &query,
270                    match_index,
271                    match_limit,
272                )?));
273            }
274            let page = if uses_bytes {
275                store.read_bytes(
276                    &output_id,
277                    byte_offset.unwrap_or(0),
278                    byte_limit.unwrap_or(ctx.tool_output_budget.max_bytes),
279                    ctx.tool_output_budget,
280                )?
281            } else {
282                store.read_lines(
283                    &output_id,
284                    line_offset.unwrap_or(0),
285                    line_limit.unwrap_or(ctx.tool_output_budget.max_lines),
286                    ctx.tool_output_budget,
287                )?
288            };
289            Ok(output_page_value(page))
290        })
291    }
292}
293
294fn optional_string(args: &ToolArgs, name: &str) -> Result<Option<String>, RuntimeError> {
295    match args.named(name) {
296        Some(Value::Str(value)) => Ok(Some(value.clone())),
297        Some(Value::Unit) | None => Ok(None),
298        Some(value) => Err(RuntimeError::TypeMismatch {
299            expected: format!("string {name}"),
300            actual: value.kind_name().into(),
301        }),
302    }
303}
304
305fn string_arg(args: &ToolArgs, name: &str) -> Result<String, RuntimeError> {
306    match args.named(name) {
307        Some(Value::Str(value)) => Ok(value.clone()),
308        Some(value) => Err(RuntimeError::TypeMismatch {
309            expected: format!("string {name}"),
310            actual: value.kind_name().into(),
311        }),
312        None => Err(RuntimeError::MissingArg(name.into())),
313    }
314}
315
316fn optional_usize(args: &ToolArgs, name: &str) -> Result<Option<usize>, RuntimeError> {
317    match args.named(name) {
318        Some(Value::Int(value)) if *value >= 0 => Ok(Some(*value as usize)),
319        Some(Value::Unit) | None => Ok(None),
320        Some(value) => Err(RuntimeError::TypeMismatch {
321            expected: format!("non-negative integer {name}"),
322            actual: value.kind_name().into(),
323        }),
324    }
325}
326
327fn optional_positive_usize(args: &ToolArgs, name: &str) -> Result<Option<usize>, RuntimeError> {
328    match args.named(name) {
329        Some(Value::Int(value)) if *value > 0 => Ok(Some(*value as usize)),
330        Some(Value::Unit) | None => Ok(None),
331        Some(value) => Err(RuntimeError::TypeMismatch {
332            expected: format!("positive integer {name}"),
333            actual: value.kind_name().into(),
334        }),
335    }
336}
337
338fn output_search_value(result: OutputSearchResult) -> Value {
339    Value::Struct(vec![
340        ("query".into(), Value::Str(result.query)),
341        (
342            "total_matches".into(),
343            Value::Int(result.total_matches as i64),
344        ),
345        (
346            "hits".into(),
347            Value::List(
348                result
349                    .hits
350                    .into_iter()
351                    .map(|hit| {
352                        Value::Struct(vec![
353                            ("line".into(), Value::Int(hit.line as i64)),
354                            ("snippet".into(), Value::Str(hit.snippet)),
355                        ])
356                    })
357                    .collect(),
358            ),
359        ),
360        ("has_more".into(), Value::Bool(result.has_more)),
361        ("next_match".into(), Value::Int(result.next_match as i64)),
362    ])
363}
364
365fn output_page_value(page: OutputPage) -> Value {
366    Value::Struct(vec![
367        ("content".into(), Value::Str(page.content)),
368        ("mode".into(), Value::Str(page.mode.into())),
369        ("offset".into(), Value::Int(page.offset as i64)),
370        ("next_offset".into(), Value::Int(page.next_offset as i64)),
371        ("total_lines".into(), Value::Int(page.total_lines as i64)),
372        ("total_bytes".into(), Value::Int(page.total_bytes as i64)),
373        ("has_more".into(), Value::Bool(page.has_more)),
374    ])
375}
376
377pub const MAX_TOOL_RESULT_CHARS: usize = 25_000;
378
379#[derive(Debug, Clone, Copy, PartialEq, Eq)]
380pub struct ToolOutputBudget {
381    pub max_lines: usize,
382    pub max_bytes: usize,
383    pub max_line_bytes: usize,
384}
385
386impl Default for ToolOutputBudget {
387    fn default() -> Self {
388        Self {
389            max_lines: 32,
390            max_bytes: 1024,
391            max_line_bytes: 384,
392        }
393    }
394}
395
396pub fn truncate_tool_result_content(
397    content: &str,
398    label: &str,
399    output_store: Option<&OutputStore>,
400) -> String {
401    truncate_tool_result_content_with_budget(
402        content,
403        label,
404        output_store,
405        ToolOutputBudget {
406            max_lines: usize::MAX,
407            max_bytes: MAX_TOOL_RESULT_CHARS,
408            max_line_bytes: MAX_TOOL_RESULT_CHARS,
409        },
410    )
411}
412
413pub fn truncate_tool_result_content_with_budget(
414    content: &str,
415    label: &str,
416    output_store: Option<&OutputStore>,
417    budget: ToolOutputBudget,
418) -> String {
419    if is_live_pagination_envelope(content, output_store)
420        || is_live_pagination_notice(content, output_store)
421    {
422        return content.to_string();
423    }
424
425    let cut = bounded_prefix_len(content, budget);
426    if cut == content.len() {
427        return content.to_string();
428    }
429
430    let total = content.len();
431    let head = &content[..cut];
432    let output_id = output_store.and_then(|store| store.register(label, content));
433
434    match output_id {
435        Some(output_id) => format!(
436            "{head}\n\n[Output truncated: total_bytes={total}, output_id={output_id}. Continue with exactly: output.read(output_id: {output_id}, line_offset: 0, line_limit: 100). For targeted lookup use: output.read(output_id: {output_id}, query: \"text\", match_limit: 20). For byte paging use: output.read(output_id: {output_id}, byte_offset: 0, byte_limit: {max_bytes}).]",
437            max_bytes = budget.max_bytes,
438            total = total,
439        ),
440        None => format!(
441            "{head}\n\n[Output truncated at configured budget: max_lines={max_lines}, max_bytes={max_bytes}, max_line_bytes={max_line_bytes}, total_bytes={total}. No output_id is available because the session output could not be written.]",
442            max_lines = budget.max_lines,
443            max_bytes = budget.max_bytes,
444            max_line_bytes = budget.max_line_bytes,
445            total = total,
446        ),
447    }
448}
449
450fn is_live_pagination_notice(content: &str, output_store: Option<&OutputStore>) -> bool {
451    let Some(store) = output_store else {
452        return false;
453    };
454    let notice = content
455        .rsplit_once("\n\n[Output truncated at configured budget:")
456        .map(|(_, notice)| notice)
457        .or_else(|| {
458            content
459                .rsplit_once("\n\n[Output truncated:")
460                .map(|(_, notice)| notice)
461        });
462    let Some(notice) = notice else {
463        return false;
464    };
465    if !notice.ends_with("]") {
466        return false;
467    }
468    let Some(total_bytes) = notice
469        .split_once("total_bytes=")
470        .and_then(|(_, value)| value.split([',', '.']).next())
471        .and_then(|value| value.trim().parse::<usize>().ok())
472    else {
473        return false;
474    };
475    let Some(output_id) = notice
476        .split_once("output_id=")
477        .and_then(|(_, value)| value.split([',', '.']).next())
478        .map(str::trim)
479        .filter(|value| !value.is_empty())
480    else {
481        return false;
482    };
483    store.validates_total_bytes(output_id, total_bytes)
484}
485
486fn is_live_pagination_envelope(content: &str, output_store: Option<&OutputStore>) -> bool {
487    let Some(store) = output_store else {
488        return false;
489    };
490    let Ok(value) = serde_json::from_str::<serde_json::Value>(content) else {
491        return false;
492    };
493    let Some(object) = value.as_object() else {
494        return false;
495    };
496    let Some(output_id) = object.get("output_id").and_then(serde_json::Value::as_str) else {
497        return false;
498    };
499    if object
500        .get("content")
501        .and_then(serde_json::Value::as_str)
502        .is_none()
503    {
504        return false;
505    }
506    let Some(total_bytes) = object
507        .get("total_bytes")
508        .and_then(serde_json::Value::as_u64)
509        .and_then(|value| usize::try_from(value).ok())
510    else {
511        return false;
512    };
513    let Some(next) = object.get("next").and_then(serde_json::Value::as_object) else {
514        return false;
515    };
516    let Some(mode) = next.get("mode").and_then(serde_json::Value::as_str) else {
517        return false;
518    };
519    let Some(offset) = next
520        .get("offset")
521        .and_then(serde_json::Value::as_u64)
522        .and_then(|value| usize::try_from(value).ok())
523    else {
524        return false;
525    };
526    let Some(has_more) = next.get("has_more").and_then(serde_json::Value::as_bool) else {
527        return false;
528    };
529    let total_lines = object
530        .get("total_lines")
531        .and_then(serde_json::Value::as_u64)
532        .and_then(|value| usize::try_from(value).ok());
533    store.validates_pagination(output_id, mode, offset, total_bytes, total_lines, has_more)
534}
535
536fn output_dir(session_dir: &Path) -> PathBuf {
537    session_dir.join("tool_outputs")
538}
539
540fn write_output_file(session_dir: &Path, output_id: &str, content: &str) -> Option<()> {
541    let out_dir = output_dir(session_dir);
542    std::fs::create_dir_all(&out_dir).ok()?;
543    let path = out_dir.join(format!("{output_id}.txt"));
544    let mut file = std::fs::OpenOptions::new()
545        .write(true)
546        .create_new(true)
547        .open(&path)
548        .ok()?;
549    if std::io::Write::write_all(&mut file, content.as_bytes()).is_ok() && file.sync_all().is_ok() {
550        return Some(());
551    }
552    drop(file);
553    let _ = std::fs::remove_file(path);
554    None
555}
556
557pub fn bounded_text_prefix(content: &str, budget: ToolOutputBudget) -> usize {
558    bounded_prefix_len(content, budget)
559}
560
561fn bounded_prefix_len(content: &str, budget: ToolOutputBudget) -> usize {
562    let mut lines = 1usize;
563    let mut line_bytes = 0usize;
564    let mut used = 0usize;
565    for (index, ch) in content.char_indices() {
566        let width = ch.len_utf8();
567        if ch == '\n' {
568            if used + width > budget.max_bytes {
569                return index;
570            }
571            used += width;
572            if lines >= budget.max_lines {
573                return index + width;
574            }
575            lines += 1;
576            line_bytes = 0;
577            continue;
578        }
579        if line_bytes + width > budget.max_line_bytes || used + width > budget.max_bytes {
580            return index;
581        }
582        line_bytes += width;
583        used += width;
584    }
585    content.len()
586}
587
588pub fn truncate_tool_results_in_message(
589    msg: &Message,
590    output_store: Option<&OutputStore>,
591) -> Option<Message> {
592    truncate_tool_results_in_message_with_budget(
593        msg,
594        output_store,
595        ToolOutputBudget {
596            max_lines: usize::MAX,
597            max_bytes: MAX_TOOL_RESULT_CHARS,
598            max_line_bytes: MAX_TOOL_RESULT_CHARS,
599        },
600    )
601}
602
603pub fn truncate_tool_results_in_message_with_budget(
604    msg: &Message,
605    output_store: Option<&OutputStore>,
606    budget: ToolOutputBudget,
607) -> Option<Message> {
608    let mut changed = false;
609    let parts: Vec<MessagePart> = msg
610        .parts
611        .iter()
612        .map(|part| match part {
613            MessagePart::ToolResult {
614                tool_use_id,
615                content,
616                is_error,
617            } => {
618                let truncated = truncate_tool_result_content_with_budget(
619                    content,
620                    tool_use_id,
621                    output_store,
622                    budget,
623                );
624                if truncated.len() != content.len() || truncated != *content {
625                    changed = true;
626                    MessagePart::ToolResult {
627                        tool_use_id: tool_use_id.clone(),
628                        content: truncated,
629                        is_error: *is_error,
630                    }
631                } else {
632                    part.clone()
633                }
634            }
635            _ => part.clone(),
636        })
637        .collect();
638
639    if !changed {
640        return None;
641    }
642    Some(Message {
643        role: msg.role,
644        parts,
645        turn_id: msg.turn_id.clone(),
646        origin: MessageOrigin::User,
647    })
648}
649
650pub fn maybe_truncate_tool_message(msg: &Message, output_store: Option<&OutputStore>) -> Message {
651    maybe_truncate_tool_message_with_budget(
652        msg,
653        output_store,
654        ToolOutputBudget {
655            max_lines: usize::MAX,
656            max_bytes: MAX_TOOL_RESULT_CHARS,
657            max_line_bytes: MAX_TOOL_RESULT_CHARS,
658        },
659    )
660}
661
662pub fn maybe_truncate_tool_message_with_budget(
663    msg: &Message,
664    output_store: Option<&OutputStore>,
665    budget: ToolOutputBudget,
666) -> Message {
667    if !matches!(msg.role, MessageRole::Tool) {
668        return msg.clone();
669    }
670    truncate_tool_results_in_message_with_budget(msg, output_store, budget)
671        .unwrap_or_else(|| msg.clone())
672}
673
674pub fn spill_dir(session_dir: &Path) -> PathBuf {
675    session_dir.join("tool_outputs")
676}
677
678#[cfg(test)]
679mod output_store_tests {
680    use super::*;
681    use tempfile::TempDir;
682
683    fn budget() -> ToolOutputBudget {
684        ToolOutputBudget {
685            max_lines: 2,
686            max_bytes: 32,
687            max_line_bytes: 16,
688        }
689    }
690
691    fn id(notice: &str) -> String {
692        notice
693            .split_once("output_id=")
694            .unwrap()
695            .1
696            .split([',', '.'])
697            .next()
698            .unwrap()
699            .to_string()
700    }
701
702    #[test]
703    fn opaque_id_hides_path_and_survives_reopen() {
704        let dir = TempDir::new().unwrap();
705        let store = OutputStore::at(dir.path());
706        let notice = truncate_tool_result_content_with_budget(
707            "one\ntwo\nthree\n",
708            "x",
709            Some(&store),
710            budget(),
711        );
712        let output_id = id(&notice);
713        assert!(!notice.contains(dir.path().to_string_lossy().as_ref()));
714        assert!(!notice.contains("fs.read"));
715        let page = OutputStore::at(dir.path())
716            .read_lines(&output_id, 1, 1, ToolOutputBudget::default())
717            .unwrap();
718        assert_eq!(page.content, "two\n");
719        assert_eq!(page.next_offset, 2);
720    }
721
722    #[test]
723    fn continuous_line_and_byte_reads_reconstruct_full_output() {
724        let dir = TempDir::new().unwrap();
725        let long_line = "前缀🚀".repeat(4096);
726        let full = format!("第一行\n{long_line}\n最后一行\n");
727        let store = OutputStore::at(dir.path());
728        let output_id = store.register("continuous", &full).unwrap();
729
730        let first = store
731            .read_lines(&output_id, 0, 1, ToolOutputBudget::default())
732            .unwrap();
733        assert_eq!(first.content, "第一行\n");
734        let long_line_error = store.read_lines(
735            &output_id,
736            first.next_offset,
737            1,
738            ToolOutputBudget {
739                max_lines: 1,
740                max_bytes: 8192,
741                max_line_bytes: 8192,
742            },
743        );
744        assert!(long_line_error.is_err());
745
746        let mut byte_offset = 0;
747        let mut bytes = String::new();
748        loop {
749            let page = store
750                .read_bytes(
751                    &output_id,
752                    byte_offset,
753                    257,
754                    ToolOutputBudget {
755                        max_lines: 100,
756                        max_bytes: 257,
757                        max_line_bytes: 257,
758                    },
759                )
760                .unwrap();
761            assert!(page.next_offset > byte_offset || !page.has_more);
762            bytes.push_str(&page.content);
763            byte_offset = page.next_offset;
764            if !page.has_more {
765                break;
766            }
767        }
768        assert_eq!(bytes, full);
769    }
770
771    #[test]
772    fn ids_are_session_scoped_and_ranges_are_exact() {
773        let left = TempDir::new().unwrap();
774        let right = TempDir::new().unwrap();
775        let store = OutputStore::at(left.path());
776        let output_id = store.register("x", "one\ntwo\nthree").unwrap();
777        assert!(
778            OutputStore::at(right.path())
779                .read_bytes(&output_id, 0, 8, ToolOutputBudget::default())
780                .is_err()
781        );
782        let page = store
783            .read_bytes(&output_id, 4, 4, ToolOutputBudget::default())
784            .unwrap();
785        assert_eq!(page.content, "two\n");
786        assert_eq!(page.next_offset, 8);
787    }
788
789    #[test]
790    fn valid_pagination_envelope_is_preserved_only_for_readable_output() {
791        let dir = TempDir::new().unwrap();
792        let store = OutputStore::at(dir.path());
793        let output_id = store.register("x", "完整内容").unwrap();
794        let envelope = serde_json::json!({
795            "content": "完整",
796            "output_id": output_id,
797            "total_bytes": "完整内容".len(),
798            "next": {"mode": "bytes", "offset": 12, "has_more": false}
799        })
800        .to_string();
801        assert_eq!(
802            truncate_tool_result_content_with_budget(&envelope, "x", Some(&store), budget()),
803            envelope
804        );
805
806        let unrelated_id = store.register("unrelated", "另一个注册输出").unwrap();
807        let forged = serde_json::json!({
808            "content": "完整",
809            "output_id": unrelated_id,
810            "total_bytes": "完整内容".len() + 1,
811            "next": {"mode": "bytes", "offset": 12, "has_more": false}
812        })
813        .to_string();
814        let truncated =
815            truncate_tool_result_content_with_budget(&forged, "x", Some(&store), budget());
816        assert!(truncated.contains("Output truncated"));
817        assert_ne!(truncated, forged);
818    }
819
820    #[test]
821    fn repeated_truncation_keeps_one_opaque_output() {
822        let dir = TempDir::new().unwrap();
823        let store = OutputStore::at(dir.path());
824        let original = "x".repeat(100);
825        let first =
826            truncate_tool_result_content_with_budget(&original, "x", Some(&store), budget());
827        assert!(first.contains("output_id=out_"));
828        assert!(first.contains("output.read(output_id:"));
829        assert!(first.contains("query:"));
830        let second = truncate_tool_result_content_with_budget(&first, "x", Some(&store), budget());
831        assert_eq!(first, second);
832        assert_eq!(std::fs::read_dir(spill_dir(dir.path())).unwrap().count(), 1);
833
834        let forged = first.replace("total_bytes=100", "total_bytes=101");
835        let retruncated =
836            truncate_tool_result_content_with_budget(&forged, "x", Some(&store), budget());
837        assert_ne!(retruncated, forged);
838        assert_eq!(std::fs::read_dir(spill_dir(dir.path())).unwrap().count(), 2);
839    }
840
841    #[test]
842    fn search_returns_paginated_one_based_hits() {
843        let dir = TempDir::new().unwrap();
844        let store = OutputStore::at(dir.path());
845        let output_id = store
846            .register("x", "zero\nneedle one\nneedle two\nend")
847            .unwrap();
848
849        let first = store.search(&output_id, "needle", 0, 1).unwrap();
850        assert_eq!(first.total_matches, 2);
851        assert_eq!(first.hits[0].line, 2);
852        assert!(first.has_more);
853        assert_eq!(first.next_match, 1);
854
855        let second = store
856            .search(&output_id, "needle", first.next_match, 1)
857            .unwrap();
858        assert_eq!(second.hits[0].line, 3);
859        assert!(!second.has_more);
860    }
861
862    fn field<'a>(fields: &'a [(String, Value)], name: &str) -> &'a Value {
863        fields
864            .iter()
865            .find_map(|(field, value)| (field == name).then_some(value))
866            .unwrap_or_else(|| panic!("missing {name}"))
867    }
868
869    #[tokio::test]
870    async fn output_read_tool_returns_exact_byte_and_line_envelopes() {
871        let dir = TempDir::new().unwrap();
872        let store = Arc::new(OutputStore::at(dir.path()));
873        let output_id = store.register("x", "one\ntwo\nthree").unwrap();
874        let ctx = ToolCtx::new().with_output_store(store);
875
876        let bytes = OutputRead
877            .call(
878                ToolArgs {
879                    positional: vec![],
880                    named: vec![
881                        ("output_id".into(), Value::Str(output_id.clone())),
882                        ("byte_offset".into(), Value::Int(4)),
883                        ("byte_limit".into(), Value::Int(4)),
884                    ],
885                },
886                &ctx,
887            )
888            .await
889            .unwrap();
890        let Value::Struct(bytes) = bytes else {
891            panic!("expected byte page");
892        };
893        assert!(matches!(field(&bytes, "content"), Value::Str(value) if value == "two\n"));
894        assert!(matches!(field(&bytes, "mode"), Value::Str(value) if value == "bytes"));
895        assert!(matches!(field(&bytes, "offset"), Value::Int(4)));
896        assert!(matches!(field(&bytes, "next_offset"), Value::Int(8)));
897        assert!(matches!(field(&bytes, "has_more"), Value::Bool(true)));
898
899        let lines = OutputRead
900            .call(
901                ToolArgs {
902                    positional: vec![],
903                    named: vec![
904                        ("output_id".into(), Value::Str(output_id)),
905                        ("line_offset".into(), Value::Int(1)),
906                        ("line_limit".into(), Value::Int(1)),
907                    ],
908                },
909                &ctx,
910            )
911            .await
912            .unwrap();
913        let Value::Struct(lines) = lines else {
914            panic!("expected line page");
915        };
916        assert!(matches!(field(&lines, "content"), Value::Str(value) if value == "two\n"));
917        assert!(matches!(field(&lines, "mode"), Value::Str(value) if value == "lines"));
918        assert!(matches!(field(&lines, "offset"), Value::Int(1)));
919        assert!(matches!(field(&lines, "next_offset"), Value::Int(2)));
920        assert!(matches!(field(&lines, "has_more"), Value::Bool(true)));
921    }
922
923    #[tokio::test]
924    async fn output_read_tool_rejects_non_progressing_and_mixed_pagination() {
925        let dir = TempDir::new().unwrap();
926        let store = Arc::new(OutputStore::at(dir.path()));
927        let output_id = store.register("x", "content").unwrap();
928        let ctx = ToolCtx::new().with_output_store(store);
929
930        for limit in ["line_limit", "byte_limit"] {
931            let error = OutputRead
932                .call(
933                    ToolArgs {
934                        positional: vec![],
935                        named: vec![
936                            ("output_id".into(), Value::Str(output_id.clone())),
937                            (limit.into(), Value::Int(0)),
938                        ],
939                    },
940                    &ctx,
941                )
942                .await
943                .unwrap_err();
944            assert!(matches!(
945                error,
946                RuntimeError::TypeMismatch { expected, .. }
947                    if expected == format!("positive integer {limit}")
948            ));
949        }
950
951        let error = OutputRead
952            .call(
953                ToolArgs {
954                    positional: vec![],
955                    named: vec![
956                        ("output_id".into(), Value::Str(output_id)),
957                        ("line_offset".into(), Value::Int(0)),
958                        ("byte_offset".into(), Value::Int(0)),
959                    ],
960                },
961                &ctx,
962            )
963            .await
964            .unwrap_err();
965        assert!(matches!(
966            error,
967            RuntimeError::ToolFailed(message) if message.contains("not both")
968        ));
969    }
970
971    #[tokio::test]
972    async fn output_read_tool_search_returns_line_hits() {
973        let dir = TempDir::new().unwrap();
974        let store = Arc::new(OutputStore::at(dir.path()));
975        let output_id = store.register("x", "zero\nneedle\nend").unwrap();
976        let ctx = ToolCtx::new().with_output_store(store);
977
978        let result = OutputRead
979            .call(
980                ToolArgs {
981                    positional: vec![],
982                    named: vec![
983                        ("output_id".into(), Value::Str(output_id)),
984                        ("query".into(), Value::Str("needle".into())),
985                    ],
986                },
987                &ctx,
988            )
989            .await
990            .unwrap();
991        let Value::Struct(fields) = result else {
992            panic!("expected search result");
993        };
994        assert!(matches!(field(&fields, "total_matches"), Value::Int(1)));
995        assert!(matches!(field(&fields, "next_match"), Value::Int(1)));
996        let Value::List(hits) = field(&fields, "hits") else {
997            panic!("expected hits");
998        };
999        let Value::Struct(hit) = &hits[0] else {
1000            panic!("expected hit");
1001        };
1002        assert!(matches!(field(hit, "line"), Value::Int(2)));
1003    }
1004
1005    #[test]
1006    fn output_read_is_registered_in_tier_zero() {
1007        let registry = crate::tool::ToolRegistry::new();
1008        crate::tools::register_tier_zero(&registry);
1009        let tool = registry.get("output.read").expect("registered output.read");
1010        assert_eq!(tool.tier(), Tier::Zero);
1011    }
1012}