A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
Add `NotebookClient` to `@marimo-team/client` (#11389)
Trevor Manz81b63098b0b6
diff --git a/packages/client/README.md b/packages/client/README.mdindex e35bad1269..13cc91e9a5 100644--- a/packages/client/README.md+++ b/packages/client/README.md@@ -1,27 +1,52 @@# @marimo-team/client-A typed client for the [marimo host protocol](../../protocols/host/README.md).+A typed client for notebooks served by a marimo host. Hosts expose each+notebook through the [host protocol](../../protocols/host/README.md), an HTTP+API with its own event stream. `NotebookClient` sends the protocol's requests+for one notebook, addressed by the notebook's URL. Request bodies are+validated before they are sent, and the host's answer comes back as data or a+problem.-- `@marimo-team/client/protocol` has the types and zod 4 schemas generated- from `protocols/host/openapi.yaml`. Clients use the types. Use the schemas- to validate protocol data yourself, for example in a host or a- conformance test.+```ts+import { NotebookClient } from "@marimo-team/client";++const notebook = new NotebookClient(+ "http://127.0.0.1:2718/api/marimo/v1/notebooks/n1",+ { token: "your-token" },+);++const result = await notebook.edit([+ { kind: "delete_cell", id: "c3", base_etag: "*" },+]);+if (!result.ok) {+ console.error(result.problem.type);+}+```++## Entry points++- `@marimo-team/client` exports `NotebookClient`.+- `@marimo-team/client/protocol` has the protocol's types and zod 4 schemas,+ generated from `protocols/host/openapi.yaml`. Use the schemas to validate+ protocol data yourself, for example in a host or a conformance test.- `@marimo-team/client/reducer` composes resources into a pure reducer over a- notebook stream. It handles `ready`, `reset`, and the notebook's identity, so- each resource handles only the events of its own kinds.+ notebook stream. It handles `ready`, `reset`, and the notebook's identity,+ so each resource handles the events of its own kinds.++## DevelopmentThe package is consumed from `dist`. Build it once, or keep it built while-you work:+you work.```shpnpm --dir packages/client buildpnpm --dir packages/client build --watch```-`src/operations.ts` is generated from the same spec. It describes each-operation for the client to call and is not exported.+`src/operations.ts` is generated from the same spec as the schemas. It+describes each operation for the client to call and is not exported.-Regenerate and check the generated files:+Regenerate and check the generated files.```shpnpm --dir packages/client codegendiff --git a/packages/client/package.json b/packages/client/package.jsonindex c600bd3177..4208077456 100644--- a/packages/client/package.json+++ b/packages/client/package.json@@ -7,6 +7,7 @@"type": "module","license": "Apache-2.0","exports": {+ ".": "./dist/index.js","./protocol": "./dist/protocol.js","./reducer": "./dist/reducer.js"},diff --git a/packages/client/src/__tests__/notebook-client.test.ts b/packages/client/src/__tests__/notebook-client.test.tsnew file mode 100644index 0000000000..6d652f3d57--- /dev/null+++ b/packages/client/src/__tests__/notebook-client.test.ts@@ -0,0 +1,209 @@+/* Copyright 2026 Marimo. All rights reserved. */++import NodeFs from "node:fs";+import NodeUrl from "node:url";+import { afterEach, describe, expect, expectTypeOf, it, vi } from "vitest";+import { z } from "zod";+import { NotebookClient } from "../notebook/client.ts";+import type { OperationId } from "../operations.ts";+import type { OperationsBelow } from "../request.ts";+import type * as Protocol from "../protocol.ts";++const fixtures = new NodeUrl.URL(+ "../../../../protocols/host/fixtures/",+ import.meta.url,+);++function readFixture(name: string): unknown {+ return JSON.parse(+ NodeFs.readFileSync(new NodeUrl.URL(name, fixtures), "utf8"),+ );+}++function json(status: number, body: unknown, type = "application/json") {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": type },+ });+}++/** A notebook client whose requests are answered by `answer`. */+function connect(+ answer: (request: Request) => Response,+ url = "http://127.0.0.1:2718/api/marimo/v1/notebooks/n1",+) {+ const fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) =>+ answer(new Request(input, init)),+ );+ const notebook = new NotebookClient(url, {+ token: "secret",+ headers: { "X-Example": "1" },+ fetch,+ });+ const sent = () => new Request(...fetch.mock.calls[0]);+ return { notebook, fetch, sent };+}++type NotebookOperationId = OperationsBelow<"/notebooks/{notebook_id}">;++afterEach(() => {+ vi.unstubAllGlobals();+});++describe("NotebookClient", () => {+ it("sends an edit below the notebook's URL and returns the validated response", async () => {+ const response = readFixture("edit-response.json");+ const { notebook, sent } = connect(() => json(200, response));+ const { changes } = readFixture("edit.json") as Protocol.EditRequest;++ const result = await notebook.edit(changes);++ expect(result).toEqual({ ok: true, status: 200, data: response });+ const request = sent();+ expect(request.method).toBe("POST");+ expect(request.url).toBe(+ "http://127.0.0.1:2718/api/marimo/v1/notebooks/n1/edits",+ );+ expect(request.headers.get("Authorization")).toBe("Bearer secret");+ expect(request.headers.get("X-Example")).toBe("1");+ expect(request.headers.get("Idempotency-Key")).toMatch(/^[\da-f-]{36}$/);+ expect(await request.json()).toEqual({ changes });+ });++ it("keeps the notebook URL's query string and ignores a trailing slash", async () => {+ const problem = readFixture("problems/not-found.json");+ const { notebook, fetch } = connect(+ () => json(404, problem, "application/problem+json"),+ "http://localhost/api/marimo/v1/notebooks/n1/?session_id=s1",+ );+ await notebook.delete();+ await notebook.interrupt("r/1");+ expect(fetch.mock.calls.map(([url]) => String(url))).toEqual([+ "http://localhost/api/marimo/v1/notebooks/n1?session_id=s1",+ "http://localhost/api/marimo/v1/notebooks/n1/runtime/runs/r%2F1?session_id=s1",+ ]);+ });++ it("accepts problems and reads their media type without regard to case", async () => {+ const problem = readFixture("problems/not-found.json");+ const { notebook, sent } = connect(() =>+ json(404, problem, "Application/Problem+JSON; charset=utf-8"),+ );+ expect(await notebook.open()).toEqual({ ok: false, status: 404, problem });+ expect(sent().headers.get("Accept")).toBe(+ "application/json, application/problem+json",+ );+ });++ it.each(["", ".", ".."])(+ "rejects the run id %j before sending",+ async (runId) => {+ const { notebook, fetch } = connect(() => json(202, {}));+ await expect(notebook.interrupt(runId)).rejects.toThrow("valid run_id");+ expect(fetch).not.toHaveBeenCalled();+ },+ );++ it("keeps its URL when a caller changes the copy it reads", async () => {+ const { notebook, fetch } = connect(+ () => new Response(null, { status: 204 }),+ );+ notebook.url.host = "attacker.example";+ await notebook.delete();+ expect(String(fetch.mock.calls[0][0])).toBe(+ "http://127.0.0.1:2718/api/marimo/v1/notebooks/n1",+ );+ });++ it("makes idempotency keys outside secure contexts", async () => {+ const { getRandomValues } = globalThis.crypto;+ vi.stubGlobal("crypto", {+ getRandomValues: getRandomValues.bind(globalThis.crypto),+ });+ const { notebook, sent } = connect(() => json(202, {}));+ await notebook.stop().catch(() => undefined);+ expect(sent().headers.get("Idempotency-Key")).toMatch(+ /^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/,+ );+ });++ it("returns problems as values", async () => {+ const problem = readFixture("problems/edit-conflict.json");+ const { notebook } = connect(() =>+ json(409, problem, "application/problem+json"),+ );+ expect(await notebook.edit([])).toEqual({+ ok: false,+ status: 409,+ problem,+ });+ });++ it("sends preconditions, decisions, and the caller's idempotency key", async () => {+ const { notebook, sent } = connect(() =>+ json(200, readFixture("edit-response.json")),+ );+ await notebook.save({+ ifMatch: "etag-1",+ decisions: { environment: "keep" },+ idempotencyKey: "retry-1",+ });+ const request = sent();+ expect(request.url).toBe(+ "http://127.0.0.1:2718/api/marimo/v1/notebooks/n1/save",+ );+ expect(request.headers.get("If-Match")).toBe("etag-1");+ expect(request.headers.get("Idempotency-Key")).toBe("retry-1");+ expect(await request.json()).toEqual({+ decisions: { environment: "keep" },+ });+ });++ it("accepts empty responses", async () => {+ const { notebook } = connect(() => new Response(null, { status: 204 }));+ expect(await notebook.delete()).toEqual({+ ok: true,+ status: 204,+ data: undefined,+ });+ });++ it("validates requests before sending them", async () => {+ const { notebook, fetch } = connect(() => json(202, {}));+ await expect(notebook.run({ cells: [] })).rejects.toBeInstanceOf(+ z.ZodError,+ );+ expect(fetch).not.toHaveBeenCalled();+ });++ it("throws on answers the protocol does not describe", async () => {+ const { notebook } = connect(() => json(200, { unexpected: true }));+ await expect(notebook.open()).rejects.toBeInstanceOf(z.ZodError);+ const html = connect(() => new Response("<html>", { status: 502 }));+ await expect(html.notebook.open()).rejects.toThrow(+ "Unexpected 502 response to notebook.open",+ );+ });++ it("has a method for each request below a notebook", () => {+ const methods = {+ "notebook.update": "update",+ "notebook.delete": "delete",+ "notebook.open": "open",+ "notebook.edit": "edit",+ "notebook.save": "save",+ "runtime.start": "start",+ "runtime.stop": "stop",+ "runtime.restart": "restart",+ "runtime.run": "run",+ "runtime.interrupt": "interrupt",+ } as const satisfies Record<NotebookOperationId, keyof NotebookClient>;+ expectTypeOf<Exclude<keyof NotebookClient, "url">>().toEqualTypeOf<+ (typeof methods)[NotebookOperationId]+ >();+ // Streams and host-level operations come with NotebookEvents and Client.+ expectTypeOf<Exclude<OperationId, NotebookOperationId>>().toEqualTypeOf<+ "events" | "notebook.create" | "notebook.events"+ >();+ });+});diff --git a/packages/client/src/index.ts b/packages/client/src/index.tsnew file mode 100644index 0000000000..5ad5f0acb7--- /dev/null+++ b/packages/client/src/index.ts@@ -0,0 +1,4 @@+/* Copyright 2026 Marimo. All rights reserved. */++export { NotebookClient, type NotebookClientInit } from "./notebook/client.ts";+export type { Result } from "./request.ts";diff --git a/packages/client/src/notebook/client.ts b/packages/client/src/notebook/client.tsnew file mode 100644index 0000000000..163729b3fb--- /dev/null+++ b/packages/client/src/notebook/client.ts@@ -0,0 +1,148 @@+/* Copyright 2026 Marimo. All rights reserved. */++import type * as Protocol from "../protocol.ts";+import {+ type Connection,+ type MutationOptions,+ type OperationsBelow,+ request,+ type Result,+ type Target,+} from "../request.ts";++/** How a `NotebookClient` reaches and authenticates with its host. */+export type NotebookClientInit = Connection;++/** Options for a request the host may need decisions for. */+interface DecisionOptions extends MutationOptions {+ /** Answers to the decisions a `decision-required` problem asked for. */+ readonly decisions?: Readonly<Record<string, string>>;+}++/** Options for saving a notebook. */+interface SaveOptions extends DecisionOptions {+ /** The document etag the client last read. A different etag is a conflict. */+ readonly ifMatch?: string;+}++type Scope = "/notebooks/{notebook_id}";++/**+ * A client for one notebook.+ *+ * Requests go to URLs below the notebook's URL and keep its query string.+ */+export class NotebookClient {+ readonly #url: URL;+ readonly #target: Target<Scope>;++ public constructor(url: string | URL, init: NotebookClientInit = {}) {+ this.#url = new URL(url);+ this.#target = {+ url: this.#url,+ prefix: "/notebooks/{notebook_id}",+ connection: init,+ };+ }++ /**+ * The notebook's URL, such as `…/api/marimo/v1/notebooks/n1`.+ *+ * Each read returns a copy, so changing it does not redirect requests.+ */+ public get url(): URL {+ return new URL(this.#url);+ }++ /** Rename or move the notebook. */+ public update(+ changes: Protocol.UpdateNotebookRequest,+ options?: MutationOptions,+ ): Promise<Result<Protocol.NotebookOutput>> {+ return this.#send("notebook.update", { body: changes, options });+ }++ /** Delete the notebook. */+ public delete(options?: MutationOptions): Promise<Result<undefined>> {+ return this.#send("notebook.delete", { options });+ }++ /** Ask the host for a URL that opens the notebook for people. */+ public open(+ options?: MutationOptions,+ ): Promise<Result<Protocol.OpenNotebookResponseOutput>> {+ return this.#send("notebook.open", { options });+ }++ /** Apply changes to the document as one unit. */+ public edit(+ changes: readonly Protocol.Change[],+ options?: MutationOptions,+ ): Promise<Result<Protocol.EditResponseOutput>> {+ return this.#send("notebook.edit", {+ body: { changes: [...changes] },+ options,+ });+ }++ /** Write the document to the notebook's store. */+ public save(+ options?: SaveOptions,+ ): Promise<Result<Protocol.EditResponseOutput>> {+ return this.#send("notebook.save", {+ body: { decisions: options?.decisions },+ headers: { "If-Match": options?.ifMatch },+ options,+ });+ }++ /** Start a runtime for the notebook. */+ public start(+ options?: DecisionOptions,+ ): Promise<Result<Protocol.RuntimeOutput>> {+ return this.#send("runtime.start", {+ body: { decisions: options?.decisions },+ options,+ });+ }++ /** Stop the notebook's runtime. */+ public stop(+ options?: MutationOptions,+ ): Promise<Result<Protocol.RuntimeOutput>> {+ return this.#send("runtime.stop", { options });+ }++ /** Restart the notebook's runtime. */+ public restart(+ options?: MutationOptions,+ ): Promise<Result<Protocol.RuntimeOutput>> {+ return this.#send("runtime.restart", { options });+ }++ /** Run cells or scratch code in the notebook's runtime. */+ public run(+ request: Protocol.RunRequest,+ options?: MutationOptions,+ ): Promise<Result<Protocol.RunOutput>> {+ return this.#send("runtime.run", { body: request, options });+ }++ /** Interrupt a run. */+ public interrupt(+ runId: Protocol.RunId,+ options?: MutationOptions,+ ): Promise<Result<Protocol.RunOutput>> {+ return this.#send("runtime.interrupt", {+ params: { run_id: runId },+ options,+ });+ }++ #send<Id extends OperationsBelow<Scope>>(+ id: Id,+ call: Parameters<typeof request<Scope, Id>>[2],+ ) {+ return request(this.#target, id, call);+ }+}diff --git a/packages/client/src/request.ts b/packages/client/src/request.tsnew file mode 100644index 0000000000..14b35a8eaf--- /dev/null+++ b/packages/client/src/request.ts@@ -0,0 +1,221 @@+/* Copyright 2026 Marimo. All rights reserved. */++import type * as z from "zod";+import { type OperationId, operations } from "./operations.ts";+import * as Protocol from "./protocol.ts";++/** How requests reach and authenticate with a host. */+export interface Connection {+ /** Sent as `Authorization: Bearer <token>`. */+ readonly token?: string;+ /** Added to every request. */+ readonly headers?: HeadersInit;+ /** Defaults to `globalThis.fetch`. */+ readonly fetch?: typeof globalThis.fetch;+}++/**+ * The outcome of a request the host answered.+ *+ * A request throws when the host cannot be reached or when its answer is not+ * one the protocol describes.+ */+export type Result<T> =+ | { readonly ok: true; readonly status: number; readonly data: T }+ | {+ readonly ok: false;+ readonly status: number;+ readonly problem: Protocol.ProblemOutput;+ };++/** Options for a request that changes state. */+export interface MutationOptions {+ readonly signal?: AbortSignal;+ /**+ * The key the host uses to answer a repeated request once.+ *+ * Defaults to a new random key. Pass the same key to retry a request.+ */+ readonly idempotencyKey?: string;+}++/** The operations a client calls as requests rather than streams. */+type RequestOperationId = {+ [Id in OperationId]: (typeof operations)[Id]["responses"] extends {+ 200: "text/event-stream";+ }+ ? never+ : Id;+}[OperationId];++/** The request operations whose paths start with `prefix`. */+export type OperationsBelow<Prefix extends string> = {+ [Id in RequestOperationId]: (typeof operations)[Id]["path"] extends+ | Prefix+ | `${Prefix}/${string}`+ ? Id+ : never;+}[RequestOperationId];++/**+ * Where a client's requests go.+ *+ * `url` stands for `prefix`, so each operation's path below `prefix` resolves+ * below `url` and keeps its query string.+ */+export interface Target<Prefix extends string> {+ readonly url: URL;+ readonly prefix: Prefix;+ readonly connection: Connection;+}++/** What a request reads from each entry of the operations table. */+interface Operation {+ readonly method: string;+ readonly path: string;+ readonly headers: Readonly<Record<string, boolean>>;+ readonly body: z.ZodType | null;+ readonly responses: Readonly<+ Record<number, z.ZodType | null | "text/event-stream">+ >;+}++const table: Readonly<Record<OperationId, Operation>> = operations;++type Entry<Id extends RequestOperationId> = (typeof operations)[Id];++/** The data of each success response an operation describes. */+type Data<Id extends RequestOperationId> = {+ [+ Status in keyof Entry<Id>["responses"]+ ]: Entry<Id>["responses"][Status] extends z.ZodType+ ? z.output<Entry<Id>["responses"][Status]>+ : undefined;+}[keyof Entry<Id>["responses"]];++/** What a request sends besides its operation. */+interface Call<Id extends RequestOperationId> {+ /** Values for the placeholders in the path below the target's prefix. */+ readonly params?: Readonly<Record<string, string>>;+ readonly body?: Entry<Id>["body"] extends z.ZodType+ ? z.input<Entry<Id>["body"]>+ : undefined;+ readonly headers?: Readonly<Record<string, string | undefined>>;+ readonly options?: MutationOptions;+}++/**+ * A random key for a request that changes state.+ *+ * `crypto.randomUUID` exists only in secure contexts, such as pages served+ * over HTTPS or from localhost. A host on a local network is often neither.+ */+function idempotencyKey(): string {+ if (typeof globalThis.crypto.randomUUID === "function") {+ return globalThis.crypto.randomUUID();+ }+ const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));+ bytes[6] = (bytes[6] & 0x0f) | 0x40;+ bytes[8] = (bytes[8] & 0x3f) | 0x80;+ const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0"));+ return [+ hex.slice(0, 4),+ hex.slice(4, 6),+ hex.slice(6, 8),+ hex.slice(8, 10),+ hex.slice(10),+ ]+ .map((group) => group.join(""))+ .join("-");+}++/** Whether a `Content-Type` names `type`, ignoring case and parameters. */+function isType(contentType: string | null, type: string): boolean {+ return contentType?.split(";", 1)[0].trim().toLowerCase() === type;+}++/** The URL an operation's path resolves to below the target. */+function resolve<Prefix extends string>(+ target: Target<Prefix>,+ path: string,+ params: Readonly<Record<string, string>>,+): URL {+ const suffix = path+ .slice(target.prefix.length)+ .replace(/\{(\w+)\}/g, (_, name: string) => {+ const value = params[name];+ // An empty or dot segment would name a different resource, and+ // percent-encoding does not stop URLs from resolving dot segments.+ if (+ value === undefined ||+ value === "" ||+ value === "." ||+ value === ".."+ ) {+ throw new Error(`${path} needs a valid ${name}`);+ }+ return encodeURIComponent(value);+ });+ const url = new URL(target.url);+ url.pathname = target.url.pathname.replace(/\/$/, "") + suffix;+ return url;+}++/**+ * Send one request and decode the host's answer.+ *+ * The body is validated before it is sent, and the response is validated+ * against the schema the protocol gives its status, so the data has the type+ * the operation describes.+ */+export async function request<+ Prefix extends string,+ Id extends OperationsBelow<Prefix>,+>(+ target: Target<Prefix>,+ id: Id,+ { params = {}, body, headers = {}, options = {} }: Call<Id>,+): Promise<Result<Data<Id>>> {+ const operation = table[id];+ const { connection } = target;+ const sent = new Headers(connection.headers);+ sent.set("Accept", "application/json, application/problem+json");+ if (connection.token !== undefined) {+ sent.set("Authorization", `Bearer ${connection.token}`);+ }+ if ("Idempotency-Key" in operation.headers) {+ sent.set("Idempotency-Key", options.idempotencyKey ?? idempotencyKey());+ }+ for (const [name, value] of Object.entries(headers)) {+ if (value !== undefined) {+ sent.set(name, value);+ }+ }+ let payload: string | undefined;+ if (operation.body !== null) {+ sent.set("Content-Type", "application/json");+ payload = JSON.stringify(operation.body.parse(body));+ }+ const fetch = connection.fetch ?? globalThis.fetch;+ const response = await fetch(resolve(target, operation.path, params), {+ method: operation.method,+ headers: sent,+ body: payload,+ signal: options.signal,+ });+ const status = response.status;+ const schema = operation.responses[status];+ if (schema === null) {+ return { ok: true, status, data: undefined as Data<Id> };+ }+ if (schema !== undefined && schema !== "text/event-stream") {+ const data = schema.parse(await response.json()) as Data<Id>;+ return { ok: true, status, data };+ }+ const type = response.headers.get("Content-Type");+ if (!response.ok && isType(type, "application/problem+json")) {+ const problem = Protocol.Problem.parse(await response.json());+ return { ok: false, status, problem };+ }+ throw new Error(`Unexpected ${status} response to ${id}`);+}