@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/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
- "src = open('.plimsoll/cell.py').read()",
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
- /** Runs one call of the tool under the key. */
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
- // A fresh run's runner and cell file live under .plimsoll/; a file of the call's own
150
- // there would replace them.
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
- const language = input.language ?? this.languages[0];
158
- if (!this.languages.includes(language)) {
159
- throw new PlimsollError("invalid_argument", `plimsoll: this tool runs ${this.languages.join(" or ")}, not ${language}`, { notDispatched: "request" });
160
- }
161
- const info = await this.#describe();
162
- const proved = info.environments.project.languages;
163
- // A daemon that states no languages predates the statement: let it try.
164
- if (proved.length > 0 && !proved.includes(language)) {
165
- throw new PlimsollError("unimplemented", `plimsoll: the sandbox image has no ${language} interpreter (it runs ${proved.join(", ")})`, {
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
- const files = input.files ?? [];
170
- const opts = { timeoutMs: this.#opts.timeoutMs, minimumIsolation: this.#opts.minimumIsolation, signal };
171
- // Without a key there is no conversation to scope a sandbox to, and sharing
172
- // one across conversations would hand one user's files to another.
173
- if (key === undefined || !(await this.persistent())) {
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
- session = await entry.session;
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.
@@ -204,6 +345,13 @@ export class CodeSandboxes {
204
345
  };
205
346
  }
206
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
+ }
207
355
  // A call refused because its session had ended ran nothing, so it is
208
356
  // safe to run once more in a new sandbox; anything else is not.
209
357
  if (!retried && session && e instanceof PlimsollError && e.sessionEnded && e.notDispatched) {
@@ -221,25 +369,34 @@ export class CodeSandboxes {
221
369
  }
222
370
  finally {
223
371
  entry.busy--;
224
- this.#touch(key);
372
+ entry.used = ++this.#clock;
373
+ this.#touch(id);
225
374
  }
226
375
  }
227
376
  }
228
377
  /** Closes the key's sandbox, if it has one. Safe to call more than once. */
229
- async dispose(key) {
230
- const entry = this.#entries.get(key);
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);
231
389
  if (!entry)
232
390
  return;
233
- this.#entries.delete(key);
391
+ this.#entries.delete(id);
234
392
  if (entry.timer)
235
393
  clearTimeout(entry.timer);
236
394
  const session = await entry.session.catch(() => undefined);
237
395
  // An ended session is collected the same way.
238
- await session?.close().catch((e) => this.#closeError(key, e));
396
+ await session?.close().catch((e) => this.#closeError(entry.key, e));
239
397
  }
240
- /** Closes every sandbox this instance holds, for shutdown. */
241
- async disposeAll() {
242
- await Promise.all([...this.#entries.keys()].map((k) => this.dispose(k)));
398
+ get #floor() {
399
+ return this.#opts.minimumIsolation ?? "kernel";
243
400
  }
244
401
  // A fresh sandbox for one call: the files, the code and a runner that prints the
245
402
  // last expression, as one project.
@@ -272,14 +429,10 @@ export class CodeSandboxes {
272
429
  }, opts);
273
430
  const step = r.steps[0];
274
431
  if (!step) {
275
- // The runner never started: the outcome says why (a bad file path, a timeout).
276
- return {
277
- ...this.#cut(language, r.outcome === "timed_out" ? 124 : 1, r.outcome === "timed_out", "", `plimsoll: the run ${r.outcome}: ${r.detail}`, false),
278
- stateKept: false,
279
- filesPersist: false,
280
- isolation: r.isolation,
281
- recordSha256: r.record.sha256,
282
- };
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 });
283
436
  }
284
437
  return {
285
438
  ...this.#cut(language, step.exitCode, step.timedOut || r.outcome === "timed_out", step.stdout, step.stderr, step.stdoutTruncated || step.stderrTruncated),
@@ -295,54 +448,115 @@ export class CodeSandboxes {
295
448
  // The key's entry, opening a session for it when it has none. The idle close is
296
449
  // armed once the session is open: an open slower than the idle interval is not idle.
297
450
  #entryFor(key) {
298
- let entry = this.#entries.get(key);
451
+ const id = keyId(key);
452
+ let entry = this.#entries.get(id);
299
453
  if (!entry) {
300
- const session = this.persistent().then((ok) => {
301
- if (!ok)
302
- throw new PlimsollError("unimplemented", "plimsoll: the daemon does not keep sessions", { notDispatched: "unsupported" });
303
- // The tool's languages are the hint: a daemon with a warm pool hands over a
304
- // sandbox with their interpreters running, and drops any it does not run.
305
- return this.client.openSession({
306
- minimumIsolation: this.#opts.minimumIsolation,
307
- lifetimeMs: this.#opts.sessionLifetimeMs,
308
- idleTimeoutMs: this.#opts.sessionIdleTimeoutMs,
309
- languages: [...this.languages],
310
- });
311
- });
312
- 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)));
313
464
  entry = e;
314
- this.#entries.set(key, e);
465
+ this.#entries.set(id, e);
315
466
  // A failed open leaves no entry behind, so the next call tries again.
316
467
  session.then((s) => {
317
468
  e.opened = s;
318
- if (this.#entries.get(key) === e)
319
- this.#touch(key);
469
+ if (this.#entries.get(id) === e)
470
+ this.#touch(id);
320
471
  }, () => {
321
- if (this.#entries.get(key) === e)
322
- this.#entries.delete(key);
472
+ if (this.#entries.get(id) === e)
473
+ this.#entries.delete(id);
323
474
  });
324
475
  }
325
476
  return entry;
326
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
+ }
327
521
  // Forgets an ended session at once, so the next call under the key opens a
328
- // 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.
329
527
  #drop(key, session) {
330
- const entry = this.#entries.get(key);
331
- if (entry?.opened === session) {
332
- this.#entries.delete(key);
333
- if (entry.timer)
334
- clearTimeout(entry.timer);
335
- }
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);
336
535
  void session.close().catch((e) => this.#closeError(key, e));
337
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.
338
540
  #closeError(key, err) {
339
- if (this.#opts.onCloseError)
340
- this.#opts.onCloseError(key, err);
341
- else
342
- console.warn(`plimsoll: closing the sandbox for ${key} failed:`, err instanceof Error ? err.message : err);
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
+ }
343
557
  }
344
- #touch(key) {
345
- const entry = this.#entries.get(key);
558
+ #touch(id) {
559
+ const entry = this.#entries.get(id);
346
560
  const ms = this.#opts.idleCloseMs ?? 10 * 60_000;
347
561
  if (!entry || ms <= 0)
348
562
  return;
@@ -350,14 +564,21 @@ export class CodeSandboxes {
350
564
  clearTimeout(entry.timer);
351
565
  // A call in flight keeps its sandbox; the call's end arms the timer again.
352
566
  entry.timer = setTimeout(() => {
353
- if (this.#entries.get(key) === entry && entry.busy === 0)
354
- void this.dispose(key);
567
+ if (this.#entries.get(id) === entry && entry.busy === 0)
568
+ void this.#dispose(id);
355
569
  }, ms);
356
570
  entry.timer.unref?.();
357
571
  }
358
572
  #cut(language, exitCode, timedOut, stdout, stderr, truncated) {
359
573
  const max = this.#opts.maxOutputChars ?? 16_000;
360
- const cut = (s) => (s.length > max ? s.slice(0, max) : s);
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
+ };
361
582
  return {
362
583
  language,
363
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;
package/dist/tool.js CHANGED
@@ -1,20 +1,26 @@
1
1
  // The executeCode tool's model-facing surface, shared by the add-ons so the
2
- // Trigger.dev and Mastra tools describe the same thing in the same words.
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
- "Within one conversation the sandbox usually keeps an interpreter per language between calls, so variables, functions, imports and loaded data " +
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
- "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. " +
18
24
  "The result also reports the isolation tier and the SHA-256 of the run record the client checked.");
19
25
  }
20
26
  /** The tool's input schema for the languages it offers. */
@@ -30,7 +36,7 @@ export function executeCodeInput(languages = DEFAULT_LANGUAGES) {
30
36
  path: z.string().min(1).describe("A relative path, such as data/orders.csv."),
31
37
  content: z.string().describe("The file's text."),
32
38
  }))
33
- .max(200)
39
+ .max(MAX_INPUT_FILES)
34
40
  .optional()
35
41
  .describe("Text files written into the working directory before the code runs, for data the code should read."),
36
42
  });
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
- /** Call from onTurnStart: records the run id for the tool and starts the sandbox without waiting. */
12
- warm(runId: string): void;
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;
package/dist/trigger.js CHANGED
@@ -3,9 +3,10 @@
3
3
  // sandbox. Warm in onTurnStart without blocking, reuse for every executeCode call,
