@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/dist/sandboxes.js
CHANGED
|
@@ -21,9 +21,83 @@
|
|
|
21
21
|
// than what was lost: freshInterpreter whenever its interpreter just started,
|
|
22
22
|
// freshSandbox whenever it is the first answered call in a newly opened sandbox,
|
|
23
23
|
// the conversation's first call included.
|
|
24
|
+
//
|
|
25
|
+
// Every kept sandbox holds one of the daemon's session slots, which every user of an
|
|
26
|
+
// app that shares one token draws on. So a key names the user it belongs to, and this
|
|
27
|
+
// instance holds at most maxSessionsPerOwner sandboxes per user (and maxSessions in
|
|
28
|
+
// all, when set): a conversation over the cap first closes the least recently used
|
|
29
|
+
// sandbox with no call in flight, whose next call then says freshSandbox. These caps
|
|
30
|
+
// count what this instance holds. Every open also names its owner (as a keyed digest),
|
|
31
|
+
// so a daemon with SANDBOX_MAX_SESSIONS_PER_OWNER does the same across every process
|
|
32
|
+
// of the app: a session it closes there refuses its next call as replaced, and the
|
|
33
|
+
// call runs once more in a new sandbox, saying freshSandbox.
|
|
34
|
+
import { createHash } from "node:crypto";
|
|
24
35
|
import { PlimsollClient } from "./client.js";
|
|
25
36
|
import { PlimsollError } from "./errors.js";
|
|
26
37
|
export const DEFAULT_LANGUAGES = ["python", "javascript"];
|
|
38
|
+
// One string per key: JSON keeps a pair from aliasing another pair, or a string key,
|
|
39
|
+
// as a separator could.
|
|
40
|
+
function keyId(key) {
|
|
41
|
+
const parts = typeof key === "string" ? [key] : key && typeof key === "object" ? [key.owner, key.conversation] : [];
|
|
42
|
+
if (parts.length === 0 || parts.some((p) => typeof p !== "string" || p === "")) {
|
|
43
|
+
throw new PlimsollError("invalid_argument", "plimsoll: a sandbox key is a nonempty string, or a nonempty owner and conversation", { notDispatched: "request" });
|
|
44
|
+
}
|
|
45
|
+
return JSON.stringify(parts);
|
|
46
|
+
}
|
|
47
|
+
const ownerOf = (key) => (typeof key === "string" ? undefined : key.owner);
|
|
48
|
+
const errorText = (e) => (e instanceof Error ? e.message : String(e));
|
|
49
|
+
// Refusal reasons that can mean the daemon is no longer the one the cached Describe
|
|
50
|
+
// described.
|
|
51
|
+
const DAEMON_CHANGED = new Set(["unsupported", "environment", "protocol", "isolation"]);
|
|
52
|
+
// Runs a stage before the code is sent to a sandbox (resolving the key, building the
|
|
53
|
+
// client, the Describe, opening the sandbox). Whatever fails there ran nothing, so the
|
|
54
|
+
// stage decides the mark, not the error's class: a transport error, a proxy's 503 or
|
|
55
|
+
// the client's own check of an open is as much a refusal as the daemon's. A mark already
|
|
56
|
+
// given is kept, with its code; an unmarked failure is marked reason environment, the
|
|
57
|
+
// rule the Python CodeExecutor applies to a failed Describe.
|
|
58
|
+
async function beforeDispatch(stage) {
|
|
59
|
+
try {
|
|
60
|
+
return await stage();
|
|
61
|
+
}
|
|
62
|
+
catch (e) {
|
|
63
|
+
if (e instanceof PlimsollError && e.notDispatched)
|
|
64
|
+
throw e;
|
|
65
|
+
if (e instanceof PlimsollError) {
|
|
66
|
+
throw new PlimsollError(e.code, e.message, { notDispatched: "environment", sessionEnded: e.sessionEnded, result: e.result, cause: e });
|
|
67
|
+
}
|
|
68
|
+
throw new PlimsollError("unknown", errorText(e), { notDispatched: "environment", cause: e });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
// Puts whether the code ran at the front of the error's message, once. Every stage
|
|
72
|
+
// before dispatch runs in beforeDispatch, so an error that is not a PlimsollError came
|
|
73
|
+
// from the dispatch or after it: the code may have run, and it is wrapped unmarked.
|
|
74
|
+
function saysWhetherItRan(e) {
|
|
75
|
+
const err = e instanceof PlimsollError ? e : new PlimsollError("unknown", errorText(e), { cause: e });
|
|
76
|
+
const lead = err.notDispatched ? `Nothing ran (${err.notDispatched}): ` : "The code may have run, and there is no checked answer for it: ";
|
|
77
|
+
if (!err.message.startsWith(lead))
|
|
78
|
+
err.message = lead + err.message;
|
|
79
|
+
return err;
|
|
80
|
+
}
|
|
81
|
+
function canceledBeforeSent(signal) {
|
|
82
|
+
return new PlimsollError("canceled", "plimsoll: the call was canceled before it was sent", { notDispatched: "request", cause: signal.reason });
|
|
83
|
+
}
|
|
84
|
+
// The promise, or a not-dispatched refusal as soon as the signal aborts: the call stops
|
|
85
|
+
// waiting, and whatever it waited for goes on.
|
|
86
|
+
function untilAborted(p, signal) {
|
|
87
|
+
if (!signal)
|
|
88
|
+
return p;
|
|
89
|
+
if (signal.aborted)
|
|
90
|
+
return Promise.reject(canceledBeforeSent(signal));
|
|
91
|
+
return new Promise((resolve, reject) => {
|
|
92
|
+
const onAbort = () => reject(canceledBeforeSent(signal));
|
|
93
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
94
|
+
p.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
/** @internal The first 12 hex digits of the key's SHA-256: names it in a log line without its IDs. */
|
|
98
|
+
export function keyDigest(key) {
|
|
99
|
+
return createHash("sha256").update(keyId(key), "utf8").digest("hex").slice(0, 12);
|
|
100
|
+
}
|
|
27
101
|
/** @internal A fresh call on a daemon without projects: the code as a snippet, its last value printed. Node and QuickJS alike. */
|
|
28
102
|
export function snippetRunner(code) {
|
|
29
103
|
return [
|
|
@@ -56,7 +130,9 @@ export const RUNNERS = {
|
|
|
56
130
|
source: [
|
|
57
131
|
"import ast, asyncio, inspect, linecache, sys",
|
|
58
132
|
"sys.path.insert(0, '')",
|
|
59
|
-
|
|
133
|
+
// UTF-8, as the client wrote it: the guest gets the image's environment, and an
|
|
134
|
+
// image whose locale is not UTF-8 would otherwise misread non-ASCII code.
|
|
135
|
+
"src = open('.plimsoll/cell.py', encoding='utf-8').read()",
|
|
60
136
|
"linecache.cache['cell'] = (len(src), None, src.splitlines(True), 'cell')",
|
|
61
137
|
"tree = ast.parse(src, 'cell', 'exec')",
|
|
62
138
|
"last = ast.Expression(tree.body.pop().value) if tree.body and isinstance(tree.body[-1], ast.Expr) else None",
|
|
@@ -83,6 +159,15 @@ export const RUNNERS = {
|
|
|
83
159
|
"globalThis.require = require('node:module').createRequire(process.cwd() + '/');",
|
|
84
160
|
"globalThis.module = { exports: {} }; globalThis.exports = globalThis.module.exports;",
|
|
85
161
|
"globalThis.__dirname = '.'; globalThis.__filename = '[eval]';",
|
|
162
|
+
// Top-level await comes from Node's private module internal/repl/await (the
|
|
163
|
+
// REPL's own rewrite of a cell), which only --expose-internals makes loadable. It
|
|
164
|
+
// is not a public API. The suite runs this runner on the node that runs the suite:
|
|
165
|
+
// 22.18.0 in CI, the line of the project image's node:22 base; it also passed on
|
|
166
|
+
// 26.3.1 on 2026-10-07. If a Node release moves or removes it, the require below
|
|
167
|
+
// fails and the cell runs without the rewrite: a cell that awaits at the top level
|
|
168
|
+
// then fails visibly (a SyntaxError on stderr, exit code 1), and so does the runner
|
|
169
|
+
// test "imports from the work directory and awaits at the top level"; a cell
|
|
170
|
+
// without top-level await runs as before.
|
|
86
171
|
"let tla = null;",
|
|
87
172
|
"try { tla = require('internal/repl/await').processTopLevelAwait; } catch {}",
|
|
88
173
|
"const src = fs.readFileSync('.plimsoll/cell.js', 'utf8');",
|
|
@@ -106,6 +191,7 @@ export const RUNNERS = {
|
|
|
106
191
|
export class CodeSandboxes {
|
|
107
192
|
#opts;
|
|
108
193
|
#entries = new Map();
|
|
194
|
+
#clock = 0;
|
|
109
195
|
#info;
|
|
110
196
|
#client;
|
|
111
197
|
constructor(opts) {
|
|
@@ -119,8 +205,9 @@ export class CodeSandboxes {
|
|
|
119
205
|
get languages() {
|
|
120
206
|
return this.#opts.languages ?? DEFAULT_LANGUAGES;
|
|
121
207
|
}
|
|
208
|
+
// Building the client is part of the Describe's stage: neither runs any code.
|
|
122
209
|
#describe() {
|
|
123
|
-
this.#info ??= this.client.describe().catch((e) => {
|
|
210
|
+
this.#info ??= beforeDispatch(() => this.client.describe()).catch((e) => {
|
|
124
211
|
this.#info = undefined; // retry the next time instead of caching a failure
|
|
125
212
|
throw e;
|
|
126
213
|
});
|
|
@@ -139,49 +226,103 @@ export class CodeSandboxes {
|
|
|
139
226
|
}
|
|
140
227
|
/**
|
|
141
228
|
* Starts creating the key's sandbox and returns at once. A failure here is
|
|
142
|
-
* not lost: the next run under the key opens a session again.
|
|
229
|
+
* not lost: the next run under the key opens a session again. A warm is a guess
|
|
230
|
+
* (a new chat the user may never type in), so it never closes another sandbox to
|
|
231
|
+
* make room: with the key's owner, or this instance, at its cap it does nothing,
|
|
232
|
+
* and the key's first call opens the sandbox, closing the least recently used idle
|
|
233
|
+
* one then. On a daemon with SANDBOX_MAX_SESSIONS_PER_OWNER a warm that opens is an
|
|
234
|
+
* open like any other: the daemon counts it, and at its cap closes that user's least
|
|
235
|
+
* recently used session there.
|
|
143
236
|
*/
|
|
144
237
|
warm(key) {
|
|
238
|
+
const id = keyId(key); // an invalid key is the caller's mistake, said at once
|
|
239
|
+
if (this.#entries.has(id) || !this.#hasRoom(ownerOf(key)))
|
|
240
|
+
return;
|
|
145
241
|
void this.#session(key).catch(() => undefined);
|
|
146
242
|
}
|
|
147
|
-
|
|
243
|
+
// Whether one more sandbox fits under both caps without closing any.
|
|
244
|
+
#hasRoom(owner) {
|
|
245
|
+
const under = (match, cap) => cap <= 0 || [...this.#entries.values()].filter(match).length < cap;
|
|
246
|
+
return (owner === undefined || under((e) => e.owner === owner, this.#opts.maxSessionsPerOwner ?? 3)) && under(() => true, this.#opts.maxSessions ?? 0);
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Runs one call of the tool under the key, or under the key a function returns (an
|
|
250
|
+
* add-on reading it from its framework's context, so a failure to find it is this
|
|
251
|
+
* call's refusal). Every error it throws is a PlimsollError whose message starts with
|
|
252
|
+
* whether the code ran: "Nothing ran (<reason>): " when it carries a not-dispatched
|
|
253
|
+
* mark, "The code may have run, and there is no checked answer for it: " otherwise. A
|
|
254
|
+
* failure before the code was sent (the key, the client, the Describe, the sandbox's
|
|
255
|
+
* open) is marked, reason environment unless the daemon gave one. A framework hands
|
|
256
|
+
* its model only the message (Mastra's error-text, the AI SDK's tool error), and that
|
|
257
|
+
* is the one thing the model must not guess.
|
|
258
|
+
*/
|
|
148
259
|
async run(key, input, signal) {
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
const reserved = (input.files ?? []).find((f) => f.path === ".plimsoll" || f.path.startsWith(".plimsoll/"));
|
|
152
|
-
if (reserved) {
|
|
153
|
-
throw new PlimsollError("invalid_argument", `plimsoll: ${JSON.stringify(reserved.path)} is under .plimsoll/, which the sandbox's runner reserves`, {
|
|
154
|
-
notDispatched: "request",
|
|
155
|
-
});
|
|
260
|
+
try {
|
|
261
|
+
return await this.#run(key, input, signal);
|
|
156
262
|
}
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
throw
|
|
166
|
-
notDispatched: "unsupported",
|
|
167
|
-
});
|
|
263
|
+
catch (e) {
|
|
264
|
+
const err = saysWhetherItRan(e);
|
|
265
|
+
// The Describe decides the mode and the languages for every call, and a daemon
|
|
266
|
+
// can change under a long-lived process (restarted with sessions on or off, or
|
|
267
|
+
// another image, tier or protocol). A refusal that says so drops it, and the next
|
|
268
|
+
// call reads it again; a capacity or request refusal says nothing of the daemon.
|
|
269
|
+
if (err.notDispatched && DAEMON_CHANGED.has(err.notDispatched))
|
|
270
|
+
this.#info = undefined;
|
|
271
|
+
throw err;
|
|
168
272
|
}
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
273
|
+
}
|
|
274
|
+
async #run(keyOrResolver, input, signal) {
|
|
275
|
+
const { key, id, info, language, files, persistent } = await beforeDispatch(async () => {
|
|
276
|
+
const key = typeof keyOrResolver === "function" ? keyOrResolver() : keyOrResolver;
|
|
277
|
+
const id = key === undefined ? undefined : keyId(key);
|
|
278
|
+
// A fresh run's runner and cell file live under .plimsoll/; a file of the call's
|
|
279
|
+
// own there would replace them.
|
|
280
|
+
const files = input.files ?? [];
|
|
281
|
+
const reserved = files.find((f) => f.path === ".plimsoll" || f.path.startsWith(".plimsoll/"));
|
|
282
|
+
if (reserved) {
|
|
283
|
+
throw new PlimsollError("invalid_argument", `plimsoll: ${JSON.stringify(reserved.path)} is under .plimsoll/, which the sandbox's runner reserves`, {
|
|
284
|
+
notDispatched: "request",
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
const language = input.language ?? this.languages[0];
|
|
288
|
+
if (!this.languages.includes(language)) {
|
|
289
|
+
throw new PlimsollError("invalid_argument", `plimsoll: this tool runs ${this.languages.join(" or ")}, not ${language}`, { notDispatched: "request" });
|
|
290
|
+
}
|
|
291
|
+
// The Describe is shared with other calls, so an abort stops this call's wait for
|
|
292
|
+
// it, not the Describe.
|
|
293
|
+
const info = await untilAborted(this.#describe(), signal);
|
|
294
|
+
const proved = info.environments.project.languages;
|
|
295
|
+
// A daemon that states no languages predates the statement: let it try.
|
|
296
|
+
if (proved.length > 0 && !proved.includes(language)) {
|
|
297
|
+
throw new PlimsollError("unimplemented", `plimsoll: the sandbox image has no ${language} interpreter (it runs ${proved.join(", ")})`, {
|
|
298
|
+
notDispatched: "unsupported",
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
// Without a key there is no conversation to scope a sandbox to, and sharing
|
|
302
|
+
// one across conversations would hand one user's files to another.
|
|
303
|
+
const persistent = key !== undefined && (await untilAborted(this.persistent(), signal));
|
|
304
|
+
return { key, id, info, language, files, persistent };
|
|
305
|
+
});
|
|
306
|
+
const opts = { timeoutMs: this.#opts.timeoutMs, minimumIsolation: this.#floor, signal };
|
|
307
|
+
if (key === undefined || !persistent) {
|
|
174
308
|
return this.#fresh(info, language, input.code, files, opts);
|
|
175
309
|
}
|
|
176
310
|
let retried = false;
|
|
177
311
|
for (;;) {
|
|
312
|
+
// A call already aborted opens no sandbox.
|
|
313
|
+
if (signal?.aborted)
|
|
314
|
+
throw canceledBeforeSent(signal);
|
|
178
315
|
// The call holds its entry from here, the open included, so the idle close
|
|
179
316
|
// cannot let the sandbox go while the call waits for it to open.
|
|
180
317
|
const entry = this.#entryFor(key);
|
|
181
318
|
entry.busy++;
|
|
319
|
+
entry.used = ++this.#clock;
|
|
182
320
|
let session;
|
|
183
321
|
try {
|
|
184
|
-
|
|
322
|
+
// The open sends no code: a failure there (the daemon unreachable, a proxy's
|
|
323
|
+
// 503, the client's own check of the session it opened) ran nothing.
|
|
324
|
+
session = await beforeDispatch(() => untilAborted(entry.session, signal));
|
|
325
|
+
// From here the cell may have been sent: an unmarked error stays unmarked.
|
|
185
326
|
const r = await session.runCell({ language, code: input.code, files }, opts);
|
|
186
327
|
// Read once the call has answered: the session runs its calls in order, so of
|
|
187
328
|
// calls made at once only the first to answer finds the sandbox new.
|
|
@@ -200,9 +341,17 @@ export class CodeSandboxes {
|
|
|
200
341
|
filesPersist: !ended,
|
|
201
342
|
...(first ? { freshSandbox: true } : {}),
|
|
202
343
|
isolation: r.isolation,
|
|
344
|
+
recordSha256: r.record.sha256,
|
|
203
345
|
};
|
|
204
346
|
}
|
|
205
347
|
catch (e) {
|
|
348
|
+
// Aborted while its sandbox opened: nothing was sent, and a sandbox no call has
|
|
349
|
+
// used is not kept for a call that has gone (the open finishes, then closes).
|
|
350
|
+
if (!session && signal?.aborted) {
|
|
351
|
+
if (entry.busy === 1 && !entry.answered && this.#entries.get(id) === entry)
|
|
352
|
+
void this.#dispose(id);
|
|
353
|
+
throw e;
|
|
354
|
+
}
|
|
206
355
|
// A call refused because its session had ended ran nothing, so it is
|
|
207
356
|
// safe to run once more in a new sandbox; anything else is not.
|
|
208
357
|
if (!retried && session && e instanceof PlimsollError && e.sessionEnded && e.notDispatched) {
|
|
@@ -220,25 +369,34 @@ export class CodeSandboxes {
|
|
|
220
369
|
}
|
|
221
370
|
finally {
|
|
222
371
|
entry.busy--;
|
|
223
|
-
this.#
|
|
372
|
+
entry.used = ++this.#clock;
|
|
373
|
+
this.#touch(id);
|
|
224
374
|
}
|
|
225
375
|
}
|
|
226
376
|
}
|
|
227
377
|
/** Closes the key's sandbox, if it has one. Safe to call more than once. */
|
|
228
|
-
|
|
229
|
-
|
|
378
|
+
dispose(key) {
|
|
379
|
+
return this.#dispose(keyId(key));
|
|
380
|
+
}
|
|
381
|
+
/** Closes every sandbox this instance holds, for shutdown. */
|
|
382
|
+
async disposeAll() {
|
|
383
|
+
await Promise.all([...this.#entries.keys()].map((id) => this.#dispose(id)));
|
|
384
|
+
}
|
|
385
|
+
// Forgets the entry at once, before the first await, so a cap counts it gone, and
|
|
386
|
+
// resolves once the daemon has closed the session and given its slot back.
|
|
387
|
+
async #dispose(id) {
|
|
388
|
+
const entry = this.#entries.get(id);
|
|
230
389
|
if (!entry)
|
|
231
390
|
return;
|
|
232
|
-
this.#entries.delete(
|
|
391
|
+
this.#entries.delete(id);
|
|
233
392
|
if (entry.timer)
|
|
234
393
|
clearTimeout(entry.timer);
|
|
235
394
|
const session = await entry.session.catch(() => undefined);
|
|
236
395
|
// An ended session is collected the same way.
|
|
237
|
-
await session?.close().catch((e) => this.#closeError(key, e));
|
|
396
|
+
await session?.close().catch((e) => this.#closeError(entry.key, e));
|
|
238
397
|
}
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
await Promise.all([...this.#entries.keys()].map((k) => this.dispose(k)));
|
|
398
|
+
get #floor() {
|
|
399
|
+
return this.#opts.minimumIsolation ?? "kernel";
|
|
242
400
|
}
|
|
243
401
|
// A fresh sandbox for one call: the files, the code and a runner that prints the
|
|
244
402
|
// last expression, as one project.
|
|
@@ -261,6 +419,7 @@ export class CodeSandboxes {
|
|
|
261
419
|
stateKept: false,
|
|
262
420
|
filesPersist: false,
|
|
263
421
|
isolation: r.isolation,
|
|
422
|
+
recordSha256: r.record.sha256,
|
|
264
423
|
};
|
|
265
424
|
}
|
|
266
425
|
const runner = RUNNERS[language];
|
|
@@ -270,19 +429,17 @@ export class CodeSandboxes {
|
|
|
270
429
|
}, opts);
|
|
271
430
|
const step = r.steps[0];
|
|
272
431
|
if (!step) {
|
|
273
|
-
//
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
filesPersist: false,
|
|
278
|
-
isolation: r.isolation,
|
|
279
|
-
};
|
|
432
|
+
// No step report: the outcome says what ended the run (a timeout, a lost report),
|
|
433
|
+
// not whether the code had started, so there is no exit code to give. Unmarked,
|
|
434
|
+
// as anything that may have run is; the checked result rides on the error.
|
|
435
|
+
throw new PlimsollError("unknown", `plimsoll: the run ended ${r.outcome} without a step report (${r.detail}). It was not retried; running it again could repeat what it did.`, { result: r });
|
|
280
436
|
}
|
|
281
437
|
return {
|
|
282
438
|
...this.#cut(language, step.exitCode, step.timedOut || r.outcome === "timed_out", step.stdout, step.stderr, step.stdoutTruncated || step.stderrTruncated),
|
|
283
439
|
stateKept: false,
|
|
284
440
|
filesPersist: false,
|
|
285
441
|
isolation: r.isolation,
|
|
442
|
+
recordSha256: r.record.sha256,
|
|
286
443
|
};
|
|
287
444
|
}
|
|
288
445
|
#session(key) {
|
|
@@ -291,54 +448,115 @@ export class CodeSandboxes {
|
|
|
291
448
|
// The key's entry, opening a session for it when it has none. The idle close is
|
|
292
449
|
// armed once the session is open: an open slower than the idle interval is not idle.
|
|
293
450
|
#entryFor(key) {
|
|
294
|
-
|
|
451
|
+
const id = keyId(key);
|
|
452
|
+
let entry = this.#entries.get(id);
|
|
295
453
|
if (!entry) {
|
|
296
|
-
const
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
});
|
|
307
|
-
});
|
|
308
|
-
const e = { session, answered: false, busy: 0 };
|
|
454
|
+
const owner = ownerOf(key);
|
|
455
|
+
// Room first: sandboxes over a cap are closed before this one opens, so the
|
|
456
|
+
// daemon has their slots back by then.
|
|
457
|
+
const freed = [
|
|
458
|
+
...(owner === undefined ? [] : this.#makeRoom((x) => x.owner === owner, this.#opts.maxSessionsPerOwner ?? 3, "this user")),
|
|
459
|
+
...this.#makeRoom(() => true, this.#opts.maxSessions ?? 0, "this app"),
|
|
460
|
+
];
|
|
461
|
+
const e = { key, owner, used: ++this.#clock, session: undefined, answered: false, busy: 0 };
|
|
462
|
+
// How another sandbox's close went never decides this open.
|
|
463
|
+
const session = (e.session = Promise.allSettled(freed).then(() => this.#open(owner)));
|
|
309
464
|
entry = e;
|
|
310
|
-
this.#entries.set(
|
|
465
|
+
this.#entries.set(id, e);
|
|
311
466
|
// A failed open leaves no entry behind, so the next call tries again.
|
|
312
467
|
session.then((s) => {
|
|
313
468
|
e.opened = s;
|
|
314
|
-
if (this.#entries.get(
|
|
315
|
-
this.#touch(
|
|
469
|
+
if (this.#entries.get(id) === e)
|
|
470
|
+
this.#touch(id);
|
|
316
471
|
}, () => {
|
|
317
|
-
if (this.#entries.get(
|
|
318
|
-
this.#entries.delete(
|
|
472
|
+
if (this.#entries.get(id) === e)
|
|
473
|
+
this.#entries.delete(id);
|
|
319
474
|
});
|
|
320
475
|
}
|
|
321
476
|
return entry;
|
|
322
477
|
}
|
|
478
|
+
async #open(owner) {
|
|
479
|
+
if (!(await this.persistent()))
|
|
480
|
+
throw new PlimsollError("unimplemented", "plimsoll: the daemon does not keep sessions", { notDispatched: "unsupported" });
|
|
481
|
+
// The tool's languages are the hint: a daemon with a warm pool hands over a
|
|
482
|
+
// sandbox with their interpreters running, and drops any it does not run. The
|
|
483
|
+
// owner lets a daemon with SANDBOX_MAX_SESSIONS_PER_OWNER hold the user to its cap
|
|
484
|
+
// across every process of the app, which this instance's own cap cannot see.
|
|
485
|
+
return this.client.openSession({
|
|
486
|
+
minimumIsolation: this.#floor,
|
|
487
|
+
lifetimeMs: this.#opts.sessionLifetimeMs,
|
|
488
|
+
idleTimeoutMs: this.#opts.sessionIdleTimeoutMs,
|
|
489
|
+
languages: [...this.languages],
|
|
490
|
+
owner,
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
// Closes the least recently used idle sandboxes among those that match until fewer
|
|
494
|
+
// than cap remain, and returns their closes. With every one busy, nothing can make
|
|
495
|
+
// room, and the new one is refused before anything is opened.
|
|
496
|
+
#makeRoom(match, cap, whose) {
|
|
497
|
+
if (cap <= 0)
|
|
498
|
+
return [];
|
|
499
|
+
const freed = [];
|
|
500
|
+
let held = [...this.#entries.values()].filter(match).length;
|
|
501
|
+
while (held >= cap) {
|
|
502
|
+
const victim = this.#leastRecent(match);
|
|
503
|
+
if (victim === undefined) {
|
|
504
|
+
throw new PlimsollError("resource_exhausted", `plimsoll: ${whose} has ${held} sandboxes, the most this tool keeps, each with a call in flight`, {
|
|
505
|
+
notDispatched: "capacity",
|
|
506
|
+
});
|
|
507
|
+
}
|
|
508
|
+
freed.push(this.#dispose(victim));
|
|
509
|
+
held--;
|
|
510
|
+
}
|
|
511
|
+
return freed;
|
|
512
|
+
}
|
|
513
|
+
#leastRecent(match) {
|
|
514
|
+
let best;
|
|
515
|
+
for (const [id, e] of this.#entries) {
|
|
516
|
+
if (e.busy === 0 && match(e) && (best === undefined || e.used < best[1].used))
|
|
517
|
+
best = [id, e];
|
|
518
|
+
}
|
|
519
|
+
return best?.[0];
|
|
520
|
+
}
|
|
323
521
|
// Forgets an ended session at once, so the next call under the key opens a
|
|
324
|
-
// new one, and collects its end from the daemon in the background.
|
|
522
|
+
// new one, and collects its end from the daemon in the background. Only the call
|
|
523
|
+
// that removes the entry closes it: a session's entry leaves the map only through
|
|
524
|
+
// here or #dispose, each of which closes it, so two calls sharing a session that
|
|
525
|
+
// ended (a model step's parallel tool calls) send one CloseSession and report a
|
|
526
|
+
// failed close once.
|
|
325
527
|
#drop(key, session) {
|
|
326
|
-
const
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
528
|
+
const id = keyId(key);
|
|
529
|
+
const entry = this.#entries.get(id);
|
|
530
|
+
if (entry?.opened !== session)
|
|
531
|
+
return;
|
|
532
|
+
this.#entries.delete(id);
|
|
533
|
+
if (entry.timer)
|
|
534
|
+
clearTimeout(entry.timer);
|
|
332
535
|
void session.close().catch((e) => this.#closeError(key, e));
|
|
333
536
|
}
|
|
537
|
+
// Never throws: it runs on the paths that close a sandbox, and an open that made room
|
|
538
|
+
// waits for those closes, so an app's reporting must not decide whether a close
|
|
539
|
+
// finishes or the next user's sandbox opens.
|
|
334
540
|
#closeError(key, err) {
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
541
|
+
// A key can hold a user's ID (an email, in some apps), so a log line names it only
|
|
542
|
+
// by a digest, enough to tell one conversation's lines from another's.
|
|
543
|
+
const failed = `plimsoll: closing the sandbox for key ${keyDigest(key)} failed:`;
|
|
544
|
+
const callback = this.#opts.onCloseError;
|
|
545
|
+
if (!callback) {
|
|
546
|
+
console.warn(failed, errorText(err));
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
// A callback that throws, or returns a promise that rejects, is logged in its place.
|
|
550
|
+
const callbackFailed = (e) => console.warn(failed, errorText(err), "; and onCloseError, reporting it, failed:", errorText(e));
|
|
551
|
+
try {
|
|
552
|
+
void Promise.resolve(callback(key, err)).catch(callbackFailed);
|
|
553
|
+
}
|
|
554
|
+
catch (e) {
|
|
555
|
+
callbackFailed(e);
|
|
556
|
+
}
|
|
339
557
|
}
|
|
340
|
-
#touch(
|
|
341
|
-
const entry = this.#entries.get(
|
|
558
|
+
#touch(id) {
|
|
559
|
+
const entry = this.#entries.get(id);
|
|
342
560
|
const ms = this.#opts.idleCloseMs ?? 10 * 60_000;
|
|
343
561
|
if (!entry || ms <= 0)
|
|
344
562
|
return;
|
|
@@ -346,14 +564,21 @@ export class CodeSandboxes {
|
|
|
346
564
|
clearTimeout(entry.timer);
|
|
347
565
|
// A call in flight keeps its sandbox; the call's end arms the timer again.
|
|
348
566
|
entry.timer = setTimeout(() => {
|
|
349
|
-
if (this.#entries.get(
|
|
350
|
-
void this
|
|
567
|
+
if (this.#entries.get(id) === entry && entry.busy === 0)
|
|
568
|
+
void this.#dispose(id);
|
|
351
569
|
}, ms);
|
|
352
570
|
entry.timer.unref?.();
|
|
353
571
|
}
|
|
354
572
|
#cut(language, exitCode, timedOut, stdout, stderr, truncated) {
|
|
355
573
|
const max = this.#opts.maxOutputChars ?? 16_000;
|
|
356
|
-
|
|
574
|
+
// Never end on the first half of a surrogate pair: a lone surrogate is not valid
|
|
575
|
+
// Unicode, and a strict provider can refuse the request that carries it back.
|
|
576
|
+
const cut = (s) => {
|
|
577
|
+
if (s.length <= max)
|
|
578
|
+
return s;
|
|
579
|
+
const c = s.charCodeAt(max - 1);
|
|
580
|
+
return s.slice(0, c >= 0xd800 && c <= 0xdbff ? max - 1 : max);
|
|
581
|
+
};
|
|
357
582
|
return {
|
|
358
583
|
language,
|
|
359
584
|
exitCode,
|
package/dist/tool.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { type ToolLanguages } from "./sandboxes.ts";
|
|
3
3
|
/** The tool's description for the languages it offers. */
|
|
4
|
-
export declare function executeCodeDescription(languages?: ToolLanguages): string;
|
|
4
|
+
export declare function executeCodeDescription(languages?: ToolLanguages, scope?: "fresh" | "conversation"): string;
|
|
5
5
|
/** The tool's input schema for the languages it offers. */
|
|
6
6
|
export declare function executeCodeInput(languages?: ToolLanguages): z.ZodObject<{
|
|
7
7
|
code: z.ZodString;
|
|
@@ -28,4 +28,5 @@ export declare const executeCodeOutput: z.ZodObject<{
|
|
|
28
28
|
filesPersist: z.ZodBoolean;
|
|
29
29
|
freshSandbox: z.ZodOptional<z.ZodLiteral<true>>;
|
|
30
30
|
isolation: z.ZodString;
|
|
31
|
+
recordSha256: z.ZodString;
|
|
31
32
|
}, z.core.$strip>;
|
package/dist/tool.js
CHANGED
|
@@ -1,20 +1,27 @@
|
|
|
1
1
|
// The executeCode tool's model-facing surface, shared by the add-ons so the
|
|
2
|
-
//
|
|
2
|
+
// tools describe the same thing in the same words, with explicit fresh-call scope.
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
import { DEFAULT_LANGUAGES } from "./sandboxes.js";
|
|
5
5
|
const NAMES = { python: "Python", javascript: "JavaScript (Node.js)" };
|
|
6
|
+
// The daemon accepts 200 project files. A fresh call adds its runner and code
|
|
7
|
+
// files, so the shared tool schema must leave those two slots available.
|
|
8
|
+
const MAX_INPUT_FILES = 200 - 2;
|
|
6
9
|
/** The tool's description for the languages it offers. */
|
|
7
|
-
export function executeCodeDescription(languages = DEFAULT_LANGUAGES) {
|
|
10
|
+
export function executeCodeDescription(languages = DEFAULT_LANGUAGES, scope = "conversation") {
|
|
8
11
|
const names = languages.map((l) => NAMES[l]).join(" or ");
|
|
12
|
+
const state = scope === "fresh"
|
|
13
|
+
? "Every call uses a fresh sandbox and interpreter: no earlier variable, import or file is retained. stateKept and filesPersist are false. "
|
|
14
|
+
: "Within one conversation the sandbox usually keeps an interpreter per language between calls, so variables, functions, imports and loaded data " +
|
|
15
|
+
"from earlier calls are still defined: the result's stateKept says whether this call's interpreter was still running when it answered, so what it defined can still be there " +
|
|
16
|
+
"for the next call (false when its deadline ended the interpreter, or the sandbox ended). freshInterpreter means " +
|
|
17
|
+
"this call's interpreter had just started, so nothing earlier calls defined exists and has to be rebuilt; freshSandbox means no file from " +
|
|
18
|
+
"earlier calls is there either. " +
|
|
19
|
+
"Files written to the working directory can still be there on the next call when filesPersist is true; freshSandbox on that call says they are not. ";
|
|
9
20
|
return (`Run ${names} in an isolated sandbox with no network access (beyond any API the operator granted it) and return its exit code, stdout and stderr. ` +
|
|
10
21
|
"The value of the code's last expression is printed, as in a notebook, so the last line can simply name what you want to see. " +
|
|
11
|
-
|
|
12
|
-
"from earlier calls are still defined: the result's stateKept says whether this call's interpreter was still running when it answered, so what it defined can still be there " +
|
|
13
|
-
"for the next call (false when its deadline ended the interpreter, or the sandbox ended). freshInterpreter means " +
|
|
14
|
-
"this call's interpreter had just started, so nothing earlier calls defined exists and has to be rebuilt; freshSandbox means no file from " +
|
|
15
|
-
"earlier calls is there either. " +
|
|
22
|
+
state +
|
|
16
23
|
"To give the code data, such as another tool's output, pass it in files rather than pasting it into the code; the code reads each file by its relative path. " +
|
|
17
|
-
"
|
|
24
|
+
"The result also reports the isolation tier and the SHA-256 of the run record the client checked.");
|
|
18
25
|
}
|
|
19
26
|
/** The tool's input schema for the languages it offers. */
|
|
20
27
|
export function executeCodeInput(languages = DEFAULT_LANGUAGES) {
|
|
@@ -29,7 +36,7 @@ export function executeCodeInput(languages = DEFAULT_LANGUAGES) {
|
|
|
29
36
|
path: z.string().min(1).describe("A relative path, such as data/orders.csv."),
|
|
30
37
|
content: z.string().describe("The file's text."),
|
|
31
38
|
}))
|
|
32
|
-
.max(
|
|
39
|
+
.max(MAX_INPUT_FILES)
|
|
33
40
|
.optional()
|
|
34
41
|
.describe("Text files written into the working directory before the code runs, for data the code should read."),
|
|
35
42
|
});
|
|
@@ -46,4 +53,5 @@ export const executeCodeOutput = z.object({
|
|
|
46
53
|
filesPersist: z.boolean(),
|
|
47
54
|
freshSandbox: z.literal(true).optional(),
|
|
48
55
|
isolation: z.string(),
|
|
56
|
+
recordSha256: z.string().regex(/^[0-9a-f]{64}$/),
|
|
49
57
|
});
|
package/dist/trigger.d.ts
CHANGED
|
@@ -8,8 +8,15 @@ export type PlimsollCodeSandboxOptions = CodeSandboxesOptions & {
|
|
|
8
8
|
export type PlimsollCodeSandbox = {
|
|
9
9
|
/** The AI SDK tool to pass to streamText's tools. */
|
|
10
10
|
executeCode: Tool<ExecuteCodeToolInput, ExecuteCodeOutput>;
|
|
11
|
-
/**
|
|
12
|
-
|
|
11
|
+
/**
|
|
12
|
+
* Call from onTurnStart: records the run id for the tool and starts the sandbox
|
|
13
|
+
* without waiting. owner is the user the chat belongs to, as your server
|
|
14
|
+
* authenticated it (never clientData, which the browser sets: a user who could
|
|
15
|
+
* choose it could close another user's sandboxes). With it, maxSessionsPerOwner
|
|
16
|
+
* counts this worker's sandboxes per user, and a daemon with
|
|
17
|
+
* SANDBOX_MAX_SESSIONS_PER_OWNER counts them across every worker.
|
|
18
|
+
*/
|
|
19
|
+
warm(runId: string, owner?: string): void;
|
|
13
20
|
/** Call from onChatSuspend and onComplete. */
|
|
14
21
|
dispose(runId: string): Promise<void>;
|
|
15
22
|
sandboxes: CodeSandboxes;
|