nb_api/client/core.rs
1use std::path::PathBuf;
2use std::process::Stdio;
3use std::sync::LazyLock;
4
5use regex::Regex;
6use tokio::process::Command;
7
8use crate::diagnostics::{append_warning, is_notebook_not_found};
9use crate::error::NbError;
10use crate::gate;
11use crate::git::derive_git_notebook_name;
12use crate::git_env::scrub_git_env;
13use crate::git_signing::apply_git_signing_env;
14use crate::nb_program::nb_program;
15use crate::transaction::Transaction;
16use crate::validate::{parse_qualified_selector, validate_notebook_name};
17use crate::{Config, NbClient};
18
19use super::read::notebook_dir_from_env;
20
21/// Regex to match ANSI/ISO 2022 escape sequences.
22///
23/// Covers:
24/// - Fe sequences: `ESC [@-Z\-_]` (single byte after ESC)
25/// - CSI sequences: `ESC [ ... m` (SGR colors, cursor control, etc.)
26/// - nF sequences: `ESC [ -/]* [0-~]` (character set designation like `ESC ( B`)
27static ANSI_REGEX: LazyLock<Regex> = LazyLock::new(|| {
28 Regex::new(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|[ -/]*[0-~])").unwrap()
29});
30
31/// Strip ANSI escape sequences from text.
32fn strip_ansi(text: &str) -> String {
33 ANSI_REGEX.replace_all(text, "").into_owned()
34}
35
36/// Result of probing a selector's textual classification via
37/// `nb show <selector> --type text`. Used by
38/// [`NbClient::show_note`](crate::NbClient::show_note) to decide whether
39/// the content-read path is safe.
40pub(super) enum ShowClassification {
41 /// `nb` classified the type as text. Caller proceeds to
42 /// the content-read path.
43 Textual,
44 /// `nb` classified the type as non-text (folder, archive,
45 /// image, audio, video, etc.). `actual_type` carries the
46 /// `nb`-reported type string (file extension or `folder`).
47 NonTextual { actual_type: String },
48 /// The probe could not classify the selector (selector not
49 /// found, internal error). Caller falls through to the
50 /// original show path so existing missing-selector
51 /// diagnostics are preserved.
52 ProbeFailure,
53}
54
55const FOLDER_REQUIRED_MESSAGE: &str = "This server is configured to require `folder` for new notes. Use the `nb.mkdir` tool to create new folders and the `nb.folders` tool to list existing folders.";
56
57impl NbClient {
58 /// Creates a new nb client.
59 ///
60 /// Uses the notebook from config if set, otherwise falls back to a
61 /// Git-derived notebook name. Does NOT read `NB_MCP_NOTEBOOK` —
62 /// that is an MCP-server-specific env var resolved by the server.
63 pub fn new(config: &Config) -> anyhow::Result<Self> {
64 let default_notebook = config
65 .notebook
66 .as_deref()
67 .map(String::from)
68 .or_else(derive_git_notebook_name);
69 Ok(Self {
70 default_notebook,
71 create_notebook: config.create_notebook,
72 disable_git_signing: config.disable_git_signing,
73 allow_top_level_notes: config.allow_top_level_notes,
74 gate_timeout: config.gate_timeout,
75 })
76 }
77
78 /// Begin a collect-then-commit [`Transaction`] for `notebook`.
79 ///
80 /// Construction performs no durable I/O and does not acquire the gate.
81 pub async fn transaction(
82 &self,
83 notebook: Option<&str>,
84 ) -> Result<Transaction, NbError> {
85 let notebook = self.resolve_notebook_name(notebook)?;
86 // Prefer filesystem existence under NB_DIR so plan construction does
87 // not invoke `nb` (which can auto-checkpoint a dirty worktree).
88 if notebook_dir_from_env(¬ebook).is_none() {
89 self.ensure_notebook(¬ebook).await?;
90 }
91 Ok(Transaction::new(self.clone(), notebook, self.gate_timeout))
92 }
93
94 /// Process-shared gate queue timeout configured on this client.
95 pub fn gate_timeout(&self) -> std::time::Duration {
96 self.gate_timeout
97 }
98
99 /// Notebook path without acquiring the notebook gate (caller holds gate or
100 /// is still resolving identity).
101 ///
102 /// Prefers `$NB_DIR/<notebook>` when that directory exists so path
103 /// resolution does not invoke `nb` (which can auto-checkpoint and clear a
104 /// dirty baseline before `Transaction::commit` inspects status).
105 pub(crate) async fn show_notebook_path_unguarded(
106 &self,
107 notebook: Option<&str>,
108 ) -> Result<PathBuf, NbError> {
109 let notebook = self.resolve_notebook_name(notebook)?;
110 if let Some(path) = notebook_dir_from_env(¬ebook) {
111 return Ok(path);
112 }
113 self.ensure_notebook(¬ebook).await?;
114 let output = self
115 .exec_vec(vec![
116 "notebooks".to_string(),
117 "show".to_string(),
118 notebook.clone(),
119 "--path".to_string(),
120 ])
121 .await?;
122 let path = output.trim();
123 if path.is_empty() {
124 return Err(NbError::CommandFailed {
125 command: format!("nb notebooks show {notebook} --path"),
126 stderr: "nb notebooks path output was empty".to_string(),
127 exit_code: None,
128 });
129 }
130 Ok(PathBuf::from(path))
131 }
132
133 pub(super) async fn with_notebook_gate<F, T>(
134 &self,
135 notebook: &str,
136 f: F,
137 ) -> Result<T, NbError>
138 where
139 F: std::future::Future<Output = Result<T, NbError>>,
140 {
141 let root = self.show_notebook_path_unguarded(Some(notebook)).await?;
142 let key = gate::git_common_dir_realpath(&root)?;
143 let _hold =
144 gate::acquire_notebook(key, self.gate_timeout, false).await?;
145 f.await
146 }
147
148 pub(super) fn require_folder_for_new_note(
149 &self,
150 folder: Option<&str>,
151 ) -> Result<(), NbError> {
152 if self.allow_top_level_notes
153 || folder.is_some_and(|value| !value.trim().is_empty())
154 {
155 return Ok(());
156 }
157 Err(NbError::ValidationError {
158 reason: FOLDER_REQUIRED_MESSAGE.to_string(),
159 location: None,
160 })
161 }
162
163 pub(super) async fn resolve_target_selector(
164 &self,
165 id: &str,
166 notebook: Option<&str>,
167 ) -> Result<(String, String), NbError> {
168 if let Some((embedded_notebook, path)) = parse_qualified_selector(id)?
169 {
170 let notebook = match notebook {
171 Some(value) => {
172 validate_notebook_name(value)?;
173 if value != embedded_notebook {
174 return Err(NbError::ValidationError {
175 reason: format!(
176 "ambiguous selector: id targets notebook `{embedded_notebook}`, but notebook field is `{value}`"
177 ),
178 location: None,
179 });
180 }
181 embedded_notebook.to_string()
182 },
183 _ => embedded_notebook.to_string(),
184 };
185 self.ensure_existing_notebook(¬ebook).await?;
186 return Ok((notebook, format!("{}:{}", embedded_notebook, path)));
187 }
188 let notebook = self.resolve_notebook(notebook).await?;
189 Ok((notebook.clone(), format!("{}:{}", notebook, id)))
190 }
191
192 pub(super) fn append_notebook_warning(
193 &self,
194 output: String,
195 notebook: &str,
196 ) -> String {
197 let Some(default_notebook) = self.default_notebook.as_deref() else {
198 return output;
199 };
200 if default_notebook == notebook {
201 return output;
202 }
203 append_warning(
204 output,
205 format!(
206 "Warning: wrote to notebook `{notebook}`, not the project default notebook `{default_notebook}`. If this was unintended, move or delete the note and retry with the correct notebook/folder."
207 ),
208 )
209 }
210
211 /// Resolves the notebook to use for a command.
212 pub(super) fn resolve_notebook_name(
213 &self,
214 notebook: Option<&str>,
215 ) -> Result<String, NbError> {
216 if let Some(name) = notebook {
217 validate_notebook_name(name)?;
218 return Ok(name.to_string());
219 }
220 if let Some(name) = self.default_notebook.as_deref() {
221 validate_notebook_name(name)?;
222 return Ok(name.to_string());
223 }
224 Err(NbError::ValidationError {
225 reason:
226 "notebook not configured; set --notebook or NB_MCP_NOTEBOOK"
227 .to_string(),
228 location: None,
229 })
230 }
231
232 pub(super) async fn resolve_notebook(
233 &self,
234 notebook: Option<&str>,
235 ) -> Result<String, NbError> {
236 let name = self.resolve_notebook_name(notebook)?;
237 self.ensure_notebook(&name).await?;
238 Ok(name)
239 }
240
241 pub(super) async fn ensure_notebook(
242 &self,
243 notebook: &str,
244 ) -> Result<(), NbError> {
245 match self.check_notebook(notebook).await {
246 Ok(()) => Ok(()),
247 // Genuine infrastructure failure (no nb binary, IO
248 // error) — surface verbatim; do not try to create.
249 Err(
250 err
251 @ (NbError::ExecutableNotFound { .. } | NbError::Io { .. }),
252 ) => Err(err),
253 // Typed NotFound from `check_notebook` means the
254 // pinned diagnostic matched the genuine notebook-
255 // absence shape (`Notebook not found: <name>`).
256 // Try to create it; if creation is disabled, surface
257 // a typed validation error; if creation fails,
258 // propagate the new CommandFailed verbatim.
259 Err(NbError::NotFound { .. }) => {
260 if !self.create_notebook {
261 return Err(NbError::ValidationError {
262 reason: format!(
263 "notebook not found; create it with the nb CLI (`nb notebooks add {}`) \
264 or remove --no-create-notebook",
265 notebook
266 ),
267 location: None,
268 });
269 }
270 self.exec_vec(vec![
271 "notebooks".to_string(),
272 "add".to_string(),
273 notebook.to_string(),
274 ])
275 .await?;
276 Ok(())
277 },
278 // Any other error from `check_notebook` (permission
279 // denied, transient crash, etc.) propagates verbatim;
280 // we deliberately do not try `notebooks add`, because
281 // a non-NotFound CommandFailed likely indicates a
282 // real failure that creation would not rescue.
283 Err(err) => Err(err),
284 }
285 }
286
287 pub(super) async fn ensure_existing_notebook(
288 &self,
289 notebook: &str,
290 ) -> Result<(), NbError> {
291 match self.check_notebook(notebook).await {
292 Ok(()) => Ok(()),
293 // Infrastructure failure — surface verbatim.
294 Err(
295 err
296 @ (NbError::ExecutableNotFound { .. } | NbError::Io { .. }),
297 ) => Err(err),
298 // Genuine notebook absence: propagate the typed
299 // `NbError::NotFound` produced by `check_notebook`
300 // verbatim. The qualified-selector path
301 // (`<notebook>:<item>`) used by `show_note`,
302 // `add_note`, `edit_note`, etc. surfaces this to the
303 // caller as the typed `NotFound` variant — the
304 // caller can distinguish "notebook gone" from a
305 // generic validation failure. Erasing the typed
306 // `NotFound` into a `ValidationError` would lose
307 // the variant distinction.
308 Err(err @ NbError::NotFound { .. }) => Err(err),
309 // Other CommandFailed errors propagate verbatim
310 // rather than being misclassified as "not found."
311 Err(err) => Err(err),
312 }
313 }
314
315 async fn check_notebook(&self, notebook: &str) -> Result<(), NbError> {
316 let show_result = self
317 .exec_vec(vec![
318 "notebooks".to_string(),
319 "show".to_string(),
320 notebook.to_string(),
321 "--path".to_string(),
322 ])
323 .await;
324 match show_result {
325 Ok(output) => {
326 if output.trim().is_empty() {
327 // Use the actual argument vector that was passed
328 // to `exec_vec`, not a reformatted display
329 // string. This way the `command` field matches
330 // what was actually executed on the wire, with
331 // no possibility of drift between the synthetic
332 // field and the real argv.
333 return Err(NbError::CommandFailed {
334 command: format!(
335 "nb notebooks show {notebook} --path"
336 ),
337 stderr: "nb notebooks path output was empty"
338 .to_string(),
339 exit_code: None,
340 });
341 }
342 Ok(())
343 },
344 Err(err) => {
345 // Surface genuine infrastructure failures verbatim
346 // so callers can distinguish "nb is broken" from
347 // "notebook does not exist". Genuine notebook
348 // absence (nb's pinned diagnostic on stderr) maps
349 // to typed `NotFound`. Any other subprocess
350 // failure (e.g., permission denied, a transient
351 // crash, an nb bug surfacing as `NotFound` in
352 // stderr without the literal `Notebook not found:`
353 // prefix) propagates as the original
354 // `CommandFailed` rather than being swallowed
355 // here. The caller (`ensure_notebook` /
356 // `ensure_existing_notebook`) decides whether to
357 // try to create the notebook on `NotFound` or
358 // surface the error verbatim otherwise.
359 match err {
360 NbError::ExecutableNotFound { .. }
361 | NbError::Io { .. } => Err(err),
362 NbError::CommandFailed { ref stderr, .. }
363 if is_notebook_not_found(stderr, notebook) =>
364 {
365 Err(NbError::NotFound {
366 selector: format!("{notebook}:"),
367 })
368 },
369 other => Err(other),
370 }
371 },
372 }
373 }
374
375 /// Executes an nb command and returns stdout.
376 pub(super) async fn exec(&self, args: &[&str]) -> Result<String, NbError> {
377 tracing::debug!(?args, "executing nb command");
378 // `nb_program` resolves `nb` to a spawnable absolute path on
379 // Windows (PATHEXT-aware: Rust std only finds `.exe` there and
380 // would miss a `nb.cmd` launcher). Unix keeps PATH resolution.
381 let mut command = Command::new(nb_program());
382 // Strip inherited `GIT_*` routing vars before chaining `.args` /
383 // `.env`. Without this, any caller invoking us from inside a
384 // git hook (pre-commit, pre-push, post-checkout) or CI runner
385 // propagates GIT_DIR / GIT_INDEX_FILE / GIT_COMMON_DIR /
386 // GIT_WORK_TREE / GIT_OBJECT_DIRECTORY /
387 // GIT_ALTERNATE_OBJECT_DIRECTORIES into the spawned `nb`,
388 // which is a bash script wrapping git — every git call inside
389 // nb then redirects to the parent repo instead of the
390 // notebook's repo. The blast-by-prefix also covers future
391 // GIT_* redirect vars without requiring a code change.
392 // See `nb-api:issues/3`. Do not remove.
393 scrub_git_env(&mut command);
394 command
395 .args(args)
396 .stdin(Stdio::null()) // Prevent TTY hangs
397 .stdout(Stdio::piped())
398 .stderr(Stdio::piped());
399 if self.disable_git_signing {
400 apply_git_signing_env(&mut command);
401 }
402 let joined = format!("nb {}", args.join(" "));
403 let output = command
404 .spawn()
405 .map_err(|e| {
406 if e.kind() == std::io::ErrorKind::NotFound {
407 NbError::ExecutableNotFound {
408 path: "nb".to_string(),
409 }
410 } else {
411 NbError::Io {
412 path: PathBuf::from("nb"),
413 source: e.into(),
414 }
415 }
416 })?
417 .wait_with_output()
418 .await
419 .map_err(|e| NbError::Io {
420 path: PathBuf::from("nb"),
421 source: e.into(),
422 })?;
423
424 if output.status.success() {
425 let stdout = String::from_utf8_lossy(&output.stdout);
426 Ok(strip_ansi(&stdout))
427 } else {
428 let stderr = String::from_utf8_lossy(&output.stderr);
429 let stdout = String::from_utf8_lossy(&output.stdout);
430 // nb sometimes writes errors to stdout
431 let stderr_text = if stderr.is_empty() {
432 strip_ansi(&stdout)
433 } else {
434 strip_ansi(&stderr)
435 };
436 Err(NbError::CommandFailed {
437 command: joined,
438 stderr: stderr_text,
439 exit_code: output.status.code(),
440 })
441 }
442 }
443
444 /// Executes an nb command with dynamic arguments.
445 pub(super) async fn exec_vec(
446 &self,
447 args: Vec<String>,
448 ) -> Result<String, NbError> {
449 let args_ref: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
450 self.exec(&args_ref).await
451 }
452}