@code-yeongyu/senpi-codemode 2026.10.8 → 2026.10.10-2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +103 -7
  3. package/package.json +6 -5
  4. package/src/bridge/http-server.ts +9 -1
  5. package/src/bridge/protocol.ts +4 -0
  6. package/src/bridges/eval-virtual-schemas.ts +1 -0
  7. package/src/config/executable-settings.json +5 -0
  8. package/src/config/project-trust.ts +51 -0
  9. package/src/config/settings-overrides.ts +2 -0
  10. package/src/environments/js-environments.ts +208 -0
  11. package/src/environments/js-installer.ts +268 -0
  12. package/src/environments/js-revision-files.ts +91 -0
  13. package/src/environments/no-links.ts +132 -0
  14. package/src/environments/project-resolves.ts +54 -0
  15. package/src/environments/py-installer.ts +64 -4
  16. package/src/environments/python-environments.ts +85 -0
  17. package/src/environments/revision-store.ts +38 -7
  18. package/src/extension/bridge-tool-call.ts +2 -0
  19. package/src/extension/cell-kernel-tools.ts +28 -0
  20. package/src/extension/kernel-replacement.ts +20 -0
  21. package/src/extension/runtime-factory.ts +44 -2
  22. package/src/extension/session-manager-proxy.ts +6 -0
  23. package/src/extension/session-manager.ts +18 -3
  24. package/src/index.ts +2 -0
  25. package/src/interpreters/detect.ts +34 -1
  26. package/src/kernels/jl/prelude.jl +6 -1
  27. package/src/kernels/js/cell-dispatch.ts +44 -0
  28. package/src/kernels/js/context-manager.ts +25 -15
  29. package/src/kernels/js/host-entries.ts +62 -0
  30. package/src/kernels/js/kernel-contract.ts +2 -0
  31. package/src/kernels/js/kernel-tools-registry.js +1 -0
  32. package/src/kernels/js/local-module-loader.ts +21 -5
  33. package/src/kernels/js/worker-core.js +3 -0
  34. package/src/kernels/js/worker-package-resolve.js +153 -0
  35. package/src/kernels/js/worker-runtime.js +4 -1
  36. package/src/kernels/js/worker-startup.ts +1 -0
  37. package/src/kernels/js/workpool.js +5 -2
  38. package/src/kernels/py/host-cell.ts +8 -31
  39. package/src/kernels/py/kernel.ts +8 -2
  40. package/src/kernels/py/prelude.py +122 -11
  41. package/src/kernels/py/process.ts +4 -0
  42. package/src/kernels/py/transport.ts +13 -1
  43. package/src/kernels/rb/workpool.rb +7 -1
  44. package/src/kernels/sandbox/sandbox-cell.ts +116 -0
  45. package/src/kernels/sandbox/vendor/pi-codemode/VENDORED.md +1 -0
  46. package/src/kernels/sandbox/vendor/pi-codemode/runtime/prelude-source.ts +14 -1
  47. package/src/kernels/sandbox/vendor/pi-codemode/runtime/worker.ts +4 -1
  48. package/src/kernels/sandbox/vendor/pi-codemode/types.ts +2 -0
  49. package/src/kernels/shared/cell-source-at-start.ts +18 -0
  50. package/src/kernels/shared/host-cell.ts +57 -0
  51. package/src/prompt/eval-prompt.ts +8 -1
  52. package/src/tool/cell-handler.ts +10 -12
  53. package/src/tool/eval-request.ts +23 -1
  54. package/src/tool/eval-tool-options.ts +6 -0
  55. package/src/tool/eval-tool.ts +17 -4
  56. package/src/tool/load-cell.ts +88 -0
  57. package/src/tool/magic-cell-host.ts +123 -0
  58. package/src/tool/magic-cells.ts +75 -0
  59. package/src/tool/run-eval-cell.ts +57 -0
  60. package/src/tool/types.ts +48 -1
package/CHANGELOG.md CHANGED
@@ -12,6 +12,64 @@
12
12
 
13
13
  ### Removed
14
14
 
