@code-yeongyu/senpi-codemode 2026.11.25 → 2026.11.27

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 (52) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +87 -0
  3. package/package.json +5 -5
  4. package/src/bridge/reserved.ts +2 -0
  5. package/src/config/feature-settings.ts +19 -0
  6. package/src/config/settings.ts +8 -0
  7. package/src/extension/eval-status-ticker.ts +5 -2
  8. package/src/extension/runtime-factory.ts +31 -5
  9. package/src/extension/session-manager.ts +4 -1
  10. package/src/index.ts +14 -6
  11. package/src/kernels/js/babel-ast.ts +64 -0
  12. package/src/kernels/js/binding-patterns.js +166 -0
  13. package/src/kernels/js/cell-run-context.js +8 -0
  14. package/src/kernels/js/declaration-extent.js +157 -0
  15. package/src/kernels/js/erase-types.ts +174 -0
  16. package/src/kernels/js/js-source-scan.js +181 -0
  17. package/src/kernels/js/kernel-contract.ts +2 -0
  18. package/src/kernels/js/last-expression.js +207 -0
  19. package/src/kernels/js/local-module-loader.ts +7 -2
  20. package/src/kernels/js/persist-declarations.js +233 -0
  21. package/src/kernels/js/rewrite-imports.ts +3 -60
  22. package/src/kernels/js/typescript-cell.ts +39 -0
  23. package/src/kernels/js/worker-core.js +1 -0
  24. package/src/kernels/js/worker-indirect-eval.js +4 -860
  25. package/src/kernels/js/worker-runtime.js +2 -0
  26. package/src/kernels/js/worker-scope.js +71 -0
  27. package/src/kernels/js/worker-startup.ts +1 -0
  28. package/src/prompt/eval-prompt-template.ts +4 -2
  29. package/src/prompt/eval-prompt.ts +4 -0
  30. package/src/skill/bun/SKILL.md +1 -0
  31. package/src/tool/cell-handler.ts +17 -1
  32. package/src/tool/detached-cell-manager.ts +42 -4
  33. package/src/tool/detached-notification-queue.ts +48 -7
  34. package/src/tool/detached-settling.ts +26 -0
  35. package/src/tool/eval-tool-options.ts +5 -1
  36. package/src/tool/eval-tool.ts +3 -1
  37. package/src/tool/js-cell-parse-message.ts +11 -3
  38. package/src/tool/managed-cell.ts +3 -0
  39. package/src/tool/run-eval-cell.ts +36 -11
  40. package/src/tool/scoped-watches.ts +53 -0
  41. package/src/tool/types.ts +14 -0
  42. package/src/written-files/model-writes.ts +55 -0
  43. package/src/written-files/ownership.ts +73 -0
  44. package/src/written-files/report.ts +63 -0
  45. package/src/written-files/scan-boundaries.ts +164 -0
  46. package/src/written-files/source-file.ts +31 -0
  47. package/src/written-files/tracker.ts +361 -0
  48. package/src/written-files/window.ts +92 -0
  49. package/src/written-files/workspace-fs.ts +104 -0
  50. package/src/written-files/workspace-scan.ts +253 -0
  51. package/src/written-files/write-hooks.ts +155 -0
  52. package/src/written-files/written-files.ts +155 -0
@@ -6,6 +6,7 @@ import { inspect } from "node:util";
6
6
  import { encodeDisplayImage, resolveDisplayOps } from "./display-image.js";
7
7
  import { terminateProcessGroups, terminateProcessTrees } from "./process-tree.js";
8
8
  import { awaitMaybePromise, indirectEval, wrapUserCode } from "./worker-indirect-eval.js";
9
+ import { installScopeHelper } from "./worker-scope.js";
9
10
  import { INJECTED_GROUP } from "./worker-cwd.js";
10
11
  import { installShellCapture } from "./worker-shell-capture.js";
11
12
  import { bindKernelBun } from "./worker-webview.js";
@@ -54,6 +55,7 @@ export class JsWorkerRuntime {
54
55
  disabled: options.kernelToolsDisabled === true,
55
56
  });
56
57
  this.#installGlobals();
