@code-yeongyu/senpi-codemode 2026.11.5-1 → 2026.11.6-2

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.
Files changed (34) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +25 -9
  3. package/package.json +4 -4
  4. package/src/bridge/protocol.ts +2 -0
  5. package/src/config/feature-settings.ts +35 -3
  6. package/src/extension/bridge-tool-call.ts +17 -2
  7. package/src/extension/cell-tool-updates.ts +21 -0
  8. package/src/extension/session-manager-proxy.ts +5 -0
  9. package/src/extension/session-manager.ts +13 -1
  10. package/src/kernels/jl/globals.jl +1 -1
  11. package/src/kernels/jl/runner.jl +8 -0
  12. package/src/kernels/js/inline-worker-entry.js +1 -0
  13. package/src/kernels/js/permission-worker-entry.js +1 -0
  14. package/src/kernels/js/power-throttling-startup.js +4 -0
  15. package/src/kernels/js/power-throttling.d.ts +18 -0
  16. package/src/kernels/js/power-throttling.js +91 -0
  17. package/src/kernels/js/process-entry.js +1 -0
  18. package/src/kernels/js/process-worker.ts +4 -7
  19. package/src/kernels/js/runtime-name.ts +7 -0
  20. package/src/kernels/js/worker-entry.js +1 -0
  21. package/src/kernels/rb/prelude.rb +3 -0
  22. package/src/kernels/rb/runner.rb +3 -0
  23. package/src/kernels/shared/subprocess-kernel.ts +3 -1
  24. package/src/prompt/eval-prompt-template.ts +2 -2
  25. package/src/skill/bun/SKILL.md +2 -2
  26. package/src/skill/bun/references/runtime-apis.md +18 -0
  27. package/src/skill/bun/references/session-recipes.md +2 -1
  28. package/src/tool/bridge-cell-binding.ts +34 -0
  29. package/src/tool/cell-handler.ts +10 -40
  30. package/src/tool/cell-runtime.ts +30 -4
  31. package/src/tool/nested-tool-call.ts +46 -0
  32. package/src/tool/nested-tool-output.ts +52 -0
  33. package/src/tool/run-eval-cell.ts +7 -9
  34. package/src/tool/types.ts +5 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,36 @@
1
1
  # Changelog
2
2
 
