@code-yeongyu/senpi-codemode 2026.11.29-4 → 2026.11.30
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/CHANGELOG.md +14 -0
- package/README.md +1 -1
- package/package.json +5 -5
- package/src/bridge/protocol.ts +9 -0
- package/src/config/memory-settings.ts +4 -1
- package/src/extension/idle-parking-kernel.ts +40 -17
- package/src/extension/session-manager.ts +1 -2
- package/src/kernels/js/context-manager.ts +13 -0
- package/src/kernels/js/permission-runtime.js +2 -0
- package/src/kernels/js/process-control-channel.js +52 -0
- package/src/kernels/js/process-entry.js +29 -16
- package/src/kernels/js/retire-offer.js +33 -0
- package/src/kernels/js/worker-core.d.ts +2 -0
- package/src/kernels/js/worker-core.js +15 -0
- package/src/kernels/js/worker-slot.ts +44 -3
- package/src/kernels/shared/subprocess-queue.ts +1 -0
- package/src/tool/types.ts +6 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [2026.11.30] - 2026-11-30
|
|
4
|
+
|
|
5
|
+
### Breaking Changes
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
|
|
11
|
+
- An idle JavaScript eval kernel gives its memory back after 30 minutes by default, but only when nothing a cell started (a server, a timer, a child process, a socket) is still alive in it. A kernel holding such work stays, state intact. `memory.idleParkMinutes: 0` turns this off ([#7773](https://github.com/code-yeongyu/senpi/pull/7773), part of [#7770](https://github.com/code-yeongyu/senpi/issues/7770))
|
|
12
|
+
|
|
13
|
+
### Fixed
|
|
14
|
+
|
|
15
|
+
### Removed
|
|
16
|
+
|
|
3
17
|
## [2026.11.29-4] - 2026-11-29
|
|
4
18
|
|
|
5
19
|
### Breaking Changes
|
package/README.md
CHANGED
|
@@ -343,7 +343,7 @@ Configuration is loaded in this order:
|
|
|
343
343
|
| `memory.ceilingMb` | a quarter of physical memory, 2048-8192 | Every kernel (JS heap and Python footprint after a collection; Ruby and Julia interpreter footprint read by the host after each result, without a globals list): when live memory reaches this size, the result says so and the kernel restarts once no cell is running or queued on it; the next result says it was restarted (`details.memory.recycled`). `0` disables. Env override: `SENPI_CODEMODE_MEMORY_CEILING_MB`. Non-zero memory thresholds must satisfy watermark <= notice <= ceiling, otherwise all three use their defaults. |
|
|
344
344
|
| `memory.retainedResultsMb` | `32` | In-memory byte budget (MiB) for the settled cells kept for `peek`/`list`, on top of the 32-cell count cap; the oldest go first and the newest is always kept. `0` keeps only the count cap. Env override: `SENPI_CODEMODE_RETAINED_RESULTS_MB` (a non-negative integer). |
|
|
345
345
|
| `memory.retainedImagesMb` | `256` | Disk budget (MiB) for settled-cell images. Images of settled cells (foreground and detached) are written as base64 files under `<session artifacts>/settled-images/` instead of staying in memory, and `peek` reads them back, so it returns the full result. Beyond the budget the oldest files are deleted first; an evicted cell's files are deleted with it; the directory is removed when the session ends. A `peek` whose image file is gone returns the text plus a one-line note. `0` keeps only the count cap. Env override: `SENPI_CODEMODE_RETAINED_IMAGES_MB` (a non-negative integer). |
|
|
346
|
-
| `memory.idleParkMinutes` |
|
|
346
|
+
| `memory.idleParkMinutes` | unset | Minutes with no cell running or queued before a kernel gives its memory back; the next cell for that language starts a fresh kernel, and that cell's result says the kernel was restarted and every earlier global is lost. Unset: the JavaScript kernel retires after 30 idle minutes, but only when nothing a cell started is still alive in it (a server, a timer, a child process, a socket); otherwise it stays as it is and the 30 minutes start over. Python, Ruby and Julia kernels are never closed. `0`: no kernel is ever closed. A number greater than 0: that many minutes for every language; JavaScript still retires only when nothing is alive in it, while Python, Ruby and Julia kernels are closed whatever they hold. |
|
|
347
347
|
| `languages.pyInterpreter` | unset | Explicit Python interpreter path: the Python kernel runs exactly that executable (a path with spaces is fine). A path that does not answer `--version` makes Python unavailable for the session, with a warning naming the setting. Unset keeps `PATH` detection. |
|
|
348
348
|
| `environments.managedRoot` | unset | Root directory for managed per-session environments; unset uses the session's default location. |
|
|
349
349
|
| `environments.autoProvision` | `true` | Lets installs provision a managed environment. `false` makes installs refuse with `environment_installer_unavailable`. |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@code-yeongyu/senpi-codemode",
|
|
3
|
-
"version": "2026.11.
|
|
3
|
+
"version": "2026.11.30",
|
|
4
4
|
"description": "Source-only senpi extension package for codemode evaluation tools",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.ts",
|
|
@@ -33,16 +33,16 @@
|
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
35
|
"@babel/parser": "8.0.4",
|
|
36
|
-
"@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.11.
|
|
37
|
-
"@earendil-works/pi-realm-registry": "npm:@code-yeongyu/senpi-realm-registry@2026.11.
|
|
36
|
+
"@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.11.30",
|
|
37
|
+
"@earendil-works/pi-realm-registry": "npm:@code-yeongyu/senpi-realm-registry@2026.11.30",
|
|
38
38
|
"quickjs-wasi": "3.6.2",
|
|
39
39
|
"typebox": "1.3.34"
|
|
40
40
|
},
|
|
41
41
|
"peerDependencies": {
|
|
42
|
-
"@code-yeongyu/senpi": "2026.11.
|
|
42
|
+
"@code-yeongyu/senpi": "2026.11.30"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
|
-
"@code-yeongyu/senpi": "2026.11.
|
|
45
|
+
"@code-yeongyu/senpi": "2026.11.30"
|
|
46
46
|
},
|
|
47
47
|
"keywords": [
|
|
48
48
|
"senpi",
|
package/src/bridge/protocol.ts
CHANGED
|
@@ -93,6 +93,13 @@ const hostToKernelMessageSchema = Type.Union([
|
|
|
93
93
|
Type.Object({
|
|
94
94
|
type: Type.Literal("close"),
|
|
95
95
|
}),
|
|
96
|
+
/**
|
|
97
|
+
* JS only, sent only with no cell running or queued: the kernel stops holding its event loop open for the host. With
|
|
98
|
+
* nothing else alive in it the runtime ends the kernel; otherwise the kernel answers `retire-declined` and stays.
|
|
99
|
+
*/
|
|
100
|
+
Type.Object({
|
|
101
|
+
type: Type.Literal("retire-offer"),
|
|
102
|
+
}),
|
|
96
103
|
/** JS only: the kernel's private port to the main-thread Bun.WebView service, sent in the transfer list. */
|
|
97
104
|
Type.Object({
|
|
98
105
|
type: Type.Literal("webview-port"),
|
|
@@ -168,6 +175,8 @@ const kernelToHostMessageSchema = Type.Union([
|
|
|
168
175
|
kernelState: Type.Optional(kernelStateSchema),
|
|
169
176
|
}),
|
|
170
177
|
Type.Object({ type: Type.Literal("closed") }),
|
|
178
|
+
/** JS only: the answer to `retire-offer` when something is still alive in the kernel; it stays, state intact. */
|
|
179
|
+
Type.Object({ type: Type.Literal("retire-declined") }),
|
|
171
180
|
Type.Object({ type: Type.Literal("webview-connect"), requestId: Type.String({ minLength: 1 }) }),
|
|
172
181
|
...kernelToolKernelToHostSchemas,
|
|
173
182
|
...kernelMemoryQueryKernelToHostSchemas,
|
|
@@ -31,7 +31,10 @@ export interface CodemodeMemorySettings {
|
|
|
31
31
|
readonly retainedResultsMb: number;
|
|
32
32
|
/** Disk budget (MiB) for settled-cell images spilled under the session artifacts dir; 0 keeps only the count cap. */
|
|
33
33
|
readonly retainedImagesMb: number;
|
|
34
|
-
/**
|
|
34
|
+
/**
|
|
35
|
+
* Minutes with no cell running or queued before a kernel gives its memory back and restarts on the next cell. Absent:
|
|
36
|
+
* 30 for a kernel that can tell whether anything is alive in it (JavaScript), never for the others. 0: never.
|
|
37
|
+
*/
|
|
35
38
|
readonly idleParkMinutes?: number;
|
|
36
39
|
}
|
|
37
40
|
|
|
@@ -12,6 +12,13 @@ import { hasKernelTools, type KernelToolsMethods } from "./kernel-tools-probe.ts
|
|
|
12
12
|
|
|
13
13
|
export type RestartParkedKernel = () => Promise<EvalKernel>;
|
|
14
14
|
|
|
15
|
+
/**
|
|
16
|
+
* The idle window for a kernel that can tell whether anything is alive in it, when `memory.idleParkMinutes` is unset.
|
|
17
|
+
* It equals the RPC host's idle-session window (`DEFAULT_SESSION_IDLE_EVICTION_MS` in coding-agent's
|
|
18
|
+
* `host-idle-policy.ts`): in-memory state lives 30 idle minutes whether or not something else keeps the session loaded.
|
|
19
|
+
*/
|
|
20
|
+
const DEFAULT_RETIRE_IDLE_MINUTES = 30;
|
|
21
|
+
|
|
15
22
|
class IdleParkingKernelClosedError extends Error {
|
|
16
23
|
readonly name = "IdleParkingKernelClosedError";
|
|
17
24
|
|
|
@@ -25,11 +32,12 @@ interface WaitingCell {
|
|
|
25
32
|
}
|
|
26
33
|
|
|
27
34
|
/**
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
35
|
+
* Once no cell has been running or queued on the session's kernel for the idle window, gives its memory back and
|
|
36
|
+
* starts a fresh kernel when the next cell arrives; that cell's result says the kernel was restarted and every global
|
|
37
|
+
* is gone. A kernel with `retireIfIdle` is only offered retirement: one that something a cell left still keeps alive
|
|
38
|
+
* declines, stays as it is, and the window starts over. Any other kernel is closed. A cell submitted while the kernel
|
|
39
|
+
* is being offered, parked or restarted waits for the outcome; a restart that fails settles that cell with the
|
|
40
|
+
* reason, and the next cell tries again.
|
|
33
41
|
*/
|
|
34
42
|
export class IdleParkingKernel implements EvalKernel {
|
|
35
43
|
readonly #language: EvalLanguage;
|
|
@@ -226,19 +234,29 @@ export class IdleParkingKernel implements EvalKernel {
|
|
|
226
234
|
this.#arm();
|
|
227
235
|
return;
|
|
228
236
|
}
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
const
|
|
232
|
-
|
|
233
|
-
|
|
237
|
+
// The kernel stays current until it is gone: a declined offer keeps it, and cells wait for the outcome.
|
|
238
|
+
const gone = kernel.retireIfIdle?.() ?? kernel.close().then(() => true);
|
|
239
|
+
const outcome = gone.then(
|
|
240
|
+
(retired) => {
|
|
241
|
+
if (retired) this.#parked();
|
|
242
|
+
},
|
|
243
|
+
(error: unknown) => {
|
|
244
|
+
this.#parked();
|
|
234
245
|
this.#parkFailure = `the idle ${this.#language} kernel could not be stopped: ${errorText(error)}; run the cell again to start a fresh kernel`;
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
246
|
+
},
|
|
247
|
+
);
|
|
248
|
+
const parking = outcome.finally(() => {
|
|
249
|
+
if (this.#parking === parking) this.#parking = null;
|
|
250
|
+
this.#arm();
|
|
251
|
+
});
|
|
239
252
|
this.#parking = parking;
|
|
240
253
|
}
|
|
241
254
|
|
|
255
|
+
#parked(): void {
|
|
256
|
+
this.#kernel = null;
|
|
257
|
+
this.#onParked();
|
|
258
|
+
}
|
|
259
|
+
|
|
242
260
|
#cancelWaiting(cellId: string, reason: string): boolean {
|
|
243
261
|
const waiting = this.#waiting.get(cellId);
|
|
244
262
|
if (waiting === undefined) return false;
|
|
@@ -249,7 +267,7 @@ export class IdleParkingKernel implements EvalKernel {
|
|
|
249
267
|
|
|
250
268
|
#parkReason(): string {
|
|
251
269
|
const minutes = this.#idleMs / 60_000;
|
|
252
|
-
return `
|
|
270
|
+
return `being idle for ${minutes} minute${minutes === 1 ? "" : "s"} with nothing running in it (memory.idleParkMinutes)`;
|
|
253
271
|
}
|
|
254
272
|
|
|
255
273
|
#restartFailure(error: unknown): string {
|
|
@@ -257,14 +275,19 @@ export class IdleParkingKernel implements EvalKernel {
|
|
|
257
275
|
}
|
|
258
276
|
}
|
|
259
277
|
|
|
278
|
+
/**
|
|
279
|
+
* `idleMinutes` is `memory.idleParkMinutes`: unset wraps only a kernel that can tell whether anything is alive in it,
|
|
280
|
+
* with the default window; 0 wraps nothing; N wraps every kernel with window N.
|
|
281
|
+
*/
|
|
260
282
|
export function parkWhenIdle(
|
|
261
283
|
language: EvalLanguage,
|
|
262
|
-
idleMinutes: number,
|
|
284
|
+
idleMinutes: number | undefined,
|
|
263
285
|
kernel: EvalKernel,
|
|
264
286
|
restart: RestartParkedKernel,
|
|
265
287
|
onParked?: () => void,
|
|
266
288
|
): EvalKernel {
|
|
267
|
-
|
|
289
|
+
const minutes = idleMinutes ?? (kernel.retireIfIdle === undefined ? 0 : DEFAULT_RETIRE_IDLE_MINUTES);
|
|
290
|
+
return minutes > 0 ? new IdleParkingKernel(language, minutes, kernel, restart, onParked) : kernel;
|
|
268
291
|
}
|
|
269
292
|
|
|
270
293
|
function errorText(error: unknown): string {
|
|
@@ -220,10 +220,9 @@ class DefaultCodemodeSessionManager implements CodemodeSessionManager {
|
|
|
220
220
|
): Promise<EvalKernel> {
|
|
221
221
|
await assertSessionCwdAvailable(this.#options.cwd);
|
|
222
222
|
const started = await this.#startLanguageKernel(language, onMessage);
|
|
223
|
-
const idleParkMinutes = this.#options.settings.memory?.idleParkMinutes ?? 0;
|
|
224
223
|
const resolvedKernel = parkWhenIdle(
|
|
225
224
|
language,
|
|
226
|
-
idleParkMinutes,
|
|
225
|
+
this.#options.settings.memory?.idleParkMinutes,
|
|
227
226
|
started.kernel,
|
|
228
227
|
async () => {
|
|
229
228
|
const restarted = await this.#startLanguageKernel(language, onMessage);
|
|
@@ -189,6 +189,19 @@ export class JavaScriptKernel {
|
|
|
189
189
|
return await this.#toolCalls.next();
|
|
190
190
|
}
|
|
191
191
|
|
|
192
|
+
/**
|
|
193
|
+
* Offers an idle kernel retirement. True: nothing was alive in it, so its runtime ended and the kernel is closed as
|
|
194
|
+
* by `close()`. False: something a cell left (a server, a timer, a child, a socket) is alive, or a cell is running
|
|
195
|
+
* or queued; the kernel stays, state intact. The runtime's own event loop decides, not a list kept here.
|
|
196
|
+
*/
|
|
197
|
+
async retireIfIdle(): Promise<boolean> {
|
|
198
|
+
const busy = this.#runs.active !== null || this.#runs.hasWaiting || this.#activation !== null;
|
|
199
|
+
if (this.#lifecycle !== "open" || busy || this.#recovery.inFlight !== null) return false;
|
|
200
|
+
if (!(await this.#slot.offerRetire())) return false;
|
|
201
|
+
await this.close();
|
|
202
|
+
return true;
|
|
203
|
+
}
|
|
204
|
+
|
|
192
205
|
async close(): Promise<void> {
|
|
193
206
|
if (this.#closePromise) return await this.#closePromise;
|
|
194
207
|
this.#slot.postMessage({ type: "close" });
|
|
@@ -197,6 +197,8 @@ export async function initializePermissionRuntime(install, workerData, engine) {
|
|
|
197
197
|
send: (message) => parentPort.postMessage(message),
|
|
198
198
|
onMessage(handler) { parentPort.on("message", handler); return () => parentPort.off("message", handler); },
|
|
199
199
|
close() { parentPort.close(); setTimeout(() => process.exit(0), 0); },
|
|
200
|
+
// The listener stays attached, so nothing the host sends is lost; only the port's hold on the loop goes.
|
|
201
|
+
release() { parentPort.unref(); return () => parentPort.ref(); },
|
|
200
202
|
}, {
|
|
201
203
|
cwd: workerData.cwd,
|
|
202
204
|
parallelPoolWidth: workerData.parallelPoolWidth,
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { createReadStream } from "node:fs";
|
|
2
|
+
import { createInterface } from "node:readline";
|
|
3
|
+
import { Worker } from "node:worker_threads";
|
|
4
|
+
|
|
5
|
+
const CONTROL_READER = `const { readSync } = require("node:fs");
|
|
6
|
+
const { StringDecoder } = require("node:string_decoder");
|
|
7
|
+
const { parentPort, workerData } = require("node:worker_threads");
|
|
8
|
+
const pause = new Int32Array(new SharedArrayBuffer(4));
|
|
9
|
+
const decoder = new StringDecoder("utf8");
|
|
10
|
+
const buffer = Buffer.alloc(1 << 16);
|
|
11
|
+
for (;;) {
|
|
12
|
+
let read;
|
|
13
|
+
try {
|
|
14
|
+
read = readSync(workerData.fd, buffer, 0, buffer.length, null);
|
|
15
|
+
} catch (error) {
|
|
16
|
+
if (error && error.code === "EAGAIN") { Atomics.wait(pause, 0, 0, 2); continue; }
|
|
17
|
+
read = 0;
|
|
18
|
+
}
|
|
19
|
+
if (read === 0) break;
|
|
20
|
+
parentPort.postMessage(decoder.write(buffer.subarray(0, read)));
|
|
21
|
+
}
|
|
22
|
+
parentPort.postMessage(null);`;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Reads the process kernel's control channel line by line and calls `onEnd` at end-of-file (the host is gone).
|
|
26
|
+
*
|
|
27
|
+
* On a private fd the channel is read on its own thread, which is returned: a retire offer unrefs it, so the channel
|
|
28
|
+
* no longer keeps the process alive, and refs it again on a decline. A stream on the fd could not let go of the loop
|
|
29
|
+
* without being closed (senpi#7770). Where fd 0 is the channel itself the stream stays and null is returned: that
|
|
30
|
+
* kernel always declines an offer.
|
|
31
|
+
*/
|
|
32
|
+
export function openControlChannel(fd, onLine, onEnd) {
|
|
33
|
+
if (fd === 0) {
|
|
34
|
+
const stream = createReadStream("", { fd });
|
|
35
|
+
createInterface({ input: stream }).on("line", onLine);
|
|
36
|
+
stream.once("end", onEnd);
|
|
37
|
+
stream.once("close", onEnd);
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
const thread = new Worker(CONTROL_READER, { eval: true, workerData: { fd } });
|
|
41
|
+
let carry = "";
|
|
42
|
+
thread.on("message", (chunk) => {
|
|
43
|
+
if (chunk === null) {
|
|
44
|
+
onEnd();
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
const lines = `${carry}${chunk}`.split("\n");
|
|
48
|
+
carry = lines.pop() ?? "";
|
|
49
|
+
for (const line of lines) onLine(line.endsWith("\r") ? line.slice(0, -1) : line);
|
|
50
|
+
});
|
|
51
|
+
return thread;
|
|
52
|
+
}
|
|
@@ -15,11 +15,11 @@
|
|
|
15
15
|
// killed). A watchdog thread also checks the parent pid and kills this process when the host is gone, so a cell
|
|
16
16
|
// that never yields (a busy loop, a blocking call) cannot keep the kernel alive past its host.
|
|
17
17
|
import "./power-throttling-startup.js";
|
|
18
|
-
import { closeSync,
|
|
18
|
+
import { closeSync, openSync, writeSync } from "node:fs";
|
|
19
19
|
import { createRequire } from "node:module";
|
|
20
|
-
import { createInterface } from "node:readline";
|
|
21
20
|
import { Readable } from "node:stream";
|
|
22
21
|
import { Worker } from "node:worker_threads";
|
|
22
|
+
import { openControlChannel } from "./process-control-channel.js";
|
|
23
23
|
import { scanDrainText } from "./process-drain-scan.js";
|
|
24
24
|
|
|
25
25
|
// Captured before any cell runs, so a cell that later replaces these never sees a frame being built.
|
|
@@ -302,11 +302,8 @@ if (globalThis.Bun !== undefined) {
|
|
|
302
302
|
}
|
|
303
303
|
}
|
|
304
304
|
|
|
305
|
-
const frameReader = createReadStream("", { fd: controlFd });
|
|
306
|
-
const frameLines = createInterface({ input: frameReader });
|
|
307
305
|
// End-of-file on the control channel means the host is gone (closed, exited or killed): never outlive it.
|
|
308
|
-
|
|
309
|
-
frameReader.once("close", () => exit(0));
|
|
306
|
+
const controlThread = openControlChannel(controlFd, onControlLine, () => exit(0));
|
|
310
307
|
// The same, from a thread a running cell cannot block: once the parent pid changes the host is gone.
|
|
311
308
|
const WATCHDOG = `const { workerData } = require("node:worker_threads");
|
|
312
309
|
setInterval(() => {
|
|
@@ -325,17 +322,19 @@ function deliver(message) {
|
|
|
325
322
|
if (lineHandler === undefined) bufferedLines.push(message);
|
|
326
323
|
else lineHandler(message);
|
|
327
324
|
}
|
|
325
|
+
let tokenArrived;
|
|
328
326
|
const tokenReceived = new Promise((resolve) => {
|
|
329
|
-
|
|
330
|
-
if (frameToken === undefined) {
|
|
331
|
-
frameToken = line;
|
|
332
|
-
resolve();
|
|
333
|
-
return;
|
|
334
|
-
}
|
|
335
|
-
if (line.length === 0) return;
|
|
336
|
-
deliver(JSON.parse(line));
|
|
337
|
-
});
|
|
327
|
+
tokenArrived = resolve;
|
|
338
328
|
});
|
|
329
|
+
function onControlLine(line) {
|
|
330
|
+
if (frameToken === undefined) {
|
|
331
|
+
frameToken = line;
|
|
332
|
+
tokenArrived();
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
if (line.length === 0) return;
|
|
336
|
+
deliver(JSON.parse(line));
|
|
337
|
+
}
|
|
339
338
|
|
|
340
339
|
const transport = {
|
|
341
340
|
send(message) {
|
|
@@ -351,11 +350,23 @@ const transport = {
|
|
|
351
350
|
onMessage(handler) {
|
|
352
351
|
lineHandler = handler;
|
|
353
352
|
for (const message of bufferedLines.splice(0)) handler(message);
|
|
354
|
-
return () =>
|
|
353
|
+
return () => {
|
|
354
|
+
lineHandler = undefined;
|
|
355
|
+
};
|
|
355
356
|
},
|
|
356
357
|
close() {
|
|
357
358
|
setTimeout(() => exit(0), 0);
|
|
358
359
|
},
|
|
360
|
+
// The control and output threads stop holding the process open; the watchdog thread never does.
|
|
361
|
+
release() {
|
|
362
|
+
if (controlThread === null) return () => {};
|
|
363
|
+
controlThread.unref();
|
|
364
|
+
outputThread?.unref();
|
|
365
|
+
return () => {
|
|
366
|
+
controlThread.ref();
|
|
367
|
+
outputThread?.ref();
|
|
368
|
+
};
|
|
369
|
+
},
|
|
359
370
|
};
|
|
360
371
|
|
|
361
372
|
await tokenReceived;
|
|
@@ -408,6 +419,7 @@ for (;;) {
|
|
|
408
419
|
else sendText(part.text);
|
|
409
420
|
}
|
|
410
421
|
}`;
|
|
422
|
+
let outputThread = null;
|
|
411
423
|
if (textPipe !== null) {
|
|
412
424
|
const reader = new Worker(DRAINER, {
|
|
413
425
|
eval: true,
|
|
@@ -424,6 +436,7 @@ if (textPipe !== null) {
|
|
|
424
436
|
pendingResults.delete(key);
|
|
425
437
|
if (result !== undefined) sendFrame(result);
|
|
426
438
|
});
|
|
439
|
+
outputThread = reader;
|
|
427
440
|
}
|
|
428
441
|
|
|
429
442
|
// The crash cause reaches the host on stderr, tagged with the token, before the kernel ends (worker mode reports it
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// How long a retire offer leaves the event loop to the cells' own work. An idle runtime ends within a few ms; one
|
|
2
|
+
// that has not ended by then is treated as occupied, which only ever keeps a kernel (senpi#7770).
|
|
3
|
+
const RETIRE_OFFER_WINDOW_MS = 200;
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The kernel side of a retire offer. `offer()` stops the transport holding the event loop open for the host; anything
|
|
7
|
+
* a cell left alive (a server, a timer, a child, a socket) still holds it. With nothing alive the runtime ends the
|
|
8
|
+
* kernel before the unref'd timer fires; otherwise the timer takes the channel back and the kernel declines, its state
|
|
9
|
+
* untouched. `end()` closes an open offer early (a message arrived) and declines it.
|
|
10
|
+
*/
|
|
11
|
+
export function createRetireOffer({ transport, emit, occupied }) {
|
|
12
|
+
let open = null;
|
|
13
|
+
|
|
14
|
+
function end() {
|
|
15
|
+
if (open === null) return;
|
|
16
|
+
clearTimeout(open.back);
|
|
17
|
+
open.restore();
|
|
18
|
+
open = null;
|
|
19
|
+
emit({ type: "retire-declined" });
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function offer() {
|
|
23
|
+
if (open !== null || occupied()) {
|
|
24
|
+
emit({ type: "retire-declined" });
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
const back = setTimeout(end, RETIRE_OFFER_WINDOW_MS);
|
|
28
|
+
back.unref?.();
|
|
29
|
+
open = { restore: transport.release(), back };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return { offer, end };
|
|
33
|
+
}
|
|
@@ -5,6 +5,8 @@ export interface WorkerCoreTransport {
|
|
|
5
5
|
send(message: KernelToHostMessage): void;
|
|
6
6
|
onMessage(handler: (message: HostToKernelMessage) => void): () => void;
|
|
7
7
|
close(): void;
|
|
8
|
+
/** Stops holding the event loop open for the host (a retire offer); the returned function holds it again. */
|
|
9
|
+
release(): () => void;
|
|
8
10
|
}
|
|
9
11
|
|
|
10
12
|
export interface WorkerCoreOptions {
|
|
@@ -8,6 +8,7 @@ import { installSessionCwd } from "./worker-cwd.js";
|
|
|
8
8
|
import { installPackageResolver } from "./worker-package-resolve.js";
|
|
9
9
|
import { createHeapProbe } from "./worker-heap.js";
|
|
10
10
|
import { createRejectionReports } from "./rejection-reports.js";
|
|
11
|
+
import { createRetireOffer } from "./retire-offer.js";
|
|
11
12
|
import { createWorkerMemory } from "./worker-memory.js";
|
|
12
13
|
import { JsWorkerRuntime } from "./worker-runtime.js";
|
|
13
14
|
import { installKernelWebView } from "./worker-webview.js";
|
|
@@ -158,7 +159,21 @@ export function createWorkerCore(transport, options) {
|
|
|
158
159
|
emit({ type: "status", event: { op: INTERRUPT_ACK_OP, cellId: activeCell.cellId, shellWaitActive: runtime.shellWaitActive } });
|
|
159
160
|
}
|
|
160
161
|
|
|
162
|
+
// A tool a cell defined stays callable between cells, so its kernel is never retired.
|
|
163
|
+
const retire = createRetireOffer({
|
|
164
|
+
transport,
|
|
165
|
+
emit,
|
|
166
|
+
occupied: () =>
|
|
167
|
+
activeCell !== null || pendingTools.size > 0 || nestedInvokes.size > 0 || (runtime?.kernelTools.defined().length ?? 0) > 0,
|
|
168
|
+
});
|
|
169
|
+
|
|
161
170
|
function onMessage(message) {
|
|
171
|
+
// The host holds every message back while an offer is open; one arriving anyway ends the offer first.
|
|
172
|
+
retire.end();
|
|
173
|
+
if (message.type === "retire-offer") {
|
|
174
|
+
retire.offer();
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
162
177
|
if (message.type === "run" || message.type === "interrupt" || message.type === "close") memory?.cancelIdle();
|
|
163
178
|
if (kernelTools.handle(message)) return;
|
|
164
179
|
if (message.type === "kernel-tools-names") {
|
|
@@ -9,6 +9,16 @@ import { KernelWebViewClients } from "./webview-host.ts";
|
|
|
9
9
|
import { WorkerStartupCancelledError } from "./worker-host.ts";
|
|
10
10
|
import { startWorkerWithInlineFallback } from "./worker-startup.ts";
|
|
11
11
|
|
|
12
|
+
interface HeldMessage {
|
|
13
|
+
readonly message: HostToKernelMessage;
|
|
14
|
+
readonly transfer: readonly MessagePort[] | undefined;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
interface RetireOffer {
|
|
18
|
+
readonly held: HeldMessage[];
|
|
19
|
+
settle(retired: boolean): void;
|
|
20
|
+
}
|
|
21
|
+
|
|
12
22
|
export interface WorkerSlotListeners {
|
|
13
23
|
isOpen(): boolean;
|
|
14
24
|
onMessage(message: KernelToHostMessage): void;
|
|
@@ -27,6 +37,7 @@ export class WorkerSlot {
|
|
|
27
37
|
#generation = 0;
|
|
28
38
|
#ready: Promise<void> | null = null;
|
|
29
39
|
#startupAbort: AbortController | null = null;
|
|
40
|
+
#offer: RetireOffer | null = null;
|
|
30
41
|
|
|
31
42
|
constructor(options: JavaScriptKernelOptions, listeners: WorkerSlotListeners, permissions?: KernelPermissionHost) {
|
|
32
43
|
this.#options = options;
|
|
@@ -57,7 +68,31 @@ export class WorkerSlot {
|
|
|
57
68
|
}
|
|
58
69
|
|
|
59
70
|
postMessage(message: HostToKernelMessage, transfer?: readonly MessagePort[]): void {
|
|
60
|
-
|
|
71
|
+
// A worker that was offered retirement gets nothing until it answers: a message would hold its loop open.
|
|
72
|
+
if (this.#offer !== null) this.#offer.held.push({ message, transfer });
|
|
73
|
+
else this.#worker?.postMessage(message, transfer);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Offers the ready worker retirement: true once it ended itself because nothing was alive in it, false when it
|
|
78
|
+
* declined (it stays as it was, and the messages held meanwhile are sent in order).
|
|
79
|
+
*/
|
|
80
|
+
offerRetire(): Promise<boolean> {
|
|
81
|
+
const worker = this.#worker;
|
|
82
|
+
if (worker === null || this.startingUp || this.#offer !== null) return Promise.resolve(false);
|
|
83
|
+
const answered = Promise.withResolvers<boolean>();
|
|
84
|
+
const offer: RetireOffer = {
|
|
85
|
+
held: [],
|
|
86
|
+
settle: (retired) => {
|
|
87
|
+
if (this.#offer !== offer) return;
|
|
88
|
+
this.#offer = null;
|
|
89
|
+
if (!retired) for (const { message, transfer } of offer.held) worker.postMessage(message, transfer);
|
|
90
|
+
answered.resolve(retired);
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
this.#offer = offer;
|
|
94
|
+
worker.postMessage({ type: "retire-offer" });
|
|
95
|
+
return answered.promise;
|
|
61
96
|
}
|
|
62
97
|
|
|
63
98
|
async ensureReady(): Promise<void> {
|
|
@@ -98,6 +133,8 @@ export class WorkerSlot {
|
|
|
98
133
|
}
|
|
99
134
|
|
|
100
135
|
async retire(): Promise<WorkerRetirement> {
|
|
136
|
+
// The worker is going either way; what an offer held back was meant for it.
|
|
137
|
+
this.#offer?.settle(true);
|
|
101
138
|
this.#generation += 1;
|
|
102
139
|
this.#startupAbort?.abort();
|
|
103
140
|
this.#startupAbort = null;
|
|
@@ -121,10 +158,14 @@ export class WorkerSlot {
|
|
|
121
158
|
this.#webViews = webViews;
|
|
122
159
|
worker.onMessage((message) => {
|
|
123
160
|
if (!this.#isCurrent(worker, generation) || webViews.consume(message)) return;
|
|
124
|
-
this.#
|
|
161
|
+
if (message.type === "retire-declined") this.#offer?.settle(false);
|
|
162
|
+
else this.#listeners.onMessage(message);
|
|
125
163
|
});
|
|
126
164
|
worker.onError((error) => {
|
|
127
|
-
if (this.#isCurrent(worker, generation))
|
|
165
|
+
if (!this.#isCurrent(worker, generation)) return;
|
|
166
|
+
// An offered worker that ends has accepted: nothing was alive in it, so this is no crash.
|
|
167
|
+
if (this.#offer !== null) this.#offer.settle(true);
|
|
168
|
+
else this.#listeners.onCrash(error);
|
|
128
169
|
});
|
|
129
170
|
}
|
|
130
171
|
|
package/src/tool/types.ts
CHANGED
|
@@ -247,6 +247,12 @@ export interface EvalKernel {
|
|
|
247
247
|
isAlive?(): boolean;
|
|
248
248
|
/** Hands over, and forgets, every queued cell of a dead kernel that never started. */
|
|
249
249
|
drainPending?(): readonly PendingCell[];
|
|
250
|
+
/**
|
|
251
|
+
* Ends the kernel only when nothing is alive in it. True: it ended itself and is closed exactly as after `close()`.
|
|
252
|
+
* False: something a cell left is alive, or a cell is running or queued; the kernel stays, state intact. Only a
|
|
253
|
+
* kernel whose runtime can tell (JavaScript) has it.
|
|
254
|
+
*/
|
|
255
|
+
retireIfIdle?(): Promise<boolean>;
|
|
250
256
|
/** Describes this kernel's registered kernel tools; only an in-process JS kernel has them. */
|
|
251
257
|
describeKernelTools?(names: readonly string[]): Promise<KernelToolsDescribeResult>;
|
|
252
258
|
/** Invokes one of this kernel's kernel tools; present exactly when `describeKernelTools` is. */
|