@runtimed/node 0.4.1 → 0.5.0

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/README.md CHANGED
@@ -1,10 +1,146 @@
1
- # @runtimed/node
1
+ # `@runtimed/node`
2
+
3
+ Run Python from Node in a kernel that stays alive between calls. Variables and
4
+ imports persist, dependencies install mid-session via uv, and plots come back
5
+ as image data in the cell result.
6
+
7
+ **Before** — new process every call, no memory:
8
+
9
+ ```js
10
+ execSync('python -c "import pandas as pd; df = pd.read_csv(\'data.csv\'); print(df.shape)"');
11
+ // next call: pandas re-imported, df gone, startup cost paid again
12
+ ```
13
+
14
+ **After** — one session, state sticks:
15
+
16
+ ```js
17
+ const { createNotebook } = require("@runtimed/node");
18
+
19
+ async function main() {
20
+ const session = await createNotebook({ workingDir: "./project" });
21
+
22
+ await session.runCell('import pandas as pd; df = pd.read_csv("data.csv")');
23
+ await session.runCell('df.groupby("region").sum()'); // df still there
24
+
25
+ await session.addDependencies(["seaborn"]); // no restart
26
+ await session.syncEnvironment(); // df survives this
27
+
28
+ const result = await session.runCell(
29
+ "import seaborn as sns; sns.heatmap(df.corr(numeric_only=True))",
30
+ );
31
+
32
+ // Plot arrives as a display_data output. `dataJson` carries base64 PNG under
33
+ // "image/png"; `blobUrlsJson` carries a daemon URL for the same bytes.
34
+ const plot = result.outputs.find((output) => output.outputType === "display_data");
35
+ console.log(Object.keys(JSON.parse(plot.dataJson))); // ["image/png", "text/plain", ...]
36
+ }
37
+
38
+ main().catch((error) => {
39
+ console.error(error);
40
+ process.exit(1);
41
+ });
42
+ ```
43
+
44
+ Built for agent loops where one session spans many turns. Session startup costs
45
+ a couple of seconds and then every later call is cheap, so the win grows with
46
+ the number of turns. Running a script once? Use a subprocess.
2
47
 
3
48
  Node.js bindings for the nteract `runtimed` daemon. This package lets Node,
4
49
  Bun, and other CommonJS-compatible runtimes create notebooks, run Python cells,
5
50
  queue executions, read outputs, save notebooks, and manage notebook dependencies
6
51
  through the same local daemon used by nteract desktop.
7
52
 
53
+ ## Embedding a notebook frontend
54
+
55
+ `@runtimed/node/relay` exposes the native byte pipe used by desktop notebook
56
+ hosts. The browser/WASM frontend remains the Automerge peer; Node owns the
57
+ daemon socket, handshake, framing, and liveness heartbeat and forwards opaque
58
+ typed frames to the browser transport.
59
+
60
+ ```js
61
+ const { createRelay } = require("@runtimed/node/relay");
62
+
63
+ const relay = await createRelay({
64
+ workingDir: process.cwd(),
65
+ ephemeral: true,
66
+ description: "embedded notebook",
67
+ });
68
+
69
+ relay.onFrame((frame) => browserTransport.send(frame));
70
+ browserTransport.on("message", (frame) => relay.send(frame));
71
+ browserTransport.on("close", () => relay.close());
72
+ ```
73
+
74
+ Hosts that supervise the daemon can use `defaultSocketPath()`,
75
+ `socketPathForChannel("stable" | "nightly")`, and
76
+ `queryDaemonInfo({ socketPath })` from the same subpath. The explicit channel
77
+ resolver is useful when the host's release channel differs from the package's
78
+ compile-time default. The query returns `null` until the daemon is ready, so
79
+ the host does not need to duplicate the pool wire protocol just to probe
80
+ readiness.
81
+
82
+ `RelaySession.info.daemonVersion` is the identity carried by that notebook's
83
+ exact handshake. It is intentionally left undefined when an older daemon omits
84
+ it rather than being filled from a later pool query, which could race a daemon
85
+ restart. Treat that artifact version as diagnostic metadata. Compatibility is
86
+ determined by the negotiated protocol number and, for optional semantics, the
87
+ capabilities advertised by the connection. Use `queryDaemonInfo()` only for
88
+ readiness and diagnostics.
89
+
90
+ Frames include the one-byte notebook frame discriminator and omit the daemon
91
+ socket's length prefix; an empty buffer is not a frame and is rejected. The
92
+ relay subscribes to native delivery eagerly so bootstrap frames are retained.
93
+ It invokes JavaScript frame handlers serially to preserve ordering, so handlers
94
+ should forward or copy a frame promptly rather than perform expensive work
95
+ inline.
96
+
97
+ Electron hosts can attach that relay directly to one transferred
98
+ `MessagePortMain` without opening a loopback listener:
99
+
100
+ ```js
101
+ const { MessageChannelMain } = require("electron");
102
+ const { createRelay } = require("@runtimed/node/relay");
103
+ const { serveElectronNotebookHost } = require("@runtimed/node/electron");
104
+
105
+ const relay = await createRelay({ notebookId: authorizedNotebookId });
106
+ const { port1, port2 } = new MessageChannelMain();
107
+
108
+ serveElectronNotebookHost({
109
+ port: port1,
110
+ relay,
111
+ handler: {
112
+ invoke(method, params) {
113
+ return invokeAuthorizedHostMethod(method, params);
114
+ },
115
+ },
116
+ });
117
+
118
+ browserWindow.webContents.postMessage("notebook:port", null, [port2]);
119
+ ```
120
+
121
+ `@runtimed/node/electron` validates the host-method allowlist and multiplexes
122
+ opaque protocol-numbered notebook frames, host requests, notifications, and
123
+ events over the port. The embedding host still owns notebook authorization,
124
+ path validation, dialogs, window lifecycle, and output CSP.
125
+
126
+ The relay is intentionally Electron-free: custom protocols, CSP, browser-peer
127
+ authentication, window lifecycle, and daemon installation remain
128
+ responsibilities of the embedding host. `connectRelay(notebookId)` is an
129
+ operator connection, not an authorization check. A host must authorize the
130
+ notebook ID itself and must not expose room discovery or relay creation directly
131
+ to an untrusted browser context.
132
+
133
+ `close()` is terminal cancellation. Natural daemon closure drains frames already
134
+ queued for JavaScript before notifying `onClose`; explicitly closing before a
135
+ browser peer subscribes discards the buffered bootstrap frames.
136
+
137
+ For a daemon-backed transport check during development:
138
+
139
+ ```bash
140
+ RUNTIMED_SOCKET_PATH=/path/to/runtimed.sock \
141
+ pnpm --dir packages/runtimed-node smoke:relay
142
+ ```
143
+
8
144
  ## Install
