@sorbetai/tools-node 0.0.0-stage → 0.1.0-alpha.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.pi ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Mario Zechner
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,359 @@
1
- # Temporary Holding Version
1
+ # `@sorbetai/tools-node`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ This package provides independently selectable Node Tools for the Pi Agent loop.
4
+ Each factory accepts a borrowed `ExecutionEnv` or an invocation-time environment
5
+ provider. Runtime's Session-owned Permission composition decides admission.
6
+
7
+ | Entry | Responsibility | Ownership |
8
+ | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | --------------------------------------------------------- |
9
+ | [`createReadTool()`](./src/execution/read.ts) | File reading, image processing, and offset-based continuation | Borrows the execution environment |
10
+ | [`createEditTool()`](./src/execution/edit.ts) | Original-file batch replacements, fuzzy matching, and diffs | Borrows the execution environment |
11
+ | [`createWriteTool()`](./src/execution/write.ts) | Complete file writes and parent-directory creation | Borrows the execution environment |
12
+ | [`createBashTool()`](./src/execution/bash.ts) | Output streaming, truncation, and structured command results | Borrows the execution environment |
13
+ | [`@sorbetai/tools-node/environment`](./src/environment/index.ts) | Filesystem capabilities, command execution, cancellation, and typed failures | Host owns construction and cleanup |
14
+ | [`readTool`, `editTool`, `writeTool`, `bashTool`](./src/plugins/execution-tools.ts) | Four execution Tools resolved from the `ExecutionEnvironment` Service | Borrows one Provider generation per logical model request |
15
+ | [`createWorkspacePlugin()`](./src/plugins/workspace.ts) | Workspace inspection Tools, fixed instructions, and Session-scoped feedback state | Borrows an invocation-time environment provider |
16
+ | `createWorkspacePluginPackage()` / `createWorkspacePluginHostBindings()` | Encodes the shipped author bundle / explicitly binds its IO Tools for one Package and Entry | Host owns installation, loader and execution environment |
17
+ | `NodeWorkspace.open()` | Canonicalizes an existing absolute cwd | Does not establish a Sandbox |
18
+
19
+ `CommandTasks` owns OS command execution and output. The first-party
20
+ [`commandTaskDefinition`](./src/commands/task.ts) owns the B4 durable result and
21
+ completion Submission; [its Host integration contract](#host-command-capability)
22
+ keeps process I/O outside Task phases.
23
+
24
+ It deliberately does not establish a filesystem, process, or network Sandbox.
25
+ Sandboxing and Run scoping are application-level execution concerns. The
26
+ provider form lets Node Agent select the already-admitted Run environment
27
+ without putting Sandbox policy into model-facing Tool schemas.
28
+
29
+ Select just the capabilities a Session needs:
30
+
31
+ ```ts
32
+ import { createReadTool, createBashTool } from '@sorbetai/tools-node';
33
+ import { NodeExecutionEnv } from '@sorbetai/tools-node/environment';
34
+
35
+ const environment = new NodeExecutionEnv({ cwd: workspaceRoot });
36
+ const tools = [createReadTool(environment), createBashTool(environment)];
37
+ ```
38
+
39
+ Pass `tools` to the Session and clean up the environment after its borrowing Sessions
40
+ close. Constructing a Tool never resolves an environment provider. Node Agent
41
+ mounts the independent tool plugins, which use these same factories and obtain
42
+ their Provider through Services.
43
+
44
+ All four factories are maintained in Sorbet, adapted from Pi's reference Tools under
45
+ the upstream MIT license. Filesystem and command operations use the borrowed execution
46
+ environment. Image processing uses Photon and edit patches use `diff`; neither the
47
+ factories nor Node Agent depend on Pi Coding Agent. Each factory owns its schema,
48
+ argument preparation and result shape.
49
+
50
+ Read uses 2,000-line/50KiB pages, line-offset continuation, UTF-8 decoding and image
51
+ processing. Long lines return a `byteRange.next` cursor: pass it as `byteOffset`
52
+ instead of a line `offset`. Ranges use zero-based UTF-8 byte offsets and an exclusive
53
+ `end`. Byte pages include presentation guidance in `content`
54
+ and unannotated text in `structuredContent`, so concatenating the latter reconstructs
55
+ the selected UTF-8 text exactly. Cursors refer to the current file, and reject an
56
+ invalid UTF-8 boundary or malformed UTF-8. Text reads use bounded binary ranges
57
+ through the environment: a byte cursor seeks directly to its page, while a line
58
+ offset scans the preceding bytes in bounded windows. Total line counts are shown
59
+ only when the current window reaches EOF. Images still load their complete bytes
60
+ for decoding. Reads observe the current file rather than a retained snapshot.
61
+ `ExecutionEnv.readBinaryFile(path, { abortSignal?, range?: { offset, length } })`
62
+ reads at most the requested bytes; omitting range reads the complete binary file.
63
+
64
+ Edit matches every replacement against the original file and writes only
65
+ after all matches succeed. It needs no previous read call. Its patch describes
66
+ LF-normalized text without a BOM; the written file preserves its original BOM and line
67
+ ending convention. Edit reads through the environment's strict UTF-8 text capability.
68
+
69
+ Filesystem methods take `FileExecutionOptions` from `/environment`, including
70
+ `abortSignal` and an optional `beforeStart` callback. The environment calls the guard
71
+ after resource waiting, immediately before dispatching IO. Sandbox filesystem workers
72
+ use the same guard after both Host process permits and the sandbox profile lease are
73
+ available. Local multi-step writes recheck after creating parent directories. Guard
74
+ failures retain their original error as a cause and return a failed Tool result; the
75
+ guard rechecks captured authority rather than requesting another Permission decision.
76
+ Each execution plugin passes its captured Plugin owner check, and stored workspace Host
77
+ bindings preserve the Package and source check supplied by their execution context.
78
+ Captured retiring owners remain usable until their borrow drains.
79
+
80
+ Edit and write share a per-environment file mutation queue, including canonical-path
81
+ aliases, even when constructed separately. Bash streams
82
+ combined output, reports nonzero exits as failed Tool results, and supplies an exit code
83
+ in `structuredContent`. It has no default timeout. Truncated command logs are stored in
84
+ local temporary files; complete output remains available unless the Host explicitly
85
+ selects an output quota. Runtime owns Permission, Approval and write-ahead Effect facts, and may
86
+ apply additional output limits.
87
+
88
+ Commands use the Host or explicitly supplied shell environment. Install `rg` on
89
+ that environment's `PATH` when using ripgrep-based commands. Custom and remote
90
+ `ExecutionEnv` implementations supply their own commands.
91
+
92
+ ## Host command capability
93
+
94
+ Bash has one schema across execution Providers. With a `CommandTasks` owner and
95
+ `managedCommands` capability, `bash({ command })` observes the same execution for
96
+ the Host's `foregroundMs` window, default 30 seconds. Completion within the window
97
+ returns its result; a still-running command returns a handle and continues without
98
+ re-execution. The window never terminates a capable command. Omitted `timeout`
99
+ means no execution deadline on this path. `runInBackground: true` overrides the
100
+ window with immediate handoff after verified setup; `yieldMs` overrides it once.
101
+
102
+ A foreground-only Provider waits
103
+ for completion or cancellation. Only an explicit `timeout` imposes an execution
104
+ deadline. Background/observation overrides reject before dispatch when handoff is
105
+ unavailable. Host opt-out removes the task owner and selects foreground execution.
106
+
107
+ | Surface | Contract | Owner |
108
+ | -------------------------------------------------- | --------------------------------------------------------------- | ------------------------------------------------------ |
109
+ | `CommandTasks` | Active handles, finite recent results, capture, wait and cancel | Execution Host |
110
+ | `FileCommandStore` | Atomic bounded current snapshot, validated on load | Host with exclusive access |
111
+ | `createBashTool(source, commands?, ownExecution?)` | Execute commands; list, inspect, read output, or cancel handles | Borrows environment and optional owner |
112
+ | `commandWaitTargets(store)` | Lets the durable `wait` Tool wait for this Session's commands | Durable `waitTargets` |
113
+ | `bashTool` with `CommandRuntime` | Same Tools over the resolved Plugin execution environment | Plugin owns commands; Node Agent supplies Unit binding |
114
+ | `ProcessCapacity` from `/environment` | Shared concurrent-execution permits with cancellable waiting | Host supplies it to local environments |
115
+
116
+ `CommandStore.write(current, archived)` must persist both sets: `archived` contains
117
+ latest states leaving the process cache, not necessarily states already saved.
118
+ A Host must finish `recover()` before exposing its Tools, and drain/close tasks
119
+ before disposing their execution environment. Stores require exclusive ownership.
120
+ A Node Host supplies a `CommandOrigin` link to the already committed Core Tool
121
+ Effect. Independent execution Hosts can use their own resource store without
122
+ requiring Sorbet Core or changing Plugin Platform.
123
+
124
+ Defaults are 10 active tasks and 64 recently completed tasks. Complete output is
125
+ streamed to disk by default; `maxOutputBytes` opts into a retained-output quota.
126
+ `maxCompleted: 0` disables the recent-result cache. Listing shows active tasks and
127
+ the recent window; old task IDs and output remain readable from Unit Task history
128
+ or the file adapter’s archived resource records. Cache eviction and current command
129
+ states share one Unit commit; the file adapter writes archives before replacing
130
+ its snapshot. Both live owners and restart recovery use the same cache default. Eviction never deletes logs. `status(taskId)` performs asynchronous
131
+ lookup so cold results do not grow the hot cache. Unobserved background completion
132
+ references remain in the recovery snapshot until delivered. Explicitly unverified
133
+ cleanup records remain until Host repair and reject successful owner close/reattachment,
134
+ even when the recent-result cache is disabled. Ordinary commands with an owner
135
+ enter this bounded window too; there is no separate short-command execution path.
136
+ Admission waits for a Session permit and then a Host process permit. Cancelling a
137
+ wait does not launch work. Permits remain held until real execution cleanup settles;
138
+ unverified cleanup retains its permits for Host repair. Actual dispatch rechecks
139
+ captured Provider authority after waiting. A live handle requires a verified identity
140
+ whose snapshot write has completed. Slow setup does not create an execution deadline.
141
+ A stalled Store can delay Tool/owner close; an observation deadline cannot certify
142
+ persistence or cancel the Store Promise.
143
+ Execution deadlines, when supplied, include setup and survive handoff.
144
+
145
+ Both Bash paths provide `output`, `truncated`, `exit_code`, `wall_time_seconds` and
146
+ `status` in structured results. A supervised result also includes `taskId`, a log
147
+ path and capture-loss indication. Return values keep bounded previews while stream callbacks receive complete output.
148
+ Direct environment calls provide an artifact path when their preview is exceeded.
149
+ Model-visible short results remain readable;
150
+ running results contain JSON with that shared shape. Terminal states distinguish
151
+ completion, failure, cancellation, timeout and unknown execution. A successful
152
+ handoff Tool Effect proves return of a handle, rather than eventual process success.
153
+
154
+ `bash({ action: 'output', taskId, offset?, limit? })` pages retained output by
155
+ byte offset and `nextOffset`, up to 65,536 bytes. The other management actions
156
+ are `list`, `status`, and `cancel`. These actions access the Session owner without
157
+ resolving an execution environment or launching a process. In Plugin execution,
158
+ Bash remains available for management after Provider withdrawal; new execution
159
+ requires an active Provider. Preview truncation differs from capture loss.
160
+
161
+ Waiting is not part of Bash. The durable executor's `wait` Tool waits on Unit
162
+ entities ([ADR-0125](../../docs/adr/0125-durable-task-wait.md)); `commandWaitTargets(store)`
163
+ lets it resolve the command id Bash returned to its CommandTask, render the stored
164
+ result (with a usable `outputReference`), and recognize command completion
165
+ notifications so a wait that returns a command withdraws its unplaced notification.
166
+
167
+ The B4 Unit path uses `new UnitCommandStore(unit, sessionId, outputDirectory)` as the
168
+ `CommandTasks` store. Register `commandTaskDefinition` on every Unit open, recover
169
+ the command owner before `unit.resume()`, and close the owner before the Unit.
170
+ Registration commits before OS dispatch; process identity, background handoff and
171
+ exit are Signals. Foreground failures remain readable even when their Tool receipt
172
+ is a failure. The Task never launches or replays a process. Output stays in files. Supplying
173
+ `outputDirectory` stores command file names and resolves them on read against the
174
+ current directory; omit it only when the supplied references are already portable
175
+ or intentionally tied to their original location.
176
+
177
+ `stageCommandTask(tx, { sessionId, epochId, command })` is the lower-level atomic
178
+ initializer. It returns Task and Signal identities. The exit phase accepts one
179
+ `command-completion-<commandId>` input unless consumed, foreground or cancelled.
180
+ A durable `wait` withdraws the unplaced completion with commandId `wait:<Tool Task id>`;
181
+ `SessionCommands` treats that, like a `command-model:` withdrawal, as delivered.
182
+ Existing receipt-only Task checkpoints remain readable.
183
+
184
+ Before Unit resume, the Host calls
185
+ `recoverSessionCommands(unit, sessionId, outputDirectory)` after the previous
186
+ process owner is gone. This tools-node recovery path settles committed command
187
+ attempts even when bash is no longer installed. It neither exposes a Tool nor
188
+ redispatches a command. Node Agent invokes it for persisted Session commands.
189
+
190
+ NodeAgent uses this Unit path by default. `FileCommandStore` remains available for
191
+ standalone process owners and offline import; see the
192
+ [NodeAgent migration contract](../node-agent/src/migration/README.md).
193
+
194
+ Before handoff, Tool abort stops execution. Afterwards explicit task cancellation,
195
+ a supplied deadline or owner close stops it. Reload reconciles unresolved saved
196
+ identities as `unknown` without replay. Failed identity inspection, malformed
197
+ snapshots and unverifiable drain remain visible. POSIX group escape and
198
+ non-atomic process identity checks limit containment; see
199
+ [ADR-0097](../../docs/adr/0097-host-owned-command-lifetimes.md).
200
+
201
+ ### Windows process ownership
202
+
203
+ The local Node environment supports managed commands on Windows 10 / Server 2016
204
+ and later with 64-bit Node (x64 or arm64). The Windows backend uses Koffi to call
205
+ Win32 inside the tools-node execution boundary. A suspended probe checks Job
206
+ assignment before dispatch. The executable is resolved to an absolute `.exe` or
207
+ `.com` through the child environment's `PATH` before creation, so a bare shell
208
+ name such as `cmd.exe` does not depend on the supervisor's current directory.
209
+ Each command is created suspended, assigned to its own Job, and resumed only
210
+ after successful assignment. Jobs enable
211
+ `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` and neither breakaway flag. A host already
212
+ inside a Job must permit nested Job assignment; incompatible host restrictions
213
+ fail before the requested command executes.
214
+
215
+ Cancellation, timeout and owner close terminate the Job and query its active
216
+ process count with a bounded deadline. Supervisor death closes its Job handle,
217
+ causing Windows to terminate members. Recovery opens the saved named Job to
218
+ terminate and verify surviving members, or observes that it no longer exists;
219
+ it settles the original task without executing the command again. Cleanup that
220
+ cannot be verified remains visible as a failure.
221
+
222
+ Ordinary descendants remain members even when they create a new process group.
223
+ Jobs are lifecycle containment, not a security sandbox: processes created by an
224
+ external service, scheduled task, WMI broker, or another process outside the Job
225
+ are outside this ownership boundary. See Microsoft's
226
+ [Job Objects documentation](https://learn.microsoft.com/en-us/windows/win32/procthread/job-objects).
227
+ Stdio uses anonymous pipes: the child inherits only the child ends, and the
228
+ supervisor drains output through `PeekNamedPipe` without staging it on disk.
229
+ Input is written through the stdin pipe, so a crashed supervisor leaves no
230
+ temporary files behind.
231
+
232
+ If the Job backend cannot be loaded or its suspended probe fails before a
233
+ command is dispatched, Windows falls back to the bounded foreground executor
234
+ instead of rejecting every command. That path has no Job containment: killing
235
+ the owner may leave descendants running, so it is a compatibility fallback, not
236
+ the managed guarantee above.
237
+
238
+ ## Service-backed execution
239
+
240
+ `readTool`, `editTool`, `writeTool`, and `bashTool` are independent Plugin
241
+ definitions. Install only the capabilities a Session needs. File plugins require
242
+ `ExecutionEnvironment`, whose value is an `ExecutionEnvironmentProvider` with
243
+ `forInvocation`, `invocationProperties`, and `confinement`. The Provider owns its
244
+ environments and cleanup. Tools own argument validation, IO behavior, and results.
245
+
246
+ `forInvocation` receives Runtime's approval outcome and the Run identity. A
247
+ sandbox Provider uses that outcome rather than recomputing permission policy.
248
+ `invocationProperties` contributes Provider-specific parameters to Tool schemas;
249
+ a local unrestricted Provider does not advertise sandbox escalation parameters.
250
+
251
+ `bashTool` requires `CommandRuntime`, a typed Service owned by this package.
252
+ Node Agent supplies the Unit, Session identity, output directory, options, and
253
+ attachment callback. `enabled: false` selects
254
+ foreground execution without a command owner; Node Agent maps
255
+ `commandExecution: false` to this setting. With command execution enabled, the plugin registers `commandTaskDefinition` through
256
+ `UnitRuntime.registerTask`, creates its `UnitCommandStore` and `SessionCommands`,
257
+ and registers `bash`; `onReady` hands its store to the Host for `commandWaitTargets`. It closes command execution before releasing
258
+ its resources. Unit recovery and shutdown must keep the commit line open while
259
+ command outcomes settle. This integration does not add a Runtime dependency to
260
+ `@sorbetai/plugins`.
261
+
262
+ The bash command owner survives execution Provider replacement. Its execution
263
+ consumer uses an optional environment binding: after withdrawal, existing handles
264
+ remain inspectable and cancellable, while new commands fail without a Provider.
265
+
266
+ Provider replacement follows Plugin request leases. Runtime retains validation,
267
+ permissions, cancellation, write-ahead Effects, and terminal outcomes. Missing
268
+ required Services leave Tools unavailable; no local execution fallback is added.
269
+ See [execution composition](../../docs/design/tool-plugins.md) for the ownership map.
270
+
271
+ ## Workspace Plugin
272
+
273
+ `createWorkspacePlugin(environment)` returns one apply function, installed with
274
+ `configure([{ key, apply, config: null }])` on a `PluginPlatform` from the independent
275
+ [`@sorbetai/plugins`](../plugins/README.md) package.
276
+
277
+ | Tool | Input | Result |
278
+ | -------------------- | ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
279
+ | `workspace_outline` | Optional `directory` (default `.`), `after` entry name, and `limit` (default 100, range 1–1000) | Name-sorted immediate entries, total entry count, and `next` cursor; no recursive traversal |
280
+ | `workspace_manifest` | Optional `path` (default `package.json`) | Validated package name/version, scripts, dependencies, and devDependencies; does not execute scripts |
281
+
282
+ The environment provider runs only after Runtime authorizes a Tool invocation and
283
+ commits its Effect intent. The factory never constructs an environment or widens its access.
284
+ Its Tool Hook supplies explicit default arguments before permission checks. The state
285
+ reader projects committed feedback; Prefix and state readers perform no filesystem IO.
286
+ File operations and cancellation delegate to Sorbet's `ExecutionEnv`; the Host owns path
287
+ access and Sandbox policy. A direct `NodeExecutionEnv` is unrestricted by itself.
288
+ Missing files, invalid manifests, denied filesystem operations, and cancellation
289
+ propagate as Tool failures through Runtime. Outline limits output entries, not the
290
+ directory listing's IO cost; manifest inspection reads and parses the entire file.
291
+ Pass an outline page's `next` value as `after` to continue through any number of
292
+ entries. Each page reads the current directory: names added before the cursor
293
+ require a fresh listing from the beginning.
294
+
295
+ The fixed Prefix explains inspection, freshness, truncation and treating file content
296
+ as data. The `workspace_inspection` named state contains the last successful feedback's
297
+ fact/Run/Tool-call identities and a compact outline or manifest summary. It is not live
298
+ filesystem truth, permission evidence, or proof of execution: other trusted Hooks may
299
+ edit or replace feedback. Error feedback is ignored. Concurrent calls use the last
300
+ successful feedback in durable Journal order, not callback completion order.
301
+
302
+ The reader uses the Session-bound committed Tool snapshot supplied by Runtime.
303
+ Replacement and reopening rebuild the same progress without executing Tools; another
304
+ Session cannot borrow it. Missing observation capability rejects preparation instead
305
+ of inventing empty state. ContextManager records adopted values and removal transitions;
306
+ physical retries reuse them. No private Map, checkpoint store or subscription is needed.
307
+ See [ADR-0081](../../docs/adr/0081-committed-tool-observation.md). The Host must still
308
+ reinstall this programmatic Entry after restart.
309
+
310
+ For an already opened `plugins` Platform and Host-owned `environment`:
311
+
312
+ ```ts
313
+ import { createWorkspacePlugin } from '@sorbetai/tools-node';
314
+
315
+ const applyWorkspace = createWorkspacePlugin(() => environment);
316
+ await plugins.configure([{ key: 'workspace', apply: applyWorkspace, config: null }]);
317
+ const session = await agent.createSession(sessionInput, { plugins });
318
+ await (await session.start({ prompt: 'Inspect the workspace structure and manifest.' })).result();
319
+ ```
320
+
321
+ Close the borrowing Node Agent before closing `plugins`, then clean up the Host
322
+ environment. Bind the provider to the correct admitted workspace/Run; Session-keyed
323
+ feedback does not select or isolate filesystem environments. The Plugin creates no
324
+ watcher, persistence store, secondary resource scope, or independent runtime. It uses
325
+ native Prefix, state and Tool Hooks. The programmatic factory does not persist an
326
+ installation or create a Service graph.
327
+
328
+ ### Installed Package
329
+
330
+ `createWorkspacePluginPackage()` reads the shipped self-contained JavaScript bundle
331
+ and returns canonical Package bytes. Register them in the Composition authority,
332
+ add an enabled Entry, and construct the loader with exact Host bindings:
333
+
334
+ ```ts
335
+ import {
336
+ createWorkspacePluginPackage,
337
+ createWorkspacePluginHostBindings,
338
+ } from '@sorbetai/tools-node';
339
+ import { NodePluginPackageLoader } from '@sorbetai/plugins/node';
340
+
341
+ const pkg = await createWorkspacePluginPackage();
342
+ // Register pkg and create entryId through the Composition authority before reconciliation.
343
+ const loader = new NodePluginPackageLoader(
344
+ authority,
345
+ createWorkspacePluginHostBindings(pkg.packageId, entryId, () => environment)
346
+ );
347
+ ```
348
+
349
+ Open a [durable Platform](../plugins/COMPOSITION.md#resource-convergence)
350
+ with that loader and authority. It builds the current enabled Desired Entries. On
351
+ reopening, recreate the Host bindings and open a new Platform against the same
352
+ authority. Missing bindings fail their owning Mount. Rebuilding resources does not
353
+ rerun historical Tools; state preparation derives progress from committed facts. The author implementation is shared with
354
+ the programmatic factory; only execution binding differs.
355
+
356
+ Run `pnpm --filter @sorbetai/tools-node test` for integration coverage.
357
+ The Node Agent suite additionally invokes this Plugin against real workspace files,
358
+ verifies denial before environment access, normalized Effect arguments, Session isolation,
359
+ replacement/reopen progress restoration, Prefix disable, and retained historical Effect results.
@@ -0,0 +1,2 @@
1
+ import { A as ok, C as ProcessLifecycle, D as ShellExecOptions, E as ShellEnvironmentBinding, O as err, S as ProcessExited, T as Result, _ as ExecutionErrorCode, a as WorkerMessage, b as FileExecutionOptions, c as executeCommand, d as CommandOutput, f as EnvironmentInvocation, g as ExecutionError, h as ExecutionEnvironmentSource, i as WorkerControl, k as getOrThrow, l as NodeExecutionEnv, m as ExecutionEnvironmentProvider, n as runSupervisedCommand, o as ExecutionEnvironment, p as ExecutionEnv, r as WorkerCommand, s as settleAbandonedProcess, t as executeProcessWorker, u as ProcessCapacity, v as FileError, w as ProcessStarted, x as FileInfo, y as FileErrorCode } from "../index-B3RbI0Wh.js";
2
+ export { CommandOutput, EnvironmentInvocation, ExecutionEnv, ExecutionEnvironment, ExecutionEnvironmentProvider, ExecutionEnvironmentSource, ExecutionError, ExecutionErrorCode, FileError, FileErrorCode, FileExecutionOptions, FileInfo, NodeExecutionEnv, ProcessCapacity, ProcessExited, ProcessLifecycle, ProcessStarted, Result, ShellEnvironmentBinding, ShellExecOptions, WorkerCommand, WorkerControl, WorkerMessage, err, executeCommand, executeProcessWorker, getOrThrow, ok, runSupervisedCommand, settleAbandonedProcess };
@@ -0,0 +1,4 @@
1
+ import { a as executeProcessWorker, c as FileError, d as ok, i as executeCommand, l as err, n as ExecutionEnvironment, o as settleAbandonedProcess, r as NodeExecutionEnv, s as ExecutionError, t as ProcessCapacity, u as getOrThrow } from "../environment-CtRyPVb9.js";
2
+ import { t as runSupervisedCommand } from "../supervised-command-DNcHAKrD.js";
3
+
4
+ export { ExecutionEnvironment, ExecutionError, FileError, NodeExecutionEnv, ProcessCapacity, err, executeCommand, executeProcessWorker, getOrThrow, ok, runSupervisedCommand, settleAbandonedProcess };
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,46 @@
1
+ import { t as runSupervisedCommand } from "../supervised-command-DNcHAKrD.js";
2
+
3
+ //#region src/environment/process-worker.ts
4
+ const controller = new AbortController();
5
+ let accepted = false;
6
+ const outputAcks = /* @__PURE__ */ new Map();
7
+ process.on("disconnect", () => {
8
+ if (!accepted) process.exitCode = 0;
9
+ controller.abort();
10
+ for (const resolve of outputAcks.values()) resolve();
11
+ outputAcks.clear();
12
+ });
13
+ process.on("message", (message) => {
14
+ if (message === "cancel") controller.abort();
15
+ else if (message.kind === "output-ack") {
16
+ outputAcks.get(message.sequence)?.();
17
+ outputAcks.delete(message.sequence);
18
+ } else if (!accepted) {
19
+ accepted = true;
20
+ runSupervisedCommand(message, controller, send).finally(() => {
21
+ if (process.connected) process.disconnect();
22
+ });
23
+ }
24
+ });
25
+ send({ kind: "ready" });
26
+ function send(message) {
27
+ return new Promise((resolve) => {
28
+ if (!process.connected || process.send === void 0) {
29
+ resolve();
30
+ return;
31
+ }
32
+ if (message.kind === "output") {
33
+ outputAcks.set(message.sequence, resolve);
34
+ process.send(message, (error) => {
35
+ if (error) {
36
+ outputAcks.delete(message.sequence);
37
+ resolve();
38
+ }
39
+ });
40
+ } else process.send(message, () => resolve());
41
+ });
42
+ }
43
+
44
+ //#endregion
45
+ export { };
46
+ //# sourceMappingURL=process-worker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process-worker.js","names":[],"sources":["../../src/environment/process-worker.ts"],"sourcesContent":["import { runSupervisedCommand } from './supervised-command.js';\nimport type { WorkerCommand, WorkerMessage, WorkerControl } from './process-protocol.js';\n\nconst controller = new AbortController();\nlet accepted = false;\nconst outputAcks = new Map<number, () => void>();\nprocess.on('disconnect', () => {\n if (!accepted) process.exitCode = 0;\n controller.abort();\n for (const resolve of outputAcks.values()) resolve();\n outputAcks.clear();\n});\nprocess.on('message', (message: WorkerCommand | WorkerControl) => {\n if (message === 'cancel') controller.abort();\n else if (message.kind === 'output-ack') {\n outputAcks.get(message.sequence)?.();\n outputAcks.delete(message.sequence);\n } else if (!accepted) {\n accepted = true;\n void runSupervisedCommand(message, controller, send).finally(() => {\n if (process.connected) process.disconnect();\n });\n }\n});\n\nvoid send({ kind: 'ready' });\n\nfunction send(message: WorkerMessage): Promise<void> {\n return new Promise((resolve) => {\n if (!process.connected || process.send === undefined) {\n resolve();\n return;\n }\n if (message.kind === 'output') {\n outputAcks.set(message.sequence, resolve);\n process.send(message, (error) => {\n if (error) {\n outputAcks.delete(message.sequence);\n resolve();\n }\n });\n } else process.send(message, () => resolve());\n });\n}\n"],"mappings":";;;AAGA,MAAM,aAAa,IAAI,iBAAiB;AACxC,IAAI,WAAW;AACf,MAAM,6BAAa,IAAI,KAAyB;AAChD,QAAQ,GAAG,oBAAoB;AAC7B,KAAI,CAAC,SAAU,SAAQ,WAAW;AAClC,YAAW,OAAO;AAClB,MAAK,MAAM,WAAW,WAAW,QAAQ,CAAE,UAAS;AACpD,YAAW,OAAO;EAClB;AACF,QAAQ,GAAG,YAAY,YAA2C;AAChE,KAAI,YAAY,SAAU,YAAW,OAAO;UACnC,QAAQ,SAAS,cAAc;AACtC,aAAW,IAAI,QAAQ,SAAS,IAAI;AACpC,aAAW,OAAO,QAAQ,SAAS;YAC1B,CAAC,UAAU;AACpB,aAAW;AACX,EAAK,qBAAqB,SAAS,YAAY,KAAK,CAAC,cAAc;AACjE,OAAI,QAAQ,UAAW,SAAQ,YAAY;IAC3C;;EAEJ;AAEG,KAAK,EAAE,MAAM,SAAS,CAAC;AAE5B,SAAS,KAAK,SAAuC;AACnD,QAAO,IAAI,SAAS,YAAY;AAC9B,MAAI,CAAC,QAAQ,aAAa,QAAQ,SAAS,QAAW;AACpD,YAAS;AACT;;AAEF,MAAI,QAAQ,SAAS,UAAU;AAC7B,cAAW,IAAI,QAAQ,UAAU,QAAQ;AACzC,WAAQ,KAAK,UAAU,UAAU;AAC/B,QAAI,OAAO;AACT,gBAAW,OAAO,QAAQ,SAAS;AACnC,cAAS;;KAEX;QACG,SAAQ,KAAK,eAAe,SAAS,CAAC;GAC7C"}