@plimsollmark/client 0.19.0 → 0.21.0

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/README.md CHANGED
@@ -1,9 +1,10 @@
1
1
  # @plimsollmark/client
2
2
 
3
- A TypeScript client for `plimsolld`, plus two add-ons that give a chat agent an
4
- `executeCode` tool backed by plimsoll: one for [Trigger.dev](https://trigger.dev) chat
5
- agents and one for [Mastra](https://mastra.ai) agents. Both add-ons sit on the same
6
- client and the same per-conversation sandbox layer, so they behave the same way.
3
+ A TypeScript client for `plimsolld`, plus three add-ons that give an agent an
4
+ `executeCode` tool backed by plimsoll: one for the [Vercel AI SDK](https://ai-sdk.dev),
5
+ one for [Trigger.dev](https://trigger.dev) chat agents and one for
6
+ [Mastra](https://mastra.ai) agents. All three sit on the same client and the same
7
+ per-conversation sandbox layer, so they behave the same way.
7
8
 
8
9
  The client has no runtime dependencies (Node >= 22.18). It speaks Connect's JSON
9
10
  protocol over `fetch` and keeps the promises the Go client keeps:
@@ -17,7 +18,11 @@ protocol over `fetch` and keeps the promises the Go client keeps:
17
18
  - in a **session** it tracks the chain of records, so a call made by anyone else who holds
18
19
  the session ID is caught at the next call, and at close;
19
20
  - an error says whether anything ran: `notDispatched` is set only when the daemon stated
20
- that nothing did, and only then is a retry safe.
21
+ that nothing did, and only then is a retry safe;
22
+ - every request carries a fresh `Plimsoll-Request-Id` and an answer counts only if it
23
+ carries the ID back: one that does not (another request's answer, served by an
24
+ intermediary, or a daemon older than protocol 3) has `answerNotBound` set and no
25
+ `notDispatched`, and a success of that kind is a `data_loss` error.
21
26
 
22
27
  The tier it reports is configuration and provider evidence, never runtime attestation
23
28
  (the README's provider table says what each tier means).
@@ -30,7 +35,19 @@ npm install @plimsollmark/client
30
35
 
31
36
  The package's version is the plimsoll release it ships in: version X.Y.Z was built and
32
37
  tested against plimsolld vX.Y.Z. The add-ons need their framework installed beside it:
33
- `@trigger.dev/sdk`, `ai` and `zod` for `/trigger`, `@mastra/core` and `zod` for `/mastra`.
38
+ `ai` and `zod` for `/ai-sdk`, `@trigger.dev/sdk`, `ai` and `zod` for `/trigger`, `@mastra/core` and `zod` for `/mastra`.
39
+
40
+ This package has no dependencies, so it brings nothing into your installation; the
41
+ frameworks do. One worth knowing about: `@trigger.dev/sdk` 4.7 pins `socket.io-client`
42
+ 4.7.5, whose `engine.io-client` resolves a `ws` affected by two advisories fixed in 8.21.0
43
+ ([GHSA-58qx-3vcg-4xpx and GHSA-96hv-2xvq-fx4p, EXTERNAL · advisory ↗](https://github.com/advisories/GHSA-96hv-2xvq-fx4p)).
44
+ npm applies `overrides` only from your application's own `package.json`, so this
45
+ package's override cannot reach your installation. Until Trigger.dev moves, add one
46
+ there, as this repository's tests do:
47
+
48
+ ```json
49
+ "overrides": { "engine.io-client": "^6.6.7" }
50
+ ```
34
51
 
35
52
  ## The client
36
53
 
@@ -43,7 +60,7 @@ const info = await plimsoll.describe(); // provider, tier, supportsSessions, ...
43
60
  const r = await plimsoll.runJavaScript("console.log(6 * 7)", { minimumIsolation: "container", timeoutMs: 10_000 });
44
61
  r.stdout; // "42\n"; a non-zero r.exitCode is a normal result, not an error
45
62
 
46
- const s = await plimsoll.openSession({ minimumIsolation: "container" }); // docker or openshell
63
+ const s = await plimsoll.openSession({ minimumIsolation: "container" }); // docker, openshell or e2b
47
64
  await s.runProject({ files: [{ path: "a.js", content: "console.log(1)" }], steps: ["node a.js"] });
48
65
  await s.runJavaScript("console.log(require('fs').readdirSync('.'))");
49
66
  // A cell runs in an interpreter the session keeps alive: what it defines is there next time.
@@ -59,6 +76,11 @@ is 0 when the code ran, 1 when it raised and 124 at the deadline. Python needs `
59
76
  the daemon's image (`plimsoll/sandbox-python` has it, with NumPy and SciPy);
60
77
  `describe()` lists the languages the daemon proved on `environments.project.languages`.
61
78
 
79
+ `close()` sends one `CloseSession` however many times it is called, and every later call
80
+ gets the first one's summary or error: the daemon forgets a session at its first close and
81
+ would answer a second with NotFound. A close refused not dispatched (aborted before it was
82
+ sent, say) closed nothing, so a later `close()` tries again.
83
+
62
84
  Cleartext HTTP is accepted only to a loopback address unless you pass `insecureHttp: true`.
63
85
 
64
86
  ## `executeCode` for an agent: `CodeSandboxes`
@@ -85,20 +107,63 @@ from your own authenticated user and conversation (or job) IDs, never from a str
85
107
  or the model supplies, or give each customer a plimsoll credential of their own
86
108
  ([who may share a session](https://github.com/plimsollmark/plimsoll/blob/main/docs/sessions.md#who-may-share-a-session)).
87
109
 
88
- `CodeSandboxes` keeps one sandbox per conversation key. With `sessions: "auto"` (the
89
- default) it asks the daemon once whether it keeps sessions:
110
+ A key is a `SandboxKey`: either a string (the Trigger.dev add-on passes its run ID) or
111
+ `{ owner, conversation }`, the user a conversation belongs to and the conversation's ID
112
+ (the AI SDK add-on passes `{ owner: userId, conversation: conversationId }`, the Mastra
113
+ add-on `{ owner: resourceId, conversation: threadId }`). The parts are encoded as a JSON
114
+ array, never joined with a separator, so no user's IDs can spell another user's key or a
115
+ string key. The owner is what `maxSessionsPerOwner` counts (below).
116
+
117
+ **The floor defaults to `kernel`.** `minimumIsolation` is the weakest isolation tier a call
118
+ accepts: the daemon refuses, before anything runs, a call whose floor its tier does not meet,
119
+ and the client checks the tier stated on the answer. `CodeSandboxes`, and so every add-on
120
+ on it, defaults to `kernel` (docker running gVisor's `runsc` runtime, which the daemon's
121
+ startup checks verified; the stronger `vm` tier also meets it) because it is the weakest
122
+ tier this project treats as fit for code you did not write. An ordinary docker daemon (runc) is the `container` tier and refuses every
123
+ call under the default: set `minimumIsolation: "container"` for local development on your
124
+ own code. Set `"vm"` when the threat model needs a virtual-machine boundary; of today's VM
125
+ providers `e2b` keeps sessions (a suspend ends its interpreters, so the next call reports
126
+ `freshInterpreter`) and `dockercloud` keeps none, so every call there runs fresh.
90
127
 
91
- - **It does** (`docker` with a project image, or `openshell`, with `SANDBOX_MAX_SESSIONS`
92
- set): a key holds one plimsoll session, and every call is a cell in that session's
128
+ `CodeSandboxes` keeps one sandbox per conversation key. With `sessions: "auto"` (the
129
+ default) it asks the daemon whether it keeps sessions (`describe()`), keeps the answer, and
130
+ asks again after a call refused for a reason that says the daemon may have changed since
131
+ (`notDispatched` `unsupported`, `environment`, `protocol` or `isolation`: a restart with
132
+ sessions turned on or off, another image or tier), never after a `capacity` or `request`
133
+ refusal:
134
+
135
+ - **It does** (`docker` with a project image, `openshell` or `e2b`, with
136
+ `SANDBOX_MAX_SESSIONS` set; on `e2b` a suspend ends the interpreters, so the next call
137
+ reports `freshInterpreter`): a key holds one plimsoll session, and every call is a cell in that session's
93
138
  interpreter. Variables, imports and loaded data from earlier calls are still defined, and
94
139
  files stay in the working directory. On one laptop on 2026-10-01, a call that used an
95
140
  80 MB array an earlier call had loaded took 10 ms on OpenShell and 23 ms on docker
96
141
  under gVisor (medians), against 939 ms and 714 ms for a fresh sandbox that rebuilt it.
97
- - **It does not** (`e2b`, `dockercloud`, `wasm`, or `sessions: "never"`): every call runs in
142
+ - **It does not** (`dockercloud`, `wasm`, a daemon with sessions off, or `sessions: "never"`): every call runs in
98
143
  a fresh sandbox, as a small project whose runner prints the last expression the same way,
99
144
  and nothing persists. `wasm` runs no projects, so there a call is a JavaScript snippet
100
145
  printing its last value; Python and files are refused before anything is sent.
101
146
 
147
+ A fresh project run (every call on a daemon without sessions, and a call without a key on
148
+ any daemon) whose result has no step report has no exit code to give: its outcome, such as
149
+ `timed_out` or `protocol_error`, says what ended the run but not whether the code had
150
+ started. So the tool throws instead of inventing an exit code: a `PlimsollError` (code
151
+ `unknown`) with no `notDispatched` mark, because the code may have run, and the checked
152
+ result on `PlimsollError.result`. Nothing retries it, since running it again could repeat
153
+ what it did.
154
+
155
+ A framework hands its model only an error's message, so every error the tool throws is a
156
+ `PlimsollError` whose message starts with whether the code ran: `Nothing ran (<reason>): `
157
+ when it carries a `notDispatched` mark (a refusal, a cap, a cancel before sending), and `The
158
+ code may have run, and there is no checked answer for it: ` otherwise. Where the call
159
+ failed decides the mark, not who raised the error: everything before the code is sent
160
+ (reading the key, building the client, the Describe, opening the sandbox) runs nothing, so
161
+ a failure there is marked even when the daemon could not mark it (unreachable, a proxy's
162
+ 503, a dropped connection, the client's own check of the session it opened), with reason
163
+ `environment` unless the daemon gave one. An error of another class there (a key or owner
164
+ resolver of the app's that throws) is wrapped the same way. From the moment the code may
165
+ have been sent, an unmarked error stays unmarked.
166
+
102
167
  The tool's output says which: `stateKept` (this call's interpreter was still running when
103
168
  it answered, so what it defined can be there for the next call; false when no interpreter is
104
169
  kept, and when the call's deadline or the sandbox's end ended it) and `filesPersist` (the same
@@ -108,12 +173,62 @@ its limit. So the output also says what is new, rather than what was lost, becau
108
173
  only the sandbox knows: `freshInterpreter` whenever the call's interpreter had just started
109
174
  (the first call in a language, a deadline, a crash), so nothing earlier calls defined
110
175
  exists, and `freshSandbox` whenever the call is the first answered one in a newly opened
111
- sandbox, so no earlier file is there either. That covers a sandbox that `dispose` or the
112
- idle close let go, one that ended by itself (its lifetime, its disk budget), and a
113
- conversation resumed in another process, which this instance cannot tell from a first
114
- call. A call without a key (no thread, no run) always runs fresh: one sandbox shared
115
- across conversations would show one user another's files. A language the daemon's image
116
- cannot run is refused before anything is sent.
176
+ sandbox, so no earlier file is there either. That covers a sandbox that `dispose`, the
177
+ idle close or a session cap (below) let go, one that ended by itself (its lifetime, its disk
178
+ budget), and a conversation resumed in another process, which this instance cannot tell
179
+ from a first call. A call without a key (no thread, no run) always runs fresh: one sandbox
180
+ shared across conversations would show one user another's files. A language the daemon's
181
+ image cannot run is refused before anything is sent. Output past `maxOutputChars` (each of
182
+ stdout and stderr) is cut and marked truncated, and a cut never ends on the first half of a
183
+ surrogate pair (the two UTF-16 code units that encode one character such as an emoji): a
184
+ lone half is not valid Unicode, and a strict model provider can refuse the request that
185
+ carries it back.
186
+
187
+ **Every kept sandbox holds one of the daemon's session slots** (`SANDBOX_MAX_SESSIONS`), and
188
+ every user of an app that shares one plimsoll token draws on the same slots. Two caps keep
189
+ one user, or one app, from holding them all:
190
+
191
+ - `maxSessionsPerOwner` (default 3; 0 for no cap): the sandboxes one owner may hold in this
192
+ instance. When the owner already holds that many, opening another of the owner's
193
+ conversations first closes the owner's least recently used sandbox with no call in flight (least recently used: the one whose last call
194
+ started or ended longest ago), and that conversation's next call opens a new sandbox and
195
+ reports `freshSandbox: true`. Three, because a person rarely works in more than a few
196
+ conversations at once, and the closed conversation loses its variables and files, never
197
+ an answer. If every one of the owner's sandboxes has a call in flight, the new
198
+ conversation's call is refused before anything opens (`PlimsollError` code
199
+ `resource_exhausted`, `notDispatched: "capacity"`). A string key names no owner and is not
200
+ counted here.
201
+ - `maxSessions` (default 0, no cap of its own): the same across all owners and string keys.
202
+ Set it to this app's share of the daemon's `SANDBOX_MAX_SESSIONS`, a number only the
203
+ daemon's operator knows.
204
+
205
+ A `warm` is a guess (Trigger.dev's recipe warms in every new run's `onTurnStart`, a chat the
206
+ user opened and never typed in included), so it never closes a sandbox to make room: when
207
+ either cap is reached it does nothing, and the conversation's first call opens its sandbox,
208
+ closing the least recently used idle one as any call does. The daemon closes a session no
209
+ request has named by its first idle timeout (`SANDBOX_SESSION_IDLE`, default 5 minutes), since
210
+ that is what a session whose open answer was lost looks like; a warmed sandbox its
211
+ conversation does not use by then is closed that way, and the first call is refused with the
212
+ end `unclaimed` (not dispatched) and runs once more in a new sandbox, saying
213
+ `freshSandbox: true`.
214
+
215
+ Both caps count what one process holds. A host that runs many processes (serverless
216
+ functions, several Trigger.dev workers) keeps one count per process, so set the daemon's
217
+ `SANDBOX_MAX_SESSIONS_PER_OWNER`, which counts them all: every open names the key's owner
218
+ to the daemon (`openSession({ owner })`, sent as a hex HMAC-SHA256 of the owner under a key derived from
219
+ the client's token (SHA-256 of a fixed prefix and the token), so the ID itself never leaves the process and the daemon, which stores
220
+ only the token's SHA-256, cannot test a guessed one). Omit `owner` for none: an empty
221
+ string is refused before anything is sent (`invalid_argument`, `notDispatched:
222
+ "request"`), because sent as no owner it would escape the cap. At that cap the daemon closes the
223
+ owner's least recently used session with no call in progress; its next call is refused as
224
+ `replaced` (not dispatched), and `CodeSandboxes` runs it once more in a new sandbox, saying
225
+ `freshSandbox: true`. The daemon cannot tell a warm from a call's open, so a warm that opens
226
+ counts there like any open, and at that cap closes the user's least recently used session,
227
+ which may be a conversation in use in another process. `SANDBOX_MAX_SESSIONS` and `SANDBOX_MAX_SESSIONS_PER_CALLER` still
228
+ bound the daemon and each caller token. A daemon at either of those refuses the
229
+ open (not dispatched, reason `capacity`), and the client does not close sandboxes in
230
+ response, because the daemon gives the same refusal for a caller over its rate limit, which
231
+ a close would not help.
117
232
 
118
233
  Each tool answer also includes `isolation` and `recordSha256`. The client checks
119
234
  the run record before returning, then gives the tool the checked record's SHA-256.
@@ -124,14 +239,22 @@ for the three properties together.
124
239
  Closing a sandbox checks the daemon's count of calls against the chain the client saw; a
125
240
  mismatch means the daemon counted a call the client has no answer for (one that ended in an
126
241
  abort, a timeout, a dropped connection or a proxy's error), or, if none did, that someone
127
- else held the session ID. It goes to `onCloseError` (by default a warning) rather than being
128
- dropped at teardown. A call that may have run but ended in an error comes with its record
242
+ else held the session ID. It goes to `onCloseError(key, err)` rather than being dropped at
243
+ teardown; `key` is the `SandboxKey` as the add-on passed it (the `{ owner, conversation }`
244
+ object for a pair). Without `onCloseError`, a `console.warn` names the key only by the first
245
+ 12 hex digits of its SHA-256 fingerprint, enough to tell one conversation's lines from
246
+ another's, never by its IDs, because a key can hold a user's ID (an email address, in some
247
+ apps). An `onCloseError` that throws, or returns a promise that rejects, is logged the same
248
+ way: an app's reporting never stops a close, or the open that waited for one to make room. A call that may have run but ended in an error comes with its record
129
249
  (`PlimsollError.unanswered`, a version 3 record); the session checks it, hands it back as
130
250
  `PlimsollError.record`, keeps it in its chain and goes on, and so does the conversation's
131
251
  sandbox. A call whose answer never arrived carries none, so the client sends nothing more
132
252
  on that session (`Session.stopped` says why), and the conversation's next call opens a new
133
253
  sandbox and reports `freshSandbox: true`. A session call aborted while it waits its turn
134
- was never sent: it is refused, marked not dispatched, and the session goes on. The
254
+ was never sent: it is refused, marked not dispatched, and the session goes on. A call
255
+ aborted before or while its sandbox opens sends nothing either (`PlimsollError` code
256
+ `canceled`, `notDispatched: "request"`), and a sandbox it was opening that no other call is
257
+ using or has used is closed as soon as it opens. The
135
258
  `.plimsoll/` directory is the runner's: a file under it is refused before anything is
136
259
  sent.
137
260
 
@@ -139,6 +262,18 @@ The session ID is a capability. It lives in the client's memory and nowhere else
139
262
  a log line, not in a record, not in Trigger.dev's `chat.local` (which is serialized into
140
263
  subtask metadata). Records carry its SHA-256.
141
264
 
265
+ ## Vercel AI SDK
266
+
267
+ `@plimsollmark/client/ai-sdk` exports `plimsollCodeTools`. Its `executeCode` tool
268
+ runs fresh; `forConversation({userId, conversationId})` binds a tool to
269
+ application-owned identity and the shared sandbox manager, with the user as the key's
270
+ owner. It accepts Python or JavaScript plus text files and returns checked results. The
271
+ default minimum isolation is kernel, as for every add-on on `CodeSandboxes`; use a
272
+ verified gVisor or VM daemon for hostile code.
273
+
274
+ See [usage, lifecycle and the no-spend local smoke check, EXTERNAL · official docs ↗](https://github.com/plimsollmark/plimsoll/blob/main/docs/ai-sdk.md).
275
+ This source add-on needs the optional `ai` and `zod` peer packages.
276
+
142
277
  ## Trigger.dev
143
278
 
144
279
  The add-on follows Trigger.dev's own
@@ -168,16 +303,27 @@ export const codeChat = chat.agent({
168
303
 
169
304
  The full example, with a test that drives real turns through Trigger.dev's `mockChatAgent`:
170
305
  [examples/trigger-chat](https://github.com/plimsollmark/plimsoll/tree/main/examples/trigger-chat/).
171
- Its source uses a `container` floor for local development. The
306
+ Its source sets a `container` floor for local development. The
172
307
  [deployable sister starter](https://github.com/plimsollmark/plimsoll-trigger-starter)
173
- uses `kernel` by default. Hostile production code needs the verified kernel or
174
- VM tier; choose `vm` when the threat model requires a VM boundary, accepting
175
- that current VM providers cannot keep cells.
308
+ uses `kernel`, the add-on's default (the snippet above writes it out). Hostile
309
+ production code needs the verified kernel or VM tier; choose `vm` when the threat
310
+ model requires a VM boundary: `e2b` keeps cells until a suspend, and `dockercloud` runs
311
+ every call fresh.
312
+
313
+ The key is the run ID. To cap each user's sandboxes, name the run's user in the warm,
314
+ as your server authenticated it: `sandbox.warm(runId, userId)`. Never take it from
315
+ `clientData`, which the browser sets: a user who could choose it could close another
316
+ user's sandboxes. The key is then the user and the run, `maxSessionsPerOwner` counts
317
+ the worker's sandboxes per user, and a daemon with `SANDBOX_MAX_SESSIONS_PER_OWNER`
318
+ counts them across every worker of the deployment. The user stays in the worker's
319
+ memory, never in `chat.local`. Without it no per-user cap applies; `maxSessions`, when
320
+ set, caps the sandboxes one worker holds.
176
321
 
177
322
  What the hooks cannot cover: a run that dies without reaching `onChatSuspend` or
178
323
  `onComplete` (its process killed, a crash) leaves its sandbox open until the add-on's idle
179
324
  close (`idleCloseMs`, default 10 minutes) or, if the process is gone too, the daemon's own
180
- idle suspend and session lifetime (`SANDBOX_SESSION_IDLE`, `SANDBOX_SESSION_LIFETIME`). A
325
+ idle suspend and session lifetime (`SANDBOX_SESSION_IDLE`, `SANDBOX_SESSION_LIFETIME`); a
326
+ sandbox no call ever used is closed at the daemon's first idle timeout. A
181
327
  worker shutting down can close every sandbox it holds with `sandbox.sandboxes.disposeAll()`.
182
328
 
183
329
  ## Mastra
@@ -195,13 +341,28 @@ export const analyst = new Agent({ id: "analyst", name: "analyst", instructions:
195
341
  // When a conversation ends: await dispose(threadId, resourceId);
196
342
  ```
197
343
 
198
- The sandbox is keyed by Mastra's thread and resource (a thread ID is unique only within
199
- its user). A call without a `resourceId` runs in a fresh sandbox every time: under an empty
200
- resource, every user without one would share a sandbox with anyone whose thread ID
201
- collided. Set the resource from your authenticated user, not from anything the user
202
- typed. Mastra has no hook for "this conversation is going to sleep", so a thread's
203
- sandbox closes on `dispose(threadId, resourceId)`, or after `idleCloseMs` (default 10
204
- minutes) without a call.
344
+ No floor is set here, so the tool requires `kernel`; for local development against an
345
+ ordinary docker daemon, pass `minimumIsolation: "container"`.
346
+
347
+ Recorded calls through this tool, two users and a disposed thread included, replay on its
348
+ integration page: [see a run, INTERNAL · plimsoll site →](https://plimsollmark.github.io/plimsoll/integrations/mastra/index.html).
349
+
350
+ The sandbox is keyed by Mastra's thread and resource, `{ owner: resourceId, conversation:
351
+ threadId }` (a thread ID is unique only within its user). A call without a `resourceId`
352
+ runs in a fresh sandbox every time: under an empty resource, every user without one would
353
+ share a sandbox with anyone whose thread ID collided. Set the resource from your
354
+ authenticated user, not from anything the user typed. Mastra has no hook for "this
355
+ conversation is going to sleep", so a thread's sandbox closes on
356
+ `dispose(threadId, resourceId)`, after `idleCloseMs` (default 10 minutes) without a call,
357
+ or when the same user opens a thread past `maxSessionsPerOwner` (default 3) and this
358
+ thread's sandbox is that user's least recently used one with no call in flight.
359
+
360
+ In an agent network, Mastra fills a missing `resourceId` with the network's name (and the
361
+ thread with the run ID), so every user of the network would count as one owner and close
362
+ each other's sandboxes. Pass `owner`, the user from your own authentication (for example a
363
+ value your server put in Mastra's `requestContext`):
364
+ `plimsollExecuteCode({ ..., owner: (ctx) => ctx.requestContext?.get("userId") })`, and the
365
+ same owner to `dispose(threadId, resourceId, owner)`. The caps then count that owner.
205
366
 
206
367
  ## Tests
207
368
 
@@ -210,8 +371,9 @@ runs, an in-memory session provider for sessions and cells, and a provider that
210
371
  project with the plan it received, for the project a fresh call sends) and runs three
211
372
  suites against them: the
212
373
  client's (needs only node), the add-ons' (needs `npm install` here), and the Trigger.dev
213
- example's (needs `npm install` in `examples/trigger-chat`; it waits out Trigger.dev's
214
- 30-second idle window to prove the suspend closes the sandbox). An ordinary Go test
374
+ example's (needs `npm install` in `examples/trigger-chat`; it waits out the example's
375
+ 3-second idle window, Trigger.dev's default being 30 seconds, to prove the suspend closes
376
+ the sandbox). An ordinary Go test
215
377
  skips a suite whose runtime or dependencies are absent. CI runs `make clients-suite`,
216
378
  which installs both npm lockfiles and sets `PLIMSOLL_REQUIRE_CLIENTS=1`, so a missing
217
379
  prerequisite or skipped Go test fails. The client's digests are also checked against the
@@ -0,0 +1,24 @@
1
+ import { type Tool } from "ai";
2
+ import { CodeSandboxes, type CodeSandboxesOptions, type ExecuteCodeOutput } from "./sandboxes.ts";
3
+ import { type ExecuteCodeToolInput } from "./tool.ts";
4
+ /** Application-owned identity, never fields of a model-generated tool call. */
5
+ export type ConversationScope = {
6
+ userId: string;
7
+ conversationId: string;
8
+ };
9
+ export type PlimsollCodeTool = Tool<ExecuteCodeToolInput, ExecuteCodeOutput>;
10
+ export type PlimsollCodeTools = {
11
+ executeCode: PlimsollCodeTool;
12
+ forConversation: (scope: ConversationScope) => PlimsollCodeTool;
13
+ warm: (scope: ConversationScope) => void;
14
+ dispose: (scope: ConversationScope) => Promise<void>;
15
+ disposeAll: () => Promise<void>;
16
+ sandboxes: CodeSandboxes;
17
+ };
18
+ /**
19
+ * Create once per process and bind tools to authenticated conversation identities.
20
+ * The unscoped executeCode always runs fresh. A scoped tool keeps interpreter state
21
+ * only when the daemon supports sessions, and reports that capability in each result.
22
+ * Default floor: verified kernel isolation, or a stronger VM boundary.
23
+ */
24
+ export declare function plimsollCodeTools(opts: CodeSandboxesOptions): PlimsollCodeTools;
package/dist/ai-sdk.js ADDED
@@ -0,0 +1,47 @@
1
+ // Vercel AI SDK tools over the shared checked client and sandbox manager.
2
+ // Only this optional entry point imports AI SDK and its schema dependency.
3
+ import { tool } from "ai";
4
+ import { PlimsollError } from "./errors.js";
5
+ import { CodeSandboxes } from "./sandboxes.js";
6
+ import { executeCodeDescription, executeCodeInput } from "./tool.js";
7
+ function scopeKey(scope) {
8
+ if (!scope || typeof scope.userId !== "string" || !scope.userId || typeof scope.conversationId !== "string" || !scope.conversationId) {
9
+ throw new PlimsollError("invalid_argument", "plimsoll: a conversation requires nonempty userId and conversationId from the application", {
10
+ notDispatched: "request",
11
+ });
12
+ }
13
+ // The user is the owner the sandboxes' per-user cap counts.
14
+ return { owner: scope.userId, conversation: scope.conversationId };
15
+ }
16
+ /**
17
+ * Create once per process and bind tools to authenticated conversation identities.
18
+ * The unscoped executeCode always runs fresh. A scoped tool keeps interpreter state
19
+ * only when the daemon supports sessions, and reports that capability in each result.
20
+ * Default floor: verified kernel isolation, or a stronger VM boundary.
21
+ */
22
+ export function plimsollCodeTools(opts) {
23
+ const sandboxes = new CodeSandboxes(opts);
24
+ const makeTool = (key) => {
25
+ const scope = key === undefined || opts.sessions === "never" ? "fresh" : "conversation";
26
+ return tool({
27
+ description: (scope === "conversation"
28
+ ? "State is kept only if the daemon keeps sessions; otherwise every call runs fresh. "
29
+ : "") + executeCodeDescription(sandboxes.languages, scope),
30
+ inputSchema: executeCodeInput(sandboxes.languages),
31
+ execute: async (input, { abortSignal }) => sandboxes.run(key, input, abortSignal),
32
+ });
33
+ };
34
+ return {
35
+ /** No conversation identity: no retained files or interpreter between calls. */
36
+ executeCode: makeTool(),
37
+ /** Bind to IDs read by the application from its authenticated request or session. */
38
+ forConversation: (scope) => makeTool(scopeKey(scope)),
39
+ /** Begin opening a supported session; subsequent execution waits for readiness. */
40
+ warm: (scope) => sandboxes.warm(scopeKey(scope)),
41
+ /** Close the conversation's sandbox when the application ends it. */
42
+ dispose: (scope) => sandboxes.dispose(scopeKey(scope)),
43
+ /** Close every held sandbox, for example during application shutdown. */
44
+ disposeAll: () => sandboxes.disposeAll(),
45
+ sandboxes,
46
+ };
47
+ }
package/dist/client.d.ts CHANGED
@@ -2,7 +2,7 @@ import { type RunRecord } from "./record.ts";
2
2
  import { type SessionEnd } from "./errors.ts";
3
3
  import type { WireCellRun, WireEnvelope, WireOpenSessionResponse, WireSoftwareRule } from "./wire.ts";
4
4
  /** The wire protocol number this client speaks (protocol.Number in Go). */
5
- export declare const PROTOCOL = 2;
5
+ export declare const PROTOCOL = 3;
6
6
  /** How strong the boundary is, weakest first. */
7
7
  export type Isolation = "none" | "process" | "container" | "kernel" | "vm";
8
8
  /** Whether a tier the daemon reported meets a floor. An unknown tier meets nothing. */
@@ -159,6 +159,13 @@ export type Info = {
159
159
  sessionIdleTimeoutMs: number;
160
160
  /** Where a session's calls run (on docker the project image), stated with supportsSessions. */
161
161
  sessionEnvironment: PayloadEnvironment;
162
+ /**
163
+ * The daemon's caps on this caller's sessions and on one owner's of them
164
+ * (openSession's owner), 0 when there is none. An app that relies on the per-owner
165
+ * cap across its processes checks maxSessionsPerOwner.
166
+ */
167
+ maxSessionsPerCaller: number;
168
+ maxSessionsPerOwner: number;
162
169
  environments: {
163
170
  javascript: PayloadEnvironment;
164
171
  project: PayloadEnvironment;
@@ -185,8 +192,28 @@ export type SessionOptions = {
185
192
  * language the daemon states still runs.
186
193
  */
187
194
  languages?: Language[];
195
+ /**
196
+ * The end user the session is for (an account ID, an email), so a daemon with a
197
+ * per-owner cap (SANDBOX_MAX_SESSIONS_PER_OWNER) keeps each user to it across every
198
+ * process of the app: at the cap it closes that user's least recently used session
199
+ * with no call in progress. It never leaves this process: the daemon gets a digest
200
+ * keyed by this client's token (ownerDigest). Omit it for none; an empty string is
201
+ * refused before anything is sent.
202
+ */
203
+ owner?: string;
188
204
  signal?: AbortSignal;
189
205
  };
206
+ /**
207
+ * What an owner is sent as: hex(HMAC-SHA256(key = SHA-256("plimsoll session owner key
208
+ * v2\n" + the client's token), message = "plimsoll session owner v2\n" + owner)), the
209
+ * same in every official client, so the processes of one app agree on a user. The
210
+ * daemon stores only a token's SHA-256, so it cannot test a guessed name against a
211
+ * digest; without a token anyone can. The key is derived, not the token itself: HMAC
212
+ * replaces a key longer than 64 bytes with its SHA-256, which for a long imported
213
+ * token is exactly the token_sha256 the clients file holds.
214
+ * @internal
215
+ */
216
+ export declare function ownerDigest(token: string | undefined, owner: string): string;
190
217
  export type SessionSummary = {
191
218
  session: string;
192
219
  calls: bigint;
@@ -290,7 +317,12 @@ export declare class Session {
290
317
  runCell(req: CellRequest, opts?: RunOptions): Promise<CellResult>;
291
318
  /**
292
319
  * Ends the session (or collects one that ended by itself) and checks the
293
- * daemon's count of executed calls against the chain this client saw.
320
+ * daemon's count of executed calls against the chain this client saw. Every
321
+ * later call returns the first one's promise, so its summary or its error, without
322
+ * another request: the daemon forgets a session at its first close, and a second
323
+ * CloseSession would be answered NotFound. The one exception is a close refused
324
+ * not dispatched (its signal aborted before it was sent, say): it closed nothing,
325
+ * so the next call tries again. The first call's signal is the one that applies.
294
326
  */
295
327
  close(signal?: AbortSignal): Promise<SessionSummary>;
296
328
  }
package/dist/client.js CHANGED
@@ -4,11 +4,12 @@
4
4
  // checks every run record against what it sent and received, checks the
5
5
  // isolation evidence against the caller's floor, and tracks a session's chain of
6
6
  // records so a call it did not make is caught.
7
+ import { createHash, createHmac, randomBytes } from "node:crypto";
7
8
  import { isIP } from "node:net";
8
9
  import { checkRecord, checkUnanswered, requestDigest, sessionFingerprint, softwareRuleAllows, } from "./record.js";
9
- import { errorFromWire, PlimsollError, sessionEndFromWire } from "./errors.js";
10
+ import { errorFromWire, NOT_DISPATCHED_HEADER, PlimsollError, REQUEST_ID_HEADER, sessionEndFromWire, unboundSuccess } from "./errors.js";
10
11
  /** The wire protocol number this client speaks (protocol.Number in Go). */
11
- export const PROTOCOL = 2;
12
+ export const PROTOCOL = 3;
12
13
  const SERVICE = "plimsoll.v1.SandboxService";
13
14
  // Above the largest legitimate project response, so a misbehaving daemon cannot
14
15
  // make the client buffer without bound (the Go client's maxResponseBytes).
@@ -22,6 +23,20 @@ export function meets(actual, floor) {
22
23
  return a >= 0 && f >= 1 && a >= f;
23
24
  }
24
25
  const DEFAULT_REQUEST_TIMEOUT_MS = 6 * 60_000;
26
+ /**
27
+ * What an owner is sent as: hex(HMAC-SHA256(key = SHA-256("plimsoll session owner key
28
+ * v2\n" + the client's token), message = "plimsoll session owner v2\n" + owner)), the
29
+ * same in every official client, so the processes of one app agree on a user. The
30
+ * daemon stores only a token's SHA-256, so it cannot test a guessed name against a
31
+ * digest; without a token anyone can. The key is derived, not the token itself: HMAC
32
+ * replaces a key longer than 64 bytes with its SHA-256, which for a long imported
33
+ * token is exactly the token_sha256 the clients file holds.
34
+ * @internal
35
+ */
36
+ export function ownerDigest(token, owner) {
37
+ const key = createHash("sha256").update("plimsoll session owner key v2\n" + (token ?? ""), "utf8").digest();
38
+ return createHmac("sha256", key).update("plimsoll session owner v2\n" + owner, "utf8").digest("hex");
39
+ }
25
40
  function validateBaseUrl(raw, insecureHttp) {
26
41
  if (raw === "" || raw !== raw.trim())
27
42
  throw new PlimsollError("invalid_argument", "plimsoll: base URL must be non-empty with no surrounding whitespace");
@@ -210,6 +225,19 @@ function digestPayload(p) {
210
225
  return { kind: "cell", language: p.cell.language, code: p.cell.code, files: p.cell.files };
211
226
  return { kind: "project", grantProfile: p.project.grantProfile ?? "", files: p.project.files, steps: p.project.steps, artifacts: p.project.artifacts };
212
227
  }
228
+ // Only codes reproduced before any HTTP request was sent by Node's bundled fetch.
229
+ // No prefixes: other TLS errors can come from reading an answer after dispatch.
230
+ function fetchDidNotSend(error) {
231
+ const seen = new Set();
232
+ while (error !== null && typeof error === "object" && !seen.has(error)) {
233
+ seen.add(error);
234
+ const cause = error;
235
+ if (cause.code === "ECONNREFUSED" || cause.code === "ERR_SSL_WRONG_VERSION_NUMBER" || cause.code === "DEPTH_ZERO_SELF_SIGNED_CERT")
236
+ return true;
237
+ error = cause.cause;
238
+ }
239
+ return false;
240
+ }
213
241
  export class PlimsollClient {
214
242
  base;
215
243
  token;
@@ -236,7 +264,9 @@ export class PlimsollClient {
236
264
  if (signal?.aborted)
237
265
  throw new PlimsollError("canceled", `plimsoll: ${method} was canceled before it was sent`, { notDispatched: "request", cause: signal.reason });
238
266
  refuseIllFormed(body, "the request");
239
- const headers = { "Content-Type": "application/json", "Connect-Protocol-Version": "1" };
267
+ // A fresh ID per request; an answer counts only if it carries the ID back.
268
+ const requestId = randomBytes(16).toString("hex");
269
+ const headers = { "Content-Type": "application/json", "Connect-Protocol-Version": "1", [REQUEST_ID_HEADER]: requestId };
240
270
  if (this.token)
241
271
  headers["Authorization"] = `Bearer ${this.token}`;
242
272
  const deadline = AbortSignal.timeout(this.requestTimeoutMs);
@@ -257,7 +287,9 @@ export class PlimsollClient {
257
287
  res = await this.fetchImpl(`${this.base}/${SERVICE}/${method}`, { method: "POST", headers, body: JSON.stringify(body), signal: both, redirect: "manual" });
258
288
  }
259
289
  catch (e) {
260
- throw cut(e) ?? new PlimsollError("unavailable", `plimsoll: ${e.message}`, { cause: e });
290
+ throw cut(e) ?? new PlimsollError("unavailable", `plimsoll: ${e.message}`, {
291
+ cause: e, notDispatched: fetchDidNotSend(e) ? "environment" : undefined,
292
+ });
261
293
  }
262
294
  if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400)) {
263
295
  void res.body?.cancel().catch(() => undefined);
@@ -279,8 +311,15 @@ export class PlimsollClient {
279
311
  catch {
280
312
  parsed = undefined;
281
313
  }
314
+ // What an answer says about the call holds only for the request it answers: one
315
+ // without this request's ID (a daemon older than protocol 3, or an intermediary that
316
+ // served another request's answer or dropped the header) is believed in nothing.
317
+ // Two echoes come back joined, which never equals one ID.
318
+ const bound = res.headers.get(REQUEST_ID_HEADER) === requestId;
282
319
  if (!res.ok)
283
- throw errorFromWire(res.status, parsed);
320
+ throw errorFromWire(res.status, parsed, { bound, mark: res.headers.get(NOT_DISPATCHED_HEADER) });
321
+ if (!bound)
322
+ throw unboundSuccess(method);
284
323
  if (parsed === undefined || typeof parsed !== "object")
285
324
  throw new PlimsollError("internal", "plimsoll: the daemon's answer is not a JSON message");
286
325
  return parsed;
@@ -309,6 +348,8 @@ export class PlimsollClient {
309
348
  sessionLifetimeMs: m.sessionLifetimeMs ?? 0,
310
349
  sessionIdleTimeoutMs: m.sessionIdleTimeoutMs ?? 0,
311
350
  sessionEnvironment: env(m.sessionEnvironment),
351
+ maxSessionsPerCaller: m.maxSessionsPerCaller ?? 0,
352
+ maxSessionsPerOwner: m.maxSessionsPerOwner ?? 0,
312
353
  environments: {
313
354
  javascript: env(m.javascriptEnvironment),
314
355
  project: env(m.projectEnvironment),
@@ -345,6 +386,11 @@ export class PlimsollClient {
345
386
  throw new PlimsollError("invalid_argument", `plimsoll: unknown language ${JSON.stringify(l)} in the hint`, { notDispatched: "request" });
346
387
  }
347
388
  }
389
+ // Undefined is no owner; anything else names one. An empty owner sent as none would
390
+ // escape the daemon's per-owner cap without a word.
391
+ if (opts.owner !== undefined && (typeof opts.owner !== "string" || opts.owner === "")) {
392
+ throw new PlimsollError("invalid_argument", "plimsoll: owner must be a nonempty string, or omitted for none", { notDispatched: "request" });
393
+ }
348
394
  const m = await this.call("OpenSession", {
349
395
  protocol: PROTOCOL,
350
396
  minimumIsolation: opts.minimumIsolation,
@@ -353,6 +399,7 @@ export class PlimsollClient {
353
399
  idleTimeoutMs: durationMs(opts.idleTimeoutMs) || undefined,
354
400
  softwareRule: rule,
355
401
  languages: opts.languages?.length ? [...new Set(opts.languages)] : undefined,
402
+ owner: opts.owner === undefined ? undefined : ownerDigest(this.token, opts.owner),
356
403
  }, opts.signal);
357
404
  const s = decoded(() => new Session(this, m, rule, opts.minimumIsolation));
358
405
  if (decoded(() => s.fingerprint !== sessionFingerprint(m.sessionId ?? ""))) {
@@ -452,6 +499,7 @@ export class Session {
452
499
  // the chain check. They are refused here instead, before anything is sent.
453
500
  #unknown;
454
501
  #queue = Promise.resolve();
502
+ #closing;
455
503
  /** @internal */
456
504
  constructor(client, m, rule, floor) {
457
505
  this.#client = client;
@@ -595,11 +643,28 @@ export class Session {
595
643
  }
596
644
  /**
597
645
  * Ends the session (or collects one that ended by itself) and checks the
598
- * daemon's count of executed calls against the chain this client saw.
646
+ * daemon's count of executed calls against the chain this client saw. Every
647
+ * later call returns the first one's promise, so its summary or its error, without
648
+ * another request: the daemon forgets a session at its first close, and a second
649
+ * CloseSession would be answered NotFound. The one exception is a close refused
650
+ * not dispatched (its signal aborted before it was sent, say): it closed nothing,
651
+ * so the next call tries again. The first call's signal is the one that applies.
599
652
  */
600
653
  close(signal) {
654
+ return (this.#closing ??= this.#closeOnce(signal));
655
+ }
656
+ #closeOnce(signal) {
601
657
  return this.#serial(async () => {
602
- const m = await this.#client.call("CloseSession", { protocol: PROTOCOL, sessionId: this.#id }, signal);
658
+ let m;
659
+ try {
660
+ m = await this.#client.call("CloseSession", { protocol: PROTOCOL, sessionId: this.#id }, signal);
661
+ }
662
+ catch (e) {
663
+ // Refused not dispatched: the session is still open on the daemon.
664
+ if (e instanceof PlimsollError && e.notDispatched)
665
+ this.#closing = undefined;
666
+ throw e;
667
+ }
603
668
  const sum = decoded(() => ({
604
669
  session: m.session ?? "",
605
670
  calls: BigInt(m.calls ?? 0),