The jupyter namespace
Every cell can use a global named jupyter. It decides how values appear in the notebook: as Markdown, HTML, SVG, images, charts or tables instead of plain text. It is a port of Deno.jupyter, the API that Deno's built-in kernel (deno jupyter) gives notebooks, so notebooks and examples written for Deno work here, and what you learn here applies there.
This page assumes no experience with Deno. The output shown is what the examples produced on the cdp-node kernel when the docs were built. Differences on other runtimes are noted where they exist, and summarized at the end.
Showing output
| Member | What it does |
|---|---|
jupyter.display(value, options?) | Show a value now, in the middle of a cell, or update one shown earlier. |
jupyter.md, jupyter.html, jupyter.svg | Tagged templates that turn a string into rendered Markdown, HTML or SVG. |
jupyter.image(pathOrBytes) | Show a PNG or JPEG from a file or from bytes. |
jupyter.$display | The symbol a class implements to choose how its instances appear. |
jupyter.format(value) | Compute the output for a value without showing it. |
jupyter.broadcast(type, content) | Send a raw Jupyter message, for things the helpers don't cover. |
Data
| Member | What it does |
|---|---|
jupyter.table(value, options?) | Show rows as a table that every frontend can display, with a text summary for agents. Not in Deno. |
jupyter.sql`...` | Run SQL on an in-memory DuckDB database; results show as tables. Not in Deno. |
jupyter.chart(chart, options?) | Draw a Vega-Lite spec or an Observable Plot chart as one SVG, with a text summary. Not in Deno. |
Asking and interrupting
| Member | What it does |
|---|---|
jupyter.signal | An AbortSignal that an interrupt aborts, so a waiting cell can stop. Not in Deno. |
prompt(), confirm() | Globals, not members: ask for a line of input or a yes/no answer, and wait for it. |
jupyter.comm, jupyter.widget | Comms, and interactive anywidget widgets: see Widgets and comms and the widget model. Not in Deno. |
Notebooks as programs
| Member | What it does |
|---|---|
jupyter.params, jupyter.result(name, value) | A run's parameters, and values published by name for whoever ran the notebook. Not in Deno. |
jupyter.host(options?) | Read, search and run other notebooks through the Ganymede server running this kernel. Not in Deno. |
The kernel
| Member | What it does |
|---|---|
jupyter.version, jupyter.runtime | The cdp-kernel version running the cell, and the runtime's name and version. Not in Deno. |
The jupyter reference lists every member's arguments and return value.
Showing output
Everything that decides how a value appears in the notebook.
How cell output works
A cell can produce output three ways:
const languages = ["TypeScript", "Rust", "Go"];
console.log(`${languages.length} languages`); // stream output (stdout)
console.error("this goes to stderr"); // stream output (stderr)
languages.map((name) => name.toUpperCase()); // the cell's result3 languages
this goes to stderr
[ 'TYPESCRIPT', 'RUST', 'GO' ]
console.logand friends print text as the cell runs.- If the cell ends with an expression, its value is the cell's result, shown under the cell (here
[ 'TYPESCRIPT', 'RUST', 'GO' ]). A trailing semicolon doesn't hide it. A cell that ends with a declaration, such asconst total = 42;, has no result. jupyter.display()shows a value at any point in the cell, as many times as you call it.
A result or displayed value isn't just text. Jupyter output is a MIME bundle: an object mapping media types to data, such as { "text/plain": "34°C", "text/html": "<b>34°C</b>" }. The frontend (JupyterLab, VS Code, Notebook) picks the richest type it can render, and falls back to text/plain. Everything on this page is a way to build those bundles. For an ordinary value such as a number, array or plain object, the bundle has only text/plain, the same text console.log would print.
Markdown, HTML and SVG
jupyter.md, jupyter.html and jupyter.svg are tagged templates: write them directly before a template literal, with no parentheses. The result is an object that renders as that media type, either as the cell's result or passed to jupyter.display.
Markdown
Use Markdown for reports built from data: headings, tables, emphasis, lists and links.
const scores = { Ada: 92, Grace: 88, Linus: 75 };
const rows = Object.entries(scores)
.map(([name, score]) => `| ${name} | ${score} |`)
.join("\n");
const average = Object.values(scores).reduce((a, b) => a + b) / 3;
jupyter.md`
## Quiz results
| Name | Score |
| ---- | ----: |
${rows}
Average: **${average.toFixed(1)}**
`;Quiz results
| Name | Score |
|---|---|
| Ada | 92 |
| Grace | 88 |
| Linus | 75 |
Average: 85.0
This renders a heading, a three-row table, and the average in bold. JupyterLab and VS Code also render LaTeX math in Markdown output, such as jupyter.md`$e^{i\pi} + 1 = 0$`.
HTML
HTML output can use any element and inline styles. Interpolated values are inserted as is, without escaping, so text from users, files or the network can break the markup or inject a <script>. Escape it yourself:
const comment = `<script>alert("hi")</script> & more`;
const escapeHTML = (s: string) =>
s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
jupyter.html`<p>Unsafe: ${comment}</p>
<p>Safe: ${escapeHTML(comment)}</p>`;Unsafe: & more
Safe: <script>alert("hi")</script> & more
The second paragraph shows the comment as literal text. The same applies to jupyter.md and jupyter.svg.
SVG
SVG is useful for small charts and diagrams drawn from data, with no library:
const data = [4, 8, 15, 16, 23, 42];
const max = Math.max(...data);
const bars = data.map((v, i) => {
const h = (v / max) * 100;
return `<rect x="${i * 30}" y="${110 - h}" width="24" height="${h}" fill="teal"/>
<text x="${i * 30 + 12}" y="125" font-size="10" text-anchor="middle">${v}</text>`;
}).join("");
jupyter.svg`<svg xmlns="http://www.w3.org/2000/svg" width="180" height="130">${bars}</svg>`;This draws a labeled bar chart. Include the xmlns attribute: some frontends render SVG output as an image, which requires it.
Showing output with display
await jupyter.display(value, options?) shows value immediately. Use it to show more than one thing from a cell, or to show progress while a cell is still running.
for (const step of ["fetch", "parse", "summarize"]) {
await jupyter.display(jupyter.md`Finished **${step}**`);
}
"all done";Finished fetch
Finished parse
Finished summarize
'all done'This shows three Markdown lines, then the result 'all done'. value can be anything a cell could end with: a template from the previous section, an image, an object with a custom display, or a plain value, which shows as text.
display returns a promise. Without await the output still appears, but output written later in the cell, such as a console.log, can appear before it.
Updating output in place
Give a display a display_id, then display again with the same id and update: true to replace it instead of adding a new output. This makes progress bars, counters and live status lines:
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const bar = (pct: number) =>
jupyter.html`<progress value="${pct}" max="100"></progress> ${pct}%`;
await jupyter.display(bar(0), { display_id: "download" });
for (let pct = 25; pct <= 100; pct += 25) {
await sleep(500);
await jupyter.display(bar(pct), { display_id: "download", update: true });
}The cell shows one progress bar that fills up. An update replaces every output with that id, including one shown by an earlier cell, so a later cell can change what an earlier one displayed. Pick ids that won't collide, such as crypto.randomUUID().
Sending a MIME bundle directly
With raw: true, a plain object is sent as the MIME bundle itself rather than being formatted. Use it for media types the helpers don't produce:
const user = { name: "Ada", roles: ["admin", "dev"], active: true };
await jupyter.display(
{
"application/json": user,
"text/plain": JSON.stringify(user),
},
{ raw: true },
);{
"active": true,
"name": "Ada",
"roles": [
"admin",
"dev"
]
}JupyterLab renders application/json as a collapsible tree. Other useful types are text/latex, application/geo+json (with an extension), and application/vnd.vegalite.v5+json. Include text/plain as a fallback for frontends that can't render the rich type.
Without raw: true, the same object is formatted like any other value, so jupyter.display({ "text/html": "<b>hi</b>" }) shows the object's text, not bold text.
Images
jupyter.image shows a PNG or JPEG. Pass a file path, relative to the notebook's directory:
jupyter.image("./chart.png");or the image's bytes as a Uint8Array:
const response = await fetch("https://www.python.org/static/img/python-logo.png");
const logo = new Uint8Array(await response.arrayBuffer());
jupyter.image(logo);The format is detected from the bytes, not the file name. Anything other than PNG or JPEG throws a TypeError; for SVG use jupyter.svg. On workerd and celld there is no file system, so pass bytes.
A Uint8Array holding a PNG or JPEG is shown as an image without jupyter.image too (see Values shown richly).
Custom display for your own classes
A class can choose how its instances appear by implementing a method keyed by the jupyter.$display symbol. The method returns a MIME bundle:
class Temperature {
celsius: number;
constructor(celsius: number) {
this.celsius = celsius;
}
[jupyter.$display]() {
const color = this.celsius >= 30 ? "crimson" : this.celsius <= 5 ? "steelblue" : "seagreen";
const fahrenheit = (this.celsius * 9) / 5 + 32;
return {
"text/plain": `${this.celsius}°C`,
"text/html": `<b style="color:${color}">${this.celsius}°C</b> (${fahrenheit.toFixed(1)}°F)`,
};
}
}
new Temperature(34);The result is a red "34°C (93.2°F)". The method is used wherever the object is shown: as a cell's result, through jupyter.display, or through jupyter.format. It is not used for objects nested inside other values: [new Temperature(2), new Temperature(20)] shows as plain text. Display each one instead:
for (const t of [new Temperature(2), new Temperature(20)]) {
await jupyter.display(t);
}The method can be async, to fetch or compute what it shows:
class Weather {
city: string;
constructor(city: string) {
this.city = city;
}
async [jupyter.$display]() {
const forecast = await Promise.resolve("18°C, light rain"); // e.g. a fetch
return { "text/markdown": `**${this.city}**: ${forecast}` };
}
}
new Weather("Portland");Portland: 18°C, light rain
In a library
jupyter.$display is Symbol.for("Jupyter.display"). Code in a module, which might also run outside a notebook, should use that form, so it doesn't depend on the jupyter global:
// matrix.ts
export class Matrix {
rows: number[][];
constructor(rows: number[][]) {
this.rows = rows;
}
[Symbol.for("Jupyter.display")]() {
const body = this.rows.map((r) => r.join(" & ")).join(" \\\\ ");
return { "text/latex": `$$\\begin{bmatrix} ${body} \\end{bmatrix}$$` };
}
}Outside a notebook the method is never called. A library written this way displays the same in deno jupyter.
For type checking, see Editor types: only jupyter.$display carries the precise method type.
Values shown richly without any code
A cell's result, or a value passed to jupyter.display, gets a rich output when it looks like one of the objects below. The checks are by shape (duck typing), so they work with any library that produces such objects, without a dependency on it. They are checked in this order:
| Value | Shown as | Detected by |
|---|---|---|
Object with a [jupyter.$display]() method | whatever it returns | the method |
| Canvas | PNG image | a toDataURL() method |
| Vega or Vega-Lite chart | interactive chart | a toSpec() method returning a spec with $schema |
| Arrow table, Polars DataFrame, DuckDB result | table | Arrow: schema.fields, numRows, getChild(); Polars: schema, head(), toRecords(); DuckDB: columnNames(), columnTypes(), getRowsJS(), currentRowCount (a reader, from runAndReadAll()) |
Uint8Array of PNG or JPEG data | image | the file signature |
| SVG element | SVG | outerHTML starting with <svg |
| HTML element | HTML | an outerHTML string |
Anything else shows as text. Some examples with common npm packages (see Writing notebooks for how npm: imports work):
Charts with Vega-Lite. vega-lite-api builds a chart in code. JupyterLab renders it as an interactive chart with no extension.
import * as vl from "npm:vega-lite-api@5";
const sales = [
{ month: "Jan", sales: 28 },
{ month: "Feb", sales: 55 },
{ month: "Mar", sales: 43 },
];
vl.markBar().data(sales).encode(vl.x().fieldO("month"), vl.y().fieldQ("sales"));A hand-written spec works too: any object whose toSpec() returns it.
Next to the chart the kernel sends a short text summary, for frontends that can't draw charts (jupyter console, a notebook converted to text, an agent reading the saved notebook). For the chart above it reads:
Vega-Lite bar chart: x=month (ordinal, 3 values), y=sales (quantitative, 28 to 55), 3 rowsTables with Polars. A nodejs-polars DataFrame shows as a table, as do Arrow tables and DuckDB results:
import pl from "npm:nodejs-polars@0.18";
const df = pl.DataFrame({
city: ["Lisbon", "Oslo", "Lima"],
population_m: [0.55, 0.71, 10.1],
coastal: [true, false, true],
});
df.sort("population_m", true);| city | population_m | coastal |
|---|---|---|
| Lima | 10.1 | true |
| Oslo | 0.71 | false |
| Lisbon | 0.55 | true |
Drawing with a canvas. @napi-rs/canvas implements the browser's Canvas 2D API:
import { createCanvas } from "npm:@napi-rs/canvas@0.1";
const canvas = createCanvas(200, 100);
const ctx = canvas.getContext("2d");
ctx.fillStyle = "#264653";
ctx.fillRect(0, 0, 200, 100);
ctx.fillStyle = "#e9c46a";
ctx.beginPath();
ctx.arc(100, 50, 35, 0, Math.PI * 2);
ctx.fill();
canvas;DOM elements. A server-side DOM such as linkedom lets you build HTML with the DOM API and show the element:
import { parseHTML } from "npm:linkedom@0.18";
const { document } = parseHTML("<!doctype html><html><body></body></html>");
const list = document.createElement("ul");
for (const item of ["eggs", "flour", "milk"]) {
const li = document.createElement("li");
li.textContent = item;
list.append(li);
}
list;- eggs
- flour
- milk
These four examples run on Node, Deno and Bun. On workerd and celld only vega-lite-api works: packages with native add-ons (Polars, @napi-rs/canvas) can't be bundled for workerd, and linkedom fails on an optional import of canvas. Deno's deno jupyter can also display WebGPU textures and buffers; that is not supported here.
Getting a bundle with format
await jupyter.format(value) returns the MIME bundle that displaying value would send, without showing anything. Use it to check a custom display, or to reuse the rendered output elsewhere:
const bundle = await jupyter.format(new Temperature(12));
Object.keys(bundle); // [ 'text/plain', 'text/html' ][ 'text/plain', 'text/html' ]
import { writeFileSync } from "node:fs";
const report = await jupyter.format(jupyter.md`# Weekly report`);
writeFileSync("report.md", report["text/markdown"] as string);For plain values the text/plain entry contains terminal color codes, as the notebook shows them: await jupyter.format(42) returns { "text/plain": "\x1b[33m42\x1b[39m" }.
Raw messages with broadcast
jupyter.broadcast(msgType, content, { metadata?, buffers? }) sends a message of any type on the kernel's output channel (IOPub), as a reply to the running cell. The helpers above are built on it. Use it for message types they don't cover; the Jupyter messaging spec lists them.
The most useful is clear_output, which clears the cell's output. With wait: true the old output stays until new output arrives, so it doesn't flicker:
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
for (const n of [3, 2, 1]) {
jupyter.broadcast("clear_output", { wait: true });
await jupyter.display(jupyter.md`Launching in **${n}**…`);
await sleep(1000);
}
jupyter.broadcast("clear_output", { wait: true });
"🚀";'🚀'The cell counts down in place and ends showing only the result. Unlike a display_id update, this clears everything the cell has printed so far, including console.log output.
broadcast sends what you give it without checking it, so a message with the wrong fields is silently ignored or mishandled by the frontend. Prefer the helpers when one fits.
Data
Tables, SQL and charts, each with a text summary that agents and consoles read. None of these are in Deno.
Tables
jupyter.table(value, options?) shows rows and columns as a table. It takes an array of row objects, an array of arrays (named with columns), an Arrow table, a Polars DataFrame or a @duckdb/node-api result:
const moons = [
{ moon: "Io", radius_km: 1821.6, discovered: new Date("1610-01-08") },
{ moon: "Europa", radius_km: 1560.8, discovered: new Date("1610-01-08") },
{ moon: "Ganymede", radius_km: 2634.1, discovered: new Date("1610-01-07") },
{ moon: "Callisto", radius_km: 2410.3, discovered: new Date("1610-01-07") },
];
jupyter.table(moons, { title: "Galilean moons" });| moon string | radius_km number | discovered date |
|---|---|---|
| Io | 1821.6 | 1610-01-08 |
| Europa | 1560.8 | 1610-01-08 |
| Ganymede | 2634.1 | 1610-01-07 |
| Callisto | 2410.3 | 1610-01-07 |
The output has three parts, so each frontend shows what it can:
application/vnd.dataresource+json: each column's name and Table Schema type, the rows as JSON, andganymede: { rows, shown }with the total row count and how many rows the output holds (pluspagewhen it holds fewer, described below). The Ganymede apps show this part as a table with sorting and paging.text/html: a plain table with each column's type under its name, up to 20 rows, and past that the first 10 and the last 5. JupyterLab, VS Code and GitHub show this.text/plain: the shape, each column's type and range, and numbered first and last rows, forjupyter consoleand agents reading the notebook. For the cell above it reads:
Table "Galilean moons" (4 rows, 3 columns)
Columns:
moon string 4 values
radius_km number 1560.8 to 2634.1
discovered date 1610-01-07 to 1610-01-08
Rows:
0 | Io | 1821.6 | 1610-01-08
1 | Europa | 1560.8 | 1610-01-08
2 | Ganymede | 2634.1 | 1610-01-07
3 | Callisto | 2410.3 | 1610-01-07The output holds at most limit rows: 1,000 by default, up to 10,000, and never more than 1 MB of JSON (in UTF-8). A bigger table says so everywhere it shows ("1,000 shown" in the summary, whose ranges then cover those rows), and its last rows still come from the whole table. Values are stored as JSON: integers past 2^53 as strings, dates as ISO 8601 strings, times of day as HH:MM:SS, NaN and infinities as the strings "NaN", "Infinity" and "-Infinity", and binary data as its length.
A table bigger than the output keeps the rest in the kernel, for the frontend to page through. The kernel keeps the last 16 such tables shown as outputs (an update of a display keeps its place), and the output names its table as ganymede.page. A frontend opens a comm to ganymede.table.v1 with { id }, the output's ganymede.page, and sends { request, offset, limit, sort }, where sort is optional and takes the form { column, descending }. The kernel answers { request, offset, total, rows }: up to 1,000 rows, as arrays in the output's field order, encoded as the output's rows are. A sort covers the whole table, up to a million rows, in the order the Ganymede apps sort the embedded rows. If the kernel no longer has the table (it restarted, or the table is one of the older ones), it sends { error } and closes the comm, and the frontend keeps to the embedded rows. The kernel pages the value itself, not a copy: if a later cell changes it, run the table's cell again so the output and its pages agree.
columns picks columns (and, for rows given as objects or arrays, their order), and title adds a caption. A column name that repeats, as from a join, gets a suffix: the second id is id_1. Column types come from the source when it declares them (Arrow, Polars, DuckDB), and otherwise from the rows embedded. An Arrow table, Polars DataFrame or DuckDB result shows as a table without the call when it is a cell's value. For DuckDB, that is a reader from runAndReadAll(): a run() result loads its rows asynchronously, so jupyter.table refuses it.
SQL with DuckDB
jupyter.sql runs SQL on an in-memory DuckDB database, as a tagged template. The result shows as a table:
const min = 2000;
await jupyter.sql`
select moon, radius_km
from (values ('Io', 1821.6), ('Ganymede', 2634.1), ('Callisto', 2410.3)) as m(moon, radius_km)
where radius_km > ${min}
order by radius_km desc`;| moon string | radius_km number |
|---|---|
| Ganymede | 2634.1 |
| Callisto | 2410.3 |
A ${value} can't change the query, whatever it holds: it becomes a bound parameter, or in the browser target a quoted literal (so that an interrupt can stop the query). Dates go in as ISO strings, objects and arrays as JSON. For text that has to be part of the query, a table name or a file path built in code, use jupyter.sql.raw(text), and never with text from outside the notebook.
The result has columns (name and DuckDB type) and rows (plain objects), for code that goes on with the data:
const { rows } = await jupyter.sql`select range as n from range(3)`;
rows.map((r) => r.n); // [ 0, 1, 2 ][ 0, 1, 2 ]
Integers that fit a JavaScript number are numbers, larger ones bigint; DATE and TIMESTAMP values are Dates, and TIME values "HH:MM:SS" strings. A repeated column name, as from a join, gets a suffix: the second id is id_1.
DuckDB reads CSV, Parquet and JSON files by path or URL, and Parquet over HTTP in ranges, fetching only the columns a query needs. jupyter.sql.load(name, source) makes a table from a file, or from data the notebook already has: an array of row objects, an Arrow table or a Polars DataFrame. Rows go in whole; bytes become base64 text.
await jupyter.sql.load("weather", "https://raw.githubusercontent.com/vega/vega-datasets/v2.11.0/data/seattle-weather.csv");
await jupyter.sql.load("moons", [
{ moon: "Io", radius_km: 1821.6, discovered: new Date("1610-01-08") },
{ moon: "Ganymede", radius_km: 2634.1, discovered: new Date("1610-01-07") },
]);
await jupyter.sql`select year(date) as year, round(avg(temp_max), 1) as avg_high from weather group by year order by year`;| year integer | avg_high number |
|---|---|
| 2012 | 15.3 |
| 2013 | 16.1 |
| 2014 | 17 |
| 2015 | 17.4 |
The database opens on the first query, which loads DuckDB: the @duckdb/node-api package on Node, Deno and Bun (installed on first use like any npm: import), and DuckDB's WebAssembly build from a CDN in the browser target and the Ganymede apps, unless the page serves its own copies (SQL_MODULES). It lasts until the kernel restarts or await jupyter.sql.close(). Interrupting the kernel stops a running query. await jupyter.sql.connection() returns DuckDB's own connection for anything the tag doesn't cover. workerd and celld have no DuckDB.
Charts
jupyter.chart draws a chart in the kernel and shows it as one SVG, with its title and legend inside, plus a text summary for readers that can't see it (an agent, jupyter console, a notebook converted to text). The SVG shows the same in the Ganymede apps, JupyterLab, VS Code and a published page, with no chart library in the frontend. Text and axes are drawn in currentColor on no background: the Ganymede apps give them the notebook's text color, light or dark; a frontend that shows SVG as a plain image, such as JupyterLab, draws them black.
Pass a Vega-Lite spec:
jupyter.chart({
title: "Galilean moons",
data: { values: [
{ moon: "Io", radius_km: 1821.6 },
{ moon: "Europa", radius_km: 1560.8 },
{ moon: "Ganymede", radius_km: 2634.1 },
{ moon: "Callisto", radius_km: 2410.3 },
] },
mark: "bar",
encoding: {
x: { field: "moon", sort: "-y" },
y: { field: "radius_km", type: "quantitative" },
},
});A Vega spec, or a vega-lite-api chart, works the same. A spec's own config wins over the defaults. jupyter.chart(spec, { spec: true }) also keeps the spec, under application/vnd.vegalite.v5+json, for a frontend that draws Vega itself.
Or pass the Observable Plot module and the options you would give Plot.plot:
import * as Plot from "npm:@observablehq/plot@0.6";
const moons = [
{ moon: "Io", radius_km: 1821.6, group: "inner" },
{ moon: "Europa", radius_km: 1560.8, group: "inner" },
{ moon: "Ganymede", radius_km: 2634.1, group: "outer" },
{ moon: "Callisto", radius_km: 2410.3, group: "outer" },
];
jupyter.chart(Plot, {
title: "Galilean moons",
color: { legend: true },
marks: [Plot.barY(moons, { x: "moon", y: "radius_km", fill: "group" }), Plot.ruleY([0])],
});Plot draws a title, caption and categorical legend as HTML beside its SVG, which a reader that shows only images drops. jupyter.chart draws title, subtitle, caption and the color legend into the SVG instead: color: { legend: true } draws swatches for categories and a ramp for a continuous scale, and legend: "swatches" or "ramp" picks the form. Legends of other scales (symbol, r, opacity) are left out, with a warning. An SVG element, such as Plot.plot(...) without those, also shows as it is.
vega and vega-lite (version 6), and linkedom for Plot where there is no DOM, load through the cell's import on first use, so a notebook that draws no chart loads none of them. A chart past 2 MB of SVG logs a warning, as every point is in the notebook: aggregate or sample the data first, for example with jupyter.sql. workerd and celld bundle a cell's imports before it runs, so jupyter.chart isn't available there.
Asking and interrupting
Cells that wait on the person running them, and stop cleanly when interrupted. For comms and interactive widgets, see Widgets and comms.
Asking for input: prompt and confirm
prompt() and confirm() work as in a browser, but ask in the notebook: the frontend shows an input box under the cell, and the cell waits for the answer.
const name = prompt("What's your name?", "world");
const shout = confirm("Shout the greeting?");
const greeting = `Hello, ${name}!`;
shout ? greeting.toUpperCase() : greeting;prompt(message, defaultValue)returns the typed text, ordefaultValuewhen the answer is empty. The default is shown in the question asWhat's your name? [world].confirm(message)adds[y/N]and returnstrueonly foryorY.prompt(message, "", { password: true })hides what is typed, for secrets you don't want saved in the notebook:tsconst apiKey = prompt("API key", "", { password: true });
When nothing can answer, prompt returns null and confirm returns false. That happens when the frontend has no input channel (some headless runners, such as nbconvert --execute), and always on workerd and celld. Code meant to run unattended should handle null.
Stopping on interrupt: jupyter.signal
An interrupt ends the running cell, but it can't settle a promise the cell is waiting on. The kernel stops waiting for the cell; the cell's own await stays pending. When only your code can end the wait, such as a reply over a comm, pass it jupyter.signal so it can give up and clean up:
const ask = jupyter.comm.open("my.app", { question: "ready?" });
const signal = jupyter.signal;
const answer = await new Promise((resolve, reject) => {
ask.onMsg((m) => resolve(m.data));
signal.addEventListener("abort", () => {
ask.close();
reject(signal.reason);
}, { once: true });
});jupyter.signal is an ordinary AbortSignal, so APIs that take one accept it as is: fetch(url, { signal: jupyter.signal }), addEventListener(type, listener, { signal: jupyter.signal }), or setTimeout from node:timers/promises.
- Each cell gets its own signal, and an interrupt aborts only the running cell's, including a cell waiting in
prompt(). A timer or request that an earlier, finished cell started with its signal keeps going. Thereasonis aDOMExceptionnamedAbortError, with the messageExecution interrupted. - A comm handler that starts while no cell runs gets its own signal too, which an interrupt during it aborts. A handler that runs during a cell (on a kernel subshell) shares the cell's.
- Read it once, when the work starts, and keep it. The kernel can't tell which cell a timer callback or a later
awaitbelongs to, so readingjupyter.signalthere gets the signal of whatever started last. - It behaves the same on every runtime. It matters most on Bun, workerd, celld and the browser target, where an interrupted cell's pending work keeps running.
Notebooks as programs
A notebook run with parameters, publishing results by name, and reading or running other notebooks. Not in Deno.
Parameters and named results
A notebook can run as a program: parameters in, named results out. Whoever starts the kernel passes the parameters, and reads the results from the run's outputs by name, without parsing them. With Ganymede:
ganymede execute fremont.ipynb -p counter="2nd Ave" -p days=7 --resultsjupyter.params holds the parameters, a frozen object. Take defaults with destructuring, so the notebook still runs on its own:
const { counter = "Fremont", days = 30 } = jupyter.params as { counter?: string; days?: number };jupyter.result(name, value) publishes a value under a name:
jupyter.result("weekday_drop", -0.19);weekday_drop = -0.19
- Parameters arrive as a JSON object in the kernel's
GANYMEDE_PARAMSenvironment variable, so any launcher can pass them, and any kernel can read them (json.loads(os.environ.get("GANYMEDE_PARAMS", "{}"))in Python). A value that isn't a JSON object makes readingjupyter.paramsthrow aTypeError. The browser target takes them from itsparamsoption instead. - A result is a
display_dataoutput with the MIME typeapplication/vnd.ganymede.result+json, holding{ "name": ..., "value": ... }, and atext/plainlinename = valuethat frontends show. The value must be JSON: it is stored asJSON.stringifywrites it, so aDatebecomes a string, and a function orBigIntthrows. - When a name is published more than once, readers take the last output, as Python's scrapbook does. Ganymede also reads scrapbook's own outputs.
Other notebooks: jupyter.host()
Under a Ganymede server, a cell can read and search the other notebooks under the server's root, through the server's host API. jupyter.host() resolves to the server, or to null when there is none, as under plain Jupyter:
const host = await jupyter.host();
if (host) {
host.notebook; // "journal/2026-11-11-quakes.ipynb": this notebook
const { hits } = await host.notebooks.search({ query: "weekday drop", dir: "journal" });
const { notebook } = await host.notebooks.read({ path: hits[0].path }); // nbformat JSON
}- The kernel holds no token. The server opens a comm to the kernel (target
ganymede.host.v1) when it starts, and answers each call on a kernel subshell, so a cell that awaits a call gets its reply. - What a notebook may read is set on the server, in its config's
[host]table; a notebook always reads itself.host.methodslists the methods this notebook may call, andhost.has(method)checks one. A call outside what is allowed rejects with aHostErrorwhosecodeisdenied. Branch onerr.code:HostErrorisn't a global, soinstanceofisn't available in a cell. - Every call takes
{ signal }, by defaultjupyter.signal, so an interrupt cancels it (codecancelled). Other codes areunavailable(no such method on this server),failed,timeoutanddisconnected(the comm closed, such as on a server restart). - With no server, the first
jupyter.host()waits up to itstimeout(1 s by default) and resolvesnull; later calls answernullat once. An interrupt ends the wait. - Ganymede 0.8.0 or later answers every call its grant allows:
notebooks.list,read,searchandresults;notebooks.run, which runs a notebook with parameters in a fresh kernel and returns its named results, when the server has granted this notebook that one; andself.add,editanddelete, which change this notebook's own cells. An older server answersunavailablefor the ones it lacks. Notebooks as programs and Ganymede's host API have the grants. - Other notebooks' outputs are data someone else wrote: don't run code found in them.
Deno and other runtimes
Notebooks written for Deno
Notebooks written for deno jupyter use Deno.jupyter rather than jupyter. Both names refer to the same object where Deno exists:
| Kernel | jupyter | Deno.jupyter |
|---|---|---|
cdp-deno | yes | yes |
cdp-node-deno | yes | yes, through the Deno compatibility shim |
cdp-node | yes | no (Deno is undefined) |
cdp-bun, cdp-workerd, cdp-celld | yes | no |
On a Deno target, Deno's own Deno.jupyter throws outside deno jupyter, so the kernel wraps the Deno namespace: Deno.jupyter returns jupyter, and everything else is Deno's.
To run an existing Deno notebook on Node, install the cdp-node-deno kernel (cdp-kernel install --runtime node --deno-compat). It adds a partial Deno namespace (runtime/deno-compat.mjs) with these members:
| Area | Members |
|---|---|
| Notebook | jupyter |
| Runtime info | version, build, pid, args, noColor, execPath(), inspect() |
| Process | cwd(), chdir(), exit(), env (get, set, delete, has, toObject) |
| Reading files | readTextFile, readFile, readDir, stat, lstat, realPath |
| Writing files | writeTextFile, writeFile, mkdir, remove, rename, makeTempDir, makeTempFile |
| Output | stdout.write, stderr.write |
| Errors | errors.NotFound, AlreadyExists, PermissionDenied, IsADirectory, NotADirectory |
Each file function has its …Sync form too, except makeTempFile, and stdout/stderr have writeSync. Deno.version.deno is "0.0.0-cdp-kernel", so code can tell the shim from real Deno.
Everything else, such as Deno.serve, Deno.Command, Deno.open, Deno.openKv, Deno.permissions, Deno.stdin and Deno.test, is undefined: calling it fails with "is not a function". The shim is a separate kernel rather than the default because libraries detect Deno with typeof Deno, and would take Deno code paths that call APIs the shim doesn't cover.
New notebooks should use jupyter, which works on every kernel.
Version and runtime
jupyter.version is the version of cdp-kernel running the cell, as cdp-kernel version prints it. jupyter.runtime is a frozen { name, version } for the target the cell runs on, so a notebook that has to behave differently on one can check:
const { name, version } = jupyter.runtime; // "node", "22.12.0"
`cdp-kernel ${jupyter.version} on ${name} ${version}`;'cdp-kernel 0.17.0 on node 22.23.5'name is "node", "deno", "bun", "workerd", "celld" or "browser". version is the runtime's own version on Node, Deno and Bun; workerd, celld and the browser target can't tell it from inside, so it is "" there. Both are read-only.
Differences by runtime
Everything on this page works on every runtime, except:
| Node, Deno | Bun | workerd, celld | |
|---|---|---|---|
jupyter.image(path) | yes | yes | no file system: pass bytes |
prompt, confirm | yes | yes | return null / false |
Deno.jupyter | Deno, or Node with --deno-compat | no | no |
| Native-add-on packages (Polars, canvas) | yes | yes | no |
jupyter.sql | yes | yes | no |
jupyter.chart | yes | yes | no |
What counts as a cell's result also differs slightly on Bun, workerd and celld: only an expression statement at the very end of the cell is a result. Choosing a runtime compares the runtimes, and Known gaps has the full list of differences.