Skip to content
Back to search

nteract

MarketplaceWorks with Claude CodeGitHubIncomplete

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 16 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/nteract/nteract with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/nteract/nteract'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/nteract--nteract/badge.svg)](/listings/nteract--nteract)

HTML

<a href="/listings/nteract--nteract"><img src="/api/listings/nteract--nteract/badge.svg" alt="findsafeskills safety rating" /></a>

Install

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

These steps run a script from the network that findsafeskills does not scan.

These instructions install nteract Desktop and its notebook tools. Pages has a separate [local setup](apps/pages/README.md#run-locally).

Download the latest release from [GitHub Releases](https://github.com/nteract/nteract/releases).

On Linux (x64 or ARM64) and macOS (Apple silicon or Intel), this command installs the AppImage or signed .app bundle, CLI/daemon, and per-user service (systemd or launchd):

curl --proto '=https' --tlsv1.2 -sSf https://sh.nteract.io | bash

macOS users can equally drag the DMG from GitHub Releases. DEB/RPM/APT installs are not currently supported because `runtimed` is a per-user daemon managed by the app and CLI, not by system package-manager scripts.

For remote workstations (Outerbounds, JupyterHub) that offer compute to hosted notebooks, use the headless installer. See [Remote workstations](docs/runbooks/remote-workstation.md) for details:

curl --proto '=https' --tlsv1.2 -sSf https://sh.nteract.io | bash -s -- --cli

Use `nteract` for notebook, workstation, and MCP operations. CLI-only installation does not configure or start a local daemon service. The desktop app bundles the same CLI. Existing `runt`, `runt-nightly`, and `nteract-mcp` commands remain compatible. See the [CLI guide](docs/runbooks/cli.md) for runtime startup, channel selection, and scripting behavior.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 20 lines
  1. {
  2. "name": "nteract",
  3. "owner": {
  4. "name": "nteract"
  5. },
  6. "plugins": [
  7. {
  8. "name": "nteract",
  9. "source": "./plugins/nteract",
  10. "description": "nteract notebooks in Claude Code.",
  11. "version": "0.8.1"
  12. },
  13. {
  14. "name": "nightly",
  15. "source": "./plugins/nightly",
  16. "description": "nteract notebooks (nightly channel) in Claude Code.",
  17. "version": "0.8.1"
  18. }
  19. ]
  20. }
README.md · README · 427 lines · 2 findings marked
  1. # nteract
  2. nteract builds tools for thinking with code, data, and documents. This monorepo
  3. is home to **nteract notebooks**, **Pages**, and the libraries and runtime that
  4. support them. People and AI agents collaborate on live Automerge documents in
  5. both products.
  6. ## Products
  7. ### nteract notebooks
  8. A local-first notebook environment for writing and running code, exploring data,
  9. and working with rich outputs. The native desktop app and hosted browser app
  10. share notebook UI and document protocols. The `runtimed` daemon manages kernels,
  11. environments, execution, and outputs; desktop, CLI, MCP, and programmatic clients
  12. work with the same live notebook.
  13. [![A nteract notebook with an outline of headings and output previews beside Markdown prose and Python code](https://img.runt.run/2026/06/2.6-outline-v3.png)](https://nteract.io/changelog/2.6)
  14. *Navigate a computational story through its headings and outputs. Screenshot
  15. from the [nteract 2.6 release notes](https://nteract.io/changelog/2.6), which also
  16. include video demos.*
  17. Start with the [desktop installation](#install), [development guide](#development),
  18. or [hosted notebook guide](apps/notebook-cloud/README.md).
  19. ### Pages
  20. Pages is a notebook-like space for writing, thinking, and exploring together.
  21. Mix rich text, images, diagrams, editable tables, task lists, and interactive
  22. dataframes in one document. Sketch an idea, explore a dataset, leave a comment
  23. on a passage, and invite an agent to help develop it. Organize related Pages
  24. into Projects and share individual Pages with collaborators. It should be as
  25. fun to explore an idea as it is to write it down.
  26. Pages has its own browser editor, document model, HTTP API, and MCP server.
  27. People edit rich content directly; agents use Markdown and structured operations
  28. on that same content. Pages displays code and diagrams; kernel execution lives
  29. in notebooks.
  30. Start with the [Pages guide](apps/pages/README.md)
  31. for features, local development, and tests, or the
  32. [deployment guide](apps/pages/DEPLOYMENT.md)
  33. for release targets. Its source lives in `apps/pages`.
  34. ## What's in here
  35. | Project | Purpose |
  36. |---------|---------|
  37. | nteract notebooks | Desktop and hosted notebooks for code execution and data exploration |
  38. | [Pages](apps/pages/README.md) | Rich collaborative documents for people and agents |
  39. | [Sift](packages/sift/README.md) | Interactive data exploration and table rendering, used in notebooks and Pages and available as a standalone library |
  40. | `runtimed` | Notebook runtime daemon for environment pools, sync, kernel execution, and outputs |
  41. | `nteract` command | CLI for notebooks, workstations, runtime operations, and supervised notebook MCP |
  42. | Client libraries | TypeScript, Node, and Python access to notebook documents and the daemon |
  43. | Elements | Shared UI catalog and interaction fixtures |
  44. <details>
  45. <summary>See Sift's interactive data exploration</summary>
  46. ![Sift filtering a Spotify tracks dataset with histograms and category summaries above the table](https://img.runt.run/sift/crossfilter-demo.gif)
  47. *Brush a column's distribution to filter the table and update the other
  48. summaries. Sift powers dataframe exploration in notebooks and Pages; see the
  49. [Sift guide](packages/sift/README.md) for standalone use and embedding.*
  50. </details>
  51. ## Install
  52. These instructions install nteract Desktop and its notebook tools. Pages has a
  53. separate [local setup](apps/pages/README.md#run-locally).
  54. Download the latest release from [GitHub Releases](https://github.com/nteract/nteract/releases).
  55. On Linux (x64 or ARM64) and macOS (Apple silicon or Intel), this command installs the
  56. AppImage or signed .app bundle, CLI/daemon, and per-user service
  57. (systemd or launchd):
  58. ```bash
  59. curl --proto '=https' --tlsv1.2 -sSf https://sh.nteract.io | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 81 on GitHub
  60. ```
  61. macOS users can equally drag the DMG from GitHub Releases. DEB/RPM/APT
  62. installs are not currently supported because `runtimed` is a per-user daemon
  63. managed by the app and CLI, not by system package-manager scripts.
  64. For remote workstations (Outerbounds, JupyterHub) that offer compute to
  65. hosted notebooks, use the headless installer. See
  66. [Remote workstations](docs/runbooks/remote-workstation.md) for details:
  67. ```bash
  68. curl --proto '=https' --tlsv1.2 -sSf https://sh.nteract.io | bash -s -- --cli
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 93 on GitHub
  69. ```
  70. Use `nteract` for notebook, workstation, and MCP operations. CLI-only installation does not configure or start a local daemon service. The desktop app bundles the same CLI. Existing `runt`, `runt-nightly`, and `nteract-mcp` commands remain compatible. See the [CLI guide](docs/runbooks/cli.md) for runtime startup, channel selection, and scripting behavior.
  71. ## Runtime model
  72. nteract notebooks store content in `NotebookDoc` and live kernel and execution
  73. state in `RuntimeStateDoc`. `CommsDoc` holds widget state and `CommentsDoc` holds
  74. notebook comments. The daemon owns kernel processes, execution queues, output
  75. capture, and the write path for execution results.
  76. Execution requests name a synced `cell_id`; the daemon reads the cell source from the shared document, records queue and status changes in runtime state, and writes outputs through the same model. The desktop app, CLI, MCP server, and agent clients use that path, so programmatic control observes the same notebook state a human is editing.
  77. Pages stores native rich text in its own Automerge document, with a separate
  78. comments document. Its host owns authorization and durable receipts. It has its
  79. own sync and persistence stack. Where the product is going is in
  80. [Pages direction](apps/pages/DIRECTION.md).
  81. ## MCP Server
  82. Both products expose MCP tools. Pages serves its own
  83. [HTTP MCP endpoint](apps/pages/REFERENCE.md#http-and-mcp-tools)
  84. for document, Project, and comment operations. The setup below is for notebooks.
  85. Run `nteract mcp` to connect AI assistants to notebooks. Local notebooks use the runtime daemon; direct hosted connections use WebSockets without a local daemon. Agents can run code, read and write cells, manage dependencies, and collaborate with humans on the same live notebook.
  86. ### Install the Codex plugin
  87. ```
  88. codex plugin marketplace add nteract/agent-plugins
  89. ```
  90. Restart Codex, then open the plugin directory, choose the nteract marketplace, and install `nteract`.
  91. The distribution repository also includes a `nightly` plugin entry for pre-release builds.
  92. If tools are missing or notebook calls fail after an app update, follow [Upgrade the Codex plugin](#upgrade-the-codex-plugin).
  93. ### Upgrade the Codex plugin
  94. The desktop app and the Codex plugin update separately. An older plugin can reject a newer app's notebook routing with `unsupported_notebook_target`, including this misleading message:
  95. ```text
  96. This child does not advertise required notebook_handle routing;
  97. upgrade the child before using notebook tools
  98. ```
  99. This can mean the **plugin proxy needs updating**, even when the desktop app is current. It can block notebook creation as well as calls using a notebook ID or handle. Plugin 0.6.6 and desktop 2.8.6 are a verified compatible pairing; their version numbers are independent.
  100. Save any notebook work before restarting your agent. Refresh the marketplace, then reinstall only the channel you use. Run these commands in a terminal. The `&&` operators stop the sequence if a step fails.
  101. Stable:
  102. ```sh
  103. codex plugin marketplace upgrade nteract-plugins &&
  104. codex plugin remove nteract@nteract-plugins &&
  105. codex plugin add nteract@nteract-plugins
  106. ```
  107. Nightly:
  108. ```sh
  109. codex plugin marketplace upgrade nteract-plugins &&
  110. codex plugin remove nightly@nteract-plugins &&
  111. codex plugin add nightly@nteract-plugins
  112. ```
  113. If you registered the marketplace at an older release with `--ref`, refreshing keeps that pin. To move to current `main`, replace the marketplace registration before reinstalling:
  114. ```sh
  115. codex plugin marketplace remove nteract-plugins &&
  116. codex plugin marketplace add nteract/agent-plugins --ref main
  117. ```
  118. Only reinstall the plugin after registration succeeds. If cloning fails, use the local checkout fallback below.
  119. Restart Codex and start a fresh session so it loads the updated proxy and tool catalog. The MCP `reconnect` tool restarts the worker behind the proxy; it does not upgrade the plugin proxy. Restarting Codex without updating the cached plugin can still launch the old binary.
  120. Check the installed plugin version in Codex's plugin settings, then ask the agent to create a notebook and run a cell containing `1 + 1`. Confirm that the cell returns `2`. Seeing a skill or a server in `codex mcp list` alone does not verify notebook execution. If it still fails, include the exact error, plugin version and channel, and `nteract --version` when [reporting an issue](https://github.com/nteract/nteract/issues).
  121. #### If the marketplace refresh times out
  122. If `marketplace upgrade` reports `git clone marketplace source timed out after 30s` or `fatal: early EOF`, stop before removing the installed plugin. The replacement marketplace has not finished downloading. Retry the refresh; if it continues to fail, clone a shallow checkout outside Codex's clone deadline and register that local directory. On macOS or Linux, for an existing `nteract-plugins` registration:
  123. ```sh
  124. mkdir -p "$HOME/.local/share/nteract" &&
  125. git clone --depth 1 --single-branch --branch main \
  126. https://github.com/nteract/agent-plugins.git \
  127. "$HOME/.local/share/nteract/agent-plugins" &&
  128. codex plugin marketplace remove nteract-plugins &&
  129. codex plugin marketplace add "$HOME/.local/share/nteract/agent-plugins"
  130. ```
  131. Use a new directory for the clone. The chain finishes downloading before removing the old marketplace registration. Codex requires that removal when changing sources under the same name; `marketplace remove` is separate from uninstalling the plugin with `plugin remove`. If you already removed the marketplace registration, skip that removal command.
  132. Only after registration succeeds, run the selected channel's `plugin remove` and `plugin add` commands above, then restart Codex. Keep the checkout: it is now the registered marketplace source. For future updates, run `git -C "$HOME/.local/share/nteract/agent-plugins" pull --ff-only` successfully before reinstalling the plugin; `marketplace upgrade` refreshes Git sources, not local directories. To return to a Git-managed marketplace later, use the remove-and-add registration commands above.
  133. ### Install the Claude Code plugin
  134. ```
  135. /plugin marketplace add nteract/agent-plugins
  136. /plugin install nteract@nteract
  137. ```
  138. Pin a specific version:
  139. ```
  140. /plugin install nteract@nteract --ref v2.3.0
  141. ```
  142. The plugin ships the `nteract-mcp` binary for your platform (macOS arm64/x64, Linux x64/arm64, Windows x64), so no separate install is needed. `main` of `nteract/agent-plugins` always points at the latest stable release.
  143. For pre-release builds (updated daily):
  144. ```
  145. /plugin install nightly@nteract
  146. ```
  147. ### Install in Claude Desktop
  148. If you use the nteract desktop app with Claude Desktop, there's a one-click install path. In the menu bar, choose **nteract → Install Extension for Claude...**
  149. ![nteract menu showing 'Install Extension for Claude...'](https://img.runt.run/install-claude-extension.png)
  150. The nteract desktop app is required: it builds a `.mcpb` bundle at runtime (manifest, icons, `nteract-mcp` binary) and hands it to Claude Desktop, which prompts you to confirm the install.
  151. ## Usage
  152. ```bash
  153. # Open a notebook
  154. nteract open path/to/notebook.ipynb
  155. # MCP server for notebook automation
  156. nteract mcp
  157. # Daemon management
  158. nteract daemon status
  159. nteract daemon logs -f
  160. ```
  161. List open notebooks with kernel and environment info:
  162. ```
  163. $ nteract notebooks
  164. ╭──────────────────────────────────────┬────────┬──────────────┬────────┬───────╮
  165. │ NOTEBOOK │ KERNEL │ ENV │ STATUS │ PEERS │
  166. ├──────────────────────────────────────┼────────┼──────────────┼────────┼───────┤
  167. │ ~/notebooks/blobstore.ipynb │ python │ uv:inline │ idle │ 1 │
  168. │ d4c441d3-d862-4ab0-afe6-ff9145cc2f3d │ python │ uv:prewarmed │ idle │ 1 │
  169. ╰──────────────────────────────────────┴────────┴──────────────┴────────┴───────╯
  170. ```
  171. ## Project structure
  172. ```
  173. nteract/nteract
  174. ├── src/ # Shared UI code (React components, hooks, utilities)
  175. │ ├── bindings/ # TypeScript types generated from Rust (ts-rs)
  176. │ ├── components/
  177. │ │ ├── ui/ # shadcn primitives (button, dialog, etc.)
  178. │ │ ├── cell/ # Notebook cell components
  179. │ │ ├── outputs/ # Output renderers (stream, error, display data)
  180. │ │ ├── editor/ # CodeMirror editor
  181. │ │ ├── isolated/ # Iframe security isolation (IsolatedFrame, CommBridgeManager)
  182. │ │ └── widgets/ # ipywidgets controls
  183. │ ├── hooks/ # Shared hooks (useSyncedSettings, useTheme)
  184. │ ├── isolated-renderer/ # Code that runs inside isolated iframes
  185. │ ├── lib/ # Shared utilities (cn(), dark-mode, error-boundary)
  186. │ └── styles/ # Global stylesheets
  187. ├── apps/ # App entry points
  188. │ ├── notebook/ # Desktop notebook Tauri app
  189. │ ├── notebook-cloud/ # Hosted notebook worker (Cloudflare)
  190. │ ├── elements/ # Elements design system catalog
  191. │ ├── pages/ # Pages: collaborative documents (npm, own lockfile)
  192. │ ├── mcp-app/ # MCP widget dev app
  193. │ └── renderer-test/ # Isolated renderer test harness
  194. ├── packages/ # Client and UI libraries
  195. │ ├── notebook-host/ # Notebook host shell
  196. │ ├── runtimed/ # TypeScript notebook client and state stores
  197. │ ├── runtimed-node/ # Node bindings for daemon
  198. │ ├── sift/ # Standalone data explorer and embeddable table UI
  199. │ └── odometer/ # Odometer component
  200. ├── crates/ # Rust code
  201. │ ├── runt/ # Shared CLI; nteract-cli and legacy runt entrypoints
  202. │ ├── runtimed/ # Background daemon
  203. │ ├── runtimed-py/ # Python bindings for the daemon
  204. │ ├── runtimed-wasm/ # WASM Automerge bindings for frontend
  205. │ ├── notebook/ # Notebook Tauri app crate
  206. │ ├── notebook-doc/ # Automerge document operations
  207. │ ├── notebook-protocol/ # Notebook wire protocol types
  208. │ ├── notebook-sync/ # Notebook sync layer
  209. │ ├── kernel-launch/ # Shared kernel launching API
  210. │ ├── kernel-env/ # Environment progress reporting
  211. │ ├── runt-mcp/ # Rust-native MCP server
  212. │ ├── runt-trust/ # Notebook trust extraction
  213. │ ├── runt-workspace/ # Workspace detection utilities
  214. │ ├── runtimed-client/ # Shared client library for daemon
  215. │ ├── repr-llm/ # LLM-friendly text summaries of visualizations
  216. │ ├── xtask/ # Build automation tasks
  217. │ └── mcp-supervisor/ # nteract-dev MCP server (proxies runt mcp + dev tools)
  218. ├── python/ # Python workspace (uv)
  219. │ ├── runtimed/ # PyPI: runtimed (Python bindings)
  220. │ ├── nteract/ # PyPI: nteract (thin launcher for `runt mcp`)
  221. │ ├── gremlin/ # Stress-testing agent
  222. │ ├── prewarm/ # Environment prewarm script
  223. │ ├── dx/ # Developer utilities
  224. │ ├── nteract-kernel-launcher/ # Kernel launcher for hosted notebooks
  225. │ └── safari-timeline/ # Safari timeline parser
  226. ├── plugins/ # Agent plugin distribution
  227. │ └── nteract/ # Codex plugin package
  228. └── docs/ # Design, decisions, and operations
  229. ```
  230. ## Development
  231. Choose the workflow for the project you're changing:
  232. - **Notebooks and runtime:** use the prerequisites and `cargo xtask` commands below.
  233. - **Pages:** use its [npm workspace setup and tests](apps/pages/README.md#run-locally).
  234. - **Sift:** use its [standalone development guide](packages/sift/README.md#quick-start).
  235. ### Prerequisites
  236. | Tool | Version | Install |
  237. |------|---------|---------|
  238. | Node.js | 22.13+ | https://nodejs.org |
  239. | pnpm | 11.9+ | `corepack enable` |
  240. | Rust | 1.99.1 | https://rustup.rs (version managed by `rust-toolchain.toml`) |
  241. **Linux only:** Install GTK/WebKit dev libraries:
  242. ```bash
  243. sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.1-dev libxdo-dev \
  244. libssl-dev libayatana-appindicator3-dev librsvg2-dev
  245. ```
  246. ### Quick start
  247. ```bash
  248. cargo xtask dev
  249. ```
  250. ### Development workflows
  251. | Workflow | Command | Use when |
  252. |----------|---------|----------|
  253. | Full dev loop | `cargo xtask dev` | Setup plus the per-worktree daemon and hot-reload app |
  254. | Clean dev restart | `cargo xtask dev --fresh` | Recover from stale Tauri listeners, bootstrap, or daemon state |
  255. | Dev status | `cargo xtask dev status` | Show the exact app identity, PID, executable, Vite URL, and daemon socket |
  256. | Focus dev app | `cargo xtask dev focus` | Activate this worktree's exact macOS app process |
  257. | Reset dev state | `cargo xtask dev reset` | Stop this worktree's app and daemon without affecting installed apps |
  258. | App-only hot reload | `cargo xtask notebook` | Run the app when the per-worktree daemon is already managed separately |
  259. | Standalone Vite | `cargo xtask vite` | Multi-window testing (Vite survives window closes) |
  260. | Attach to Vite | `cargo xtask notebook --attach` | Connect Tauri to already-running Vite |
  261. | Debug build | `cargo xtask build` | Full debug build (frontend + rust) |
  262. | E2E debug build | `cargo xtask e2e build` | Debug build with built-in WebDriver server |
  263. | Rust-only build | `cargo xtask build --rust-only` | Rebuild rust, reuse existing frontend |
  264. | Run bundled | `cargo xtask run notebook.ipynb` | Run standalone binary |
  265. | Lint (check) | `cargo xtask lint` | Check formatting and linting across Rust, JS/TS, Python |
  266. | Lint (fix) | `cargo xtask lint --fix` | Auto-fix formatting and linting |
  267. | Dev daemon | `cargo xtask dev-daemon` | Run per-worktree dev daemon |
  268. | Artifact status | `cargo xtask artifacts status` | Check generated WASM, renderer, and MCP widget artifacts |
  269. | Install nightly (Linux/headless) | `./scripts/install-nightly` | Build + install runtimed + runt + nteract-mcp as the local nightly. Refuses on macOS and when an app bundle is installed. |
  270. | Release .app | `cargo xtask build-app` | Testing app bundle locally |
  271. | Release DMG | `cargo xtask build-dmg` | Distribution (usually CI) |
  272. | Generate icons | `cargo xtask icons [source.png]` | Generate icon variants from source image |
  273. `cargo xtask dev` installs dependencies, ensures generated artifacts, starts the
  274. per-worktree dev daemon, waits for it to be ready, and then launches the notebook
  275. app with hot reload. It stops the daemon it started when the app exits. For repeat
  276. launches, use `cargo xtask dev --skip-install --skip-build`.
  277. On macOS, every worktree gets a cached app wrapper with a distinct name and bundle
  278. identifier, such as `nteract Dev f0f9d9` and
  279. `org.nteract.desktop.dev.f0f9d99b161f`. This keeps unsigned source builds separate
  280. from installed stable and Nightly apps without changing release packaging or
  281. claiming `.ipynb` file associations. Use `cargo xtask dev status` to obtain the
  282. live automation PID. Accessibility scripts should select the System Events process
  283. by that PID instead of asking LaunchServices for an app named `nteract`:
  284. ```applescript
  285. set devPid to 12345 -- copy Automation PID from `cargo xtask dev status`
  286. tell application "System Events"
  287. tell first application process whose unix id is devPid
  288. -- perform UI automation here
  289. end tell
  290. end tell
  291. ```
  292. Frontend edits continue through Vite hot reload. After changes to Tauri bootstrap
  293. or event-listener setup, use `cargo xtask dev --fresh` to terminate only this
  294. worktree's exact app process, stop its daemon, and relaunch both cleanly. The
  295. equivalent manual sequence is `cargo xtask dev reset` followed by
  296. `cargo xtask dev`.
  297. ### Build order
  298. The UI must be built before Rust because `crates/notebook` embeds assets from `apps/notebook/dist/` via Tauri.
  299. ### Common commands
  300. ```bash
  301. pnpm build # Build notebook UI
  302. cargo test # Run Rust tests
  303. pnpm test:run # Run JS tests
  304. cargo xtask artifacts status # Check generated artifact readiness
  305. cargo xtask artifacts ensure runtime # Rebuild only runtimed-wasm when needed
  306. cargo fmt # Format Rust
  307. vp check --fix # Lint + format JS/TS
  308. cargo clippy --all-targets -- -D warnings # Lint Rust
  309. ```
  310. ## Library crates
  311. The underlying Rust libraries are published to crates.io:
  312. - [`jupyter-protocol`](https://crates.io/crates/jupyter-protocol): Jupyter messaging protocol
  313. - [`jupyter-zmq-client`](https://crates.io/crates/jupyter-zmq-client): Jupyter kernel interactions over ZeroMQ
  314. - [`nbformat`](https://crates.io/crates/nbformat): Notebook parsing
  315. ## Contributing
  316. See [CONTRIBUTING.md](CONTRIBUTING.md) for contributor workflows,
  317. [AGENTS.md](AGENTS.md) for agent guidance, and [docs/README.md](docs/README.md)
  318. for the documentation map. Key entry points:
  319. - [Pages contributor guidance](apps/pages/AGENTS.md): document model, editor, host, and tests
  320. - `crates/runtimed/AGENTS.md`: architecture, daemon, state ownership
  321. - `apps/notebook/src/AGENTS.md`: frontend architecture
  322. - `crates/notebook-wire/AGENTS.md`: wire protocol
  323. - `cargo xtask help`: all build commands
  324. ## License
  325. BSD-3-Clause
plugins/nteract/pi/extensions/repl.ts · Bundled script · 1,298 lines · 3 findings marked
  1. /**
  2. * nteract Python REPL for pi — direct bindings edition.
  3. *
  4. * Uses the in-process @runtimed/node native binding to talk to
  5. * the running runtimed daemon, with no MCP subprocess. State (imports,
  6. * variables) persists across calls within the pi session.
  7. *
  8. * Config (env vars):
  9. * NTERACT_RUNTIMED_NODE_PATH override the runtimed-node package path.
  10. *
  11. * Daemon socket selection follows the runtimed-node contract:
  12. * `RUNTIMED_SOCKET_PATH` overrides outright, `RUNTIMED_WORKSPACE_PATH` (or
  13. * `RUNTIMED_DEV=1` plus a git checkout) selects the per-worktree dev daemon,
  14. * otherwise the running channel is auto-detected.
  15. *
  16. * After editing, run `/reload` in pi.
  17. */
  18. import type { ImageContent, TextContent } from "@earendil-works/pi-ai";
  19. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  20. import { highlightCode } from "@earendil-works/pi-coding-agent";
  21. import { Text, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
  22. import { existsSync } from "node:fs";
  23. import { createRequire } from "node:module";
  24. import { homedir } from "node:os";
  25. import path from "node:path";
  26. import { fileURLToPath } from "node:url";
  27. import { Type } from "typebox";
  28. // --- runtimed-node loader ----------------------------------------------------
  29. type RuntimedNode = {
  30. defaultSocketPath(): string;
  31. PackageManager?: { Uv: "uv"; Conda: "conda"; Pixi: "pixi" };
  32. createNotebook(opts?: {
  33. runtime?: string;
  34. workingDir?: string;
  35. socketPath?: string;
  36. peerLabel?: string;
  37. description?: string;
  38. dependencies?: string[];
  39. packageManager?: "uv" | "conda" | "pixi";
  40. }): Promise<Session>;
  41. openNotebook(
  42. notebookId: string,
  43. opts?: { socketPath?: string; peerLabel?: string; description?: string },
  44. ): Promise<Session>;
  45. readParquetFile(filePath: string, offset: number, limit: number): TableRowPage;
  46. readArrowFile?(filePath: string, offset: number, limit: number): TableRowPage;
  47. readArrowChunks?(filePaths: string[], offset: number, limit: number): TableRowPage;
  48. summarizeParquetFile?(filePath: string): TableSummaryResult;
  49. summarizeArrowFile?(filePath: string): TableSummaryResult;
  50. summarizeArrowChunks?(filePaths: string[]): TableSummaryResult;
  51. resolveBlobPath?(hash: string, socketPath?: string): string | null | undefined;
  52. };
  53. type JsOutput = {
  54. outputType: string;
  55. name?: string;
  56. text?: string;
  57. dataJson?: string;
  58. ename?: string;
  59. evalue?: string;
  60. traceback?: string[];
  61. executionCount?: number;
  62. blobUrlsJson?: string;
  63. blobPathsJson?: string;
  64. };
  65. type CellResult = {
  66. cellId: string;
  67. executionId: string;
  68. executionCount?: number;
  69. status: string; // "done" | "error" | "timeout" | "kernel_error"
  70. success: boolean;
  71. outputs?: JsOutput[];
  72. };
  73. type TableRowPage = {
  74. columns: string[];
  75. rows: string[][];
  76. totalRows: number;
  77. offset: number;
  78. };
  79. type TableSummaryResult = {
  80. numRows: number;
  81. numBytes: number;
  82. columns: Array<{ name: string; dataType: string; nullCount: number; statsJson: string }>;
  83. };
  84. type QueuedExecution = {
  85. cellId: string;
  86. executionId: string;
  87. };
  88. type ExecutionViewSnapshot = {
  89. execution_count: number | null;
  90. status: string;
  91. success: boolean | null;
  92. output_ids: string[];
  93. };
  94. type ExecutionViewChangeset = {
  95. execution_upserts?: Array<[executionId: string, snapshot: ExecutionViewSnapshot]>;
  96. };
  97. type SubscriptionLike = {
  98. unsubscribe?: () => void;
  99. dispose?: () => void;
  100. };
  101. type ObservableLike<T> = {
  102. subscribe(next: (value: T) => void): SubscriptionLike;
  103. };
  104. type Session = {
  105. readonly notebookId: string;
  106. readonly executionViewChanges$?: ObservableLike<ExecutionViewChangeset>;
  107. runCell(
  108. source: string,
  109. opts?: { timeoutMs?: number; cellType?: string; onUpdate?: (progress: CellResult) => void },
  110. ): Promise<CellResult>;
  111. queueCell(source: string, opts?: { cellType?: string }): Promise<QueuedExecution>;
  112. waitForExecution(
  113. executionId: string,
  114. opts?: { timeoutMs?: number; cellId?: string; onUpdate?: (progress: CellResult) => void },
  115. ): Promise<CellResult>;
  116. addUvDependency?(pkg: string): Promise<void>;
  117. addDependencies?(
  118. packages: string[],
  119. opts?: { packageManager?: "uv" | "conda" | "pixi" },
  120. ): Promise<void>;
  121. getDependencyStatus?(): Promise<{ uv?: { dependencies: string[] }; fingerprint?: string }>;
  122. getRuntimeStatus?(): Promise<{
  123. status: string;
  124. lifecycle: string;
  125. errorReason?: string;
  126. errorDetails?: string;
  127. }>;
  128. syncEnvironment(): Promise<void>;
  129. saveNotebook(path?: string): Promise<void>;
  130. shutdownNotebook?(): Promise<boolean>;
  131. close(): Promise<void>;
  132. };
  133. function loadRuntimedNode(): RuntimedNode | null {
  134. const extensionDir = path.dirname(fileURLToPath(import.meta.url));
  135. const candidates = [
  136. process.env.NTERACT_RUNTIMED_NODE_PATH,
  137. "@runtimed/node",
  138. path.resolve(extensionDir, "../../../..", "packages", "runtimed-node", "src", "index.cjs"),
  139. ].filter((candidate): candidate is string => Boolean(candidate));
  140. const req = createRequire(import.meta.url);
  141. const errors: string[] = [];
  142. for (const candidate of candidates) {
  143. try {
  144. return req(candidate) as RuntimedNode;
  145. } catch (e) {
  146. errors.push(`${candidate}: ${e instanceof Error ? e.message : String(e)}`);
  147. }
  148. }
  149. console.error("[nteract-repl] failed to load runtimed-node:\n" + errors.join("\n"));
  150. return null;
  151. }
  152. // --- bootstrap detection -----------------------------------------------------
  153. const INSTALL_HINT =
  154. "The nteract daemon (runtimed) isn't installed yet.\n" +
  155. "Quick install: curl -fsSL https://sh.nteract.io | bash\n" +
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 173 on GitHub
  156. "Or visit: https://nteract.io";
  157. type BootstrapStatus =
  158. | { kind: "ready"; rn: RuntimedNode }
  159. | { kind: "missing"; reason: "binding" | "daemon" };
  160. function findOnPath(cmd: string): string | undefined {
  161. const dirs = (process.env.PATH ?? "").split(path.delimiter);
  162. for (const dir of dirs) {
  163. if (!dir) continue;
  164. const candidate = path.join(dir, cmd);
  165. if (existsSync(candidate)) return candidate;
  166. }
  167. return undefined;
  168. }
  169. function detectBootstrap(): BootstrapStatus {
  170. const rn = loadRuntimedNode();
  171. if (!rn) return { kind: "missing", reason: "binding" };
  172. // defaultSocketPath() already honors RUNTIMED_SOCKET_PATH and the dev /
  173. // worktree-aware resolution from runt-workspace, so this is the single point
  174. // of truth. The socket file only exists while the daemon is running, but the
  175. // parent cache dir survives shutdowns, so dir-existence covers "installed
  176. // but stopped".
  177. const socket = rn.defaultSocketPath();
  178. const installed =
  179. existsSync(socket) ||
  180. existsSync(path.dirname(socket)) ||
  181. Boolean(findOnPath("runt")) ||
  182. Boolean(findOnPath("runt-nightly"));
  183. return installed ? { kind: "ready", rn } : { kind: "missing", reason: "daemon" };
  184. }
  185. // --- DataTable TUI component --------------------------------------------------
  186. type Theme = {
  187. fg: (color: string, text: string) => string;
  188. bg: (color: string, text: string) => string;
  189. bold: (text: string) => string;
  190. };
  191. type ColumnStats = {
  192. kind: string;
  193. min?: number;
  194. max?: number;
  195. distinct_count?: number;
  196. top?: [string, number][];
  197. true_count?: number;
  198. false_count?: number;
  199. };
  200. const PARQUET_MIME = "application/vnd.apache.parquet";
  201. const ARROW_STREAM_MIME = "application/vnd.apache.arrow.stream";
  202. const ARROW_STREAM_MANIFEST_MIME = "application/vnd.nteract.arrow-stream-manifest+json";
  203. type ArrowManifestColumn = {
  204. name: string;
  205. type?: string;
  206. nullable?: boolean;
  207. };
  208. type ArrowManifestChunk = {
  209. index?: number;
  210. hash?: string;
  211. size?: number;
  212. row_count?: number;
  213. record_batch_count?: number;
  214. encoding?: string;
  215. };
  216. type ArrowStreamManifest = {
  217. schema?: {
  218. columns?: ArrowManifestColumn[];
  219. };
  220. chunks?: ArrowManifestChunk[];
  221. complete?: boolean;
  222. summary?: {
  223. total_rows?: number;
  224. included_rows?: number;
  225. sampled?: boolean;
  226. sample_strategy?: string;
  227. };
  228. };
  229. type TableSource =
  230. | { kind: "parquet"; path: string }
  231. | { kind: "arrow"; path: string }
  232. | { kind: "arrow-manifest"; manifest: ArrowStreamManifest; chunkPaths: string[] };
  233. function formatStat(stats: ColumnStats | null): string {
  234. if (!stats) return "";
  235. switch (stats.kind) {
  236. case "numeric":
  237. return `${stats.min?.toFixed(1)}..${stats.max?.toFixed(1)}`;
  238. case "string":
  239. return `${stats.distinct_count ?? "?"}d`;
  240. case "boolean":
  241. return `T:${stats.true_count ?? 0} F:${stats.false_count ?? 0}`;
  242. default:
  243. return "";
  244. }
  245. }
  246. function resolvePath(userPath: string, workingDir = process.cwd()): string {
  247. const expanded = expandHome(userPath);
  248. return path.isAbsolute(expanded) ? expanded : path.resolve(workingDir, expanded);
  249. }
  250. function expandHome(userPath: string): string {
  251. if (userPath === "~") return homedir();
  252. if (userPath.startsWith("~/") || userPath.startsWith("~\\")) {
  253. return path.join(homedir(), userPath.slice(2));
  254. }
  255. return userPath;
  256. }
  257. const SPARK_CHARS = "▁▂▃▄▅▆▇█";
  258. const RATIO_PARTIAL_CHARS = ["", "▏", "▎", "▍", "▌", "▋", "▊", "▉"];
  259. function sparkline(values: number[], width: number): string {
  260. if (values.length === 0 || width <= 0) return "";
  261. const min = Math.min(...values);
  262. const max = Math.max(...values);
  263. const bins = Array.from({ length: Math.min(width, 8) }, () => 0);
  264. if (min === max) {
  265. return SPARK_CHARS[3].repeat(bins.length);
  266. }
  267. const range = max - min;
  268. for (const v of values) {
  269. const bi = Math.min(Math.floor(((v - min) / range) * bins.length), bins.length - 1);
  270. bins[bi]++;
  271. }
  272. const maxCount = Math.max(...bins);
  273. return bins
  274. .map(
  275. (c) =>
  276. SPARK_CHARS[maxCount === 0 ? 0 : Math.round((c / maxCount) * (SPARK_CHARS.length - 1))],
  277. )
  278. .join("");
  279. }
  280. function ratioBar(numerator: number, denominator: number, width: number): string {
  281. if (denominator <= 0 || width <= 0) return "";
  282. const ratio = Math.max(0, Math.min(1, numerator / denominator));
  283. if (width < 3) {
  284. const glyphIndex = Math.round(ratio * (RATIO_PARTIAL_CHARS.length - 1));
  285. return RATIO_PARTIAL_CHARS[glyphIndex] || "█";
  286. }
  287. const innerWidth = Math.max(1, width - 2);
  288. const filledWidth = ratio * innerWidth;
  289. let fullCells = Math.floor(filledWidth);
  290. let partialIndex = Math.round((filledWidth - fullCells) * 8);
  291. if (partialIndex === 8) {
  292. fullCells += 1;
  293. partialIndex = 0;
  294. }
  295. if (fullCells >= innerWidth) {
  296. fullCells = innerWidth;
  297. partialIndex = 0;
  298. }
  299. const partial = partialIndex > 0 ? RATIO_PARTIAL_CHARS[partialIndex] : "";
  300. const usedCells = fullCells + (partial ? 1 : 0);
  301. const emptyCells = Math.max(0, innerWidth - usedCells);
  302. return `│${"█".repeat(fullCells)}${partial}${" ".repeat(emptyCells)}│`;
  303. }
  304. function rankedFrequencyStrip(stats: ColumnStats, width: number): string {
  305. if (width <= 0 || !stats.top?.length) return "";
  306. const top = stats.top.filter(([, count]) => Number.isFinite(count) && count > 0);
  307. if (!top.length) return "";
  308. const hasOther = (stats.distinct_count ?? top.length) > top.length;
  309. const maxWidth = Math.min(width, top.length + (hasOther ? 1 : 0));
  310. if (maxWidth <= 0) return "";
  311. const topWidth = hasOther && maxWidth > 1 ? maxWidth - 1 : maxWidth;
  312. const visibleTop = top.slice(0, topWidth);
  313. const maxCount = Math.max(...visibleTop.map(([, count]) => count));
  314. const glyphs = visibleTop
  315. .map(([, count]) => {
  316. const index = Math.max(0, Math.ceil((count / maxCount) * SPARK_CHARS.length) - 1);
  317. return SPARK_CHARS[index];
  318. })
  319. .join("");
  320. return hasOther && maxWidth > visibleTop.length ? `${glyphs}·` : glyphs;
  321. }
  322. function sparklineForColumn(
  323. rows: string[][],
  324. ci: number,
  325. stats: ColumnStats | null,
  326. colType: string,
  327. width: number,
  328. ): string {
  329. if (stats?.kind === "boolean") {
  330. const t = stats.true_count ?? 0;
  331. const f = stats.false_count ?? 0;
  332. const total = t + f;
  333. if (total === 0) return "";
  334. return ratioBar(t, total, width);
  335. }
  336. if (stats?.kind === "numeric" || /int|float|decimal|uint/.test(colType)) {
  337. const nums: number[] = [];
  338. for (const row of rows) {
  339. const n = parseFloat(row[ci]);
  340. if (!isNaN(n)) nums.push(n);
  341. }
  342. return sparkline(nums, width);
  343. }
  344. if (stats?.kind === "string" && stats.top && stats.top.length > 0) {
  345. return rankedFrequencyStrip(stats, width);
  346. }
  347. return "";
  348. }
  349. class DataTable {
  350. private columns: string[];
  351. private rows: string[][];
  352. private totalRows: number;
  353. private colTypes: string[];
  354. private colStats: (ColumnStats | null)[];
  355. private theme: Theme;
  356. private cachedLines?: string[];
  357. private cachedWidth?: number;
  358. private indent: number;
  359. private footerText?: string;
  360. constructor(
  361. columns: string[],
  362. rows: string[][],
  363. totalRows: number,
  364. colTypes: string[],
  365. colStats: (ColumnStats | null)[],
  366. theme: Theme,
  367. indent: number = 0,
  368. footerText?: string,
  369. ) {
  370. this.columns = columns;
  371. this.rows = rows;
  372. this.totalRows = totalRows;
  373. this.colTypes = colTypes;
  374. this.colStats = colStats;
  375. this.theme = theme;
  376. this.indent = indent;
  377. this.footerText = footerText;
  378. }
  379. invalidate(): void {
  380. this.cachedLines = undefined;
  381. this.cachedWidth = undefined;
  382. }
  383. render(width: number): string[] {
  384. if (this.cachedLines && this.cachedWidth === width) {
  385. return this.cachedLines;
  386. }
  387. const t = this.theme;
  388. const numRows = this.rows.length;
  389. const totalCols = this.columns.length;
  390. const MIN_COL_W = 6;
  391. // Calculate natural column widths: max of header, type, stat, and data
  392. const naturalWidths = this.columns.map((col, ci) => {
  393. let w = col.length;
  394. w = Math.max(w, (this.colTypes[ci] ?? "").length);
  395. const statStr = formatStat(this.colStats[ci] ?? null);
  396. w = Math.max(w, statStr.length);
  397. for (const row of this.rows) {
  398. w = Math.max(w, (row[ci] ?? "").length);
  399. }
  400. return w;
  401. });
  402. // Greedily fit columns left-to-right within the available width.
  403. // Each column costs its width + 3 chars of border ("│ " + " │").
  404. let budget = width - 1; // leading "│"
  405. let visibleCount = 0;
  406. for (let i = 0; i < totalCols; i++) {
  407. const colCost = Math.max(naturalWidths[i], MIN_COL_W) + 3;
  408. if (budget - colCost < 0 && visibleCount > 0) break;
  409. budget -= colCost;
  410. visibleCount++;
  411. }
  412. visibleCount = Math.max(1, visibleCount);
  413. const hiddenCols = totalCols - visibleCount;
  414. // Slice to visible columns
  415. const columns = this.columns.slice(0, visibleCount);
  416. const colTypes = this.colTypes.slice(0, visibleCount);
  417. const colStats = this.colStats.slice(0, visibleCount);
  418. const rows = this.rows.map((r) => r.slice(0, visibleCount));
  419. const numCols = columns.length;
  420. const colWidths = naturalWidths.slice(0, visibleCount);
  421. // Shrink proportionally only if still over budget after column pruning
  422. const borderOverhead = 1 + numCols * 3;
  423. const totalColWidth = colWidths.reduce((a, b) => a + b, 0);
  424. const availableForCols = width - borderOverhead;
  425. if (totalColWidth > availableForCols && availableForCols > numCols) {
  426. const ratio = availableForCols / totalColWidth;
  427. for (let i = 0; i < numCols; i++) {
  428. colWidths[i] = Math.max(MIN_COL_W, Math.floor(colWidths[i] * ratio));
  429. }
  430. }
  431. const pad = (s: string, w: number) => {
  432. const vw = visibleWidth(s);
  433. return vw >= w ? truncateToWidth(s, w, "…") : s + " ".repeat(w - vw);
  434. };
  435. const rpad = (s: string, w: number) => {
  436. const vw = visibleWidth(s);
  437. return vw >= w ? truncateToWidth(s, w, "…") : " ".repeat(w - vw) + s;
  438. };
  439. // Detect numeric columns for right-alignment
  440. const isNumeric = colTypes.map((dt) => /int|float|decimal|uint/.test(dt));
  441. const align = (s: string, ci: number, w: number) => (isNumeric[ci] ? rpad(s, w) : pad(s, w));
  442. const lines: string[] = [];
  443. // ── Top border ──
  444. const topBorder = t.fg("muted", "┌" + colWidths.map((w) => "─".repeat(w + 2)).join("┬") + "┐");
  445. lines.push(topBorder);
  446. // ── Column headers ──
  447. const headerCells = columns.map((col, ci) => t.fg("accent", t.bold(pad(col, colWidths[ci]))));
  448. lines.push(
  449. t.fg("muted", "│") + " " + headerCells.join(t.fg("muted", " │ ")) + " " + t.fg("muted", "│"),
  450. );
  451. // ── Type row ──
  452. const typeCells = colTypes.map((dt, ci) => t.fg("dim", pad(dt, colWidths[ci])));
  453. lines.push(
  454. t.fg("muted", "│") + " " + typeCells.join(t.fg("muted", " │ ")) + " " + t.fg("muted", "│"),
  455. );
  456. // ── Sparkline row ──
  457. const sparkCells = colStats.map((stats, ci) => {
  458. const spark = sparklineForColumn(rows, ci, stats, colTypes[ci] ?? "", colWidths[ci]);
  459. return t.fg("dim", pad(spark, colWidths[ci]));
  460. });
  461. lines.push(
  462. t.fg("muted", "│") + " " + sparkCells.join(t.fg("muted", " │ ")) + " " + t.fg("muted", "│"),
  463. );
  464. // ── Stats row ──
  465. const statCells = colStats.map((stats, ci) => {
  466. const statStr = formatStat(stats);
  467. return t.fg("dim", pad(statStr, colWidths[ci]));
  468. });
  469. lines.push(
  470. t.fg("muted", "│") + " " + statCells.join(t.fg("muted", " │ ")) + " " + t.fg("muted", "│"),
  471. );
  472. // ── Header separator ──
  473. const headerSep = t.fg("muted", "╞" + colWidths.map((w) => "═".repeat(w + 2)).join("╪") + "╡");
  474. lines.push(headerSep);
  475. // ── Data rows ──
  476. for (let r = 0; r < numRows; r++) {
  477. const row = rows[r];
  478. const cells = row.map((v, ci) => align(v, ci, colWidths[ci]));
  479. const rowStr =
  480. t.fg("muted", "│") + " " + cells.join(t.fg("muted", " │ ")) + " " + t.fg("muted", "│");
  481. lines.push(rowStr);
  482. }
  483. // ── Bottom border ──
  484. const botBorder = t.fg("muted", "└" + colWidths.map((w) => "─".repeat(w + 2)).join("┴") + "┘");
  485. lines.push(botBorder);
  486. // ── Footer info ──
  487. const showingRows = numRows < this.totalRows ? `showing ${numRows} of ` : "";
  488. const hiddenSuffix = hiddenCols > 0 ? ` (${hiddenCols} more columns)` : "";
  489. const infoText =
  490. this.footerText ?? `${showingRows}${this.totalRows} rows × ${totalCols} columns`;
  491. const info = t.fg("dim", `${infoText}${hiddenSuffix}`);
  492. lines.push(info);
  493. // Indent all lines to align with Out[n]: prompt
  494. const indent = " ".repeat(this.indent);
  495. for (let i = 0; i < lines.length; i++) {
  496. lines[i] = indent + lines[i];
  497. }
  498. this.cachedLines = lines;
  499. this.cachedWidth = width;
  500. return lines;
  501. }
  502. }
  503. // --- output formatting -------------------------------------------------------
  504. function stripAnsi(s: string): string {
  505. const esc = String.fromCharCode(27);
  506. return s.replace(new RegExp(`${esc}\\[[0-9;]*[A-Za-z]`, "g"), "");
  507. }
  508. function formatResult(result: CellResult): {
  509. content: (TextContent | ImageContent)[];
  510. isError: boolean;
  511. } {
  512. const outputs = result.outputs ?? [];
  513. const isError =
  514. result.status === "error" ||
  515. result.status === "kernel_error" ||
  516. result.status === "kernel_failed" ||
  517. outputs.some((o) => o.outputType === "error");
  518. const parts: (TextContent | ImageContent)[] = [];
  519. const header = `cell ${result.cellId} [${result.executionCount ?? "?"}] ${result.status}`;
  520. const textChunks: string[] = [];
  521. for (const o of outputs) {
  522. switch (o.outputType) {
  523. case "stream": {
  524. const prefix = o.name === "stderr" ? "[stderr] " : "";
  525. textChunks.push(prefix + (o.text ?? ""));
  526. break;
  527. }
  528. case "execute_result":
  529. case "display_data": {
  530. if (!o.dataJson) break;
  531. let data: Record<string, { type: string; value: unknown }>;
  532. try {
  533. data = JSON.parse(o.dataJson);
  534. } catch {
  535. break;
  536. }
  537. const hasImage = Object.keys(data).some(
  538. (m) => m.startsWith("image/") && m !== "image/svg+xml",
  539. );
  540. // Text-ish rep for the agent. Skip generic Figure reprs when we
  541. // also have an image — the image is more useful.
  542. const textRep =
  543. (data["text/llm+plain"]?.value as string | undefined) ??
  544. (data["text/plain"]?.value as string | undefined);
  545. if (textRep && !(hasImage && /^<Figure[^>]*>/.test(textRep.trim()))) {
  546. textChunks.push(String(textRep));
  547. }
  548. // Attach images directly so the model can see them.
  549. for (const [mime, entry] of Object.entries(data)) {
  550. if (!mime.startsWith("image/")) continue;
  551. if (mime === "image/svg+xml") continue; // text, not a raster image
  552. if (entry?.type !== "binary" || typeof entry.value !== "string") continue;
  553. // Dedupe images we've already emitted (Jupyter often sends the
  554. // same image as both execute_result and display_data).
  555. const dup = parts.some(
  556. (p) =>
  557. p.type === "image" &&
  558. (p as ImageContent).data === entry.value &&
  559. (p as ImageContent).mimeType === mime,
  560. );
  561. if (dup) continue;
  562. parts.push({
  563. type: "image",
  564. mimeType: mime,
  565. data: entry.value,
  566. } as ImageContent);
  567. }
  568. break;
  569. }
  570. case "error": {
  571. const tb = Array.isArray(o.traceback) ? o.traceback.join("\n") : "";
  572. textChunks.push(tb || `${o.ename ?? "Error"}: ${o.evalue ?? ""}`);
  573. break;
  574. }
  575. default:
  576. textChunks.push(`[${o.outputType} output]`);
  577. }
  578. }
  579. const body = stripAnsi(textChunks.join("").replace(/\n+$/, ""));
  580. parts.unshift({
  581. type: "text",
  582. text: body ? `${header}\n${body}` : header,
  583. });
  584. return { content: parts, isError };
  585. }
  586. function parseJsonObject(raw: string | undefined): Record<string, any> | undefined {
  587. if (!raw) return undefined;
  588. try {
  589. const parsed = JSON.parse(raw);
  590. return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : undefined;
  591. } catch {
  592. return undefined;
  593. }
  594. }
  595. function parseArrowManifestEntry(entry: any): ArrowStreamManifest | undefined {
  596. if (!entry || typeof entry !== "object") return undefined;
  597. let value = entry.value;
  598. if (entry.type === "text" && typeof value === "string") {
  599. try {
  600. value = JSON.parse(value);
  601. } catch {
  602. return undefined;
  603. }
  604. }
  605. if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
  606. return value as ArrowStreamManifest;
  607. }
  608. function parseTableManifest(dataJson: string | undefined): ArrowStreamManifest | undefined {
  609. const data = parseJsonObject(dataJson);
  610. return parseArrowManifestEntry(data?.[ARROW_STREAM_MANIFEST_MIME]);
  611. }
  612. function resolveManifestChunkPaths(
  613. manifest: ArrowStreamManifest,
  614. rn: Pick<RuntimedNode, "resolveBlobPath"> | undefined,
  615. ): string[] {
  616. const resolveBlobPath = rn?.resolveBlobPath;
  617. if (!resolveBlobPath) return [];
  618. const paths: string[] = [];
  619. for (const chunk of manifest.chunks ?? []) {
  620. if (typeof chunk.hash !== "string") continue;
  621. const resolved = resolveBlobPath(chunk.hash);
  622. if (typeof resolved === "string" && resolved.length > 0) {
  623. paths.push(resolved);
  624. }
  625. }
  626. return paths;
  627. }
  628. function findLegacyParquetBlobPath(result: CellResult): string | undefined {
  629. const source = findTableSource(result, undefined);
  630. return source?.kind === "parquet" ? source.path : undefined;
  631. }
  632. export function findTableSource(
  633. result: CellResult,
  634. rn?: Pick<RuntimedNode, "resolveBlobPath">,
  635. ): TableSource | undefined {
  636. for (const o of result.outputs ?? []) {
  637. const paths = parseJsonObject(o.blobPathsJson);
  638. const parquetPath = paths?.[PARQUET_MIME];
  639. if (typeof parquetPath === "string") return { kind: "parquet", path: parquetPath };
  640. const arrowPath = paths?.[ARROW_STREAM_MIME];
  641. if (typeof arrowPath === "string") return { kind: "arrow", path: arrowPath };
  642. }
  643. for (const o of result.outputs ?? []) {
  644. const manifest = parseTableManifest(o.dataJson);
  645. if (manifest) {
  646. return {
  647. kind: "arrow-manifest",
  648. manifest,
  649. chunkPaths: resolveManifestChunkPaths(manifest, rn),
  650. };
  651. }
  652. }
  653. return undefined;
  654. }
  655. function parseSummaryStats(summary: TableSummaryResult | undefined): {
  656. colTypes: string[];
  657. colStats: (ColumnStats | null)[];
  658. } {
  659. if (!summary) return { colTypes: [], colStats: [] };
  660. return {
  661. colTypes: summary.columns.map((c) => c.dataType),
  662. colStats: summary.columns.map((c) => {
  663. try {
  664. return JSON.parse(c.statsJson) as ColumnStats;
  665. } catch {
  666. return null;
  667. }
  668. }),
  669. };
  670. }
  671. function renderDataTableText(
  672. page: TableRowPage,
  673. count: number | undefined,
  674. theme: Theme,
  675. width: number,
  676. colTypes: string[],
  677. colStats: (ColumnStats | null)[],
  678. footerText?: string,
  679. ): string {
  680. const prompt = count != null ? `Out[${count}]:` : "Out:";
  681. const promptStr = theme.fg("muted", prompt);
  682. const indent = prompt.length + 1;
  683. const dt = new DataTable(
  684. page.columns,
  685. page.rows,
  686. page.totalRows,
  687. page.columns.map((_, i) => colTypes[i] ?? ""),
  688. page.columns.map((_, i) => colStats[i] ?? null),
  689. theme,
  690. indent,
  691. footerText,
  692. );
  693. const tableLines = dt.render(width - indent);
  694. const indentStr = " ".repeat(indent);
  695. if (tableLines.length > 0 && tableLines[0].startsWith(indentStr)) {
  696. tableLines[0] = `${promptStr} ${tableLines[0].slice(indent)}`;
  697. }
  698. return tableLines.join("\n");
  699. }
  700. function manifestColumns(manifest: ArrowStreamManifest): ArrowManifestColumn[] {
  701. return (manifest.schema?.columns ?? []).filter(
  702. (column) => column && typeof column.name === "string",
  703. );
  704. }
  705. function manifestIncludedRows(manifest: ArrowStreamManifest): number {
  706. const included = manifest.summary?.included_rows;
  707. if (typeof included === "number") return included;
  708. return (manifest.chunks ?? []).reduce((sum, chunk) => sum + (chunk.row_count ?? 0), 0);
  709. }
  710. function manifestTotalRows(manifest: ArrowStreamManifest): number {
  711. const total = manifest.summary?.total_rows;
  712. if (typeof total === "number") return total;
  713. return manifestIncludedRows(manifest);
  714. }
  715. function manifestFooterText(manifest: ArrowStreamManifest, columnCount: number): string {
  716. const included = manifestIncludedRows(manifest);
  717. const total = manifestTotalRows(manifest);
  718. const sampled = Boolean(manifest.summary?.sampled);
  719. const rowText = manifest.complete
  720. ? sampled && total > included
  721. ? `sampled ${included} of ${total}`
  722. : `${total}`
  723. : total > 0
  724. ? `loading ${included}/${total}`
  725. : `loading ${included}`;
  726. return `${rowText} rows × ${columnCount} columns`;
  727. }
  728. function renderManifestSkeletonText(
  729. source: Extract<TableSource, { kind: "arrow-manifest" }>,
  730. count: number | undefined,
  731. theme: Theme,
  732. width: number,
  733. ): string | undefined {
  734. const columns = manifestColumns(source.manifest);
  735. if (!columns.length) return undefined;
  736. const page: TableRowPage = {
  737. columns: columns.map((column) => column.name),
  738. rows: [],
  739. totalRows: manifestTotalRows(source.manifest),
  740. offset: 0,
  741. };
  742. return renderDataTableText(
  743. page,
  744. count,
  745. theme,
  746. width,
  747. columns.map((column) => column.type ?? ""),
  748. columns.map(() => null),
  749. manifestFooterText(source.manifest, columns.length),
  750. );
  751. }
  752. export function renderTableTextForSource(
  753. source: TableSource | undefined,
  754. count: number | undefined,
  755. theme: Theme,
  756. rn: RuntimedNode,
  757. width: number = process.stdout.columns || 120,
  758. ): string | undefined {
  759. if (!source) return undefined;
  760. try {
  761. if (source.kind === "parquet") {
  762. const page = rn.readParquetFile(source.path, 0, 40);
  763. if (!page?.columns?.length) return undefined;
  764. const { colTypes, colStats } = parseSummaryStats(rn.summarizeParquetFile?.(source.path));
  765. return renderDataTableText(page, count, theme, width, colTypes, colStats);
  766. }
  767. if (source.kind === "arrow") {
  768. const page = rn.readArrowFile?.(source.path, 0, 40);
  769. if (!page?.columns?.length) return undefined;
  770. const { colTypes, colStats } = parseSummaryStats(rn.summarizeArrowFile?.(source.path));
  771. return renderDataTableText(page, count, theme, width, colTypes, colStats);
  772. }
  773. const expectedChunkCount = (source.manifest.chunks ?? []).filter(
  774. (chunk) => typeof chunk.hash === "string",
  775. ).length;
  776. const hasAllChunkPaths =
  777. expectedChunkCount > 0 && source.chunkPaths.length === expectedChunkCount;
  778. if (source.manifest.complete && hasAllChunkPaths && rn.readArrowChunks) {
  779. try {
  780. const page = rn.readArrowChunks(source.chunkPaths, 0, 40);
  781. if (page?.columns?.length) {
  782. const { colTypes, colStats } = parseSummaryStats(
  783. rn.summarizeArrowChunks?.(source.chunkPaths),
  784. );
  785. return renderDataTableText(page, count, theme, width, colTypes, colStats);
  786. }
  787. } catch {
  788. // Fall through to the manifest skeleton if chunk files are unavailable.
  789. }
  790. }
  791. return renderManifestSkeletonText(source, count, theme, width);
  792. } catch {
  793. return undefined;
  794. }
  795. }
  796. // --- extension ---------------------------------------------------------------
  797. // Braille frames for the "waiting on first token" spinner shown in `In [*]:`
  798. // before any input_json_delta arrives. Anthropic validates the JSON server-side,
  799. // so the gap between toolcall_start and the first delta can be hundreds of ms.
  800. const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
  801. const SPINNER_INTERVAL_MS = 80;
  802. type InCallState = {
  803. spinner?: { frame: number; timer: ReturnType<typeof setInterval> };
  804. };
  805. const PYTHON_PARAMS = Type.Object({
  806. code: Type.String({
  807. description:
  808. "Python source to execute in the persistent notebook session. Use print(...) for side effects; the last expression's repr is returned as the result.",
  809. }),
  810. dependencies: Type.Optional(
  811. Type.Array(Type.String(), {
  812. description:
  813. "Packages to add before executing this code. On the first call they are recorded before the kernel starts; on later calls they are hot-synced into the running environment.",
  814. }),
  815. ),
  816. timeout_secs: Type.Optional(
  817. Type.Number({
  818. description: "Max seconds to wait for execution (default 120).",
  819. default: 120,
  820. }),
  821. ),
  822. });
  823. const ADD_DEPENDENCIES_PARAMS = Type.Object({
  824. packages: Type.Array(Type.String(), {
  825. description: "Package specs (e.g. ['matplotlib', 'pandas>=2']).",
  826. }),
  827. });
  828. type AddDependenciesDetails = {
  829. notebook_id?: string;
  830. packages?: string[];
  831. };
  832. const SAVE_NOTEBOOK_PARAMS = Type.Object({
  833. path: Type.Optional(
  834. Type.String({
  835. description:
  836. "File path to save to (e.g. './analysis.ipynb'). If omitted, saves to the original location.",
  837. }),
  838. ),
  839. });
  840. type SaveNotebookDetails = {
  841. notebook_id: string;
  842. path?: string;
  843. };
  844. export default function nteractReplExtension(pi: ExtensionAPI) {
  845. const bootstrap = detectBootstrap();
  846. if (bootstrap.kind === "missing") {
  847. // Surface a one-liner toast each session so the user sees the hint without
  848. // having to invoke the tool first.
  849. pi.on("session_start", async (_event, ctx) => {
  850. ctx.ui.notify(INSTALL_HINT, "warning");
  851. });
  852. // Register python_repl with a stub execute() so the LLM can still advertise
  853. // the capability and surface install guidance the moment it tries to run
  854. // Python. Throwing routes the message into the tool-result channel that the
  855. // model relays back to the user.
  856. pi.registerTool({
  857. name: "python_repl",
  858. label: "Python REPL",
  859. description:
  860. "Execute Python in your persistent REPL. Requires the nteract daemon (runtimed). " +
  861. "If unavailable, recommend the user install with `curl -fsSL https://sh.nteract.io | bash` " +
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 965 on GitHub
  862. "or download the desktop app at https://nteract.io.",
  863. promptSnippet:
  864. "python_repl: requires the nteract daemon. Install with `curl -fsSL https://sh.nteract.io | bash` or via https://nteract.io.",
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 968 on GitHub
  865. parameters: PYTHON_PARAMS,
  866. async execute() {
  867. throw new Error(INSTALL_HINT);
  868. },
  869. });
  870. return;
  871. }
  872. const rn = bootstrap.rn;
  873. let session: Session | null = null;
  874. let opening: Promise<Session> | null = null;
  875. let nextExecCount: number | null = 1;
  876. let executionViewSubscription: SubscriptionLike | null = null;
  877. function disposeExecutionViewTracking(): void {
  878. const sub = executionViewSubscription;
  879. executionViewSubscription = null;
  880. sub?.unsubscribe?.();
  881. sub?.dispose?.();
  882. }
  883. function trackExecutionView(sess: Session): void {
  884. disposeExecutionViewTracking();
  885. executionViewSubscription =
  886. sess.executionViewChanges$?.subscribe((changeset) => {
  887. for (const [, snapshot] of changeset.execution_upserts ?? []) {
  888. const count = snapshot.execution_count;
  889. if (typeof count === "number") {
  890. nextExecCount = Math.max(nextExecCount ?? 1, count + 1);
  891. }
  892. }
  893. }) ?? null;
  894. }
  895. async function addDependenciesAndSync(sess: Session, packages: string[]): Promise<void> {
  896. const unique = Array.from(new Set(packages.map((pkg) => pkg.trim()).filter(Boolean)));
  897. if (!unique.length) return;
  898. if (sess.addDependencies) {
  899. await sess.addDependencies(unique);
  900. } else if (sess.addUvDependency) {
  901. for (const pkg of unique) {
  902. await sess.addUvDependency(pkg);
  903. }
  904. } else {
  905. throw new Error("@runtimed/node Session does not support dependency edits");
  906. }
  907. await sess.syncEnvironment();
  908. }
  909. async function ensureSession(initialDependencies: string[] = []): Promise<Session> {
  910. const dependencies = Array.from(
  911. new Set(initialDependencies.map((pkg) => pkg.trim()).filter(Boolean)),
  912. );
  913. if (session) {
  914. await addDependenciesAndSync(session, dependencies);
  915. return session;
  916. }
  917. if (opening) {
  918. const opened = await opening;
  919. await addDependenciesAndSync(opened, dependencies);
  920. return opened;
  921. }
  922. opening = (async () => {
  923. // Omit socketPath so the binding resolves through defaultSocketPath(),
  924. // which honors RUNTIMED_SOCKET_PATH / RUNTIMED_WORKSPACE_PATH and the
  925. // channel auto-detect.
  926. session = await rn.createNotebook({
  927. runtime: "python",
  928. workingDir: process.cwd(),
  929. peerLabel: "pi",
  930. description: "pi Python REPL",
  931. dependencies,
  932. });
  933. trackExecutionView(session);
  934. return session;
  935. })();
  936. try {
  937. return await opening;
  938. } finally {
  939. opening = null;
  940. }
  941. }
  942. pi.registerTool<typeof PYTHON_PARAMS, unknown, InCallState>({
  943. name: "python_repl",
  944. label: "Python REPL",
  945. description:
  946. "Execute Python in your persistent REPL. Backed by a real IPython runtime. Variables, imports, and state stick around between calls. The last expression is the result; use print() or display() for intermediate output. Images (matplotlib, PIL, widgets) are returned inline.",
  947. promptSnippet:
  948. "python_repl: run Python in your persistent REPL (variables and imports persist; returns stdout + last expression + images).",
  949. promptGuidelines: [
  950. "Use `python_repl` for data analysis, plotting, and multi-step workflows. State persists between calls in a real IPython runtime.",
  951. "Variables and imports stick around. No need to re-import or redefine on every turn unless the user has reloaded the session.",
  952. "The last expression is the result; use print() or display() for intermediate output.",
  953. "Images (matplotlib, PIL, widgets) come back inline. The user sees them if their terminal supports graphics.",
  954. "Pass `dependencies` on the first call to pre-install packages before the kernel starts.",
  955. "Use `python_add_dependencies` to install packages mid-session without restarting the kernel.",
  956. ],
  957. parameters: PYTHON_PARAMS,
  958. renderCall(args, theme, _context) {
  959. const text =
  960. (_context.lastComponent as InstanceType<typeof Text> | undefined) ?? new Text("", 0, 0);
  961. const code = (args?.code ?? "").replace(/^\n+/, "");
  962. const count = nextExecCount;
  963. const prompt = count != null ? `In [${count}]:` : "In [*]:";
  964. const promptStr = theme.fg("accent", theme.bold(prompt));
  965. // Anthropic gates input_json_delta on server-side validation, so there is
  966. // a visible pause between toolcall_start and the first token of `code`.
  967. // Show a braille spinner in the prompt slot until either the first
  968. // character streams in or the call resolves another way.
  969. const state = _context.state as InCallState;
  970. const waitingForFirstToken =
  971. !code && !_context.executionStarted && !_context.argsComplete && !_context.isError;
  972. if (waitingForFirstToken) {
  973. if (!state.spinner) {
  974. const timer = setInterval(() => {
  975. const s = state.spinner;
  976. if (!s) return;
  977. s.frame = (s.frame + 1) % SPINNER_FRAMES.length;
  978. _context.invalidate();
  979. }, SPINNER_INTERVAL_MS);
  980. // Don't keep the event loop alive on the spinner alone.
  981. timer.unref?.();
  982. state.spinner = { frame: 0, timer };
  983. }
  984. const frame = SPINNER_FRAMES[state.spinner.frame];
  985. text.setText(`${promptStr} ${theme.fg("muted", frame)}`);
  986. return text;
  987. }
  988. if (state.spinner) {
  989. clearInterval(state.spinner.timer);
  990. state.spinner = undefined;
  991. }
  992. const lines = highlightCode(code, "python");
  993. // Indent continuation lines to align with first line after prompt
  994. const pad = " ".repeat(prompt.length + 1);
  995. const formatted = lines
  996. .map((l, i) => (i === 0 ? `${promptStr} ${l}` : `${pad}${l}`))
  997. .join("\n");
  998. text.setText(formatted);
  999. return text;
  1000. },
  1001. renderResult(result, _options, theme, _context) {
  1002. const details = (result as any).details ?? {};
  1003. const count = details.execution_count;
  1004. const isErr = details.is_error;
  1005. // Update the closure count for the next renderCall
  1006. if (count != null) {
  1007. nextExecCount = count + 1;
  1008. }
  1009. const tableSource =
  1010. (details.table_source as TableSource | undefined) ??
  1011. (typeof details.parquet_blob_path === "string"
  1012. ? ({ kind: "parquet", path: details.parquet_blob_path } as TableSource)
  1013. : undefined);
  1014. const tableText = renderTableTextForSource(tableSource, count, theme, rn);
  1015. if (tableText) {
  1016. const text =
  1017. (_context.lastComponent instanceof Text ? _context.lastComponent : undefined) ??
  1018. new Text("", 0, 0);
  1019. text.setText(tableText);
  1020. return text;
  1021. }
  1022. // Extract text output from content
  1023. const textContent = (result.content ?? [])
  1024. .filter((c: any) => c.type === "text")
  1025. .map((c: any) => c.text)
  1026. .join("\n");
  1027. // Strip the "cell <id> [n] status" header we put in the text content
  1028. const body = textContent.replace(/^cell \S* \[[^\]]*\] \S*\n?/, "").trim();
  1029. const text =
  1030. (_context.lastComponent instanceof Text ? _context.lastComponent : undefined) ??
  1031. new Text("", 0, 0);
  1032. if (!body) {
  1033. // No output — just show a check/cross
  1034. const icon = isErr ? theme.fg("error", "\u2717") : theme.fg("success", "\u2713");
  1035. text.setText(icon);
  1036. } else if (isErr) {
  1037. text.setText(theme.fg("error", body));
  1038. } else {
  1039. const prompt = count != null ? `Out[${count}]:` : "Out:";
  1040. const promptStr = theme.fg("muted", prompt);
  1041. const pad = " ".repeat(prompt.length + 1);
  1042. const bodyLines = body.split("\n");
  1043. const formatted = bodyLines
  1044. .map((l: string, i: number) => (i === 0 ? `${promptStr} ${l}` : `${pad}${l}`))
  1045. .join("\n");
  1046. text.setText(formatted);
  1047. }
  1048. return text;
  1049. },
  1050. async execute(_toolCallId, params, signal, onUpdate) {
  1051. if (signal?.aborted) throw new Error("aborted");
  1052. const sess = await ensureSession(params.dependencies ?? []);
  1053. const timeoutSecs = Math.max(1, params.timeout_secs ?? 120);
  1054. const result = await sess.runCell(params.code, {
  1055. timeoutMs: Math.round(timeoutSecs * 1000),
  1056. onUpdate: (progress) => {
  1057. const { content, isError } = formatResult(progress);
  1058. onUpdate?.({
  1059. content,
  1060. details: {
  1061. notebook_id: sess.notebookId,
  1062. cell_id: progress.cellId,
  1063. execution_id: progress.executionId,
  1064. status: progress.status,
  1065. execution_count: progress.executionCount,
  1066. is_error: isError,
  1067. table_source: findTableSource(progress, rn),
  1068. parquet_blob_path: findLegacyParquetBlobPath(progress),
  1069. streaming: true,
  1070. },
  1071. });
  1072. },
  1073. });
  1074. const tableSource = findTableSource(result, rn);
  1075. const { content, isError } = formatResult(result);
  1076. return {
  1077. content,
  1078. details: {
  1079. notebook_id: sess.notebookId,
  1080. cell_id: result.cellId,
  1081. execution_id: result.executionId,
  1082. status: result.status,
  1083. execution_count: result.executionCount,
  1084. is_error: isError,
  1085. table_source: tableSource,
  1086. parquet_blob_path: tableSource?.kind === "parquet" ? tableSource.path : undefined,
  1087. runtime: sess.getRuntimeStatus
  1088. ? await sess.getRuntimeStatus().catch(() => undefined)
  1089. : undefined,
  1090. },
  1091. };
  1092. },
  1093. });
  1094. pi.registerTool<typeof ADD_DEPENDENCIES_PARAMS, AddDependenciesDetails>({
  1095. name: "python_add_dependencies",
  1096. label: "Add Dependencies",
  1097. description:
  1098. "Install packages into the running Python environment without restarting. Accepts pip-style specs like 'matplotlib', 'numpy>=2', 'requests'. The kernel stays hot.",
  1099. promptSnippet:
  1100. "python_add_dependencies: install packages into the running Python session (no restart needed).",
  1101. parameters: ADD_DEPENDENCIES_PARAMS,
  1102. async execute(_toolCallId, params, signal) {
  1103. if (signal?.aborted) throw new Error("aborted");
  1104. if (!params.packages.length) {
  1105. return { content: [{ type: "text", text: "No packages given." }], details: {} };
  1106. }
  1107. const sess = await ensureSession();
  1108. await addDependenciesAndSync(sess, params.packages);
  1109. return {
  1110. content: [
  1111. {
  1112. type: "text",
  1113. text: `Installed into ${sess.notebookId}: ${params.packages.join(", ")}`,
  1114. },
  1115. ],
  1116. details: { notebook_id: sess.notebookId, packages: params.packages },
  1117. };
  1118. },
  1119. });
  1120. pi.registerTool<typeof SAVE_NOTEBOOK_PARAMS, SaveNotebookDetails>({
  1121. name: "python_save_notebook",
  1122. label: "Save Notebook",
  1123. description:
  1124. "Save the current Python session as an .ipynb file. If no path is given, saves to the original location (if it was opened from a file). Provide a path to save elsewhere.",
  1125. promptSnippet: "python_save_notebook: save the current session as an .ipynb file.",
  1126. parameters: SAVE_NOTEBOOK_PARAMS,
  1127. async execute(_toolCallId, params, signal) {
  1128. if (signal?.aborted) throw new Error("aborted");
  1129. const sess = await ensureSession();
  1130. const savePath = params.path ? resolvePath(params.path) : undefined;
  1131. await sess.saveNotebook(savePath);
  1132. const where = savePath ?? "original location";
  1133. return {
  1134. content: [{ type: "text", text: `Notebook saved to ${where}` }],
  1135. details: { notebook_id: sess.notebookId, path: savePath },
  1136. };
  1137. },
  1138. });
  1139. pi.registerCommand("python-reset", {
  1140. description:
  1141. "Start fresh: next /python_repl call opens a new kernel (clean slate, no prior variables or imports)",
  1142. handler: async (_args, ctx) => {
  1143. const old = session;
  1144. session = null;
  1145. nextExecCount = 1;
  1146. disposeExecutionViewTracking();
  1147. if (old) {
  1148. try {
  1149. if (old.shutdownNotebook) {
  1150. await old.shutdownNotebook();
  1151. } else {
  1152. await old.close();
  1153. }
  1154. } catch {}
  1155. }
  1156. ctx.ui.notify(
  1157. "Python session closed. Next python_repl call will start a fresh kernel.",
  1158. "info",
  1159. );
  1160. },
  1161. });
  1162. pi.on("session_shutdown", async () => {
  1163. disposeExecutionViewTracking();
  1164. if (session) {
  1165. try {
  1166. if (session.shutdownNotebook) {
  1167. await session.shutdownNotebook();
  1168. } else {
  1169. await session.close();
  1170. }
  1171. } catch {}
  1172. session = null;
  1173. }
  1174. });
  1175. }

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.