@code-yeongyu/senpi-codemode 2026.11.26 → 2026.11.28

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
package/CHANGELOG.md CHANGED
@@ -1,5 +1,36 @@
1
1
  # Changelog
2
2
 
3
+ ## [2026.11.28] - 2026-11-28
4
+
5
+ ### Breaking Changes
6
+
7
+ ### Added
8
+
9
+ ### Changed
10
+
11
+ ### Fixed
12
+
13
+ ### Removed
14
+
15
+ ## [2026.11.27] - 2026-11-27
16
+
17
+ ### Breaking Changes
18
+
19
+ ### Added
20
+
21
+ - Source files an eval cell writes without a `write` or `edit` call go through the write hooks when the cell settles, and the cell result lists them with what the hooks appended, such as diagnostics ([#7276](https://github.com/code-yeongyu/senpi/pull/7276))
22
+ - `jsCells.typescript` (off by default): a JS eval cell written in TypeScript runs with its types erased in place, so bindings persist and errors keep the submitted line and column; constructs that generate runtime code are refused with their position ([#7489](https://github.com/code-yeongyu/senpi/pull/7489)).
23
+ - `jsCells.scope` (off by default): `await using s = scope()` with `s.serve`, `s.spawn`, `s.tempDir` and `s.monitor` closes what a cell opened when the block exits, and a stopped or timed-out cell's scoped watches are stopped by the host ([#7489](https://github.com/code-yeongyu/senpi/pull/7489)).
24
+ - `statusTicker` setting (default `true`): `false` stops the once-per-second refresh of a detached cell's elapsed label in the footer status, which still shows on detach, updates when the set of detached cells changes, and clears when the last one settles ([#7536](https://github.com/code-yeongyu/senpi/pull/7536))
25
+
26
+ ### Changed
27
+
28
+ ### Fixed
29
+
30
+ - A JS eval cell with a block holding `using` / `await using` followed by a statement on the same line, or ending in a bare `using` declaration, now runs and disposes its resources instead of failing with `Unexpected identifier 'using'` ([#7489](https://github.com/code-yeongyu/senpi/pull/7489)).
31
+
32
+ ### Removed
33
+
3
34
  ## [2026.11.26] - 2026-11-26
4
35
 
5
36
  ### Breaking Changes
package/README.md CHANGED
@@ -30,6 +30,9 @@ task-tool names are known.
30
30
  pending-call counts, and bounded per-tool aggregates.
31
31
  - Bounded streaming output with head/tail previews, column clamping, and
32
32
  session-adjacent spill files for large streams.
33
+ - Source files a cell writes on its own (the `write()` helper, `fs`, a child
34
+ process, any kernel) go through the hooks a `write` call triggers when the
35
+ cell settles, and the result lists them; see "Files a cell writes".
33
36
  - TUI and HTML-export rendering for syntax-highlighted cells, status rows,
34
37
  task progress, structured display values, truncation warnings, and image
35
38
  fallbacks. A JavaScript cell sent as dense one-line code is previewed broken
@@ -309,6 +312,7 @@ Configuration is loaded in this order:
309
312
  "maxColumns": 768
310
313
  },
311
314
  "statusEvents": true,
315
+ "statusTicker": true,
312
316
  "memory": {
313
317
  "gcWatermarkMb": 256,
314
318
  "noticeMb": 1024,
@@ -333,6 +337,7 @@ Configuration is loaded in this order:
333
337
  | `outputSink.headBytes` | `20480` | Bytes retained from the beginning of a middle-truncated preview; `0` disables it. |
334
338
  | `outputSink.maxColumns` | `768` | Maximum columns per printed output line; `0` disables column clamping. A cell's return value is never column-clamped (the byte and line budgets still apply). |
335
339
  | `statusEvents` | `true` | Enables kernel status-event forwarding and rendering. Each cell retains at most 100 status rows; after overflow, one omitted-count row precedes the latest 99 events. |
340
+ | `statusTicker` | `true` | Refreshes a detached cell's footer status once per second so its elapsed label advances. `false` keeps the footer status (shown when a cell detaches, updated when the set of detached cells changes, cleared when the last one settles) but stops the per-second refresh, so no status update depends on how long a cell runs. Independent of `statusEvents`. |
336
341
  | `memory.gcWatermarkMb` | `256` | JavaScript kernel: a finished cell whose heap reached this size and grew runs a full collection before its result; whenever at least this much stays live, an idle full collection runs about a second after the cell, so dropped globals return their memory without a reset. Python kernel: a finished cell whose process footprint reached this size and grew runs `gc.collect()` (plus glibc `malloc_trim(0)` on Linux) before its result, and while at least this much stays live the next cells collect too (at most 1/20 of the time), so `del rows` returns its memory. `0` disables. Env override: `SENPI_CODEMODE_MEMORY_GC_WATERMARK_MB`. |
337
342
  | `memory.noticeMb` | `1024` | When live memory (JS heap or Python footprint after a collection; Ruby and Julia interpreter footprint read by the host after each cell) reaches this size (first time, or 25% more than at the last notice), the result gets one bracketed notice naming the largest globals and how to drop them (`rows = undefined`, `del rows`, `rows = nil`, `rows = nothing`), plus `details.memory`. `0` disables. Env override: `SENPI_CODEMODE_MEMORY_NOTICE_MB`. |
338
343
  | `memory.ceilingMb` | a quarter of physical memory, 2048-8192 | Every kernel (JS heap and Python footprint after a collection; Ruby and Julia interpreter footprint read by the host after each result, without a globals list): when live memory reaches this size, the result says so and the kernel restarts once no cell is running or queued on it; the next result says it was restarted (`details.memory.recycled`). `0` disables. Env override: `SENPI_CODEMODE_MEMORY_CEILING_MB`. Non-zero memory thresholds must satisfy watermark <= notice <= ceiling, otherwise all three use their defaults. |
@@ -349,6 +354,8 @@ Configuration is loaded in this order:
349
354
  | `sandbox.memoryMb` | `64` | Memory cap (MiB) for a sandbox cell. Env override: `SENPI_CODEMODE_SANDBOX_MEMORY_MB` (a positive integer wins). |
350
355
  | `sandbox.timeoutSeconds` | `300` | Time limit for a sandbox cell. |
351
356
  | `prompt.advertiseHelpers` | `false` | When `true`, one pointer line to `tool_schema('eval:helpers')` is appended to the eval description. |
357
+ | `jsCells.typescript` | `false` | When `true`, a JS cell the engine rejects as JavaScript but that parses as TypeScript runs with its types erased in place (never type-checked; every token keeps its line and column, so errors and parse diagnostics point at the submitted text). Valid JavaScript is never reinterpreted. `enum`, `namespace`, constructor parameter properties, `import =` and `export =` are refused with their position. The eval description says so. |
358
+ | `jsCells.scope` | `false` | When `true`, JS cells get the `scope()` helper below and a Bun kernel's eval description documents it with `using` / `await using`. |
352
359
  | `kernelTools.enabled` | `true` | Allows cells to define kernel tools. `false` makes JavaScript `tool(fn)` and Python `@tool` refuse with `tools_unavailable`, naming this setting. |
353
360
 
354
361
  Every key in the table takes the effect its row describes.
@@ -392,6 +399,7 @@ options object and asynchronous helpers are `await`-able.
392
399
  | `workpool(agent, name, mode?, tools?)` | Creates a thin adapter over the normal host `workpool` tool; exposes `pool_id`, `push(items)`, `close()`, `inspect()`, and `cancel()`. JS awaits creation and operations. `tools` is a list of kernel-tool names this cell defined; the pool's workers may call exactly those, the host refuses any name the caller doesn't hold, and a value that isn't a list of names raises `invalid_tools`. Ruby and Julia define no kernel tools, so they have nothing to grant. |
393
400
  | `output(ids, format?, offset?, limit?)` | Delegates transcript retrieval to the configured active `taskTools.output` tool. |
394
401
  | `parallel(thunks)` | Runs thunks through the configured bounded pool while preserving input order. |
402
+ | `scope()` | JS, with `jsCells.scope`: an `AsyncDisposableStack` for `await using s = scope()`. `s.serve(opts)`, `s.spawn(cmd, opts)` (Bun), `await s.tempDir(prefix?)` and `await s.monitor(args)` start a resource and register its teardown; everything closes in reverse order when the block exits, on throw too, and disposing twice is a no-op. `s.move()` hands the open resources to a new stack. A stopped or timed-out cell still loses them: cell ownership ends its servers and children, the release hook removes its temp dirs, and the host stops its scoped watches. `persistent: true` watches are refused; start those with `tool.monitor`. |
395
403
  | `pipeline(items, ...stages)` | Applies stages left to right with a barrier between stages. |
396
404
  | `log(message)` / `phase(title)` | Emits progress text and starts a status phase. |
397
405
 
@@ -607,6 +615,85 @@ directory. A truncated result tells the model so in its text: the kept and
607
615
  original sizes, then a plain-path notice such as
608
616
  `[Full output: /absolute/path/eval-….log]`.
609
617
 
618
+ ## Files a cell writes
619
+
620
+ A cell can change workspace files without a `write` or `edit` call: through the
621
+ `write()` helper, `fs`, `Bun.write`, a child process, or a Python, Ruby or Julia
622
+ cell. When a cell settles with a kernel result, the source files that changed in
623
+ the workspace while it ran go through the `tool_result` handlers a `write` call
624
+ triggers, and the result gains one text block: the list of those files, then
625
+ whatever the handlers appended for each (diagnostics, for example).
626
+ `EvalToolDetails.writtenFiles` carries the same list for RPC consumers. A cell
627
+ that changed no source file gets no block. A detached cell delivers the block in
628
+ its completion notification.
629
+
630
+ - **Source file**: a regular file whose real location, with every directory in
631
+ its path resolved, is inside the session cwd and outside `.git`,
632
+ `node_modules` and the session's own artifacts directory (a path below a
633
+ directory that links out of the workspace or into one of those is never
634
+ listed, read or hooked; on a case-insensitive filesystem `NODE_MODULES` or
635
+ `.GIT` counts as the excluded directory when it resolves to the same one, and
636
+ also when either lookup fails for any reason but the path being absent; a
637
+ file is read only if the file opened is the regular file just checked and,
638
+ after the open, the path still names it at the same real location with no
639
+ link as its last entry, so a symlink swapped in as the last entry, even to the
640
+ checked file moved out, is not followed. A file moved out after those checks
641
+ is still read through the already open descriptor), that the workspace
642
+ does not ignore, at most 1 MiB, whose first 8 KiB are UTF-8 text. The definition lives in `src/written-files/source-file.ts`.
643
+ - **Detection** compares the workspace before and after the cell, so it covers
644
+ every way of writing. In a git repository it reads `git status` (files that
645
+ differ from HEAD or are untracked, plus files committed while the cell ran,
646
+ plus the earlier scan's tracked files, so a tracked file written back to its
647
+ HEAD content counts as written; an untracked file the cell makes ignored does
648
+ not, nor does a file taken out of the index with `git rm --cached`: an
649
+ earlier tracked file that leaves `git status` is carried only when
650
+ `git ls-files` still finds it in the index, and not when git cannot say);
651
+ elsewhere it lists the workspace through an empty repository kept in the
652
+ session artifacts, so the workspace's own ignore files still apply. It needs
653
+ `git`; without it the first cell says the check is off.
654
+ - **Cost**: one scan before the first live cell starts and one at each
655
+ settlement. A scan is one `git` process killed at 500 ms that may stat at most
656
+ 5,000 changed or untracked paths, plus one more under the same deadline when
657
+ HEAD moved and one when earlier tracked files left `git status`. Three scans in a row that fail or run over
658
+ that budget turn the check off for the session, and the cell says so.
659
+ - **Hooks**: only `tool_result` handlers run, with `toolName: "write"`,
660
+ `input: { path, content }` (absolute path, the content on disk) and
661
+ `parentToolCallId` set to the eval call. No tool runs, so nothing is written
662
+ again, no permission is asked and no write guard can block it. A handler that
663
+ fails is named in the block; the cell still succeeds.
664
+ - **Once**: a file a `write` or `edit` call took through the hooks, from the cell
665
+ or from the model while a detached cell was running, is not sent again unless
666
+ it was rewritten afterwards. A file a cell's settlement listed belongs to that
667
+ cell until its write hooks for it return, so a hook that rewrites it (a
668
+ formatter) is never charged to another cell that settles meanwhile; that other
669
+ cell leaves the file out, and a change it made to that file while the hook ran
670
+ is taken as the hook's. The file stays the cell's until the whole handler chain
671
+ for it returns: the host bounds each handler and moves on to the next when one
672
+ times out, so a write a handler makes after the chain returned is reported by
673
+ whichever cell settles next. A `write` or `edit` call the model issues holds its
674
+ file from before it writes until it ends, so a cell settling meanwhile neither
675
+ lists nor hooks it. Neither side waits for the other: a call that takes a file
676
+ a settling cell has already looked at, up to the moment the cell's hooks for it
677
+ start, takes it from that cell, which then neither lists, counts nor hooks it
678
+ and leaves the change to the call. A call that starts while the cell's hooks
679
+ for the file run gets its own hooks; the cell's ran for what the cell wrote.
680
+ A settlement that claims a file and then cannot run its
681
+ hooks (the cell was cancelled or closed) leaves the change for the next cell.
682
+ - **Limits**: the first 20 files are listed and hooked and the rest are counted;
683
+ hook output is capped at 2,000 code points per file and 12,000 per cell. The
684
+ count can exceed the 20 listed files, and then it is not exactly what the
685
+ cell wrote: a file a model call takes from the cell leaves the list and the
686
+ count only when it was listed. A file past the limit is never claimed, so it
687
+ stays counted even when a model `write` or `edit` took it while the cell
688
+ settled; the cell never hooks it, and the call's own hooks are its only ones.
689
+ The part of the count beyond the list is therefore an upper bound, and no file
690
+ in it is reported again.
691
+
692
+ Not covered: a cell that is cancelled, times out or is killed (it has no kernel
693
+ result); deleted files, which are never reported; files inside submodules and nested repositories. Cells
694
+ that run at the same time share one comparison, so a change is reported once, by
695
+ the first of them to settle.
696
+
610
697
  ## Deliberate differences from oh-my-pi
611
698
 
612
699
  - There is no `budget` helper.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@code-yeongyu/senpi-codemode",
3
- "version": "2026.11.26",
3
+ "version": "2026.11.28",
4
4
  "description": "Source-only senpi extension package for codemode evaluation tools",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -33,16 +33,16 @@
33
33
  },
34
34
  "dependencies": {
35
35
  "@babel/parser": "8.0.4",
36
- "@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.11.26",
37
- "@earendil-works/pi-realm-registry": "npm:@code-yeongyu/senpi-realm-registry@2026.11.26",
36
+ "@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.11.28",
37
+ "@earendil-works/pi-realm-registry": "npm:@code-yeongyu/senpi-realm-registry@2026.11.28",
38
38
  "quickjs-wasi": "3.6.2",
39
39
  "typebox": "1.3.34"
40
40
  },
41
41
  "peerDependencies": {
42
- "@code-yeongyu/senpi": "2026.11.26"
42
+ "@code-yeongyu/senpi": "2026.11.28"
43
43
  },
44
44
  "devDependencies": {
45
- "@code-yeongyu/senpi": "2026.11.26"
45
+ "@code-yeongyu/senpi": "2026.11.28"
46
46
  },
47
47
  "keywords": [
48
48
  "senpi",
@@ -23,6 +23,8 @@ export const TIMEOUT_PAUSE_OP = "timeout-pause" as const;
23
23
  export const TIMEOUT_RESUME_OP = "timeout-resume" as const;
24
24
  /** Status op the JS worker emits the moment it receives `interrupt`; proves its event loop is not blocked. */
25
25
  export const INTERRUPT_ACK_OP = "interrupt-ack" as const;
26
+ /** A JS cell's `scope().monitor()` holds (`held: true`) or released (`held: false`) the watch `bashId`. */
27
+ export const SCOPE_MONITOR_OP = "scope-monitor" as const;
26
28
  /** Status op the JS worker emits when a cell child is tracked or exits, so the host can retire it if the worker is lost. */
27
29
  export const CHILD_LIFECYCLE_OP = "child" as const;
28
30
  /** Status op the JS worker emits after an idle full collection between cells, carrying the live heap it measured. */
@@ -44,6 +44,12 @@ export const featureSettingsProperties = {
44
44
  Type.Object({ advertiseHelpers: Type.Optional(Type.Boolean()) }, { additionalProperties: false }),
45
45
  ),
46
46
  kernelTools: Type.Optional(Type.Object({ enabled: Type.Optional(Type.Boolean()) }, { additionalProperties: false })),
47
+ jsCells: Type.Optional(
48
+ Type.Object(
49
+ { typescript: Type.Optional(Type.Boolean()), scope: Type.Optional(Type.Boolean()) },
50
+ { additionalProperties: false },
51
+ ),
52
+ ),
47
53
  };
48
54
 
49
55
  const featureSettingsSchema = Type.Object(featureSettingsProperties);
@@ -99,6 +105,7 @@ export function pickFeatureSettings(input: CodemodeFeatureSettings): CodemodeFea
99
105
  ...(input.sandbox === undefined ? {} : { sandbox: input.sandbox }),
100
106
  ...(input.prompt === undefined ? {} : { prompt: input.prompt }),
101
107
  ...(input.kernelTools === undefined ? {} : { kernelTools: input.kernelTools }),
108
+ ...(input.jsCells === undefined ? {} : { jsCells: input.jsCells }),
102
109
  };
103
110
  }
104
111
 
@@ -140,3 +147,15 @@ export function resolveAdvertiseHelpers(settings: CodemodeFeatureSettings): bool
140
147
  export function resolveKernelToolsEnabled(settings: CodemodeFeatureSettings): boolean {
141
148
  return settings.kernelTools?.enabled ?? true;
142
149
  }
150
+
151
+ export interface ResolvedJsCells {
152
+ /** Run JS cells written in TypeScript with their types erased; the prompt says so. */
153
+ readonly typescript: boolean;
154
+ /** Install the `scope()` helper for `await using` cleanup; the prompt documents it. */
155
+ readonly scope: boolean;
156
+ }
157
+
158
+ /** Both off by default, so the kernel, its globals and the default eval prompt stay as they were. */
159
+ export function resolveJsCells(settings: CodemodeFeatureSettings): ResolvedJsCells {
160
+ return { typescript: settings.jsCells?.typescript ?? false, scope: settings.jsCells?.scope ?? false };
161
+ }
@@ -47,7 +47,10 @@ export const codemodeSettingsSchema = Type.Object(
47
47
  { additionalProperties: false },
48
48
  ),
49
49
  ),
50
+ // A status source that emits on a timer is a `status*` boolean here: the fused-equivalence cases turn every one
51
+ // off (.agents/skills/senpi-qa/scripts/lib/equivalence-codemode-settings.test.mjs enforces it).
50
52
  statusEvents: Type.Optional(Type.Boolean()),
53
+ statusTicker: Type.Optional(Type.Boolean()),
51
54
  memory: Type.Optional(memorySettingsSchema),
52
55
  ...featureSettingsProperties,
53
56
  },