9
145
 
10
146
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runtimed/node",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "Node.js bindings for controlling nteract runtimed notebooks and Python kernels.",
5
5
  "type": "module",
6
6
  "license": "BSD-3-Clause",
@@ -29,12 +29,27 @@
29
29
  "types": "./src/index.d.ts",
30
30
  "require": "./src/index.cjs",
31
31
  "default": "./src/index.cjs"
32
+ },
33
+ "./relay": {
34
+ "types": "./src/relay.d.ts",
35
+ "require": "./src/relay.cjs",
36
+ "default": "./src/relay.cjs"
37
+ },
38
+ "./electron": {
39
+ "types": "./src/electron.d.ts",
40
+ "require": "./src/electron.cjs",
41
+ "default": "./src/electron.cjs"
32
42
  }
33
43
  },
34
44
  "files": [
35
45
  "README.md",
36
46
  "src/index.cjs",
37
47
  "src/index.d.ts",
48
+ "src/relay.cjs",
49
+ "src/relay.d.ts",
50
+ "src/electron.cjs",
51
+ "src/electron.d.ts",
52
+ "src/relay-session.cjs",
38
53
  "src/session.cjs",
39
54
  "src/napi-observables.cjs",
40
55
  "src/binding.cjs",
@@ -52,9 +67,9 @@
52
67
  "rxjs": "^7.8.2"
53
68
  },
54
69
  "optionalDependencies": {
55
- "@runtimed/node-darwin-arm64": "0.4.1",
56
- "@runtimed/node-win32-x64-msvc": "0.4.1",
57
- "@runtimed/node-linux-x64-gnu": "0.4.1"
70
+ "@runtimed/node-darwin-arm64": "0.5.0",
71
+ "@runtimed/node-win32-x64-msvc": "0.5.0",
72
+ "@runtimed/node-linux-x64-gnu": "0.5.0"
58
73
  },
59
74
  "publishConfig": {
60
75
  "access": "public"
@@ -69,6 +84,7 @@
69
84
  "pack:platform:dry-run": "node scripts/assemble-platform-package.mjs --pack-dry-run",
70
85
  "pack:dry-run": "pnpm pack --dry-run",
71
86
  "smoke": "node -e \"const m = require('./src/index.cjs'); console.log('defaultSocketPath:', m.defaultSocketPath());\"",
87
+ "smoke:relay": "node scripts/smoke-relay.cjs",
72
88
  "smoke:api": "node scripts/smoke-api.cjs"
73
89
  }
74
90
  }
