@code-yeongyu/senpi-codemode 2026.11.6-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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
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
+
3
17
  ## [2026.11.6-1] - 2026-11-06
4
18
 
5
19
  ### Breaking Changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@code-yeongyu/senpi-codemode",
3
- "version": "2026.11.6-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.6-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.6-1"
41
+ "@code-yeongyu/senpi": "2026.11.6-2"
42
42
  },
43
43
  "devDependencies": {
44
- "@code-yeongyu/senpi": "2026.11.6-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,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
@@ -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
  }
@@ -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 = (