@@ -96,6 +99,8 @@ export interface CodemodeSettings extends CodemodeFeatureSettings {
96
99
  readonly taskTools?: CodemodeTaskTools;
97
100
  readonly outputSink?: CodemodeOutputSink;
98
101
  readonly statusEvents?: boolean;
102
+ /** The once-per-second refresh of a detached cell's elapsed label in the footer status (default on). */
103
+ readonly statusTicker?: boolean;
99
104
  readonly memory?: CodemodeMemorySettings;
100
105
  }
101
106
 
@@ -104,6 +109,7 @@ export type ResolvedCodemodeSettings = CodemodeSettings & {
104
109
  readonly taskTools: CodemodeTaskTools;
105
110
  readonly outputSink: CodemodeOutputSink;
106
111
  readonly statusEvents: boolean;
112
+ readonly statusTicker: boolean;
107
113
  readonly memory: CodemodeMemorySettings;
108
114
  };
109
115
 
@@ -164,6 +170,7 @@ export const defaultCodemodeSettings: ResolvedCodemodeSettings = {
164
170
  maxColumns: 768,
165
171
  },
166
172
  statusEvents: true,
173
+ statusTicker: true,
167
174
  memory: validatedMemorySettings(undefined).settings,
168
175
  };
169
176
 
@@ -237,6 +244,7 @@ function mergeSettings(input: CodemodeSettingsInput): ResolvedCodemodeSettings {
237
244
  maxColumns: input.outputSink?.maxColumns ?? defaultCodemodeSettings.outputSink.maxColumns,
238
245
  },
