@code-yeongyu/senpi-codemode 2026.11.29 → 2026.11.30-3
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 +74 -0
- package/README.md +1 -1
- package/package.json +5 -5
- package/src/bridge/kernel-tools-protocol.ts +1 -1
- package/src/bridge/protocol.ts +9 -0
- package/src/bridges/agent-bridge.ts +1 -1
- package/src/bridges/handle-bridge.ts +1 -1
- package/src/config/feature-settings.ts +2 -2
- package/src/config/memory-settings.ts +4 -1
- package/src/environments/js-installer.ts +2 -2
- package/src/environments/packages-install.ts +1 -1
- package/src/extension/eval-status.ts +2 -2
- package/src/extension/idle-parking-kernel.ts +40 -17
- package/src/extension/kernel-registration.ts +1 -1
- package/src/extension/removed-tool-hints.ts +1 -1
- package/src/extension/session-manager.ts +1 -2
- package/src/extension/skill-contribution.ts +1 -3
- package/src/handles/handle-args.ts +2 -2
- package/src/handles/wait.ts +2 -2
- package/src/kernels/AGENTS.md +1 -1
- package/src/kernels/js/context-manager.ts +13 -0
- package/src/kernels/js/interrupt-bounds.ts +3 -3
- package/src/kernels/js/kernel-tools-errors.ts +1 -1
- 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/process-tree-host.ts +5 -5
- package/src/kernels/js/process-worker.ts +1 -1
- 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-host.ts +1 -5
- package/src/kernels/js/worker-slot.ts +44 -3
- package/src/kernels/js/worker-startup.ts +1 -1
- package/src/kernels/py/startup.ts +1 -1
- package/src/kernels/shared/bun-ffi.ts +1 -1
- package/src/kernels/shared/kernel-death.ts +1 -1
- package/src/kernels/shared/subprocess-queue.ts +1 -0
- package/src/kernels/shared/subprocess-startup.ts +1 -1
- package/src/output/streaming-output.ts +2 -4
- package/src/prompt/eval-prompt.ts +1 -1
- package/src/timeouts/run-budget.ts +1 -1
- package/src/tool/call-capture.ts +2 -2
- package/src/tool/cell-deadlines.ts +1 -1
- package/src/tool/detached-cell-snapshot.ts +1 -1
- package/src/tool/image-resize.ts +1 -1
- package/src/tool/image.ts +1 -7
- package/src/tool/render-cell.ts +0 -2
- package/src/tool/render-live.ts +1 -2
- package/src/tool/terminal-snapshot-store.ts +2 -2
- package/src/tool/types.ts +6 -0
- package/src/kernels/js/prelude.ts +0 -17
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,79 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [2026.11.30-3] - 2026-11-30
|
|
4
|
+
|
|
5
|
+
### Breaking Changes
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
|
|
13
|
+
### Removed
|
|
14
|
+
|
|
15
|
+
## [2026.11.30-2] - 2026-11-30
|
|
16
|
+
|
|
17
|
+
### Breaking Changes
|
|
18
|
+
|
|
19
|
+
### Added
|
|
20
|
+
|
|
21
|
+
### Changed
|
|
22
|
+
|
|
23
|
+
### Fixed
|
|
24
|
+
|
|
25
|
+
### Removed
|
|
26
|
+
|
|
27
|
+
## [2026.11.30] - 2026-11-30
|
|
28
|
+
|
|
29
|
+
### Breaking Changes
|
|
30
|
+
|
|
31
|
+
### Added
|
|
32
|
+
|
|
33
|
+
### Changed
|
|
34
|
+
|
|
35
|
+
- 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))
|
|
36
|
+
|
|
37
|
+
### Fixed
|
|
38
|
+
|
|
39
|
+
### Removed
|
|
40
|
+
|
|
41
|
+
## [2026.11.29-4] - 2026-11-29
|
|
42
|
+
|
|
43
|
+
### Breaking Changes
|
|
44
|
+
|
|
45
|
+
### Added
|
|
46
|
+
|
|
47
|
+
### Changed
|
|
48
|
+
|
|
49
|
+
### Fixed
|
|
50
|
+
|
|
51
|
+
### Removed
|
|
52
|
+
|
|
53
|
+
## [2026.11.29-3] - 2026-11-29
|
|
54
|
+
|
|
55
|
+
### Breaking Changes
|
|
56
|
+
|
|
57
|
+
### Added
|
|
58
|
+
|
|
59
|
+
### Changed
|
|
60
|
+
|
|
61
|
+
### Fixed
|
|
62
|
+
|
|
63
|
+
### Removed
|
|
64
|
+
|
|
65
|
+
## [2026.11.29-2] - 2026-11-29
|
|
66
|
+
|
|
67
|
+
### Breaking Changes
|
|
68
|
+
|
|
69
|
+
### Added
|
|
70
|
+
|
|
71
|
+
### Changed
|
|
72
|
+
|
|
73
|
+
### Fixed
|
|
74
|
+
|
|
75
|
+
### Removed
|
|
76
|
+
|
|
3
77
|
## [2026.11.29] - 2026-11-29
|
|
4
78
|
|
|
5
79
|
### 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-3",
|
|
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-3",
|
|
37
|
+
"@earendil-works/pi-realm-registry": "npm:@code-yeongyu/senpi-realm-registry@2026.11.30-3",
|
|
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-3"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
|
-
"@code-yeongyu/senpi": "2026.11.
|
|
45
|
+
"@code-yeongyu/senpi": "2026.11.30-3"
|
|
46
46
|
},
|
|
47
47
|
"keywords": [
|
|
48
48
|
"senpi",
|
|
@@ -16,7 +16,7 @@ const kernelToolErrorSchema = Type.Object({
|
|
|
16
16
|
});
|
|
17
17
|
|
|
18
18
|
/** Per-call execution scope for the nested host calls the invoked closure makes (#1731). */
|
|
19
|
-
|
|
19
|
+
const kernelToolInvokeScopeSchema = Type.Object({
|
|
20
20
|
tools: Type.Optional(
|
|
21
21
|
Type.Object({
|
|
22
22
|
allow: Type.Optional(Type.Array(Type.String({ minLength: 1 }))),
|
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,
|
|
@@ -73,7 +73,7 @@ export type EvalAgentResult = (
|
|
|
73
73
|
// The session-owned executor identifies a bridge across JS and HTTP calls; do not retain retired sessions.
|
|
74
74
|
const isolationCapabilities = new WeakMap<AgentExecuteTool, Map<string, boolean>>();
|
|
75
75
|
|
|
76
|
-
|
|
76
|
+
class AgentIsolationNotAppliedError extends Error {
|
|
77
77
|
readonly name = "AgentIsolationNotAppliedError";
|
|
78
78
|
readonly code = "isolation_not_applied";
|
|
79
79
|
|
|
@@ -10,7 +10,7 @@ import { parseOutputArgs, parseRefArgs, parseSendArgs, parseWaitArgs } from "../
|
|
|
10
10
|
import type { HandleBackend, HandleRegistry } from "../handles/handle-registry.ts";
|
|
11
11
|
import { waitForHandles } from "../handles/wait.ts";
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
const HANDLE_TOOL_NAMES = [
|
|
14
14
|
RESERVED_WAIT_TOOL,
|
|
15
15
|
RESERVED_HANDLE_STATUS_TOOL,
|
|
16
16
|
RESERVED_HANDLE_OUTPUT_TOOL,
|
|
@@ -4,8 +4,8 @@ import { runtimeNameOf } from "../kernels/js/runtime-name.ts";
|
|
|
4
4
|
|
|
5
5
|
type Environment = Readonly<Record<string, string | undefined>>;
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
7
|
+
const JS_ISOLATION_ENVIRONMENT_FLAG = "SENPI_CODEMODE_JS_ISOLATION";
|
|
8
|
+
const SANDBOX_MEMORY_ENVIRONMENT_FLAG = "SENPI_CODEMODE_SANDBOX_MEMORY_MB";
|
|
9
9
|
|
|
10
10
|
export const featureSettingsProperties = {
|
|
11
11
|
environments: Type.Optional(
|
|
@@ -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
|
|
|
@@ -68,13 +68,13 @@ export function absoluteSpec(spec: string, cwd: string): string {
|
|
|
68
68
|
return file === undefined ? absolute : `file:${absolute}`;
|
|
69
69
|
}
|
|
70
70
|
|
|
71
|
-
|
|
71
|
+
function jsInstallArgv(installer: JsInstaller, root: string, packages: readonly string[]): string[] {
|
|
72
72
|
return installer === "bun"
|
|
73
73
|
? ["add", "--ignore-scripts", "--cwd", root, ...packages]
|
|
74
74
|
: ["install", "--ignore-scripts", "--no-audit", "--no-fund", "--prefix", root, ...packages];
|
|
75
75
|
}
|
|
76
76
|
|
|
77
|
-
|
|
77
|
+
function jsRemoveArgv(installer: JsInstaller, root: string, name: string): string[] {
|
|
78
78
|
return installer === "bun"
|
|
79
79
|
? ["remove", "--ignore-scripts", "--cwd", root, name]
|
|
80
80
|
: ["uninstall", "--ignore-scripts", "--no-audit", "--no-fund", "--prefix", root, name];
|
|
@@ -8,7 +8,7 @@ export interface PackagesInstallEnvironments {
|
|
|
8
8
|
readonly js?: JsEnvironments;
|
|
9
9
|
}
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
const PACKAGES_INSTALL_DEFAULT_TIMEOUT_SECONDS = 600;
|
|
12
12
|
|
|
13
13
|
interface PackagesInstallRequest {
|
|
14
14
|
readonly manager: "pip" | "bun" | "npm";
|
|
@@ -37,7 +37,7 @@ function labelOf(entry: EvalDetachedCellStatusEntry): string {
|
|
|
37
37
|
* the monitor builtin's formatElapsedSeconds; kept local like the rest of the
|
|
38
38
|
* duplicated status-file helpers between the two packages.
|
|
39
39
|
*/
|
|
40
|
-
|
|
40
|
+
function formatElapsedSeconds(value: number): string {
|
|
41
41
|
const seconds = Math.max(0, Math.trunc(value));
|
|
42
42
|
if (seconds < 60) return `${seconds}s`;
|
|
43
43
|
const minutes = Math.trunc(seconds / 60);
|
|
@@ -54,7 +54,7 @@ export function formatElapsedSeconds(value: number): string {
|
|
|
54
54
|
}
|
|
55
55
|
|
|
56
56
|
/** Whole seconds since the oldest executing detached cell started; queued cells do not tick. */
|
|
57
|
-
|
|
57
|
+
function evalCellElapsedSeconds(entries: readonly EvalDetachedCellStatusEntry[], nowMs: number): number {
|
|
58
58
|
let oldest = Number.POSITIVE_INFINITY;
|
|
59
59
|
for (const entry of entries) {
|
|
60
60
|
if (entry.queuedBehind === undefined) oldest = Math.min(oldest, entry.startedAtMs);
|
|
@@ -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 {
|
|
@@ -34,7 +34,7 @@ export interface SubprocessKernelStart {
|
|
|
34
34
|
readonly peerKernelToolsDescribe?: PeerKernelToolsDescribe;
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
-
|
|
37
|
+
function registerKernel(sessionId: string, language: EvalLanguage, memory: RegisteredKernelSource): string {
|
|
38
38
|
const id = crypto.randomUUID();
|
|
39
39
|
kernelRegistry.register({ id, sessionId, language, source: memory });
|
|
40
40
|
return id;
|
|
@@ -3,7 +3,7 @@ export interface RemovedToolHintRegistrar {
|
|
|
3
3
|
registerRemovedToolHint(name: string, hint: string): void;
|
|
4
4
|
}
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
const WAIT_REMOVED_TOOL_HINT =
|
|
7
7
|
"wait is not a tool; inside a cell use the wait(handles) helper (tool_schema('eval:wait')), or let detached cells notify.";
|
|
8
8
|
|
|
9
9
|
export function registerRemovedToolHints(pi: RemovedToolHintRegistrar): void {
|
|
@@ -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);
|
|
@@ -7,15 +7,13 @@ const BUN_SKILL_BASE_DIR = dirname(fileURLToPath(import.meta.url));
|
|
|
7
7
|
|
|
8
8
|
let loggedMissingBunSkill = false;
|
|
9
9
|
|
|
10
|
-
export const BUN_SKILL_MIN_VERSION = "1.4.0";
|
|
11
|
-
|
|
12
10
|
/** Reads the js eval kernel's bun version; undefined on a node kernel. */
|
|
13
11
|
export type BunKernelVersionSource = () => string | undefined;
|
|
14
12
|
|
|
15
13
|
const kernelBunVersion: BunKernelVersionSource = () => process.versions.bun;
|
|
16
14
|
|
|
17
15
|
/**
|
|
18
|
-
* True when the version is at least
|
|
16
|
+
* True when the version is at least 1.4: parses the leading
|
|
19
17
|
* `<major>.<minor>` integers of the string and gates on major > 1 || (major === 1 && minor >= 4).
|
|
20
18
|
* Unparseable or missing versions never enable the skill.
|
|
21
19
|
*/
|
|
@@ -12,7 +12,7 @@ const handleRefSchema = Type.Object(
|
|
|
12
12
|
{ additionalProperties: true },
|
|
13
13
|
);
|
|
14
14
|
|
|
15
|
-
|
|
15
|
+
const WAIT_MODES = ["all", "any", "settled"] as const;
|
|
16
16
|
export type WaitMode = (typeof WAIT_MODES)[number];
|
|
17
17
|
|
|
18
18
|
const waitArgsSchema = Type.Object(
|
|
@@ -44,7 +44,7 @@ export interface WaitRequest {
|
|
|
44
44
|
readonly timeoutSeconds?: number;
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
-
|
|
47
|
+
class HandleArgumentsError extends Error {
|
|
48
48
|
readonly name = "HandleArgumentsError";
|
|
49
49
|
readonly code = "eval_handle_invalid_arguments";
|
|
50
50
|
|
package/src/handles/wait.ts
CHANGED
|
@@ -19,7 +19,7 @@ export interface WaitBackend {
|
|
|
19
19
|
export type WaitAnyResult = { readonly index: number; readonly ref: HandleRef; readonly value: unknown };
|
|
20
20
|
|
|
21
21
|
/** A handle's own failure, raised by `wait(..., {mode: "all"})` and `control.wait()`; `code` is in the text. */
|
|
22
|
-
|
|
22
|
+
class HandleOutcomeError extends Error {
|
|
23
23
|
readonly name = "HandleOutcomeError";
|
|
24
24
|
readonly code: string;
|
|
25
25
|
readonly ref: HandleRef;
|
|
@@ -33,7 +33,7 @@ export class HandleOutcomeError extends Error {
|
|
|
33
33
|
}
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
-
|
|
36
|
+
class WaitAllRejectedError extends Error {
|
|
37
37
|
readonly name = "WaitAllRejectedError";
|
|
38
38
|
readonly code = "eval_wait_all_rejected";
|
|
39
39
|
readonly outcomes: readonly HandleOutcome[];
|
package/src/kernels/AGENTS.md
CHANGED
|
@@ -10,7 +10,7 @@ runner/prelude assets).
|
|
|
10
10
|
| --- | --- |
|
|
11
11
|
| JavaScript host API | `js/context-manager.ts` (`JavaScriptKernel`), `js/worker-host.ts` |
|
|
12
12
|
| JS worker runtime, entries | `js/worker-runtime.js`, `js/worker-entry.js`, `js/inline-worker-entry.js`, `js/inline-worker.ts`, `js/worker-core.js` (+ `worker-core.d.ts`) |
|
|
13
|
-
| JS import rewriting, queueing | `js/rewrite-imports.ts`, `js/run-queue.ts`, `js/
|
|
13
|
+
| JS import rewriting, queueing | `js/rewrite-imports.ts`, `js/run-queue.ts`, `js/local-module-loader.ts` |
|
|
14
14
|
| Python kernel | `py/kernel.ts`, `py/transport.ts`, `py/process.ts`, `py/prelude.py` |
|
|
15
15
|
| Ruby kernel | `rb/kernel.ts` + `rb/prelude.rb`, `rb/runner.rb` |
|
|
16
16
|
| Julia kernel | `jl/kernel.ts` + `jl/prelude.jl`, `jl/runner.jl` |
|
|
@@ -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" });
|
|
@@ -3,11 +3,11 @@ import type { WorkerLike } from "./inline-worker.ts";
|
|
|
3
3
|
import { type PendingJavaScriptRun, stoppedResult } from "./run-queue.ts";
|
|
4
4
|
|
|
5
5
|
/** How long the worker gets to acknowledge `interrupt`; silence means its event loop is blocked in synchronous code. */
|
|
6
|
-
|
|
6
|
+
const INTERRUPT_ACK_MS = 500;
|
|
7
7
|
/** How long an acknowledged cell gets to settle before the VM is replaced. */
|
|
8
8
|
export const JS_INTERRUPT_GRACE_MS = 2_000;
|
|
9
9
|
/** How long `worker.terminate()` may take before the worker is abandoned as blocked in a synchronous call. */
|
|
10
|
-
|
|
10
|
+
const WORKER_TERMINATE_DEADLINE_MS = 3_000;
|
|
11
11
|
|
|
12
12
|
export type CooperativeSettlement = "settled" | "unresponsive";
|
|
13
13
|
export type WorkerRetirement = "terminated" | "abandoned";
|
|
@@ -50,7 +50,7 @@ export async function retireWorker(
|
|
|
50
50
|
return outcome;
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
-
|
|
53
|
+
function abandonedWorkerNote(deadlineMs = WORKER_TERMINATE_DEADLINE_MS): string {
|
|
54
54
|
return `JavaScript worker did not stop within ${deadlineMs}ms: a synchronous call (for example Bun.spawnSync or child_process.spawnSync) is blocking it. A fresh worker replaced it; the blocked call keeps running until it returns.\n`;
|
|
55
55
|
}
|
|
56
56
|
|
|
@@ -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
|
|
@@ -23,7 +23,7 @@ function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
|
|
|
23
23
|
return typeof value === "object" && value !== null;
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
-
|
|
26
|
+
function isProcessAlive(pid: number): boolean {
|
|
27
27
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
28
28
|
try {
|
|
29
29
|
process.kill(pid, 0);
|
|
@@ -33,7 +33,7 @@ export function isProcessAlive(pid: number): boolean {
|
|
|
33
33
|
}
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
-
|
|
36
|
+
function signalProcess(pid: number, signal: NodeJS.Signals): boolean {
|
|
37
37
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
38
38
|
try {
|
|
39
39
|
process.kill(pid, signal);
|
|
@@ -52,7 +52,7 @@ function ps(args: readonly string[]): Promise<string> {
|
|
|
52
52
|
});
|
|
53
53
|
}
|
|
54
54
|
|
|
55
|
-
|
|
55
|
+
async function readProcessTable(): Promise<Map<number, number[]>> {
|
|
56
56
|
const children = new Map<number, number[]>();
|
|
57
57
|
if (process.platform === "win32") return children;
|
|
58
58
|
const stdout = await ps(["-axo", "pid=,ppid="]);
|
|
@@ -68,7 +68,7 @@ export async function readProcessTable(): Promise<Map<number, number[]>> {
|
|
|
68
68
|
return children;
|
|
69
69
|
}
|
|
70
70
|
|
|
71
|
-
|
|
71
|
+
function collectDescendants(table: ReadonlyMap<number, readonly number[]>, roots: readonly number[]): number[] {
|
|
72
72
|
const seen = new Set<number>(roots);
|
|
73
73
|
const queue = [...roots];
|
|
74
74
|
const descendants: number[] = [];
|
|
@@ -85,7 +85,7 @@ export function collectDescendants(table: ReadonlyMap<number, readonly number[]>
|
|
|
85
85
|
return descendants;
|
|
86
86
|
}
|
|
87
87
|
|
|
88
|
-
|
|
88
|
+
function ownedRoots(
|
|
89
89
|
table: ReadonlyMap<number, readonly number[]>,
|
|
90
90
|
parentPid: number,
|
|
91
91
|
roots: readonly number[],
|
|
@@ -26,7 +26,7 @@ export function resolveJsProcessEntryUrl(options: JavaScriptProcessEntryUrlOptio
|
|
|
26
26
|
return pathToFileURL(requireCodemodeRuntimeAsset(localPath, join("kernels", "js", "process-entry.js"), options));
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
-
|
|
29
|
+
class JavaScriptProcessRuntimeUnavailableError extends Error {
|
|
30
30
|
readonly name = "JavaScriptProcessRuntimeUnavailableError";
|
|
31
31
|
readonly runtime: string;
|
|
32
32
|
readonly searchPath: string;
|
|
@@ -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") {
|
|
@@ -85,11 +85,7 @@ export function waitForReady(worker: WorkerLike, signal: AbortSignal): Promise<v
|
|
|
85
85
|
});
|
|
86
86
|
}
|
|
87
87
|
|
|
88
|
-
|
|
89
|
-
readonly message: string;
|
|
90
|
-
readonly name?: string;
|
|
91
|
-
readonly stack?: string;
|
|
92
|
-
}): Error {
|
|
88
|
+
function errorFromBridge(error: { readonly message: string; readonly name?: string; readonly stack?: string }): Error {
|
|
93
89
|
const result = new Error(error.message);
|
|
94
90
|
if (error.name) result.name = error.name;
|
|
95
91
|
if (error.stack) result.stack = error.stack;
|
|
@@ -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
|
|
|
@@ -25,7 +25,7 @@ export function resolveJsWorkerEntryUrl(options: JavaScriptWorkerEntryUrlOptions
|
|
|
25
25
|
*/
|
|
26
26
|
export const PROCESS_STARTUP_DEADLINE_MS = 30_000;
|
|
27
27
|
|
|
28
|
-
|
|
28
|
+
class ProcessKernelStartupTimeoutError extends Error {
|
|
29
29
|
constructor(deadlineMs: number) {
|
|
30
30
|
super(
|
|
31
31
|
`JavaScript kernel process did not become ready within ${deadlineMs / 1000}s; it was stopped, and the next cell starts a fresh one`,
|
|
@@ -18,7 +18,7 @@ export const pythonStartupCeilingMs = 120_000;
|
|
|
18
18
|
const stages = ["interpreter-launch", "stdlib-imports", "runtime-init", "host-init"] as const;
|
|
19
19
|
export type PythonStartupStage = (typeof stages)[number];
|
|
20
20
|
|
|
21
|
-
|
|
21
|
+
class PythonKernelStartupError extends Error {
|
|
22
22
|
readonly stage: PythonStartupStage;
|
|
23
23
|
|
|
24
24
|
constructor(stage: PythonStartupStage, reason: string, cause?: Error) {
|
|
@@ -10,7 +10,7 @@ export type BunFfi = {
|
|
|
10
10
|
};
|
|
11
11
|
|
|
12
12
|
/** True when `value` carries the `bun:ffi` surface the kernel CPU readers use (`dlopen`, `FFIType`, `ptr`). */
|
|
13
|
-
|
|
13
|
+
function isBunFfi(value: unknown): value is BunFfi {
|
|
14
14
|
if (typeof value !== "object" || value === null) return false;
|
|
15
15
|
if (!("dlopen" in value) || typeof value.dlopen !== "function") return false;
|
|
16
16
|
if (!("ptr" in value) || typeof value.ptr !== "function") return false;
|
|
@@ -40,7 +40,7 @@ function lostPhrase(lost: LostGlobals | undefined): string {
|
|
|
40
40
|
return `. Lost: ${named.join(", ")}${more > 0 ? ` and ${more} more` : ""}`;
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
-
|
|
43
|
+
const EVAL_KERNEL_UNAVAILABLE = "eval_kernel_unavailable";
|
|
44
44
|
|
|
45
45
|
/** A queued cell that never ran: its kernel died again before the replacement finished one cell. */
|
|
46
46
|
export class KernelUnavailableError extends Error {
|
|
@@ -7,7 +7,7 @@ import type { KernelToHostMessage } from "../../bridge/protocol.ts";
|
|
|
7
7
|
* (blocked on a lock, a pipe or a stopped process) does. It restarts on every sign of progress, so it is
|
|
8
8
|
* not a total startup budget. Where the group's CPU cannot be read it never fires.
|
|
9
9
|
*/
|
|
10
|
-
|
|
10
|
+
const subprocessStartupNoProgressMs = 30_000;
|
|
11
11
|
|
|
12
12
|
const STDERR_TAIL_CHARS = 2_000;
|
|
13
13
|
const stages = ["interpreter-launch", "stdlib-imports", "runtime-init", "host-init"] as const;
|
|
@@ -4,12 +4,10 @@ import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, truncateTail } from "../host-sdk.
|
|
|
4
4
|
import { formatMiddleElisionMarker } from "./output-meta.ts";
|
|
5
5
|
import { TailBuffer, TailLineRing, truncateHeadBytes } from "./streaming-output-buffer.ts";
|
|
6
6
|
|
|
7
|
-
export { artifactNotice,
|
|
8
|
-
export {
|
|
7
|
+
export { artifactNotice, resolveSessionArtifactsDir } from "./output-meta.ts";
|
|
8
|
+
export { truncateTailBytes } from "./streaming-output-buffer.ts";
|
|
9
9
|
export { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, TailBuffer, TailLineRing, truncateTail };
|
|
10
10
|
|
|
11
|
-
export const ARTIFACT_DEFAULT_HEAD_BYTES = 3 * 1024 * 1024;
|
|
12
|
-
|
|
13
11
|
export interface OutputSummary {
|
|
14
12
|
readonly output: string;
|
|
15
13
|
readonly truncated: boolean;
|
|
@@ -67,7 +67,7 @@ const OPENAI_MODEL_RE = /(^|[/.:])(gpt|chatgpt|codex)[-.]|(^|[/.:])o[134](?:[-.]
|
|
|
67
67
|
* - `default`: everything else (and no model) — maximum-emphasis fallback.
|
|
68
68
|
*/
|
|
69
69
|
/** True only for GPT model ids that receive the terse eval composition dialect. */
|
|
70
|
-
|
|
70
|
+
function isGptCodeModeModel(modelId: string | undefined): boolean {
|
|
71
71
|
return modelId !== undefined && /(^|[/.:])gpt[-.]/iu.test(modelId);
|
|
72
72
|
}
|
|
73
73
|
|
|
@@ -12,7 +12,7 @@ export interface RunBudgetOptions {
|
|
|
12
12
|
readonly onExhausted: (event: RunBudgetEvent) => void;
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
-
|
|
15
|
+
function runBudgetError(cellId: string, budgetSeconds: number): Error {
|
|
16
16
|
const error = new Error(
|
|
17
17
|
`Eval cell ${cellId} exhausted its ${budgetSeconds}s run budget (own execution time; host tool calls excluded) and was killed.`,
|
|
18
18
|
);
|
package/src/tool/call-capture.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type { EvalToolCallSummary } from "./types.ts";
|
|
|
4
4
|
export const MAX_ENRICHED_TOOL_CALLS = 30;
|
|
5
5
|
export const MAX_AGGREGATED_TOOL_NAMES = 64;
|
|
6
6
|
export const MAX_CAPTURED_IDENTIFIER_CODE_POINTS = 128;
|
|
7
|
-
|
|
7
|
+
const MAX_CAPTURED_TOOL_NAME_CODE_POINTS = 128;
|
|
8
8
|
export const MAX_RPC_EVENT_BYTES = 32 * 1024;
|
|
9
9
|
|
|
10
10
|
const MAX_ARGUMENT_STRING_CODE_POINTS = 512;
|
|
@@ -115,7 +115,7 @@ export function createToolCallMetric(name: string, startedAt: number): EvalToolC
|
|
|
115
115
|
};
|
|
116
116
|
}
|
|
117
117
|
|
|
118
|
-
|
|
118
|
+
function settleToolCallMetric(metric: EvalToolCallMetric, ok: boolean, completedAt: number): void {
|
|
119
119
|
metric.ok = ok;
|
|
120
120
|
metric.durationMs = Math.max(0, completedAt - metric.startedAt);
|
|
121
121
|
}
|
|
@@ -15,7 +15,7 @@ export interface CellDeadlinesOptions {
|
|
|
15
15
|
readonly onExpire: (expiry: CellDeadlineExpiry) => void;
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
-
|
|
18
|
+
function hardLimitError(cellId: string, hardLimitSeconds: number): Error {
|
|
19
19
|
const error = new Error(`Eval cell ${cellId} was killed at the ${hardLimitSeconds}s hard limit.`);
|
|
20
20
|
error.name = "TimeoutError";
|
|
21
21
|
return error;
|
|
@@ -59,7 +59,7 @@ export function queuedBehindCell(
|
|
|
59
59
|
];
|
|
60
60
|
}
|
|
61
61
|
|
|
62
|
-
|
|
62
|
+
function currentDetachedResult(cell: DetachedCellResultSource): AgentToolResult<EvalToolDetails> {
|
|
63
63
|
return cell.terminalResult ?? cell.liveResult?.() ?? fallbackResult(cell.input);
|
|
64
64
|
}
|
|
65
65
|
|
package/src/tool/image-resize.ts
CHANGED
|
@@ -19,7 +19,7 @@ export type EvalImageResizer = (
|
|
|
19
19
|
|
|
20
20
|
type WebpModel = { readonly provider: string; readonly api: string } | undefined;
|
|
21
21
|
|
|
22
|
-
|
|
22
|
+
function webpExclusionForModel(model: WebpModel): true | undefined {
|
|
23
23
|
if (model === undefined) return undefined;
|
|
24
24
|
return model.provider === "ollama" ||
|
|
25
25
|
model.provider === "ollama-cloud" ||
|
package/src/tool/image.ts
CHANGED
|
@@ -15,13 +15,7 @@ import { sanitizeDisplayJson } from "./display-json-bounds.ts";
|
|
|
15
15
|
import { MAX_DISPLAY_TEXT_BYTES } from "./display-json-size.ts";
|
|
16
16
|
import { type EvalImageContent, type EvalImageResizer, resizeEvalImage } from "./image-resize.ts";
|
|
17
17
|
|
|
18
|
-
export {
|
|
19
|
-
type EvalImageContent,
|
|
20
|
-
type EvalImageResizeResult,
|
|
21
|
-
type EvalImageResizer,
|
|
22
|
-
resizeEvalImage,
|
|
23
|
-
webpExclusionForModel,
|
|
24
|
-
} from "./image-resize.ts";
|
|
18
|
+
export { type EvalImageContent, type EvalImageResizeResult, type EvalImageResizer } from "./image-resize.ts";
|
|
25
19
|
export { marshalToolResult, toolResultIsError } from "./tool-result-marshal.ts";
|
|
26
20
|
|
|
27
21
|
// Per-cell display caps: display payloads are retained for the whole result lifetime, so an unbounded
|
package/src/tool/render-cell.ts
CHANGED
|
@@ -32,8 +32,6 @@ import { formatDuration } from "./tool-widgets.ts";
|
|
|
32
32
|
import type { EvalCellResult } from "./types.ts";
|
|
33
33
|
|
|
34
34
|
export type { CellBadges } from "./render-live.ts";
|
|
35
|
-
export { LIVE_CODE_WINDOW_LINES } from "./render-live.ts";
|
|
36
|
-
|
|
37
35
|
// A summary has no length limit, so a collapsed block shows its first lines and marks the cut.
|
|
38
36
|
function summaryVisualLines(summary: string, width: number, expanded: boolean): string[] {
|
|
39
37
|
const lines = renderAllVisualLines(summary, width);
|
package/src/tool/render-live.ts
CHANGED
|
@@ -33,14 +33,13 @@ const FRAME_HEADER_PREFIX: PrefixStyle = { prefix: "╭─ ", continuation: "│
|
|
|
33
33
|
const FRAME_INNER_PREFIX: PrefixStyle = { prefix: "│ ", continuation: "│ ", color: "borderMuted" };
|
|
34
34
|
const FRAME_SECTION_PREFIX: PrefixStyle = { prefix: "├─ ", continuation: "│ ", color: "dim" };
|
|
35
35
|
|
|
36
|
-
export const LIVE_CODE_WINDOW_LINES = 6;
|
|
37
36
|
// The live block's total height never changes: header + 6 body rows + border. When output or
|
|
38
37
|
// status events exist, they take a fixed tail section and the code window shrinks inside the
|
|
39
38
|
// same total (review MEDIUM-2): 6 code rows alone, or 3 code + 3 tail rows.
|
|
40
39
|
const LIVE_BODY_ROWS = 6;
|
|
41
40
|
const LIVE_TAIL_ROWS = 3;
|
|
42
41
|
|
|
43
|
-
|
|
42
|
+
function isLiveCellStatus(status: CellStatus): boolean {
|
|
44
43
|
return status === "pending" || status === "running";
|
|
45
44
|
}
|
|
46
45
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { EvalDetachedCellSnapshot } from "./detached-cell-contract.ts";
|
|
2
2
|
import type { RetainedContentPart, SettledContentPart, SettledImageSpill } from "./settled-image-spill.ts";
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
const TERMINAL_SNAPSHOT_CAP = 32;
|
|
5
5
|
|
|
6
6
|
export interface TerminalSnapshotStoreOptions {
|
|
7
7
|
readonly cap?: number;
|
|
@@ -97,7 +97,7 @@ function withContent(
|
|
|
97
97
|
return { ...snapshot, result: { ...snapshot.result, content: [...content] } };
|
|
98
98
|
}
|
|
99
99
|
|
|
100
|
-
|
|
100
|
+
function estimateSnapshotBytes(snapshot: EvalDetachedCellSnapshot): number {
|
|
101
101
|
let bytes = snapshot.outputTail.length * 2;
|
|
102
102
|
for (const part of snapshot.result.content) {
|
|
103
103
|
bytes += part.type === "text" ? part.text.length * 2 : part.data.length;
|
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. */
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
export const JAVASCRIPT_KERNEL_PRELUDE = [
|
|
2
|
-
"print(...values): write stdout text.",
|
|
3
|
-
"display(value): emit JSON, markdown, or image display output; image bytes, data: URLs, Blob-like values, tool results, and their images[i] frames all render as images.",
|
|
4
|
-
"log(message): emit a progress log line.",
|
|
5
|
-
"phase(title): emit a progress phase.",
|
|
6
|
-
"env(key?, value?): read, set, or list environment values.",
|
|
7
|
-
"read(path, options?): read UTF-8 text; plain paths use cwd and local:// uses the session local root.",
|
|
8
|
-
"write(path, content): write UTF-8 or binary data and return the resolved path.",
|
|
9
|
-
"tool.<name>(args): request a host tool call through the bridge; resolves to { text, images?, details?, hasError? }.",
|
|
10
|
-
"tool(fn, metadata?): register a named JavaScript function as a fenced kernel tool for in-process children.",
|
|
11
|
-
"completion(prompt, options?): request a host completion bridge call.",
|
|
12
|
-
"output(...ids, options?): retrieve task output through the reserved output bridge.",
|
|
13
|
-
'agent(prompt, options?): delegate work; isolated/apply/merge need a host that supports isolation, otherwise a warning. merge: "patch"/"branch" (false/true aliases). Unapplied foreground changes throw with recovery instructions. Handles return immediately; await the completion notification or read task_output for the isolation result.',
|
|
14
|
-
"workpool(agent, name, options?): await a host-owned pool adapter with pool_id, push, close, inspect, and cancel; options only accept mode.",
|
|
15
|
-
"parallel(thunks): run async thunks through the configured bounded pool; preserves order and rethrows the lowest-index error after all settle.",
|
|
16
|
-
"pipeline(items, ...stages): map items through staged async transforms with a barrier between stages.",
|
|
17
|
-
].join("\n");
|