@a10k/iridium-dev-server 0.0.0-stage → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/Readme.md +232 -0
- package/index.js +15 -0
- package/lib/config.js +28 -0
- package/lib/define-module.js +129 -0
- package/lib/live.js +87 -0
- package/lib/mcp-stdio.js +78 -0
- package/lib/mcp.js +312 -0
- package/lib/notebooks.js +137 -0
- package/lib/server.js +295 -0
- package/lib/viewer.js +210 -0
- package/package.json +44 -4
- package/skill/SKILL.md +92 -0
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 Wishyoulization
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/Readme.md
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
# Iridium Dev Server
|
|
2
|
+
|
|
3
|
+
Local dev server for working with Observable notebooks: edit them in [Iridium](https://github.com/wishyoulization/iridium), save them as files, and compile them to ES modules you can embed in any app.
|
|
4
|
+
|
|
5
|
+
> Published on npm as `@a10k/iridium-dev-server` (previously `@wishyoulization/iridium-dev-server`).
|
|
6
|
+
|
|
7
|
+
Cells are compiled by Observable's own engine, [Notebook Kit](https://observablehq.com/notebook-kit/kit): classic Observable JavaScript (`viewof`, `mutable`, `import {x} from "@user/notebook"`, `require(…)`) and plain JavaScript cells (several statements, `const` declarations, `npm:` imports, `display(…)`), as in Observable Notebooks 2.0.
|
|
8
|
+
|
|
9
|
+
It also includes an [MCP](https://modelcontextprotocol.io) server and a skill, so AI assistants such as Claude can build notebooks with you, live, in the tab you're watching.
|
|
10
|
+
|
|
11
|
+
Requires Node.js 22 or later.
|
|
12
|
+
|
|
13
|
+
## Quick start
|
|
14
|
+
|
|
15
|
+
Start a server in any folder (notebooks are saved there as `<name>.html`):
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
mkdir my-notebooks && cd my-notebooks
|
|
19
|
+
npx @a10k/iridium-dev-server
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Open http://localhost:8080/ to edit the `index` notebook, or http://localhost:8080/my-notebook for any other (it's created on first save). Write a cell, run it with Shift+Enter, save with ⌘S / Ctrl+S.
|
|
23
|
+
|
|
24
|
+
Try these cells, one per cell:
|
|
25
|
+
|
|
26
|
+
```js
|
|
27
|
+
viewof n = Inputs.range([1, 100], { value: 20, step: 1, label: "Points" })
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
```js
|
|
31
|
+
points = d3.range(n).map((i) => ({ x: i, y: Math.sin(i / 3) }))
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
```js
|
|
35
|
+
Plot.lineY(points, { x: "x", y: "y" }).plot({ width })
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Drag the slider and the chart follows: cells re-run when the values they use change.
|
|
39
|
+
|
|
40
|
+
To build notebooks with Claude instead, see [Live collaboration and AI assistants](#live-collaboration-and-ai-assistants-mcp).
|
|
41
|
+
|
|
42
|
+
## Install
|
|
43
|
+
|
|
44
|
+
Run it with `npx` as above, or add it to a project:
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
npm i -D @a10k/iridium-dev-server
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
or install it globally to get the `iridium-dev-server` command everywhere:
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
npm i -g @a10k/iridium-dev-server
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Run the development server
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
npx @a10k/iridium-dev-server
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Open http://localhost:8080/ to edit the `index` notebook, or http://localhost:8080/my-notebook for any other. Running a cell (Shift+Enter) or saving (the save button or ⌘S) writes the notebook file and its compiled module.
|
|
63
|
+
|
|
64
|
+
## Notebook list API
|
|
65
|
+
|
|
66
|
+
`GET /api/notebooks?q=&page=1&per_page=25&sort=name|modified` returns the notebooks whose name or title contains `q` (any case), one page at a time:
|
|
67
|
+
|
|
68
|
+
```json
|
|
69
|
+
{ "q": "zdog", "sort": "name", "page": 1, "per_page": 25, "pages": 1, "total": 2,
|
|
70
|
+
"items": [{ "name": "cubrt-with-zdog", "title": "Cubrt with Zdog", "url": "/cubrt-with-zdog", "modified": "2026-11-21T…Z", "cells": 12, "size": 5480 }] }
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
`DELETE /api/notebooks/<name>` moves a notebook and its attachments folder to the Trash (macOS's, restorable with Put Back; elsewhere a `.trash` folder in the notebooks folder) and removes its compiled module.
|
|
74
|
+
|
|
75
|
+
`per_page` is at most 200, out-of-range pages are clamped, and the `index` notebook (the home page at `/`) isn't listed. A home page notebook can render it with a search input and pager: fetch the JSON in a cell and draw the cards with `htl.html`.
|
|
76
|
+
|
|
77
|
+
## Live collaboration and AI assistants (MCP)
|
|
78
|
+
|
|
79
|
+
Every tab showing a notebook connects to the server (a green dot in its favicon, like the macOS traffic light; grey when offline), so an AI assistant can work on the notebook in that tab while you watch.
|
|
80
|
+
|
|
81
|
+
The server includes an [MCP](https://modelcontextprotocol.io) server, so assistants such as Claude can build and edit notebooks with you: they add and edit cells in the tab you're watching, and read each cell's live output (value, rendered text, errors) to check their work. Tools: `create_notebook`, `open_notebook`, `list_notebooks`, `read_notebook`, `add_cell`, `add_cells`, `edit_cell`, `delete_cell`, `move_cell`, `run_cell`, `evaluate`, `screenshot_cells`, `save_notebook`.
|
|
82
|
+
|
|
83
|
+
`screenshot_cells` returns PNGs of cells as your tab shows them. The tab captures itself with Chrome's tab capture (`getDisplayMedia` on the current tab), scrolling each cell into view and cropping to it. The first time, the tab asks you to allow it: click **Allow tab capture**, then share the tab. Capture stays on until you stop sharing in Chrome's bar.
|
|
84
|
+
|
|
85
|
+
### Set up Claude Code
|
|
86
|
+
|
|
87
|
+
Once, from any folder:
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
claude mcp add --scope user iridium -- npx -y @a10k/iridium-dev-server mcp
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Then install the skill (it teaches Claude the workflow and how to write good cells):
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
npm i -g @a10k/iridium-dev-server
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
mkdir -p ~/.claude/skills && cp -r "$(npm root -g)/@a10k/iridium-dev-server/skill" ~/.claude/skills/iridium-notebooks
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
(If you installed it in a project instead, copy `node_modules/@a10k/iridium-dev-server/skill`.) Check the connection with `claude mcp list`, then start a new chat.
|
|
104
|
+
|
|
105
|
+
### Set up Claude Desktop and other MCP clients
|
|
106
|
+
|
|
107
|
+
Add the server to the client's MCP config (for Claude Desktop: Settings → Developer → Edit Config, `claude_desktop_config.json`), then restart it:
|
|
108
|
+
|
|
109
|
+
```json
|
|
110
|
+
{
|
|
111
|
+
"mcpServers": {
|
|
112
|
+
"iridium": {
|
|
113
|
+
"command": "npx",
|
|
114
|
+
"args": ["-y", "@a10k/iridium-dev-server", "mcp"]
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
The same `command`/`args` work in Cursor, VS Code and other clients that launch stdio MCP servers. In clients that take skills, add the `skill` folder as a skill; elsewhere, the MCP server's own instructions are enough to get started.
|
|
121
|
+
|
|
122
|
+
### Example prompts
|
|
123
|
+
|
|
124
|
+
Ask in a new chat:
|
|
125
|
+
|
|
126
|
+
- "Make an Iridium notebook exploring a random walk: a slider for the number of steps, a line chart, and summary stats."
|
|
127
|
+
- "Create an Iridium notebook that loads this CSV URL, shows it as a table, and charts the second column over time."
|
|
128
|
+
- "Open my `sales` notebook and add a monthly revenue chart under the data cell."
|
|
129
|
+
- "Take a screenshot of the chart cell and tighten its margins."
|
|
130
|
+
- "Open it in Google Chrome." / "Save the notebook."
|
|
131
|
+
|
|
132
|
+
The notebook opens in your browser and fills in as the assistant works; edit cells yourself at any time and it sees your changes.
|
|
133
|
+
|
|
134
|
+
### How it works
|
|
135
|
+
|
|
136
|
+
- `iridium-dev-server mcp` speaks MCP over stdio. It serves the current folder's notebooks if it has an `.iridiumrc`, otherwise `~/Documents/Iridium` (or `IRIDIUM_HOME`), created on first use with port 8090. If a dev server is already running there, it connects to it, so every chat reaches the same open tabs; otherwise it starts one.
|
|
137
|
+
- A running dev server also serves MCP over HTTP at `/mcp` (e.g. `claude mcp add --transport http iridium http://localhost:8080/mcp`).
|
|
138
|
+
- New notebooks open in your default browser, or in another one: assistants can pass `browser` (e.g. `"Google Chrome"`), and `IRIDIUM_BROWSER` sets it for every notebook. Set `IRIDIUM_OPEN_BROWSER=0` to disable opening (e.g. when the assistant shows them in its own browser).
|
|
139
|
+
- The assistant works on the notebook in your open tab, as you would: the server only relays its commands (add, edit, run or delete cells, read outputs, save) to the tab, and keeps no notebook state. Its edits are unsaved until you save, or ask it to save, which does what the tab's Save does. Assistants can address cells by the name they define, patch long cells with `edit_cell` `replace: [{old, new}]`, and list cells compactly with `read_notebook` `brief: true`.
|
|
140
|
+
- `skill/SKILL.md` teaches the assistant the workflow and how to write good cells; the MCP server also sends short instructions of its own.
|
|
141
|
+
- Cells run in your browser, so live outputs need a tab showing the notebook.
|
|
142
|
+
|
|
143
|
+
## Static build
|
|
144
|
+
|
|
145
|
+
`-build` (or `--build`) compiles every notebook to an ES module without starting the server:
|
|
146
|
+
|
|
147
|
+
```bash
|
|
148
|
+
npx @a10k/iridium-dev-server -build
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
## Notebook files
|
|
152
|
+
|
|
153
|
+
Notebooks are saved in Notebook Kit's HTML format (`<name>.html`), the open format Observable Desktop edits:
|
|
154
|
+
|
|
155
|
+
```html
|
|
156
|
+
<!doctype html>
|
|
157
|
+
<notebook theme="air">
|
|
158
|
+
<title>my-notebook</title>
|
|
159
|
+
<script id="1" type="application/vnd.observable.javascript" pinned="">
|
|
160
|
+
a = 21
|
|
161
|
+
</script>
|
|
162
|
+
<script id="2" type="module">
|
|
163
|
+
const doubled = a * 2;
|
|
164
|
+
display(doubled);
|
|
165
|
+
</script>
|
|
166
|
+
</notebook>
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
- Classic Observable JavaScript cells are stored as `application/vnd.observable.javascript`, plain JavaScript cells as `module`. Pinned cells (editor visible) have `pinned`.
|
|
170
|
+
- Markdown, HTML, TeX and Graphviz cells from Observable Desktop open as the equivalent `md`/`html`/`tex`/`dot` template and are saved back in their own mode. Other modes (SQL, Python, …) can't run in Iridium but are kept unchanged.
|
|
171
|
+
- **Legacy `.ojs` notebooks** are still read. The first save writes `<name>.html` next to it; from then on the `.html` file is used. The `.ojs` file is left untouched, so delete it once you're happy with the conversion.
|
|
172
|
+
|
|
173
|
+
## Embedding compiled notebooks
|
|
174
|
+
|
|
175
|
+
Each notebook compiles to `<name>.js` exporting the classic `define(runtime, observer)`, with the usual variable names (`viewof x`, `mutable x`), so existing embeds keep working:
|
|
176
|
+
|
|
177
|
+
```js
|
|
178
|
+
import { Runtime } from "https://cdn.jsdelivr.net/npm/@observablehq/runtime@6/+esm";
|
|
179
|
+
import { Library, FileAttachments } from "https://cdn.jsdelivr.net/npm/@observablehq/stdlib@5/+esm";
|
|
180
|
+
import { Inspector } from "https://cdn.jsdelivr.net/npm/@observablehq/inspector@5/+esm";
|
|
181
|
+
import define from "./my-notebook.js";
|
|
182
|
+
|
|
183
|
+
const runtime = new Runtime(new Library());
|
|
184
|
+
runtime.fileAttachments = FileAttachments; // runtime 6 no longer includes it; imported notebooks may need it
|
|
185
|
+
runtime.module(define, Inspector.into(document.body));
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
- Works with `@observablehq/runtime` 5.9+ (runtime 5 includes the standard library and `fileAttachments`, so `new Runtime()` is enough) and 6 as above.
|
|
189
|
+
- Every named cell is passed to `observer(name)`, so you can pick cells to render by name.
|
|
190
|
+
- Plain JavaScript cells: each `display(…)` call in a run goes to its own observer; top-level declarations are named variables.
|
|
191
|
+
- Built-ins specific to Notebook Kit (such as the sample datasets like `penguins`) aren't in `@observablehq/stdlib`; provide them yourself if an embedded notebook uses them.
|
|
192
|
+
|
|
193
|
+
## Configuration
|
|
194
|
+
|
|
195
|
+
Save an `.iridiumrc` file (JSON) in the project root, or an `"iridiumrc"` field in `package.json`:
|
|
196
|
+
|
|
197
|
+
```json
|
|
198
|
+
{
|
|
199
|
+
"notebooks": "./src",
|
|
200
|
+
"compiled": "./dist",
|
|
201
|
+
"static": "./public",
|
|
202
|
+
"port": 8080,
|
|
203
|
+
"host": "localhost",
|
|
204
|
+
"local_editor": true,
|
|
205
|
+
"head": "<style>body{font-family:'Trebuchet MS';}</style>"
|
|
206
|
+
}
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
| Option | Default | |
|
|
210
|
+
| --- | --- | --- |
|
|
211
|
+
| `notebooks` | `.` | Folder for notebook files (`.html`, legacy `.ojs`). |
|
|
212
|
+
| `compiled` | `.` | Folder for compiled modules (`.js`), served for embedding. |
|
|
213
|
+
| `static` | — | Extra folder of static assets to serve. |
|
|
214
|
+
| `port` | `8080` | |
|
|
215
|
+
| `host` | `localhost` | The server writes files, so it only listens locally. Use `0.0.0.0` to expose it on your network. |
|
|
216
|
+
| `local_editor` | `true` | Serve Iridium from the installed package (works offline). `false` loads it from jsDelivr at the same version. |
|
|
217
|
+
| `head` | `""` | Extra markup for the page `<head>` (fonts, scripts, styles). |
|
|
218
|
+
|
|
219
|
+
## Security
|
|
220
|
+
|
|
221
|
+
`/read`, `/save`, `/list`, `/api/notebooks`, `/mcp` and the live WebSocket (`/__live__/<name>`) only accept requests addressed to this machine (`localhost`) and, from a browser, from the server's own pages, so other websites can't read or change notebooks (CSRF, DNS rebinding). Notebook names are reduced to letters, digits and `-`, so files are only ever read or written inside the `notebooks` and `compiled` folders. Compiled modules and static files allow cross-origin `GET` for embedding.
|
|
222
|
+
|
|
223
|
+
## Scripts
|
|
224
|
+
|
|
225
|
+
Add to your project's `package.json` for convenience:
|
|
226
|
+
|
|
227
|
+
```json
|
|
228
|
+
"scripts": {
|
|
229
|
+
"start": "iridium-dev-server",
|
|
230
|
+
"build": "iridium-dev-server -build"
|
|
231
|
+
}
|
|
232
|
+
```
|
package/index.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// iridium-dev-server edit notebooks in Iridium (live, with MCP at /mcp)
|
|
3
|
+
// iridium-dev-server -build compile every notebook to a define() module
|
|
4
|
+
// iridium-dev-server mcp MCP over stdio, for assistants (see lib/mcp-stdio.js)
|
|
5
|
+
import { createRequire } from 'node:module';
|
|
6
|
+
import { loadConfig } from './lib/config.js';
|
|
7
|
+
import { compileAll, startServer } from './lib/server.js';
|
|
8
|
+
import { runStdio } from './lib/mcp-stdio.js';
|
|
9
|
+
|
|
10
|
+
const args = process.argv.slice(2);
|
|
11
|
+
const { version } = createRequire(import.meta.url)('./package.json');
|
|
12
|
+
|
|
13
|
+
if (args[0] === 'mcp') await runStdio({ version });
|
|
14
|
+
else if (args.some((arg) => arg === '-build' || arg === '--build')) compileAll(loadConfig());
|
|
15
|
+
else startServer(loadConfig());
|
package/lib/config.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// Reads the dev server's configuration from `.iridiumrc` (JSON) in the current
|
|
2
|
+
// directory, or an "iridiumrc" field in package.json.
|
|
3
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
4
|
+
|
|
5
|
+
const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));
|
|
6
|
+
|
|
7
|
+
const load = () => {
|
|
8
|
+
if (existsSync('.iridiumrc')) return readJson('.iridiumrc');
|
|
9
|
+
if (existsSync('package.json')) return readJson('package.json').iridiumrc ?? {};
|
|
10
|
+
return {};
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
// Paths in the config are relative to the current directory.
|
|
14
|
+
export const loadConfig = () => {
|
|
15
|
+
const config = load();
|
|
16
|
+
return {
|
|
17
|
+
notebooks: config.notebooks ?? '.', // where notebooks (.html, legacy .ojs) live
|
|
18
|
+
compiled: config.compiled ?? '.', // where compiled define() modules (.js) go
|
|
19
|
+
static: config.static, // optional extra folder of static assets
|
|
20
|
+
port: config.port ?? 8080,
|
|
21
|
+
host: config.host ?? 'localhost', // the server can write files: local only by default
|
|
22
|
+
localEditor: config.local_editor ?? true, // serve Iridium locally, or from a CDN
|
|
23
|
+
head: config.head ?? '', // extra markup for the page <head>
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export const hasConfig = () =>
|
|
28
|
+
existsSync('.iridiumrc') || (existsSync('package.json') && 'iridiumrc' in readJson('package.json'));
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// Compiles a notebook into an ES module with the classic Observable contract:
|
|
2
|
+
//
|
|
3
|
+
// import define from "./notebook.js";
|
|
4
|
+
// new Runtime(new Library()).module(define, Inspector.into(element));
|
|
5
|
+
//
|
|
6
|
+
// Cells are compiled by Notebook Kit (through Iridium's compileCell, the same
|
|
7
|
+
// compiler the editor uses); this file only turns each compiled cell into
|
|
8
|
+
// runtime variables, with the names classic modules use ("viewof x",
|
|
9
|
+
// "mutable x"), so embeds that observe or redefine cells by name keep working.
|
|
10
|
+
// Needs @observablehq/runtime 5.9+ (for `@variable`, used by notebook imports).
|
|
11
|
+
import { compileCell } from '@a10k/iridium/src/compile.js';
|
|
12
|
+
|
|
13
|
+
// Kit names special variables viewof$x / mutable$x; classic modules use spaces.
|
|
14
|
+
const classicName = (name) =>
|
|
15
|
+
name.replace(/^viewof\$/, 'viewof ').replace(/^mutable\$/, 'mutable ');
|
|
16
|
+
|
|
17
|
+
const str = JSON.stringify;
|
|
18
|
+
|
|
19
|
+
// Gists are served as text/plain, which browsers won't import() directly.
|
|
20
|
+
const GIST_IMPORT = /\bimport\(("https:\/\/gist\.githubusercontent\.com\/[^"]*")\)/g;
|
|
21
|
+
|
|
22
|
+
const HELPERS = `const importGist = (url) =>
|
|
23
|
+
fetch(url)
|
|
24
|
+
.then((response) => response.text())
|
|
25
|
+
.then((js) => import(URL.createObjectURL(new Blob([js], { type: "text/javascript" }))));
|
|
26
|
+
|
|
27
|
+
// display(value) and view(input) for plain JavaScript cells: the n-th display
|
|
28
|
+
// call of a run goes to the cell's n-th observer.
|
|
29
|
+
const cellDisplay = (observer) => {
|
|
30
|
+
const observers = [];
|
|
31
|
+
let index = 0;
|
|
32
|
+
const display = (value) => {
|
|
33
|
+
(observers[index++] ??= observer() ?? {}).fulfilled?.(value);
|
|
34
|
+
return value;
|
|
35
|
+
};
|
|
36
|
+
return {
|
|
37
|
+
start: () => void (index = 0),
|
|
38
|
+
display,
|
|
39
|
+
view: (Generators) => (input) => Generators.input(display(input)),
|
|
40
|
+
};
|
|
41
|
+
};`;
|
|
42
|
+
|
|
43
|
+
const defineCell = (record, index) => {
|
|
44
|
+
if (record.error) {
|
|
45
|
+
return ` main.variable(observer()).define([], () => { throw new SyntaxError(${str(record.error)}); });`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const inputs = record.inputs ?? [];
|
|
49
|
+
let body = `(${record.body.replace(GIST_IMPORT, 'importGist($1)')})`;
|
|
50
|
+
let runtimeInputs = inputs.map(classicName);
|
|
51
|
+
const lines = [];
|
|
52
|
+
|
|
53
|
+
// Plain JavaScript cells may call display()/view(): give them the shim. In
|
|
54
|
+
// Observable JavaScript those are ordinary names (e.g. an imported view).
|
|
55
|
+
const usesDisplay = record.mode === 'js' && (inputs.includes('display') || inputs.includes('view'));
|
|
56
|
+
if (usesDisplay) {
|
|
57
|
+
const shim = `display${index}`;
|
|
58
|
+
lines.push(` const ${shim} = cellDisplay(observer);`);
|
|
59
|
+
runtimeInputs = inputs.filter((i) => i !== 'display' && i !== 'view').map(classicName);
|
|
60
|
+
if (inputs.includes('view')) runtimeInputs.push('Generators');
|
|
61
|
+
const params = runtimeInputs.map((_, i) => `$${i}`);
|
|
62
|
+
const generators = `$${runtimeInputs.indexOf('Generators')}`;
|
|
63
|
+
let next = 0;
|
|
64
|
+
const args = inputs.map((input) =>
|
|
65
|
+
input === 'display' ? `${shim}.display` : input === 'view' ? `${shim}.view(${generators})` : `$${next++}`,
|
|
66
|
+
);
|
|
67
|
+
body = `function (${params}) {\n ${shim}.start();\n return ${body}.call(this, ${args});\n }`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const define = (observed, name, ins, fn) =>
|
|
71
|
+
` main.${observed ? `variable(${observed}).define(` : 'define('}${name ? `${str(name)}, ` : ''}${str(ins)}, ${fn});`;
|
|
72
|
+
|
|
73
|
+
if (record.automutable) {
|
|
74
|
+
const name = record.output.replace(/^initial /, '');
|
|
75
|
+
lines.push(
|
|
76
|
+
define(null, `initial ${name}`, runtimeInputs, body),
|
|
77
|
+
define(`observer(${str(`mutable ${name}`)})`, `mutable ${name}`, ['Mutable', `initial ${name}`], '(M, _) => new M(_)'),
|
|
78
|
+
define(`observer(${str(name)})`, name, [`mutable ${name}`], '(_) => _.generator'),
|
|
79
|
+
);
|
|
80
|
+
} else if (record.autoview) {
|
|
81
|
+
const view = classicName(record.output);
|
|
82
|
+
const name = view.replace(/^viewof /, '');
|
|
83
|
+
lines.push(
|
|
84
|
+
define(`observer(${str(view)})`, view, runtimeInputs, body),
|
|
85
|
+
define(`observer(${str(name)})`, name, ['Generators', view], '(G, _) => G.input(_)'),
|
|
86
|
+
);
|
|
87
|
+
} else if (record.output) {
|
|
88
|
+
lines.push(define(`observer(${str(record.output)})`, record.output, runtimeInputs, body));
|
|
89
|
+
} else if (record.outputs?.length) {
|
|
90
|
+
// Several outputs (a plain JavaScript cell's declarations, or a notebook
|
|
91
|
+
// import): one variable returns them all, one variable per name picks one.
|
|
92
|
+
const cell = `cell ${index}`;
|
|
93
|
+
const isImport = inputs.includes('@variable');
|
|
94
|
+
lines.push(define(isImport ? null : 'true', cell, runtimeInputs, body));
|
|
95
|
+
for (const output of record.outputs) {
|
|
96
|
+
lines.push(
|
|
97
|
+
isImport
|
|
98
|
+
? define(null, output, [cell], `(_) => _[${str(output)}]`)
|
|
99
|
+
: define(`observer(${str(output)})`, output, [cell], `(_) => _[${str(output)}]`),
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
} else {
|
|
103
|
+
lines.push(define(record.autodisplay ? 'observer()' : 'true', null, runtimeInputs, body));
|
|
104
|
+
}
|
|
105
|
+
return lines.join('\n');
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
// File attachments ship in a folder next to the module; FileAttachment(name)
|
|
109
|
+
// resolves to them, as in modules published by Observable.
|
|
110
|
+
const fileAttachments = ({ folder, names = [] } = {}) =>
|
|
111
|
+
names.length
|
|
112
|
+
? ` const fileAttachments = new Map(${str(names)}.map((name) => [name, { url: new URL(\`./${folder}/\${encodeURIComponent(name)}\`, import.meta.url), mimeType: null }]));
|
|
113
|
+
main.builtin("FileAttachment", runtime.fileAttachments((name) => fileAttachments.get(name)));\n`
|
|
114
|
+
: '';
|
|
115
|
+
|
|
116
|
+
export const compileModule = (cells, { name, files } = {}) => {
|
|
117
|
+
const definitions = cells
|
|
118
|
+
.filter((cell) => !cell.mode || ['ojs', 'js', 'md', 'html', 'tex', 'dot'].includes(cell.mode))
|
|
119
|
+
.map((cell, index) => defineCell(compileCell(String(cell.sourceCode ?? '')), index + 1));
|
|
120
|
+
return `// Compiled by iridium-dev-server${name ? ` from ${name}` : ''}. Do not edit.
|
|
121
|
+
${HELPERS}
|
|
122
|
+
|
|
123
|
+
export default function define(runtime, observer) {
|
|
124
|
+
const main = runtime.module();
|
|
125
|
+
${fileAttachments(files)}${definitions.join('\n')}
|
|
126
|
+
return main;
|
|
127
|
+
}
|
|
128
|
+
`;
|
|
129
|
+
};
|
package/lib/live.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// Relay between assistants (the MCP server) and the editor tabs showing a
|
|
2
|
+
// notebook. The server keeps no notebook state: each open tab is the live
|
|
3
|
+
// notebook, and tools act on it by sending the tab commands over WebSocket
|
|
4
|
+
// (add, edit, run or delete cells, save, describe outputs, evaluate). The tab
|
|
5
|
+
// does the work exactly as if the user had, and its file is read and written
|
|
6
|
+
// only by the tab's own load and Save.
|
|
7
|
+
|
|
8
|
+
export class Relay {
|
|
9
|
+
constructor() {
|
|
10
|
+
this.tabs = new Map(); // name → Set of sockets
|
|
11
|
+
this.requests = new Map(); // request id → { resolve, reject, socket }
|
|
12
|
+
this.nextRequest = 1;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
connect(name, socket) {
|
|
16
|
+
if (!this.tabs.has(name)) this.tabs.set(name, new Set());
|
|
17
|
+
const tabs = this.tabs.get(name);
|
|
18
|
+
tabs.add(socket);
|
|
19
|
+
socket.lastActive = Date.now();
|
|
20
|
+
socket.on('message', (data) => {
|
|
21
|
+
let message;
|
|
22
|
+
try {
|
|
23
|
+
message = JSON.parse(String(data));
|
|
24
|
+
} catch {
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
if (message.type === 'active') {
|
|
28
|
+
// The user is looking at this tab: send it the next commands.
|
|
29
|
+
socket.lastActive = Date.now();
|
|
30
|
+
} else if (message.type === 'response' && this.requests.has(message.id)) {
|
|
31
|
+
const request = this.requests.get(message.id);
|
|
32
|
+
if (message.error) request.reject(new Error(message.error));
|
|
33
|
+
else request.resolve(message.result);
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
socket.on('close', () => {
|
|
37
|
+
tabs.delete(socket);
|
|
38
|
+
if (!tabs.size) this.tabs.delete(name);
|
|
39
|
+
for (const request of this.requests.values()) {
|
|
40
|
+
if (request.socket === socket) request.reject(new Error('The tab closed before answering.'));
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
clients(name) {
|
|
46
|
+
return this.tabs.get(name)?.size ?? 0;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// The tab to act on: the one the user was in most recently.
|
|
50
|
+
tab(name) {
|
|
51
|
+
const tabs = [...(this.tabs.get(name) ?? [])];
|
|
52
|
+
return tabs.sort((a, b) => b.lastActive - a.lastActive)[0] ?? null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Sends `method` to the notebook's tab and resolves with its answer.
|
|
56
|
+
request(name, method, params = {}, timeout = 30000) {
|
|
57
|
+
const socket = this.tab(name);
|
|
58
|
+
if (!socket) {
|
|
59
|
+
return Promise.reject(new Error(`No browser tab is showing the notebook "${name}". Call open_notebook to open one.`));
|
|
60
|
+
}
|
|
61
|
+
const id = this.nextRequest++;
|
|
62
|
+
return new Promise((resolve, reject) => {
|
|
63
|
+
const done = (fn) => (value) => {
|
|
64
|
+
clearTimeout(timer);
|
|
65
|
+
this.requests.delete(id);
|
|
66
|
+
fn(value);
|
|
67
|
+
};
|
|
68
|
+
const timer = setTimeout(
|
|
69
|
+
() => done(reject)(new Error(`The tab did not answer ${method} within ${timeout / 1000}s (a cell may be running a long computation).`)),
|
|
70
|
+
timeout,
|
|
71
|
+
);
|
|
72
|
+
this.requests.set(id, { resolve: done(resolve), reject: done(reject), socket });
|
|
73
|
+
socket.send(JSON.stringify({ type: 'request', id, method, params }));
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// The tab's cells (all, or `ids`) once they have finished running, waiting
|
|
78
|
+
// up to `wait` ms, and whether the tab has unsaved changes.
|
|
79
|
+
async describe(name, ids, wait = 8000) {
|
|
80
|
+
const end = Date.now() + wait;
|
|
81
|
+
for (;;) {
|
|
82
|
+
const result = await this.request(name, 'describe', { ids });
|
|
83
|
+
if (result.cells.every((cell) => cell.status !== 'pending') || Date.now() >= end) return result;
|
|
84
|
+
await new Promise((resolve) => setTimeout(resolve, 150));
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
package/lib/mcp-stdio.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// `iridium-dev-server mcp`: the MCP server over stdio, for assistants such as
|
|
2
|
+
// Claude Code. It serves the current directory's notebooks if it has an
|
|
3
|
+
// .iridiumrc; otherwise a home folder (IRIDIUM_HOME, or ~/Documents/Iridium,
|
|
4
|
+
// created on first use). If a dev server already runs there, this process
|
|
5
|
+
// bridges to its /mcp endpoint so every assistant shares the same live
|
|
6
|
+
// notebooks; otherwise it starts one. stdout carries the protocol, so all
|
|
7
|
+
// logging goes to stderr.
|
|
8
|
+
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
9
|
+
import { homedir } from 'node:os';
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
12
|
+
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
13
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
14
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
15
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
16
|
+
import { hasConfig, loadConfig } from './config.js';
|
|
17
|
+
import { createMcpServer } from './mcp.js';
|
|
18
|
+
import { serverUrl, startServer } from './server.js';
|
|
19
|
+
|
|
20
|
+
const log = (...args) => console.error('[iridium]', ...args);
|
|
21
|
+
|
|
22
|
+
const useHome = () => {
|
|
23
|
+
const home = process.env.IRIDIUM_HOME ?? join(homedir(), 'Documents', 'Iridium');
|
|
24
|
+
mkdirSync(join(home, 'notebooks'), { recursive: true });
|
|
25
|
+
const rc = join(home, '.iridiumrc');
|
|
26
|
+
if (!existsSync(rc)) {
|
|
27
|
+
writeFileSync(rc, `${JSON.stringify({ notebooks: './notebooks', compiled: './dist', port: 8090 }, null, 2)}\n`);
|
|
28
|
+
}
|
|
29
|
+
mkdirSync(join(home, 'dist'), { recursive: true });
|
|
30
|
+
process.chdir(home);
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
// Is an Iridium dev server already answering at url?
|
|
34
|
+
const isIridium = async (url) => {
|
|
35
|
+
try {
|
|
36
|
+
const response = await fetch(`${url}/__iridium__/iridium.js`, { method: 'HEAD', signal: AbortSignal.timeout(1500) });
|
|
37
|
+
return response.ok;
|
|
38
|
+
} catch {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const bridge = async (url, version) => {
|
|
44
|
+
const client = new Client({ name: 'iridium-stdio-bridge', version });
|
|
45
|
+
await client.connect(new StreamableHTTPClientTransport(new URL(`${url}/mcp`)));
|
|
46
|
+
const server = new Server(
|
|
47
|
+
{ name: 'iridium', version },
|
|
48
|
+
{ capabilities: { tools: {} }, instructions: client.getInstructions() },
|
|
49
|
+
);
|
|
50
|
+
server.setRequestHandler(ListToolsRequestSchema, (request) => client.listTools(request.params));
|
|
51
|
+
server.setRequestHandler(CallToolRequestSchema, (request) => client.callTool(request.params));
|
|
52
|
+
await server.connect(new StdioServerTransport());
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
export const runStdio = async ({ version }) => {
|
|
56
|
+
if (!hasConfig()) useHome();
|
|
57
|
+
const config = loadConfig();
|
|
58
|
+
const url = serverUrl(config);
|
|
59
|
+
log(`notebooks in ${join(process.cwd(), config.notebooks)}`);
|
|
60
|
+
|
|
61
|
+
if (await isIridium(url)) {
|
|
62
|
+
log(`using the dev server already running at ${url}`);
|
|
63
|
+
await bridge(url, version);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const { server, mcpOptions } = startServer(config, { log });
|
|
68
|
+
await new Promise((resolve, reject) => {
|
|
69
|
+
server.once('listening', resolve);
|
|
70
|
+
server.once('error', reject);
|
|
71
|
+
}).catch((error) => {
|
|
72
|
+
log(`could not start the dev server on port ${config.port}: ${error.message}`);
|
|
73
|
+
process.exit(1);
|
|
74
|
+
});
|
|
75
|
+
await createMcpServer(mcpOptions).connect(new StdioServerTransport());
|
|
76
|
+
// When the assistant goes away, stop serving.
|
|
77
|
+
process.stdin.on('close', () => process.exit(0));
|
|
78
|
+
};
|