239
246
  statusEvents: input.statusEvents ?? defaultCodemodeSettings.statusEvents,
247
+ statusTicker: input.statusTicker ?? defaultCodemodeSettings.statusTicker,
240
248
  memory: validatedMemorySettings(input.memory).settings,
241
249
  ...pickFeatureSettings(input),
242
250
  };
@@ -41,12 +41,15 @@ export class EvalStatusTicker {
41
41
  /**
42
42
  * Point the ticker at the current detached-cell set, render once immediately,
43
43
  * and start the interval while cells are live (or stop it when none remain).
44
+ * With `live` false (the `statusTicker` setting off) only the cell-set changes
45
+ * render: the elapsed label never advances between them, so no event depends on
46
+ * how many wall-clock seconds a cell ran.
44
47
  */
45
- sync(entries: readonly EvalDetachedCellStatusEntry[]): void {
48
+ sync(entries: readonly EvalDetachedCellStatusEntry[], live = true): void {
46
49
  this.entries = entries;
47
50
  this.hasRendered = false;
48
51
  if (!this.tick()) return;
49
- if (entries.length === 0) {
52
+ if (entries.length === 0 || !live) {
50
53
  this.stopInterval();
51
54
  return;
52
55
  }
@@ -28,7 +28,10 @@ import {
28
28
  import { processRuntimeInfo } from "../kernels/js/process-worker.ts";
29
29
  import { sessionEnvironmentFrom } from "../kernels/session-env.ts";
30
30
  import { resolveSessionArtifactsDir } from "../output/streaming-output.ts";
31
+ import { toolResultIsError } from "../tool/tool-result-marshal.ts";
31
32
  import type { EnabledEvalLanguages, EvalLanguage, EvalRuntimes } from "../tool/types.ts";
33
+ import { createGitRunner, createNodeFsAccess } from "../written-files/scan-boundaries.ts";
34
+ import { WrittenFiles } from "../written-files/written-files.ts";
32
35
  import { reachableToolNames } from "./reachable-tools.ts";
33
36
  import { jsRuntimeInfo, runtimesFromAvailability } from "./runtime-info.ts";
34
37
  import {
@@ -41,6 +44,8 @@ export interface CodemodeRuntimeAPI {
41
44
  readonly executeTool: AgentExecuteTool;
42
45
  getActiveTools(): string[];
43
46
  getAllTools(): readonly EvalSchemaToolInfo[];
47
+ /** True on a hand whose loop runs elsewhere; a host without it is never one. */
48
+ isLoopRemote?(): boolean;
44
49
  }
45
50
 
46
51
  export interface RuntimeFactoryOptions {
@@ -62,6 +67,7 @@ export type SessionRuntime = {
62
67
  readonly spawns: boolean;
63
68
  readonly pythonEnvironments?: PythonEnvironments;
64
69
  readonly jsEnvironments: JsEnvironments;
70
+ readonly writtenFiles: WrittenFiles;
65
71
  };
66
72
 
67
73
  export async function createRuntime(
@@ -94,7 +100,18 @@ export async function createRuntime(
94
100
  const jsProcessIsolation = resolveJsIsolation(settings) === "process";
95
101
  const artifacts = resolveSessionArtifactsDir(ctx.sessionManager.getSessionFile());
96
102
  const activeTools = reachableToolNames(pi);
97
- const executeTool = createExecuteTool(pi, activeTools);
103
+ // Kernels and their children never see the RPC host's supervisor hand-off (senpi#5635).
104
+ const inheritedEnv = () => childEnvironmentOf(process.env);
105
+ const writtenFiles = new WrittenFiles({
106
+ cwd: ctx.cwd,
107
+ artifactsDir: artifacts.dir,
108
+ git: createGitRunner(inheritedEnv),
109
+ fs: createNodeFsAccess(),
110
+ hooksRunHere: () => pi.isLoopRemote?.() !== true,
111
+ });
112
+ const executeTool = createExecuteTool(pi, activeTools, (toolName, params) =>
113
+ writtenFiles.noteToolCall(toolName, params),
114
+ );
98
115
  const create = options.createSessionManager ?? createCodemodeSessionManager;
99
116
  const sessionId = sessionIdFrom(event);
100
117
  const killGuard = readKillGuardSetting(ctx.cwd, ctx.agentDir) === "on";
@@ -103,8 +120,6 @@ export async function createRuntime(
103
120
  // bash's BASH_ENV wrapper, as the bash tool does.
104
121
  const killGuardEnv = killGuard ? activeKillGuardEnvironment({ ...process.env, ...pathEntry }) : {};
105
122
  const sessionEnv = { ...sessionEnvironmentFrom(ctx), ...pathEntry, ...killGuardEnv, ...withheldCredentialEntries() };
106
- // Kernels and their children never see the RPC host's supervisor hand-off (senpi#5635).
107
- const inheritedEnv = () => childEnvironmentOf(process.env);
108
123
  const configuredPoolWidth = settings.parallelPoolWidth;
109
124
  const parallelPoolWidth = Number.isFinite(configuredPoolWidth) ? Math.max(1, Math.trunc(configuredPoolWidth)) : 1;
110
125
  const pythonEnvironments =
@@ -155,6 +170,7 @@ export async function createRuntime(
155
170
  env: { ...inheritedEnv(), ...sessionEnv },
156
171
  settings,
157
172
  }),
173
+ writtenFiles,
158
174
  ...(pythonEnvironments === undefined ? {} : { pythonEnvironments }),
159
175
  };
160
176
  }
@@ -176,13 +192,23 @@ const TOP_LEVEL_ONLY_TOOL_REFUSALS: ReadonlyMap<string, string> = new Map([
176
192
  ],
177
193
  ]);
178
194
 
179
- export function createExecuteTool(pi: CodemodeRuntimeAPI, activeTools?: ReadonlySet<string>): AgentExecuteTool {
195
+ export function createExecuteTool(
196
+ pi: CodemodeRuntimeAPI,
197
+ activeTools?: ReadonlySet<string>,
198
+ /** Told of each call that completed through the session's hooks without an error. */
199
+ onCompleted?: (toolName: string, params: unknown) => Promise<void>,
200
+ ): AgentExecuteTool {
180
201
  // A cell names tools directly and cannot run tool_search first, so eval opts in to
181
202
  // lazy activation. Eligibility still belongs to the extension that registered the tool.
182
203
  const executeTool: AgentExecuteTool = (toolName, params, executeOptions) => {
183
204
  const refusal = TOP_LEVEL_ONLY_TOOL_REFUSALS.get(toolName);
184
205
  if (refusal !== undefined) return Promise.reject(new Error(refusal));
185
- return pi.executeTool(toolName, params, { ...executeOptions, activateInactiveTool: true });
206
+ const call = pi.executeTool(toolName, params, { ...executeOptions, activateInactiveTool: true });
207
+ if (onCompleted === undefined) return call;
208
+ return call.then(async (result) => {
209
+ if (!toolResultIsError(result)) await onCompleted(toolName, params);
210
+ return result;
211
+ });
186
212
  };
187
213
  return Object.assign(executeTool, {
188
214
  isToolAvailable: (name: string): boolean => (activeTools ?? reachableToolNames(pi)).has(name),
@@ -10,7 +10,7 @@ import {
10
10
  import { type BridgeServerHandle, startBridgeServer } from "../bridge/http-server.ts";
11
11
  import type { KernelToHostMessage } from "../bridge/protocol.ts";
12
12
  import type { CompletionRequest, CompletionResult } from "../completion/handler.ts";
13
- import { resolveJsIsolation, resolveKernelToolsEnabled } from "../config/feature-settings.ts";
13
+ import { resolveJsCells, resolveJsIsolation, resolveKernelToolsEnabled } from "../config/feature-settings.ts";
14
14
  import { resolveKernelMemoryThresholds } from "../config/memory-settings.ts";
15
15
  import { collectOrphanedChildren } from "../host-sdk.ts";
16
16
  import { JavaScriptKernel } from "../kernels/js/context-manager.ts";
@@ -300,6 +300,7 @@ class DefaultCodemodeSessionManager implements CodemodeSessionManager {
300
300
  if (language === "js") {
301
301
  const memoryThresholds = resolveKernelMemoryThresholds(this.#options.settings.memory);
302
302
  const processIsolation = resolveJsIsolation(this.#options.settings) === "process";
303
+ const jsCells = resolveJsCells(this.#options.settings);
303
304
  const kernel = new JavaScriptKernel({
304
305
  sessionId: this.#options.sessionId,
305
306
  cwd: this.#options.cwd,
@@ -315,6 +316,8 @@ class DefaultCodemodeSessionManager implements CodemodeSessionManager {
315
316
  ? { processMemory: { thresholds: memoryThresholds, readFootprint: readProcessFootprint } }
316
317
  : {}),
317
318
  ...(resolveKernelToolsEnabled(this.#options.settings) ? {} : { kernelToolsEnabled: false }),
319
+ ...(jsCells.typescript ? { typescriptCells: true } : {}),
320
+ ...(jsCells.scope ? { scopeHelper: true } : {}),
318
321
  ...(this.#options.sessionEnv ? { sessionEnv: this.#options.sessionEnv } : {}),
319
322
  ...(this.#options.inheritedEnv ? { inheritedEnv: this.#options.inheritedEnv } : {}),
320
323
  ...(this.#options.killGuard === true
package/src/index.ts CHANGED
@@ -41,6 +41,7 @@ import {
41
41
  import { createEvalTool } from "./tool/eval-tool.ts";
42
42
  import { renderEvalCall, renderEvalResult } from "./tool/render.ts";
43
43
  import type { NestedToolRenderers } from "./tool/tool-widgets.ts";
44
+ import { observeModelWrites } from "./written-files/model-writes.ts";
44
45
 
45
46
  // session_before_switch / session_before_fork are veto points another extension can cancel, so they never
46
47
  // tear the runtime down; a switch or fork that goes ahead emits session_shutdown before the old session ends.
@@ -48,7 +49,7 @@ const SESSION_LIFECYCLE_EVENTS = ["session_start", "session_shutdown"] as const;
48
49
 
49
50
  type SessionLifecycleEvent = (typeof SESSION_LIFECYCLE_EVENTS)[number];
50
51
 
51
- type CodemodeEvent = SessionLifecycleEvent | "model_select" | "turn_start";
52
+ type CodemodeEvent = SessionLifecycleEvent | "model_select" | "turn_start" | "tool_call_ready" | "tool_execution_end";
52
53
 
53
54
  export interface CodemodeExtensionAPI {
54
55
  registerTool(tool: ReturnType<typeof createEvalTool>): void;
@@ -147,9 +148,11 @@ export default function senpiCodemode(pi: CodemodeExtensionAPI, options: SenpiCo
147
148
  );
148
149
  },
149
150
  });
150
- const showDetachedCells = (entries: readonly EvalDetachedCellStatusEntry[]): void => {
151
- statusTicker.sync(entries);
152
- };
151
+ const showDetachedCells =
152
+ (live: boolean) =>
153
+ (entries: readonly EvalDetachedCellStatusEntry[]): void => {
154
+ statusTicker.sync(entries, live);
155
+ };
153
156
  const emitWakeSourceState = (state: WakeSourceState): void => {
154
157
  // Same dual publication as the settle payload below: the in-process bus
155
158
  // feeds the TUI footer, the rpc channel feeds out-of-process consumers.
@@ -195,6 +198,7 @@ export default function senpiCodemode(pi: CodemodeExtensionAPI, options: SenpiCo
195
198
  jsEnvironments: runtime.jsEnvironments,
196
199
  cellManager,
197
200
  handles,
201
+ writtenFiles: runtime.writtenFiles,
198
202
  executionTracker: manager,
199
203
  onCellSettled,
200
204
  renderers,
@@ -246,7 +250,7 @@ export default function senpiCodemode(pi: CodemodeExtensionAPI, options: SenpiCo
246
250
  retainedResultsBytes: resolveRetainedResultsBytes(defaultCodemodeSettings),
247
251
  hardLimitSeconds: resolveHardLimitSeconds(defaultCodemodeSettings),
248
252
  runBudgetSeconds: resolveRunBudgetSeconds(defaultCodemodeSettings),
249
- onStatusChange: showDetachedCells,
253
+ onStatusChange: showDetachedCells(defaultCodemodeSettings.statusTicker),
250
254
  onWakeSourceState: emitWakeSourceState,
251
255
  ...(options.now === undefined ? {} : { now: options.now }),
252
256
  }),
@@ -262,6 +266,10 @@ export default function senpiCodemode(pi: CodemodeExtensionAPI, options: SenpiCo
262
266
  );
263
267
  registerRemovedToolHints(pi);
264
268
  registerBunSkillContribution(pi);
269
+ observeModelWrites(
270
+ (event, handler) => pi.on(event, handler),
271
+ () => activeRuntime?.writtenFiles,
272
+ );
265
273
 
266
274
  const startSession = async (event: unknown, ctx: ExtensionContext): Promise<void> => {
267
275
  const previousCells = activeCells;
@@ -288,7 +296,7 @@ export default function senpiCodemode(pi: CodemodeExtensionAPI, options: SenpiCo
288
296
  retainedImagesBytes: resolveRetainedImagesBytes(runtime.settings),
289
297
  hardLimitSeconds: resolveHardLimitSeconds(runtime.settings),
290
298
  runBudgetSeconds: resolveRunBudgetSeconds(runtime.settings),
291
- onStatusChange: showDetachedCells,
299
+ onStatusChange: showDetachedCells(runtime.settings.statusTicker),
292
300
  onWakeSourceState: emitWakeSourceState,
293
301
  ...(options.now === undefined ? {} : { now: options.now }),
294
302
  });
@@ -0,0 +1,64 @@
1
+ import { parse } from "@babel/parser";
2
+
3
+ export type AstNode = {
4
+ readonly type: string;
5
+ readonly start: number;
6
+ readonly end: number;
7
+ readonly value: Readonly<Record<string, unknown>>;
8
+ };
9
+
10
+ export type ParsedProgram = ReturnType<typeof parse>;
11
+
12
+ function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
13
+ return value !== null && typeof value === "object" && !Array.isArray(value);
14
+ }
15
+
16
+ export function nodeFrom(value: unknown): AstNode | undefined {
17
+ if (!isRecord(value)) return undefined;
18
+ const type = value.type;
19
+ const start = value.start;
20
+ const end = value.end;
21
+ if (typeof type !== "string" || typeof start !== "number" || typeof end !== "number") return undefined;
22
+ return { type, start, end, value };
23
+ }
24
+
25
+ /**
26
+ * Parses a cell as a TypeScript module with the kernel's top-level allowances. `errorRecovery` keeps a best-effort
27
+ * tree for the import rewrite; type erasure needs an exact parse and turns it off.
28
+ */
29
+ export function parseCellProgram(code: string, errorRecovery = true): ParsedProgram | undefined {
30
+ try {
31
+ return parse(code, {
32
+ sourceType: "module",
33
+ allowAwaitOutsideFunction: true,
34
+ allowReturnOutsideFunction: true,
35
+ allowImportExportEverywhere: true,
36
+ allowNewTargetOutsideFunction: true,
37
+ allowSuperOutsideMethod: true,
38
+ allowUndeclaredExports: true,
39
+ errorRecovery,
40
+ plugins: ["typescript"],
41
+ });
42
+ } catch (error) {
43
+ if (error instanceof SyntaxError) return undefined;
44
+ throw error;
45
+ }
46
+ }
47
+
48
+ export function walkNodes(root: unknown, visit: (node: AstNode) => void): void {
49
+ const stack: unknown[] = [root];
50
+ while (stack.length > 0) {
51
+ const current = stack.pop();
52
+ if (Array.isArray(current)) {
53
+ for (let index = current.length - 1; index >= 0; index -= 1) stack.push(current[index]);
54
+ continue;
55
+ }
56
+ if (!isRecord(current)) continue;
57
+ const node = nodeFrom(current);
58
+ if (node) visit(node);
59
+ for (const [key, value] of Object.entries(current)) {
60
+ if (key === "loc" || key === "extra" || key === "range" || key.endsWith("Comments")) continue;
61
+ if (value !== null && typeof value === "object") stack.push(value);
62
+ }
63
+ }
64
+ }