@plimsollmark/client 0.18.0 → 0.20.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 +193 -30
- package/dist/ai-sdk.d.ts +24 -0
- package/dist/ai-sdk.js +47 -0
- package/dist/client.d.ts +33 -1
- package/dist/client.js +43 -2
- package/dist/errors.d.ts +10 -5
- package/dist/errors.js +18 -7
- package/dist/mastra.d.ts +16 -4
- package/dist/mastra.js +17 -11
- package/dist/sandboxes.d.ts +62 -9
- package/dist/sandboxes.js +303 -78
- package/dist/tool.d.ts +2 -1
- package/dist/tool.js +17 -9
- package/dist/trigger.d.ts +9 -2
- package/dist/trigger.js +21 -8
- package/dist/wire.d.ts +2 -0
- package/package.json +14 -6
package/README.md
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
# @plimsollmark/client
|
|
2
2
|
|
|
3
|
-
A TypeScript client for `plimsolld`, plus
|
|
4
|
-
`executeCode` tool backed by plimsoll: one for [
|
|
5
|
-
|
|
6
|
-
|
|
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:
|
|
@@ -30,7 +31,19 @@ npm install @plimsollmark/client
|
|
|
30
31
|
|
|
31
32
|
The package's version is the plimsoll release it ships in: version X.Y.Z was built and
|
|
32
33
|
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`.
|
|
34
|
+
`ai` and `zod` for `/ai-sdk`, `@trigger.dev/sdk`, `ai` and `zod` for `/trigger`, `@mastra/core` and `zod` for `/mastra`.
|
|
35
|
+
|
|
36
|
+
This package has no dependencies, so it brings nothing into your installation; the
|
|
37
|
+
frameworks do. One worth knowing about: `@trigger.dev/sdk` 4.7 pins `socket.io-client`
|
|
38
|
+
4.7.5, whose `engine.io-client` resolves a `ws` affected by two advisories fixed in 8.21.0
|
|
39
|
+
([GHSA-58qx-3vcg-4xpx and GHSA-96hv-2xvq-fx4p, EXTERNAL · advisory ↗](https://github.com/advisories/GHSA-96hv-2xvq-fx4p)).
|
|
40
|
+
npm applies `overrides` only from your application's own `package.json`, so this
|
|
41
|
+
package's override cannot reach your installation. Until Trigger.dev moves, add one
|
|
42
|
+
there, as this repository's tests do:
|
|
43
|
+
|
|
44
|
+
```json
|
|
45
|
+
"overrides": { "engine.io-client": "^6.6.7" }
|
|
46
|
+
```
|
|
34
47
|
|
|
35
48
|
## The client
|
|
36
49
|
|
|
@@ -43,7 +56,7 @@ const info = await plimsoll.describe(); // provider, tier, supportsSessions, ...
|
|
|
43
56
|
const r = await plimsoll.runJavaScript("console.log(6 * 7)", { minimumIsolation: "container", timeoutMs: 10_000 });
|
|
44
57
|
r.stdout; // "42\n"; a non-zero r.exitCode is a normal result, not an error
|
|
45
58
|
|
|
46
|
-
const s = await plimsoll.openSession({ minimumIsolation: "container" }); // docker or
|
|
59
|
+
const s = await plimsoll.openSession({ minimumIsolation: "container" }); // docker, openshell or e2b
|
|
47
60
|
await s.runProject({ files: [{ path: "a.js", content: "console.log(1)" }], steps: ["node a.js"] });
|
|
48
61
|
await s.runJavaScript("console.log(require('fs').readdirSync('.'))");
|
|
49
62
|
// A cell runs in an interpreter the session keeps alive: what it defines is there next time.
|
|
@@ -59,6 +72,11 @@ is 0 when the code ran, 1 when it raised and 124 at the deadline. Python needs `
|
|
|
59
72
|
the daemon's image (`plimsoll/sandbox-python` has it, with NumPy and SciPy);
|
|
60
73
|
`describe()` lists the languages the daemon proved on `environments.project.languages`.
|
|
61
74
|
|
|
75
|
+
`close()` sends one `CloseSession` however many times it is called, and every later call
|
|
76
|
+
gets the first one's summary or error: the daemon forgets a session at its first close and
|
|
77
|
+
would answer a second with NotFound. A close refused not dispatched (aborted before it was
|
|
78
|
+
sent, say) closed nothing, so a later `close()` tries again.
|
|
79
|
+
|
|
62
80
|
Cleartext HTTP is accepted only to a loopback address unless you pass `insecureHttp: true`.
|
|
63
81
|
|
|
64
82
|
## `executeCode` for an agent: `CodeSandboxes`
|
|
@@ -85,20 +103,63 @@ from your own authenticated user and conversation (or job) IDs, never from a str
|
|
|
85
103
|
or the model supplies, or give each customer a plimsoll credential of their own
|
|
86
104
|
([who may share a session](https://github.com/plimsollmark/plimsoll/blob/main/docs/sessions.md#who-may-share-a-session)).
|
|
87
105
|
|
|
88
|
-
`
|
|
89
|
-
|
|
106
|
+
A key is a `SandboxKey`: either a string (the Trigger.dev add-on passes its run ID) or
|
|
107
|
+
`{ owner, conversation }`, the user a conversation belongs to and the conversation's ID
|
|
108
|
+
(the AI SDK add-on passes `{ owner: userId, conversation: conversationId }`, the Mastra
|
|
109
|
+
add-on `{ owner: resourceId, conversation: threadId }`). The parts are encoded as a JSON
|
|
110
|
+
array, never joined with a separator, so no user's IDs can spell another user's key or a
|
|
111
|
+
string key. The owner is what `maxSessionsPerOwner` counts (below).
|
|
112
|
+
|
|
113
|
+
**The floor defaults to `kernel`.** `minimumIsolation` is the weakest isolation tier a call
|
|
114
|
+
accepts: the daemon refuses, before anything runs, a call whose floor its tier does not meet,
|
|
115
|
+
and the client checks the tier stated on the answer. `CodeSandboxes`, and so every add-on
|
|
116
|
+
on it, defaults to `kernel` (docker running gVisor's `runsc` runtime, which the daemon's
|
|
117
|
+
startup checks verified; the stronger `vm` tier also meets it) because it is the weakest
|
|
118
|
+
tier this project treats as fit for code you did not write. An ordinary docker daemon (runc) is the `container` tier and refuses every
|
|
119
|
+
call under the default: set `minimumIsolation: "container"` for local development on your
|
|
120
|
+
own code. Set `"vm"` when the threat model needs a virtual-machine boundary; of today's VM
|
|
121
|
+
providers `e2b` keeps sessions (a suspend ends its interpreters, so the next call reports
|
|
122
|
+
`freshInterpreter`) and `dockercloud` keeps none, so every call there runs fresh.
|
|
90
123
|
|
|
91
|
-
|
|
92
|
-
|
|
124
|
+
`CodeSandboxes` keeps one sandbox per conversation key. With `sessions: "auto"` (the
|
|
125
|
+
default) it asks the daemon whether it keeps sessions (`describe()`), keeps the answer, and
|
|
126
|
+
asks again after a call refused for a reason that says the daemon may have changed since
|
|
127
|
+
(`notDispatched` `unsupported`, `environment`, `protocol` or `isolation`: a restart with
|
|
128
|
+
sessions turned on or off, another image or tier), never after a `capacity` or `request`
|
|
129
|
+
refusal:
|
|
130
|
+
|
|
131
|
+
- **It does** (`docker` with a project image, `openshell` or `e2b`, with
|
|
132
|
+
`SANDBOX_MAX_SESSIONS` set; on `e2b` a suspend ends the interpreters, so the next call
|
|
133
|
+
reports `freshInterpreter`): a key holds one plimsoll session, and every call is a cell in that session's
|
|
93
134
|
interpreter. Variables, imports and loaded data from earlier calls are still defined, and
|
|
94
135
|
files stay in the working directory. On one laptop on 2026-10-01, a call that used an
|
|
95
136
|
80 MB array an earlier call had loaded took 10 ms on OpenShell and 23 ms on docker
|
|
96
137
|
under gVisor (medians), against 939 ms and 714 ms for a fresh sandbox that rebuilt it.
|
|
97
|
-
- **It does not** (`
|
|
138
|
+
- **It does not** (`dockercloud`, `wasm`, a daemon with sessions off, or `sessions: "never"`): every call runs in
|
|
98
139
|
a fresh sandbox, as a small project whose runner prints the last expression the same way,
|
|
99
140
|
and nothing persists. `wasm` runs no projects, so there a call is a JavaScript snippet
|
|
100
141
|
printing its last value; Python and files are refused before anything is sent.
|
|
101
142
|
|
|
143
|
+
A fresh project run (every call on a daemon without sessions, and a call without a key on
|
|
144
|
+
any daemon) whose result has no step report has no exit code to give: its outcome, such as
|
|
145
|
+
`timed_out` or `protocol_error`, says what ended the run but not whether the code had
|
|
146
|
+
started. So the tool throws instead of inventing an exit code: a `PlimsollError` (code
|
|
147
|
+
`unknown`) with no `notDispatched` mark, because the code may have run, and the checked
|
|
148
|
+
result on `PlimsollError.result`. Nothing retries it, since running it again could repeat
|
|
149
|
+
what it did.
|
|
150
|
+
|
|
151
|
+
A framework hands its model only an error's message, so every error the tool throws is a
|
|
152
|
+
`PlimsollError` whose message starts with whether the code ran: `Nothing ran (<reason>): `
|
|
153
|
+
when it carries a `notDispatched` mark (a refusal, a cap, a cancel before sending), and `The
|
|
154
|
+
code may have run, and there is no checked answer for it: ` otherwise. Where the call
|
|
155
|
+
failed decides the mark, not who raised the error: everything before the code is sent
|
|
156
|
+
(reading the key, building the client, the Describe, opening the sandbox) runs nothing, so
|
|
157
|
+
a failure there is marked even when the daemon could not mark it (unreachable, a proxy's
|
|
158
|
+
503, a dropped connection, the client's own check of the session it opened), with reason
|
|
159
|
+
`environment` unless the daemon gave one. An error of another class there (a key or owner
|
|
160
|
+
resolver of the app's that throws) is wrapped the same way. From the moment the code may
|
|
161
|
+
have been sent, an unmarked error stays unmarked.
|
|
162
|
+
|
|
102
163
|
The tool's output says which: `stateKept` (this call's interpreter was still running when
|
|
103
164
|
it answered, so what it defined can be there for the next call; false when no interpreter is
|
|
104
165
|
kept, and when the call's deadline or the sandbox's end ended it) and `filesPersist` (the same
|
|
@@ -108,24 +169,83 @@ its limit. So the output also says what is new, rather than what was lost, becau
|
|
|
108
169
|
only the sandbox knows: `freshInterpreter` whenever the call's interpreter had just started
|
|
109
170
|
(the first call in a language, a deadline, a crash), so nothing earlier calls defined
|
|
110
171
|
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
|
|
112
|
-
idle close let go, one that ended by itself (its lifetime, its disk
|
|
113
|
-
conversation resumed in another process, which this instance cannot tell
|
|
114
|
-
call. A call without a key (no thread, no run) always runs fresh: one sandbox
|
|
115
|
-
across conversations would show one user another's files. A language the daemon's
|
|
116
|
-
cannot run is refused before anything is sent.
|
|
172
|
+
sandbox, so no earlier file is there either. That covers a sandbox that `dispose`, the
|
|
173
|
+
idle close or a session cap (below) let go, one that ended by itself (its lifetime, its disk
|
|
174
|
+
budget), and a conversation resumed in another process, which this instance cannot tell
|
|
175
|
+
from a first call. A call without a key (no thread, no run) always runs fresh: one sandbox
|
|
176
|
+
shared across conversations would show one user another's files. A language the daemon's
|
|
177
|
+
image cannot run is refused before anything is sent. Output past `maxOutputChars` (each of
|
|
178
|
+
stdout and stderr) is cut and marked truncated, and a cut never ends on the first half of a
|
|
179
|
+
surrogate pair (the two UTF-16 code units that encode one character such as an emoji): a
|
|
180
|
+
lone half is not valid Unicode, and a strict model provider can refuse the request that
|
|
181
|
+
carries it back.
|
|
182
|
+
|
|
183
|
+
**Every kept sandbox holds one of the daemon's session slots** (`SANDBOX_MAX_SESSIONS`), and
|
|
184
|
+
every user of an app that shares one plimsoll token draws on the same slots. Two caps keep
|
|
185
|
+
one user, or one app, from holding them all:
|
|
186
|
+
|
|
187
|
+
- `maxSessionsPerOwner` (default 3; 0 for no cap): the sandboxes one owner may hold in this
|
|
188
|
+
instance. When the owner already holds that many, opening another of the owner's
|
|
189
|
+
conversations first closes the owner's least recently used sandbox with no call in flight (least recently used: the one whose last call
|
|
190
|
+
started or ended longest ago), and that conversation's next call opens a new sandbox and
|
|
191
|
+
reports `freshSandbox: true`. Three, because a person rarely works in more than a few
|
|
192
|
+
conversations at once, and the closed conversation loses its variables and files, never
|
|
193
|
+
an answer. If every one of the owner's sandboxes has a call in flight, the new
|
|
194
|
+
conversation's call is refused before anything opens (`PlimsollError` code
|
|
195
|
+
`resource_exhausted`, `notDispatched: "capacity"`). A string key names no owner and is not
|
|
196
|
+
counted here.
|
|
197
|
+
- `maxSessions` (default 0, no cap of its own): the same across all owners and string keys.
|
|
198
|
+
Set it to this app's share of the daemon's `SANDBOX_MAX_SESSIONS`, a number only the
|
|
199
|
+
daemon's operator knows.
|
|
200
|
+
|
|
201
|
+
A `warm` is a guess (Trigger.dev's recipe warms in every new run's `onTurnStart`, a chat the
|
|
202
|
+
user opened and never typed in included), so it never closes a sandbox to make room: when
|
|
203
|
+
either cap is reached it does nothing, and the conversation's first call opens its sandbox,
|
|
204
|
+
closing the least recently used idle one as any call does.
|
|
205
|
+
|
|
206
|
+
Both caps count what one process holds. A host that runs many processes (serverless
|
|
207
|
+
functions, several Trigger.dev workers) keeps one count per process, so set the daemon's
|
|
208
|
+
`SANDBOX_MAX_SESSIONS_PER_OWNER`, which counts them all: every open names the key's owner
|
|
209
|
+
to the daemon (`openSession({ owner })`, sent as a hex HMAC-SHA256 of the owner under a key derived from
|
|
210
|
+
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
|
|
211
|
+
only the token's SHA-256, cannot test a guessed one). Omit `owner` for none: an empty
|
|
212
|
+
string is refused before anything is sent (`invalid_argument`, `notDispatched:
|
|
213
|
+
"request"`), because sent as no owner it would escape the cap. At that cap the daemon closes the
|
|
214
|
+
owner's least recently used session with no call in progress; its next call is refused as
|
|
215
|
+
`replaced` (not dispatched), and `CodeSandboxes` runs it once more in a new sandbox, saying
|
|
216
|
+
`freshSandbox: true`. The daemon cannot tell a warm from a call's open, so a warm that opens
|
|
217
|
+
counts there like any open, and at that cap closes the user's least recently used session,
|
|
218
|
+
which may be a conversation in use in another process. `SANDBOX_MAX_SESSIONS` and `SANDBOX_MAX_SESSIONS_PER_CALLER` still
|
|
219
|
+
bound the daemon and each caller token. A daemon at either of those refuses the
|
|
220
|
+
open (not dispatched, reason `capacity`), and the client does not close sandboxes in
|
|
221
|
+
response, because the daemon gives the same refusal for a caller over its rate limit, which
|
|
222
|
+
a close would not help.
|
|
223
|
+
|
|
224
|
+
Each tool answer also includes `isolation` and `recordSha256`. The client checks
|
|
225
|
+
the run record before returning, then gives the tool the checked record's SHA-256.
|
|
226
|
+
The digest names that record; it is not a signature or a proof that the guest
|
|
227
|
+
computed honestly. See the [Trigger.dev feature and deployment guide](https://github.com/plimsollmark/plimsoll/blob/main/docs/trigger-dev.md)
|
|
228
|
+
for the three properties together.
|
|
117
229
|
|
|
118
230
|
Closing a sandbox checks the daemon's count of calls against the chain the client saw; a
|
|
119
231
|
mismatch means the daemon counted a call the client has no answer for (one that ended in an
|
|
120
232
|
abort, a timeout, a dropped connection or a proxy's error), or, if none did, that someone
|
|
121
|
-
else held the session ID. It goes to `onCloseError
|
|
122
|
-
|
|
233
|
+
else held the session ID. It goes to `onCloseError(key, err)` rather than being dropped at
|
|
234
|
+
teardown; `key` is the `SandboxKey` as the add-on passed it (the `{ owner, conversation }`
|
|
235
|
+
object for a pair). Without `onCloseError`, a `console.warn` names the key only by the first
|
|
236
|
+
12 hex digits of its SHA-256 fingerprint, enough to tell one conversation's lines from
|
|
237
|
+
another's, never by its IDs, because a key can hold a user's ID (an email address, in some
|
|
238
|
+
apps). An `onCloseError` that throws, or returns a promise that rejects, is logged the same
|
|
239
|
+
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
|
|
123
240
|
(`PlimsollError.unanswered`, a version 3 record); the session checks it, hands it back as
|
|
124
241
|
`PlimsollError.record`, keeps it in its chain and goes on, and so does the conversation's
|
|
125
242
|
sandbox. A call whose answer never arrived carries none, so the client sends nothing more
|
|
126
243
|
on that session (`Session.stopped` says why), and the conversation's next call opens a new
|
|
127
244
|
sandbox and reports `freshSandbox: true`. A session call aborted while it waits its turn
|
|
128
|
-
was never sent: it is refused, marked not dispatched, and the session goes on.
|
|
245
|
+
was never sent: it is refused, marked not dispatched, and the session goes on. A call
|
|
246
|
+
aborted before or while its sandbox opens sends nothing either (`PlimsollError` code
|
|
247
|
+
`canceled`, `notDispatched: "request"`), and a sandbox it was opening that no other call is
|
|
248
|
+
using or has used is closed as soon as it opens. The
|
|
129
249
|
`.plimsoll/` directory is the runner's: a file under it is refused before anything is
|
|
130
250
|
sent.
|
|
131
251
|
|
|
@@ -133,6 +253,18 @@ The session ID is a capability. It lives in the client's memory and nowhere else
|
|
|
133
253
|
a log line, not in a record, not in Trigger.dev's `chat.local` (which is serialized into
|
|
134
254
|
subtask metadata). Records carry its SHA-256.
|
|
135
255
|
|
|
256
|
+
## Vercel AI SDK
|
|
257
|
+
|
|
258
|
+
`@plimsollmark/client/ai-sdk` exports `plimsollCodeTools`. Its `executeCode` tool
|
|
259
|
+
runs fresh; `forConversation({userId, conversationId})` binds a tool to
|
|
260
|
+
application-owned identity and the shared sandbox manager, with the user as the key's
|
|
261
|
+
owner. It accepts Python or JavaScript plus text files and returns checked results. The
|
|
262
|
+
default minimum isolation is kernel, as for every add-on on `CodeSandboxes`; use a
|
|
263
|
+
verified gVisor or VM daemon for hostile code.
|
|
264
|
+
|
|
265
|
+
See [usage, lifecycle and the no-spend local smoke check, EXTERNAL · official docs ↗](https://github.com/plimsollmark/plimsoll/blob/main/docs/ai-sdk.md).
|
|
266
|
+
This source add-on needs the optional `ai` and `zod` peer packages.
|
|
267
|
+
|
|
136
268
|
## Trigger.dev
|
|
137
269
|
|
|
138
270
|
The add-on follows Trigger.dev's own
|
|
@@ -147,7 +279,7 @@ import { plimsollCodeSandbox } from "@plimsollmark/client/trigger";
|
|
|
147
279
|
|
|
148
280
|
const sandbox = plimsollCodeSandbox({
|
|
149
281
|
client: () => new PlimsollClient({ baseUrl: process.env.PLIMSOLL_URL!, token: process.env.PLIMSOLL_TOKEN }),
|
|
150
|
-
minimumIsolation: "
|
|
282
|
+
minimumIsolation: "kernel",
|
|
151
283
|
});
|
|
152
284
|
|
|
153
285
|
export const codeChat = chat.agent({
|
|
@@ -162,6 +294,21 @@ export const codeChat = chat.agent({
|
|
|
162
294
|
|
|
163
295
|
The full example, with a test that drives real turns through Trigger.dev's `mockChatAgent`:
|
|
164
296
|
[examples/trigger-chat](https://github.com/plimsollmark/plimsoll/tree/main/examples/trigger-chat/).
|
|
297
|
+
Its source sets a `container` floor for local development. The
|
|
298
|
+
[deployable sister starter](https://github.com/plimsollmark/plimsoll-trigger-starter)
|
|
299
|
+
uses `kernel`, the add-on's default (the snippet above writes it out). Hostile
|
|
300
|
+
production code needs the verified kernel or VM tier; choose `vm` when the threat
|
|
301
|
+
model requires a VM boundary: `e2b` keeps cells until a suspend, and `dockercloud` runs
|
|
302
|
+
every call fresh.
|
|
303
|
+
|
|
304
|
+
The key is the run ID. To cap each user's sandboxes, name the run's user in the warm,
|
|
305
|
+
as your server authenticated it: `sandbox.warm(runId, userId)`. Never take it from
|
|
306
|
+
`clientData`, which the browser sets: a user who could choose it could close another
|
|
307
|
+
user's sandboxes. The key is then the user and the run, `maxSessionsPerOwner` counts
|
|
308
|
+
the worker's sandboxes per user, and a daemon with `SANDBOX_MAX_SESSIONS_PER_OWNER`
|
|
309
|
+
counts them across every worker of the deployment. The user stays in the worker's
|
|
310
|
+
memory, never in `chat.local`. Without it no per-user cap applies; `maxSessions`, when
|
|
311
|
+
set, caps the sandboxes one worker holds.
|
|
165
312
|
|
|
166
313
|
What the hooks cannot cover: a run that dies without reaching `onChatSuspend` or
|
|
167
314
|
`onComplete` (its process killed, a crash) leaves its sandbox open until the add-on's idle
|
|
@@ -184,13 +331,28 @@ export const analyst = new Agent({ id: "analyst", name: "analyst", instructions:
|
|
|
184
331
|
// When a conversation ends: await dispose(threadId, resourceId);
|
|
185
332
|
```
|
|
186
333
|
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
334
|
+
No floor is set here, so the tool requires `kernel`; for local development against an
|
|
335
|
+
ordinary docker daemon, pass `minimumIsolation: "container"`.
|
|
336
|
+
|
|
337
|
+
Recorded calls through this tool, two users and a disposed thread included, replay on its
|
|
338
|
+
integration page: [see a run, INTERNAL · plimsoll site →](https://plimsollmark.github.io/plimsoll/integrations/mastra/index.html).
|
|
339
|
+
|
|
340
|
+
The sandbox is keyed by Mastra's thread and resource, `{ owner: resourceId, conversation:
|
|
341
|
+
threadId }` (a thread ID is unique only within its user). A call without a `resourceId`
|
|
342
|
+
runs in a fresh sandbox every time: under an empty resource, every user without one would
|
|
343
|
+
share a sandbox with anyone whose thread ID collided. Set the resource from your
|
|
344
|
+
authenticated user, not from anything the user typed. Mastra has no hook for "this
|
|
345
|
+
conversation is going to sleep", so a thread's sandbox closes on
|
|
346
|
+
`dispose(threadId, resourceId)`, after `idleCloseMs` (default 10 minutes) without a call,
|
|
347
|
+
or when the same user opens a thread past `maxSessionsPerOwner` (default 3) and this
|
|
348
|
+
thread's sandbox is that user's least recently used one with no call in flight.
|
|
349
|
+
|
|
350
|
+
In an agent network, Mastra fills a missing `resourceId` with the network's name (and the
|
|
351
|
+
thread with the run ID), so every user of the network would count as one owner and close
|
|
352
|
+
each other's sandboxes. Pass `owner`, the user from your own authentication (for example a
|
|
353
|
+
value your server put in Mastra's `requestContext`):
|
|
354
|
+
`plimsollExecuteCode({ ..., owner: (ctx) => ctx.requestContext?.get("userId") })`, and the
|
|
355
|
+
same owner to `dispose(threadId, resourceId, owner)`. The caps then count that owner.
|
|
194
356
|
|
|
195
357
|
## Tests
|
|
196
358
|
|
|
@@ -199,8 +361,9 @@ runs, an in-memory session provider for sessions and cells, and a provider that
|
|
|
199
361
|
project with the plan it received, for the project a fresh call sends) and runs three
|
|
200
362
|
suites against them: the
|
|
201
363
|
client's (needs only node), the add-ons' (needs `npm install` here), and the Trigger.dev
|
|
202
|
-
example's (needs `npm install` in `examples/trigger-chat`; it waits out
|
|
203
|
-
|
|
364
|
+
example's (needs `npm install` in `examples/trigger-chat`; it waits out the example's
|
|
365
|
+
3-second idle window, Trigger.dev's default being 30 seconds, to prove the suspend closes
|
|
366
|
+
the sandbox). An ordinary Go test
|
|
204
367
|
skips a suite whose runtime or dependencies are absent. CI runs `make clients-suite`,
|
|
205
368
|
which installs both npm lockfiles and sets `PLIMSOLL_REQUIRE_CLIENTS=1`, so a missing
|
|
206
369
|
prerequisite or skipped Go test fails. The client's digests are also checked against the
|
package/dist/ai-sdk.d.ts
ADDED
|
@@ -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
|
@@ -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,6 +4,7 @@
|
|
|
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 } from "node:crypto";
|
|
7
8
|
import { isIP } from "node:net";
|
|
8
9
|
import { checkRecord, checkUnanswered, requestDigest, sessionFingerprint, softwareRuleAllows, } from "./record.js";
|
|
9
10
|
import { errorFromWire, PlimsollError, sessionEndFromWire } from "./errors.js";
|
|
@@ -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");
|
|
@@ -309,6 +324,8 @@ export class PlimsollClient {
|
|
|
309
324
|
sessionLifetimeMs: m.sessionLifetimeMs ?? 0,
|
|
310
325
|
sessionIdleTimeoutMs: m.sessionIdleTimeoutMs ?? 0,
|
|
311
326
|
sessionEnvironment: env(m.sessionEnvironment),
|
|
327
|
+
maxSessionsPerCaller: m.maxSessionsPerCaller ?? 0,
|
|
328
|
+
maxSessionsPerOwner: m.maxSessionsPerOwner ?? 0,
|
|
312
329
|
environments: {
|
|
313
330
|
javascript: env(m.javascriptEnvironment),
|
|
314
331
|
project: env(m.projectEnvironment),
|
|
@@ -345,6 +362,11 @@ export class PlimsollClient {
|
|
|
345
362
|
throw new PlimsollError("invalid_argument", `plimsoll: unknown language ${JSON.stringify(l)} in the hint`, { notDispatched: "request" });
|
|
346
363
|
}
|
|
347
364
|
}
|
|
365
|
+
// Undefined is no owner; anything else names one. An empty owner sent as none would
|
|
366
|
+
// escape the daemon's per-owner cap without a word.
|
|
367
|
+
if (opts.owner !== undefined && (typeof opts.owner !== "string" || opts.owner === "")) {
|
|
368
|
+
throw new PlimsollError("invalid_argument", "plimsoll: owner must be a nonempty string, or omitted for none", { notDispatched: "request" });
|
|
369
|
+
}
|
|
348
370
|
const m = await this.call("OpenSession", {
|
|
349
371
|
protocol: PROTOCOL,
|
|
350
372
|
minimumIsolation: opts.minimumIsolation,
|
|
@@ -353,6 +375,7 @@ export class PlimsollClient {
|
|
|
353
375
|
idleTimeoutMs: durationMs(opts.idleTimeoutMs) || undefined,
|
|
354
376
|
softwareRule: rule,
|
|
355
377
|
languages: opts.languages?.length ? [...new Set(opts.languages)] : undefined,
|
|
378
|
+
owner: opts.owner === undefined ? undefined : ownerDigest(this.token, opts.owner),
|
|
356
379
|
}, opts.signal);
|
|
357
380
|
const s = decoded(() => new Session(this, m, rule, opts.minimumIsolation));
|
|
358
381
|
if (decoded(() => s.fingerprint !== sessionFingerprint(m.sessionId ?? ""))) {
|
|
@@ -452,6 +475,7 @@ export class Session {
|
|
|
452
475
|
// the chain check. They are refused here instead, before anything is sent.
|
|
453
476
|
#unknown;
|
|
454
477
|
#queue = Promise.resolve();
|
|
478
|
+
#closing;
|
|
455
479
|
/** @internal */
|
|
456
480
|
constructor(client, m, rule, floor) {
|
|
457
481
|
this.#client = client;
|
|
@@ -595,11 +619,28 @@ export class Session {
|
|
|
595
619
|
}
|
|
596
620
|
/**
|
|
597
621
|
* 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.
|
|
622
|
+
* daemon's count of executed calls against the chain this client saw. Every
|
|
623
|
+
* later call returns the first one's promise, so its summary or its error, without
|
|
624
|
+
* another request: the daemon forgets a session at its first close, and a second
|
|
625
|
+
* CloseSession would be answered NotFound. The one exception is a close refused
|
|
626
|
+
* not dispatched (its signal aborted before it was sent, say): it closed nothing,
|
|
627
|
+
* so the next call tries again. The first call's signal is the one that applies.
|
|
599
628
|
*/
|
|
600
629
|
close(signal) {
|
|
630
|
+
return (this.#closing ??= this.#closeOnce(signal));
|
|
631
|
+
}
|
|
632
|
+
#closeOnce(signal) {
|
|
601
633
|
return this.#serial(async () => {
|
|
602
|
-
|
|
634
|
+
let m;
|
|
635
|
+
try {
|
|
636
|
+
m = await this.#client.call("CloseSession", { protocol: PROTOCOL, sessionId: this.#id }, signal);
|
|
637
|
+
}
|
|
638
|
+
catch (e) {
|
|
639
|
+
// Refused not dispatched: the session is still open on the daemon.
|
|
640
|
+
if (e instanceof PlimsollError && e.notDispatched)
|
|
641
|
+
this.#closing = undefined;
|
|
642
|
+
throw e;
|
|
643
|
+
}
|
|
603
644
|
const sum = decoded(() => ({
|
|
604
645
|
session: m.session ?? "",
|
|
605
646
|
calls: BigInt(m.calls ?? 0),
|
package/dist/errors.d.ts
CHANGED
|
@@ -2,8 +2,12 @@ import type { RunRecord } from "./record.ts";
|
|
|
2
2
|
import type { WireError, WireRecord } from "./wire.ts";
|
|
3
3
|
/** Why a request was refused before any code ran (plimsoll.v1.NotDispatchedReason). */
|
|
4
4
|
export type Refusal = "request" | "permission" | "protocol" | "unsupported" | "isolation" | "capacity" | "environment" | "unknown";
|
|
5
|
-
/**
|
|
6
|
-
|
|
5
|
+
/**
|
|
6
|
+
* Why a session ended (plimsoll.v1.SessionEnd), "open" while it has not. "unknown" is
|
|
7
|
+
* an end this client has no name for (a daemon newer than the client): the session
|
|
8
|
+
* ended, for a reason it cannot name.
|
|
9
|
+
*/
|
|
10
|
+
export type SessionEnd = "open" | "closed" | "expired" | "disk_exceeded" | "main_process_ended" | "boundary_failed" | "sandbox_changed" | "shutdown" | "replaced" | "not_found" | "unknown";
|
|
7
11
|
/**
|
|
8
12
|
* Connect's status codes, plus the two this client raises itself:
|
|
9
13
|
* "data_loss" for an answer that does not check (the run may have executed),
|
|
@@ -23,9 +27,10 @@ export declare class PlimsollError extends Error {
|
|
|
23
27
|
detail: string;
|
|
24
28
|
} | undefined;
|
|
25
29
|
/**
|
|
26
|
-
* The result the daemon returned, on
|
|
27
|
-
*
|
|
28
|
-
*
|
|
30
|
+
* The result the daemon returned, on an error raised after it answered, so the
|
|
31
|
+
* run may have executed: "data_loss" when the record or the isolation evidence
|
|
32
|
+
* did not check, and "unknown" from CodeSandboxes when a fresh run came back
|
|
33
|
+
* with no step report. This is what came back.
|
|
29
34
|
*/
|
|
30
35
|
readonly result: unknown;
|
|
31
36
|
/**
|
package/dist/errors.js
CHANGED
|
@@ -12,9 +12,10 @@ export class PlimsollError extends Error {
|
|
|
12
12
|
/** Set when a session call was refused because its session had ended. */
|
|
13
13
|
sessionEnded;
|
|
14
14
|
/**
|
|
15
|
-
* The result the daemon returned, on
|
|
16
|
-
*
|
|
17
|
-
*
|
|
15
|
+
* The result the daemon returned, on an error raised after it answered, so the
|
|
16
|
+
* run may have executed: "data_loss" when the record or the isolation evidence
|
|
17
|
+
* did not check, and "unknown" from CodeSandboxes when a fresh run came back
|
|
18
|
+
* with no step report. This is what came back.
|
|
18
19
|
*/
|
|
19
20
|
result;
|
|
20
21
|
/**
|
|
@@ -48,14 +49,22 @@ const SESSION_ENDS = [
|
|
|
48
49
|
"boundary_failed",
|
|
49
50
|
"sandbox_changed",
|
|
50
51
|
"shutdown",
|
|
52
|
+
"replaced",
|
|
53
|
+
"not_found",
|
|
51
54
|
];
|
|
55
|
+
// Only an absent or unspecified end means open. Any other value says the session
|
|
56
|
+
// ended, so one this client has no name for is "unknown", never "open": read as open,
|
|
57
|
+
// an ended session would be reported as still holding its state and files. The
|
|
58
|
+
// refusal decode below keeps its mark the same way.
|
|
52
59
|
export function sessionEndFromWire(v) {
|
|
53
|
-
if (v === undefined)
|
|
60
|
+
if (v === undefined || v === 0)
|
|
54
61
|
return "open";
|
|
55
62
|
if (typeof v === "number")
|
|
56
|
-
return SESSION_ENDS[v] ?? "
|
|
63
|
+
return SESSION_ENDS[v] ?? "unknown";
|
|
57
64
|
const name = v.replace(/^SESSION_END_/, "").toLowerCase();
|
|
58
|
-
|
|
65
|
+
if (name === "unspecified")
|
|
66
|
+
return "open";
|
|
67
|
+
return name !== "open" && name !== "unknown" && SESSION_ENDS.includes(name) ? name : "unknown";
|
|
59
68
|
}
|
|
60
69
|
// Reads one varint at b[i]; returns [value, next index].
|
|
61
70
|
function varint(b, i) {
|
|
@@ -192,8 +201,10 @@ export function errorFromWire(httpStatus, body) {
|
|
|
192
201
|
notDispatched = REFUSALS[decodeDetail(bytes).reason] ?? "unknown";
|
|
193
202
|
}
|
|
194
203
|
else if (d.type === "plimsoll.v1.SessionEnded") {
|
|
204
|
+
// The detail itself says the session ended, so an unspecified reason is not "open".
|
|
195
205
|
const m = decodeDetail(bytes);
|
|
196
|
-
|
|
206
|
+
const reason = sessionEndFromWire(m.reason);
|
|
207
|
+
sessionEnded = { reason: reason === "open" ? "unknown" : reason, detail: m.detail };
|
|
197
208
|
}
|
|
198
209
|
else if (d.type === "plimsoll.v1.UnansweredCall") {
|
|
199
210
|
unanswered = decodeUnanswered(bytes);
|