1use serde_json::json;
5
6use super::input::{InputReader, type_name};
7use super::js_number_text;
8use crate::error::{Error, Result};
9use crate::state_store::StateStore;
10use crate::tools::{FunctionTool, ToolError};
11use crate::types::{JsonObject, JsonSchema, JsonValue};
12
13const DEFAULT_MAX_NOTEBOOK_SIZE_BYTES: usize = 1_048_576;
14const MODES: [&str; 5] = ["create", "list", "read", "write", "clear"];
15const STATE_KEY: &str = "notebooks";
16
17pub(crate) const NOTEBOOK_DESCRIPTION: &str = "Manages text notebooks for note-taking and documentation. Supports create, list, read, write (append, replace, or insert), and clear operations. In write mode: newStr alone appends to the end; newStr with oldStr replaces matching text; newStr with insertLine inserts at a position. A write only succeeds on a notebook that already exists: use list to check, or create to start a new one (create replaces any existing content). Notebooks persist within the agent invocation.";
19
20const WRITE_REQUIREMENTS: &str = "Write operation requires newStr, optionally with oldStr for replacement or insertLine for insertion; oldStr and insertLine cannot be combined";
21
22#[derive(Debug, Clone, Default, bon::Builder)]
24#[builder(on(String, into))]
25pub struct MakeNotebookOptions {
26 pub name: Option<String>,
28 pub description: Option<String>,
30 pub max_notebook_size_bytes: Option<usize>,
32}
33
34fn input_schema() -> JsonSchema {
35 json!({
36 "type": "object",
37 "properties": {
38 "mode": {
39 "type": "string",
40 "enum": MODES,
41 "description": "The operation to perform: `create`, `list`, `read`, `write`, `clear`."
42 },
43 "name": {"description": "Name of the notebook to operate on. Defaults to \"default\".", "type": "string"},
44 "newStr": {
45 "description": "Text to append, or the new string for replacement and insertion operations.",
46 "type": "string"
47 },
48 "readRange": {
49 "description": "Optional parameter of `read` command. Line range to show [start, end]. Supports negative indices.",
50 "type": "array",
51 "items": {"type": "number"}
52 },
53 "oldStr": {"description": "String to replace in write mode when doing text replacement.", "type": "string"},
54 "insertLine": {
55 "description": "Line number (int) or search text (str) for insertion point in write mode.\nSupports negative indices.",
56 "type": ["string", "number"]
57 }
58 },
59 "required": ["mode"],
60 "additionalProperties": false
61 })
62}
63
64#[must_use]
66pub fn notebook() -> FunctionTool {
67 build(
68 "notebook".to_owned(),
69 NOTEBOOK_DESCRIPTION.to_owned(),
70 DEFAULT_MAX_NOTEBOOK_SIZE_BYTES,
71 )
72}
73
74pub fn make_notebook(options: MakeNotebookOptions) -> Result<FunctionTool> {
92 let name = options.name.unwrap_or_else(|| "notebook".to_owned());
93 if name.is_empty() {
94 return Err(Error::other("name must be a non-empty string"));
95 }
96 let max_size = options
97 .max_notebook_size_bytes
98 .unwrap_or(DEFAULT_MAX_NOTEBOOK_SIZE_BYTES);
99 if max_size < 1 {
100 return Err(Error::other("maxNotebookSizeBytes must be a positive integer"));
101 }
102 let description = options.description.unwrap_or_else(|| NOTEBOOK_DESCRIPTION.to_owned());
103 Ok(build(name, description, max_size))
104}
105
106fn build(name: String, description: String, max_size: usize) -> FunctionTool {
107 FunctionTool::builder(name, description)
108 .input_schema(input_schema())
109 .callback(move |input, context| {
110 let state = context.agent().app_state().clone();
111 async move { run(&state, &input, max_size).map(JsonValue::String) }
112 })
113}
114
115#[derive(Clone, Copy)]
116enum InsertLine<'a> {
117 Text(&'a str),
118 Number(f64),
119}
120
121struct Input<'a> {
122 mode: &'a str,
123 name: &'a str,
124 new_str: Option<&'a str>,
125 read_range: Option<Vec<f64>>,
126 old_str: Option<&'a str>,
127 insert_line: Option<InsertLine<'a>>,
128}
129
130fn parse(input: &JsonValue) -> std::result::Result<Input<'_>, ToolError> {
131 let mut reader = InputReader::new(input);
132 let mode = reader.one_of("mode", &MODES);
133 let name = reader.optional_string("name");
134 let new_str = reader.optional_string("newStr");
135 let read_range = match reader.get("readRange") {
136 None => None,
137 Some(JsonValue::Array(items)) => {
138 let numbers: Option<Vec<f64>> = items.iter().map(JsonValue::as_f64).collect();
139 if numbers.is_none() {
140 reader.issue("readRange", "Invalid input: expected array of numbers");
141 }
142 numbers
143 }
144 Some(other) => {
145 let message = format!("Invalid input: expected array, received {}", type_name(Some(other)));
146 reader.issue("readRange", message);
147 None
148 }
149 };
150 let old_str = reader.optional_string("oldStr");
151 let insert_line = match reader.get("insertLine") {
152 None => None,
153 Some(JsonValue::String(text)) => Some(InsertLine::Text(text)),
154 Some(value) => match value.as_f64() {
155 Some(number) => Some(InsertLine::Number(number)),
156 None => {
157 reader.issue("insertLine", "Invalid input: expected string | number");
158 None
159 }
160 },
161 };
162 if mode == Some("write") {
163 let has_replacement = old_str.is_some() && new_str.is_some();
164 let has_insertion = insert_line.is_some() && new_str.is_some();
165 let has_append = old_str.is_none() && insert_line.is_none() && new_str.is_some();
166 let ambiguous = old_str.is_some() && insert_line.is_some();
167 if !(has_replacement || has_insertion || has_append) || ambiguous {
168 reader.root_issue(WRITE_REQUIREMENTS);
169 }
170 }
171 reader.finish()?;
172 Ok(Input {
173 mode: mode.unwrap_or_default(),
174 name: name.unwrap_or("default"),
175 new_str,
176 read_range,
177 old_str,
178 insert_line,
179 })
180}
181
182fn load(state: &StateStore) -> std::result::Result<JsonObject, ToolError> {
183 let mut notebooks = match state.get_value(STATE_KEY) {
184 None | Some(JsonValue::Null) => JsonObject::new(),
185 Some(JsonValue::Object(notebooks)) => {
186 if notebooks.values().any(|value| !value.is_string()) {
187 return Err(ToolError::msg(
188 "Malformed notebooks state: keys and values must be strings",
189 ));
190 }
191 notebooks
192 }
193 Some(_) => return Err(ToolError::msg("Malformed notebooks state: expected a plain object")),
194 };
195 if notebooks.is_empty() {
196 notebooks.insert("default".to_owned(), JsonValue::String(String::new()));
197 }
198 Ok(notebooks)
199}
200
201fn content<'a>(notebooks: &'a JsonObject, name: &str) -> std::result::Result<&'a str, ToolError> {
202 notebooks
203 .get(name)
204 .and_then(JsonValue::as_str)
205 .ok_or_else(|| ToolError::msg(format!("Notebook '{name}' not found")))
206}
207
208fn run(state: &StateStore, input: &JsonValue, max_size: usize) -> std::result::Result<String, ToolError> {
209 let input = parse(input)?;
210 let mut notebooks = load(state)?;
211 let name = input.name;
212 let result = match input.mode {
213 "create" => create(&mut notebooks, name, input.new_str),
214 "list" => list(¬ebooks),
215 "read" => read(¬ebooks, name, input.read_range.as_deref())?,
216 "write" => write(&mut notebooks, name, input.old_str, input.new_str, input.insert_line)?,
217 _ => clear(&mut notebooks, name)?,
218 };
219 if matches!(input.mode, "create" | "write") {
220 let size = notebooks.get(name).and_then(JsonValue::as_str).map_or(0, str::len);
221 if size > max_size {
222 return Err(ToolError::msg(format!(
223 "Notebook '{name}' content ({size} bytes) would exceed maximum of {max_size} bytes"
224 )));
225 }
226 }
227 if matches!(input.mode, "create" | "write" | "clear") {
228 state.set(STATE_KEY, JsonValue::Object(notebooks))?;
229 }
230 Ok(result)
231}
232
233fn create(notebooks: &mut JsonObject, name: &str, new_str: Option<&str>) -> String {
234 notebooks.insert(
235 name.to_owned(),
236 JsonValue::String(new_str.unwrap_or_default().to_owned()),
237 );
238 let described = if new_str.is_some_and(|text| !text.is_empty()) {
239 " with specified content"
240 } else {
241 " (empty)"
242 };
243 format!("Created notebook '{name}'{described}")
244}
245
246fn list(notebooks: &JsonObject) -> String {
247 let details: Vec<String> = notebooks
248 .iter()
249 .map(|(name, content)| {
250 let content = content.as_str().unwrap_or_default();
251 if content.is_empty() {
252 format!("- {name}: Empty")
253 } else {
254 format!("- {name}: {} lines", content.split('\n').count())
255 }
256 })
257 .collect();
258 format!("Available notebooks:\n{}", details.join("\n"))
259}
260
261fn read(notebooks: &JsonObject, name: &str, read_range: Option<&[f64]>) -> std::result::Result<String, ToolError> {
262 let content = content(notebooks, name)?;
263 let Some(read_range) = read_range else {
264 if content.is_empty() {
265 return Ok(format!("Notebook '{name}' is empty"));
266 }
267 return Ok(content.to_owned());
268 };
269 let lines: Vec<&str> = content.split('\n').collect();
270 let (Some(&first), Some(&second)) = (read_range.first(), read_range.get(1)) else {
271 return Err(ToolError::msg(
272 "`readRange` must be a list of two integers: `[start, end]`",
273 ));
274 };
275 #[allow(clippy::cast_precision_loss, reason = "line counts are far below 2^53")]
276 let count = lines.len() as f64;
277 let start = if first < 0.0 { count + first + 1.0 } else { first };
278 let end = if second < 0.0 { count + second + 1.0 } else { second };
279 let mut selected = Vec::new();
280 let mut line_number = start.max(1.0);
281 while line_number <= end.min(count) {
282 let line = if line_number.fract() == 0.0 {
283 #[allow(
284 clippy::cast_possible_truncation,
285 clippy::cast_sign_loss,
286 reason = "whole and in range"
287 )]
288 lines[line_number as usize - 1]
289 } else {
290 "undefined"
291 };
292 selected.push(format!("{}: {line}", js_number_text(line_number)));
293 line_number += 1.0;
294 }
295 if selected.is_empty() {
296 return Ok(format!(
297 "No lines found in range [{}, {}]. Notebook '{name}' has {} line(s).",
298 js_number_text(first),
299 js_number_text(second),
300 lines.len()
301 ));
302 }
303 Ok(selected.join("\n"))
304}
305
306fn write(
307 notebooks: &mut JsonObject,
308 name: &str,
309 old_str: Option<&str>,
310 new_str: Option<&str>,
311 insert_line: Option<InsertLine<'_>>,
312) -> std::result::Result<String, ToolError> {
313 let current = content(notebooks, name)?.to_owned();
314 let Some(new_str) = new_str else {
315 return Err(ToolError::msg("Invalid write operation"));
316 };
317 let updated = match (old_str, insert_line) {
318 (None, None) => {
319 if new_str.is_empty() {
320 return Ok(format!("No changes made to notebook '{name}'"));
321 }
322 let separator = if !current.is_empty() && !current.ends_with('\n') {
323 "\n"
324 } else {
325 ""
326 };
327 notebooks.insert(
328 name.to_owned(),
329 JsonValue::String(format!("{current}{separator}{new_str}")),
330 );
331 return Ok(format!("Appended text to notebook '{name}'"));
332 }
333 (Some(old_str), _) => {
334 if !current.contains(old_str) {
335 return Err(ToolError::msg(format!(
336 "String '{old_str}' not found in notebook '{name}'"
337 )));
338 }
339 notebooks.insert(
340 name.to_owned(),
341 JsonValue::String(current.replacen(old_str, new_str, 1)),
342 );
343 return Ok(format!("Replaced text in notebook '{name}'"));
344 }
345 (None, Some(insert_line)) => insert(¤t, name, insert_line, new_str)?,
346 };
347 notebooks.insert(name.to_owned(), JsonValue::String(updated.0));
348 Ok(format!(
349 "Inserted text at line {} in notebook '{name}'",
350 js_number_text(updated.1 + 2.0)
351 ))
352}
353
354fn insert(
356 current: &str,
357 name: &str,
358 insert_line: InsertLine<'_>,
359 new_str: &str,
360) -> std::result::Result<(String, f64), ToolError> {
361 let mut lines: Vec<&str> = current.split('\n').collect();
362 #[allow(clippy::cast_precision_loss, reason = "line counts are far below 2^53")]
363 let count = lines.len() as f64;
364 let line_number = match insert_line {
365 InsertLine::Text(text) => match lines.iter().position(|line| line.contains(text)) {
366 #[allow(clippy::cast_precision_loss, reason = "line counts are far below 2^53")]
367 Some(index) => index as f64,
368 None => {
369 return Err(ToolError::msg(format!("Text '{text}' not found in notebook '{name}'")));
370 }
371 },
372 InsertLine::Number(number) if number < 0.0 => count + number,
373 InsertLine::Number(number) => number - 1.0,
374 };
375 if line_number < -1.0 || line_number > count {
376 return Err(ToolError::msg("Line number out of range"));
377 }
378 #[allow(
379 clippy::cast_possible_truncation,
380 clippy::cast_sign_loss,
381 reason = "checked to be in range"
382 )]
383 let at = ((line_number + 1.0).trunc() as usize).min(lines.len());
384 lines.insert(at, new_str);
385 Ok((lines.join("\n"), line_number))
386}
387
388fn clear(notebooks: &mut JsonObject, name: &str) -> std::result::Result<String, ToolError> {
389 content(notebooks, name)?;
390 notebooks.insert(name.to_owned(), JsonValue::String(String::new()));
391 Ok(format!("Cleared notebook '{name}'"))
392}
393
394#[cfg(test)]
395mod tests;