package/src/binding.cjs CHANGED
@@ -77,8 +77,8 @@ function requireNative() {
77
77
  try {
78
78
  const binding = require('@runtimed/node-android-arm64')
79
79
  const bindingPackageVersion = require('@runtimed/node-android-arm64/package.json').version
80
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
81
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
80
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
81
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
82
82
  }
83
83
  return binding
84
84
  } catch (e) {
@@ -93,8 +93,8 @@ function requireNative() {
93
93
  try {
94
94
  const binding = require('@runtimed/node-android-arm-eabi')
95
95
  const bindingPackageVersion = require('@runtimed/node-android-arm-eabi/package.json').version
96
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
97
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
96
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
97
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
98
98
  }
99
99
  return binding
100
100
  } catch (e) {
@@ -114,8 +114,8 @@ function requireNative() {
114
114
  try {
115
115
  const binding = require('@runtimed/node-win32-x64-gnu')
116
116
  const bindingPackageVersion = require('@runtimed/node-win32-x64-gnu/package.json').version
117
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
118
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
117
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
118
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
119
119
  }
120
120
  return binding
121
121
  } catch (e) {
@@ -130,8 +130,8 @@ function requireNative() {
130
130
  try {
131
131
  const binding = require('@runtimed/node-win32-x64-msvc')
132
132
  const bindingPackageVersion = require('@runtimed/node-win32-x64-msvc/package.json').version
133
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
134
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
133
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
134
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
135
135
  }
136
136
  return binding
137
137
  } catch (e) {
@@ -147,8 +147,8 @@ function requireNative() {
147
147
  try {
148
148
  const binding = require('@runtimed/node-win32-ia32-msvc')
149
149
  const bindingPackageVersion = require('@runtimed/node-win32-ia32-msvc/package.json').version
150
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
151
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
150
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
151
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
152
152
  }
153
153
  return binding
154
154
  } catch (e) {
@@ -163,8 +163,8 @@ function requireNative() {
163
163
  try {
164
164
  const binding = require('@runtimed/node-win32-arm64-msvc')
165
165
  const bindingPackageVersion = require('@runtimed/node-win32-arm64-msvc/package.json').version
166
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
167
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
166
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
167
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
168
168
  }
169
169
  return binding
170
170
  } catch (e) {
@@ -182,8 +182,8 @@ function requireNative() {
182
182
  try {
183
183
  const binding = require('@runtimed/node-darwin-universal')
184
184
  const bindingPackageVersion = require('@runtimed/node-darwin-universal/package.json').version
185
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
186
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
185
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
186
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
187
187
  }
188
188
  return binding
189
189
  } catch (e) {
@@ -198,8 +198,8 @@ function requireNative() {
198
198
  try {
199
199
  const binding = require('@runtimed/node-darwin-x64')
200
200
  const bindingPackageVersion = require('@runtimed/node-darwin-x64/package.json').version
201
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
202
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
201
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
202
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
203
203
  }
204
204
  return binding
205
205
  } catch (e) {
@@ -214,8 +214,8 @@ function requireNative() {
214
214
  try {
215
215
  const binding = require('@runtimed/node-darwin-arm64')
216
216
  const bindingPackageVersion = require('@runtimed/node-darwin-arm64/package.json').version
217
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
218
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
217
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
218
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
219
219
  }
220
220
  return binding
221
221
  } catch (e) {
@@ -234,8 +234,8 @@ function requireNative() {
234
234
  try {
235
235
  const binding = require('@runtimed/node-freebsd-x64')
236
236
  const bindingPackageVersion = require('@runtimed/node-freebsd-x64/package.json').version
237
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
238
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
237
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
238
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
239
239
  }
240
240
  return binding
241
241
  } catch (e) {
@@ -250,8 +250,8 @@ function requireNative() {
250
250
  try {
251
251
  const binding = require('@runtimed/node-freebsd-arm64')
252
252
  const bindingPackageVersion = require('@runtimed/node-freebsd-arm64/package.json').version
253
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
254
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
253
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
254
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
255
255
  }
256
256
  return binding
257
257
  } catch (e) {
@@ -271,8 +271,8 @@ function requireNative() {
271
271
  try {
272
272
  const binding = require('@runtimed/node-linux-x64-musl')
273
273
  const bindingPackageVersion = require('@runtimed/node-linux-x64-musl/package.json').version
274
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
275
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
274
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
275
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
276
276
  }
277
277
  return binding
278
278
  } catch (e) {
@@ -287,8 +287,8 @@ function requireNative() {
287
287
  try {
288
288
  const binding = require('@runtimed/node-linux-x64-gnu')
289
289
  const bindingPackageVersion = require('@runtimed/node-linux-x64-gnu/package.json').version
290
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
291
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
290
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
291
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
292
292
  }
293
293
  return binding
294
294
  } catch (e) {
@@ -305,8 +305,8 @@ function requireNative() {
305
305
  try {
306
306
  const binding = require('@runtimed/node-linux-arm64-musl')
307
307
  const bindingPackageVersion = require('@runtimed/node-linux-arm64-musl/package.json').version
308
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
309
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
308
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
309
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
310
310
  }
311
311
  return binding
312
312
  } catch (e) {
@@ -321,8 +321,8 @@ function requireNative() {
321
321
  try {
322
322
  const binding = require('@runtimed/node-linux-arm64-gnu')
323
323
  const bindingPackageVersion = require('@runtimed/node-linux-arm64-gnu/package.json').version
324
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
325
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
324
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
325
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
326
326
  }
327
327
  return binding
328
328
  } catch (e) {
@@ -339,8 +339,8 @@ function requireNative() {
339
339
  try {
340
340
  const binding = require('@runtimed/node-linux-arm-musleabihf')
341
341
  const bindingPackageVersion = require('@runtimed/node-linux-arm-musleabihf/package.json').version
342
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
343
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
342
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
343
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
344
344
  }
345
345
  return binding
346
346
  } catch (e) {
@@ -355,8 +355,8 @@ function requireNative() {
355
355
  try {
356
356
  const binding = require('@runtimed/node-linux-arm-gnueabihf')
357
357
  const bindingPackageVersion = require('@runtimed/node-linux-arm-gnueabihf/package.json').version
358
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
359
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
358
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
359
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
360
360
  }
361
361
  return binding
362
362
  } catch (e) {
@@ -373,8 +373,8 @@ function requireNative() {
373
373
  try {
374
374
  const binding = require('@runtimed/node-linux-loong64-musl')
375
375
  const bindingPackageVersion = require('@runtimed/node-linux-loong64-musl/package.json').version
376
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
377
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
376
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
377
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
378
378
  }
379
379
  return binding
380
380
  } catch (e) {
@@ -389,8 +389,8 @@ function requireNative() {
389
389
  try {
390
390
  const binding = require('@runtimed/node-linux-loong64-gnu')
391
391
  const bindingPackageVersion = require('@runtimed/node-linux-loong64-gnu/package.json').version
392
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
393
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
392
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
393
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
394
394
  }
395
395
  return binding
396
396
  } catch (e) {
@@ -407,8 +407,8 @@ function requireNative() {
407
407
  try {
408
408
  const binding = require('@runtimed/node-linux-riscv64-musl')
409
409
  const bindingPackageVersion = require('@runtimed/node-linux-riscv64-musl/package.json').version
410
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
411
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
410
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
411
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
412
412
  }
413
413
  return binding
414
414
  } catch (e) {
@@ -423,8 +423,8 @@ function requireNative() {
423
423
  try {
424
424
  const binding = require('@runtimed/node-linux-riscv64-gnu')
425
425
  const bindingPackageVersion = require('@runtimed/node-linux-riscv64-gnu/package.json').version
426
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
427
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
426
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
427
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
428
428
  }
429
429
  return binding
430
430
  } catch (e) {
@@ -440,8 +440,8 @@ function requireNative() {
440
440
  try {
441
441
  const binding = require('@runtimed/node-linux-ppc64-gnu')
442
442
  const bindingPackageVersion = require('@runtimed/node-linux-ppc64-gnu/package.json').version
443
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
444
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
443
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
444
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
445
445
  }
446
446
  return binding
447
447
  } catch (e) {
@@ -456,8 +456,8 @@ function requireNative() {
456
456
  try {
457
457
  const binding = require('@runtimed/node-linux-s390x-gnu')
458
458
  const bindingPackageVersion = require('@runtimed/node-linux-s390x-gnu/package.json').version
459
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
460
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
459
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
460
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
461
461
  }
462
462
  return binding
463
463
  } catch (e) {
@@ -476,8 +476,8 @@ function requireNative() {
476
476
  try {
477
477
  const binding = require('@runtimed/node-openharmony-arm64')
478
478
  const bindingPackageVersion = require('@runtimed/node-openharmony-arm64/package.json').version
479
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
480
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
479
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
480
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
481
481
  }
482
482
  return binding
483
483
  } catch (e) {
@@ -492,8 +492,8 @@ function requireNative() {
492
492
  try {
493
493
  const binding = require('@runtimed/node-openharmony-x64')
494
494
  const bindingPackageVersion = require('@runtimed/node-openharmony-x64/package.json').version
495
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
496
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
495
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
496
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
497
497
  }
498
498
  return binding
499
499
  } catch (e) {
@@ -508,8 +508,8 @@ function requireNative() {
508
508
  try {
509
509
  const binding = require('@runtimed/node-openharmony-arm')
510
510
  const bindingPackageVersion = require('@runtimed/node-openharmony-arm/package.json').version
511
- if (bindingPackageVersion !== '0.4.1' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
512
- throw new Error(`Native binding package version mismatch, expected 0.4.1 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
511
+ if (bindingPackageVersion !== '0.5.0' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') {
512
+ throw new Error(`Native binding package version mismatch, expected 0.5.0 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`)
513
513
  }
514
514
  return binding
515
515
  } catch (e) {
@@ -577,16 +577,21 @@ if (!nativeBinding) {
577
577
 
578
578
  module.exports = nativeBinding
579
579
  module.exports.EventSubscription = nativeBinding.EventSubscription
580
+ module.exports.NativeRelaySession = nativeBinding.NativeRelaySession
580
581
  module.exports.Session = nativeBinding.Session
581
582
  module.exports.blobStorePath = nativeBinding.blobStorePath
583
+ module.exports.connectRelay = nativeBinding.connectRelay
582
584
  module.exports.createNotebook = nativeBinding.createNotebook
583
585
  module.exports.CreateNotebookEnvironmentMode = nativeBinding.CreateNotebookEnvironmentMode
586
+ module.exports.createRelay = nativeBinding.createRelay
584
587
  module.exports.defaultSocketPath = nativeBinding.defaultSocketPath
585
588
  module.exports.getExecutionResult = nativeBinding.getExecutionResult
586
589
  module.exports.listActiveNotebooks = nativeBinding.listActiveNotebooks
587
590
  module.exports.openNotebook = nativeBinding.openNotebook
588
591
  module.exports.openNotebookPath = nativeBinding.openNotebookPath
592
+ module.exports.openRelayPath = nativeBinding.openRelayPath
589
593
  module.exports.PackageManager = nativeBinding.PackageManager
594
+ module.exports.queryDaemonInfo = nativeBinding.queryDaemonInfo
590
595
  module.exports.readArrowChunks = nativeBinding.readArrowChunks
591
596
  module.exports.readArrowFile = nativeBinding.readArrowFile
592
597
  module.exports.readParquetFile = nativeBinding.readParquetFile
package/src/binding.d.ts CHANGED
@@ -6,6 +6,25 @@ export declare class EventSubscription {
6
6
  dispose(): void
7
7
  }
8
8
 
9
+ /** A native byte pipe between a Node host and one daemon notebook room. */
10
+ export declare class NativeRelaySession {
11
+ get notebookId(): string
12
+ get info(): RelayInfo
13
+ get closed(): boolean
14
+ /** Forward one complete typed frame (`type byte | payload`) to the daemon. */
15
+ send(frame: Buffer): Promise<void>
16
+ /**
17
+ * Subscribe once to lossless inbound typed frames and relay closure.
18
+ *
19
+ * The receiver is single-consumer by design: one browser transport owns a
20
+ * daemon connection. The returned subscription must stay alive for the
21
+ * lifetime of the bridge.
22
+ */
23
+ subscribeFrames(onFrame: (arg0: Buffer) => void, onClose: () => void): EventSubscription
24
+ /** Close the native relay. Idempotent. */
25
+ close(): void
26
+ }
27
+
9
28
  /** A connected notebook session. */
10
29
  export declare class Session {
11
30
  /** The notebook ID (always a UUID). */
@@ -169,6 +188,15 @@ export interface CondaDependencyStatus {
169
188
  python?: string
170
189
  }
171
190
 
191
+ /**
192
+ * Join an active notebook room by ID and return its native typed-frame relay.
193
+ *
194
+ * The daemon treats this API as an operator connection. Embedding hosts must
195
+ * authorize the requested notebook ID before calling it and must not expose
196
+ * room discovery or this relay directly to an untrusted browser context.
197
+ */
198
+ export declare function connectRelay(notebookId: string, options?: OpenRelayOptions | undefined | null): Promise<NativeRelaySession>
199
+
172
200
  /** Options for `Session.createCell()`. */
173
201
  export interface CreateCellOptions {
174
202
  /** Cell source type: `"code"` (default), `"markdown"`, or `"raw"`. */
@@ -216,6 +244,40 @@ export interface CreateNotebookOptions {
216
244
  environmentMode?: CreateNotebookEnvironmentMode
217
245
  }
218
246
 
247
+ /** Create a notebook room and return its native typed-frame relay. */
248
+ export declare function createRelay(options?: CreateRelayOptions | undefined | null): Promise<NativeRelaySession>
249
+
250
+ export interface CreateRelayOptions {
251
+ /** Runtime type. Defaults to `"python"`. */
252
+ runtime?: string
253
+ /** Kernel working directory. */
254
+ workingDir?: string
255
+ /** Override the daemon endpoint. */
256
+ socketPath?: string
257
+ /** Restore or join an untitled notebook room by ID. */
258
+ notebookId?: string
259
+ /** Actor/operator label advertised during the handshake. */
260
+ peerLabel?: string
261
+ /** Human-readable fallback for `peerLabel`. */
262
+ description?: string
263
+ /** Keep the notebook only in memory. Defaults to false. */
264
+ ephemeral?: boolean
265
+ /** Dependencies to seed into notebook metadata. */
266
+ dependencies?: Array<string>
267
+ /** Package manager preference for seeded dependencies. */
268
+ packageManager?: PackageManager
269
+ /** Project/notebook environment inheritance mode. */
270
+ environmentMode?: CreateNotebookEnvironmentMode
271
+ }
272
+
273
+ /** Daemon metadata needed by a Node host before it opens a notebook relay. */
274
+ export interface DaemonInfo {
275
+ version: string
276
+ socketPath: string
277
+ isDevMode: boolean
278
+ blobPort?: number
279
+ }
280
+
219
281
  /**
220
282
  * Return the default daemon socket path.
221
283
  *
@@ -323,6 +385,18 @@ export interface OpenNotebookOptions {
323
385
  /** Open an existing notebook file by path. */
324
386
  export declare function openNotebookPath(path: string, options?: OpenNotebookOptions | undefined | null): Promise<Session>
325
387
 
388
+ export interface OpenRelayOptions {
389
+ /** Override the daemon endpoint. */
390
+ socketPath?: string
391
+ /** Actor/operator label advertised during the handshake. */
392
+ peerLabel?: string
393
+ /** Human-readable fallback for `peerLabel`. */
394
+ description?: string
395
+ }
396
+
397
+ /** Open a notebook file and return its native typed-frame relay. */
398
+ export declare function openRelayPath(path: string, options?: OpenRelayOptions | undefined | null): Promise<NativeRelaySession>
399
+
326
400
  /**
327
401
  * Package manager for Python notebook dependencies.
328
402
  *
@@ -369,6 +443,21 @@ export interface PixiDependencyStatus {
369
443
  python?: string
370
444
  }
371
445
 
446
+ /**
447
+ * Probe the selected daemon and return its host-facing metadata when ready.
448
+ *
449
+ * `None` intentionally covers both an absent endpoint and a daemon that has
450
+ * bound its socket but is not ready to answer pool requests yet. Hosts can
451
+ * poll this function while supervising a cold start without cloning the wire
452
+ * protocol in JavaScript.
453
+ */
454
+ export declare function queryDaemonInfo(options?: QueryDaemonOptions | undefined | null): Promise<DaemonInfo | null>
455
+
456
+ export interface QueryDaemonOptions {
457
+ /** Override the daemon endpoint. */
458
+ socketPath?: string
459
+ }
460
+
372
461
  /** Options for `Session.queueCell()`. */
373
462
  export interface QueueCellOptions {
374
463
  /** Cell source type: `"code"` (default), `"markdown"`, or `"raw"`. */
@@ -393,6 +482,27 @@ export declare function readArrowFile(filePath: string, offset: number, limit: n
393
482
  */
394
483
  export declare function readParquetFile(filePath: string, offset: number, limit: number): ParquetRowPage
395
484
 
485
+ /** Bootstrap and daemon metadata needed by a browser host. */
486
+ export interface RelayInfo {
487
+ notebookId: string
488
+ cellCount?: number
489
+ needsTrustApproval?: boolean
490
+ ephemeral?: boolean
491
+ notebookPath?: string
492
+ runtime?: string
493
+ actorLabel?: string
494
+ connectionScope?: string
495
+ commentsDocId?: string
496
+ /** JSON encoding of the daemon-authoritative notebook reference. */
497
+ commentsNotebookRefJson?: string
498
+ protocol: string
499
+ protocolVersion?: number
500
+ daemonVersion?: string
501
+ socketPath: string
502
+ blobPort?: number
503
+ isDevMode: boolean
504
+ }
505
+
396
506
  /** Resolve a blob hash to the local on-disk blob path for the selected daemon. */
397
507
  export declare function resolveBlobPath(hash: string, socketPath?: string | undefined | null): string | null
398
508
 
@@ -0,0 +1,157 @@
1
+ "use strict";
2
+
3
+ const ELECTRON_HOST_PROTOCOL_VERSION = 1;
4
+
5
+ const ELECTRON_HOST_METHODS = Object.freeze([
6
+ "daemon.isConnected",
7
+ "daemon.reconnect",
8
+ "daemon.getInfo",
9
+ "daemon.getReadyInfo",
10
+ "relay.prepareSync",
11
+ "relay.notifySyncReady",
12
+ "blobs.getPort",
13
+ "deps.checkTyposquats",
14
+ "notebook.applyPathChanged",
15
+ "notebook.getDefaultSaveDirectory",
16
+ "notebook.openInNewWindow",
17
+ "notebook.openHostedInNewWindow",
18
+ "notebook.cloneToEphemeral",
19
+ "window.getTitle",
20
+ "window.setTitle",
21
+ "window.setTheme",
22
+ "system.getGitInfo",
23
+ "system.getUsername",
24
+ "system.getFontFamilies",
25
+ "dialog.openFile",
26
+ "dialog.saveFile",
27
+ "externalLinks.open",
28
+ "updater.check",
29
+ "updater.beginUpgrade",
30
+ "settings.openWindow",
31
+ "settings.getSynced",
32
+ "settings.setSynced",
33
+ "settings.rotateInstallId",
34
+ ]);
35
+ const HOST_METHODS = new Set(ELECTRON_HOST_METHODS);
36
+
37
+ function isRecord(value) {
38
+ return typeof value === "object" && value !== null;
39
+ }
40
+
41
+ function normalizeFrame(value) {
42
+ if (value instanceof Uint8Array) return value;
43
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
44
+ if (ArrayBuffer.isView(value)) {
45
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
46
+ }
47
+ if (Array.isArray(value) && value.every((part) => Number.isInteger(part))) {
48
+ return new Uint8Array(value);
49
+ }
50
+ return null;
51
+ }
52
+
53
+ function isHostNotification(value) {
54
+ if (!isRecord(value) || !isRecord(value.params) || typeof value.params.message !== "string") {
55
+ return false;
56
+ }
57
+ return ["log.debug", "log.info", "log.warn", "log.error"].includes(String(value.method));
58
+ }
59
+
60
+ /**
61
+ * Attach an authorized RelaySession and an allowlisted host handler to one
62
+ * MessagePortMain. This opens no listener and never exposes the daemon socket.
63
+ */
64
+ function serveElectronNotebookHost(options) {
65
+ let closed = false;
66
+ let relayClosed = false;
67
+
68
+ const emitEvent = (event, payload) => {
69
+ if (!closed) options.port.postMessage({ type: "nteract:host-event", event, payload });
70
+ };
71
+
72
+ const sendResponse = (id, response) => {
73
+ if (!closed) options.port.postMessage({ type: "nteract:host-response", id, ...response });
74
+ };
75
+
76
+ const server = {
77
+ emit: emitEvent,
78
+ async close() {
79
+ if (closed) return;
80
+ closed = true;
81
+ options.port.off("message", onPortMessage);
82
+ options.port.off("close", onPortClose);
83
+ unlistenFrame();
84
+ unlistenClose();
85
+ options.port.close();
86
+ await options.relay.close();
87
+ },
88
+ };
89
+
90
+ const closeBestEffort = () => {
91
+ void server.close().catch(() => {});
92
+ };
93
+
94
+ const onPortMessage = (event) => {
95
+ if (closed || !isRecord(event.data)) return;
96
+ const message = event.data;
97
+
98
+ if (message.type === "nteract:frame") {
99
+ const frame = normalizeFrame(message.frame);
100
+ if (frame) {
101
+ void options.relay.send(frame).catch(() => {
102
+ emitEvent("transport.status", "offline");
103
+ closeBestEffort();
104
+ });
105
+ }
106
+ return;
107
+ }
108
+
109
+ if (message.type === "nteract:host-notification") {
110
+ if (isHostNotification(message.notification)) options.handler.notify?.(message.notification);
111
+ return;
112
+ }
113
+
114
+ if (
115
+ message.type !== "nteract:host-request" ||
116
+ typeof message.id !== "string" ||
117
+ !HOST_METHODS.has(message.method)
118
+ ) {
119
+ return;
120
+ }
121
+
122
+ void Promise.resolve(options.handler.invoke(message.method, message.params)).then(
123
+ (value) => sendResponse(message.id, { ok: true, value }),
124
+ (error) =>
125
+ sendResponse(message.id, {
126
+ ok: false,
127
+ error: error instanceof Error ? error.message : String(error),
128
+ }),
129
+ );
130
+ };
131
+
132
+ const onPortClose = () => {
133
+ closeBestEffort();
134
+ };
135
+
136
+ const unlistenFrame = options.relay.onFrame((frame) => {
137
+ if (!closed) options.port.postMessage({ type: "nteract:frame", frame: Uint8Array.from(frame) });
138
+ });
139
+ const unlistenClose = options.relay.onClose(() => {
140
+ relayClosed = true;
141
+ emitEvent("transport.status", "offline");
142
+ // Keep the capability port alive: Electron hosts may replace the native
143
+ // relay when the renderer invokes daemon.reconnect over this same port.
144
+ });
145
+
146
+ options.port.on("message", onPortMessage);
147
+ options.port.on("close", onPortClose);
148
+ options.port.start();
149
+ emitEvent("transport.status", relayClosed ? "offline" : "online");
150
+ return server;
151
+ }
152
+
153
+ module.exports = {
154
+ ELECTRON_HOST_METHODS,
155
+ ELECTRON_HOST_PROTOCOL_VERSION,
156
+ serveElectronNotebookHost,
157
+ };
@@ -0,0 +1,112 @@
1
+ export const ELECTRON_HOST_PROTOCOL_VERSION: 1;
2
+
3
+ export type ConnectionStatus = "connecting" | "online" | "offline" | "reconnecting";
4
+
5
+ export type ElectronHostNativeTheme = "light" | "dark" | "system";
6
+ export type ElectronHostUpdateStatus =
7
+ | "idle"
8
+ | "checking"
9
+ | "available"
10
+ | "downloading"
11
+ | "ready"
12
+ | "unavailable"
13
+ | "error";
14
+
15
+ export interface ElectronHostUpdaterState {
16
+ status: ElectronHostUpdateStatus;
17
+ version: string | null;
18
+ error: string | null;
19
+ }
20
+
21
+ export interface ElectronHostMethodMap {
22
+ "daemon.isConnected": { params: undefined; result: boolean };
23
+ "daemon.reconnect": { params: { force?: boolean }; result: void };
24
+ "daemon.getInfo": { params: undefined; result: unknown | null };
25
+ "daemon.getReadyInfo": { params: undefined; result: unknown | null };
26
+ "relay.prepareSync": { params: { generation?: number }; result: void };
27
+ "relay.notifySyncReady": { params: { generation?: number }; result: void };
28
+ "blobs.getPort": { params: undefined; result: number };
29
+ "deps.checkTyposquats": { params: { packages: string[] }; result: unknown[] };
30
+ "notebook.applyPathChanged": { params: { path: string }; result: void };
31
+ "notebook.getDefaultSaveDirectory": { params: undefined; result: string };
32
+ "notebook.openInNewWindow": { params: { path: string }; result: void };
33
+ "notebook.openHostedInNewWindow": { params: { url: string }; result: void };
34
+ "notebook.cloneToEphemeral": { params: undefined; result: string };
35
+ "window.getTitle": { params: undefined; result: string };
36
+ "window.setTitle": { params: { title: string }; result: void };
37
+ "window.setTheme": { params: { theme: ElectronHostNativeTheme }; result: void };
38
+ "system.getGitInfo": { params: undefined; result: unknown | null };
39
+ "system.getUsername": { params: undefined; result: string };
40
+ "system.getFontFamilies": { params: undefined; result: string[] };
41
+ "dialog.openFile": { params: unknown; result: string | null };
42
+ "dialog.saveFile": { params: unknown; result: string | null };
43
+ "externalLinks.open": { params: { url: string }; result: void };
44
+ "updater.check": { params: undefined; result: ElectronHostUpdaterState };
45
+ "updater.beginUpgrade": { params: undefined; result: void };
46
+ "settings.openWindow": { params: undefined; result: void };
47
+ "settings.getSynced": { params: undefined; result: Record<string, unknown> };
48
+ "settings.setSynced": { params: { key: string; value: unknown }; result: void };
49
+ "settings.rotateInstallId": { params: undefined; result: string };
50
+ }
51
+
52
+ export type ElectronHostMethod = keyof ElectronHostMethodMap;
53
+ export const ELECTRON_HOST_METHODS: readonly ElectronHostMethod[];
54
+ export type ElectronHostMethodParams<M extends ElectronHostMethod> =
55
+ ElectronHostMethodMap[M]["params"];
56
+ export type ElectronHostMethodResult<M extends ElectronHostMethod> =
57
+ ElectronHostMethodMap[M]["result"];
58
+
59
+ export type ElectronHostNotification =
60
+ | { method: "log.debug"; params: { message: string } }
61
+ | { method: "log.info"; params: { message: string } }
62
+ | { method: "log.warn"; params: { message: string } }
63
+ | { method: "log.error"; params: { message: string } };
64
+
65
+ export interface ElectronHostEventMap {
66
+ "daemon.ready": unknown;
67
+ "daemon.progress": unknown;
68
+ "daemon.disconnected": undefined;
69
+ "daemon.unavailable": unknown;
70
+ "transport.status": ConnectionStatus;
71
+ "window.focusChanged": boolean;
72
+ "updater.changed": ElectronHostUpdaterState;
73
+ "settings.changed": Record<string, unknown>;
74
+ command: { id: string; payload: unknown };
75
+ }
76
+
77
+ export interface ElectronMainPort {
78
+ postMessage(message: unknown): void;
79
+ on(event: "message", listener: (event: { data: unknown }) => void): this;
80
+ on(event: "close", listener: () => void): this;
81
+ off(event: "message", listener: (event: { data: unknown }) => void): this;
82
+ off(event: "close", listener: () => void): this;
83
+ start(): void;
84
+ close(): void;
85
+ }
86
+
87
+ /** Structural RelaySession surface; accepts @runtimed/node/relay sessions and test doubles. */
88
+ export interface ElectronRelaySession {
89
+ send(frame: Uint8Array | ArrayBuffer): Promise<void>;
90
+ onFrame(listener: (frame: Uint8Array) => void): () => void;
91
+ onClose(listener: () => void): () => void;
92
+ close(): Promise<void>;
93
+ }
94
+
95
+ export interface ElectronNotebookHostHandler {
96
+ invoke<M extends ElectronHostMethod>(
97
+ method: M,
98
+ params: ElectronHostMethodParams<M>,
99
+ ): Promise<ElectronHostMethodResult<M>> | ElectronHostMethodResult<M>;
100
+ notify?(notification: ElectronHostNotification): void;
101
+ }
102
+
103
+ export interface ElectronNotebookHostServer {
104
+ emit<E extends keyof ElectronHostEventMap>(event: E, payload: ElectronHostEventMap[E]): void;
105
+ close(): Promise<void>;
106
+ }
107
+
108
+ export function serveElectronNotebookHost(options: {
109
+ port: ElectronMainPort;
110
+ relay: ElectronRelaySession;
111
+ handler: ElectronNotebookHostHandler;
112
+ }): ElectronNotebookHostServer;
package/src/index.cjs CHANGED
@@ -9,6 +9,7 @@
9
9
 
10
10
  const binding = require("./binding.cjs");
11
11
  const { Session } = require("./session.cjs");
12
+ const relay = require("./relay.cjs");
12
13
 
13
14
  async function createNotebook(options) {
14
15
  return new Session(await binding.createNotebook(options));
@@ -18,10 +19,16 @@ async function openNotebook(notebookId, options) {
18
19
  return new Session(await binding.openNotebook(notebookId, options));
19
20
  }
20
21
 
22
+ async function openNotebookPath(path, options) {
23
+ return new Session(await binding.openNotebookPath(path, options));
24
+ }
25
+
21
26
  module.exports = {
22
27
  ...binding,
23
28
  createNotebook,
24
29
  openNotebook,
30
+ openNotebookPath,
25
31
  NativeSession: binding.Session,
26
32
  Session,
33
+ ...relay,
27
34
  };
package/src/index.d.ts CHANGED
@@ -1,5 +1,16 @@
1
1
  import type { Observable } from "rxjs";
2
2
 
3
+ export { RelaySession, connectRelay, createRelay, openRelayPath } from "./relay";
4
+ export type {
5
+ CommentsNotebookRef,
6
+ CreateRelayOptions,
7
+ DaemonInfo,
8
+ OpenRelayOptions,
9
+ QueryDaemonOptions,
10
+ RelayFrame,
11
+ RelayInfo,
12
+ } from "./relay";
13
+
3
14
  export type NotebookDocPhase = "pending" | "syncing" | "interactive";
4
15
  export type RuntimeStatePhase = "pending" | "syncing" | "ready";
5
16
 
@@ -267,6 +278,7 @@ export function defaultSocketPath(): string;
267
278
  export function socketPathForChannel(channel: "stable" | "nightly"): string;
268
279
  export function createNotebook(options?: CreateNotebookOptions): Promise<Session>;
269
280
  export function openNotebook(notebookId: string, options?: OpenNotebookOptions): Promise<Session>;
281
+ export function openNotebookPath(path: string, options?: OpenNotebookOptions): Promise<Session>;
270
282
  export function getExecutionResult(
271
283
  executionId: string,
272
284
  options?: { socketPath?: string },
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * JavaScript-facing relay wrapper over the native `NativeRelaySession`.
5
+ *
6
+ * The native side owns the daemon connection and delivers ordered, lossless
7
+ * typed frames. This wrapper only fans those frames out to host listeners and
8
+ * normalizes ArrayBuffer views for N-API.
9
+ */
10
+ class RelaySession {
11
+ constructor(nativeSession) {
12
+ this._native = nativeSession;
13
+ this._frameListeners = new Set();
14
+ this._pendingFrames = [];
15
+ this._drainingPending = false;
16
+ this._closeListeners = new Set();
17
+ this._closeEmitted = false;
18
+ this._subscription = nativeSession.subscribeFrames(
19
+ (frame) => {
20
+ if (this._frameListeners.size === 0 || this._drainingPending) {
21
+ this._pendingFrames.push(frame);
22
+ return;
23
+ }
24
+ for (const listener of Array.from(this._frameListeners)) listener(frame);
25
+ },
26
+ () => this._emitClose(),
27
+ );
28
+ }
29
+
30
+ get notebookId() {
31
+ return this._native.notebookId;
32
+ }
33
+
34
+ get info() {
35
+ return normalizeRelayInfo(this._native.info);
36
+ }
37
+
38
+ get closed() {
39
+ return this._closeEmitted || this._native.closed;
40
+ }
41
+
42
+ send(frame) {
43
+ return this._native.send(toBuffer(frame));
44
+ }
45
+
46
+ onFrame(listener) {
47
+ if (typeof listener !== "function") throw new TypeError("frame listener must be a function");
48
+ if (this.closed) throw new Error("Relay is closed");
49
+ this._frameListeners.add(listener);
50
+ this._drainingPending = true;
51
+ try {
52
+ while (this._pendingFrames.length > 0) {
53
+ const pending = this._pendingFrames;
54
+ this._pendingFrames = [];
55
+ for (const frame of pending) listener(frame);
56
+ }
57
+ } finally {
58
+ this._drainingPending = false;
59
+ }
60
+ return () => this._frameListeners.delete(listener);
61
+ }
62
+
63
+ onClose(listener) {
64
+ if (typeof listener !== "function") throw new TypeError("close listener must be a function");
65
+ if (this.closed) {
66
+ queueMicrotask(listener);
67
+ return () => {};
68
+ }
69
+ this._closeListeners.add(listener);
70
+ return () => this._closeListeners.delete(listener);
71
+ }
72
+
73
+ async close() {
74
+ if (this._native.closed) {
75
+ this._emitClose();
76
+ return;
77
+ }
78
+ this._native.close();
79
+ this._emitClose();
80
+ }
81
+
82
+ _emitClose() {
83
+ if (this._closeEmitted) return;
84
+ this._closeEmitted = true;
85
+ this._frameListeners.clear();
86
+ this._pendingFrames = [];
87
+ this._drainingPending = false;
88
+ for (const listener of Array.from(this._closeListeners)) listener();
89
+ this._closeListeners.clear();
90
+ this._subscription?.dispose?.();
91
+ this._subscription = null;
92
+ }
93
+ }
94
+
95
+ function toBuffer(frame) {
96
+ if (Buffer.isBuffer(frame)) return frame;
97
+ if (frame instanceof ArrayBuffer) return Buffer.from(frame);
98
+ if (ArrayBuffer.isView(frame)) {
99
+ return Buffer.from(frame.buffer, frame.byteOffset, frame.byteLength);
100
+ }
101
+ throw new TypeError("relay frame must be a Buffer, ArrayBuffer view, or ArrayBuffer");
102
+ }
103
+
104
+ function normalizeRelayInfo(info) {
105
+ const { commentsNotebookRefJson, ...rest } = info;
106
+ let commentsNotebookRef = null;
107
+ if (commentsNotebookRefJson) {
108
+ try {
109
+ commentsNotebookRef = JSON.parse(commentsNotebookRefJson);
110
+ } catch {
111
+ // Treat malformed optional metadata as unavailable. Frame transport and
112
+ // notebook synchronization do not depend on this presentation hint.
113
+ }
114
+ }
115
+ return { ...rest, commentsNotebookRef };
116
+ }
117
+
118
+ module.exports = { RelaySession, normalizeRelayInfo, toBuffer };
package/src/relay.cjs ADDED
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+
3
+ const binding = require("./binding.cjs");
4
+ const { RelaySession } = require("./relay-session.cjs");
5
+
6
+ async function createRelay(options) {
7
+ return new RelaySession(await binding.createRelay(options));
8
+ }
9
+
10
+ async function openRelayPath(path, options) {
11
+ return new RelaySession(await binding.openRelayPath(path, options));
12
+ }
13
+
14
+ async function connectRelay(notebookId, options) {
15
+ return new RelaySession(await binding.connectRelay(notebookId, options));
16
+ }
17
+
18
+ async function queryDaemonInfo(options) {
19
+ return binding.queryDaemonInfo(options);
20
+ }
21
+
22
+ module.exports = {
23
+ RelaySession,
24
+ createRelay,
25
+ openRelayPath,
26
+ connectRelay,
27
+ queryDaemonInfo,
28
+ defaultSocketPath: binding.defaultSocketPath,
29
+ socketPathForChannel: binding.socketPathForChannel,
30
+ };
package/src/relay.d.ts ADDED
@@ -0,0 +1,86 @@
1
+ export type RuntimeKind = "python" | "deno" | (string & {});
2
+ export type PackageManager = "uv" | "conda" | "pixi";
3
+ export type CreateNotebookEnvironmentMode = "auto" | "project" | "notebook";
4
+
5
+ export type CommentsNotebookRef =
6
+ | { kind: "hosted_room"; room_locator: string }
7
+ | { kind: "local_path"; canonical_path: string }
8
+ | { kind: "local_room"; room_id: string };
9
+
10
+ export interface CreateRelayOptions {
11
+ runtime?: RuntimeKind;
12
+ workingDir?: string;
13
+ socketPath?: string;
14
+ notebookId?: string;
15
+ peerLabel?: string;
16
+ description?: string;
17
+ ephemeral?: boolean;
18
+ dependencies?: string[];
19
+ packageManager?: PackageManager;
20
+ environmentMode?: CreateNotebookEnvironmentMode;
21
+ }
22
+
23
+ export interface OpenRelayOptions {
24
+ socketPath?: string;
25
+ peerLabel?: string;
26
+ description?: string;
27
+ }
28
+
29
+ export interface QueryDaemonOptions {
30
+ socketPath?: string;
31
+ }
32
+
33
+ export interface DaemonInfo {
34
+ version: string;
35
+ socketPath: string;
36
+ isDevMode: boolean;
37
+ blobPort?: number;
38
+ }
39
+
40
+ export interface RelayInfo {
41
+ notebookId: string;
42
+ cellCount?: number;
43
+ needsTrustApproval?: boolean;
44
+ ephemeral?: boolean;
45
+ notebookPath?: string;
46
+ runtime?: string;
47
+ actorLabel?: string;
48
+ connectionScope?: string;
49
+ commentsDocId?: string;
50
+ commentsNotebookRef: CommentsNotebookRef | null;
51
+ protocol: string;
52
+ protocolVersion?: number;
53
+ /** Exact notebook-handshake identity; never filled from a later pool query. */
54
+ daemonVersion?: string;
55
+ socketPath: string;
56
+ blobPort?: number;
57
+ isDevMode: boolean;
58
+ }
59
+
60
+ export type RelayFrame = Buffer | Uint8Array | DataView | ArrayBuffer;
61
+
62
+ /**
63
+ * Native, host-neutral byte pipe for one browser/WASM notebook peer.
64
+ * Frames include the one-byte typed-frame discriminator and no length prefix.
65
+ */
66
+ export class RelaySession {
67
+ readonly notebookId: string;
68
+ readonly info: RelayInfo;
69
+ readonly closed: boolean;
70
+ send(frame: RelayFrame): Promise<void>;
71
+ onFrame(listener: (frame: Buffer) => void): () => void;
72
+ onClose(listener: () => void): () => void;
73
+ /** Terminal cancellation. Buffered frames not yet observed by a listener are discarded. */
74
+ close(): Promise<void>;
75
+ }
76
+
77
+ export function createRelay(options?: CreateRelayOptions): Promise<RelaySession>;
78
+ export function openRelayPath(path: string, options?: OpenRelayOptions): Promise<RelaySession>;
79
+ /** Operator connection: the embedding host must authorize notebookId before calling. */
80
+ export function connectRelay(notebookId: string, options?: OpenRelayOptions): Promise<RelaySession>;
81
+ /** Resolve the daemon endpoint selected by the runtimed environment. */
82
+ export function defaultSocketPath(): string;
83
+ /** Resolve a stable or nightly daemon endpoint independently of this package's build channel. */
84
+ export function socketPathForChannel(channel: "stable" | "nightly"): string;
85
+ /** Return null until the selected daemon is ready to answer pool requests. */
86
+ export function queryDaemonInfo(options?: QueryDaemonOptions): Promise<DaemonInfo | null>;