15
+ ## [2026.10.10-2] - 2026-10-05
16
+
17
+ ### Breaking Changes
18
+
19
+ ### Added
20
+
21
+ - `@code-yeongyu/senpi-codemode/executable-settings.json` lists the settings that name an executable run at session start (today `languages.pyInterpreter`). senpi's project-trust check reads it, so a project codemode file that sets one asks for trust, and a test fails if a new free-form string setting is neither on the list nor marked as not naming an executable ([#2772](https://github.com/code-yeongyu/senpi/pull/2772)).
22
+
23
+ ### Changed
24
+
25
+ ### Fixed
26
+
27
+ - Settings that were accepted but did nothing now take effect ([#2763](https://github.com/code-yeongyu/senpi/issues/2763)): `kernelTools.enabled: false` makes JavaScript `tool(fn)` and Python `@tool` refuse with `tools_unavailable`; `languages.pyInterpreter` makes the Python kernel run exactly that executable (a path that does not answer makes Python unavailable, with a warning naming the setting; one named by a project's own settings file is honored only in a trusted project); `prompt.advertiseHelpers: true` adds one line pointing at `tool_schema('eval:helpers')` to the eval description. Settings-file warnings (an unknown key, a fallback to defaults) now reach the user as a notice, or on stderr without a UI.
28
+
29
+ ### Removed
30
+
31
+ ## [2026.10.10] - 2026-10-05
32
+
33
+ ### Breaking Changes
34
+
35
+ ### Added
36
+
37
+ - Isolated eval cells: with `sandbox.enabled`, `isolate: true` runs a JavaScript cell in a fresh QuickJS VM with no persistence and no ambient host (only `tools.*`, `print`, `display`), streaming output under a credit window. Off by default; the eval schema is unchanged until the setting is on.
38
+ - A JavaScript cell that is only `%bun add <package ...>` or `%npm add <package ...>` installs packages into a per-session managed environment without restarting the kernel; the next cell imports them by bare name, the project's `package.json` and `node_modules` are untouched, lifecycle scripts never run, and a failed or cancelled install leaves the previous packages active ([#2452](https://github.com/code-yeongyu/senpi/issues/2452)).
39
+
40
+ ### Changed
41
+
42
+ ### Fixed
43
+
44
+ - An isolated (`isolate: true`) cell whose QuickJS runtime is missing now fails with `eval_isolate_unavailable` before any of its code runs, instead of a module-resolution error that named a host path ([#2452](https://github.com/code-yeongyu/senpi/issues/2452)).
45
+
46
+ - `%bun add` over a package first installed from a local directory now works when the new archive's top directory is not `package/` (a GitHub-style `<repo>-<sha>.tgz`, or a plain `.tar`): its name is read from the archive's own top-level directory, so the old directory's links are removed before bun installs ([#2452](https://github.com/code-yeongyu/senpi/issues/2452)).
47
+
48
+ - A nested tool call that is denied inside an `eval` cell (a permission denial or another hook's block) now reaches the cell as the plain denial, without the `Expected parameters:` schema hint that made it read like an argument error; argument failures still get the hint ([#2700](https://github.com/code-yeongyu/senpi/issues/2700)). Thanks to @MoerAI ([#2755](https://github.com/code-yeongyu/senpi/pull/2755)).
49
+ - An `eval` run with an invalid `language` value (for example `"python"`, `""` or `null`) now gets its own error listing the enabled languages, instead of the "run requires language" message meant for an omitted one; `peek` and `stop` still need no language ([#1395](https://github.com/code-yeongyu/senpi/issues/1395)). Thanks to @MoerAI.
50
+
51
+ ### Removed
52
+
53
+ ## [2026.10.9] - 2026-10-04
54
+
55
+ ### Breaking Changes
56
+
57
+ ### Added
58
+
59
+ - Python `agent(prompt, tools=[...])` grants the child the cell's `@tool` functions by name, like JavaScript's `agent(prompt, { tools })`; anything other than a list of names is refused with `invalid_tools` ([#2731](https://github.com/code-yeongyu/senpi/issues/2731)).
60
+ - `workpool(agent, name, {mode, tools})` forwards `tools`, a list of kernel-tool names the cell defined, to the host workpool unchanged in all four languages, so pool workers can call them; anything other than a list of names is refused with `invalid_tools` before reaching the host. Which kernels' tools a host accepts is the host's call: JavaScript `tool(fn)` tools work on omo today, while Python `@tool` tools need omo#9529 ([#2452](https://github.com/code-yeongyu/senpi/issues/2452)).
61
+ - A Python or JavaScript cell that is only `%load <path>` runs that local file as the cell: its definitions persist, Python tracebacks name the file and its sibling modules import, and JavaScript resolves the file's relative imports from its directory; remote URLs are refused ([#2452](https://github.com/code-yeongyu/senpi/issues/2452)).
62
+ - A Python cell that is only `%pip install <requirements>` installs packages without restarting the kernel; the next cell imports them. Packages go into the session's own environment (or `<cwd>/.senpi/python-packages` after `%environment project`), never the interpreter's site-packages or the user site, and a failed or cancelled install leaves the previous packages active ([#2452](https://github.com/code-yeongyu/senpi/issues/2452)).
63
+
64
+ ### Changed
65
+
66
+ ### Fixed
67
+
68
+ - A Python cell can now grant its `@tool` functions to a child ([#2731](https://github.com/code-yeongyu/senpi/issues/2731)). Host calls from Python cells (`tool.task(..., tools=[...])`, `agent(..., tools=[...])`, `workpool(..., tools=[...])`) reached the host with no kernel-tools capability, so every such grant was refused as unavailable. Each call now carries its cell, and the host gives it that cell's capability while the cell runs; a call from another, unknown or finished cell gets none.
69
+ - `%pip` parsing follow-ups ([#2689](https://github.com/code-yeongyu/senpi/pull/2689)): a `%pip` or `%environment` line after code now says to put it on its own cell instead of "Unsupported line magic"; a comment line ending in a backslash no longer swallows the `%pip` line after it; inside double quotes a backslash is kept unless it escapes a quote, backslash, `$` or a backtick, as a POSIX shell does.
70
+
71
+ ### Removed
72
+
15
73
  ## [2026.10.8] - 2026-10-04
16
74
 
17
75
  ### Breaking Changes
package/README.md CHANGED
@@ -67,6 +67,12 @@ Windows fresh-cache bootstrap p99 (30 samples). A stalled or failed start names
67
67
  the last stage and retains the interpreter's diagnostic error. The low-level
68
68
  `PythonKernel.start({ startupTimeoutMs })` override applies per stage.
69
69
 
70
+ Every `eval` run must explicitly select an enabled `language` (`js`, `py`, `rb`,
71
+ or `jl`); there is no default kernel, even when only one language is enabled.
72
+ Omitting `action` means `run`, so it also requires `language`. Control requests
73
+ with `action: "peek"` or `action: "stop"` use `cell_id` and do not require a
74
+ language.
75
+
70
76
  ### Session environment
71
77
 
72
78
  Every kernel starts with the active session's `PI_*` environment — `PI_SESSION_ID`,
@@ -100,6 +106,93 @@ getter and may name a file that does not exist yet. It honors session-directory
100
106
  and in-memory sessions; it cannot be derived reliably from `PI_SESSION_FILE`. If the host
101
107
  omits the getter, the variable is unset rather than inherited from the launching process.
102
108
 
109
+ ### Loading a file
110
+
111
+ A Python or JavaScript cell whose only line is `%load <path>` reads that file and
112
+ runs it as the cell, so its definitions persist like any cell. The path is relative
113
+ to the session directory, or a `local://` or `file://` URL; other URL schemes are
114
+ refused and nothing is fetched. The cell runs as its file: Python compiles it under
115
+ the file's name, so tracebacks name the file and line, and sets `__file__` and puts
116
+ the file's directory first on the import path, so `from sibling import g` resolves
117
+ next to it. JavaScript evaluates it under the file's name and resolves its relative
118
+ imports from the file's directory. The file is read when the cell's turn comes in
119
+ the kernel's queue, so a `%load` queued behind the cell that writes the file runs
120
+ what that cell wrote. When the cell ends, Python takes the file's directory back off
121
+ the import path and restores `__file__`, so later cells import as before. A file that
122
+ cannot be read fails the cell with a message naming the path as written
123
+ (`file not found: <path>`, `permission denied: <path>`); files over 8 MiB, and
124
+ anything that is not a regular file, are refused.
125
+
126
+ ### JavaScript packages
127
+
128
+ A JavaScript cell whose only line is `%bun add <package ...>` or `%npm add <package ...>`
129
+ installs packages without restarting the kernel; the next cell imports them by bare name.
130
+ `%bun add` uses bun and `%npm add` uses npm; `environments.js.installer` (`bun`, `npm` or
131
+ `auto`: bun when it is on `PATH`, else npm) applies only where the magic names none, and the
132
+ kernel's own runtime never changes to get one.
133
+
134
+ In the default managed mode packages go into an environment revision under the session's
135
+ artifacts directory, never into the project's `package.json` or `node_modules`. With
136
+ `environments.managedRoot` set, every session using that root shares one revision chain: their
137
+ installs are serialized and each revision carries the packages installed before it.
138
+ A bare import resolves from the session directory's `node_modules` first and then from the
139
+ active revision, using each package's `exports` for `import` (ESM-only packages load), so the
140
+ project's own packages still win, and both win over Senpi's own dependencies (a package neither has may still load from Senpi's install). When a
141
+ newly added package is also in the project's `node_modules`, the result says
142
+ `environment_resolution_conflict` because the project copy resolves first.
143
+
144
+ Each install builds a new revision that carries the previous one forward (its `package.json`,
145
+ lockfile, and from `.npmrc` only `registry`, `@scope:registry`, `strict-ssl`, `ca` and `cafile`, rewritten as a regular file; credentials and every other key are dropped, and `bunfig.toml` is not carried)
146
+ and is published only when the installer succeeds; a failed or cancelled install, or one still
147
+ running when the session closes, leaves the previous revision active. Lifecycle scripts never run
148
+ (`--ignore-scripts`), installer flags are refused because the host picks the destination, and a
149
+ path-like package (`./pkg`, `file:../pkg`) is a path from the session directory. Package names
150
+ are split on whitespace; quoting is not supported. Error and installer text names the session directory as
151
+ `<cwd>`, the revision as `<root>`, the temp directory as `<tmp>`, the home directory as `~`, and an
152
+ absolute package path by its file name only. `%environment project` installs
153
+ into the session directory itself instead.
154
+
155
+ ### Python packages
156
+
157
+ A Python cell whose only line is `%pip install <requirements>` installs packages
158
+ without restarting the kernel: variables, the process and its working directory
159
+ stay as they were. The cell runs in the kernel's queue like any other cell (it waits
160
+ for the cell ahead of it, can be cancelled while queued, and detaches past the
161
+ foreground window), but the install runs on the host, so its time does not count
162
+ against the run budget. The next cell imports the new packages; modules a cell
163
+ already imported stay cached until `reset`.
164
+
165
+ Packages go into the session's own environment, never into the interpreter's
166
+ site-packages or the user site: pip always runs as
167
+ `<kernel interpreter> -m pip install --target <environment>`, and flags that pick
168
+ another destination (`--target`, `--user`, `--prefix`, `--root`, `--home`,
169
+ `-e`) are refused. Each install builds a new revision of the environment and
170
+ publishes it only when pip succeeds, so a failed or cancelled install leaves the
171
+ previous packages active and importable. A cell that mixes `%pip` with code is
172
+ refused; put `%pip` on its own cell.
173
+
174
+ `%environment managed` (the default) keeps the environment under the session's
175
+ artifacts directory, or `environments.managedRoot` when set; `%environment project`
176
+ installs into `<cwd>/.senpi/python-packages` instead, shared by every session in
177
+ that project, with concurrent installs serialised by a lock. Setting
178
+ `environments.autoProvision` to `false` turns installs off
179
+ (`environment_installer_unavailable`). Failures carry pip's error output and one
180
+ of `environment_install_failed`, `environment_install_cancelled`,
181
+ `environment_installer_unavailable` or `environment_resolution_conflict`.
182
+
183
+ ### Isolated cells
184
+
185
+ With `sandbox.enabled: true`, a JavaScript call may pass `isolate: true`. The cell then runs in a fresh QuickJS VM (the vendored pi codemode runtime) instead of the persistent kernel:
186
+
187
+ - Nothing persists: globals from the kernel are not visible, and a global set in one isolated cell is gone in the next. `store()` throws `eval_isolate_no_state` and `load()` returns `undefined`.
188
+ - No ambient host: there is no `process`, `require`, file system, network, child processes or timers. The cell's only reach is `tools.<name>` (also `tool.<name>`; every active tool except `eval`, run through the same permission hooks as a direct call) plus `print`, `display`, `text` and `image`.
189
+ - `isolate: true` isolates the JavaScript, not the tools it calls: a tool keeps its normal reach. `tools.bash`, for example, runs a shell with the session's environment and files, under the same permission hooks as any other call.
190
+ - Output streams from the VM in frames under a 256 KiB credit window, so the VM never holds a large item; the host joins an item's frames before adding it to the result, and memory stays bounded by `sandbox.memoryMb`.
191
+ - It is a host entry in the JavaScript queue: it waits for earlier cells, Stop and the run budget end it, and the persistent kernel is never restarted for it.
192
+ - Limits: `sandbox.memoryMb` (default 64) and `sandbox.timeoutSeconds` (default 300). Failures are named: `eval_isolate_memory_limit`, `eval_isolate_timeout`, `eval_isolate_unresolved_promise` (a top-level promise that can never settle) and `eval_isolate_unavailable` (the runtime could not start).
193
+
194
+ While `sandbox.enabled` is `false` (the default) the `isolate` field is absent from the eval schema, and passing it is refused with `eval_isolate_invalid`, as are `isolate` with another language and `isolate` with `reset`.
195
+
103
196
  ## Settings
104
197
 
105
198
  Configuration is loaded in this order:
@@ -161,7 +254,7 @@ Configuration is loaded in this order:
161
254
  | `memory.retainedResultsMb` | `32` | In-memory byte budget (MiB) for the settled cells kept for `peek`/`list`, on top of the 32-cell count cap; the oldest go first and the newest is always kept. `0` keeps only the count cap. Env override: `SENPI_CODEMODE_RETAINED_RESULTS_MB` (a non-negative integer). |
162
255
  | `memory.retainedImagesMb` | `256` | Disk budget (MiB) for settled-cell images. Images of settled cells (foreground and detached) are written as base64 files under `<session artifacts>/settled-images/` instead of staying in memory, and `peek` reads them back, so it returns the full result. Beyond the budget the oldest files are deleted first; an evicted cell's files are deleted with it; the directory is removed when the session ends. A `peek` whose image file is gone returns the text plus a one-line note. `0` keeps only the count cap. Env override: `SENPI_CODEMODE_RETAINED_IMAGES_MB` (a non-negative integer). |
163
256
  | `memory.idleParkMinutes` | `0` | Off by default. When greater than 0, a kernel with no cell running or queued for this many minutes is closed to give its memory back, and the next cell for that language starts a fresh one; that cell's result says the kernel was restarted and every earlier global is lost. Applies to every language. |
164
- | `languages.pyInterpreter` | unset | Explicit Python interpreter path. Unset keeps today's `PATH` detection. |
257
+ | `languages.pyInterpreter` | unset | Explicit Python interpreter path: the Python kernel runs exactly that executable (a path with spaces is fine). A path that does not answer `--version` makes Python unavailable for the session, with a warning naming the setting. Unset keeps `PATH` detection. |
165
258
  | `environments.managedRoot` | unset | Root directory for managed per-session environments; unset uses the session's default location. |
166
259
  | `environments.autoProvision` | `true` | Lets installs provision a managed environment. `false` makes installs refuse with `environment_installer_unavailable`. |
167
260
  | `environments.js.installer` | `auto` | Installer for the managed JavaScript environment: `auto`, `bun` or `npm`. |
@@ -171,16 +264,16 @@ Configuration is loaded in this order:
171
264
  | `sandbox.memoryMb` | `64` | Memory cap (MiB) for a sandbox cell. Env override: `SENPI_CODEMODE_SANDBOX_MEMORY_MB` (a positive integer wins). |
172
265
  | `sandbox.timeoutSeconds` | `300` | Time limit for a sandbox cell. |
173
266
  | `prompt.advertiseHelpers` | `false` | When `true`, one pointer line to `tool_schema('eval:helpers')` is appended to the eval description. |
174
- | `kernelTools.enabled` | `true` | Allows cells to define kernel tools (`tool(fn)`, `@tool`). `false` makes them refuse with `tools_unavailable`. |
267
+ | `kernelTools.enabled` | `true` | Allows cells to define kernel tools. `false` makes JavaScript `tool(fn)` and Python `@tool` refuse with `tools_unavailable`, naming this setting. |
175
268
 
176
- The `languages.pyInterpreter`, `environments.*`, `isolation.*`, `sandbox.*`, `prompt.*` and `kernelTools.*` keys are accepted and validated now, with the defaults shown, which match today's behaviour. The effect each of those rows describes takes effect when its feature ships; until then, setting a key changes nothing.
269
+ Every key in the table takes the effect its row describes. The one exception is `isolation.js`: it is accepted and validated now and takes effect with process isolation ([#2706](https://github.com/code-yeongyu/senpi/pull/2706)); until then the JavaScript kernel stays a worker.
177
270
 
178
271
  `SENPI_CODEMODE_PY`, `SENPI_CODEMODE_JS`, `SENPI_CODEMODE_RB`, and
179
272
  `SENPI_CODEMODE_JL` override the corresponding file setting. `1` or `true`
180
273
  enables; `0` or `false` disables. Any other value leaves the file setting in
181
274
  effect.
182
275
 
183
- A top-level key this version does not know is ignored with one warning naming it, and the rest of the file still applies, so a settings file written for a newer senpi keeps working. Malformed JSON, or an invalid value or an unknown key inside a known setting, falls back to all defaults with a warning.
276
+ Settings problems reach the user as a notice in the interactive UI, or a `[senpi-codemode]` line on stderr without one. A top-level key this version does not know is ignored with one warning naming it, and the rest of the file still applies, so a settings file written for a newer senpi keeps working. Malformed JSON, or an invalid value or an unknown key inside a known setting, falls back to all defaults with a warning.
184
277
  The detached-cell environment override uses the run-budget parser: a positive
185
278
  base-10 integer wins over the file value; zero, negative, and malformed values
186
279
  leave the file value in effect.
@@ -207,7 +300,7 @@ options object and asynchronous helpers are `await`-able.
207
300
  | `agent(prompt, ...)` | Delegates to the configured active `taskTools.task` tool. Supports background handles and structured JSON results. |
208
301
  | `wait(handles, timeout?, mode?)` | Blocks the cell until the given handles settle (agent handle records, `handle()` views, completion handles, closed workpools, or saved `{kind, id, run_epoch}` references). `mode` is `all` (values in input order; the first failed, cancelled, or lost handle raises), `any` (`{index, ref, value}` of the first success), or `settled` (one outcome per input slot). `timeout` is wall-clock seconds from entry; on expiry `eval_wait_timeout` is raised and nothing is cancelled. Rides the bridge-call path, so the run budget pauses while parked. Agent and workpool handles need the host's `EvalHandleHost` capability (`eval_wait_unavailable` without it); completion handles always work. Julia extends `Base.wait` for handle views (`wait(handle(node))`). Details: `tool_schema("eval:wait")`. |
209
302
  | `handle(node \| ref \| {pool_id})` | Returns a rich view: the legacy record's fields plus a non-enumerable `control` (Python: attribute on a `dict` subclass; Ruby: singleton method) with `status()`, `output(format?, offset?, limit?)`, `send(message)` (agent handles only), `cancel()` (idempotent for that run epoch; never touches a successor run), and `wait(timeout?)`. Every control call is fenced by owner, id, and `run_epoch` inside the task owner (`eval_handle_stale`, `eval_handle_forbidden`). `completion(prompt, handle: true)` returns such a view for a host completion. The `agent(..., handle: true)` record itself is unchanged. Details: `tool_schema("eval:helpers")`. |
210
- | `workpool(agent, name, mode?)` | Creates a thin adapter over the normal host `workpool` tool; exposes `pool_id`, `push(items)`, `close()`, `inspect()`, and `cancel()`. JS awaits creation and operations. |
303
+ | `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. |
211
304
  | `output(ids, format?, offset?, limit?)` | Delegates transcript retrieval to the configured active `taskTools.output` tool. |
212
305
  | `parallel(thunks)` | Runs thunks through the configured bounded pool while preserving input order. |
213
306
  | `pipeline(items, ...stages)` | Applies stages left to right with a barrier between stages. |
@@ -256,8 +349,11 @@ Any isolation metadata supplied by the host on a handle is preserved as
256
349
  `{subagent_type, prompt, model?}` as its plain-data agent spec. Mode is `fresh`
257
350
  or `keep_alive`: pass `{mode: "fresh"}` in JS, `mode="fresh"` in Python/Julia,
258
351
  or `mode: "fresh"` in Ruby. Omission is forwarded unchanged to the engine;
259
- hosts without an approved default still require an explicit mode. Custom tool
260
- names are not enabled by this adapter.
352
+ hosts without an approved default still require an explicit mode. `tools`
353
+ (kernel-tool names, for example from Python `@tool` or JavaScript `tool(fn)`) is
354
+ forwarded unchanged to the host's `create`, which validates it: `{tools: ["add"]}`
355
+ in JS, `tools=["add"]` in Python/Julia, `tools: ["add"]` in Ruby. There is no
356
+ `pool.wait()`; the host delivers the aggregate.
261
357
 
262
358
  `push` forwards `[{key, input}]` and returns the host receipt without waiting
263
359
  for admission. Operations return the same `{text, details, images?, hasError?}`
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "@code-yeongyu/senpi-codemode",
3
- "version": "2026.10.8",
3
+ "version": "2026.10.10-2",
4
4
  "description": "Source-only senpi extension package for codemode evaluation tools",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
7
7
  "types": "./src/index.ts",
8
8
  "exports": {
9
9
  ".": "./src/index.ts",
10
- "./package.json": "./package.json"
10
+ "./package.json": "./package.json",
11
+ "./executable-settings.json": "./src/config/executable-settings.json"
11
12
  },
12
13
  "files": [
13
14
  "src",
@@ -32,15 +33,15 @@
32
33
  },
33
34
  "dependencies": {
34
35
  "@babel/parser": "8.0.4",
35
- "@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.10.8",
36
+ "@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.10.10-2",
36
37
  "quickjs-wasi": "3.6.2",
37
38
  "typebox": "1.3.34"
38
39
  },
39
40
  "peerDependencies": {
40
- "@code-yeongyu/senpi": "2026.10.8"
41
+ "@code-yeongyu/senpi": "2026.10.10-2"
41
42
  },
42
43
  "devDependencies": {
43
- "@code-yeongyu/senpi": "2026.10.8"
44
+ "@code-yeongyu/senpi": "2026.10.10-2"
44
45
  },
45
46
  "keywords": [
46
47
  "senpi",
@@ -8,6 +8,8 @@ const LOOPBACK_HOST = "127.0.0.1";
8
8
 
9
9
  export interface BridgeHttpCallRequest {
10
10
  callId: string;
11
+ /** The calling run's secret; the host resolves that run's kernel-tools capability from it. */
12
+ cellToken?: string;
11
13
  toolName: string;
12
14
  args: unknown;
13
15
  signal: AbortSignal;
@@ -132,7 +134,13 @@ async function dispatchCall(body: unknown, options: BridgeServerOptions, signal:
132
134
  try {
133
135
  return {
134
136
  ok: true,
135
- value: await options.onCall({ callId: body.callId, toolName: body.toolName, args: body.args, signal }),
137
+ value: await options.onCall({
138
+ callId: body.callId,
139
+ ...(typeof body.cellToken === "string" ? { cellToken: body.cellToken } : {}),
140
+ toolName: body.toolName,
141
+ args: body.args,
142
+ signal,
143
+ }),
136
144
  };
137
145
  } catch (error) {
138
146
  return { ok: false, error: bridgeError(error) };
@@ -44,6 +44,10 @@ const hostToKernelMessageSchema = Type.Union([
44
44
  cellId: Type.String({ minLength: 1 }),
45
45
  code: Type.String(),
46
46
  timeoutMs: Type.Optional(Type.Integer({ minimum: 1 })),
47
+ /** Python only: the published environment revision to import from, applied before the cell runs; empty removes the previous one. */
48
+ envRoot: Type.Optional(Type.String()),
49
+ /** The file a `%load` cell runs; the runner compiles under its name and imports beside it. */
50
+ sourceFile: Type.Optional(Type.String({ minLength: 1 })),
47
51
  /** Python only: active tool globals to install before the cell and deactivated ones to remove. */
48
52
  preludes: Type.Optional(
49
53
  Type.Object({
@@ -52,6 +52,7 @@ const helpersEntry: EvalSchemaResult = {
52
52
  "control.status() goes through the host subscription; control.send/cancel/output are fenced by owner, id and run_epoch inside the task owner (stale -> eval_handle_stale, foreign -> eval_handle_forbidden); control.output() returns only that epoch's transcript. The plain output() helper and task tools are unchanged.",
53
53
  "The legacy agent(..., {handle: true}) record is unchanged: .output stays a string and no enumerable key is added. A saved {kind, id, run_epoch} (or the record itself) can be rebound with handle(ref) in a later cell or after a kernel reset while the owner and run epoch are valid.",
54
54
  "completion(prompt, {handle: true}) (py: handle=True) returns a control handle after preflight validation; provider failures surface in its outcome; its deadline derives from the creating cell's hard deadline. Completion handles are codemode-owned and need no host capability; once the session generation is dropped they fail with eval_handle_stale.",
55
+ "workpool(agent, name, {mode?, tools?}) (py/jl: mode=, tools=; rb: mode:, tools:) forwards tools (kernel-tool names, e.g. from @tool or tool(fn)) unchanged to the host workpool tool's create; the host checks them. There is no pool.wait(): the host delivers the aggregate and the kernel stays free to serve kernel tools.",
55
56
  "See tool_schema('eval:wait') for the barrier semantics.",
56
57
  ].join("\n"),
57
58
  parameters: {
@@ -0,0 +1,5 @@
1
+ {
2
+ "projectExecutableSettings": [
3
+ "languages.pyInterpreter"
4
+ ]
5
+ }
@@ -0,0 +1,51 @@
1
+ import { join } from "node:path";
2
+ import executableSettings from "./executable-settings.json" with { type: "json" };
3
+ import type { CodemodeSettings } from "./settings.ts";
4
+
5
+ /**
6
+ * Settings that name an executable run at session start (an interpreter's `--version` probe, then the kernel). The
7
+ * one list of them lives in `executable-settings.json`, which senpi's project-trust check also reads: a project
8
+ * codemode file that sets any of them asks for trust. Without trust they are dropped with a warning and never run.
9
+ * Trust is asked only when the project's own file sets one, so a host that cannot answer still starts sessions;
10
+ * such a host counts as not trusting the project.
11
+ */
12
+ export const PROJECT_EXECUTABLE_SETTINGS: readonly string[] = executableSettings.projectExecutableSettings;
13
+
14
+ export function withoutUntrustedInterpreter<Settings extends CodemodeSettings>(
15
+ settings: Settings,
16
+ source: string | null,
17
+ cwd: string,
18
+ isProjectTrusted: (() => boolean) | undefined,
19
+ ): { readonly settings: Settings; readonly warning?: string } {
20
+ const projectFile = join(cwd, ".senpi", "codemode.json");
21
+ if (source !== projectFile) return { settings };
22
+ const named = PROJECT_EXECUTABLE_SETTINGS.filter((path) => valueAt(settings, path) !== undefined);
23
+ if (named.length === 0 || isProjectTrusted?.() === true) return { settings };
24
+ let trimmed: Settings = settings;
25
+ for (const path of named) trimmed = withoutPath(trimmed, path);
26
+ const list = named.map((path) => `${path} "${String(valueAt(settings, path))}"`).join(", ");
27
+ return {
28
+ settings: trimmed,
29
+ warning: `${list} in ${projectFile} is ignored because this project is not trusted; it was not run`,
30
+ };
31
+ }
32
+
33
+ function valueAt(value: unknown, path: string): unknown {
34
+ let current: unknown = value;
35
+ for (const key of path.split(".")) {
36
+ if (typeof current !== "object" || current === null) return undefined;
37
+ current = Reflect.get(current, key);
38
+ }
39
+ return current;
40
+ }
41
+
42
+ function withoutPath<T>(value: T, path: string): T {
43
+ const copy = structuredClone(value);
44
+ const keys = path.split(".");
45
+ const last = keys.pop();
46
+ let parent: unknown = copy;
47
+ for (const key of keys)
48
+ parent = typeof parent === "object" && parent !== null ? Reflect.get(parent, key) : undefined;
49
+ if (last !== undefined && typeof parent === "object" && parent !== null) Reflect.deleteProperty(parent, last);
50
+ return copy;
51
+ }
@@ -20,6 +20,8 @@ export function resolveEnabledLanguages(
20
20
  env: Environment = process.env,
21
21
  ): CodemodeSettings["languages"] {
22
22
  return {
23
+ // Keep the non-flag keys (languages.pyInterpreter); only the four enable flags take env overrides.
24
+ ...settings.languages,
23
25
  py: resolveLanguage(settings.languages.py, env[languageEnvironmentFlags.py]),
24
26
  js: resolveLanguage(settings.languages.js, env[languageEnvironmentFlags.js]),
25
27
  rb: resolveLanguage(settings.languages.rb, env[languageEnvironmentFlags.rb]),
@@ -0,0 +1,208 @@
1
+ import { mkdir, readFile, realpath, rm, stat } from "node:fs/promises";
2
+ import { isAbsolute, join } from "node:path";
3
+ import type { ResolvedCodemodeSettings } from "../config/settings.ts";
4
+ import { withRootLock } from "./install-lock.ts";
5
+ import {
6
+ absoluteSpec,
7
+ type JsInstallerChoice,
8
+ parseJsPackages,
9
+ requestedPackageName,
10
+ resolveJsInstaller,
11
+ runJsInstall,
12
+ withoutHostPaths,
13
+ } from "./js-installer.ts";
14
+ import { carryNpmrcSettings, recordedFileSpecs, seedPackageJson } from "./js-revision-files.ts";
15
+ import { assertBuiltRevisionLinks, assertNoLinksBelow, recordedInstallSources } from "./no-links.ts";
16
+ import { projectResolves } from "./project-resolves.ts";
17
+ import type { EnvironmentMode } from "./py-environment.ts";
18
+ import { EnvironmentError } from "./py-installer.ts";
19
+ import { mkdirPrivate, publishNextRevision, readActiveRevision } from "./revision-store.ts";
20
+
21
+ /** The paths in a revision that the installer writes. */
22
+ const INSTALLER_WRITES = [
23
+ "package.json",
24
+ "package-lock.json",
25
+ "bun.lock",
26
+ "bun.lockb",
27
+ "node_modules",
28
+ ".npmrc",
29
+ "bunfig.toml",
30
+ ];
31
+
32
+ export interface JsInstallReceipt {
33
+ readonly installer: "bun" | "npm";
34
+ readonly mode: EnvironmentMode;
35
+ readonly revision: number | undefined;
36
+ readonly added: readonly string[];
37
+ readonly shadowed: readonly string[];
38
+ }
39
+
40
+ export interface JsEnvironmentsOptions {
41
+ readonly artifactsDir: string;
42
+ readonly cwd: string;
43
+ readonly runtime: string;
44
+ readonly env: NodeJS.ProcessEnv;
45
+ readonly settings: Pick<ResolvedCodemodeSettings, "environments">;
46
+ }
47
+
48
+ export class JsEnvironments {
49
+ readonly #options: JsEnvironmentsOptions;
50
+ #mode: EnvironmentMode = "managed";
51
+ #packageRoot: string | undefined;
52
+
53
+ constructor(options: JsEnvironmentsOptions) {
54
+ this.#options = options;
55
+ }
56
+
57
+ get mode(): EnvironmentMode {
58
+ return this.#mode;
59
+ }
60
+
61
+ get packageRoot(): string | undefined {
62
+ return this.#mode === "managed" ? this.#packageRoot : undefined;
63
+ }
64
+
65
+ async setMode(mode: EnvironmentMode): Promise<string> {
66
+ this.#mode = mode;
67
+ if (mode === "project") return this.#options.cwd;
68
+ this.#packageRoot = (await readActiveRevision(this.#managedBase()))?.dir;
69
+ return this.#managedBase();
70
+ }
71
+
72
+ async install(
73
+ requested: string,
74
+ signal: AbortSignal,
75
+ onOutput?: (stream: "stdout" | "stderr", data: string) => void,
76
+ requestedInstaller?: "bun" | "npm",
77
+ ): Promise<JsInstallReceipt> {
78
+ const environments = this.#options.settings.environments;
79
+ if (environments?.autoProvision === false) {
80
+ throw new EnvironmentError(
81
+ "environment_installer_unavailable",
82
+ "installs are turned off for this project (environments.autoProvision is false)",
83
+ );
84
+ }
85
+ const packages = parseJsPackages(requested).map((spec) => absoluteSpec(spec, this.#options.cwd));
86
+ // `%bun add` and `%npm add` name their installer; the setting applies only where the magic does not.
87
+ const choice: JsInstallerChoice = requestedInstaller ?? environments?.js?.installer ?? "auto";
88
+ const { installer, command } = resolveJsInstaller(choice, this.#options.env);
89
+ let recordedSpecs: readonly string[] = [];
90
+ const run = (root: string, remove?: string) =>
91
+ runJsInstall({
92
+ installer,
93
+ command,
94
+ root,
95
+ packages,
96
+ ...(remove === undefined ? {} : { remove }),
97
+ recordedSpecs,
98
+ cwd: this.#options.cwd,
99
+ env: this.#options.env,
100
+ signal,
101
+ ...(onOutput === undefined ? {} : { onOutput }),
102
+ });
103
+ // The lock and the revision store fail with raw file system errors; they reach the cell redacted.
104
+ const redacted =
105
+ (...roots: string[]) =>
106
+ (error: unknown) => {
107
+ const raw =
108
+ error instanceof EnvironmentError
109
+ ? error.message.slice(error.code.length + 2)
110
+ : String(error instanceof Error ? error.message : error);
111
+ const text = roots.reduce(
112
+ (message, root) => withoutHostPaths(message, { root, cwd: this.#options.cwd, packages, recordedSpecs }),
113
+ raw,
114
+ );
115
+ if (error instanceof EnvironmentError) throw new EnvironmentError(error.code, text);
116
+ // An abort while waiting for the lock or before the publish is a cancel, not a failure.
117
+ if (signal.aborted)
118
+ throw new EnvironmentError("environment_install_cancelled", `the install was cancelled: ${text}`);
119
+ throw new EnvironmentError("environment_install_failed", text);
120
+ };
121
+ if (this.#mode === "project") {
122
+ const before = await dependencyNames(this.#options.cwd);
123
+ const lockRoot = join(this.#options.cwd, ".senpi", "js-packages");
124
+ await mkdir(lockRoot, { recursive: true });
125
+ await withRootLock(lockRoot, async () => await run(this.#options.cwd), signal).catch(redacted(lockRoot));
126
+ const added = (await dependencyNames(this.#options.cwd)).filter((name) => !before.includes(name));
127
+ return { installer, mode: "project", revision: undefined, added, shadowed: [] };
128
+ }
129
+ let added: string[] = [];
130
+ const requestedBase = this.#managedBase();
131
+ const base = await canonicalBase(this.#managedRoot(), requestedBase).catch(redacted(requestedBase));
132
+ const { revision } = await publishNextRevision(
133
+ base,
134
+ async (staging) => {
135
+ await carryNpmrcSettings(staging);
136
+ await rm(join(staging, "bunfig.toml"), { recursive: true, force: true });
137
+ await seedPackageJson(staging);
138
+ // Every path the installer writes must be the revision's own, never a link out of it.
139
+ for (const entry of INSTALLER_WRITES) await assertNoLinksBelow(base, join(staging, entry));
140
+ const before = await dependencyNames(staging);
141
+ recordedSpecs = await recordedFileSpecs(staging);
142
+ // A package whose source changes kind (a directory to a tarball or registry version, or back) is removed
143
+ // first: bun keeps its per-file links into the old directory otherwise (#2758).
144
+ for (const name of await sourceKindChanges(staging, packages)) await run(staging, name);
145
+ await run(staging);
146
+ await assertBuiltRevisionLinks(staging);
147
+ added = (await dependencyNames(staging)).filter((name) => !before.includes(name));
148
+ },
149
+ signal,
150
+ ).catch(redacted(base, requestedBase));
151
+ this.#packageRoot = revision.dir;
152
+ const shadowed = added.filter((name) => projectResolves(this.#options.cwd, name));
153
+ return { installer, mode: "managed", revision: revision.number, added, shadowed };
154
+ }
155
+
156
+ #managedRoot(): string {
157
+ return this.#options.settings.environments?.managedRoot ?? this.#options.artifactsDir;
158
+ }
159
+
160
+ #managedBase(): string {
161
+ return join(this.#managedRoot(), "environments", "js", this.#options.runtime);
162
+ }
163
+ }
164
+
165
+ async function dependencyNames(root: string): Promise<string[]> {
166
+ try {
167
+ const manifest: unknown = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
168
+ if (typeof manifest !== "object" || manifest === null || !("dependencies" in manifest)) return [];
169
+ const dependencies = manifest.dependencies;
170
+ return typeof dependencies === "object" && dependencies !== null ? Object.keys(dependencies) : [];
171
+ } catch (error) {
172
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return [];
173
+ throw error;
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Creates the managed base, checks that nothing below the managed root is a link, and returns its realpath: npm keys
179
+ * a linked package in its lockfile by a path relative to the prefix, and a prefix under a linked directory (macOS
180
+ * `/var` is a link to `/private/var`) gives keys that stop resolving once the staged revision is renamed.
181
+ */
182
+ async function canonicalBase(managedRoot: string, base: string): Promise<string> {
183
+ await assertNoLinksBelow(managedRoot, base);
184
+ await mkdirPrivate(base);
185
+ await assertNoLinksBelow(managedRoot, base);
186
+ return await realpath(base);
187
+ }
188
+
189
+ /** Names among `packages` whose recorded source is a directory and is not the same directory now, or the reverse. */
190
+ export async function sourceKindChanges(revision: string, packages: readonly string[]): Promise<string[]> {
191
+ const installed = new Set(await dependencyNames(revision));
192
+ const sources = await recordedInstallSources(revision);
193
+ const changed: string[] = [];
194
+ for (const spec of packages) {
195
+ const name = await requestedPackageName(spec);
196
+ if (name === undefined || !installed.has(name)) continue;
197
+ const directory = await localDirectory(spec);
198
+ if (directory !== sources.get(name)) changed.push(name);
199
+ }
200
+ return changed;
201
+ }
202
+
203
+ async function localDirectory(spec: string): Promise<string | undefined> {
204
+ const path = spec.startsWith("file:") ? spec.slice("file:".length) : spec;
205
+ if (!isAbsolute(path)) return undefined;
206
+ const resolved = await realpath(path).catch(() => undefined);
207
+ return resolved !== undefined && (await stat(resolved)).isDirectory() ? resolved : undefined;
208
+ }