Skip to main content

pi_core/
context_metadata.rs

1//! Typed metadata for tool results used by context projection.
2//!
3//! This metadata lets the projection engine choose a strategy
4//! based on structured data rather than guessing from raw text.
5
6use serde::{Deserialize, Serialize};
7use ts_rs::TS;
8
9/// What kind of content a tool result contains.
10#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
11#[serde(rename_all = "snake_case")]
12pub enum ContentKind {
13    FileRead,
14    CommandOutput,
15    Diff,
16    SearchResults,
17    DirectoryListing,
18    GenericText,
19}
20
21/// Projection strategy for a single tool result.
22#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
23#[serde(rename_all = "snake_case", tag = "type")]
24pub enum ContextStrategy {
25    #[serde(rename = "keep_full")]
26    KeepFull,
27    #[serde(rename = "head")]
28    Head { max_chars: usize },
29    #[serde(rename = "tail")]
30    Tail { max_chars: usize },
31    #[serde(rename = "head_tail")]
32    HeadTail { head_chars: usize, tail_chars: usize },
33    #[serde(rename = "drop_if_old")]
34    DropIfOld,
35    /// Applied by microcompact: old tool result replaced with a one-line summary.
36    #[serde(rename = "microcompacted")]
37    Microcompacted,
38}
39
40/// Typed metadata that a host can attach to tool results for projection.
41#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
42pub struct ToolResultContext {
43    pub content_kind: ContentKind,
44    pub strategy: ContextStrategy,
45    pub original_chars: usize,
46    pub truncated_by_tool: bool,
47    #[serde(skip_serializing_if = "Option::is_none")]
48    pub path: Option<String>,
49    #[serde(skip_serializing_if = "Option::is_none")]
50    pub exit_code: Option<i32>,
51}
52
53/// Fallback strategy when metadata is missing, keyed by tool name.
54pub fn fallback_strategy(tool_name: &str) -> ContextStrategy {
55    match tool_name {
56        "read" => ContextStrategy::Head { max_chars: 2000 },
57        "bash" => ContextStrategy::Tail { max_chars: 2000 },
58        "edit" | "write" => ContextStrategy::KeepFull,
59        "grep" | "find" | "ls" => ContextStrategy::Head { max_chars: 2000 },
60        _ => ContextStrategy::Head { max_chars: 2000 },
61    }
62}