58
+ if (options.scopeHelper === true) installScopeHelper({ callTool: (name, args) => this.#callTool(name, args), emitStatus: (event) => this.#emitStatus(event) });
57
59
  }
58
60
 
59
61
  get kernelTools() {
@@ -0,0 +1,71 @@
1
+ import { rmSync } from "node:fs";
2
+ import { mkdtemp, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { onCellRelease, runOutsideCell } from "./cell-run-context.js";
6
+ import { terminateProcessTrees } from "./process-tree.js";
7
+
8
+ // Mirrors SCOPE_MONITOR_OP in src/bridge/reserved.ts (this worker file cannot import TypeScript).
9
+ const SCOPE_MONITOR_OP = "scope-monitor";
10
+ const CHILD_STOP_GRACE_MS = 2_000;
11
+ const ENDED_WATCH_RE = /^No terminal session found with id/u;
12
+
13
+ /**
14
+ * Installs `scope()`: an AsyncDisposableStack whose helpers start a resource and register its teardown, so
15
+ * `await using s = scope()` closes everything the block opened when it exits, on success or throw. Disposal is the
16
+ * native stack's: once only, in reverse order, every teardown attempted. `move()` hands the open resources on.
17
+ * Teardown runs outside the cell context, so it still works after the cell was stopped; a stopped cell's servers and
18
+ * children are also ended by cell ownership, its temp dirs by the release hook below, its watches by the host.
19
+ */
20
+ export function installScopeHelper({ callTool, emitStatus }) {
21
+ class CellScope extends AsyncDisposableStack {
22
+ serve(options) {
23
+ const server = Bun.serve(options);
24
+ this.defer(() => runOutsideCell(() => server.stop(true)));
25
+ return server;
26
+ }
27
+
28
+ spawn(command, options) {
29
+ const child = Bun.spawn(command, options);
30
+ this.defer(() => runOutsideCell(() => stopChild(child)));
31
+ return child;
32
+ }
33
+
34
+ async tempDir(prefix = "eval-scope-") {
35
+ const path = await mkdtemp(join(tmpdir(), prefix));
36
+ const forget = onCellRelease(() => runOutsideCell(() => rmSync(path, { recursive: true, force: true })));
37
+ this.defer(async () => {
38
+ forget();
39
+ await runOutsideCell(() => rm(path, { recursive: true, force: true }));
40
+ });
41
+ return path;
42
+ }
43
+
44
+ async monitor(args) {
45
+ if (args?.persistent === true) {
46
+ throw new TypeError("scope().monitor() ends its watch with the scope; start a standing watch with tool.monitor({ persistent: true })");
47
+ }
48
+ const result = await callTool("monitor", args ?? {});
49
+ const bashId = result?.details?.bash_id;
50
+ if (typeof bashId !== "string") throw new Error(`monitor did not start a watch: ${result?.text ?? String(result)}`);
51
+ emitStatus({ op: SCOPE_MONITOR_OP, bashId, held: true });
52
+ this.defer(async () => {
53
+ const stopped = await callTool("kill_bash", { bash_id: bashId });
54
+ if (isToolError(stopped) && !ENDED_WATCH_RE.test(stopped.text ?? "")) throw new Error(`kill_bash ${bashId}: ${stopped.text}`);
55
+ emitStatus({ op: SCOPE_MONITOR_OP, bashId, held: false });
56
+ });
57
+ return result;
58
+ }
59
+ }
60
+ globalThis.scope = () => new CellScope();
61
+ }
62
+
63
+ async function stopChild(child) {
64
+ if (child.exitCode !== null || child.signalCode !== null) return;
65
+ await terminateProcessTrees([child.pid], { graceMs: CHILD_STOP_GRACE_MS, settled: child.exited });
66
+ await child.exited;
67
+ }
68
+
69
+ function isToolError(result) {
70
+ return result !== null && typeof result === "object" && (result.hasError === true || result.isError === true);
71
+ }
@@ -116,6 +116,7 @@ async function initializeWorker(worker: WorkerLike, hooks: WorkerStartupHooks, s
116
116
  : {}),
117
117
  ...(options.memory === undefined ? {} : { memory: options.memory }),
118
118
  ...(options.kernelToolsEnabled === false ? { kernelToolsDisabled: true } : {}),
119
+ ...(options.scopeHelper === true ? { scopeHelper: true } : {}),
119
120
  ...(options.killGuard === undefined
120
121
  ? {}
121
122
  : { killGuard: { moduleUrl: String(options.killGuard.moduleUrl), agentPid: options.killGuard.agentPid } }),
@@ -31,7 +31,7 @@ Host: {{hostLine}}. Cells execute here. \`parallel(thunks)\` runs through a fixe
31
31
  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.
32
32
 
33
33
  {{#if py}}Python runs on a live event loop: use top-level \`await\`; \`asyncio.run(…)\` raises.{{/if}}
34
- {{#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}}
34
+ {{#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}}{{#if jsTypescript}} A \`"js"\` cell may be written in TypeScript: its types are erased in place before it runs and never checked, so errors keep your line and column; enum, namespace and constructor parameter properties are refused. Keep reusable typed code in a \`.ts\` module, check it with \`bun check\`, and import it.{{/if}}{{#if jsScope}} Close what a cell opens with \`using\` / \`await using\`: \`await using s = scope()\`, then \`s.serve(opts)\`, \`s.spawn(cmd, opts)\`, \`await s.tempDir()\`, \`await s.monitor({ command, filter })\`, \`s.defer(fn)\` for any other cleanup and \`s.use(x)\` for anything disposable; all of it closes when the block ends, on throw too, and \`s.move()\` hands it on.{{/if}}
35
35
  {{#if rb}}Ruby: synchronous; helper options are keyword args{{#if spawns}} (e.g. \`output("id", limit: 2)\`){{/if}}; the last expression auto-displays unless it is \`nil\`, an assignment, or a definition (like IRB).{{/if}}
36
36
  {{#if jl}}Julia: synchronous; helper options are standard keyword args{{#if spawns}} (e.g. \`output("id", limit=2)\`){{/if}}; the last expression auto-displays unless it is an assignment or a definition (like the Julia REPL).{{/if}}
37
37
  On error, fix and re-run only the failing step; a normal error keeps state, while a timeout or stop message says whether the kernel restarted.
@@ -71,7 +71,9 @@ log(message) → None
71
71
  Progress line above the status tree.
72
72
  phase(title) → None
73
73
  Phase grouping subsequent status lines.
74
- {{#if kernelPreludeDocs}}{{kernelPreludeDocs}}
74
+ {{#if jsScope}}scope() → AsyncDisposableStack (JS only)
75
+ \`await using s = scope()\`; s.serve / s.spawn / s.tempDir / s.monitor start a resource that closes with the block; s.defer(fn), s.use(x), s.move().
76
+ {{/if}}{{#if kernelPreludeDocs}}{{kernelPreludeDocs}}
75
77
  {{/if}}\`\`\`
76
78
  </prelude>
77
79
  {{#if spawns}}
@@ -42,6 +42,8 @@ export interface EvalPromptOptions {
42
42
  readonly kernelPreludes?: readonly KernelPreludeContribution[];
43
43
  /** Tools withheld from the model's direct list and reachable only as `tool.<name>(...)` in a cell (senpi#6886). */
44
44
  readonly evalOnlyTools?: readonly string[];
45
+ /** `jsCells`: document TypeScript cells and the Bun-only `scope()` helper (senpi#7381); absent leaves the text as it was. */
46
+ readonly jsCells?: { readonly typescript: boolean; readonly scope: boolean };
45
47
  }
46
48
 
47
49
  /** Prompt dialect for the eval-first batching emphasis. */
@@ -109,6 +111,8 @@ export function buildEvalPrompt(
109
111
  styleDefault: style === "default",
110
112
  hostLine: options.hostLine ?? "",
111
113
  jsBun: options.jsRuntime?.name === "bun",
114
+ jsTypescript: enabled.js && options.jsCells?.typescript === true,
115
+ jsScope: enabled.js && options.jsCells?.scope === true && options.jsRuntime?.name === "bun",
112
116
  jsVersion: options.jsRuntime?.version ?? "",
113
117
  // pinnedDisplayPath: the test-only checkout pin (senpi#5067); the path itself unless SENPI_TEST_WORKSTATION pins it.
114
118
  bunSkillPath: options.bunSkillPath === undefined ? "" : pinnedDisplayPath(options.bunSkillPath),
@@ -51,3 +51,4 @@ Free wins (no code change): 2x lower CPU, 13-48% less server memory, 2-2.5x fast
51
51
  7. **Read the matching reference before using an unfamiliar API** — signatures and caveats (`Bun.markdown` HTML is unsanitized, HTTP/3 is experimental, `writer({ append: true })` truncated a results file) live there, not here; [session-recipes](references/session-recipes.md) holds the rest of the session-learned traps.
52
52
  8. **Upgrading a project or debugging behavior that changed?** Read [breaking-changes](references/breaking-changes.md) first — 1.4.0 changed YAML/TOML strictness, `.xml`/`.css` imports, `Bun.$` globbing and fetch headers; 1.4.1-1.4.4 changed `Bun.Glob` parsing, WebSocket close timing and `bun install` flag handling.
53
53
  9. **TLS errors after upgrade are usually intentional** — 1.4.x tightened certificate verification across `fetch`, `tls.connect`, `Bun.connect`, `RedisClient`, `Bun.SQL`. See [security](references/security.md) before loosening anything.
54
+ 10. **Close what a cell opens with `using` / `await using`.** The binding disposes when its block exits, on a throw too: `await using child = Bun.spawn(...)` kills and awaits the child, `await using dir = await fs.promises.mkdtempDisposable(prefix)` removes the directory, and `await using stack = new AsyncDisposableStack()` collects the rest through `stack.use(x)`, `stack.adopt(value, close)` and `stack.defer(fn)`. A `Bun.serve` server only disposes synchronously, so register `stack.defer(() => server.stop(true))`; values with no dispose method keep `try/finally`. Under the `jsCells.scope` profile, `scope()` does this for servers, children, temp dirs and `tool.monitor` watches, and `stack.move()` hands what must outlive the block to its new owner.
@@ -25,6 +25,7 @@ import { CellResultBuilder, type CellState } from "./cell-runtime.ts";
25
25
  import type { EvalImageResizer } from "./image.ts";
26
26
  import { type ResolvedToolReply, runNestedTool } from "./nested-tool-call.ts";
27
27
  import type { CellToolUpdateSink } from "./nested-tool-output.ts";
28
+ import { ScopedWatches } from "./scoped-watches.ts";
28
29
  import { upsertStatusEvent } from "./status-events.ts";
29
30
  import { isCoreWidgetName } from "./tool-widgets.ts";
30
31
  import type { EvalKernel, EvalStatusEvent, EvalToolDetails } from "./types.ts";
@@ -55,6 +56,8 @@ export class CellHandler {
55
56
  readonly #runtime: CellBridgeRuntime;
56
57
  readonly #resultBuilder: CellResultBuilder;
57
58
  readonly #dispatchContext: ReturnType<typeof AsyncLocalStorage.snapshot>;
59
+ readonly #scopedWatches = new ScopedWatches();
60
+ #settledOk = false;
58
61
 
59
62
  constructor(kernel: EvalKernel, state: CellState, runtime: CellBridgeRuntime) {
60
63
  this.#kernel = kernel;
@@ -87,7 +90,7 @@ export class CellHandler {
87
90
  this.#resultBuilder.setPhase(message.title);
88
91
  return;
89
92
  case "status":
90
- this.#recordStatus(message.event);
93
+ if (!this.#scopedWatches.observe(message.event)) this.#recordStatus(message.event);
91
94
  return;
92
95
  case "log":
93
96
  this.#resultBuilder.push(`${message.message}\n`);
@@ -115,13 +118,26 @@ export class CellHandler {
115
118
  }
116
119
 
117
120
  async finalize(result: Extract<KernelToHostMessage, { type: "result" }>): Promise<AgentToolResult<EvalToolDetails>> {
121
+ this.#settledOk = result.ok;
122
+ await this.stopScopedWatches();
118
123
  return await this.#resultBuilder.finalize(result);
119
124
  }
120
125
 
121
126
  async finalizeCancellation(error: Error): Promise<AgentToolResult<EvalToolDetails>> {
127
+ await this.stopScopedWatches();
122
128
  return await this.#resultBuilder.finalizeCancellation(error);
123
129
  }
124
130
 
131
+ /**
132
+ * A cell that ends without an ok result (error, stop, timeout) cannot close its scoped watches itself, so the host
133
+ * does (senpi#7381). An ok cell already closed them, or moved them on deliberately. Stopping twice is a no-op.
134
+ */
135
+ async stopScopedWatches(): Promise<void> {
136
+ if (this.#settledOk) return;
137
+ for (const failure of await this.#scopedWatches.stopHeld(this.#runtime.executeTool))
138
+ this.#resultBuilder.push(`${failure}\n`);
139
+ }
140
+
125
141
  async flushOutput(): Promise<void> {
126
142
  await this.#resultBuilder.flushOutput();
127
143
  }
@@ -21,6 +21,7 @@ import {
21
21
  } from "./detached-cell-state.ts";
22
22
  import { detachedStatusEntries, detachedWakeSourceState } from "./detached-cell-status.ts";
23
23
  import { DetachedNotificationQueue } from "./detached-notification-queue.ts";
24
+ import { SettlingCells } from "./detached-settling.ts";
24
25
  import { createManagedCell, type LiveResultProvider, type ManagedCell } from "./managed-cell.ts";
25
26
  import { SettledImageSpill } from "./settled-image-spill.ts";
26
27
  import { TerminalSnapshotStore } from "./terminal-snapshot-store.ts";
@@ -90,6 +91,9 @@ export class EvalDetachedCellManager {
90
91
  readonly #cells = new Map<string, ManagedCell>();
91
92
  readonly #interrupting = new Map<string, ManagedCell>();
92
93
  readonly #detached = new Map<string, ManagedCell>();
94
+ /** Ended cells whose final result is still settling, by id; a new cell under the id supersedes the old one. */
95
+ readonly #amending = new Map<string, ManagedCell>();
96
+ readonly #settling = new SettlingCells<ManagedCell>(() => this.#emitWakeSourceState([...this.#detached.values()]));
93
97
  readonly #terminalSnapshots: TerminalSnapshotStore;
94
98
  readonly #notificationQueue: DetachedNotificationQueue;
95
99
  readonly #now: () => number;
@@ -130,6 +134,7 @@ export class EvalDetachedCellManager {
130
134
  this.#cells.delete(cellId);
131
135
  }
132
136
  this.#terminalSnapshots.delete(cellId);
137
+ this.#amending.delete(cellId);
133
138
  const cell = createManagedCell({
134
139
  cellId,
135
140
  input,
@@ -191,13 +196,29 @@ export class EvalDetachedCellManager {
191
196
  return true;
192
197
  }
193
198
 
194
- complete(cell: ManagedCell, result: AgentToolResult<EvalToolDetails>): boolean {
199
+ /**
200
+ * Ends the cell with `result` now. When `final` is given, the cell's result becomes what it resolves to (the result
201
+ * with its written files) and the completion notification waits for it; the state never does.
202
+ */
203
+ complete(
204
+ cell: ManagedCell,
205
+ result: AgentToolResult<EvalToolDetails>,
206
+ final?: Promise<AgentToolResult<EvalToolDetails>>,
207
+ ): boolean {
195
208
  const state =
196
209
  result.details.cells?.[0]?.status === "cancelled"
197
210
  ? "cancelled"
198
211
  : result.details.isError === true
199
212
  ? "failed"
200
213
  : "completed";
214
+ if (final !== undefined && allowsDetachedCellTransition(cell.state, state)) {
215
+ this.#amending.set(cell.cellId, cell);
216
+ // A settlement that fails keeps the result the cell ended with.
217
+ cell.finalResult = final.then(
218
+ (amended) => this.#amend(cell, amended),
219
+ () => this.#amend(cell, undefined),
220
+ );
221
+ }
201
222
  return this.#settle(cell, state, result);
202
223
  }
203
224
 
@@ -235,9 +256,13 @@ export class EvalDetachedCellManager {
235
256
  return { live: this.liveCells(), recent: this.#terminalSnapshots.list() };
236
257
  }
237
258
 
259
+ /** The cell's final snapshot: once it ended and its result has its written files. */
238
260
  async waitForTerminal(cellId: string): Promise<EvalDetachedCellSnapshot> {
239
- const live = this.#cells.get(cellId);
240
- return live === undefined ? this.#terminal(cellId) : await live.terminal.promise;
261
+ const cell = this.#cells.get(cellId) ?? this.#amending.get(cellId);
262
+ if (cell === undefined) return this.#terminal(cellId);
263
+ await cell.terminal.promise;
264
+ await cell.finalResult;
265
+ return this.#snapshot(cell);
241
266
  }
242
267
 
243
268
  async dispose(): Promise<void> {
@@ -279,6 +304,10 @@ export class EvalDetachedCellManager {
279
304
  this.#refreshTerminalSnapshot(cell);
280
305
  if (cell.wasDetached) {
281
306
  this.#detached.delete(cell.cellId);
307
+ const settling =
308
+ cell.finalResult === undefined || cell.notificationQueued
309
+ ? undefined
310
+ : { ready: cell.finalResult, onDelivered: this.#settling.hold(cell) };
282
311
  this.#emitStatus();
283
312
  if (!cell.notificationQueued) {
284
313
  cell.notificationQueued = true;
@@ -287,6 +316,7 @@ export class EvalDetachedCellManager {
287
316
  await cell.interruptOutcome?.promise;
288
317
  return this.#snapshot(cell);
289
318
  },
319
+ ...settling,
290
320
  });
291
321
  }
292
322
  }
@@ -337,6 +367,14 @@ export class EvalDetachedCellManager {
337
367
  }
338
368
  }
339
369
 
370
+ #amend(cell: ManagedCell, result: AgentToolResult<EvalToolDetails> | undefined): void {
371
+ if (this.#amending.get(cell.cellId) !== cell) return;
372
+ this.#amending.delete(cell.cellId);
373
+ if (result === undefined) return;
374
+ cell.terminalResult = result;
375
+ this.#refreshTerminalSnapshot(cell);
376
+ }
377
+
340
378
  #refreshTerminalSnapshot(cell: ManagedCell): void {
341
379
  if (!this.#cells.has(cell.cellId)) this.#terminalSnapshots.remember(this.#snapshot(cell));
342
380
  }
@@ -348,7 +386,7 @@ export class EvalDetachedCellManager {
348
386
  }
349
387
 
350
388
  #emitWakeSourceState(liveCells: readonly ManagedCell[]): void {
351
- this.#onWakeSourceState?.(detachedWakeSourceState(liveCells));
389
+ this.#onWakeSourceState?.(detachedWakeSourceState([...liveCells, ...this.#settling.values()]));
352
390
  }
353
391
 
354
392
  #snapshot(cell: ManagedCell): EvalDetachedCellSnapshot {
@@ -3,11 +3,22 @@ import { buildDetachedCellNotification } from "./detached-cell-notification.ts";
3
3
 
4
4
  export interface PendingDetachedNotification {
5
5
  readonly snapshot: () => EvalDetachedCellSnapshot | Promise<EvalDetachedCellSnapshot>;
6
+ /**
7
+ * Resolves once the cell's own result is final (its write hooks returned). The notification joins a batch only then,
8
+ * so one cell's slow hook never holds back another cell's notification. If it rejects, the notification is still
9
+ * delivered, with the result the cell has.
10
+ */
11
+ readonly ready?: Promise<void>;
12
+ /** Called once the notification was handed to the notifier, or its delivery failed. */
13
+ readonly onDelivered?: () => void;
6
14
  }
7
15
 
16
+ type QueuedNotification = Omit<PendingDetachedNotification, "ready">;
17
+
8
18
  export class DetachedNotificationQueue {
9
19
  readonly #notifier: EvalDetachedCellNotifier | undefined;
10
- #pending: PendingDetachedNotification[] = [];
20
+ #pending: QueuedNotification[] = [];
21
+ readonly #waiting = new Set<Promise<void>>();
11
22
  #flush: Promise<void> | undefined;
12
23
 
13
24
  constructor(notifier: EvalDetachedCellNotifier | undefined) {
@@ -15,23 +26,46 @@ export class DetachedNotificationQueue {
15
26
  }
16
27
 
17
28
  enqueue(notification: PendingDetachedNotification): void {
18
- this.#pending.push(notification);
19
- this.#schedule();
29
+ const { ready, ...queued } = notification;
30
+ if (ready === undefined) {
31
+ this.#push(queued);
32
+ return;
33
+ }
34
+ const deliver = () => {
35
+ this.#waiting.delete(waiting);
36
+ this.#push(queued);
37
+ };
38
+ const waiting = ready.then(deliver, deliver);
39
+ this.#waiting.add(waiting);
20
40
  }
21
41
 
42
+ /** Resolves once every notification enqueued so far was delivered, including those still waiting to be ready. */
22
43
  async flush(): Promise<void> {
44
+ while (this.#waiting.size > 0) await Promise.all(this.#waiting);
23
45
  const flush = this.#flush;
24
46
  if (flush !== undefined) await flush;
25
47
  }
26
48
 
49
+ #push(notification: QueuedNotification): void {
50
+ this.#pending.push(notification);
51
+ this.#schedule();
52
+ }
53
+
27
54
  #schedule(): void {
28
55
  if (this.#flush !== undefined) return;
29
56
  const flush = Promise.resolve().then(async () => {
30
57
  const pending = this.#pending.splice(0);
31
- const notifications = await Promise.all(
32
- pending.map(async (item) => buildDetachedCellNotification(await item.snapshot())),
33
- );
34
- this.#notifier?.notify(notifications);
58
+ const delivered = this.#deliver(pending);
59
+ const failures: unknown[] = [];
60
+ await delivered.catch((error: unknown) => failures.push(error));
61
+ for (const item of pending) {
62
+ try {
63
+ item.onDelivered?.();
64
+ } catch (error) {
65
+ failures.push(error);
66
+ }
67
+ }
68
+ if (failures.length > 0) throw failures[0];
35
69
  });
36
70
  this.#flush = flush;
37
71
  void flush.then(
@@ -40,6 +74,13 @@ export class DetachedNotificationQueue {
40
74
  );
41
75
  }
42
76
 
77
+ async #deliver(pending: readonly QueuedNotification[]): Promise<void> {
78
+ const notifications = await Promise.all(
79
+ pending.map(async (item) => buildDetachedCellNotification(await item.snapshot())),
80
+ );
81
+ this.#notifier?.notify(notifications);
82
+ }
83
+
43
84
  #finish(flush: Promise<void>): void {
44
85
  if (this.#flush !== flush) return;
45
86
  this.#flush = undefined;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Ended detached cells whose completion notification still waits for their written files to settle. They stay in the
3
+ * wake-source count until the notification is handed over: the engine takes custody of a notification only at
4
+ * delivery, and a wake-source record, unlike an extension-opened obligation, is retired by the engine when a session is
5
+ * restored, so a process that dies mid-settlement cannot leave the session waiting forever.
6
+ */
7
+ export class SettlingCells<Cell> {
8
+ readonly #cells = new Set<Cell>();
9
+ readonly #onRelease: () => void;
10
+
11
+ constructor(onRelease: () => void) {
12
+ this.#onRelease = onRelease;
13
+ }
14
+
15
+ /** Counts `cell` from now on; the returned release stops counting it, once. */
16
+ hold(cell: Cell): () => void {
17
+ this.#cells.add(cell);
18
+ return () => {
19
+ if (this.#cells.delete(cell)) this.#onRelease();
20
+ };
21
+ }
22
+
23
+ values(): readonly Cell[] {
24
+ return [...this.#cells];
25
+ }
26
+ }
@@ -2,6 +2,7 @@ import type {
2
2
  AgentToolResult,
3
3
  AgentToolUpdateCallback,
4
4
  ExtensionContext,
5
+ ExtensionToolContext,
5
6
  KernelPreludeContribution,
6
7
  ToolDefinition,
7
8
  } from "@code-yeongyu/senpi";
@@ -12,6 +13,7 @@ import type { JsEnvironments } from "../environments/js-environments.ts";
12
13
  import type { PythonEnvironments } from "../environments/python-environments.ts";
13
14
  import type { EvalExecutionTracker } from "../extension/session-manager.ts";
14
15
  import type { HandleRegistry } from "../handles/handle-registry.ts";
16
+ import type { WrittenFiles } from "../written-files/written-files.ts";
15
17
  import type { EvalTimeoutFactory } from "./cell-execution.ts";
16
18
  import type { EvalDetachedCellManager } from "./detached-cell-manager.ts";
17
19
  import type { EvalExecutionEventPayload } from "./eval-execution-event.ts";
@@ -79,6 +81,8 @@ export interface CreateEvalToolOptions {
79
81
  readonly promptKernelPreludes?: readonly KernelPreludeContribution[];
80
82
  /** Tools the session reaches only through eval; the description names them. Snapshot taken at (re)registration. */
81
83
  readonly evalOnlyTools?: readonly string[];
84
+ /** The session's written-files check; absent before session_start, and then cells report no written files. */
85
+ readonly writtenFiles?: WrittenFiles;
82
86
  }
83
87
 
84
88
  export interface EvalCellInvocation {
@@ -86,5 +90,5 @@ export interface EvalCellInvocation {
86
90
  readonly input: EvalToolInput;
87
91
  readonly signal: AbortSignal;
88
92
  readonly onUpdate: AgentToolUpdateCallback<EvalToolDetails> | undefined;
89
- readonly ctx: ExtensionContext;
93
+ readonly ctx: ExtensionToolContext;
90
94
  }
@@ -1,6 +1,6 @@
1
1
  import type { AgentToolResult, ToolDefinition } from "@code-yeongyu/senpi";
2
2
  import type { TUnsafe } from "typebox";
3
- import { resolveAdvertiseHelpers, resolveSandbox } from "../config/feature-settings.ts";
3
+ import { resolveAdvertiseHelpers, resolveJsCells, resolveSandbox } from "../config/feature-settings.ts";
4
4
  import {
5
5
  DEFAULT_FOREGROUND_WINDOW_SECONDS,
6
6
  defaultCodemodeSettings,
@@ -54,6 +54,7 @@ export function createEvalTool(options: CreateEvalToolOptions) {
54
54
  hardLimitSeconds: options.hardLimitSeconds ?? defaultEvalDeadlineSeconds.hardLimitSeconds,
55
55
  };
56
56
  const sandbox = resolveSandbox(options.settings ?? defaultCodemodeSettings).enabled;
57
+ const jsCells = resolveJsCells(options.settings ?? defaultCodemodeSettings);
57
58
  const parameters = createEvalInputSchema(options.enabledLanguages, deadlines, { sandbox });
58
59
  const prompt = buildEvalPrompt(options.enabledLanguages, {
59
60
  spawns: options.spawns ?? false,
@@ -68,6 +69,7 @@ export function createEvalTool(options: CreateEvalToolOptions) {
68
69
  ...(options.bunSkillPath === undefined ? {} : { bunSkillPath: options.bunSkillPath }),
69
70
  ...(options.promptKernelPreludes === undefined ? {} : { kernelPreludes: options.promptKernelPreludes }),
70
71
  ...(options.evalOnlyTools === undefined ? {} : { evalOnlyTools: options.evalOnlyTools }),
72
+ ...(jsCells.typescript || jsCells.scope ? { jsCells } : {}),
71
73
  });
72
74
  const languages = enabledLanguageList(options.enabledLanguages);
73
75
  registerEvalArgumentValidator(parameters, languages);
@@ -1,9 +1,17 @@
1
1
  import { parse } from "@babel/parser";
2
2
 
3
- /** Only consulted after the kernel fails to compile. Locate the error in submitted, not rewritten, code. */
4
- export function jsCellParseMessage(code: string, message: string): string {
3
+ /**
4
+ * Only consulted after the kernel fails to compile. Locate the error in submitted, not rewritten, code. A TypeScript
5
+ * cell keeps every token's position when its types are erased, so a TypeScript parse locates its real error.
6
+ */
7
+ export function jsCellParseMessage(code: string, message: string, typescript = false): string {
5
8
  try {
6
- parse(code, { sourceType: "unambiguous", allowReturnOutsideFunction: true, allowAwaitOutsideFunction: true });
9
+ parse(code, {
10
+ sourceType: "unambiguous",
11
+ allowReturnOutsideFunction: true,
12
+ allowAwaitOutsideFunction: true,
13
+ ...(typescript ? { plugins: ["typescript" as const] } : {}),
14
+ });
7
15
  } catch (error) {
8
16
  if (!(error instanceof SyntaxError) || !("loc" in error)) return message;
9
17
  const loc = error.loc;
@@ -22,6 +22,8 @@ export type ManagedCell = {
22
22
  interruptOutcome: PromiseWithResolvers<void> | undefined;
23
23
  liveResult: LiveResultProvider | undefined;
24
24
  terminalResult: AgentToolResult<EvalToolDetails> | undefined;
25
+ /** Holds the completion notification until the result the cell ended with has its written files. */
26
+ finalResult: Promise<void> | undefined;
25
27
  notificationQueued: boolean;
26
28
  readonly deadlines: CellDeadlines;
27
29
  readonly hardLimitSeconds: number;
@@ -69,6 +71,7 @@ export function createManagedCell(init: ManagedCellInit): ManagedCell {
69
71
  interruptOutcome: undefined,
70
72
  liveResult: undefined,
71
73
  terminalResult: undefined,
74
+ finalResult: undefined,
72
75
  notificationQueued: false,
73
76
  deadlines,
74
77
  hardLimitSeconds,
@@ -7,13 +7,15 @@ import {
7
7
  kernelToolsStorage,
8
8
  } from "@code-yeongyu/senpi";
9
9
  import type { KernelToHostMessage } from "../bridge/protocol.ts";
10
- import { resolveSandbox } from "../config/feature-settings.ts";
10
+ import { resolveJsCells, resolveSandbox } from "../config/feature-settings.ts";
11
11
  import { DEFAULT_FOREGROUND_WINDOW_SECONDS, defaultCodemodeSettings } from "../config/settings.ts";
12
12
  import type { JsEnvironments } from "../environments/js-environments.ts";
13
13
  import type { PackagesInstallEnvironments } from "../environments/packages-install.ts";
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 { withWrittenFiles } from "../written-files/report.ts";
18
+ import { settleWrittenFiles } from "../written-files/written-files.ts";
17
19
  import { bindBridgeCell } from "./bridge-cell-binding.ts";
18
20
  import { abortError, CellExecution, defaultTimeoutFactory } from "./cell-execution.ts";
19
21
  import { CellHandler, type CellState } from "./cell-handler.ts";
@@ -211,6 +213,8 @@ async function executeCell(
211
213
  void pending.catch((error: unknown) => execution.cancel(error));
212
214
  };
213
215
  let releaseCellKernelTools: (() => void) | undefined;
216
+ // Opened first so the scan of the workspace's state before the cell overlaps kernel acquisition (senpi#7232).
217
+ const written = options.writtenFiles?.open(invocation.ctx);
214
218
  try {
215
219
  const kernel = await execution.wait(options.kernelManager.getKernel(invocation.input.language, onMessage));
216
220
  // Computed before the handler so its construction-time snapshot captures this cell's capability.
@@ -297,6 +301,7 @@ async function executeCell(
297
301
  const envRoot = environments === undefined ? undefined : () => environments.activeRoot ?? "";
298
302
  const jsEnvironments = invocation.input.language === "js" ? options.jsEnvironments : undefined;
299
303
  const packageRoot = jsEnvironments === undefined ? undefined : () => jsEnvironments.packageRoot;
304
+ if (written !== undefined) await execution.wait(written.ready);
300
305
  const result = await execution.wait(
301
306
  kernel.run({
302
307
  cellId: invocation.cellId,
@@ -320,16 +325,32 @@ async function executeCell(
320
325
  );
321
326
  if (result.ok && state.pendingBridgeCalls.length > 0)
322
327
  await execution.wait(Promise.all(state.pendingBridgeCalls));
323
- if (
328
+ const finished = await handler.finalize(
324
329
  !result.ok &&
325
- result.error.code === "js_cell_parse_error" &&
326
- invocation.input.language === "js" &&
327
- magic.kind === "ordinary"
328
- ) {
329
- const message = jsCellParseMessage(invocation.input.code, result.error.message);
330
- return await handler.finalize({ ...result, error: { ...result.error, message } });
331
- }
332
- return await handler.finalize(result);
330
+ result.error.code === "js_cell_parse_error" &&
331
+ invocation.input.language === "js" &&
332
+ magic.kind === "ordinary"
333
+ ? {
334
+ ...result,
335
+ error: {
336
+ ...result.error,
337
+ message: jsCellParseMessage(
338
+ invocation.input.code,
339
+ result.error.message,
340
+ resolveJsCells(options.settings ?? {}).typescript,
341
+ ),
342
+ },
343
+ }
344
+ : result,
345
+ );
346
+ // The cell's code ended, so its state is final now: the written files settle after it as host work. A stop, list or
347
+ // wake count never waits on the write hooks, and a stop cannot cancel hooks for code that already ended; the
348
+ // settled result (with its file list) still becomes the cell's result and notification (senpi#7232).
349
+ const settled = execution
350
+ .wait(settleWrittenFiles(written, state.signal, [execution, cell.deadlines]))
351
+ .then((writtenFiles) => withWrittenFiles(finished, writtenFiles));
352
+ cellManager.complete(cell, finished, settled);
353
+ return await settled;
333
354
  };
334
355
  return kernelTools ? await kernelToolsStorage.run(kernelTools, runBound) : await runBound();
335
356
  } catch (error) {
@@ -350,10 +371,14 @@ async function executeCell(
350
371
  } finally {
351
372
  // First, so nothing below can skip it: from here on a host call carrying this run's secret gets no kernel tools.
352
373
  releaseCellKernelTools?.();
374
+ written?.close();
353
375
  state.active = false;
354
376
  bridgeAbortController.abort();
355
377
  execution.finish();
356
- if (handler) await handler.flushOutput();
378
+ if (handler) {
379
+ await handler.stopScopedWatches();
380
+ await handler.flushOutput();
381
+ }
357
382
  // The cell settled: stop the kernel dispatcher from holding this cell's listener (#2260).
358
383
  options.kernelManager.releaseKernelListener?.(invocation.input.language, onMessage);
359
384
  }