3
+ ## [2026.11.6-2] - 2026-11-07
4
+
5
+ ### Breaking Changes
6
+
7
+ ### Added
8
+
9
+ ### Changed
10
+
11
+ ### Fixed
12
+
13
+ - A tool called from an eval cell now streams its partial results into the cell's live update (in JavaScript cells and over the bridge for Python, Ruby and Julia cells), so `tool.bash(...)` output shows while the command runs instead of all at once when it ends; the value returned to the cell and the cell's result are unchanged ([#6167](https://github.com/code-yeongyu/senpi/issues/6167))
14
+
15
+ ### Removed
16
+
17
+ ## [2026.11.6-1] - 2026-11-06
18
+
19
+ ### Breaking Changes
20
+
21
+ ### Added
22
+
23
+ ### Changed
24
+
25
+ - The JavaScript `eval` kernel runs in its own process by default when senpi's executable is `bun` on macOS or Linux, so a crash on the kernel (Bun 1.4.4 `Worker` threads can corrupt the JavaScriptCore heap and kill the host with `SIGBUS`/`SIGTRAP`) settles the cell with the signal and the session survives; a Node.js host, a compiled binary and a Windows bun host keep the worker thread, and `isolation.js` / `SENPI_CODEMODE_JS_ISOLATION` still win on every host ([#6094](https://github.com/code-yeongyu/senpi/issues/6094), [#6095](https://github.com/code-yeongyu/senpi/pull/6095))
26
+
27
+ ### Fixed
28
+
29
+ - The bundled `bun` skill's capability map now gives `--retry=<N>` and `--compile --bytecode --bytecode-order=<profile>` in forms bun accepts, its shell-trap fix spawns with `env: process.env`, and the references it points to now cover IPC, `stripANSI`, `inspect.table`, hashing, UUID v7, semver, `deepEquals`, gzip/zstd and `which` ([#6008](https://github.com/code-yeongyu/senpi/issues/6008))
30
+ - On Windows, the JavaScript eval kernels opt every process they start out of EcoQoS power throttling, as senpi does, so commands run from eval code are not held to a few percent of a core; `SENPI_KEEP_POWER_THROTTLING=1` keeps Windows' default ([#6131](https://github.com/code-yeongyu/senpi/pull/6131))
31
+
32
+ ### Removed
33
+
3
34
  ## [2026.11.5-1] - 2026-11-05
4
35
 
5
36
  ### Breaking Changes
package/README.md CHANGED
@@ -61,13 +61,29 @@ schema; it is not an installation failure.
61
61
 
62
62
  ### JavaScript process isolation
63
63
 
64
- By default the JavaScript kernel runs as a worker thread on the host's own
65
- runtime (`isolation.js: "worker"`). Setting `isolation.js: "process"` (or
66
- `SENPI_CODEMODE_JS_ISOLATION=process`, which wins over the file) runs each
67
- JavaScript kernel in its own subprocess instead, so a kernel crash (a native
68
- `SIGSEGV`, an out-of-memory, `process.exit`, an uncaught error) cannot take down
69
- the host session. The next cell runs on a replacement child, and its result
70
- carries the restart notice and names the crash.
64
+ The JavaScript kernel runs either as a worker thread on the host's own runtime
65
+ (`isolation.js: "worker"`) or in its own subprocess (`isolation.js: "process"`),
66
+ where a kernel crash (a native `SIGSEGV` or `SIGBUS`, an out-of-memory,
67
+ `process.exit`, an uncaught error) cannot take down the host session. The next
68
+ cell runs on a replacement child, and its result carries the restart notice and
69
+ names the crash. Without a setting, the default follows the host's executable:
70
+
71
+ - A macOS or Linux host whose executable is `bun` (an npm or bun install of
72
+ senpi or omo run through `bun`) defaults to `"process"`. A Bun 1.4.4 `Worker`
73
+ thread can corrupt the JavaScriptCore heap and kill the whole host with
74
+ `SIGBUS` or `SIGTRAP` (open upstream class; the symptom behind omo#12369),
75
+ and a kernel in its own process cannot.
76
+ - A Node.js host and a compiled binary (the desktop engine) default to
77
+ `"worker"`. A compiled executable cannot run the kernel child itself, so
78
+ process mode there needs a `bun` or `node` on `PATH`, which only an explicit
79
+ setting asks for.
80
+ - A Windows bun host also defaults to `"worker"`: the crash evidence is
81
+ macOS, and the process kernel's Windows channel is not covered by CI, so
82
+ there the mode stays opt-in.
83
+
84
+ `SENPI_CODEMODE_JS_ISOLATION` wins over the file, and the file wins over the
85
+ host default, in both directions: `isolation.js: "worker"` restores the thread
86
+ on a bun host.
71
87
 
72
88
  **Trust model.** Process mode isolates crashes, not hostile code. A cell runs in
73
89
  the same process that talks to the host, so it can reach everything that process
@@ -121,7 +137,7 @@ How it works:
121
137
  runtime (`Install bun or node, or use isolation.js: "worker"`). The result's
122
138
  memory reading is the child's process footprint.
123
139
 
124
- The default stays `"worker"`, and worker-mode behaviour is unchanged.
140
+ Worker-mode behaviour is unchanged.
125
141
 
126
142
  To run the `environments` suites with bun children (the runtime the product
127
143
  uses), run them under bun: `SENPI_CODEMODE_JS_ISOLATION=process bunx --bun vitest
@@ -328,7 +344,7 @@ Configuration is loaded in this order:
328
344
  | `environments.autoProvision` | `true` | Lets installs provision a managed environment. `false` makes installs refuse with `environment_installer_unavailable`. |
329
345
  | `environments.js.installer` | `auto` | Installer for the managed JavaScript environment: `auto`, `bun` or `npm`. |
330
346
  | `environments.py.installer` | `pip` | Installer for the managed Python environment. |
331
- | `isolation.js` | `worker` | JavaScript kernel isolation: `worker` (today's worker thread) or `process`. Env override: `SENPI_CODEMODE_JS_ISOLATION`. |
347
+ | `isolation.js` | `process` on a macOS or Linux host whose executable is `bun`, else `worker` | JavaScript kernel isolation: `worker` (a worker thread) or `process` (its own subprocess; a kernel crash cannot kill the session). Env override: `SENPI_CODEMODE_JS_ISOLATION`. |
332
348
  | `sandbox.enabled` | `false` | Allows sandbox cells. While `false` the sandbox option is neither accepted nor advertised. |
333
349
  | `sandbox.memoryMb` | `64` | Memory cap (MiB) for a sandbox cell. Env override: `SENPI_CODEMODE_SANDBOX_MEMORY_MB` (a positive integer wins). |
334
350
  | `sandbox.timeoutSeconds` | `300` | Time limit for a sandbox cell. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@code-yeongyu/senpi-codemode",
3
- "version": "2026.11.5-1",
3
+ "version": "2026.11.6-2",
4
4
  "description": "Source-only senpi extension package for codemode evaluation tools",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -33,15 +33,15 @@
33
33
  },
34
34
  "dependencies": {
35
35
  "@babel/parser": "8.0.4",
36
- "@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.11.5-1",
36
+ "@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.11.6-2",
37
37
  "quickjs-wasi": "3.6.2",
38
38
  "typebox": "1.3.34"
39
39
  },
40
40
  "peerDependencies": {
41
- "@code-yeongyu/senpi": "2026.11.5-1"
41
+ "@code-yeongyu/senpi": "2026.11.6-2"
42
42
  },
43
43
  "devDependencies": {
44
- "@code-yeongyu/senpi": "2026.11.5-1"
44
+ "@code-yeongyu/senpi": "2026.11.6-2"
45
45
  },
46
46
  "keywords": [
47
47
  "senpi",
@@ -59,6 +59,8 @@ const hostToKernelMessageSchema = Type.Union([
59
59
  envRoot: Type.Optional(Type.String()),
60
60
  /** The file a `%load` cell runs; the runner compiles under its name and imports beside it. */
61
61
  sourceFile: Type.Optional(Type.String({ minLength: 1 })),
62
+ /** The run's bridge secret; the kernel attaches it to the cell's `/call` requests (see `EvalKernelRunInput`). */
63
+ bridgeCellToken: Type.Optional(Type.String({ minLength: 1 })),
62
64
  /** Python only: active tool globals to install before the cell and deactivated ones to remove. */
63
65
  preludes: Type.Optional(
64
66
  Type.Object({
@@ -1,5 +1,6 @@
1
1
  import type { Static } from "typebox";
2
2
  import { Type } from "typebox";
3
+ import { runtimeNameOf } from "../kernels/js/runtime-name.ts";
3
4
 
4
5
  type Environment = Readonly<Record<string, string | undefined>>;
5
6
 
@@ -51,6 +52,33 @@ export type CodemodeFeatureSettings = Static<typeof featureSettingsSchema>;
51
52
 
52
53
  export type JsIsolation = "worker" | "process";
53
54
 
55
+ /** The host as the JavaScript kernel's default isolation sees it: what its own executable is, and on which platform. */
56
+ export interface JsIsolationHost {
57
+ /** "bun" or "node" when the host's executable is that runtime; undefined for a compiled binary. */
58
+ readonly executable: "bun" | "node" | undefined;
59
+ readonly platform: NodeJS.Platform;
60
+ }
61
+
62
+ export function currentJsIsolationHost(
63
+ execPath: string = process.execPath,
64
+ platform: NodeJS.Platform = process.platform,
65
+ ): JsIsolationHost {
66
+ return { executable: runtimeNameOf(execPath), platform };
67
+ }
68
+
69
+ /**
70
+ * Without a setting, a POSIX host whose executable is bun runs the kernel in its own process: a Bun 1.4.4 Worker thread
71
+ * can corrupt the JavaScriptCore heap and take the whole host down with it (SIGBUS/SIGTRAP on macOS, the open upstream
72
+ * class behind omo#12369), and a kernel process cannot. A Node.js host keeps the worker thread, and so does a compiled
73
+ * binary: its executable cannot run process-entry.js, so process mode there needs a bun or node on PATH, which only an
74
+ * explicit setting asks for. A Windows bun host keeps the worker thread too: the crash evidence is macOS, and the
75
+ * process kernel's Windows channel (no libc, cell output shares the frame channel) has no CI coverage, so there the
76
+ * mode stays opt-in.
77
+ */
78
+ export function defaultJsIsolation(host: JsIsolationHost): JsIsolation {
79
+ return host.executable === "bun" && host.platform !== "win32" ? "process" : "worker";
80
+ }
81
+
54
82
  export interface ResolvedSandbox {
55
83
  readonly enabled: boolean;
56
84
  readonly memoryMb: number;
@@ -74,11 +102,15 @@ export function pickFeatureSettings(input: CodemodeFeatureSettings): CodemodeFea
74
102
  };
75
103
  }
76
104
 
77
- /** The environment wins over the file; an unknown value is ignored. Default: today's worker-thread kernel. */
78
- export function resolveJsIsolation(settings: CodemodeFeatureSettings, env: Environment = process.env): JsIsolation {
105
+ /** The environment wins over the file, the file over the host default; an unknown value is ignored. */
106
+ export function resolveJsIsolation(
107
+ settings: CodemodeFeatureSettings,
108
+ env: Environment = process.env,
109
+ host: JsIsolationHost = currentJsIsolationHost(),
110
+ ): JsIsolation {
79
111
  const fromEnv = env[JS_ISOLATION_ENVIRONMENT_FLAG];
80
112
  if (fromEnv === "worker" || fromEnv === "process") return fromEnv;
81
- return settings.isolation?.js ?? "worker";
113
+ return settings.isolation?.js ?? defaultJsIsolation(host);
82
114
  }
83
115
 
84
116
  /** Off by default; the environment's memory cap wins over the file when it is a positive integer. */
@@ -1,7 +1,8 @@
1
- import type { EvalHandleHost } from "@code-yeongyu/senpi";
1
+ import type { AgentToolResult, EvalHandleHost } from "@code-yeongyu/senpi";
2
2
  import { isReservedToolName, runReservedTool } from "../bridges/reserved-dispatch.ts";
3
3
  import { defaultCodemodeSettings } from "../config/settings.ts";
4
4
  import { marshalToolResult } from "../tool/image.ts";
5
+ import type { CellToolUpdateSink } from "../tool/nested-tool-output.ts";
5
6
  import type { CreateCodemodeSessionManagerOptions } from "./session-manager-contract.ts";
6
7
 
7
8
  export interface BridgeToolCallRequest {
@@ -25,9 +26,23 @@ export async function routeBridgeToolCall(
25
26
  >,
26
27
  request: BridgeToolCallRequest,
27
28
  evalHandleHost?: EvalHandleHost,
29
+ toolUpdates?: CellToolUpdateSink,
28
30
  ): Promise<unknown> {
29
31
  if (!isReservedToolName(request.toolName)) {
30
- return marshalToolResult(await options.executeTool(request.toolName, request.args, { signal: request.signal }));
32
+ const live =
33
+ toolUpdates === undefined
34
+ ? {}
35
+ : {
36
+ onUpdate: (partial: AgentToolResult<unknown>) =>
37
+ toolUpdates.nestedToolUpdate(request.callId, partial),
38
+ };
39
+ try {
40
+ return marshalToolResult(
41
+ await options.executeTool(request.toolName, request.args, { signal: request.signal, ...live }),
42
+ );
43
+ } finally {
44
+ toolUpdates?.nestedToolSettled(request.callId);
45
+ }
31
46
  }
32
47
  const taskTools = options.settings.taskTools ?? defaultCodemodeSettings.taskTools;
33
48
  return await runReservedTool(request.toolName, {
@@ -0,0 +1,21 @@
1
+ import type { CellToolUpdateSink } from "../tool/nested-tool-output.ts";
2
+
3
+ /**
4
+ * The live-update sinks of the subprocess-kernel cells running right now, keyed by the same per-run secret as
5
+ * `CellKernelTools`: a bridge call carrying it streams its tool's partial results into that cell (#6167).
6
+ */
7
+ export class CellToolUpdates {
8
+ readonly #byToken = new Map<string, CellToolUpdateSink>();
9
+
10
+ bind(token: string, sink: CellToolUpdateSink): () => void {
11
+ this.#byToken.set(token, sink);
12
+ return () => {
13
+ if (this.#byToken.get(token) === sink) this.#byToken.delete(token);
14
+ };
15
+ }
16
+
17
+ /** The sink bound to `token`; an absent, unknown or released token gets none. */
18
+ sinkFor(token: string | undefined): CellToolUpdateSink | undefined {
19
+ return token === undefined ? undefined : this.#byToken.get(token);
20
+ }
21
+ }
@@ -2,6 +2,7 @@ import type { ExtensionContext } from "@code-yeongyu/senpi";
2
2
  import type { KernelToHostMessage } from "../bridge/protocol.ts";
3
3
  import type { CompletionRequest, CompletionResult } from "../completion/handler.ts";
4
4
  import type { KernelToolsCapability } from "../kernels/js/kernel-tools-types.ts";
5
+ import type { CellToolUpdateSink } from "../tool/nested-tool-output.ts";
5
6
  import type { EvalKernel, EvalLanguage } from "../tool/types.ts";
6
7
  import {
7
8
  CodemodeSessionDisposedError,
@@ -112,6 +113,10 @@ export class SessionManagerProxy implements CodemodeSessionManager, EvalExecutio
112
113
  return this.#current?.bindCellKernelTools?.(token, capability) ?? (() => undefined);
113
114
  }
114
115
 
116
+ bindCellToolUpdates(token: string, sink: CellToolUpdateSink): () => void {
117
+ return this.#current?.bindCellToolUpdates?.(token, sink) ?? (() => undefined);
118
+ }
119
+
115
120
  async complete(request: CompletionRequest, ctx: ExtensionContext): Promise<CompletionResult> {
116
121
  this.assertEvalExecutionAllowed();
117
122
  const current = this.#current;
@@ -16,10 +16,12 @@ import { JavaScriptKernel } from "../kernels/js/context-manager.ts";
16
16
  import type { KernelToolsCapability, KernelToolsDescribeResult } from "../kernels/js/kernel-tools-types.ts";
17
17
  import type { SessionEnvironment } from "../kernels/session-env.ts";
18
18
  import type { KernelLifecycle } from "../kernels/shared/kernel-death.ts";
19
+ import type { CellToolUpdateSink } from "../tool/nested-tool-output.ts";
19
20
  import type { EvalKernel, EvalLanguage } from "../tool/types.ts";
20
21
  import { type BridgeDispatchContext, dispatchBridgeCompletion } from "./bridge-dispatch.ts";
21
22
  import { type BridgeToolCallRequest, routeBridgeToolCall } from "./bridge-tool-call.ts";
22
23
  import { CellKernelTools } from "./cell-kernel-tools.ts";
24
+ import { CellToolUpdates } from "./cell-tool-updates.ts";
23
25
  import { parkWhenIdle } from "./idle-parking-kernel.ts";
24
26
  import { KernelGlobalsLedger } from "./kernel-globals-ledger.ts";
25
27
  import {
@@ -78,6 +80,7 @@ class DefaultCodemodeSessionManager implements CodemodeSessionManager {
78
80
  /** One per language for the manager's life, so an idle-park restart never re-announces an earlier generation. */
79
81
  readonly #ledgers = new Map<EvalLanguage, Promise<KernelGlobalsLedger>>();
80
82
  readonly #cellKernelTools = new CellKernelTools();
83
+ readonly #cellToolUpdates = new CellToolUpdates();
81
84
  #context: ExtensionContext | undefined;
82
85
  #generation = 0;
83
86
  #disposePromise: Promise<void> | undefined;
@@ -111,7 +114,12 @@ class DefaultCodemodeSessionManager implements CodemodeSessionManager {
111
114
 
112
115
  async #call(request: BridgeToolCallRequest): Promise<unknown> {
113
116
  return await this.#cellKernelTools.run(request.cellToken, () =>
114
- routeBridgeToolCall(this.#options, request, this.#context?.evalHandleHost),
117
+ routeBridgeToolCall(
118
+ this.#options,
119
+ request,
120
+ this.#context?.evalHandleHost,
121
+ this.#cellToolUpdates.sinkFor(request.cellToken),
122
+ ),
115
123
  );
116
124
  }
117
125
 
@@ -119,6 +127,10 @@ class DefaultCodemodeSessionManager implements CodemodeSessionManager {
119
127
  return this.#cellKernelTools.bind(token, capability);
120
128
  }
121
129
 
130
+ bindCellToolUpdates(token: string, sink: CellToolUpdateSink): () => void {
131
+ return this.#cellToolUpdates.bind(token, sink);
132
+ }
133
+
122
134
  async getKernel(language: EvalLanguage, onMessage: (message: KernelToHostMessage) => void): Promise<EvalKernel> {
123
135
  if (this.#disposePromise) throw new CodemodeSessionDisposedError();
124
136
  // Persistent kernels are reused across cells, but each cell needs its OWN
@@ -1,4 +1,4 @@
1
- const SENPI_MEMORY_INTERNALS = Set([:senpi_current_cell, :senpi_connection, :senpi_frame_io, :senpi_stdout_capture, :senpi_stderr_capture, :senpi_protocol_stdin])
1
+ const SENPI_MEMORY_INTERNALS = Set([:senpi_current_cell, :senpi_cell_token, :senpi_connection, :senpi_frame_io, :senpi_stdout_capture, :senpi_stderr_capture, :senpi_protocol_stdin])
2
2
 
3
3
  const SENPI_SIZER_SAMPLE = 1_000
4
4
  const SENPI_SIZER_NODE_BUDGET = 5_000
@@ -16,6 +16,7 @@ include("prelude.jl")
16
16
  const senpi_connection = Dict{String, Any}()
17
17
  const senpi_write_lock = ReentrantLock()
18
18
  global senpi_current_cell = nothing
19
+ global senpi_cell_token = nothing
19
20
  global senpi_memory_cell = nothing
20
21
 
21
22
  function senpi_escape(text::AbstractString)
@@ -237,6 +238,10 @@ function senpi_bridge_request(path::String, payload; read_timeout=nothing)
237
238
  port = get(senpi_connection, "port", nothing)
238
239
  token = get(senpi_connection, "token", nothing)
239
240
  port isa Integer && token isa AbstractString || error("Julia tool bridge is not initialized")
241
+ # The run's secret routes the host's kernel tools and the tool's live output to this cell (#6167).
242
+ if path == "/call" && senpi_cell_token isa String && payload isa AbstractDict && !haskey(payload, "cellToken")
243
+ payload = merge(payload, Dict{String, Any}("cellToken" => senpi_cell_token))
244
+ end
240
245
  body = senpi_json(payload)
241
246
  socket = connect(ip"127.0.0.1", port)
242
247
  timed_out = Ref(false)
@@ -330,6 +335,8 @@ function senpi_run_cell(message)
330
335
  code = string(get(message, "code", ""))
331
336
  started = time()
332
337
  global senpi_current_cell = cell_id
338
+ cell_token = get(message, "bridgeCellToken", nothing)
339
+ global senpi_cell_token = cell_token isa AbstractString ? String(cell_token) : nothing
333
340
  try
334
341
  parsed = Meta.parse("begin\n" * code * "\nend")
335
342
  if parsed isa Expr && parsed.head === :error
@@ -351,6 +358,7 @@ function senpi_run_cell(message)
351
358
  senpi_emit(Dict("type" => "result", "cellId" => cell_id, "ok" => false, "error" => senpi_error(error), "durationMs" => round(Int, (time() - started) * 1000)))
352
359
  finally
353
360
  global senpi_current_cell = nothing
361
+ global senpi_cell_token = nothing
354
362
  global senpi_memory_cell = cell_id
355
363
  end
356
364
  end
@@ -1 +1,2 @@
1
+ import "./power-throttling-startup.js";
1
2
  import "./interpose.js";
@@ -1 +1,2 @@
1
+ import "./power-throttling-startup.js";
1
2
  import "./interpose.js";
@@ -0,0 +1,4 @@
1
+ // senpi#6125: imported first by every eval kernel entry, before interpose.js captures the launchers.
2
+ import { installKernelPowerThrottlingOptOut } from "./power-throttling.js";
3
+
4
+ installKernelPowerThrottlingOptOut();
@@ -0,0 +1,18 @@
1
+ export interface KernelPowerThrottling {
2
+ OpenProcess(access: number, inherit: number, pid: number): unknown;
3
+ SetProcessInformation(handle: unknown, infoClass: number, info: Uint8Array, length: number): number;
4
+ CloseHandle(handle: unknown): number;
5
+ }
6
+
7
+ export type KernelPowerThrottlingInstall =
8
+ | { status: "skipped"; reason: "not-windows" | "opted-out" | "no-ffi" }
9
+ | { status: "installed"; self: boolean; restore(): void };
10
+
11
+ export function installKernelPowerThrottlingOptOut(options?: {
12
+ platform?: NodeJS.Platform;
13
+ env?: NodeJS.ProcessEnv;
14
+ pid?: number;
15
+ load?: (platform: NodeJS.Platform) => KernelPowerThrottling | undefined;
16
+ childProcessPrototype?: { spawn(...args: unknown[]): unknown; pid?: number };
17
+ bun?: { spawn(...args: unknown[]): { pid?: number } };
18
+ }): KernelPowerThrottlingInstall;
@@ -0,0 +1,91 @@
1
+ // senpi#6125: the eval kernel's realms opt their children out of Windows EcoQoS throttling, as senpi's own entries do
2
+ // (packages/coding-agent/src/core/windows-power-throttling.ts). Plain JS (with power-throttling.d.ts) because the worker
3
+ // and process kernel entries import it before interpose.js captures the launchers. The policy is per process and not
4
+ // inherited, and the launcher patch is per JavaScript realm, so each kernel realm installs its own. A no-op off Windows,
5
+ // without bun:ffi, or with SENPI_KEEP_POWER_THROTTLING=1; off Windows it imports nothing, so the interposition that
6
+ // follows sees the same module graph as before.
7
+ const PROCESS_POWER_THROTTLING_CLASS = 4;
8
+ const PROCESS_SET_INFORMATION = 0x0200;
9
+
10
+ function optOutState() {
11
+ const info = new Uint8Array(12);
12
+ const view = new DataView(info.buffer);
13
+ view.setUint32(0, 1, true);
14
+ view.setUint32(4, 1, true);
15
+ return info;
16
+ }
17
+
18
+ function loadKernel32PowerThrottling(platform = process.platform) {
19
+ if (platform !== "win32") return undefined;
20
+ const ffi = process.getBuiltinModule("bun:ffi");
21
+ if (ffi === undefined) return undefined;
22
+ let lib;
23
+ try {
24
+ lib = ffi.dlopen("kernel32.dll", {
25
+ OpenProcess: { args: ["u32", "i32", "u32"], returns: "ptr" },
26
+ SetProcessInformation: { args: ["ptr", "i32", "ptr", "u32"], returns: "i32" },
27
+ CloseHandle: { args: ["ptr"], returns: "i32" },
28
+ });
29
+ } catch {
30
+ // A kernel32 without these exports (pre-Windows 8): keep Windows' default policy rather than fail the kernel.
31
+ return undefined;
32
+ }
33
+ return {
34
+ OpenProcess: (access, inherit, pid) => lib.symbols.OpenProcess(access, inherit, pid),
35
+ SetProcessInformation: (handle, infoClass, info, length) =>
36
+ Number(lib.symbols.SetProcessInformation(handle, infoClass, ffi.ptr(info), length)),
37
+ CloseHandle: (handle) => Number(lib.symbols.CloseHandle(handle)),
38
+ };
39
+ }
40
+
41
+ function disableExecutionSpeedThrottling(kernel, pid) {
42
+ try {
43
+ const handle = kernel.OpenProcess(PROCESS_SET_INFORMATION, 0, pid);
44
+ if (!handle) return false;
45
+ try {
46
+ const info = optOutState();
47
+ return kernel.SetProcessInformation(handle, PROCESS_POWER_THROTTLING_CLASS, info, info.byteLength) !== 0;
48
+ } finally {
49
+ kernel.CloseHandle(handle);
50
+ }
51
+ } catch {
52
+ // The child is already running: an FFI failure must never turn its launch into an exception.
53
+ return false;
54
+ }
55
+ }
56
+
57
+ export function installKernelPowerThrottlingOptOut(options = {}) {
58
+ const platform = options.platform ?? process.platform;
59
+ if (platform !== "win32") return { status: "skipped", reason: "not-windows" };
60
+ if ((options.env ?? process.env).SENPI_KEEP_POWER_THROTTLING === "1") return { status: "skipped", reason: "opted-out" };
61
+ const kernel = (options.load ?? loadKernel32PowerThrottling)(platform);
62
+ if (kernel === undefined) return { status: "skipped", reason: "no-ffi" };
63
+ const self = disableExecutionSpeedThrottling(kernel, options.pid ?? process.pid);
64
+ const proto = options.childProcessPrototype ?? process.getBuiltinModule("node:child_process").ChildProcess.prototype;
65
+ const bun = options.bun ?? globalThis.Bun;
66
+ const optOut = (pid) => {
67
+ if (typeof pid === "number" && pid > 0) disableExecutionSpeedThrottling(kernel, pid);
68
+ };
69
+ const originalSpawn = proto.spawn;
70
+ proto.spawn = function (...args) {
71
+ const result = originalSpawn.apply(this, args);
72
+ optOut(this.pid);
73
+ return result;
74
+ };
75
+ const originalBunSpawn = bun?.spawn;
76
+ if (originalBunSpawn !== undefined) {
77
+ bun.spawn = function (...args) {
78
+ const subprocess = originalBunSpawn.apply(this, args);
79
+ optOut(subprocess.pid);
80
+ return subprocess;
81
+ };
82
+ }
83
+ return {
84
+ status: "installed",
85
+ self,
86
+ restore: () => {
87
+ proto.spawn = originalSpawn;
88
+ if (originalBunSpawn !== undefined) bun.spawn = originalBunSpawn;
89
+ },
90
+ };
91
+ }
@@ -14,6 +14,7 @@
14
14
  // Lifetime: the kernel exits the moment its control channel reaches end-of-file (the host closed it, exited or was
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
+ import "./power-throttling-startup.js";
17
18
  import { closeSync, createReadStream, openSync, writeSync } from "node:fs";
18
19
  import { createRequire } from "node:module";
19
20
  import { createInterface } from "node:readline";
@@ -1,7 +1,7 @@
1
1
  import { execFileSync } from "node:child_process";
2
2
  import { randomBytes } from "node:crypto";
3
3
  import { accessSync, constants } from "node:fs";
4
- import { basename, dirname, join } from "node:path";
4
+ import { dirname, join } from "node:path";
5
5
  import { fileURLToPath, pathToFileURL } from "node:url";
6
6
  import type { KernelToHostMessage } from "../../bridge/protocol.ts";
7
7
  import { isKernelToHostMessage, parseBridgeJsonLine, validateBridgeMessage } from "../../bridge/protocol.ts";
@@ -9,8 +9,11 @@ import type { EvalRuntimeInfo } from "../../tool/types.ts";
9
9
  import { type CodemodeRuntimeAssetEnvironment, requireCodemodeRuntimeAsset } from "../shared/runtime-asset.ts";
10
10
  import { type SubprocessLike, SubprocessProcess, spawnSubprocess } from "../shared/subprocess-process.ts";
11
11
  import type { WorkerLike } from "./inline-worker.ts";
12
+ import { runtimeNameOf } from "./runtime-name.ts";
12
13
  import { JavaScriptWorkerExitedError } from "./worker-host.ts";
13
14
 
15
+ export { runtimeNameOf } from "./runtime-name.ts";
16
+
14
17
  const PROCESS_CLOSE_GRACE_MS = 2_000;
15
18
 
16
19
  export interface JavaScriptProcessEntryUrlOptions extends CodemodeRuntimeAssetEnvironment {
@@ -99,12 +102,6 @@ export function processRuntimeInfo(searchPath: string | undefined): EvalRuntimeI
99
102
  return { name, version, path: command, isolation: "process" };
100
103
  }
101
104
 
102
- /** "bun" or "node" from an executable path; undefined for anything else (a compiled senpi binary, for one). */
103
- export function runtimeNameOf(command: string): "bun" | "node" | undefined {
104
- const name = basename(command).replace(/\.(exe|cmd|bat)$/i, "");
105
- return name === "bun" || name === "node" ? name : undefined;
106
- }
107
-
108
105
  function isExecutable(path: string): boolean {
109
106
  try {
110
107
  accessSync(path, constants.X_OK);
@@ -0,0 +1,7 @@
1
+ import { basename } from "node:path";
2
+
3
+ /** "bun" or "node" from an executable path; undefined for anything else (a compiled senpi binary, for one). */
4
+ export function runtimeNameOf(command: string): "bun" | "node" | undefined {
5
+ const name = basename(command).replace(/\.(exe|cmd|bat)$/i, "");
6
+ return name === "bun" || name === "node" ? name : undefined;
7
+ }
@@ -1 +1,2 @@
1
+ import "./power-throttling-startup.js";
1
2
  import "./interpose.js";
@@ -94,6 +94,9 @@ def __senpi_bridge_request(path, payload, read_timeout: 60)
94
94
  request = Net::HTTP::Post.new(uri)
95
95
  request["authorization"] = "Bearer #{token}"
96
96
  request["content-type"] = "application/json"
97
+ # The run's secret routes the host's kernel tools and the tool's live output to this cell (#6167).
98
+ cell_token = $__senpi_cell_token
99
+ payload = payload.merge("cellToken" => cell_token) if path == "/call" && cell_token.is_a?(String) && !payload.key?("cellToken")
97
100
  request.body = JSON.generate(payload)
98
101
  __senpi_emit_status("timeout-pause", force: true)
99
102
  begin
@@ -9,6 +9,7 @@ $stdout.flush
9
9
  $__senpi_binding = TOPLEVEL_BINDING
10
10
  $__senpi_frame_mutex = Mutex.new
11
11
  $__senpi_current_cell = nil
12
+ $__senpi_cell_token = nil
12
13
  $__senpi_memory_cell = nil
13
14
  $__senpi_capture_cell = nil
14
15
  $__senpi_connection = nil
@@ -277,6 +278,7 @@ def __senpi_run_cell(message)
277
278
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
278
279
  cell_id = message["cellId"].to_s
279
280
  $__senpi_current_cell = cell_id
281
+ $__senpi_cell_token = message["bridgeCellToken"].is_a?(String) ? message["bridgeCellToken"] : nil
280
282
  $__senpi_capture_cell = cell_id
281
283
  begin
282
284
  source = message["code"].to_s
@@ -303,6 +305,7 @@ def __senpi_run_cell(message)
303
305
  ensure
304
306
  $__senpi_capture_cell = nil
305
307
  $__senpi_current_cell = nil
308
+ $__senpi_cell_token = nil
306
309
  $__senpi_memory_cell = cell_id
307
310
  end
308
311
  end
@@ -181,7 +181,9 @@ export class SubprocessKernel {
181
181
  const timeoutMs = run.input.timeoutMs;
182
182
  if (timeoutMs !== undefined) run.timer = setTimeout(() => this.handleTimeout(run, timeoutMs), timeoutMs);
183
183
  try {
184
- process.send(encodeBridgeFrame({ type: "run", cellId: run.input.cellId, code: run.input.code, timeoutMs }));
184
+ const { cellId, code, bridgeCellToken } = run.input;
185
+ const token = bridgeCellToken === undefined ? {} : { bridgeCellToken };
186
+ process.send(encodeBridgeFrame({ type: "run", cellId, code, timeoutMs, ...token }));
185
187
  } catch (error) {
186
188
  this.failClosed(new KernelProcessError(error instanceof Error ? error.message : String(error)));
187
189
  }
@@ -21,12 +21,12 @@ GPT eval: batch a step's independent tool calls in one cell with \`tool.<name>(a
21
21
  - Write real code around the calls - loops, branches, joins, a try/except per risky item - and keep every failed or missing item in the result verbatim; re-read truncated output before deciding.
22
22
  {{#if monitor}}- Long-running build, test run, deploy, or watch work starts with \`tool.monitor({ command, filter })\`, with the decisive-line filter inside the same cell; keep working until its event wakes the turn.{{/if}}{{/if}}
23
23
  {{#if hostLine}}
24
- Host: {{hostLine}}. Cells execute here. Size \`parallel(thunks)\` pools to its cores; \`tool.<name>()\` shell commands must fit this platform, even when the code you are writing targets another machine.
24
+ Host: {{hostLine}}. Cells execute here. \`parallel(thunks)\` runs through a fixed-width pool (the codemode \`parallelPoolWidth\` setting, default 4) whatever the core count; \`tool.<name>()\` shell commands must fit this platform, even when the code you are writing targets another machine.
25
25
  {{/if}}
26
26
 
27
27
  \`language\`: {{#if py}}\`"py"\` IPython kernel{{/if}}{{#ifAll py js}}, {{/ifAll}}{{#if js}}\`"js"\` persistent JavaScript VM{{/if}}{{#if rb}}{{#ifAny py js}}, {{/ifAny}}\`"rb"\` persistent Ruby kernel{{/if}}{{#if jl}}{{#ifAny py js rb}}, {{/ifAny}}\`"jl"\` persistent Julia kernel{{/if}}.
28
28
 
29
- A cell that outlives the foreground window detaches and keeps running; further cells on the same language queue behind it in submission order on the same kernel (state is shared, execution is serial) while other languages run at once, up to {{maxDetachedCells}} background cells per session; each detached cell completes as one notification. Do not re-run a detached or queued cell; read, cancel or enumerate them with \`eval({ action: "peek" | "stop", cell_id })\` / \`eval({ action: "list" })\`; list shows live and recently settled cells across languages without consuming notifications. Its own execution time is capped at {{runBudgetSeconds}}s (queue time and time inside host tool calls are not charged; the hard limit stays wall-clock from submission; raise \`timeout\` only for a declared long run), and a killed js cell that cannot settle restarts its kernel with every global lost.
29
+ A cell still running when the call stops waiting for it (the detach point in the parameter schema) detaches and keeps running; further cells on the same language queue behind it in submission order on the same kernel (state is shared, execution is serial) while other languages run at once, up to {{maxDetachedCells}} background cells per session (at that cap, a further cell that cannot detach is cancelled when its foreground window ends, so stop or await a live cell first); each detached cell completes as one notification. Do not re-run a detached or queued cell; read, cancel or enumerate them with \`eval({ action: "peek" | "stop", cell_id })\` / \`eval({ action: "list" })\`; list shows live and recently settled cells across languages without consuming notifications. Its own execution time is capped at {{runBudgetSeconds}}s (queue time and time inside host tool calls are not charged; the hard limit stays wall-clock from submission; raise \`timeout\` only for a declared long run), and a killed js cell that cannot settle restarts its kernel with every global lost.
30
30
 
31
31
  {{#if py}}Python runs on a live event loop: use top-level \`await\`; \`asyncio.run(…)\` raises.{{/if}}
32
32
  {{#if js}}{{#if jsBun}}JS runs in-process on Bun {{jsVersion}}: top-level \`await\`/\`return\` work; \`Bun.*\` builtins available, including \`new Bun.WebView()\`, a headless browser (navigate/click/evaluate/screenshot) to reach for before \`curl\` or a browser CLI when a page needs JS, a login, or a screenshot. Shell out through \`Bun.$\` or \`Bun.spawn\`, never \`Bun.spawnSync\`: a synchronous child blocks the worker and cannot be interrupted.{{#if bunSkillPath}} Before a cell that installs a package, spawns a process, server or PTY, runs tests, or starts a long run, read the bun skill at {{bunSkillPath}}: its builtins replace the npm packages you would otherwise install, and it lists the Bun.$ / Bun.spawn / bun test traps that cost past sessions hours.{{/if}}{{else}}JS runs under Node.js worker: top-level \`await\`/\`return\` work; \`fetch\`/\`Buffer\` available.{{/if}}{{/if}}
@@ -29,9 +29,9 @@ Bun 1.4.0 (Aug 2026) through 1.4.4 (Oct 2026) ships builtins and CLIs that repla
29
29
  | Serve a static dir (ETag/Range/304 handled) | `Bun.serve({ routes: { "/x/*": { dir } } })` | express.static, serve-static, sirv | http-networking |
30
30
  | HTTP/2 + HTTP/3 server; fetch protocol/compress/proxy; per-client pools | `http2: true`, `http3: true`, `fetch(url, { protocol, compress, proxy })`, `new Bun.FetchSession()` | undici Agent | http-networking |
31
31
  | Stream a download to disk; replay a request as curl | `Bun.write(path, await fetch(url))`, `BUN_CONFIG_VERBOSE_FETCH=curl` | pipeline + createWriteStream | http-networking |
32
- | Tests across CPU workers / CI shards / changed files / flaky retry | `bun test --parallel --shard=1/3 --changed=main --retry` | jest/vitest infra | test |
32
+ | Tests across CPU workers / CI shards / changed files / flaky retry | `bun test --parallel --shard=1/3 --changed=main --retry=3` | jest/vitest infra | test |
33
33
  | Kill "passes alone, fails in suite" bugs; hunt flakes | `bun test --isolate`, `--rerun-each N`, `--only-failures` | vitest default behavior | test |
34
- | Single-file executables with embedded assets and profile-guided startup; feature flags; in-memory bundling; metafile; React Compiler | `bun build --compile --asset ./public --bytecode-order`, `bun:bundle feature()`, `files:{}`, `metafile: true`, `--react-compiler` | pkg hacks, esbuild define/plugins, babel-plugin-react-compiler | build |
34
+ | Single-file executables with embedded assets and profile-guided startup; feature flags; in-memory bundling; metafile; React Compiler | `bun build --compile --bytecode --bytecode-order=<profile> --asset ./public`, `bun:bundle feature()`, `files:{}`, `metafile: true`, `--react-compiler` | pkg hacks, esbuild define/plugins, babel-plugin-react-compiler | build |
35
35
  | Diff package versions, fix vulns, dedupe/prune, licenses, explain a dep | `bun pm diff`, `bun audit fix`, `bun dedupe`, `bun prune`, `bun pm licenses`, `bun why` | npm-diff, npm audit fix, npm ls | install |
36
36
  | Offline / cached installs; Docker layers; CI cache; 7x faster CI | `bun install --offline\|--prefer-offline`, `bun pm fetch`, `bun pm cache pack\|unpack`, `linker = "isolated"` | pnpm store | install |
37
37
  | Profile CPU/heap/bundle as grep-able Markdown | `bun --cpu-prof-md`, `--heap-prof-md`, `bun build --metafile-md` | Chrome DevTools round-trip | dev-tooling |
@@ -143,6 +143,24 @@ Docs: <https://bun.com/docs/runtime/utils>
143
143
  Bun.stringWidth("\x1b[32mgreen\x1b[0m e\u0301"); // terminal columns, ANSI + grapheme aware
144
144
  Bun.sliceAnsi(str, 0, 20); // slice by columns, preserving ANSI codes
145
145
  Bun.wrapAnsi(str, 80); // wrap by columns
146
+ Bun.stripANSI("\x1b[31mred\x1b[0m"); // "red"
147
+ Bun.inspect.table([{ a: 1, b: 2 }]); // box-drawn table string, like console.table
148
+ ```
149
+
150
+ ## Hashing, ids, versions, equality, compression, PATH lookup
151
+
152
+ Docs: <https://bun.com/docs/runtime/utils>, <https://bun.com/docs/runtime/hashing>
153
+
154
+ ```ts
155
+ Bun.hash("data"); // fast non-crypto hash (wyhash), returns a bigint
156
+ new Bun.CryptoHasher("sha256").update(buf).digest("hex");
157
+ await Bun.password.hash(pw); await Bun.password.verify(pw, hash); // argon2id by default
158
+ Bun.randomUUIDv7(); // time-ordered UUID string
159
+ Bun.semver.satisfies("1.4.4", "^1.4.0"); Bun.semver.order("1.4.3", "1.4.4"); // true; -1
160
+ Bun.deepEquals(a, b); // structural equality (third arg true = strict)
161
+ Bun.gzipSync(bytes); Bun.gunzipSync(gz);
162
+ Bun.zstdCompressSync(bytes); Bun.zstdDecompressSync(z);
163
+ Bun.which("gh"); // absolute path or null
146
164
  ```
147
165
 
148
166
  ## Databases and object storage
@@ -16,7 +16,7 @@ await $`bun run build`.cwd("/repo").env({ ...process.env, CI: "1" });
16
16
  | Trap | What happens | Fix |
17
17
  |---|---|---|
18
18
  | `${"a b c"}` | ONE argv entry — vitest reported "No test files found" with rc 0 and the gate looked green (2026-09-21) | pass an array: `${["a", "b", "c"]}` spreads into separate args |
19
- | `$?`, `$VAR`, `for … done`, `$(…)` | `$` is escaped to a literal; unsupported syntax is a PARSE error (nothing runs) or a silent `command not found` with rc 0 (2026-10-10, 10-22) | run real bash: `Bun.spawn(["bash", "-c", script])` or `` $`bash -c ${script}` `` |
19
+ | `$?`, `$VAR`, `for … done`, `$(…)` | `$` is escaped to a literal; unsupported syntax is a PARSE error (nothing runs) or a silent `command not found` with rc 0 (2026-10-10, 10-22) | run real bash: `Bun.spawn(["bash", "-c", script], { env: process.env, stdin: "ignore" })` or `` $`bash -c ${script}` `` |
20
20
  | `VAR=x cmd` prefix | not applied to a directly executed binary — `` $`HOME=/x printenv HOME` `` prints the real HOME; only `sh -c` sees it (2026-10-25) | `.env({ ... })`, or `Bun.spawn(cmd, { env })` |
21
21
  | `ssh host <<'EOF' … EOF` | the heredoc body ran on the LOCAL host (2026-10-23) | `Bun.spawn(["ssh", host, "bash -s"], { stdin: new Blob([script]) })`, or scp a script file |
22
22
  | Globs in `${...}` | literal since 1.4.0; only patterns written in the template expand | write the pattern in the template |
@@ -43,6 +43,7 @@ proc.resourceUsage(); // { maxRSS, cpuTime: { user, system } } — measure, do n
43
43
  - Re-spawning Bun: use `process.execPath`, never `"bun"` from PATH — a mise shim refused a temp HOME, a stray 1.4.0 shim in `~/.bun/install/global/node_modules/.bin` hung rpc tests, and after a reboot PATH resolved `bun` to a vite-plus shim with shim recursion; the `bun test vX.Y.Z` header line is the tell (2026-09-28, 10-26, 10-29). Inside a compiled binary `bun` can be the binary itself — see [build](build.md).
44
44
  - `proc.signalCode` is set when a signal is SENT, not when the child exits: a child ignoring SIGTERM keeps running while `signalCode === "SIGTERM"`; await `proc.exited` with a deadline, then `proc.kill("SIGKILL")` (2026-10-02).
45
45
  - **The js eval kernel SIGKILLs every `Bun.spawn` child when its cell settles** — four Chromium launches in a row died 0.05-9 s after the launching cell completed, and a child parked in `globalThis` does not survive (2026-09-16/10-17). Anything that must outlive a cell (browser, daemon, dev server, `ssh` running a remote job, a `git commit` with slow hooks) starts through `tool.monitor({ command })` or `tool.bash({ run_in_background: true })`; keep only its id/pid in `globalThis`. Conversely `bun --no-orphans script.ts` makes a script exit when its parent dies and SIGKILL every descendant on exit. A stopped long `Bun.$` cell restarts the whole kernel and loses every global; keep helpers in an importable file and restore with `Object.assign(globalThis, await import(path))` (2026-10-02).
46
+ - IPC with a Bun child: `Bun.spawn([process.execPath, "child.ts"], { env: process.env, ipc(message, child) {} })`, then `child.send(value)`; the child uses `process.send(value)` and `process.on("message", fn)` (structured-clone values; measured on 1.4.4).
46
47
  - PTY: `Bun.spawn(["bash"], { terminal: { cols, rows, data(term, chunk) {} } })` then `proc.terminal.write()/resize()` — replaces node-pty and the macOS `script -q /dev/null` trick.
47
48
  - `Bun.spawnSync` blocks the kernel thread and cannot be interrupted: never in an eval cell. `maxBuffer` kills a chatty sync child.
48
49
  - `signal: AbortSignal.timeout(ms)` works for `fetch` and `spawn` alike (`killSignal` picks the signal).
@@ -0,0 +1,34 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type { KernelToolsCapability } from "../kernels/js/kernel-tools-types.ts";
3
+ import type { CellToolUpdateSink } from "./nested-tool-output.ts";
4
+ import type { EvalKernelManager, EvalLanguage } from "./types.ts";
5
+
6
+ export interface BridgeCellBinding {
7
+ readonly token: string | undefined;
8
+ /** First thing a settling cell runs: from then on a call carrying the token gets no kernel tools and streams nowhere. */
9
+ readonly release: () => void;
10
+ }
11
+
12
+ /**
13
+ * Subprocess kernels call the host over the bridge, outside this cell's async context. Their calls carry a fresh
14
+ * secret minted for this run and sent only to this cell's kernel, never the model-visible cell id, so code in another
15
+ * kernel cannot name this cell into its tools or its live view. JS calls already run inside this cell's scope (#1754).
16
+ */
17
+ export function bindBridgeCell(
18
+ manager: EvalKernelManager,
19
+ language: EvalLanguage,
20
+ kernelTools: KernelToolsCapability | undefined,
21
+ toolUpdates: CellToolUpdateSink,
22
+ ): BridgeCellBinding {
23
+ if (language === "js") return { token: undefined, release: () => undefined };
24
+ const token = randomUUID();
25
+ const releaseKernelTools = kernelTools === undefined ? undefined : manager.bindCellKernelTools?.(token, kernelTools);
26
+ const releaseToolUpdates = manager.bindCellToolUpdates?.(token, toolUpdates);
27
+ return {
28
+ token,
29
+ release: () => {
30
+ releaseKernelTools?.();
31
+ releaseToolUpdates?.();
32
+ },
33
+ };
34
+ }
@@ -1,10 +1,5 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
- import {
3
- type AgentToolResult,
4
- type ExtensionContext,
5
- kernelToolsStorage,
6
- sanitizeTerminalLabel,
7
- } from "@code-yeongyu/senpi";
2
+ import { type AgentToolResult, type ExtensionContext, kernelToolsStorage } from "@code-yeongyu/senpi";
8
3
  import type { KernelToHostMessage } from "../bridge/protocol.ts";
9
4
  import { RESERVED_SCHEMA_TOOL } from "../bridge/reserved.ts";
10
5
  import type { AgentExecuteTool } from "../bridges/agent-bridge.ts";
@@ -24,23 +19,17 @@ import {
24
19
  MAX_CAPTURED_IDENTIFIER_CODE_POINTS,
25
20
  recordToolCall,
26
21
  type ToolCallCapture,
27
- toolCallResultPreview,
28
22
  } from "./call-capture.ts";
29
23
  import { completionCallOptions, reservedDispatchContext } from "./cell-reserved-dispatch.ts";
30
24
  import { CellResultBuilder, type CellState } from "./cell-runtime.ts";
31
- import { type EvalImageResizer, marshalToolResult, toolResultIsError } from "./image.ts";
25
+ import type { EvalImageResizer } from "./image.ts";
26
+ import { type ResolvedToolReply, runNestedTool } from "./nested-tool-call.ts";
27
+ import type { CellToolUpdateSink } from "./nested-tool-output.ts";
32
28
  import { upsertStatusEvent } from "./status-events.ts";
33
29
  import type { EvalKernel, EvalStatusEvent, EvalToolDetails } from "./types.ts";
34
30
 
35
31
  export type { CellState } from "./cell-runtime.ts";
36
32
 
37
- type ResolvedToolReply = {
38
- readonly value: unknown;
39
- readonly toolCallOk: boolean;
40
- readonly resultPreview?: string;
41
- readonly errorText?: string;
42
- };
43
-
44
33
  export interface CellBridgeRuntime {
45
34
  readonly executeTool: AgentExecuteTool;
46
35
  readonly listTools?: () => readonly EvalSchemaToolInfo[];
@@ -140,6 +129,11 @@ export class CellHandler {
140
129
  return this.#resultBuilder.liveResult();
141
130
  }
142
131
 
132
+ /** Where the cell's bridge calls (py/rb/jl kernels) stream their nested tools' partial results. */
133
+ get toolUpdates(): CellToolUpdateSink {
134
+ return this.#resultBuilder;
135
+ }
136
+
143
137
  async #handleToolCall(message: Extract<KernelToHostMessage, { type: "tool-call" }>): Promise<void> {
144
138
  const startedAt = Date.now();
145
139
  const metric = createToolCallMetric(message.toolName, startedAt);
@@ -197,31 +191,7 @@ export class CellHandler {
197
191
  }
198
192
  await this.#deliverToolReply(
199
193
  message,
200
- async () => {
201
- const result = await this.#runtime.executeTool(message.toolName, message.args, {
202
- signal: this.#state.signal,
203
- });
204
- const toolCallOk = !toolResultIsError(result);
205
- if (toolCallOk) {
206
- const resultPreview = toolCallResultPreview(result);
207
- return {
208
- value: marshalToolResult(result),
209
- toolCallOk,
210
- ...(resultPreview === undefined ? {} : { resultPreview }),
211
- };
212
- }
213
- let errorText: string | undefined;
214
- for (const part of result.content) {
215
- if (part.type !== "text") continue;
216
- errorText = capCodePoints(sanitizeTerminalLabel(part.text), 512);
217
- break;
218
- }
219
- return {
220
- value: marshalToolResult(result),
221
- toolCallOk,
222
- ...(errorText === undefined ? {} : { errorText }),
223
- };
224
- },
194
+ () => runNestedTool(this.#runtime.executeTool, message, this.#state.signal, this.#resultBuilder),
225
195
  capture,
226
196
  );
227
197
  }
@@ -5,6 +5,7 @@ import { formatModelTruncationNotice } from "../output/output-meta.ts";
5
5
  import { DEFAULT_MAX_BYTES, TailLineRing } from "../output/streaming-output.ts";
6
6
  import type { EvalToolCallMetric } from "./call-capture.ts";
7
7
  import { type EvalImageResizer, EvalOutputCollector, type EvalOutputResult } from "./image.ts";
8
+ import { type CellToolUpdateSink, NestedToolOutput } from "./nested-tool-output.ts";
8
9
  import type {
9
10
  EvalKernelState,
10
11
  EvalMemoryDetails,
@@ -51,8 +52,10 @@ export interface CellResultBuilderOptions {
51
52
  readonly state: CellState;
52
53
  }
53
54
 
54
- export class CellResultBuilder {
55
+ export class CellResultBuilder implements CellToolUpdateSink {
55
56
  readonly #output: EvalOutputCollector;
57
+ readonly #nestedTools = new NestedToolOutput();
58
+ #finished = false;
56
59
  readonly #state: CellState;
57
60
  #memory: KernelMemoryReport | undefined;
58
61
  #restartNotice: string | undefined;
@@ -118,8 +121,25 @@ export class CellResultBuilder {
118
121
  await this.#output.flush();
119
122
  }
120
123
 
124
+ /** A nested tool's partial result streams through the same throttled live update as the cell's own output (#6167). */
125
+ nestedToolUpdate(callId: string, partial: AgentToolResult<unknown>): void {
126
+ if (this.#finished || !this.#nestedTools.update(callId, partial)) return;
127
+ this.#scheduleOutputUpdate();
128
+ }
129
+
130
+ nestedToolSettled(callId: string): void {
131
+ if (this.dropNestedTool(callId)) this.#scheduleOutputUpdate();
132
+ }
133
+
134
+ /** Removes a settled call's partial from the live view without emitting; the caller's next update shows it gone. */
135
+ dropNestedTool(callId: string): boolean {
136
+ if (!this.#nestedTools.drop(callId)) return false;
137
+ this.#state.output = this.#liveCellOutput();
138
+ return true;
139
+ }
140
+
121
141
  liveResult(): AgentToolResult<EvalToolDetails> {
122
- this.#state.output = this.#output.cellTailText();
142
+ this.#state.output = this.#liveCellOutput();
123
143
  return {
124
144
  content: [{ type: "text", text: this.#liveUpdateText() }],
125
145
  details: this.#details(undefined, this.#state.status === "error"),
@@ -149,10 +169,14 @@ export class CellResultBuilder {
149
169
 
150
170
  #emitOutputUpdate(): void {
151
171
  this.#lastOutputUpdateAt = Date.now();
152
- this.#state.output = this.#output.cellTailText();
172
+ this.#state.output = this.#liveCellOutput();
153
173
  this.emitUpdate(false);
154
174
  }
155
175
 
176
+ #liveCellOutput(): string {
177
+ return this.#nestedTools.appendTo(this.#output.cellTailText());
178
+ }
179
+
156
180
  #clearOutputUpdateTimer(): void {
157
181
  if (this.#outputUpdateTimer === undefined) return;
158
182
  clearTimeout(this.#outputUpdateTimer);
@@ -160,6 +184,8 @@ export class CellResultBuilder {
160
184
  }
161
185
 
162
186
  async #finish(isError: boolean): Promise<AgentToolResult<EvalToolDetails>> {
187
+ this.#finished = true;
188
+ this.#nestedTools.clear();
163
189
  this.#clearOutputUpdateTimer();
164
190
  const output = await this.#output.finish();
165
191
  this.#state.output = output.output;
@@ -225,7 +251,7 @@ export class CellResultBuilder {
225
251
  : `queued behind ${this.#state.queuedBehind.join(", ")} in the ${this.#state.input.language} kernel`;
226
252
  }
227
253
  const summary = this.#state.input.summary === undefined ? "" : ` ${this.#state.input.summary}`;
228
- const output = this.#liveLines.text();
254
+ const output = this.#nestedTools.appendLines(this.#liveLines.text(), LIVE_UPDATE_LINES);
229
255
  return `1/1 cells ${this.#state.status}\n[1] ${this.#state.input.language}${summary} ${this.#state.status}${output.length === 0 ? "" : `\n${output}`}`;
230
256
  }
231
257
  }
@@ -0,0 +1,46 @@
1
+ import { sanitizeTerminalLabel } from "@code-yeongyu/senpi";
2
+ import type { KernelToHostMessage } from "../bridge/protocol.ts";
3
+ import type { AgentExecuteTool } from "../bridges/agent-bridge.ts";
4
+ import { capCodePoints, toolCallResultPreview } from "./call-capture.ts";
5
+ import type { CellResultBuilder } from "./cell-runtime.ts";
6
+ import { marshalToolResult, toolResultIsError } from "./image.ts";
7
+
8
+ export type ResolvedToolReply = {
9
+ readonly value: unknown;
10
+ readonly toolCallOk: boolean;
11
+ readonly resultPreview?: string;
12
+ readonly errorText?: string;
13
+ };
14
+
15
+ /** Runs an ordinary host tool for a JS cell; its partial results stream into the cell's live update (#6167). */
16
+ export async function runNestedTool(
17
+ executeTool: AgentExecuteTool,
18
+ message: Extract<KernelToHostMessage, { type: "tool-call" }>,
19
+ signal: AbortSignal,
20
+ live: CellResultBuilder,
21
+ ): Promise<ResolvedToolReply> {
22
+ const result = await executeTool(message.toolName, message.args, {
23
+ signal,
24
+ onUpdate: (partial) => live.nestedToolUpdate(message.callId, partial),
25
+ }).finally(() => live.dropNestedTool(message.callId));
26
+ const toolCallOk = !toolResultIsError(result);
27
+ if (toolCallOk) {
28
+ const resultPreview = toolCallResultPreview(result);
29
+ return {
30
+ value: marshalToolResult(result),
31
+ toolCallOk,
32
+ ...(resultPreview === undefined ? {} : { resultPreview }),
33
+ };
34
+ }
35
+ let errorText: string | undefined;
36
+ for (const part of result.content) {
37
+ if (part.type !== "text") continue;
38
+ errorText = capCodePoints(sanitizeTerminalLabel(part.text), 512);
39
+ break;
40
+ }
41
+ return {
42
+ value: marshalToolResult(result),
43
+ toolCallOk,
44
+ ...(errorText === undefined ? {} : { errorText }),
45
+ };
46
+ }
@@ -0,0 +1,52 @@
1
+ import type { AgentToolResult } from "@code-yeongyu/senpi";
2
+ import { DEFAULT_MAX_BYTES, truncateTailBytes } from "../output/streaming-output.ts";
3
+
4
+ /** Where a running cell receives the partial results of the tools it calls, so they stream live (#6167). */
5
+ export interface CellToolUpdateSink {
6
+ nestedToolUpdate(callId: string, partial: AgentToolResult<unknown>): void;
7
+ nestedToolSettled(callId: string): void;
8
+ }
9
+
10
+ /**
11
+ * The latest partial output of each tool call a cell is still awaiting. It joins the cell's live view only: the
12
+ * value the tool returns to the cell and the cell's own result never contain it.
13
+ */
14
+ export class NestedToolOutput {
15
+ readonly #byCall = new Map<string, string>();
16
+
17
+ /** Keeps the call's newest partial; false when it adds no new text. */
18
+ update(callId: string, partial: AgentToolResult<unknown>): boolean {
19
+ const text = partial.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n");
20
+ if (text.length === 0 || this.#byCall.get(callId) === text) return false;
21
+ this.#byCall.set(callId, text);
22
+ return true;
23
+ }
24
+
25
+ /** Forgets a settled call; false when it never showed output. */
26
+ drop(callId: string): boolean {
27
+ return this.#byCall.delete(callId);
28
+ }
29
+
30
+ clear(): void {
31
+ this.#byCall.clear();
32
+ }
33
+
34
+ appendTo(output: string): string {
35
+ let combined = output;
36
+ for (const text of this.#byCall.values()) {
37
+ const tail = truncateTailBytes(text, DEFAULT_MAX_BYTES).text;
38
+ combined = combined.length === 0 || combined.endsWith("\n") ? `${combined}${tail}` : `${combined}\n${tail}`;
39
+ }
40
+ return combined;
41
+ }
42
+
43
+ /** Like `appendTo`, kept to the last `maxLines` lines; `output` is returned untouched while no call shows output. */
44
+ appendLines(output: string, maxLines: number): string {
45
+ if (this.#byCall.size === 0) return output;
46
+ const combined = this.appendTo(output);
47
+ const hasTrailingNewline = combined.endsWith("\n");
48
+ const lines = combined.split("\n");
49
+ if (hasTrailingNewline) lines.pop();
50
+ return `${lines.slice(-maxLines).join("\n")}${hasTrailingNewline ? "\n" : ""}`;
51
+ }
52
+ }
@@ -14,6 +14,7 @@ import type { PackagesInstallEnvironments } from "../environments/packages-insta
14
14
  import { KERNEL_TOOLS_CAPABILITIES, type KernelToolsCapability } from "../kernels/js/kernel-tools-types.ts";
15
15
  import { sandboxCellExecutor, sandboxRuntimeInfo } from "../kernels/sandbox/sandbox-cell.ts";
16
16
  import { TIMEOUT_PAUSE_OP, TIMEOUT_RESUME_OP } from "../timeouts/bridge-timeout.ts";
17
+ import { bindBridgeCell } from "./bridge-cell-binding.ts";
17
18
  import { abortError, CellExecution, defaultTimeoutFactory } from "./cell-execution.ts";
18
19
  import { CellHandler, type CellState } from "./cell-handler.ts";
19
20
  import type { EvalDetachedCellManager } from "./detached-cell-manager.ts";
@@ -214,15 +215,12 @@ async function executeCell(
214
215
  // Computed before the handler so its construction-time snapshot captures this cell's capability.
215
216
  // Worker messages later restore that snapshot before calling host tools (#1754, #2512).
216
217
  const kernelTools = kernelToolsFor(kernel);
217
- // Subprocess kernels call the host over the bridge, outside this async context. Their calls carry a fresh secret
218
- // minted for this run and sent only to this cell's kernel, never the model-visible cell id, so code in another
219
- // kernel cannot name this cell into its tools. JS calls already run inside this cell's scope (#1754).
220
- const bridgeCellToken =
221
- kernelTools === undefined || invocation.input.language === "js" ? undefined : randomUUID();
222
- releaseCellKernelTools =
223
- kernelTools === undefined || bridgeCellToken === undefined
224
- ? undefined
225
- : options.kernelManager.bindCellKernelTools?.(bridgeCellToken, kernelTools);
218
+ const bridgeCell = bindBridgeCell(options.kernelManager, invocation.input.language, kernelTools, {
219
+ nestedToolUpdate: (callId, partial) => handler?.toolUpdates.nestedToolUpdate(callId, partial),
220
+ nestedToolSettled: (callId) => handler?.toolUpdates.nestedToolSettled(callId),
221
+ });
222
+ const bridgeCellToken = bridgeCell.token;
223
+ releaseCellKernelTools = bridgeCell.release;
226
224
  const runBound = async (): Promise<AgentToolResult<EvalToolDetails>> => {
227
225
  const queue = kernel.queueSnapshot();
228
226
  state.queuedBehind = [...(queue.activeCellId === null ? [] : [queue.activeCellId]), ...queue.queuedCellIds];
package/src/tool/types.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  } from "../config/settings.ts";
16
16
  import type { KernelToolsCapability, KernelToolsDescribeResult } from "../kernels/js/kernel-tools-types.ts";
17
17
  import type { TruncationMeta } from "../output/output-meta.ts";
18
+ import type { CellToolUpdateSink } from "./nested-tool-output.ts";
18
19
 
19
20
  export const evalLanguageOrder = ["js", "py", "rb", "jl"] as const;
20
21
  export type EvalLanguage = (typeof evalLanguageOrder)[number];
@@ -208,7 +209,8 @@ export interface EvalKernelRunInput {
208
209
  */
209
210
  readonly resolveAtStart?: () => CellSourceAtStart;
210
211
  /**
211
- * Subprocess kernels attach this to the cell's host calls, and the host gives those calls the cell's kernel tools.
212
+ * Subprocess kernels attach this to the cell's host calls, and the host gives those calls the cell's kernel tools
213
+ * and streams their partial results into the cell's live update.
212
214
  * A fresh secret per run, sent only to the kernel that runs the cell; never a model-visible id.
213
215
  */
214
216
  readonly bridgeCellToken?: string;
@@ -263,6 +265,8 @@ export interface EvalKernelManager {
263
265
  * the host over the bridge, outside the cell's async context). The returned release runs when the cell settles.
264
266
  */
265
267
  bindCellKernelTools?(token: string, capability: KernelToolsCapability): () => void;
268
+ /** Streams the partial results of the tools a subprocess-kernel cell calls over the bridge into that cell (#6167). */
269
+ bindCellToolUpdates?(token: string, sink: CellToolUpdateSink): () => void;
266
270
  }
267
271
 
268
272
  export type ExecuteTool = (