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