4
4
  // dispose in onChatSuspend (right before the run sleeps) and in onComplete.
5
5
  //
6
- // The sandboxes live in this module's memory, keyed by run id; chat.local holds
7
- // only the run id, because Trigger.dev serializes chat.local into subtask
8
- // metadata and a session ID is a capability that must stay in this process.
6
+ // The sandboxes live in this module's memory, keyed by run id (and the run's owner,
7
+ // when warm names one); chat.local holds only the run id, because Trigger.dev
8
+ // serializes chat.local into subtask metadata, a session ID is a capability that must
9
+ // stay in this process, and the owner is a user's identity.
9
10
  import { chat } from "@trigger.dev/sdk/ai";
10
11
  import { tool } from "ai";
11
12
  import { CodeSandboxes } from "./sandboxes.js";
@@ -13,17 +14,29 @@ import { executeCodeDescription, executeCodeInput } from "./tool.js";
13
14
  export function plimsollCodeSandbox(opts) {
14
15
  const sandboxes = new CodeSandboxes(opts);
15
16
  const current = chat.local({ id: opts.localId ?? "plimsollCodeSandbox" });
16
- function warm(runId) {
17
+ // The owner warm named for each run, in this module's memory only.
18
+ const owners = new Map();
19
+ const keyOf = (runId) => {
20
+ const owner = owners.get(runId);
21
+ return owner === undefined ? runId : { owner, conversation: runId };
22
+ };
23
+ function warm(runId, owner) {
17
24
  current.init({ runId });
18
- sandboxes.warm(runId);
25
+ if (owner !== undefined)
26
+ owners.set(runId, owner);
27
+ sandboxes.warm(keyOf(runId));
19
28
  }
20
- function dispose(runId) {
21
- return sandboxes.dispose(runId);
29
+ async function dispose(runId) {
30
+ const key = keyOf(runId);
31
+ owners.delete(runId);
32
+ await sandboxes.dispose(key);
22
33
  }
23
34
  const executeCode = tool({
24
35
  description: executeCodeDescription(sandboxes.languages),
25
36
  inputSchema: executeCodeInput(sandboxes.languages),
26
- execute: async (input, { abortSignal }) => sandboxes.run(current.get().runId, input, abortSignal),
37
+ // The key is read inside run, so a turn whose onTurnStart never warmed (chat.local
38
+ // then has no run id) is refused as nothing ran, with the lead the model needs.
39
+ execute: async (input, { abortSignal }) => sandboxes.run(() => keyOf(current.get().runId), input, abortSignal),
27
40
  });
28
41
  return { executeCode, warm, dispose, sandboxes };
29
42
  }
package/dist/wire.d.ts CHANGED
@@ -153,6 +153,8 @@ export type WireDescribeResponse = {
153
153
  supportsSessions?: boolean;
154
154
  sessionLifetimeMs?: number;
155
155
  sessionIdleTimeoutMs?: number;
156
+ maxSessionsPerCaller?: number;
157
+ maxSessionsPerOwner?: number;
156
158
  sessionEnvironment?: WirePayloadEnvironment;
157
159
  };
158
160
  export type WireOpenSessionRequest = {