Skip to main content

agent_types/
tool.rs

1//! Tool-related pure types: Content, ToolMetadata, ToolExposure, ActivationContext.
2
3use serde::{Deserialize, Serialize};
4use std::path::PathBuf;
5
6use crate::session::SessionId;
7use llm_trait::message::ImageAttachment;
8
9/// Structured content returned by a tool, aligned with the MCP `content`
10/// array shape (no envelope, no orchestration/failure/truncation semantics).
11///
12/// `Text` is the textual face and `Image` the pictorial one: a tool that
13/// hands the model something to *look at* returns an `Image`, and
14/// [`content_images`] turns those into the attachments that ride the tool
15/// result to the provider (`content_text` keeps only the words). `Detail`
16/// carries machine-readable metadata (e.g. edit line numbers) that the UI
17/// can consume but the LLM never sees.
18#[derive(Clone, Debug, Serialize, Deserialize)]
19#[serde(tag = "type", rename_all = "snake_case")]
20pub enum Content {
21    Text {
22        text: String,
23    },
24    /// Base64-encoded image payload.
25    Image {
26        data: String,
27        mime_type: String,
28    },
29    /// Machine-readable metadata for UI consumption (not sent to the LLM).
30    Detail {
31        data: serde_json::Value,
32    },
33    /// A stored observation artifact referenced by id (M3c,
34    /// action-executor-design §6): the body is fetched on demand via
35    /// `obs.fetch`; the model face is the summary+reference line carried in
36    /// `Text` — so this typed channel marks the artifact for UI/logs without
37    /// duplicating the line.
38    Artifact {
39        /// Stable store id (`art_<seq>`).
40        capture_id: String,
41        /// What the body is (`"stdout"` / `"stderr"` / `"observation"` / the
42        /// emitter's own label).
43        kind: String,
44        /// The truncation-heuristic glimpse of the body.
45        summary: String,
46    },
47}
48
49impl Content {
50    pub fn text(s: impl Into<String>) -> Self {
51        Content::Text { text: s.into() }
52    }
53
54    pub fn image(data: impl Into<String>, mime_type: impl Into<String>) -> Self {
55        Content::Image {
56            data: data.into(),
57            mime_type: mime_type.into(),
58        }
59    }
60
61    pub fn detail(data: serde_json::Value) -> Self {
62        Content::Detail { data }
63    }
64
65    pub fn artifact(
66        capture_id: impl Into<String>,
67        kind: impl Into<String>,
68        summary: impl Into<String>,
69    ) -> Self {
70        Content::Artifact {
71            capture_id: capture_id.into(),
72            kind: kind.into(),
73            summary: summary.into(),
74        }
75    }
76}
77
78impl From<Content> for Vec<Content> {
79    fn from(c: Content) -> Self {
80        vec![c]
81    }
82}
83
84/// Join the textual portion of tool output into a single string for display
85/// and session history. Non-text variants (e.g. `Image`, `Detail`) are skipped;
86/// `Artifact` is skipped too — its model face is the summary+reference line
87/// already carried in `Text` (the typed channel marks the artifact for UI).
88pub fn content_text(contents: &[Content]) -> String {
89    contents
90        .iter()
91        .filter_map(|c| match c {
92            Content::Text { text } => Some(text.as_str()),
93            Content::Image { .. } | Content::Detail { .. } | Content::Artifact { .. } => None,
94        })
95        .collect::<Vec<_>>()
96        .join("\n")
97}
98
99/// Extract the pictures a tool's output hands the model to look at, in the
100/// order they were produced — the image face of a tool result, exactly as
101/// [`content_text`] is its textual face. Empty when the output carried none.
102pub fn content_images(contents: &[Content]) -> Vec<ImageAttachment> {
103    contents
104        .iter()
105        .filter_map(|c| match c {
106            Content::Image { data, mime_type } => Some(ImageAttachment::Base64 {
107                data: data.clone(),
108                media_type: Some(mime_type.clone()),
109                detail: None,
110            }),
111            _ => None,
112        })
113        .collect()
114}
115
116/// Extract structured detail metadata from tool output. When multiple `Detail`
117/// entries exist, they are merged into a single object. Returns `None` if no
118/// `Detail` entries are present.
119pub fn content_details(contents: &[Content]) -> Option<serde_json::Value> {
120    let details: Vec<&serde_json::Value> = contents
121        .iter()
122        .filter_map(|c| match c {
123            Content::Detail { data } => Some(data),
124            _ => None,
125        })
126        .collect();
127    match details.len() {
128        0 => None,
129        1 => Some(details[0].clone()),
130        _ => {
131            // Merge multiple detail objects into one
132            let mut merged = serde_json::Map::new();
133            for d in details {
134                if let Some(obj) = d.as_object() {
135                    for (k, v) in obj {
136                        merged.insert(k.clone(), v.clone());
137                    }
138                }
139            }
140            Some(serde_json::Value::Object(merged))
141        }
142    }
143}
144
145/// Machine-readable metadata for a registered tool — origin, version, and
146/// runtime requirements in a stable shape consumers can inspect without
147/// parsing the LLM-facing definition JSON.
148#[derive(Clone, Debug, Serialize, Deserialize)]
149pub struct ToolMetadata {
150    /// Tool name (matches `Tool::name`).
151    pub name: String,
152    /// Human-readable description.
153    pub description: String,
154    /// Where this tool comes from: a crate name (e.g. `"phi-tools"`), a
155    /// framework identifier (`"agent-base"`, `"agent-works"`), or
156    /// `"custom"` for user-defined tools.
157    pub origin: String,
158    /// Crate / package version, or `"unknown"` when built outside a crate.
159    pub version: String,
160    /// Optional runtime requirements or capabilities this tool depends on.
161    pub requirements: Vec<String>,
162}
163
164/// Visibility level of a tool to the LLM model.
165///
166/// Controls whether a tool appears in the tool definitions sent to the model
167/// each turn. Defaults to `Direct` for backward compatibility.
168#[derive(Clone, Debug, PartialEq, Eq)]
169pub enum ToolExposure {
170    /// Always visible to the model. This is the default.
171    Direct,
172    /// Conditionally visible — the tool decides via `Tool::should_activate`.
173    Deferred,
174    /// Never visible to the model (internal/framework tools).
175    Hidden,
176}
177
178/// Context passed to `Tool::should_activate` for Deferred tools.
179///
180/// Built once per react-loop iteration; tools inspect it to decide
181/// whether they should be exposed to the model this turn.
182#[derive(Clone, Debug)]
183pub struct ActivationContext {
184    /// Current session ID.
185    pub session_id: SessionId,
186    /// Names of tools already activated (Direct + activated Deferred) this turn.
187    pub current_tools: Vec<String>,
188    /// Workspace / working directory path.
189    pub workspace: PathBuf,
190}